processResult.py 19 KB

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