blob: 57be7ea4ca9179baa9033edbaf84017d7f84b529 [file] [log] [blame]
bungeman@google.com85669f92011-06-17 13:58:14 +00001'''
2Created on May 16, 2011
3
4@author: bungeman
5'''
bungeman@google.com85669f92011-06-17 13:58:14 +00006import bench_util
bensong@google.com848fa2b2013-03-07 17:12:43 +00007import getopt
8import httplib
9import itertools
bungeman@google.com85669f92011-06-17 13:58:14 +000010import json
bensong@google.com848fa2b2013-03-07 17:12:43 +000011import os
12import re
13import sys
14import urllib
15import urllib2
bungeman@google.com85669f92011-06-17 13:58:14 +000016import xml.sax.saxutils
17
epoger@google.com3d8cd172012-05-11 18:26:16 +000018# We throw out any measurement outside this range, and log a warning.
19MIN_REASONABLE_TIME = 0
20MAX_REASONABLE_TIME = 99999
21
bensong@google.comad0c5d22012-09-13 21:08:52 +000022# Constants for prefixes in output title used in buildbot.
23TITLE_PREAMBLE = 'Bench_Performance_for_Skia_'
24TITLE_PREAMBLE_LENGTH = len(TITLE_PREAMBLE)
25
bungeman@google.com85669f92011-06-17 13:58:14 +000026def usage():
27 """Prints simple usage information."""
bensong@google.com848fa2b2013-03-07 17:12:43 +000028
29 print '-a <url> the url to use for adding bench values to app engine app.'
30 print ' Example: "https://skiadash.appspot.com/add_point".'
31 print ' If not set, will skip this step.'
bungeman@google.com85669f92011-06-17 13:58:14 +000032 print '-b <bench> the bench to show.'
33 print '-c <config> the config to show (GPU, 8888, 565, etc).'
epoger@google.com5b2e01c2012-06-25 20:29:04 +000034 print '-d <dir> a directory containing bench_r<revision>_<scalar> files.'
bensong@google.comad0c5d22012-09-13 21:08:52 +000035 print '-e <file> file containing expected bench values/ranges.'
36 print ' Will raise exception if actual bench values are out of range.'
37 print ' See bench_expectations.txt for data format and examples.'
bungeman@google.com85669f92011-06-17 13:58:14 +000038 print '-f <revision>[:<revision>] the revisions to use for fitting.'
epoger@google.com37260002011-08-08 20:27:04 +000039 print ' Negative <revision> is taken as offset from most recent revision.'
bensong@google.com8ccfa552012-08-17 21:42:14 +000040 print '-i <time> the time to ignore (w, c, g, etc).'
41 print ' The flag is ignored when -t is set; otherwise we plot all the'
42 print ' times except the one specified here.'
epoger@google.com5b2e01c2012-06-25 20:29:04 +000043 print '-l <title> title to use for the output graph'
bensong@google.com8ccfa552012-08-17 21:42:14 +000044 print '-m <representation> representation of bench value.'
45 print ' See _ListAlgorithm class in bench_util.py.'
borenet@google.com5dc06782013-03-12 17:16:07 +000046 print '-o <path> path to which to write output.'
epoger@google.com5b2e01c2012-06-25 20:29:04 +000047 print '-r <revision>[:<revision>] the revisions to show.'
48 print ' Negative <revision> is taken as offset from most recent revision.'
49 print '-s <setting>[=<value>] a setting to show (alpha, scalar, etc).'
50 print '-t <time> the time to show (w, c, g, etc).'
bungeman@google.com85669f92011-06-17 13:58:14 +000051 print '-x <int> the desired width of the svg.'
52 print '-y <int> the desired height of the svg.'
53 print '--default-setting <setting>[=<value>] setting for those without.'
54
55
56class Label:
57 """The information in a label.
58
59 (str, str, str, str, {str:str})"""
60 def __init__(self, bench, config, time_type, settings):
61 self.bench = bench
62 self.config = config
63 self.time_type = time_type
64 self.settings = settings
65
66 def __repr__(self):
67 return "Label(%s, %s, %s, %s)" % (
68 str(self.bench),
69 str(self.config),
70 str(self.time_type),
71 str(self.settings),
72 )
73
74 def __str__(self):
75 return "%s_%s_%s_%s" % (
76 str(self.bench),
77 str(self.config),
78 str(self.time_type),
79 str(self.settings),
80 )
81
82 def __eq__(self, other):
83 return (self.bench == other.bench and
84 self.config == other.config and
85 self.time_type == other.time_type and
86 self.settings == other.settings)
87
88 def __hash__(self):
89 return (hash(self.bench) ^
90 hash(self.config) ^
91 hash(self.time_type) ^
92 hash(frozenset(self.settings.iteritems())))
93
epoger@google.com37260002011-08-08 20:27:04 +000094def get_latest_revision(directory):
95 """Returns the latest revision number found within this directory.
96 """
97 latest_revision_found = -1
98 for bench_file in os.listdir(directory):
99 file_name_match = re.match('bench_r(\d+)_(\S+)', bench_file)
100 if (file_name_match is None):
101 continue
102 revision = int(file_name_match.group(1))
103 if revision > latest_revision_found:
104 latest_revision_found = revision
105 if latest_revision_found < 0:
106 return None
107 else:
108 return latest_revision_found
109
bensong@google.com87348162012-08-15 17:31:46 +0000110def parse_dir(directory, default_settings, oldest_revision, newest_revision,
111 rep):
bungeman@google.com85669f92011-06-17 13:58:14 +0000112 """Parses bench data from files like bench_r<revision>_<scalar>.
113
114 (str, {str, str}, Number, Number) -> {int:[BenchDataPoints]}"""
115 revision_data_points = {} # {revision : [BenchDataPoints]}
epoger@google.come9b31fa2013-02-14 20:13:32 +0000116 file_list = os.listdir(directory)
117 file_list.sort()
118 for bench_file in file_list:
bungeman@google.com85669f92011-06-17 13:58:14 +0000119 file_name_match = re.match('bench_r(\d+)_(\S+)', bench_file)
120 if (file_name_match is None):
121 continue
epoger@google.com3d8cd172012-05-11 18:26:16 +0000122
bungeman@google.com85669f92011-06-17 13:58:14 +0000123 revision = int(file_name_match.group(1))
124 scalar_type = file_name_match.group(2)
epoger@google.com3d8cd172012-05-11 18:26:16 +0000125
bungeman@google.com85669f92011-06-17 13:58:14 +0000126 if (revision < oldest_revision or revision > newest_revision):
127 continue
epoger@google.com3d8cd172012-05-11 18:26:16 +0000128
bungeman@google.com85669f92011-06-17 13:58:14 +0000129 file_handle = open(directory + '/' + bench_file, 'r')
epoger@google.com3d8cd172012-05-11 18:26:16 +0000130
bungeman@google.com85669f92011-06-17 13:58:14 +0000131 if (revision not in revision_data_points):
132 revision_data_points[revision] = []
133 default_settings['scalar'] = scalar_type
134 revision_data_points[revision].extend(
bensong@google.com87348162012-08-15 17:31:46 +0000135 bench_util.parse(default_settings, file_handle, rep))
bungeman@google.com85669f92011-06-17 13:58:14 +0000136 file_handle.close()
137 return revision_data_points
138
epoger@google.com3d8cd172012-05-11 18:26:16 +0000139def add_to_revision_data_points(new_point, revision, revision_data_points):
140 """Add new_point to set of revision_data_points we are building up.
141 """
142 if (revision not in revision_data_points):
143 revision_data_points[revision] = []
144 revision_data_points[revision].append(new_point)
145
146def filter_data_points(unfiltered_revision_data_points):
147 """Filter out any data points that are utterly bogus.
148
149 Returns (allowed_revision_data_points, ignored_revision_data_points):
150 allowed_revision_data_points: points that survived the filter
151 ignored_revision_data_points: points that did NOT survive the filter
152 """
153 allowed_revision_data_points = {} # {revision : [BenchDataPoints]}
154 ignored_revision_data_points = {} # {revision : [BenchDataPoints]}
155 revisions = unfiltered_revision_data_points.keys()
156 revisions.sort()
157 for revision in revisions:
158 for point in unfiltered_revision_data_points[revision]:
159 if point.time < MIN_REASONABLE_TIME or point.time > MAX_REASONABLE_TIME:
160 add_to_revision_data_points(point, revision, ignored_revision_data_points)
161 else:
162 add_to_revision_data_points(point, revision, allowed_revision_data_points)
163 return (allowed_revision_data_points, ignored_revision_data_points)
164
epoger@google.com1513f6e2012-06-27 13:38:37 +0000165def get_abs_path(relative_path):
166 """My own implementation of os.path.abspath() that better handles paths
167 which approach Window's 260-character limit.
168 See https://code.google.com/p/skia/issues/detail?id=674
169
170 This implementation adds path components one at a time, resolving the
171 absolute path each time, to take advantage of any chdirs into outer
172 directories that will shorten the total path length.
173
174 TODO: share a single implementation with upload_to_bucket.py, instead
175 of pasting this same code into both files."""
176 if os.path.isabs(relative_path):
177 return relative_path
178 path_parts = relative_path.split(os.sep)
179 abs_path = os.path.abspath('.')
180 for path_part in path_parts:
181 abs_path = os.path.abspath(os.path.join(abs_path, path_part))
182 return abs_path
183
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000184def redirect_stdout(output_path):
185 """Redirect all following stdout to a file.
186
187 You may be asking yourself, why redirect stdout within Python rather than
188 redirecting the script's output in the calling shell?
189 The answer lies in https://code.google.com/p/skia/issues/detail?id=674
190 ('buildbot: windows GenerateBenchGraphs step fails due to filename length'):
191 On Windows, we need to generate the absolute path within Python to avoid
192 the operating system's 260-character pathname limit, including chdirs."""
epoger@google.com1513f6e2012-06-27 13:38:37 +0000193 abs_path = get_abs_path(output_path)
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000194 sys.stdout = open(abs_path, 'w')
195
bungeman@google.com85669f92011-06-17 13:58:14 +0000196def create_lines(revision_data_points, settings
bensong@google.com8ccfa552012-08-17 21:42:14 +0000197 , bench_of_interest, config_of_interest, time_of_interest
198 , time_to_ignore):
epoger@google.com2459a392013-02-14 18:58:05 +0000199 """Convert revision data into a dictionary of line data.
bungeman@google.com85669f92011-06-17 13:58:14 +0000200
bensong@google.com848fa2b2013-03-07 17:12:43 +0000201 Args:
202 revision_data_points: a dictionary with integer keys (revision #) and a
203 list of bench data points as values
204 settings: a dictionary of setting names to value
205 bench_of_interest: optional filter parameters: which bench type is of
206 interest. If None, process them all.
207 config_of_interest: optional filter parameters: which config type is of
208 interest. If None, process them all.
209 time_of_interest: optional filter parameters: which timer type is of
210 interest. If None, process them all.
211 time_to_ignore: optional timer type to ignore
212
213 Returns:
214 a dictionary of this form:
215 keys = Label objects
216 values = a list of (x, y) tuples sorted such that x values increase
217 monotonically
218 """
bungeman@google.com85669f92011-06-17 13:58:14 +0000219 revisions = revision_data_points.keys()
220 revisions.sort()
221 lines = {} # {Label:[(x,y)] | x[n] <= x[n+1]}
222 for revision in revisions:
223 for point in revision_data_points[revision]:
224 if (bench_of_interest is not None and
225 not bench_of_interest == point.bench):
226 continue
227
228 if (config_of_interest is not None and
229 not config_of_interest == point.config):
230 continue
231
232 if (time_of_interest is not None and
233 not time_of_interest == point.time_type):
234 continue
bensong@google.com8ccfa552012-08-17 21:42:14 +0000235 elif (time_to_ignore is not None and
236 time_to_ignore == point.time_type):
237 continue
bungeman@google.com85669f92011-06-17 13:58:14 +0000238
239 skip = False
240 for key, value in settings.items():
241 if key in point.settings and point.settings[key] != value:
242 skip = True
243 break
244 if skip:
245 continue
246
247 line_name = Label(point.bench
248 , point.config
249 , point.time_type
250 , point.settings)
251
252 if line_name not in lines:
253 lines[line_name] = []
254
255 lines[line_name].append((revision, point.time))
256
257 return lines
258
259def bounds(lines):
260 """Finds the bounding rectangle for the lines.
261
262 {Label:[(x,y)]} -> ((min_x, min_y),(max_x,max_y))"""
263 min_x = bench_util.Max
264 min_y = bench_util.Max
265 max_x = bench_util.Min
266 max_y = bench_util.Min
267
268 for line in lines.itervalues():
269 for x, y in line:
270 min_x = min(min_x, x)
271 min_y = min(min_y, y)
272 max_x = max(max_x, x)
273 max_y = max(max_y, y)
274
275 return ((min_x, min_y), (max_x, max_y))
276
277def create_regressions(lines, start_x, end_x):
278 """Creates regression data from line segments.
279
280 ({Label:[(x,y)] | [n].x <= [n+1].x}, Number, Number)
281 -> {Label:LinearRegression}"""
282 regressions = {} # {Label : LinearRegression}
283
284 for label, line in lines.iteritems():
285 regression_line = [p for p in line if start_x <= p[0] <= end_x]
286
287 if (len(regression_line) < 2):
288 continue
289 regression = bench_util.LinearRegression(regression_line)
290 regressions[label] = regression
291
292 return regressions
293
294def bounds_slope(regressions):
295 """Finds the extreme up and down slopes of a set of linear regressions.
296
297 ({Label:LinearRegression}) -> (max_up_slope, min_down_slope)"""
298 max_up_slope = 0
299 min_down_slope = 0
300 for regression in regressions.itervalues():
301 min_slope = regression.find_min_slope()
302 max_up_slope = max(max_up_slope, min_slope)
303 min_down_slope = min(min_down_slope, min_slope)
304
305 return (max_up_slope, min_down_slope)
306
307def main():
308 """Parses command line and writes output."""
309
310 try:
311 opts, _ = getopt.getopt(sys.argv[1:]
bensong@google.com848fa2b2013-03-07 17:12:43 +0000312 , "a:b:c:d:e:f:i:l:m:o:r:s:t:x:y:"
bungeman@google.com85669f92011-06-17 13:58:14 +0000313 , "default-setting=")
314 except getopt.GetoptError, err:
315 print str(err)
316 usage()
317 sys.exit(2)
318
319 directory = None
320 config_of_interest = None
321 bench_of_interest = None
322 time_of_interest = None
bensong@google.com8ccfa552012-08-17 21:42:14 +0000323 time_to_ignore = None
borenet@google.com5dc06782013-03-12 17:16:07 +0000324 output_path = None
bensong@google.comad0c5d22012-09-13 21:08:52 +0000325 bench_expectations = {}
bensong@google.com848fa2b2013-03-07 17:12:43 +0000326 appengine_url = None # used for adding data to appengine datastore
bensong@google.comb6204b12012-08-16 20:49:28 +0000327 rep = None # bench representation algorithm
epoger@google.com37260002011-08-08 20:27:04 +0000328 revision_range = '0:'
329 regression_range = '0:'
330 latest_revision = None
bungeman@google.com85669f92011-06-17 13:58:14 +0000331 requested_height = None
332 requested_width = None
epoger@google.com37260002011-08-08 20:27:04 +0000333 title = 'Bench graph'
bungeman@google.com85669f92011-06-17 13:58:14 +0000334 settings = {}
335 default_settings = {}
epoger@google.com37260002011-08-08 20:27:04 +0000336
337 def parse_range(range):
338 """Takes '<old>[:<new>]' as a string and returns (old, new).
339 Any revision numbers that are dependent on the latest revision number
340 will be filled in based on latest_revision.
341 """
342 old, _, new = range.partition(":")
343 old = int(old)
344 if old < 0:
345 old += latest_revision;
bungeman@google.com85669f92011-06-17 13:58:14 +0000346 if not new:
epoger@google.com37260002011-08-08 20:27:04 +0000347 new = latest_revision;
348 new = int(new)
349 if new < 0:
350 new += latest_revision;
351 return (old, new)
352
bungeman@google.com85669f92011-06-17 13:58:14 +0000353 def add_setting(settings, setting):
354 """Takes <key>[=<value>] adds {key:value} or {key:True} to settings."""
355 name, _, value = setting.partition('=')
356 if not value:
357 settings[name] = True
358 else:
359 settings[name] = value
bensong@google.comad0c5d22012-09-13 21:08:52 +0000360
361 def read_expectations(expectations, filename):
362 """Reads expectations data from file and put in expectations dict."""
363 for expectation in open(filename).readlines():
364 elements = expectation.strip().split(',')
365 if not elements[0] or elements[0].startswith('#'):
366 continue
367 if len(elements) != 5:
368 raise Exception("Invalid expectation line format: %s" %
369 expectation)
370 bench_entry = elements[0] + ',' + elements[1]
371 if bench_entry in expectations:
372 raise Exception("Dup entries for bench expectation %s" %
373 bench_entry)
374 # [<Bench_BmpConfig_TimeType>,<Platform-Alg>] -> (LB, UB)
375 expectations[bench_entry] = (float(elements[-2]),
376 float(elements[-1]))
377
378 def check_expectations(lines, expectations, newest_revision, key_suffix):
379 """Check if there are benches in latest rev outside expected range."""
380 exceptions = []
381 for line in lines:
382 line_str = str(line)
383 bench_platform_key = (line_str[ : line_str.find('_{')] + ',' +
384 key_suffix)
385 this_revision, this_bench_value = lines[line][-1]
386 if (this_revision != newest_revision or
387 bench_platform_key not in expectations):
388 # Skip benches without value for latest revision.
389 continue
390 this_min, this_max = expectations[bench_platform_key]
391 if this_bench_value < this_min or this_bench_value > this_max:
392 exceptions.append('Bench %s value %s out of range [%s, %s].' %
393 (bench_platform_key, this_bench_value, this_min, this_max))
394 if exceptions:
395 raise Exception('Bench values out of range:\n' +
396 '\n'.join(exceptions))
397
bensong@google.com848fa2b2013-03-07 17:12:43 +0000398 def write_to_appengine(line_data_dict, url, newest_revision, bot):
399 """Writes latest bench values to appengine datastore.
400 line_data_dict: dictionary from create_lines.
401 url: the appengine url used to send bench values to write
402 newest_revision: the latest revision that this script reads
403 bot: the bot platform the bench is run on
404 """
bensong@google.comae6f47e2013-04-08 14:57:40 +0000405 config_data_dic = {}
bensong@google.com848fa2b2013-03-07 17:12:43 +0000406 for label in line_data_dict.iterkeys():
407 if not label.bench.endswith('.skp') or label.time_type:
408 # filter out non-picture and non-walltime benches
409 continue
410 config = label.config
411 rev, val = line_data_dict[label][-1]
412 # This assumes that newest_revision is >= the revision of the last
413 # data point we have for each line.
414 if rev != newest_revision:
415 continue
bensong@google.comae6f47e2013-04-08 14:57:40 +0000416 if config not in config_data_dic:
417 config_data_dic[config] = []
418 config_data_dic[config].append(label.bench.replace('.skp', '') +
419 ':%.2f' % val)
420 for config in config_data_dic:
421 if config_data_dic[config]:
422 data = {'master': 'Skia', 'bot': bot, 'test': config,
423 'revision': newest_revision,
424 'benches': ','.join(config_data_dic[config])}
425 req = urllib2.Request(appengine_url,
426 urllib.urlencode({'data': json.dumps(data)}))
427 try:
428 urllib2.urlopen(req)
429 except urllib2.HTTPError, e:
430 sys.stderr.write("HTTPError for JSON data %s: %s\n" % (
431 data, e))
432 except urllib2.URLError, e:
433 sys.stderr.write("URLError for JSON data %s: %s\n" % (
434 data, e))
435 except httplib.HTTPException, e:
436 sys.stderr.write("HTTPException for JSON data %s: %s\n" % (
437 data, e))
bensong@google.com848fa2b2013-03-07 17:12:43 +0000438
bungeman@google.com85669f92011-06-17 13:58:14 +0000439 try:
440 for option, value in opts:
bensong@google.com848fa2b2013-03-07 17:12:43 +0000441 if option == "-a":
442 appengine_url = value
443 elif option == "-b":
bungeman@google.com85669f92011-06-17 13:58:14 +0000444 bench_of_interest = value
445 elif option == "-c":
446 config_of_interest = value
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000447 elif option == "-d":
448 directory = value
bensong@google.comad0c5d22012-09-13 21:08:52 +0000449 elif option == "-e":
450 read_expectations(bench_expectations, value)
bungeman@google.com85669f92011-06-17 13:58:14 +0000451 elif option == "-f":
epoger@google.com37260002011-08-08 20:27:04 +0000452 regression_range = value
bensong@google.com8ccfa552012-08-17 21:42:14 +0000453 elif option == "-i":
454 time_to_ignore = value
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000455 elif option == "-l":
456 title = value
bensong@google.com87348162012-08-15 17:31:46 +0000457 elif option == "-m":
458 rep = value
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000459 elif option == "-o":
borenet@google.com5dc06782013-03-12 17:16:07 +0000460 output_path = value
461 redirect_stdout(output_path)
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000462 elif option == "-r":
463 revision_range = value
464 elif option == "-s":
465 add_setting(settings, value)
466 elif option == "-t":
467 time_of_interest = value
bungeman@google.com85669f92011-06-17 13:58:14 +0000468 elif option == "-x":
469 requested_width = int(value)
470 elif option == "-y":
471 requested_height = int(value)
472 elif option == "--default-setting":
473 add_setting(default_settings, value)
474 else:
475 usage()
476 assert False, "unhandled option"
477 except ValueError:
478 usage()
479 sys.exit(2)
epoger@google.comc71174d2011-08-08 17:19:23 +0000480
bungeman@google.com85669f92011-06-17 13:58:14 +0000481 if directory is None:
482 usage()
483 sys.exit(2)
epoger@google.comc71174d2011-08-08 17:19:23 +0000484
borenet@google.com5dc06782013-03-12 17:16:07 +0000485 if not output_path:
486 print 'Warning: No output path provided. No graphs will be written.'
487
bensong@google.com8ccfa552012-08-17 21:42:14 +0000488 if time_of_interest:
489 time_to_ignore = None
490
bensong@google.comad0c5d22012-09-13 21:08:52 +0000491 # The title flag (-l) provided in buildbot slave is in the format
492 # Bench_Performance_for_Skia_<platform>, and we want to extract <platform>
493 # for use in platform_and_alg to track matching benches later. If title flag
494 # is not in this format, there may be no matching benches in the file
495 # provided by the expectation_file flag (-e).
bensong@google.com848fa2b2013-03-07 17:12:43 +0000496 bot = title # To store the platform as bot name
bensong@google.comad0c5d22012-09-13 21:08:52 +0000497 platform_and_alg = title
498 if platform_and_alg.startswith(TITLE_PREAMBLE):
bensong@google.com848fa2b2013-03-07 17:12:43 +0000499 bot = platform_and_alg[TITLE_PREAMBLE_LENGTH:]
500 platform_and_alg = bot + '-' + rep
bensong@google.com8c1de762012-08-15 18:27:38 +0000501 title += ' [representation: %s]' % rep
502
epoger@google.com37260002011-08-08 20:27:04 +0000503 latest_revision = get_latest_revision(directory)
504 oldest_revision, newest_revision = parse_range(revision_range)
505 oldest_regression, newest_regression = parse_range(regression_range)
506
epoger@google.com3d8cd172012-05-11 18:26:16 +0000507 unfiltered_revision_data_points = parse_dir(directory
bungeman@google.com85669f92011-06-17 13:58:14 +0000508 , default_settings
509 , oldest_revision
bensong@google.com87348162012-08-15 17:31:46 +0000510 , newest_revision
511 , rep)
epoger@google.comc71174d2011-08-08 17:19:23 +0000512
epoger@google.com3d8cd172012-05-11 18:26:16 +0000513 # Filter out any data points that are utterly bogus... make sure to report
514 # that we did so later!
515 (allowed_revision_data_points, ignored_revision_data_points) = filter_data_points(
516 unfiltered_revision_data_points)
517
epoger@google.comc71174d2011-08-08 17:19:23 +0000518 # Update oldest_revision and newest_revision based on the data we could find
epoger@google.com3d8cd172012-05-11 18:26:16 +0000519 all_revision_numbers = allowed_revision_data_points.keys()
epoger@google.comc71174d2011-08-08 17:19:23 +0000520 oldest_revision = min(all_revision_numbers)
521 newest_revision = max(all_revision_numbers)
522
epoger@google.com3d8cd172012-05-11 18:26:16 +0000523 lines = create_lines(allowed_revision_data_points
bungeman@google.com85669f92011-06-17 13:58:14 +0000524 , settings
525 , bench_of_interest
526 , config_of_interest
bensong@google.com8ccfa552012-08-17 21:42:14 +0000527 , time_of_interest
528 , time_to_ignore)
epoger@google.comc71174d2011-08-08 17:19:23 +0000529
bungeman@google.com85669f92011-06-17 13:58:14 +0000530 regressions = create_regressions(lines
531 , oldest_regression
532 , newest_regression)
epoger@google.comc71174d2011-08-08 17:19:23 +0000533
borenet@google.com5dc06782013-03-12 17:16:07 +0000534 if output_path:
535 output_xhtml(lines, oldest_revision, newest_revision,
536 ignored_revision_data_points, regressions, requested_width,
537 requested_height, title)
bungeman@google.com85669f92011-06-17 13:58:14 +0000538
bensong@google.com848fa2b2013-03-07 17:12:43 +0000539 if appengine_url:
540 write_to_appengine(lines, appengine_url, newest_revision, bot)
541
borenet@google.com5dc06782013-03-12 17:16:07 +0000542 if bench_expectations:
543 check_expectations(lines, bench_expectations, newest_revision,
544 platform_and_alg)
bensong@google.comad0c5d22012-09-13 21:08:52 +0000545
bungeman@google.com85669f92011-06-17 13:58:14 +0000546def qa(out):
547 """Stringify input and quote as an xml attribute."""
548 return xml.sax.saxutils.quoteattr(str(out))
549def qe(out):
550 """Stringify input and escape as xml data."""
551 return xml.sax.saxutils.escape(str(out))
552
553def create_select(qualifier, lines, select_id=None):
554 """Output select with options showing lines which qualifier maps to it.
555
556 ((Label) -> str, {Label:_}, str?) -> _"""
557 options = {} #{ option : [Label]}
558 for label in lines.keys():
559 option = qualifier(label)
560 if (option not in options):
561 options[option] = []
562 options[option].append(label)
563 option_list = list(options.keys())
564 option_list.sort()
565 print '<select class="lines"',
566 if select_id is not None:
567 print 'id=%s' % qa(select_id)
568 print 'multiple="true" size="10" onchange="updateSvg();">'
569 for option in option_list:
570 print '<option value=' + qa('[' +
571 reduce(lambda x,y:x+json.dumps(str(y))+',',options[option],"")[0:-1]
572 + ']') + '>'+qe(option)+'</option>'
573 print '</select>'
574
epoger@google.com3d8cd172012-05-11 18:26:16 +0000575def output_ignored_data_points_warning(ignored_revision_data_points):
576 """Write description of ignored_revision_data_points to stdout as xhtml.
577 """
578 num_ignored_points = 0
579 description = ''
580 revisions = ignored_revision_data_points.keys()
581 if revisions:
582 revisions.sort()
583 revisions.reverse()
584 for revision in revisions:
585 num_ignored_points += len(ignored_revision_data_points[revision])
586 points_at_this_revision = []
587 for point in ignored_revision_data_points[revision]:
588 points_at_this_revision.append(point.bench)
589 points_at_this_revision.sort()
590 description += 'r%d: %s\n' % (revision, points_at_this_revision)
591 if num_ignored_points == 0:
592 print 'Did not discard any data points; all were within the range [%d-%d]' % (
593 MIN_REASONABLE_TIME, MAX_REASONABLE_TIME)
594 else:
595 print '<table width="100%" bgcolor="ff0000"><tr><td align="center">'
596 print 'Discarded %d data points outside of range [%d-%d]' % (
597 num_ignored_points, MIN_REASONABLE_TIME, MAX_REASONABLE_TIME)
598 print '</td></tr><tr><td width="100%" align="center">'
599 print ('<textarea rows="4" style="width:97%" readonly="true" wrap="off">'
600 + qe(description) + '</textarea>')
601 print '</td></tr></table>'
602
603def output_xhtml(lines, oldest_revision, newest_revision, ignored_revision_data_points,
epoger@google.com37260002011-08-08 20:27:04 +0000604 regressions, requested_width, requested_height, title):
bungeman@google.com85669f92011-06-17 13:58:14 +0000605 """Outputs an svg/xhtml view of the data."""
606 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"',
607 print '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
608 print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">'
609 print '<head>'
epoger@google.com3d8cd172012-05-11 18:26:16 +0000610 print '<title>%s</title>' % qe(title)
bungeman@google.com85669f92011-06-17 13:58:14 +0000611 print '</head>'
612 print '<body>'
613
614 output_svg(lines, regressions, requested_width, requested_height)
epoger@google.com3d8cd172012-05-11 18:26:16 +0000615
bungeman@google.com85669f92011-06-17 13:58:14 +0000616 #output the manipulation controls
617 print """
618<script type="text/javascript">//<![CDATA[
619 function getElementsByClass(node, searchClass, tag) {
620 var classElements = new Array();
621 var elements = node.getElementsByTagName(tag);
622 var pattern = new RegExp("^|\\s"+searchClass+"\\s|$");
623 for (var i = 0, elementsFound = 0; i < elements.length; ++i) {
624 if (pattern.test(elements[i].className)) {
625 classElements[elementsFound] = elements[i];
626 ++elementsFound;
627 }
628 }
629 return classElements;
630 }
631 function getAllLines() {
632 var selectElem = document.getElementById('benchSelect');
633 var linesObj = {};
634 for (var i = 0; i < selectElem.options.length; ++i) {
635 var lines = JSON.parse(selectElem.options[i].value);
636 for (var j = 0; j < lines.length; ++j) {
637 linesObj[lines[j]] = true;
638 }
639 }
640 return linesObj;
641 }
642 function getOptions(selectElem) {
643 var linesSelectedObj = {};
644 for (var i = 0; i < selectElem.options.length; ++i) {
645 if (!selectElem.options[i].selected) continue;
646
647 var linesSelected = JSON.parse(selectElem.options[i].value);
648 for (var j = 0; j < linesSelected.length; ++j) {
649 linesSelectedObj[linesSelected[j]] = true;
650 }
651 }
652 return linesSelectedObj;
653 }
654 function objectEmpty(obj) {
655 for (var p in obj) {
656 return false;
657 }
658 return true;
659 }
660 function markSelectedLines(selectElem, allLines) {
661 var linesSelected = getOptions(selectElem);
662 if (!objectEmpty(linesSelected)) {
663 for (var line in allLines) {
664 allLines[line] &= (linesSelected[line] == true);
665 }
666 }
667 }
668 function updateSvg() {
669 var allLines = getAllLines();
670
671 var selects = getElementsByClass(document, 'lines', 'select');
672 for (var i = 0; i < selects.length; ++i) {
673 markSelectedLines(selects[i], allLines);
674 }
675
676 for (var line in allLines) {
677 var svgLine = document.getElementById(line);
678 var display = (allLines[line] ? 'inline' : 'none');
679 svgLine.setAttributeNS(null,'display', display);
680 }
681 }
682
683 function mark(markerId) {
684 for (var line in getAllLines()) {
685 var svgLineGroup = document.getElementById(line);
686 var display = svgLineGroup.getAttributeNS(null,'display');
687 if (display == null || display == "" || display != "none") {
688 var svgLine = document.getElementById(line+'_line');
689 if (markerId == null) {
690 svgLine.removeAttributeNS(null,'marker-mid');
691 } else {
692 svgLine.setAttributeNS(null,'marker-mid', markerId);
693 }
694 }
695 }
696 }
697//]]></script>"""
epoger@google.comc71174d2011-08-08 17:19:23 +0000698
bungeman@google.com85669f92011-06-17 13:58:14 +0000699 all_settings = {}
700 variant_settings = set()
701 for label in lines.keys():
702 for key, value in label.settings.items():
703 if key not in all_settings:
704 all_settings[key] = value
705 elif all_settings[key] != value:
706 variant_settings.add(key)
epoger@google.comc71174d2011-08-08 17:19:23 +0000707
bungeman@google.com752acc72012-09-12 19:34:17 +0000708 print '<table border="0" width="%s">' % requested_width
709 #output column headers
710 print """
711<tr valign="top"><td width="50%">
712<table border="0" width="100%">
713<tr><td align="center"><table border="0">
714<form>
715<tr valign="bottom" align="center">
716<td width="1">Bench&nbsp;Type</td>
717<td width="1">Bitmap Config</td>
718<td width="1">Timer&nbsp;Type (Cpu/Gpu/wall)</td>
719"""
720
bungeman@google.com85669f92011-06-17 13:58:14 +0000721 for k in variant_settings:
bungeman@google.com752acc72012-09-12 19:34:17 +0000722 print '<td width="1">%s</td>' % qe(k)
723
724 print '<td width="1"><!--buttons--></td></tr>'
725
726 #output column contents
727 print '<tr valign="top" align="center">'
728 print '<td width="1">'
729 create_select(lambda l: l.bench, lines, 'benchSelect')
730 print '</td><td width="1">'
731 create_select(lambda l: l.config, lines)
732 print '</td><td width="1">'
733 create_select(lambda l: l.time_type, lines)
734
735 for k in variant_settings:
736 print '</td><td width="1">'
737 create_select(lambda l: l.settings.get(k, " "), lines)
epoger@google.comc71174d2011-08-08 17:19:23 +0000738
739 print '</td><td width="1"><button type="button"',
bungeman@google.com85669f92011-06-17 13:58:14 +0000740 print 'onclick=%s' % qa("mark('url(#circleMark)'); return false;"),
epoger@google.comc71174d2011-08-08 17:19:23 +0000741 print '>Mark Points</button>'
742 print '<button type="button" onclick="mark(null);">Clear Points</button>'
epoger@google.com3d8cd172012-05-11 18:26:16 +0000743 print '</td>'
epoger@google.comc71174d2011-08-08 17:19:23 +0000744 print """
epoger@google.com3d8cd172012-05-11 18:26:16 +0000745</tr>
746</form>
747</table></td></tr>
748<tr><td align="center">
749<hr />
750"""
751
752 output_ignored_data_points_warning(ignored_revision_data_points)
753 print '</td></tr></table>'
754 print '</td><td width="2%"><!--gutter--></td>'
755
756 print '<td><table border="0">'
757 print '<tr><td align="center">%s<br></br>revisions r%s - r%s</td></tr>' % (
758 qe(title),
759 bench_util.CreateRevisionLink(oldest_revision),
760 bench_util.CreateRevisionLink(newest_revision))
761 print """
762<tr><td align="left">
epoger@google.comc71174d2011-08-08 17:19:23 +0000763<p>Brighter red indicates tests that have gotten worse; brighter green
764indicates tests that have gotten better.</p>
765<p>To highlight individual tests, hold down CONTROL and mouse over
766graph lines.</p>
767<p>To highlight revision numbers, hold down SHIFT and mouse over
768the graph area.</p>
769<p>To only show certain tests on the graph, select any combination of
770tests in the selectors at left. (To show all, select all.)</p>
771<p>Use buttons at left to mark/clear points on the lines for selected
772benchmarks.</p>
epoger@google.com3d8cd172012-05-11 18:26:16 +0000773</td></tr>
774</table>
775
epoger@google.comc71174d2011-08-08 17:19:23 +0000776</td>
777</tr>
epoger@google.comc71174d2011-08-08 17:19:23 +0000778</table>
779</body>
780</html>"""
bungeman@google.com85669f92011-06-17 13:58:14 +0000781
782def compute_size(requested_width, requested_height, rev_width, time_height):
783 """Converts potentially empty requested size into a concrete size.
784
785 (Number?, Number?) -> (Number, Number)"""
786 pic_width = 0
787 pic_height = 0
788 if (requested_width is not None and requested_height is not None):
789 pic_height = requested_height
790 pic_width = requested_width
791
792 elif (requested_width is not None):
793 pic_width = requested_width
794 pic_height = pic_width * (float(time_height) / rev_width)
795
796 elif (requested_height is not None):
797 pic_height = requested_height
798 pic_width = pic_height * (float(rev_width) / time_height)
799
800 else:
801 pic_height = 800
802 pic_width = max(rev_width*3
803 , pic_height * (float(rev_width) / time_height))
804
805 return (pic_width, pic_height)
806
807def output_svg(lines, regressions, requested_width, requested_height):
808 """Outputs an svg view of the data."""
809
810 (global_min_x, _), (global_max_x, global_max_y) = bounds(lines)
811 max_up_slope, min_down_slope = bounds_slope(regressions)
812
813 #output
814 global_min_y = 0
815 x = global_min_x
816 y = global_min_y
817 w = global_max_x - global_min_x
818 h = global_max_y - global_min_y
819 font_size = 16
820 line_width = 2
821
822 pic_width, pic_height = compute_size(requested_width, requested_height
823 , w, h)
824
825 def cw(w1):
826 """Converts a revision difference to display width."""
827 return (pic_width / float(w)) * w1
828 def cx(x):
829 """Converts a revision to a horizontal display position."""
830 return cw(x - global_min_x)
831
832 def ch(h1):
833 """Converts a time difference to a display height."""
834 return -(pic_height / float(h)) * h1
835 def cy(y):
836 """Converts a time to a vertical display position."""
837 return pic_height + ch(y - global_min_y)
838
bensong@google.com74267432012-08-30 18:19:02 +0000839 print '<!--Picture height %.2f corresponds to bench value %.2f.-->' % (
840 pic_height, h)
bungeman@google.com85669f92011-06-17 13:58:14 +0000841 print '<svg',
842 print 'width=%s' % qa(str(pic_width)+'px')
843 print 'height=%s' % qa(str(pic_height)+'px')
844 print 'viewBox="0 0 %s %s"' % (str(pic_width), str(pic_height))
845 print 'onclick=%s' % qa(
846 "var event = arguments[0] || window.event;"
847 " if (event.shiftKey) { highlightRevision(null); }"
848 " if (event.ctrlKey) { highlight(null); }"
849 " return false;")
850 print 'xmlns="http://www.w3.org/2000/svg"'
851 print 'xmlns:xlink="http://www.w3.org/1999/xlink">'
852
853 print """
854<defs>
855 <marker id="circleMark"
856 viewBox="0 0 2 2" refX="1" refY="1"
857 markerUnits="strokeWidth"
858 markerWidth="2" markerHeight="2"
859 orient="0">
860 <circle cx="1" cy="1" r="1"/>
861 </marker>
862</defs>"""
863
864 #output the revisions
865 print """
866<script type="text/javascript">//<![CDATA[
867 var previousRevision;
868 var previousRevisionFill;
869 var previousRevisionStroke
870 function highlightRevision(id) {
871 if (previousRevision == id) return;
epoger@google.comc71174d2011-08-08 17:19:23 +0000872
873 document.getElementById('revision').firstChild.nodeValue = 'r' + id;
874 document.getElementById('rev_link').setAttribute('xlink:href',
875 'http://code.google.com/p/skia/source/detail?r=' + id);
bungeman@google.com85669f92011-06-17 13:58:14 +0000876
877 var preRevision = document.getElementById(previousRevision);
878 if (preRevision) {
879 preRevision.setAttributeNS(null,'fill', previousRevisionFill);
880 preRevision.setAttributeNS(null,'stroke', previousRevisionStroke);
881 }
882
883 var revision = document.getElementById(id);
884 previousRevision = id;
885 if (revision) {
886 previousRevisionFill = revision.getAttributeNS(null,'fill');
887 revision.setAttributeNS(null,'fill','rgb(100%, 95%, 95%)');
888
889 previousRevisionStroke = revision.getAttributeNS(null,'stroke');
890 revision.setAttributeNS(null,'stroke','rgb(100%, 90%, 90%)');
891 }
892 }
893//]]></script>"""
894
895 def print_rect(x, y, w, h, revision):
896 """Outputs a revision rectangle in display space,
897 taking arguments in revision space."""
898 disp_y = cy(y)
899 disp_h = ch(h)
900 if disp_h < 0:
901 disp_y += disp_h
902 disp_h = -disp_h
903
904 print '<rect id=%s x=%s y=%s' % (qa(revision), qa(cx(x)), qa(disp_y),),
905 print 'width=%s height=%s' % (qa(cw(w)), qa(disp_h),),
906 print 'fill="white"',
epoger@google.comc71174d2011-08-08 17:19:23 +0000907 print 'stroke="rgb(98%%,98%%,88%%)" stroke-width=%s' % qa(line_width),
bungeman@google.com85669f92011-06-17 13:58:14 +0000908 print 'onmouseover=%s' % qa(
909 "var event = arguments[0] || window.event;"
910 " if (event.shiftKey) {"
911 " highlightRevision('"+str(revision)+"');"
912 " return false;"
913 " }"),
914 print ' />'
915
916 xes = set()
917 for line in lines.itervalues():
918 for point in line:
919 xes.add(point[0])
920 revisions = list(xes)
921 revisions.sort()
922
923 left = x
924 current_revision = revisions[0]
925 for next_revision in revisions[1:]:
926 width = (((next_revision - current_revision) / 2.0)
927 + (current_revision - left))
928 print_rect(left, y, width, h, current_revision)
929 left += width
930 current_revision = next_revision
931 print_rect(left, y, x+w - left, h, current_revision)
epoger@google.comc71174d2011-08-08 17:19:23 +0000932
bungeman@google.com85669f92011-06-17 13:58:14 +0000933 #output the lines
934 print """
935<script type="text/javascript">//<![CDATA[
936 var previous;
937 var previousColor;
938 var previousOpacity;
939 function highlight(id) {
940 if (previous == id) return;
epoger@google.comc71174d2011-08-08 17:19:23 +0000941
bungeman@google.com85669f92011-06-17 13:58:14 +0000942 document.getElementById('label').firstChild.nodeValue = id;
epoger@google.comc71174d2011-08-08 17:19:23 +0000943
bungeman@google.com85669f92011-06-17 13:58:14 +0000944 var preGroup = document.getElementById(previous);
945 if (preGroup) {
946 var preLine = document.getElementById(previous+'_line');
947 preLine.setAttributeNS(null,'stroke', previousColor);
948 preLine.setAttributeNS(null,'opacity', previousOpacity);
epoger@google.comc71174d2011-08-08 17:19:23 +0000949
bungeman@google.com85669f92011-06-17 13:58:14 +0000950 var preSlope = document.getElementById(previous+'_linear');
951 if (preSlope) {
952 preSlope.setAttributeNS(null,'visibility', 'hidden');
953 }
954 }
epoger@google.comc71174d2011-08-08 17:19:23 +0000955
bungeman@google.com85669f92011-06-17 13:58:14 +0000956 var group = document.getElementById(id);
957 previous = id;
958 if (group) {
959 group.parentNode.appendChild(group);
960
961 var line = document.getElementById(id+'_line');
962 previousColor = line.getAttributeNS(null,'stroke');
963 previousOpacity = line.getAttributeNS(null,'opacity');
964 line.setAttributeNS(null,'stroke', 'blue');
965 line.setAttributeNS(null,'opacity', '1');
966
967 var slope = document.getElementById(id+'_linear');
968 if (slope) {
969 slope.setAttributeNS(null,'visibility', 'visible');
970 }
971 }
972 }
973//]]></script>"""
epoger@google.com2459a392013-02-14 18:58:05 +0000974
975 # Add a new element to each item in the 'lines' list: the label in string
976 # form. Then use that element to sort the list.
977 sorted_lines = []
bungeman@google.com85669f92011-06-17 13:58:14 +0000978 for label, line in lines.items():
epoger@google.com2459a392013-02-14 18:58:05 +0000979 sorted_lines.append([str(label), label, line])
980 sorted_lines.sort()
981
982 for label_as_string, label, line in sorted_lines:
983 print '<g id=%s>' % qa(label_as_string)
bungeman@google.com85669f92011-06-17 13:58:14 +0000984 r = 128
985 g = 128
986 b = 128
987 a = .10
988 if label in regressions:
989 regression = regressions[label]
990 min_slope = regression.find_min_slope()
991 if min_slope < 0:
992 d = max(0, (min_slope / min_down_slope))
993 g += int(d*128)
994 a += d*0.9
995 elif min_slope > 0:
996 d = max(0, (min_slope / max_up_slope))
997 r += int(d*128)
998 a += d*0.9
999
1000 slope = regression.slope
1001 intercept = regression.intercept
1002 min_x = regression.min_x
1003 max_x = regression.max_x
1004 print '<polyline id=%s' % qa(str(label)+'_linear'),
1005 print 'fill="none" stroke="yellow"',
1006 print 'stroke-width=%s' % qa(abs(ch(regression.serror*2))),
1007 print 'opacity="0.5" pointer-events="none" visibility="hidden"',
1008 print 'points="',
1009 print '%s,%s' % (str(cx(min_x)), str(cy(slope*min_x + intercept))),
1010 print '%s,%s' % (str(cx(max_x)), str(cy(slope*max_x + intercept))),
1011 print '"/>'
1012
1013 print '<polyline id=%s' % qa(str(label)+'_line'),
1014 print 'onmouseover=%s' % qa(
1015 "var event = arguments[0] || window.event;"
1016 " if (event.ctrlKey) {"
1017 " highlight('"+str(label).replace("'", "\\'")+"');"
1018 " return false;"
1019 " }"),
1020 print 'fill="none" stroke="rgb(%s,%s,%s)"' % (str(r), str(g), str(b)),
1021 print 'stroke-width=%s' % qa(line_width),
1022 print 'opacity=%s' % qa(a),
1023 print 'points="',
1024 for point in line:
1025 print '%s,%s' % (str(cx(point[0])), str(cy(point[1]))),
1026 print '"/>'
epoger@google.comc71174d2011-08-08 17:19:23 +00001027
bungeman@google.com85669f92011-06-17 13:58:14 +00001028 print '</g>'
epoger@google.comc71174d2011-08-08 17:19:23 +00001029
bungeman@google.com85669f92011-06-17 13:58:14 +00001030 #output the labels
1031 print '<text id="label" x="0" y=%s' % qa(font_size),
1032 print 'font-size=%s> </text>' % qa(font_size)
epoger@google.comc71174d2011-08-08 17:19:23 +00001033
1034 print '<a id="rev_link" xlink:href="" target="_top">'
1035 print '<text id="revision" x="0" y=%s style="' % qa(font_size*2)
1036 print 'font-size: %s; ' % qe(font_size)
1037 print 'stroke: #0000dd; text-decoration: underline; '
1038 print '"> </text></a>'
1039
bungeman@google.com85669f92011-06-17 13:58:14 +00001040 print '</svg>'
epoger@google.comc71174d2011-08-08 17:19:23 +00001041
bungeman@google.com85669f92011-06-17 13:58:14 +00001042if __name__ == "__main__":
1043 main()