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