blob: 1bcb7f50c77dadab47e84c0f2508c110d457d1ea [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
epoger@google.com3d8cd172012-05-11 18:26:16 +000014# We throw out any measurement outside this range, and log a warning.
15MIN_REASONABLE_TIME = 0
16MAX_REASONABLE_TIME = 99999
17
bensong@google.comad0c5d22012-09-13 21:08:52 +000018# Constants for prefixes in output title used in buildbot.
19TITLE_PREAMBLE = 'Bench_Performance_for_Skia_'
20TITLE_PREAMBLE_LENGTH = len(TITLE_PREAMBLE)
21
bungeman@google.com85669f92011-06-17 13:58:14 +000022def usage():
23 """Prints simple usage information."""
24
bungeman@google.com85669f92011-06-17 13:58:14 +000025 print '-b <bench> the bench to show.'
26 print '-c <config> the config to show (GPU, 8888, 565, etc).'
epoger@google.com5b2e01c2012-06-25 20:29:04 +000027 print '-d <dir> a directory containing bench_r<revision>_<scalar> files.'
bensong@google.comad0c5d22012-09-13 21:08:52 +000028 print '-e <file> file containing expected bench values/ranges.'
29 print ' Will raise exception if actual bench values are out of range.'
30 print ' See bench_expectations.txt for data format and examples.'
bungeman@google.com85669f92011-06-17 13:58:14 +000031 print '-f <revision>[:<revision>] the revisions to use for fitting.'
epoger@google.com37260002011-08-08 20:27:04 +000032 print ' Negative <revision> is taken as offset from most recent revision.'
bensong@google.com8ccfa552012-08-17 21:42:14 +000033 print '-i <time> the time to ignore (w, c, g, etc).'
34 print ' The flag is ignored when -t is set; otherwise we plot all the'
35 print ' times except the one specified here.'
epoger@google.com5b2e01c2012-06-25 20:29:04 +000036 print '-l <title> title to use for the output graph'
bensong@google.com8ccfa552012-08-17 21:42:14 +000037 print '-m <representation> representation of bench value.'
38 print ' See _ListAlgorithm class in bench_util.py.'
epoger@google.com5b2e01c2012-06-25 20:29:04 +000039 print '-o <path> path to which to write output; writes to stdout if not specified'
40 print '-r <revision>[:<revision>] the revisions to show.'
41 print ' Negative <revision> is taken as offset from most recent revision.'
42 print '-s <setting>[=<value>] a setting to show (alpha, scalar, etc).'
43 print '-t <time> the time to show (w, c, g, etc).'
bungeman@google.com85669f92011-06-17 13:58:14 +000044 print '-x <int> the desired width of the svg.'
45 print '-y <int> the desired height of the svg.'
46 print '--default-setting <setting>[=<value>] setting for those without.'
47
48
49class Label:
50 """The information in a label.
51
52 (str, str, str, str, {str:str})"""
53 def __init__(self, bench, config, time_type, settings):
54 self.bench = bench
55 self.config = config
56 self.time_type = time_type
57 self.settings = settings
58
59 def __repr__(self):
60 return "Label(%s, %s, %s, %s)" % (
61 str(self.bench),
62 str(self.config),
63 str(self.time_type),
64 str(self.settings),
65 )
66
67 def __str__(self):
68 return "%s_%s_%s_%s" % (
69 str(self.bench),
70 str(self.config),
71 str(self.time_type),
72 str(self.settings),
73 )
74
75 def __eq__(self, other):
76 return (self.bench == other.bench and
77 self.config == other.config and
78 self.time_type == other.time_type and
79 self.settings == other.settings)
80
81 def __hash__(self):
82 return (hash(self.bench) ^
83 hash(self.config) ^
84 hash(self.time_type) ^
85 hash(frozenset(self.settings.iteritems())))
86
epoger@google.com37260002011-08-08 20:27:04 +000087def get_latest_revision(directory):
88 """Returns the latest revision number found within this directory.
89 """
90 latest_revision_found = -1
91 for bench_file in os.listdir(directory):
92 file_name_match = re.match('bench_r(\d+)_(\S+)', bench_file)
93 if (file_name_match is None):
94 continue
95 revision = int(file_name_match.group(1))
96 if revision > latest_revision_found:
97 latest_revision_found = revision
98 if latest_revision_found < 0:
99 return None
100 else:
101 return latest_revision_found
102
bensong@google.com87348162012-08-15 17:31:46 +0000103def parse_dir(directory, default_settings, oldest_revision, newest_revision,
104 rep):
bungeman@google.com85669f92011-06-17 13:58:14 +0000105 """Parses bench data from files like bench_r<revision>_<scalar>.
106
107 (str, {str, str}, Number, Number) -> {int:[BenchDataPoints]}"""
108 revision_data_points = {} # {revision : [BenchDataPoints]}
epoger@google.come9b31fa2013-02-14 20:13:32 +0000109 file_list = os.listdir(directory)
110 file_list.sort()
111 for bench_file in file_list:
bungeman@google.com85669f92011-06-17 13:58:14 +0000112 file_name_match = re.match('bench_r(\d+)_(\S+)', bench_file)
113 if (file_name_match is None):
114 continue
epoger@google.com3d8cd172012-05-11 18:26:16 +0000115
bungeman@google.com85669f92011-06-17 13:58:14 +0000116 revision = int(file_name_match.group(1))
117 scalar_type = file_name_match.group(2)
epoger@google.com3d8cd172012-05-11 18:26:16 +0000118
bungeman@google.com85669f92011-06-17 13:58:14 +0000119 if (revision < oldest_revision or revision > newest_revision):
120 continue
epoger@google.com3d8cd172012-05-11 18:26:16 +0000121
bungeman@google.com85669f92011-06-17 13:58:14 +0000122 file_handle = open(directory + '/' + bench_file, 'r')
epoger@google.com3d8cd172012-05-11 18:26:16 +0000123
bungeman@google.com85669f92011-06-17 13:58:14 +0000124 if (revision not in revision_data_points):
125 revision_data_points[revision] = []
126 default_settings['scalar'] = scalar_type
127 revision_data_points[revision].extend(
bensong@google.com87348162012-08-15 17:31:46 +0000128 bench_util.parse(default_settings, file_handle, rep))
bungeman@google.com85669f92011-06-17 13:58:14 +0000129 file_handle.close()
130 return revision_data_points
131
epoger@google.com3d8cd172012-05-11 18:26:16 +0000132def add_to_revision_data_points(new_point, revision, revision_data_points):
133 """Add new_point to set of revision_data_points we are building up.
134 """
135 if (revision not in revision_data_points):
136 revision_data_points[revision] = []
137 revision_data_points[revision].append(new_point)
138
139def filter_data_points(unfiltered_revision_data_points):
140 """Filter out any data points that are utterly bogus.
141
142 Returns (allowed_revision_data_points, ignored_revision_data_points):
143 allowed_revision_data_points: points that survived the filter
144 ignored_revision_data_points: points that did NOT survive the filter
145 """
146 allowed_revision_data_points = {} # {revision : [BenchDataPoints]}
147 ignored_revision_data_points = {} # {revision : [BenchDataPoints]}
148 revisions = unfiltered_revision_data_points.keys()
149 revisions.sort()
150 for revision in revisions:
151 for point in unfiltered_revision_data_points[revision]:
152 if point.time < MIN_REASONABLE_TIME or point.time > MAX_REASONABLE_TIME:
153 add_to_revision_data_points(point, revision, ignored_revision_data_points)
154 else:
155 add_to_revision_data_points(point, revision, allowed_revision_data_points)
156 return (allowed_revision_data_points, ignored_revision_data_points)
157
epoger@google.com1513f6e2012-06-27 13:38:37 +0000158def get_abs_path(relative_path):
159 """My own implementation of os.path.abspath() that better handles paths
160 which approach Window's 260-character limit.
161 See https://code.google.com/p/skia/issues/detail?id=674
162
163 This implementation adds path components one at a time, resolving the
164 absolute path each time, to take advantage of any chdirs into outer
165 directories that will shorten the total path length.
166
167 TODO: share a single implementation with upload_to_bucket.py, instead
168 of pasting this same code into both files."""
169 if os.path.isabs(relative_path):
170 return relative_path
171 path_parts = relative_path.split(os.sep)
172 abs_path = os.path.abspath('.')
173 for path_part in path_parts:
174 abs_path = os.path.abspath(os.path.join(abs_path, path_part))
175 return abs_path
176
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000177def redirect_stdout(output_path):
178 """Redirect all following stdout to a file.
179
180 You may be asking yourself, why redirect stdout within Python rather than
181 redirecting the script's output in the calling shell?
182 The answer lies in https://code.google.com/p/skia/issues/detail?id=674
183 ('buildbot: windows GenerateBenchGraphs step fails due to filename length'):
184 On Windows, we need to generate the absolute path within Python to avoid
185 the operating system's 260-character pathname limit, including chdirs."""
epoger@google.com1513f6e2012-06-27 13:38:37 +0000186 abs_path = get_abs_path(output_path)
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000187 sys.stdout = open(abs_path, 'w')
188
bungeman@google.com85669f92011-06-17 13:58:14 +0000189def create_lines(revision_data_points, settings
bensong@google.com8ccfa552012-08-17 21:42:14 +0000190 , bench_of_interest, config_of_interest, time_of_interest
191 , time_to_ignore):
epoger@google.com2459a392013-02-14 18:58:05 +0000192 """Convert revision data into a dictionary of line data.
bungeman@google.com85669f92011-06-17 13:58:14 +0000193
194 ({int:[BenchDataPoints]}, {str:str}, str?, str?, str?)
195 -> {Label:[(x,y)] | [n].x <= [n+1].x}"""
196 revisions = revision_data_points.keys()
197 revisions.sort()
198 lines = {} # {Label:[(x,y)] | x[n] <= x[n+1]}
199 for revision in revisions:
200 for point in revision_data_points[revision]:
201 if (bench_of_interest is not None and
202 not bench_of_interest == point.bench):
203 continue
204
205 if (config_of_interest is not None and
206 not config_of_interest == point.config):
207 continue
208
209 if (time_of_interest is not None and
210 not time_of_interest == point.time_type):
211 continue
bensong@google.com8ccfa552012-08-17 21:42:14 +0000212 elif (time_to_ignore is not None and
213 time_to_ignore == point.time_type):
214 continue
bungeman@google.com85669f92011-06-17 13:58:14 +0000215
216 skip = False
217 for key, value in settings.items():
218 if key in point.settings and point.settings[key] != value:
219 skip = True
220 break
221 if skip:
222 continue
223
224 line_name = Label(point.bench
225 , point.config
226 , point.time_type
227 , point.settings)
228
229 if line_name not in lines:
230 lines[line_name] = []
231
232 lines[line_name].append((revision, point.time))
233
234 return lines
235
236def bounds(lines):
237 """Finds the bounding rectangle for the lines.
238
239 {Label:[(x,y)]} -> ((min_x, min_y),(max_x,max_y))"""
240 min_x = bench_util.Max
241 min_y = bench_util.Max
242 max_x = bench_util.Min
243 max_y = bench_util.Min
244
245 for line in lines.itervalues():
246 for x, y in line:
247 min_x = min(min_x, x)
248 min_y = min(min_y, y)
249 max_x = max(max_x, x)
250 max_y = max(max_y, y)
251
252 return ((min_x, min_y), (max_x, max_y))
253
254def create_regressions(lines, start_x, end_x):
255 """Creates regression data from line segments.
256
257 ({Label:[(x,y)] | [n].x <= [n+1].x}, Number, Number)
258 -> {Label:LinearRegression}"""
259 regressions = {} # {Label : LinearRegression}
260
261 for label, line in lines.iteritems():
262 regression_line = [p for p in line if start_x <= p[0] <= end_x]
263
264 if (len(regression_line) < 2):
265 continue
266 regression = bench_util.LinearRegression(regression_line)
267 regressions[label] = regression
268
269 return regressions
270
271def bounds_slope(regressions):
272 """Finds the extreme up and down slopes of a set of linear regressions.
273
274 ({Label:LinearRegression}) -> (max_up_slope, min_down_slope)"""
275 max_up_slope = 0
276 min_down_slope = 0
277 for regression in regressions.itervalues():
278 min_slope = regression.find_min_slope()
279 max_up_slope = max(max_up_slope, min_slope)
280 min_down_slope = min(min_down_slope, min_slope)
281
282 return (max_up_slope, min_down_slope)
283
284def main():
285 """Parses command line and writes output."""
286
287 try:
288 opts, _ = getopt.getopt(sys.argv[1:]
bensong@google.comad0c5d22012-09-13 21:08:52 +0000289 , "b:c:d:e:f:i:l:m:o:r:s:t:x:y:"
bungeman@google.com85669f92011-06-17 13:58:14 +0000290 , "default-setting=")
291 except getopt.GetoptError, err:
292 print str(err)
293 usage()
294 sys.exit(2)
295
296 directory = None
297 config_of_interest = None
298 bench_of_interest = None
299 time_of_interest = None
bensong@google.com8ccfa552012-08-17 21:42:14 +0000300 time_to_ignore = None
bensong@google.comad0c5d22012-09-13 21:08:52 +0000301 bench_expectations = {}
bensong@google.comb6204b12012-08-16 20:49:28 +0000302 rep = None # bench representation algorithm
epoger@google.com37260002011-08-08 20:27:04 +0000303 revision_range = '0:'
304 regression_range = '0:'
305 latest_revision = None
bungeman@google.com85669f92011-06-17 13:58:14 +0000306 requested_height = None
307 requested_width = None
epoger@google.com37260002011-08-08 20:27:04 +0000308 title = 'Bench graph'
bungeman@google.com85669f92011-06-17 13:58:14 +0000309 settings = {}
310 default_settings = {}
epoger@google.com37260002011-08-08 20:27:04 +0000311
312 def parse_range(range):
313 """Takes '<old>[:<new>]' as a string and returns (old, new).
314 Any revision numbers that are dependent on the latest revision number
315 will be filled in based on latest_revision.
316 """
317 old, _, new = range.partition(":")
318 old = int(old)
319 if old < 0:
320 old += latest_revision;
bungeman@google.com85669f92011-06-17 13:58:14 +0000321 if not new:
epoger@google.com37260002011-08-08 20:27:04 +0000322 new = latest_revision;
323 new = int(new)
324 if new < 0:
325 new += latest_revision;
326 return (old, new)
327
bungeman@google.com85669f92011-06-17 13:58:14 +0000328 def add_setting(settings, setting):
329 """Takes <key>[=<value>] adds {key:value} or {key:True} to settings."""
330 name, _, value = setting.partition('=')
331 if not value:
332 settings[name] = True
333 else:
334 settings[name] = value
bensong@google.comad0c5d22012-09-13 21:08:52 +0000335
336 def read_expectations(expectations, filename):
337 """Reads expectations data from file and put in expectations dict."""
338 for expectation in open(filename).readlines():
339 elements = expectation.strip().split(',')
340 if not elements[0] or elements[0].startswith('#'):
341 continue
342 if len(elements) != 5:
343 raise Exception("Invalid expectation line format: %s" %
344 expectation)
345 bench_entry = elements[0] + ',' + elements[1]
346 if bench_entry in expectations:
347 raise Exception("Dup entries for bench expectation %s" %
348 bench_entry)
349 # [<Bench_BmpConfig_TimeType>,<Platform-Alg>] -> (LB, UB)
350 expectations[bench_entry] = (float(elements[-2]),
351 float(elements[-1]))
352
353 def check_expectations(lines, expectations, newest_revision, key_suffix):
354 """Check if there are benches in latest rev outside expected range."""
355 exceptions = []
356 for line in lines:
357 line_str = str(line)
358 bench_platform_key = (line_str[ : line_str.find('_{')] + ',' +
359 key_suffix)
360 this_revision, this_bench_value = lines[line][-1]
361 if (this_revision != newest_revision or
362 bench_platform_key not in expectations):
363 # Skip benches without value for latest revision.
364 continue
365 this_min, this_max = expectations[bench_platform_key]
366 if this_bench_value < this_min or this_bench_value > this_max:
367 exceptions.append('Bench %s value %s out of range [%s, %s].' %
368 (bench_platform_key, this_bench_value, this_min, this_max))
369 if exceptions:
370 raise Exception('Bench values out of range:\n' +
371 '\n'.join(exceptions))
372
bungeman@google.com85669f92011-06-17 13:58:14 +0000373 try:
374 for option, value in opts:
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000375 if option == "-b":
bungeman@google.com85669f92011-06-17 13:58:14 +0000376 bench_of_interest = value
377 elif option == "-c":
378 config_of_interest = value
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000379 elif option == "-d":
380 directory = value
bensong@google.comad0c5d22012-09-13 21:08:52 +0000381 elif option == "-e":
382 read_expectations(bench_expectations, value)
bungeman@google.com85669f92011-06-17 13:58:14 +0000383 elif option == "-f":
epoger@google.com37260002011-08-08 20:27:04 +0000384 regression_range = value
bensong@google.com8ccfa552012-08-17 21:42:14 +0000385 elif option == "-i":
386 time_to_ignore = value
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000387 elif option == "-l":
388 title = value
bensong@google.com87348162012-08-15 17:31:46 +0000389 elif option == "-m":
390 rep = value
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000391 elif option == "-o":
392 redirect_stdout(value)
393 elif option == "-r":
394 revision_range = value
395 elif option == "-s":
396 add_setting(settings, value)
397 elif option == "-t":
398 time_of_interest = value
bungeman@google.com85669f92011-06-17 13:58:14 +0000399 elif option == "-x":
400 requested_width = int(value)
401 elif option == "-y":
402 requested_height = int(value)
403 elif option == "--default-setting":
404 add_setting(default_settings, value)
405 else:
406 usage()
407 assert False, "unhandled option"
408 except ValueError:
409 usage()
410 sys.exit(2)
epoger@google.comc71174d2011-08-08 17:19:23 +0000411
bungeman@google.com85669f92011-06-17 13:58:14 +0000412 if directory is None:
413 usage()
414 sys.exit(2)
epoger@google.comc71174d2011-08-08 17:19:23 +0000415
bensong@google.com8ccfa552012-08-17 21:42:14 +0000416 if time_of_interest:
417 time_to_ignore = None
418
bensong@google.comad0c5d22012-09-13 21:08:52 +0000419 # The title flag (-l) provided in buildbot slave is in the format
420 # Bench_Performance_for_Skia_<platform>, and we want to extract <platform>
421 # for use in platform_and_alg to track matching benches later. If title flag
422 # is not in this format, there may be no matching benches in the file
423 # provided by the expectation_file flag (-e).
424 platform_and_alg = title
425 if platform_and_alg.startswith(TITLE_PREAMBLE):
426 platform_and_alg = (
427 platform_and_alg[TITLE_PREAMBLE_LENGTH:] + '-' + rep)
bensong@google.com8c1de762012-08-15 18:27:38 +0000428 title += ' [representation: %s]' % rep
429
epoger@google.com37260002011-08-08 20:27:04 +0000430 latest_revision = get_latest_revision(directory)
431 oldest_revision, newest_revision = parse_range(revision_range)
432 oldest_regression, newest_regression = parse_range(regression_range)
433
epoger@google.com3d8cd172012-05-11 18:26:16 +0000434 unfiltered_revision_data_points = parse_dir(directory
bungeman@google.com85669f92011-06-17 13:58:14 +0000435 , default_settings
436 , oldest_revision
bensong@google.com87348162012-08-15 17:31:46 +0000437 , newest_revision
438 , rep)
epoger@google.comc71174d2011-08-08 17:19:23 +0000439
epoger@google.com3d8cd172012-05-11 18:26:16 +0000440 # Filter out any data points that are utterly bogus... make sure to report
441 # that we did so later!
442 (allowed_revision_data_points, ignored_revision_data_points) = filter_data_points(
443 unfiltered_revision_data_points)
444
epoger@google.comc71174d2011-08-08 17:19:23 +0000445 # Update oldest_revision and newest_revision based on the data we could find
epoger@google.com3d8cd172012-05-11 18:26:16 +0000446 all_revision_numbers = allowed_revision_data_points.keys()
epoger@google.comc71174d2011-08-08 17:19:23 +0000447 oldest_revision = min(all_revision_numbers)
448 newest_revision = max(all_revision_numbers)
449
epoger@google.com3d8cd172012-05-11 18:26:16 +0000450 lines = create_lines(allowed_revision_data_points
bungeman@google.com85669f92011-06-17 13:58:14 +0000451 , settings
452 , bench_of_interest
453 , config_of_interest
bensong@google.com8ccfa552012-08-17 21:42:14 +0000454 , time_of_interest
455 , time_to_ignore)
epoger@google.comc71174d2011-08-08 17:19:23 +0000456
bungeman@google.com85669f92011-06-17 13:58:14 +0000457 regressions = create_regressions(lines
458 , oldest_regression
459 , newest_regression)
epoger@google.comc71174d2011-08-08 17:19:23 +0000460
epoger@google.com3d8cd172012-05-11 18:26:16 +0000461 output_xhtml(lines, oldest_revision, newest_revision, ignored_revision_data_points,
epoger@google.com37260002011-08-08 20:27:04 +0000462 regressions, requested_width, requested_height, title)
bungeman@google.com85669f92011-06-17 13:58:14 +0000463
bensong@google.comad0c5d22012-09-13 21:08:52 +0000464 check_expectations(lines, bench_expectations, newest_revision,
465 platform_and_alg)
466
bungeman@google.com85669f92011-06-17 13:58:14 +0000467def qa(out):
468 """Stringify input and quote as an xml attribute."""
469 return xml.sax.saxutils.quoteattr(str(out))
470def qe(out):
471 """Stringify input and escape as xml data."""
472 return xml.sax.saxutils.escape(str(out))
473
474def create_select(qualifier, lines, select_id=None):
475 """Output select with options showing lines which qualifier maps to it.
476
477 ((Label) -> str, {Label:_}, str?) -> _"""
478 options = {} #{ option : [Label]}
479 for label in lines.keys():
480 option = qualifier(label)
481 if (option not in options):
482 options[option] = []
483 options[option].append(label)
484 option_list = list(options.keys())
485 option_list.sort()
486 print '<select class="lines"',
487 if select_id is not None:
488 print 'id=%s' % qa(select_id)
489 print 'multiple="true" size="10" onchange="updateSvg();">'
490 for option in option_list:
491 print '<option value=' + qa('[' +
492 reduce(lambda x,y:x+json.dumps(str(y))+',',options[option],"")[0:-1]
493 + ']') + '>'+qe(option)+'</option>'
494 print '</select>'
495
epoger@google.com3d8cd172012-05-11 18:26:16 +0000496def output_ignored_data_points_warning(ignored_revision_data_points):
497 """Write description of ignored_revision_data_points to stdout as xhtml.
498 """
499 num_ignored_points = 0
500 description = ''
501 revisions = ignored_revision_data_points.keys()
502 if revisions:
503 revisions.sort()
504 revisions.reverse()
505 for revision in revisions:
506 num_ignored_points += len(ignored_revision_data_points[revision])
507 points_at_this_revision = []
508 for point in ignored_revision_data_points[revision]:
509 points_at_this_revision.append(point.bench)
510 points_at_this_revision.sort()
511 description += 'r%d: %s\n' % (revision, points_at_this_revision)
512 if num_ignored_points == 0:
513 print 'Did not discard any data points; all were within the range [%d-%d]' % (
514 MIN_REASONABLE_TIME, MAX_REASONABLE_TIME)
515 else:
516 print '<table width="100%" bgcolor="ff0000"><tr><td align="center">'
517 print 'Discarded %d data points outside of range [%d-%d]' % (
518 num_ignored_points, MIN_REASONABLE_TIME, MAX_REASONABLE_TIME)
519 print '</td></tr><tr><td width="100%" align="center">'
520 print ('<textarea rows="4" style="width:97%" readonly="true" wrap="off">'
521 + qe(description) + '</textarea>')
522 print '</td></tr></table>'
523
524def output_xhtml(lines, oldest_revision, newest_revision, ignored_revision_data_points,
epoger@google.com37260002011-08-08 20:27:04 +0000525 regressions, requested_width, requested_height, title):
bungeman@google.com85669f92011-06-17 13:58:14 +0000526 """Outputs an svg/xhtml view of the data."""
527 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"',
528 print '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
529 print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">'
530 print '<head>'
epoger@google.com3d8cd172012-05-11 18:26:16 +0000531 print '<title>%s</title>' % qe(title)
bungeman@google.com85669f92011-06-17 13:58:14 +0000532 print '</head>'
533 print '<body>'
534
535 output_svg(lines, regressions, requested_width, requested_height)
epoger@google.com3d8cd172012-05-11 18:26:16 +0000536
bungeman@google.com85669f92011-06-17 13:58:14 +0000537 #output the manipulation controls
538 print """
539<script type="text/javascript">//<![CDATA[
540 function getElementsByClass(node, searchClass, tag) {
541 var classElements = new Array();
542 var elements = node.getElementsByTagName(tag);
543 var pattern = new RegExp("^|\\s"+searchClass+"\\s|$");
544 for (var i = 0, elementsFound = 0; i < elements.length; ++i) {
545 if (pattern.test(elements[i].className)) {
546 classElements[elementsFound] = elements[i];
547 ++elementsFound;
548 }
549 }
550 return classElements;
551 }
552 function getAllLines() {
553 var selectElem = document.getElementById('benchSelect');
554 var linesObj = {};
555 for (var i = 0; i < selectElem.options.length; ++i) {
556 var lines = JSON.parse(selectElem.options[i].value);
557 for (var j = 0; j < lines.length; ++j) {
558 linesObj[lines[j]] = true;
559 }
560 }
561 return linesObj;
562 }
563 function getOptions(selectElem) {
564 var linesSelectedObj = {};
565 for (var i = 0; i < selectElem.options.length; ++i) {
566 if (!selectElem.options[i].selected) continue;
567
568 var linesSelected = JSON.parse(selectElem.options[i].value);
569 for (var j = 0; j < linesSelected.length; ++j) {
570 linesSelectedObj[linesSelected[j]] = true;
571 }
572 }
573 return linesSelectedObj;
574 }
575 function objectEmpty(obj) {
576 for (var p in obj) {
577 return false;
578 }
579 return true;
580 }
581 function markSelectedLines(selectElem, allLines) {
582 var linesSelected = getOptions(selectElem);
583 if (!objectEmpty(linesSelected)) {
584 for (var line in allLines) {
585 allLines[line] &= (linesSelected[line] == true);
586 }
587 }
588 }
589 function updateSvg() {
590 var allLines = getAllLines();
591
592 var selects = getElementsByClass(document, 'lines', 'select');
593 for (var i = 0; i < selects.length; ++i) {
594 markSelectedLines(selects[i], allLines);
595 }
596
597 for (var line in allLines) {
598 var svgLine = document.getElementById(line);
599 var display = (allLines[line] ? 'inline' : 'none');
600 svgLine.setAttributeNS(null,'display', display);
601 }
602 }
603
604 function mark(markerId) {
605 for (var line in getAllLines()) {
606 var svgLineGroup = document.getElementById(line);
607 var display = svgLineGroup.getAttributeNS(null,'display');
608 if (display == null || display == "" || display != "none") {
609 var svgLine = document.getElementById(line+'_line');
610 if (markerId == null) {
611 svgLine.removeAttributeNS(null,'marker-mid');
612 } else {
613 svgLine.setAttributeNS(null,'marker-mid', markerId);
614 }
615 }
616 }
617 }
618//]]></script>"""
epoger@google.comc71174d2011-08-08 17:19:23 +0000619
bungeman@google.com85669f92011-06-17 13:58:14 +0000620 all_settings = {}
621 variant_settings = set()
622 for label in lines.keys():
623 for key, value in label.settings.items():
624 if key not in all_settings:
625 all_settings[key] = value
626 elif all_settings[key] != value:
627 variant_settings.add(key)
epoger@google.comc71174d2011-08-08 17:19:23 +0000628
bungeman@google.com752acc72012-09-12 19:34:17 +0000629 print '<table border="0" width="%s">' % requested_width
630 #output column headers
631 print """
632<tr valign="top"><td width="50%">
633<table border="0" width="100%">
634<tr><td align="center"><table border="0">
635<form>
636<tr valign="bottom" align="center">
637<td width="1">Bench&nbsp;Type</td>
638<td width="1">Bitmap Config</td>
639<td width="1">Timer&nbsp;Type (Cpu/Gpu/wall)</td>
640"""
641
bungeman@google.com85669f92011-06-17 13:58:14 +0000642 for k in variant_settings:
bungeman@google.com752acc72012-09-12 19:34:17 +0000643 print '<td width="1">%s</td>' % qe(k)
644
645 print '<td width="1"><!--buttons--></td></tr>'
646
647 #output column contents
648 print '<tr valign="top" align="center">'
649 print '<td width="1">'
650 create_select(lambda l: l.bench, lines, 'benchSelect')
651 print '</td><td width="1">'
652 create_select(lambda l: l.config, lines)
653 print '</td><td width="1">'
654 create_select(lambda l: l.time_type, lines)
655
656 for k in variant_settings:
657 print '</td><td width="1">'
658 create_select(lambda l: l.settings.get(k, " "), lines)
epoger@google.comc71174d2011-08-08 17:19:23 +0000659
660 print '</td><td width="1"><button type="button"',
bungeman@google.com85669f92011-06-17 13:58:14 +0000661 print 'onclick=%s' % qa("mark('url(#circleMark)'); return false;"),
epoger@google.comc71174d2011-08-08 17:19:23 +0000662 print '>Mark Points</button>'
663 print '<button type="button" onclick="mark(null);">Clear Points</button>'
epoger@google.com3d8cd172012-05-11 18:26:16 +0000664 print '</td>'
epoger@google.comc71174d2011-08-08 17:19:23 +0000665 print """
epoger@google.com3d8cd172012-05-11 18:26:16 +0000666</tr>
667</form>
668</table></td></tr>
669<tr><td align="center">
670<hr />
671"""
672
673 output_ignored_data_points_warning(ignored_revision_data_points)
674 print '</td></tr></table>'
675 print '</td><td width="2%"><!--gutter--></td>'
676
677 print '<td><table border="0">'
678 print '<tr><td align="center">%s<br></br>revisions r%s - r%s</td></tr>' % (
679 qe(title),
680 bench_util.CreateRevisionLink(oldest_revision),
681 bench_util.CreateRevisionLink(newest_revision))
682 print """
683<tr><td align="left">
epoger@google.comc71174d2011-08-08 17:19:23 +0000684<p>Brighter red indicates tests that have gotten worse; brighter green
685indicates tests that have gotten better.</p>
686<p>To highlight individual tests, hold down CONTROL and mouse over
687graph lines.</p>
688<p>To highlight revision numbers, hold down SHIFT and mouse over
689the graph area.</p>
690<p>To only show certain tests on the graph, select any combination of
691tests in the selectors at left. (To show all, select all.)</p>
692<p>Use buttons at left to mark/clear points on the lines for selected
693benchmarks.</p>
epoger@google.com3d8cd172012-05-11 18:26:16 +0000694</td></tr>
695</table>
696
epoger@google.comc71174d2011-08-08 17:19:23 +0000697</td>
698</tr>
epoger@google.comc71174d2011-08-08 17:19:23 +0000699</table>
700</body>
701</html>"""
bungeman@google.com85669f92011-06-17 13:58:14 +0000702
703def compute_size(requested_width, requested_height, rev_width, time_height):
704 """Converts potentially empty requested size into a concrete size.
705
706 (Number?, Number?) -> (Number, Number)"""
707 pic_width = 0
708 pic_height = 0
709 if (requested_width is not None and requested_height is not None):
710 pic_height = requested_height
711 pic_width = requested_width
712
713 elif (requested_width is not None):
714 pic_width = requested_width
715 pic_height = pic_width * (float(time_height) / rev_width)
716
717 elif (requested_height is not None):
718 pic_height = requested_height
719 pic_width = pic_height * (float(rev_width) / time_height)
720
721 else:
722 pic_height = 800
723 pic_width = max(rev_width*3
724 , pic_height * (float(rev_width) / time_height))
725
726 return (pic_width, pic_height)
727
728def output_svg(lines, regressions, requested_width, requested_height):
729 """Outputs an svg view of the data."""
730
731 (global_min_x, _), (global_max_x, global_max_y) = bounds(lines)
732 max_up_slope, min_down_slope = bounds_slope(regressions)
733
734 #output
735 global_min_y = 0
736 x = global_min_x
737 y = global_min_y
738 w = global_max_x - global_min_x
739 h = global_max_y - global_min_y
740 font_size = 16
741 line_width = 2
742
743 pic_width, pic_height = compute_size(requested_width, requested_height
744 , w, h)
745
746 def cw(w1):
747 """Converts a revision difference to display width."""
748 return (pic_width / float(w)) * w1
749 def cx(x):
750 """Converts a revision to a horizontal display position."""
751 return cw(x - global_min_x)
752
753 def ch(h1):
754 """Converts a time difference to a display height."""
755 return -(pic_height / float(h)) * h1
756 def cy(y):
757 """Converts a time to a vertical display position."""
758 return pic_height + ch(y - global_min_y)
759
bensong@google.com74267432012-08-30 18:19:02 +0000760 print '<!--Picture height %.2f corresponds to bench value %.2f.-->' % (
761 pic_height, h)
bungeman@google.com85669f92011-06-17 13:58:14 +0000762 print '<svg',
763 print 'width=%s' % qa(str(pic_width)+'px')
764 print 'height=%s' % qa(str(pic_height)+'px')
765 print 'viewBox="0 0 %s %s"' % (str(pic_width), str(pic_height))
766 print 'onclick=%s' % qa(
767 "var event = arguments[0] || window.event;"
768 " if (event.shiftKey) { highlightRevision(null); }"
769 " if (event.ctrlKey) { highlight(null); }"
770 " return false;")
771 print 'xmlns="http://www.w3.org/2000/svg"'
772 print 'xmlns:xlink="http://www.w3.org/1999/xlink">'
773
774 print """
775<defs>
776 <marker id="circleMark"
777 viewBox="0 0 2 2" refX="1" refY="1"
778 markerUnits="strokeWidth"
779 markerWidth="2" markerHeight="2"
780 orient="0">
781 <circle cx="1" cy="1" r="1"/>
782 </marker>
783</defs>"""
784
785 #output the revisions
786 print """
787<script type="text/javascript">//<![CDATA[
788 var previousRevision;
789 var previousRevisionFill;
790 var previousRevisionStroke
791 function highlightRevision(id) {
792 if (previousRevision == id) return;
epoger@google.comc71174d2011-08-08 17:19:23 +0000793
794 document.getElementById('revision').firstChild.nodeValue = 'r' + id;
795 document.getElementById('rev_link').setAttribute('xlink:href',
796 'http://code.google.com/p/skia/source/detail?r=' + id);
bungeman@google.com85669f92011-06-17 13:58:14 +0000797
798 var preRevision = document.getElementById(previousRevision);
799 if (preRevision) {
800 preRevision.setAttributeNS(null,'fill', previousRevisionFill);
801 preRevision.setAttributeNS(null,'stroke', previousRevisionStroke);
802 }
803
804 var revision = document.getElementById(id);
805 previousRevision = id;
806 if (revision) {
807 previousRevisionFill = revision.getAttributeNS(null,'fill');
808 revision.setAttributeNS(null,'fill','rgb(100%, 95%, 95%)');
809
810 previousRevisionStroke = revision.getAttributeNS(null,'stroke');
811 revision.setAttributeNS(null,'stroke','rgb(100%, 90%, 90%)');
812 }
813 }
814//]]></script>"""
815
816 def print_rect(x, y, w, h, revision):
817 """Outputs a revision rectangle in display space,
818 taking arguments in revision space."""
819 disp_y = cy(y)
820 disp_h = ch(h)
821 if disp_h < 0:
822 disp_y += disp_h
823 disp_h = -disp_h
824
825 print '<rect id=%s x=%s y=%s' % (qa(revision), qa(cx(x)), qa(disp_y),),
826 print 'width=%s height=%s' % (qa(cw(w)), qa(disp_h),),
827 print 'fill="white"',
epoger@google.comc71174d2011-08-08 17:19:23 +0000828 print 'stroke="rgb(98%%,98%%,88%%)" stroke-width=%s' % qa(line_width),
bungeman@google.com85669f92011-06-17 13:58:14 +0000829 print 'onmouseover=%s' % qa(
830 "var event = arguments[0] || window.event;"
831 " if (event.shiftKey) {"
832 " highlightRevision('"+str(revision)+"');"
833 " return false;"
834 " }"),
835 print ' />'
836
837 xes = set()
838 for line in lines.itervalues():
839 for point in line:
840 xes.add(point[0])
841 revisions = list(xes)
842 revisions.sort()
843
844 left = x
845 current_revision = revisions[0]
846 for next_revision in revisions[1:]:
847 width = (((next_revision - current_revision) / 2.0)
848 + (current_revision - left))
849 print_rect(left, y, width, h, current_revision)
850 left += width
851 current_revision = next_revision
852 print_rect(left, y, x+w - left, h, current_revision)
epoger@google.comc71174d2011-08-08 17:19:23 +0000853
bungeman@google.com85669f92011-06-17 13:58:14 +0000854 #output the lines
855 print """
856<script type="text/javascript">//<![CDATA[
857 var previous;
858 var previousColor;
859 var previousOpacity;
860 function highlight(id) {
861 if (previous == id) return;
epoger@google.comc71174d2011-08-08 17:19:23 +0000862
bungeman@google.com85669f92011-06-17 13:58:14 +0000863 document.getElementById('label').firstChild.nodeValue = id;
epoger@google.comc71174d2011-08-08 17:19:23 +0000864
bungeman@google.com85669f92011-06-17 13:58:14 +0000865 var preGroup = document.getElementById(previous);
866 if (preGroup) {
867 var preLine = document.getElementById(previous+'_line');
868 preLine.setAttributeNS(null,'stroke', previousColor);
869 preLine.setAttributeNS(null,'opacity', previousOpacity);
epoger@google.comc71174d2011-08-08 17:19:23 +0000870
bungeman@google.com85669f92011-06-17 13:58:14 +0000871 var preSlope = document.getElementById(previous+'_linear');
872 if (preSlope) {
873 preSlope.setAttributeNS(null,'visibility', 'hidden');
874 }
875 }
epoger@google.comc71174d2011-08-08 17:19:23 +0000876
bungeman@google.com85669f92011-06-17 13:58:14 +0000877 var group = document.getElementById(id);
878 previous = id;
879 if (group) {
880 group.parentNode.appendChild(group);
881
882 var line = document.getElementById(id+'_line');
883 previousColor = line.getAttributeNS(null,'stroke');
884 previousOpacity = line.getAttributeNS(null,'opacity');
885 line.setAttributeNS(null,'stroke', 'blue');
886 line.setAttributeNS(null,'opacity', '1');
887
888 var slope = document.getElementById(id+'_linear');
889 if (slope) {
890 slope.setAttributeNS(null,'visibility', 'visible');
891 }
892 }
893 }
894//]]></script>"""
epoger@google.com2459a392013-02-14 18:58:05 +0000895
896 # Add a new element to each item in the 'lines' list: the label in string
897 # form. Then use that element to sort the list.
898 sorted_lines = []
bungeman@google.com85669f92011-06-17 13:58:14 +0000899 for label, line in lines.items():
epoger@google.com2459a392013-02-14 18:58:05 +0000900 sorted_lines.append([str(label), label, line])
901 sorted_lines.sort()
902
903 for label_as_string, label, line in sorted_lines:
904 print '<g id=%s>' % qa(label_as_string)
bungeman@google.com85669f92011-06-17 13:58:14 +0000905 r = 128
906 g = 128
907 b = 128
908 a = .10
909 if label in regressions:
910 regression = regressions[label]
911 min_slope = regression.find_min_slope()
912 if min_slope < 0:
913 d = max(0, (min_slope / min_down_slope))
914 g += int(d*128)
915 a += d*0.9
916 elif min_slope > 0:
917 d = max(0, (min_slope / max_up_slope))
918 r += int(d*128)
919 a += d*0.9
920
921 slope = regression.slope
922 intercept = regression.intercept
923 min_x = regression.min_x
924 max_x = regression.max_x
925 print '<polyline id=%s' % qa(str(label)+'_linear'),
926 print 'fill="none" stroke="yellow"',
927 print 'stroke-width=%s' % qa(abs(ch(regression.serror*2))),
928 print 'opacity="0.5" pointer-events="none" visibility="hidden"',
929 print 'points="',
930 print '%s,%s' % (str(cx(min_x)), str(cy(slope*min_x + intercept))),
931 print '%s,%s' % (str(cx(max_x)), str(cy(slope*max_x + intercept))),
932 print '"/>'
933
934 print '<polyline id=%s' % qa(str(label)+'_line'),
935 print 'onmouseover=%s' % qa(
936 "var event = arguments[0] || window.event;"
937 " if (event.ctrlKey) {"
938 " highlight('"+str(label).replace("'", "\\'")+"');"
939 " return false;"
940 " }"),
941 print 'fill="none" stroke="rgb(%s,%s,%s)"' % (str(r), str(g), str(b)),
942 print 'stroke-width=%s' % qa(line_width),
943 print 'opacity=%s' % qa(a),
944 print 'points="',
945 for point in line:
946 print '%s,%s' % (str(cx(point[0])), str(cy(point[1]))),
947 print '"/>'
epoger@google.comc71174d2011-08-08 17:19:23 +0000948
bungeman@google.com85669f92011-06-17 13:58:14 +0000949 print '</g>'
epoger@google.comc71174d2011-08-08 17:19:23 +0000950
bungeman@google.com85669f92011-06-17 13:58:14 +0000951 #output the labels
952 print '<text id="label" x="0" y=%s' % qa(font_size),
953 print 'font-size=%s> </text>' % qa(font_size)
epoger@google.comc71174d2011-08-08 17:19:23 +0000954
955 print '<a id="rev_link" xlink:href="" target="_top">'
956 print '<text id="revision" x="0" y=%s style="' % qa(font_size*2)
957 print 'font-size: %s; ' % qe(font_size)
958 print 'stroke: #0000dd; text-decoration: underline; '
959 print '"> </text></a>'
960
bungeman@google.com85669f92011-06-17 13:58:14 +0000961 print '</svg>'
epoger@google.comc71174d2011-08-08 17:19:23 +0000962
bungeman@google.com85669f92011-06-17 13:58:14 +0000963if __name__ == "__main__":
964 main()