processResult.py 20 KB

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