blob: 649a3a1e7784520cb759dabf091fd3d293514936 [file] [log] [blame]
bungeman@google.com85669f92011-06-17 13:58:14 +00001'''
2Created on May 16, 2011
3
4@author: bungeman
5'''
6import sys
7import getopt
8import re
9import os
10import bench_util
11import json
12import xml.sax.saxutils
13
14def usage():
15 """Prints simple usage information."""
16
17 print '-d <dir> a directory containing bench_r<revision>_<scalar> files.'
18 print '-b <bench> the bench to show.'
19 print '-c <config> the config to show (GPU, 8888, 565, etc).'
20 print '-t <time> the time to show (w, c, g, etc).'
21 print '-s <setting>[=<value>] a setting to show (alpha, scalar, etc).'
22 print '-r <revision>[:<revision>] the revisions to show.'
23 print '-f <revision>[:<revision>] the revisions to use for fitting.'
24 print '-x <int> the desired width of the svg.'
25 print '-y <int> the desired height of the svg.'
26 print '--default-setting <setting>[=<value>] setting for those without.'
27
28
29class Label:
30 """The information in a label.
31
32 (str, str, str, str, {str:str})"""
33 def __init__(self, bench, config, time_type, settings):
34 self.bench = bench
35 self.config = config
36 self.time_type = time_type
37 self.settings = settings
38
39 def __repr__(self):
40 return "Label(%s, %s, %s, %s)" % (
41 str(self.bench),
42 str(self.config),
43 str(self.time_type),
44 str(self.settings),
45 )
46
47 def __str__(self):
48 return "%s_%s_%s_%s" % (
49 str(self.bench),
50 str(self.config),
51 str(self.time_type),
52 str(self.settings),
53 )
54
55 def __eq__(self, other):
56 return (self.bench == other.bench and
57 self.config == other.config and
58 self.time_type == other.time_type and
59 self.settings == other.settings)
60
61 def __hash__(self):
62 return (hash(self.bench) ^
63 hash(self.config) ^
64 hash(self.time_type) ^
65 hash(frozenset(self.settings.iteritems())))
66
67def parse_dir(directory, default_settings, oldest_revision, newest_revision):
68 """Parses bench data from files like bench_r<revision>_<scalar>.
69
70 (str, {str, str}, Number, Number) -> {int:[BenchDataPoints]}"""
71 revision_data_points = {} # {revision : [BenchDataPoints]}
72 for bench_file in os.listdir(directory):
73 file_name_match = re.match('bench_r(\d+)_(\S+)', bench_file)
74 if (file_name_match is None):
75 continue
76
77 revision = int(file_name_match.group(1))
78 scalar_type = file_name_match.group(2)
79
80 if (revision < oldest_revision or revision > newest_revision):
81 continue
82
83 file_handle = open(directory + '/' + bench_file, 'r')
84
85 if (revision not in revision_data_points):
86 revision_data_points[revision] = []
87 default_settings['scalar'] = scalar_type
88 revision_data_points[revision].extend(
89 bench_util.parse(default_settings, file_handle))
90 file_handle.close()
91 return revision_data_points
92
93def create_lines(revision_data_points, settings
94 , bench_of_interest, config_of_interest, time_of_interest):
95 """Convert revision data into sorted line data.
96
97 ({int:[BenchDataPoints]}, {str:str}, str?, str?, str?)
98 -> {Label:[(x,y)] | [n].x <= [n+1].x}"""
99 revisions = revision_data_points.keys()
100 revisions.sort()
101 lines = {} # {Label:[(x,y)] | x[n] <= x[n+1]}
102 for revision in revisions:
103 for point in revision_data_points[revision]:
104 if (bench_of_interest is not None and
105 not bench_of_interest == point.bench):
106 continue
107
108 if (config_of_interest is not None and
109 not config_of_interest == point.config):
110 continue
111
112 if (time_of_interest is not None and
113 not time_of_interest == point.time_type):
114 continue
115
116 skip = False
117 for key, value in settings.items():
118 if key in point.settings and point.settings[key] != value:
119 skip = True
120 break
121 if skip:
122 continue
123
124 line_name = Label(point.bench
125 , point.config
126 , point.time_type
127 , point.settings)
128
129 if line_name not in lines:
130 lines[line_name] = []
131
132 lines[line_name].append((revision, point.time))
133
134 return lines
135
136def bounds(lines):
137 """Finds the bounding rectangle for the lines.
138
139 {Label:[(x,y)]} -> ((min_x, min_y),(max_x,max_y))"""
140 min_x = bench_util.Max
141 min_y = bench_util.Max
142 max_x = bench_util.Min
143 max_y = bench_util.Min
144
145 for line in lines.itervalues():
146 for x, y in line:
147 min_x = min(min_x, x)
148 min_y = min(min_y, y)
149 max_x = max(max_x, x)
150 max_y = max(max_y, y)
151
152 return ((min_x, min_y), (max_x, max_y))
153
154def create_regressions(lines, start_x, end_x):
155 """Creates regression data from line segments.
156
157 ({Label:[(x,y)] | [n].x <= [n+1].x}, Number, Number)
158 -> {Label:LinearRegression}"""
159 regressions = {} # {Label : LinearRegression}
160
161 for label, line in lines.iteritems():
162 regression_line = [p for p in line if start_x <= p[0] <= end_x]
163
164 if (len(regression_line) < 2):
165 continue
166 regression = bench_util.LinearRegression(regression_line)
167 regressions[label] = regression
168
169 return regressions
170
171def bounds_slope(regressions):
172 """Finds the extreme up and down slopes of a set of linear regressions.
173
174 ({Label:LinearRegression}) -> (max_up_slope, min_down_slope)"""
175 max_up_slope = 0
176 min_down_slope = 0
177 for regression in regressions.itervalues():
178 min_slope = regression.find_min_slope()
179 max_up_slope = max(max_up_slope, min_slope)
180 min_down_slope = min(min_down_slope, min_slope)
181
182 return (max_up_slope, min_down_slope)
183
184def main():
185 """Parses command line and writes output."""
186
187 try:
188 opts, _ = getopt.getopt(sys.argv[1:]
189 , "d:b:c:t:s:r:f:x:y:"
190 , "default-setting=")
191 except getopt.GetoptError, err:
192 print str(err)
193 usage()
194 sys.exit(2)
195
196 directory = None
197 config_of_interest = None
198 bench_of_interest = None
199 time_of_interest = None
200 oldest_revision = 0
201 newest_revision = bench_util.Max
202 oldest_regression = 0
203 newest_regression = bench_util.Max
204 requested_height = None
205 requested_width = None
206 settings = {}
207 default_settings = {}
208
209 def parse_range(revision_range):
210 """Takes <old>[:<new>] returns (old, new) or (old, Max)."""
211 old, _, new = revision_range.partition(":")
212 if not new:
213 return (int(old), bench_util.Max)
214 return (int(old), int(new))
215
216 def add_setting(settings, setting):
217 """Takes <key>[=<value>] adds {key:value} or {key:True} to settings."""
218 name, _, value = setting.partition('=')
219 if not value:
220 settings[name] = True
221 else:
222 settings[name] = value
223
224 try:
225 for option, value in opts:
226 if option == "-d":
227 directory = value
228 elif option == "-b":
229 bench_of_interest = value
230 elif option == "-c":
231 config_of_interest = value
232 elif option == "-t":
233 time_of_interest = value
234 elif option == "-s":
235 add_setting(settings, value)
236 elif option == "-r":
237 oldest_revision, newest_revision = parse_range(value)
238 elif option == "-f":
239 oldest_regression, newest_regression = parse_range(value)
240 elif option == "-x":
241 requested_width = int(value)
242 elif option == "-y":
243 requested_height = int(value)
244 elif option == "--default-setting":
245 add_setting(default_settings, value)
246 else:
247 usage()
248 assert False, "unhandled option"
249 except ValueError:
250 usage()
251 sys.exit(2)
252
253 if directory is None:
254 usage()
255 sys.exit(2)
256
257 revision_data_points = parse_dir(directory
258 , default_settings
259 , oldest_revision
260 , newest_revision)
261
262 lines = create_lines(revision_data_points
263 , settings
264 , bench_of_interest
265 , config_of_interest
266 , time_of_interest)
267
268 regressions = create_regressions(lines
269 , oldest_regression
270 , newest_regression)
271
272 output_xhtml(lines, regressions, requested_width, requested_height)
273
274def qa(out):
275 """Stringify input and quote as an xml attribute."""
276 return xml.sax.saxutils.quoteattr(str(out))
277def qe(out):
278 """Stringify input and escape as xml data."""
279 return xml.sax.saxutils.escape(str(out))
280
281def create_select(qualifier, lines, select_id=None):
282 """Output select with options showing lines which qualifier maps to it.
283
284 ((Label) -> str, {Label:_}, str?) -> _"""
285 options = {} #{ option : [Label]}
286 for label in lines.keys():
287 option = qualifier(label)
288 if (option not in options):
289 options[option] = []
290 options[option].append(label)
291 option_list = list(options.keys())
292 option_list.sort()
293 print '<select class="lines"',
294 if select_id is not None:
295 print 'id=%s' % qa(select_id)
296 print 'multiple="true" size="10" onchange="updateSvg();">'
297 for option in option_list:
298 print '<option value=' + qa('[' +
299 reduce(lambda x,y:x+json.dumps(str(y))+',',options[option],"")[0:-1]
300 + ']') + '>'+qe(option)+'</option>'
301 print '</select>'
302
303def output_xhtml(lines, regressions, requested_width, requested_height):
304 """Outputs an svg/xhtml view of the data."""
305 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"',
306 print '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
307 print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">'
308 print '<head>'
309 print '<title>Bench graph</title>'
310 print '</head>'
311 print '<body>'
312
313 output_svg(lines, regressions, requested_width, requested_height)
314
315 #output the manipulation controls
316 print """
317<script type="text/javascript">//<![CDATA[
318 function getElementsByClass(node, searchClass, tag) {
319 var classElements = new Array();
320 var elements = node.getElementsByTagName(tag);
321 var pattern = new RegExp("^|\\s"+searchClass+"\\s|$");
322 for (var i = 0, elementsFound = 0; i < elements.length; ++i) {
323 if (pattern.test(elements[i].className)) {
324 classElements[elementsFound] = elements[i];
325 ++elementsFound;
326 }
327 }
328 return classElements;
329 }
330 function getAllLines() {
331 var selectElem = document.getElementById('benchSelect');
332 var linesObj = {};
333 for (var i = 0; i < selectElem.options.length; ++i) {
334 var lines = JSON.parse(selectElem.options[i].value);
335 for (var j = 0; j < lines.length; ++j) {
336 linesObj[lines[j]] = true;
337 }
338 }
339 return linesObj;
340 }
341 function getOptions(selectElem) {
342 var linesSelectedObj = {};
343 for (var i = 0; i < selectElem.options.length; ++i) {
344 if (!selectElem.options[i].selected) continue;
345
346 var linesSelected = JSON.parse(selectElem.options[i].value);
347 for (var j = 0; j < linesSelected.length; ++j) {
348 linesSelectedObj[linesSelected[j]] = true;
349 }
350 }
351 return linesSelectedObj;
352 }
353 function objectEmpty(obj) {
354 for (var p in obj) {
355 return false;
356 }
357 return true;
358 }
359 function markSelectedLines(selectElem, allLines) {
360 var linesSelected = getOptions(selectElem);
361 if (!objectEmpty(linesSelected)) {
362 for (var line in allLines) {
363 allLines[line] &= (linesSelected[line] == true);
364 }
365 }
366 }
367 function updateSvg() {
368 var allLines = getAllLines();
369
370 var selects = getElementsByClass(document, 'lines', 'select');
371 for (var i = 0; i < selects.length; ++i) {
372 markSelectedLines(selects[i], allLines);
373 }
374
375 for (var line in allLines) {
376 var svgLine = document.getElementById(line);
377 var display = (allLines[line] ? 'inline' : 'none');
378 svgLine.setAttributeNS(null,'display', display);
379 }
380 }
381
382 function mark(markerId) {
383 for (var line in getAllLines()) {
384 var svgLineGroup = document.getElementById(line);
385 var display = svgLineGroup.getAttributeNS(null,'display');
386 if (display == null || display == "" || display != "none") {
387 var svgLine = document.getElementById(line+'_line');
388 if (markerId == null) {
389 svgLine.removeAttributeNS(null,'marker-mid');
390 } else {
391 svgLine.setAttributeNS(null,'marker-mid', markerId);
392 }
393 }
394 }
395 }
396//]]></script>"""
397
398 print '<form>'
399
400 create_select(lambda l: l.bench, lines, 'benchSelect')
401 create_select(lambda l: l.config, lines)
402 create_select(lambda l: l.time_type, lines)
403
404 all_settings = {}
405 variant_settings = set()
406 for label in lines.keys():
407 for key, value in label.settings.items():
408 if key not in all_settings:
409 all_settings[key] = value
410 elif all_settings[key] != value:
411 variant_settings.add(key)
412
413 for k in variant_settings:
414 create_select(lambda l: l.settings[k], lines)
415
416 print '<button type="button"',
417 print 'onclick=%s' % qa("mark('url(#circleMark)'); return false;"),
418 print '>Mark</button>'
419 print '<button type="button" onclick="mark(null);">Clear</button>'
420
421 print '</form>'
422 print '</body>'
423 print '</html>'
424
425def compute_size(requested_width, requested_height, rev_width, time_height):
426 """Converts potentially empty requested size into a concrete size.
427
428 (Number?, Number?) -> (Number, Number)"""
429 pic_width = 0
430 pic_height = 0
431 if (requested_width is not None and requested_height is not None):
432 pic_height = requested_height
433 pic_width = requested_width
434
435 elif (requested_width is not None):
436 pic_width = requested_width
437 pic_height = pic_width * (float(time_height) / rev_width)
438
439 elif (requested_height is not None):
440 pic_height = requested_height
441 pic_width = pic_height * (float(rev_width) / time_height)
442
443 else:
444 pic_height = 800
445 pic_width = max(rev_width*3
446 , pic_height * (float(rev_width) / time_height))
447
448 return (pic_width, pic_height)
449
450def output_svg(lines, regressions, requested_width, requested_height):
451 """Outputs an svg view of the data."""
452
453 (global_min_x, _), (global_max_x, global_max_y) = bounds(lines)
454 max_up_slope, min_down_slope = bounds_slope(regressions)
455
456 #output
457 global_min_y = 0
458 x = global_min_x
459 y = global_min_y
460 w = global_max_x - global_min_x
461 h = global_max_y - global_min_y
462 font_size = 16
463 line_width = 2
464
465 pic_width, pic_height = compute_size(requested_width, requested_height
466 , w, h)
467
468 def cw(w1):
469 """Converts a revision difference to display width."""
470 return (pic_width / float(w)) * w1
471 def cx(x):
472 """Converts a revision to a horizontal display position."""
473 return cw(x - global_min_x)
474
475 def ch(h1):
476 """Converts a time difference to a display height."""
477 return -(pic_height / float(h)) * h1
478 def cy(y):
479 """Converts a time to a vertical display position."""
480 return pic_height + ch(y - global_min_y)
481
482 print '<svg',
483 print 'width=%s' % qa(str(pic_width)+'px')
484 print 'height=%s' % qa(str(pic_height)+'px')
485 print 'viewBox="0 0 %s %s"' % (str(pic_width), str(pic_height))
486 print 'onclick=%s' % qa(
487 "var event = arguments[0] || window.event;"
488 " if (event.shiftKey) { highlightRevision(null); }"
489 " if (event.ctrlKey) { highlight(null); }"
490 " return false;")
491 print 'xmlns="http://www.w3.org/2000/svg"'
492 print 'xmlns:xlink="http://www.w3.org/1999/xlink">'
493
494 print """
495<defs>
496 <marker id="circleMark"
497 viewBox="0 0 2 2" refX="1" refY="1"
498 markerUnits="strokeWidth"
499 markerWidth="2" markerHeight="2"
500 orient="0">
501 <circle cx="1" cy="1" r="1"/>
502 </marker>
503</defs>"""
504
505 #output the revisions
506 print """
507<script type="text/javascript">//<![CDATA[
508 var previousRevision;
509 var previousRevisionFill;
510 var previousRevisionStroke
511 function highlightRevision(id) {
512 if (previousRevision == id) return;
513
514 document.getElementById('revision').firstChild.nodeValue = id;
515
516 var preRevision = document.getElementById(previousRevision);
517 if (preRevision) {
518 preRevision.setAttributeNS(null,'fill', previousRevisionFill);
519 preRevision.setAttributeNS(null,'stroke', previousRevisionStroke);
520 }
521
522 var revision = document.getElementById(id);
523 previousRevision = id;
524 if (revision) {
525 previousRevisionFill = revision.getAttributeNS(null,'fill');
526 revision.setAttributeNS(null,'fill','rgb(100%, 95%, 95%)');
527
528 previousRevisionStroke = revision.getAttributeNS(null,'stroke');
529 revision.setAttributeNS(null,'stroke','rgb(100%, 90%, 90%)');
530 }
531 }
532//]]></script>"""
533
534 def print_rect(x, y, w, h, revision):
535 """Outputs a revision rectangle in display space,
536 taking arguments in revision space."""
537 disp_y = cy(y)
538 disp_h = ch(h)
539 if disp_h < 0:
540 disp_y += disp_h
541 disp_h = -disp_h
542
543 print '<rect id=%s x=%s y=%s' % (qa(revision), qa(cx(x)), qa(disp_y),),
544 print 'width=%s height=%s' % (qa(cw(w)), qa(disp_h),),
545 print 'fill="white"',
546 print 'stroke="rgb(99%%,99%%,99%%)" stroke-width=%s' % qa(line_width),
547 print 'onmouseover=%s' % qa(
548 "var event = arguments[0] || window.event;"
549 " if (event.shiftKey) {"
550 " highlightRevision('"+str(revision)+"');"
551 " return false;"
552 " }"),
553 print ' />'
554
555 xes = set()
556 for line in lines.itervalues():
557 for point in line:
558 xes.add(point[0])
559 revisions = list(xes)
560 revisions.sort()
561
562 left = x
563 current_revision = revisions[0]
564 for next_revision in revisions[1:]:
565 width = (((next_revision - current_revision) / 2.0)
566 + (current_revision - left))
567 print_rect(left, y, width, h, current_revision)
568 left += width
569 current_revision = next_revision
570 print_rect(left, y, x+w - left, h, current_revision)
571
572 #output the lines
573 print """
574<script type="text/javascript">//<![CDATA[
575 var previous;
576 var previousColor;
577 var previousOpacity;
578 function highlight(id) {
579 if (previous == id) return;
580
581 document.getElementById('label').firstChild.nodeValue = id;
582
583 var preGroup = document.getElementById(previous);
584 if (preGroup) {
585 var preLine = document.getElementById(previous+'_line');
586 preLine.setAttributeNS(null,'stroke', previousColor);
587 preLine.setAttributeNS(null,'opacity', previousOpacity);
588
589 var preSlope = document.getElementById(previous+'_linear');
590 if (preSlope) {
591 preSlope.setAttributeNS(null,'visibility', 'hidden');
592 }
593 }
594
595 var group = document.getElementById(id);
596 previous = id;
597 if (group) {
598 group.parentNode.appendChild(group);
599
600 var line = document.getElementById(id+'_line');
601 previousColor = line.getAttributeNS(null,'stroke');
602 previousOpacity = line.getAttributeNS(null,'opacity');
603 line.setAttributeNS(null,'stroke', 'blue');
604 line.setAttributeNS(null,'opacity', '1');
605
606 var slope = document.getElementById(id+'_linear');
607 if (slope) {
608 slope.setAttributeNS(null,'visibility', 'visible');
609 }
610 }
611 }
612//]]></script>"""
613 for label, line in lines.items():
614 print '<g id=%s>' % qa(label)
615 r = 128
616 g = 128
617 b = 128
618 a = .10
619 if label in regressions:
620 regression = regressions[label]
621 min_slope = regression.find_min_slope()
622 if min_slope < 0:
623 d = max(0, (min_slope / min_down_slope))
624 g += int(d*128)
625 a += d*0.9
626 elif min_slope > 0:
627 d = max(0, (min_slope / max_up_slope))
628 r += int(d*128)
629 a += d*0.9
630
631 slope = regression.slope
632 intercept = regression.intercept
633 min_x = regression.min_x
634 max_x = regression.max_x
635 print '<polyline id=%s' % qa(str(label)+'_linear'),
636 print 'fill="none" stroke="yellow"',
637 print 'stroke-width=%s' % qa(abs(ch(regression.serror*2))),
638 print 'opacity="0.5" pointer-events="none" visibility="hidden"',
639 print 'points="',
640 print '%s,%s' % (str(cx(min_x)), str(cy(slope*min_x + intercept))),
641 print '%s,%s' % (str(cx(max_x)), str(cy(slope*max_x + intercept))),
642 print '"/>'
643
644 print '<polyline id=%s' % qa(str(label)+'_line'),
645 print 'onmouseover=%s' % qa(
646 "var event = arguments[0] || window.event;"
647 " if (event.ctrlKey) {"
648 " highlight('"+str(label).replace("'", "\\'")+"');"
649 " return false;"
650 " }"),
651 print 'fill="none" stroke="rgb(%s,%s,%s)"' % (str(r), str(g), str(b)),
652 print 'stroke-width=%s' % qa(line_width),
653 print 'opacity=%s' % qa(a),
654 print 'points="',
655 for point in line:
656 print '%s,%s' % (str(cx(point[0])), str(cy(point[1]))),
657 print '"/>'
658
659 print '</g>'
660
661 #output the labels
662 print '<text id="label" x="0" y=%s' % qa(font_size),
663 print 'font-size=%s> </text>' % qa(font_size)
664
665 print '<text id="revision" x="0" y=%s' % qa(font_size*2),
666 print 'font-size=%s> </text>' % qa(font_size)
667
668 print '</svg>'
669
670if __name__ == "__main__":
671 main()