processResult.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. # Process the test results
  2. # Test status (like passed, or failed with error code)
  3. import argparse
  4. import re
  5. import TestScripts.NewParser as parse
  6. import TestScripts.CodeGen
  7. from collections import deque
  8. import os.path
  9. import csv
  10. import TestScripts.ParseTrace
  11. import colorama
  12. from colorama import init,Fore, Back, Style
  13. import sys
  14. resultStatus=0
  15. init()
  16. def errorStr(id):
  17. if id == 1:
  18. return("UNKNOWN_ERROR")
  19. if id == 2:
  20. return("Equality error")
  21. if id == 3:
  22. return("Absolute difference error")
  23. if id == 4:
  24. return("Relative difference error")
  25. if id == 5:
  26. return("SNR error")
  27. if id == 6:
  28. return("Different length error")
  29. if id == 7:
  30. return("Assertion error")
  31. if id == 8:
  32. return("Memory allocation error")
  33. if id == 9:
  34. return("Empty pattern error")
  35. if id == 10:
  36. return("Buffer tail corrupted")
  37. if id == 11:
  38. return("Close float error")
  39. return("Unknown error %d" % id)
  40. def findItem(root,path):
  41. """ Find a node in a tree
  42. Args:
  43. path (list) : A list of node ID
  44. This list is describing a path in the tree.
  45. By starting from the root and following this path,
  46. we can find the node in the tree.
  47. Raises:
  48. Nothing
  49. Returns:
  50. TreeItem : A node
  51. """
  52. # The list is converted into a queue.
  53. q = deque(path)
  54. q.popleft()
  55. c = root
  56. while q:
  57. n = q.popleft()
  58. # We get the children based on its ID and continue
  59. c = c[n-1]
  60. return(c)
  61. def joinit(iterable, delimiter):
  62. # Intersperse a delimiter between element of a list
  63. it = iter(iterable)
  64. yield next(it)
  65. for x in it:
  66. yield delimiter
  67. yield x
  68. # Return test result as a text tree
  69. class TextFormatter:
  70. def start(self):
  71. None
  72. def printGroup(self,elem,theId):
  73. if elem is None:
  74. elem = root
  75. message=elem.data["message"]
  76. if not elem.data["deprecated"]:
  77. kind = "Suite"
  78. ident = " " * elem.ident
  79. if elem.kind == TestScripts.Parser.TreeElem.GROUP:
  80. kind = "Group"
  81. #print(elem.path)
  82. print(Style.BRIGHT + ("%s%s : %s (%d)" % (ident,kind,message,theId)) + Style.RESET_ALL)
  83. def printTest(self,elem, theId, theError,errorDetail,theLine,passed,cycles,params):
  84. message=elem.data["message"]
  85. func=elem.data["class"]
  86. if not elem.data["deprecated"]:
  87. kind = "Test"
  88. ident = " " * elem.ident
  89. p=Fore.RED + "FAILED" + Style.RESET_ALL
  90. if passed == 1:
  91. p= Fore.GREEN + "PASSED" + Style.RESET_ALL
  92. if cycles > 0:
  93. print("%s%s %s(%s - %d)%s : %s (cycles = %d)" % (ident,message,Style.BRIGHT,func,theId,Style.RESET_ALL,p,cycles))
  94. else:
  95. print("%s%s %s(%s - %d)%s : %s" % (ident,message,Style.BRIGHT,func,theId,Style.RESET_ALL,p))
  96. if params:
  97. print("%s %s" % (ident,params))
  98. if passed != 1:
  99. print(Fore.RED + ("%s %s at line %d" % (ident, errorStr(theError), theLine)) + Style.RESET_ALL)
  100. if (len(errorDetail)>0):
  101. print(Fore.RED + ident + " " + errorDetail + Style.RESET_ALL)
  102. def pop(self):
  103. None
  104. def end(self):
  105. None
  106. # Return test result as a text tree
  107. class HTMLFormatter:
  108. def __init__(self):
  109. self.nb=1
  110. self.suite=False
  111. def start(self):
  112. print("<html><head><title>Test Results</title></head><body>")
  113. def printGroup(self,elem,theId):
  114. if elem is None:
  115. elem = root
  116. message=elem.data["message"]
  117. if not elem.data["deprecated"]:
  118. kind = "Suite"
  119. ident = " " * elem.ident
  120. if elem.kind == TestScripts.Parser.TreeElem.GROUP:
  121. kind = "Group"
  122. if kind == "Group":
  123. print("<h%d> %s (%d) </h%d>" % (self.nb,message,theId,self.nb))
  124. else:
  125. print("<h%d> %s (%d) </h%d>" % (self.nb,message,theId,self.nb))
  126. self.suite=True
  127. print("<table style=\"width:100%\">")
  128. print("<tr>")
  129. print("<td>Name</td>")
  130. print("<td>ID</td>")
  131. print("<td>Status</td>")
  132. print("<td>Params</td>")
  133. print("<td>Cycles</td>")
  134. print("</tr>")
  135. self.nb = self.nb + 1
  136. def printTest(self,elem, theId, theError,errorDetail,theLine,passed,cycles,params):
  137. message=elem.data["message"]
  138. if not elem.data["deprecated"]:
  139. kind = "Test"
  140. ident = " " * elem.ident
  141. p="<font color=\"red\">FAILED</font>"
  142. if passed == 1:
  143. p= "<font color=\"green\">PASSED</font>"
  144. print("<tr>")
  145. print("<td><pre>%s</pre></td>" % (message,))
  146. print("<td>%d</td>" % theId)
  147. print("<td>%s</td>" % p)
  148. if params:
  149. print("<td>%s</td>\n" % (params))
  150. else:
  151. print("<td></td>\n")
  152. print("<td>%d</td>" % cycles)
  153. print("</tr>")
  154. if passed != 1:
  155. print("<tr><td colspan=4><font color=\"red\">%s at line %d</font></td></tr>" % (errorStr(theError), theLine))
  156. if (len(errorDetail)>0):
  157. print("<tr><td colspan=4><font color=\"red\">" + errorDetail + "</font></td></tr>")
  158. def pop(self):
  159. if self.suite:
  160. print("</table>")
  161. self.nb = self.nb - 1
  162. self.suite=False
  163. def end(self):
  164. print("</body></html>")
  165. # Return test result as a CSV
  166. class CSVFormatter:
  167. def __init__(self):
  168. self.name=[]
  169. self._start=True
  170. def start(self):
  171. print("CATEGORY,NAME,ID,STATUS,CYCLES,PARAMS")
  172. def printGroup(self,elem,theId):
  173. if elem is None:
  174. elem = root
  175. # Remove Root from category name in CSV file.
  176. if not self._start:
  177. self.name.append(elem.data["class"])
  178. else:
  179. self._start=False
  180. message=elem.data["message"]
  181. if not elem.data["deprecated"]:
  182. kind = "Suite"
  183. ident = " " * elem.ident
  184. if elem.kind == TestScripts.Parser.TreeElem.GROUP:
  185. kind = "Group"
  186. def printTest(self,elem, theId, theError, errorDetail,theLine,passed,cycles,params):
  187. message=elem.data["message"]
  188. if not elem.data["deprecated"]:
  189. kind = "Test"
  190. name=elem.data["class"]
  191. category= "".join(list(joinit(self.name,":")))
  192. print("%s,%s,%d,%d,%d,\"%s\"" % (category,name,theId,passed,cycles,params))
  193. def pop(self):
  194. if self.name:
  195. self.name.pop()
  196. def end(self):
  197. None
  198. class MathematicaFormatter:
  199. def __init__(self):
  200. self._hasContent=[False]
  201. self._toPop=[]
  202. def start(self):
  203. None
  204. def printGroup(self,elem,theId):
  205. if self._hasContent[len(self._hasContent)-1]:
  206. print(",",end="")
  207. print("<|")
  208. self._hasContent[len(self._hasContent)-1] = True
  209. self._hasContent.append(False)
  210. if elem is None:
  211. elem = root
  212. message=elem.data["message"]
  213. if not elem.data["deprecated"]:
  214. kind = "Suite"
  215. ident = " " * elem.ident
  216. if elem.kind == TestScripts.Parser.TreeElem.GROUP:
  217. kind = "Group"
  218. print("\"%s\" ->" % (message))
  219. #if kind == "Suite":
  220. print("{",end="")
  221. self._toPop.append("}")
  222. #else:
  223. # self._toPop.append("")
  224. def printTest(self,elem, theId, theError,errorDetail,theLine,passed,cycles,params):
  225. message=elem.data["message"]
  226. if not elem.data["deprecated"]:
  227. kind = "Test"
  228. ident = " " * elem.ident
  229. p="FAILED"
  230. if passed == 1:
  231. p="PASSED"
  232. parameters=""
  233. if params:
  234. parameters = "%s" % params
  235. if self._hasContent[len(self._hasContent)-1]:
  236. print(",",end="")
  237. print("<|\"NAME\" -> \"%s\",\"ID\" -> %d,\"STATUS\" -> \"%s\",\"CYCLES\" -> %d,\"PARAMS\" -> \"%s\"|>" % (message,theId,p,cycles,parameters))
  238. self._hasContent[len(self._hasContent)-1] = True
  239. #if passed != 1:
  240. # print("%s Error = %d at line %d" % (ident, theError, theLine))
  241. def pop(self):
  242. print(self._toPop.pop(),end="")
  243. print("|>")
  244. self._hasContent.pop()
  245. def end(self):
  246. None
  247. NORMAL = 1
  248. INTEST = 2
  249. TESTPARAM = 3
  250. ERRORDESC = 4
  251. def createMissingDir(destPath):
  252. theDir=os.path.normpath(os.path.dirname(destPath))
  253. if not os.path.exists(theDir):
  254. os.makedirs(theDir)
  255. def correctPath(path):
  256. while (path[0]=="/") or (path[0] == "\\"):
  257. path = path[1:]
  258. return(path)
  259. def extractDataFiles(results,outputDir):
  260. infile = False
  261. f = None
  262. for l in results:
  263. if re.match(r'^.*D:[ ].*$',l):
  264. if infile:
  265. if re.match(r'^.*D:[ ]END$',l):
  266. infile = False
  267. if f:
  268. f.close()
  269. else:
  270. if f:
  271. m = re.match(r'^.*D:[ ](.*)$',l)
  272. data = m.group(1)
  273. f.write(data)
  274. f.write("\n")
  275. else:
  276. m = re.match(r'^.*D:[ ](.*)$',l)
  277. path = str(m.group(1))
  278. infile = True
  279. destPath = os.path.join(outputDir,correctPath(path))
  280. createMissingDir(destPath)
  281. f = open(destPath,"w")
  282. def writeBenchmark(elem,benchFile,theId,theError,passed,cycles,params,config):
  283. if benchFile:
  284. testname=elem.data["class"]
  285. #category= elem.categoryDesc()
  286. name=elem.data["message"]
  287. category=elem.getSuiteMessage()
  288. old=""
  289. if "testData" in elem.data:
  290. if "oldID" in elem.data["testData"]:
  291. old=elem.data["testData"]["oldID"]
  292. benchFile.write("\"%s\",\"%s\",\"%s\",%d,\"%s\",%s,%d,%s\n" % (category,testname,name,theId,old,params,cycles,config))
  293. def getCyclesFromTrace(trace):
  294. if not trace:
  295. return(0)
  296. else:
  297. return(TestScripts.ParseTrace.getCycles(trace))
  298. def analyseResult(resultPath,root,results,embedded,benchmark,trace,formatter):
  299. global resultStatus
  300. calibration = 0
  301. if trace:
  302. # First cycle in the trace is the calibration data
  303. # The noramlisation factor must be coherent with the C code one.
  304. calibration = int(getCyclesFromTrace(trace) / 20)
  305. formatter.start()
  306. path = []
  307. state = NORMAL
  308. prefix=""
  309. elem=None
  310. theId=None
  311. theError=None
  312. errorDetail=""
  313. theLine=None
  314. passed=0
  315. cycles=None
  316. benchFile = None
  317. config=""
  318. if embedded:
  319. prefix = ".*[S]+:[ ]"
  320. # Parse the result file.
  321. # NORMAL mode is when we are parsing suite or group.
  322. # Otherwise we are parsing a test and we need to analyse the
  323. # test result.
  324. # TESTPARAM is used to read parameters of the test.
  325. # Format of output is:
  326. #node ident : s id or g id or t or u
  327. #test status : id error linenb status Y or N (Y when passing)
  328. #param for this test b x,x,x,x or b alone if not param
  329. #node end : p
  330. # In FPGA mode:
  331. #Prefix S:[ ] before driver dump
  332. # D:[ ] before data dump (output patterns)
  333. for l in results:
  334. l = l.strip()
  335. if not re.match(r'^.*D:[ ].*$',l):
  336. if state == NORMAL:
  337. if len(l) > 0:
  338. # Line starting with g or s is a suite or group.
  339. # In FPGA mode, those line are prefixed with 'S: '
  340. # and data file with 'D: '
  341. if re.match(r'^%s[gs][ ]+[0-9]+.*$' % prefix,l):
  342. # Extract the test id
  343. theId=re.sub(r'^%s[gs][ ]+([0-9]+).*$' % prefix,r'\1',l)
  344. theId=int(theId)
  345. path.append(theId)
  346. # From a list of id, find the TreeElem in the Parsed tree
  347. # to know what is the node.
  348. elem = findItem(root,path)
  349. # Display formatted output for this node
  350. if elem.params:
  351. #print(elem.params.full)
  352. benchPath = os.path.join(benchmark,elem.fullPath(),"fullBenchmark.csv")
  353. createMissingDir(benchPath)
  354. if benchFile:
  355. printf("ERROR BENCH FILE %s ALREADY OPEN" % benchPath)
  356. benchFile.close()
  357. benchFile=None
  358. benchFile=open(benchPath,"w")
  359. header = "".join(list(joinit(elem.params.full,",")))
  360. # A test and a benchmark are different
  361. # so we don't dump a status and error
  362. # A status and error in a benchmark would
  363. # impact the cycles since the test
  364. # would be taken into account in the measurement
  365. # So benchmark are always passing and contain no test
  366. #benchFile.write("ID,%s,PASSED,ERROR,CYCLES\n" % header)
  367. csvheaders = ""
  368. with open(os.path.join(resultPath,'currentConfig.csv'), 'r') as f:
  369. reader = csv.reader(f)
  370. csvheaders = next(reader, None)
  371. configList = list(reader)
  372. #print(configList)
  373. config = "".join(list(joinit(configList[0],",")))
  374. configHeaders = "".join(list(joinit(csvheaders,",")))
  375. benchFile.write("CATEGORY,TESTNAME,NAME,ID,OLDID,%s,CYCLES,%s\n" % (header,configHeaders))
  376. formatter.printGroup(elem,theId)
  377. # If we have detected a test, we switch to test mode
  378. if re.match(r'^%s[t][ ]*$' % prefix,l):
  379. state = INTEST
  380. # Pop
  381. # End of suite or group
  382. if re.match(r'^%sp.*$' % prefix,l):
  383. if benchFile:
  384. benchFile.close()
  385. benchFile=None
  386. path.pop()
  387. formatter.pop()
  388. elif state == INTEST:
  389. if len(l) > 0:
  390. # In test mode, we are looking for test status.
  391. # A line starting with S
  392. # (There may be empty lines or line for data files)
  393. passRe = r'^%s([0-9]+)[ ]+([0-9]+)[ ]+([0-9]+)[ ]+([t0-9]+)[ ]+([YN]).*$' % prefix
  394. if re.match(passRe,l):
  395. # If we have found a test status then we will start again
  396. # in normal mode after this.
  397. m = re.match(passRe,l)
  398. # Extract test ID, test error code, line number and status
  399. theId=m.group(1)
  400. theId=int(theId)
  401. theError=m.group(2)
  402. theError=int(theError)
  403. theLine=m.group(3)
  404. theLine=int(theLine)
  405. maybeCycles = m.group(4)
  406. if maybeCycles == "t":
  407. cycles = getCyclesFromTrace(trace) - calibration
  408. else:
  409. cycles = int(maybeCycles)
  410. status=m.group(5)
  411. passed=0
  412. # Convert status to number as used by formatter.
  413. if status=="Y":
  414. passed = 1
  415. if status=="N":
  416. passed = 0
  417. # Compute path to this node
  418. newPath=path.copy()
  419. newPath.append(theId)
  420. # Find the node in the Tree
  421. elem = findItem(root,newPath)
  422. state = ERRORDESC
  423. else:
  424. if re.match(r'^%sp.*$' % prefix,l):
  425. if benchFile:
  426. benchFile.close()
  427. benchFile=None
  428. path.pop()
  429. formatter.pop()
  430. if re.match(r'^%s[t][ ]*$' % prefix,l):
  431. state = INTEST
  432. else:
  433. state = NORMAL
  434. elif state == ERRORDESC:
  435. if len(l) > 0:
  436. if re.match(r'^.*E:.*$',l):
  437. if re.match(r'^.*E:[ ].*$',l):
  438. m = re.match(r'^.*E:[ ](.*)$',l)
  439. errorDetail = m.group(1)
  440. else:
  441. errorDetail = ""
  442. state = TESTPARAM
  443. else:
  444. if len(l) > 0:
  445. state = INTEST
  446. params=""
  447. if re.match(r'^.*b[ ]+([0-9,]+)$',l):
  448. m=re.match(r'^.*b[ ]+([0-9,]+)$',l)
  449. params=m.group(1).strip()
  450. # Format the node
  451. #print(elem.fullPath())
  452. #createMissingDir(destPath)
  453. writeBenchmark(elem,benchFile,theId,theError,passed,cycles,params,config)
  454. else:
  455. params=""
  456. writeBenchmark(elem,benchFile,theId,theError,passed,cycles,params,config)
  457. # Format the node
  458. if not passed:
  459. resultStatus=1
  460. formatter.printTest(elem,theId,theError,errorDetail,theLine,passed,cycles,params)
  461. formatter.end()
  462. def analyze(root,results,args,trace):
  463. # currentConfig.csv should be in the same place
  464. resultPath=os.path.dirname(args.r)
  465. if args.c:
  466. analyseResult(resultPath,root,results,args.e,args.b,trace,CSVFormatter())
  467. elif args.html:
  468. analyseResult(resultPath,root,results,args.e,args.b,trace,HTMLFormatter())
  469. elif args.m:
  470. analyseResult(resultPath,root,results,args.e,args.b,trace,MathematicaFormatter())
  471. else:
  472. print("")
  473. print(Fore.RED + "The cycles displayed by this script must not be trusted." + Style.RESET_ALL)
  474. print(Fore.RED + "They are just an indication. The timing code has not yet been validated." + Style.RESET_ALL)
  475. print("")
  476. analyseResult(resultPath,root,results,args.e,args.b,trace,TextFormatter())
  477. parser = argparse.ArgumentParser(description='Parse test description')
  478. parser.add_argument('-f', nargs='?',type = str, default="Output.pickle", help="Test description file path")
  479. # Where the result file can be found
  480. parser.add_argument('-r', nargs='?',type = str, default=None, help="Result file path")
  481. parser.add_argument('-c', action='store_true', help="CSV output")
  482. parser.add_argument('-html', action='store_true', help="HTML output")
  483. parser.add_argument('-e', action='store_true', help="Embedded test")
  484. # -o needed when -e is true to know where to extract the output files
  485. parser.add_argument('-o', nargs='?',type = str, default="Output", help="Output dir path")
  486. parser.add_argument('-b', nargs='?',type = str, default="FullBenchmark", help="Full Benchmark dir path")
  487. parser.add_argument('-m', action='store_true', help="Mathematica output")
  488. parser.add_argument('-t', nargs='?',type = str, default=None, help="External trace file")
  489. args = parser.parse_args()
  490. if args.f is not None:
  491. #p = parse.Parser()
  492. # Parse the test description file
  493. #root = p.parse(args.f)
  494. root=parse.loadRoot(args.f)
  495. if args.t:
  496. with open(args.t,"r") as trace:
  497. with open(args.r,"r") as results:
  498. analyze(root,results,args,iter(trace))
  499. else:
  500. with open(args.r,"r") as results:
  501. analyze(root,results,args,None)
  502. if args.e:
  503. # In FPGA mode, extract output files from stdout (result file)
  504. with open(args.r,"r") as results:
  505. extractDataFiles(results,args.o)
  506. sys.exit(resultStatus)
  507. else:
  508. parser.print_help()