]> rtime.felk.cvut.cz Git - can-benchmark.git/blob - gw-tests/genhtml/genhtml.py
051e034ec5c0894085a3cb92c7b440fb9458c254
[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         ps = "<a href='%s'>Plot source</a>" % ("plot"+pngName[5:-4]+".gp")
160         if 'NO_PDF' in os.environ:
161             return "<div><img src='%s' />%s</div>" % (pngName, ps)
162         else:
163             return "<div><a href='%s'><img src='%s' /></a>%s</div>" % \
164                    (pngName[:-4]+".pdf", pngName, ps)
165         
166     def htmlPrintStats(self, html):
167         cwd = os.getcwd()
168         os.chdir(self.path)
169         stats = glob.glob("*-stat.txt")
170         print >>html, "<h3>Statistics</h3>"
171         print >>html, "<table><tr>"
172         stats.sort()
173         for i in stats:
174             lines = open(i).readlines()
175             def fixupLine(l):
176                 comment = l.find("#")
177                 if comment >= 0:
178                     l = l[:comment-1]
179                 if l.find("cmdline=") == 0:
180                     l = "<abbr title=%s>cmdline=...</abbr>" % str(l[8:])
181                 return l
182             lines = [fixupLine(l) for l in lines]
183             print >>html, "<td><h4>%s</h4>%s</td>" % (i, "<br />".join(lines))
184         print >>html, "</tr></table>"
185         os.chdir(cwd)
186         
187     def generateHtml(self):
188         html = open(os.path.join(self.path, 'results.html'), "w")
189         title = "CAN gateway timing analysis"
190         cdup = "../"*len(self.values)
191         print >> html, """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
192 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
193 <head>
194 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
195 <title>%s</title>
196 <link rel="stylesheet" href="%sstyle.css" type="text/css" /> 
197 </head>
198 <body>
199 <h1>%s</h1>"""  % (title, cdup, title)
200         params = ["%s %s" % (v.dim, v) for v in self.values]
201         print >>html, "Results for:", ", ".join(params)
202         print >>html, "<div class='otherview'><h4>Other results</h4><table>"
203         for d in self.tests.space:
204             links = []
205             for v in d:
206                 if v in self.values:
207                     links.append("<span class='value current'>%s</span>"%str(v))
208                 else:
209                     vv = DimValues(self.values)
210                     vv.replace(v)
211                     try:
212                         href = cdup + urllib.quote(self.tests[vv.key()].path+"/results.html")
213                         links.append("<span class='value other'><a href='%s'>%s</a></span>"%(href, str(v)))
214                     except KeyError:
215                         links.append("<span class='value missing'>%s</span>"%str(v))
216             print >>html, "<tr><th>%s</th><td>" % d, " ".join(links), "</td></tr>"
217
218         print >>html, "</table></div>"
219         print >>html, self.fullImgLink("graph.png")
220         self.htmlPrintStats(html)
221         cwd = os.getcwd()
222         os.chdir(self.path)
223         additionalImgs = glob.glob("graph?*.png")
224         if additionalImgs: print >>html, "<h3>Additional graphs</h3>"
225         for i in additionalImgs:
226             print >>html, "<h4>%s</h4>" % i[5:-4]
227             print >>html, self.fullImgLink(i)
228         os.chdir(cwd)
229         
230         print >>html, "<hr />"
231         print >>html, "<a href='./'>Raw data</a><br />"
232         print >>html, "<a href='%s'>Script source</a><br />" % (cdup+self.name+".sh.html")
233         print >>html, "<a href='%s'>Back to top</a><br />" % cdup
234         print >>html,"%s</body></html>" % html_copyright
235         html.close()
236
237 class Space(list):
238     """List of Dimensions()s (order matters)"""
239     def __init__(self, *dimensions):
240         self.extend(list(dimensions))
241     def path2dimValues(self, path):
242         coordinates = path.split("/")
243         if len(coordinates) != len(self):
244             raise KeyError("The number coordinates do not match the number of dimensions: " + str(coordinates))
245         
246         dv = DimValues([DimValue(self[i], coordinates[i]) \
247                             for i in xrange(len(coordinates))])
248         return dv
249
250     def iterValues(self):
251         idx = [0 for i in xrange(len(self))]
252         done=False
253         while not done:
254             values=DimValues()
255             for i in xrange(len(self)):
256                 values.append(self[i].values()[idx[i]])
257             yield values
258             done=True
259             for i in xrange(len(self)):
260                 idx[i] += 1
261                 if idx[i] < len(self[i]):
262                     done=False
263                     break
264                 idx[i] = 0
265     def reorder(self, dimValues):
266         reordered = DimValues()
267         for d in self:
268             for v in dimValues:
269                 if v.dim == d:
270                     reordered.append(v)
271         return reordered
272     def iterDimensionPairs(self):
273         for i in xrange(len(self)):
274             for j in xrange(i+1, len(self)):
275                 yield (self[i], self[j])
276                 yield (self[j], self[i])
277     def iterRemainingDimensions(self, dimensionPair):
278         for d in self:
279             if d not in dimensionPair:
280                 yield d
281
282
283 class Tests(dict):
284     """Represents all tests organized along several dimensions"""
285     def __init__(self, rootpath, space):
286         dict.__init__(self)
287         self.space = space
288         if (rootpath):
289             self.populate(rootpath)
290     def getTest(self, key):
291         if len(key) != len(self.space):
292             raise KeyError("The coordinates in key do not match the dimension of the space")
293         realkey = self.space.reorder(key)
294         return self[realkey.key()]
295
296     def addTest(self, test):
297         self[test.values.key()] = test
298         
299     def populate(self, rootpath):
300         for root, dirs, files in os.walk(rootpath):
301             if (root.find(rootpath) == 0):
302                 path = root[len(rootpath):]
303             else:
304                 path = rootpath
305             if Test.isOnPath(root):
306                 dv = self.space.path2dimValues(path)
307                 self.addTest(Test(root, dv, self))
308     def generateHtml(self):
309         for pair in self.space.iterDimensionPairs():
310             remDims = Space(*tuple([d for d in self.space.iterRemainingDimensions(pair)]))
311             for vals in remDims.iterValues():
312                 page = Page(pair, vals, self)
313                 print page.getName()
314                 page.generate()
315         try:
316             os.remove("index.html")
317         except OSError: pass
318         os.symlink(page.getName(), "index.html")
319         css = open("style.css", "w")
320         print >>css, """img { border: 0; }
321 table { border-collapse: collapse; }
322 th, td { border: 1px solid lightgray; padding: 4px;}
323 h4 { margin: 0; }
324 .otherview { margin: 1ex 0}
325 .otherview .value { color: black; padding: 0ex 1ex; -moz-border-radius: 1ex; border-radius: 1ex;}
326 .otherview .value a { color: inherit; text-decoration: none; }
327 .otherview .other:hover { background: #eee; }
328 .otherview .missing { color: gray; }
329 .otherview .current { background: #ccc; }
330 .na { width: 150px; height: 109px; display:  table-cell; text-align: center; vertical-align: middle; }
331 """
332         css.close()
333         for test in self.values():
334             print test.path
335             test.generateHtml()
336
337         os.system("source-highlight -d --output-dir=. ../*.sh > /dev/null")
338
339 class Page(object):
340     def __init__(self, dimPair, valsOther, tests):
341         self.dimy, self.dimx = dimPair
342         self.dimOther = [v.dim for v in valsOther]
343         self.valsOther = tests.space.reorder(valsOther)
344         self.tests = tests
345     def getName(self):
346         return "%s-vs-%s-for-%s.html"%(self.dimy.type, self.dimx.type,
347                                        "-".join(["%02d"%v.index() for v in self.valsOther]))
348     def generate(self):
349         html = open(self.getName(), "w")
350         title = "CAN gateway timing analysis" 
351         print >> html, """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
352 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
353 <head>
354 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
355 <title>%s</title>
356 <link rel="stylesheet" href="style.css" type="text/css" /> 
357 </head>
358 <body>
359 <h1>%s</h1>"""  % (title, title)
360         params = ["%s %s" % (v.dim, v) for v in self.valsOther]
361         print >>html, "<h3>Results for ", ", ".join(params), "</h3>"
362         print >>html, "<div class='otherview'><h4>Other views</h4>"
363         print >>html, "<table><tr>"
364         for d in self.dimOther:
365             print >>html, "<th>%s</th>" % d
366             print >>html, "<td><a href='%s'>&rarr;</a> " % \
367                 Page((self.dimy, d), self.valsOther - d + self.dimx.getValue(0), self.tests).getName()
368             print >>html, "<a href='%s'>&darr;</a></td>" % \
369                 Page((d, self.dimx), self.valsOther - d + self.dimy.getValue(0), self.tests).getName()
370             links = []
371             print >>html, "<td>"
372             for v in d:
373                 if v in self.valsOther:
374                     links.append("<span class='value current'>%s</span>"%str(v))
375                 else:
376                     vv = DimValues(self.valsOther)
377                     vv.replace(v)
378                     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)))
379             print >>html, " ".join(links)
380             print >>html, "</td></tr>"
381         print >>html, "</table></div>"
382
383         print >>html, "<table><thead><tr><td>%s &rarr; <br />%s &darr;</td>" % (self.dimx.name, self.dimy.name)
384         for x in self.dimx:
385             print >>html, "<th>%s</th>" % x.htmlTableHeading()
386         print >>html, "</tr></thead>"
387         for y in self.dimy:
388             print >>html, "<tr><th>%s</th>" % y.htmlTableHeading()
389
390             for x in self.dimx:
391                 print >>html, "<td>"
392                 idx = [x,y]
393                 idx.extend(self.valsOther)
394                 try:
395                     test = tests.getTest(idx)
396                     test.printThumbLink(html)
397                 except KeyError:
398                     print >>html, "<span class='na'>N/A</span>"
399                 print >>html, "</td>"
400             print >>html, "</tr>"
401         print >> html, """
402 </table>
403 %s
404 </body>
405 """ % html_copyright
406
407
408 if __name__ == "__main__":
409     os.chdir(sys.argv[1])
410     os.system("rm *.html")
411     tests = Tests("./", Space(DimensionHostKern(), DimensionKern(), DimensionTraffic(), DimensionLoad(), DimensionTest()))
412     tests.generateHtml()
413     sys.exit(0)