]> rtime.felk.cvut.cz Git - can-benchmark.git/blob - gw-tests/genhtml/genhtml.py
1ed6ce74e0b279f8f2e168add68392d3226f486b
[can-benchmark.git] / gw-tests / genhtml / genhtml.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 import os;
4 import dircache;
5 import sys;
6 import urllib
7 import traceback
8 import glob
9
10 html_copyright = """<div style="font-size: small; color: gray; margin-top: 1em;">Authors: Michal Sojka, Pavel Píša, Copyright © 2010, 2011 Czech Technical University in Prague</div>"""
11
12 class DimValue(object):
13     def __new__(cls, dim, value):
14         if value in dim:
15             return dim[value]
16         else:
17             return super(DimValue, cls).__new__(cls)
18     def __init__(self, dim, value):
19         self.dim = dim
20         self.value = value
21         self.dim.addValue(self)
22     def __str__(self):
23         return self.dim.val2str(self.value)
24     def __repr__(self):
25         return "DimValue(%s, %s)" % (repr(self.dim), repr(self.value))
26     def htmlTableHeading(self):
27         return self.dim.htmlTableHeading(self.value)
28     def index(self):
29         return self.dim.sortedKeys.index(self.value)
30
31 class DimValues(list):
32     def replace(self, val):
33         for i in xrange(len(self)):
34             if self[i].dim == val.dim:
35                 self[i] = val
36     def __add__(self, val):
37         ret = DimValues(self)
38         ret.append(val)
39         return ret
40     def __sub__(self, dim):
41         result = DimValues(self)
42         for v in self:
43             if v.dim == dim:
44                 result.remove(v)
45         return result
46     def key(self):
47         return tuple([v.value for v in self])
48
49 class Dimension(dict):
50     def __init__(self, atype, name=None):
51         self.type = atype
52         if (name):
53             self.name = name
54         else:
55             self.name = atype
56         self.sortedKeys = []
57
58     def __iter__(self):
59         for i in xrange(len(self)):
60             yield self.getValue(i)
61     def getValue(self, index):
62         return self[self.sortedKeys[index]]
63
64     def addValue(self, value):
65         if value not in self:
66             if isinstance(value, DimValue):
67                 self[value.value] = value
68             else:
69                 raise Exception("Unsupported usage of addValue")
70                 #self[value] = DimValue(self, value)
71             self.sortedKeys = self.keys()
72             self.sortedKeys.sort()
73     def val2str(self, v):
74         return str(v)
75     def htmlTableHeading(self, v):
76         return self.val2str(v)
77     def __str__(self):
78         return self.name
79     def __repr__(self):
80         return "Dimension(%s)"%self.type
81
82 class DimensionKern(Dimension):
83     def __init__(self):
84         Dimension.__init__(self, 'gwkern', 'GW kernel')
85     def htmlTableHeading(self, v):
86         i=v.find(":")
87         if i>0: kver=v[:i]
88         else: kver=v
89         return v+"<br><a href='config-%s'>config</a>"%(urllib.quote(kver))
90     def versions(self):
91         for v in self.values:
92             i=v.find(":")
93             if i>0: kver=v[:i]
94             else: kver=v
95             yield kver
96
97 class DimensionHostKern(Dimension):
98     def __init__(self):
99         Dimension.__init__(self, 'hostkern', 'Host kernel')
100     def val2str(self, v):
101         if v.find("host-") == 0:
102             v = v[5:]
103         return v
104     def htmlTableHeading(self, v):
105         v = self.val2str(v)
106         i = v.find(":")
107         if i>0: kver = v[:i]
108         else: kver = v
109         return v+"<br><a href='config-%s'>config</a>"%(urllib.quote(kver))
110     def versions(self):
111         for v in self.values:
112             i=v.find(":")
113             if i>0: kver=v[:i]
114             else: kver=v
115             yield kver
116
117 class DimensionTest(Dimension):
118     def __init__(self):
119         Dimension.__init__(self, 'test', 'Test')
120     def htmlTableHeading(self, v):
121         return v+"<br><a href='%s.sh.html'>source</a>"%(urllib.quote(v))
122
123 class DimensionLoad(Dimension):
124     def __init__(self):
125         Dimension.__init__(self, 'load', 'Load')
126
127 class DimensionTraffic(Dimension):
128     def __init__(self):
129         Dimension.__init__(self, 'traf', 'Traffic')
130     def val2str(self, v):
131         if v == "50":
132             return "50%"
133         elif v == "oneatatime":
134             return "one message at a time"
135         else:
136             return v
137     def htmlTableHeading(self, v):
138         return self.val2str(v)
139 class Test(object):
140     @classmethod
141     def isOnPath(cls, path):
142         f = os.path.join(path, 'plot.sh')
143         return os.path.isfile(f)
144     def __init__(self, path, values, tests=None):
145         self.path = path
146         self.name = os.path.basename(path)
147         self.values = values
148         self.tests = tests
149     def printThumbLink(self, file):
150 #         try:
151 #             imgs = [img for img in dircache.listdir(thumb)]
152 #         except OSError:
153 #             imgs = [ self.name + ".png" ]
154         imgs = [ 'tgraph.png' ]
155         for img in imgs:
156             print >>file, "<a href='%s/results.html'><img src='%s/%s'></a>" % \
157                   (urllib.quote(self.path), urllib.quote(self.path), img)
158     def fullImgLink(self, pngName):
159         if 'NO_PDF' in os.environ:
160             return "<div><img src='%s' /></div>" % pngName
161         else:
162             return "<div><a href='%s'><img src='%s' /></a></div>" % \
163                    (pngName[:-4]+".pdf", pngName)
164         
165     def htmlPrintStats(self, html):
166         cwd = os.getcwd()
167         os.chdir(self.path)
168         stats = glob.glob("*-stat.txt")
169         print >>html, "<h3>Statistics</h3>"
170         print >>html, "<table><tr>"
171         stats.sort()
172         for i in stats:
173             lines = open(i).readlines()
174             def fixupLine(l):
175                 comment = l.find("#")
176                 if comment >= 0:
177                     l = l[:comment-1]
178                 if l.find("cmdline=") == 0:
179                     l = "<abbr title=%s>cmdline=...</abbr>" % str(l[8:])
180                 return l
181             lines = [fixupLine(l) for l in lines]
182             print >>html, "<td><h4>%s</h4>%s</td>" % (i, "<br />".join(lines))
183         print >>html, "</tr></table>"
184         os.chdir(cwd)
185         
186     def generateHtml(self):
187         html = open(os.path.join(self.path, 'results.html'), "w")
188         title = "CAN gateway timing analysis"
189         cdup = "../"*len(self.values)
190         print >> html, """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
191 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
192 <head>
193 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
194 <title>%s</title>
195 <link rel="stylesheet" href="%sstyle.css" type="text/css" /> 
196 </head>
197 <body>
198 <h1>%s</h1>"""  % (title, cdup, title)
199         params = ["%s %s" % (v.dim, v) for v in self.values]
200         print >>html, "Results for:", ", ".join(params)
201         print >>html, "<div class='otherview'><h4>Other results</h4><table>"
202         for d in self.tests.space:
203             links = []
204             for v in d:
205                 if v in self.values:
206                     links.append("<span class='value current'>%s</span>"%str(v))
207                 else:
208                     vv = DimValues(self.values)
209                     vv.replace(v)
210                     try:
211                         href = cdup + urllib.quote(self.tests[vv.key()].path+"/results.html")
212                         links.append("<span class='value other'><a href='%s'>%s</a></span>"%(href, str(v)))
213                     except KeyError:
214                         links.append("<span class='value missing'>%s</span>"%str(v))
215             print >>html, "<tr><th>%s</th><td>" % d, " ".join(links), "</td></tr>"
216
217         print >>html, "</table></div>"
218         print >>html, self.fullImgLink("graph.png")
219         self.htmlPrintStats(html)
220         cwd = os.getcwd()
221         os.chdir(self.path)
222         additionalImgs = glob.glob("graph?*.png")
223         if additionalImgs: print >>html, "<h3>Additional graphs</h3>"
224         for i in additionalImgs:
225             print >>html, "<h4>%s</h4>" % i[5:-4]
226             print >>html, self.fullImgLink(i)
227         os.chdir(cwd)
228         
229         print >>html, "<hr />"
230         print >>html, "<a href='./'>Raw data</a><br />"
231         print >>html, "<a href='%s'>Script source</a><br />" % (cdup+self.name+".sh.html")
232         print >>html, "<a href='%s'>Back to top</a><br />" % cdup
233         print >>html,"%s</body></html>" % html_copyright
234         html.close()
235
236 class Space(list):
237     """List of Dimensions()s (order matters)"""
238     def __init__(self, *dimensions):
239         self.extend(list(dimensions))
240     def path2dimValues(self, path):
241         coordinates = path.split("/")
242         if len(coordinates) != len(self):
243             raise KeyError("The number coordinates do not match the number of dimensions: " + str(coordinates))
244         
245         dv = DimValues([DimValue(self[i], coordinates[i]) \
246                             for i in xrange(len(coordinates))])
247         return dv
248
249     def iterValues(self):
250         idx = [0 for i in xrange(len(self))]
251         done=False
252         while not done:
253             values=DimValues()
254             for i in xrange(len(self)):
255                 values.append(self[i].values()[idx[i]])
256             yield values
257             done=True
258             for i in xrange(len(self)):
259                 idx[i] += 1
260                 if idx[i] < len(self[i]):
261                     done=False
262                     break
263                 idx[i] = 0
264     def reorder(self, dimValues):
265         reordered = DimValues()
266         for d in self:
267             for v in dimValues:
268                 if v.dim == d:
269                     reordered.append(v)
270         return reordered
271     def iterDimensionPairs(self):
272         for i in xrange(len(self)):
273             for j in xrange(i+1, len(self)):
274                 yield (self[i], self[j])
275                 yield (self[j], self[i])
276     def iterRemainingDimensions(self, dimensionPair):
277         for d in self:
278             if d not in dimensionPair:
279                 yield d
280
281
282 class Tests(dict):
283     """Represents all tests organized along several dimensions"""
284     def __init__(self, rootpath, space):
285         dict.__init__(self)
286         self.space = space
287         if (rootpath):
288             self.populate(rootpath)
289     def getTest(self, key):
290         if len(key) != len(self.space):
291             raise KeyError("The coordinates in key do not match the dimension of the space")
292         realkey = self.space.reorder(key)
293         return self[realkey.key()]
294
295     def addTest(self, test):
296         self[test.values.key()] = test
297         
298     def populate(self, rootpath):
299         for root, dirs, files in os.walk(rootpath):
300             if (root.find(rootpath) == 0):
301                 path = root[len(rootpath):]
302             else:
303                 path = rootpath
304             if Test.isOnPath(root):
305                 dv = self.space.path2dimValues(path)
306                 self.addTest(Test(root, dv, self))
307     def generateHtml(self):
308         for pair in self.space.iterDimensionPairs():
309             remDims = Space(*tuple([d for d in self.space.iterRemainingDimensions(pair)]))
310             for vals in remDims.iterValues():
311                 page = Page(pair, vals, self)
312                 print page.getName()
313                 page.generate()
314         try:
315             os.remove("index.html")
316         except OSError: pass
317         os.symlink(page.getName(), "index.html")
318         css = open("style.css", "w")
319         print >>css, """img { border: 0; }
320 table { border-collapse: collapse; }
321 th, td { border: 1px solid lightgray; padding: 4px;}
322 h4 { margin: 0; }
323 .otherview { margin: 1ex 0}
324 .otherview .value { color: black; padding: 0ex 1ex; -moz-border-radius: 1ex; border-radius: 1ex;}
325 .otherview .value a { color: inherit; text-decoration: none; }
326 .otherview .other:hover { background: #eee; }
327 .otherview .missing { color: gray; }
328 .otherview .current { background: #ccc; }
329 """
330         css.close()
331         for test in self.values():
332             print test.path
333             test.generateHtml()
334
335         os.system("source-highlight -d --output-dir=. ../*.sh > /dev/null")
336
337 class Page(object):
338     def __init__(self, dimPair, valsOther, tests):
339         self.dimy, self.dimx = dimPair
340         self.dimOther = [v.dim for v in valsOther]
341         self.valsOther = tests.space.reorder(valsOther)
342         self.tests = tests
343     def getName(self):
344         return "%s-vs-%s-for-%s.html"%(self.dimy.type, self.dimx.type,
345                                        "-".join(["%02d"%v.index() for v in self.valsOther]))
346     def generate(self):
347         html = open(self.getName(), "w")
348         title = "CAN gateway timing analysis" 
349         print >> html, """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
350 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
351 <head>
352 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
353 <title>%s</title>
354 <link rel="stylesheet" href="style.css" type="text/css" /> 
355 </head>
356 <body>
357 <h1>%s</h1>"""  % (title, title)
358         params = ["%s %s" % (v.dim, v) for v in self.valsOther]
359         print >>html, "<h3>Results for ", ", ".join(params), "</h3>"
360         print >>html, "<div class='otherview'><h4>Other views</h4>"
361         print >>html, "<table><tr>"
362         for d in self.dimOther:
363             print >>html, "<th>%s</th>" % d
364             print >>html, "<td><a href='%s'>&rarr;</a> " % \
365                 Page((self.dimy, d), self.valsOther - d + self.dimx.getValue(0), self.tests).getName()
366             print >>html, "<a href='%s'>&darr;</a></td>" % \
367                 Page((d, self.dimx), self.valsOther - d + self.dimy.getValue(0), self.tests).getName()
368             links = []
369             print >>html, "<td>"
370             for v in d:
371                 if v in self.valsOther:
372                     links.append("<span class='value current'>%s</span>"%str(v))
373                 else:
374                     vv = DimValues(self.valsOther)
375                     vv.replace(v)
376                     links.append("<span class='value other'><a href='%s'>%s</a></span>"%(urllib.quote(Page((self.dimy, self.dimx), vv, self.tests).getName()), str(v)))
377             print >>html, " ".join(links)
378             print >>html, "</td></tr>"
379         print >>html, "</table></div>"
380
381         print >>html, "<table><thead><tr><td>%s &rarr; <br />%s &darr;</td>" % (self.dimx.name, self.dimy.name)
382         for x in self.dimx:
383             print >>html, "<th>%s</th>" % x.htmlTableHeading()
384         print >>html, "</tr></thead>"
385         for y in self.dimy:
386             print >>html, "<tr><th>%s</th>" % y.htmlTableHeading()
387
388             for x in self.dimx:
389                 print >>html, "<td>"
390                 idx = [x,y]
391                 idx.extend(self.valsOther)
392                 try:
393                     test = tests.getTest(idx)
394                     test.printThumbLink(html)
395                 except KeyError:
396                     print >>html, "N/A"
397                 print >>html, "</td>"
398             print >>html, "</tr>"
399         print >> html, """
400 </table>
401 %s
402 </body>
403 """ % html_copyright
404
405
406 if __name__ == "__main__":
407     os.chdir(sys.argv[1])
408     os.system("rm *.html")
409     tests = Tests("./", Space(DimensionHostKern(), DimensionKern(), DimensionTraffic(), DimensionLoad(), DimensionTest()))
410     tests.generateHtml()
411     sys.exit(0)