blob: 3dd0c706135a1c099a09c3fa4fb17905fc314eee [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
bensong@google.com848fa2b2013-03-07 17:12:43 +000026# Number of data points to send to appengine at once.
27DATA_POINT_BATCHSIZE = 100
28
29def grouper(n, iterable):
30 """Groups list into list of lists for a given size. See itertools doc:
31 http://docs.python.org/2/library/itertools.html#module-itertools
32 """
33 args = [iter(iterable)] * n
34 return [[n for n in t if n] for t in itertools.izip_longest(*args)]
35
36
bungeman@google.com85669f92011-06-17 13:58:14 +000037def usage():
38 """Prints simple usage information."""
bensong@google.com848fa2b2013-03-07 17:12:43 +000039
40 print '-a <url> the url to use for adding bench values to app engine app.'
41 print ' Example: "https://skiadash.appspot.com/add_point".'
42 print ' If not set, will skip this step.'
bungeman@google.com85669f92011-06-17 13:58:14 +000043 print '-b <bench> the bench to show.'
44 print '-c <config> the config to show (GPU, 8888, 565, etc).'
epoger@google.com5b2e01c2012-06-25 20:29:04 +000045 print '-d <dir> a directory containing bench_r<revision>_<scalar> files.'
bensong@google.comad0c5d22012-09-13 21:08:52 +000046 print '-e <file> file containing expected bench values/ranges.'
47 print ' Will raise exception if actual bench values are out of range.'
48 print ' See bench_expectations.txt for data format and examples.'
bungeman@google.com85669f92011-06-17 13:58:14 +000049 print '-f <revision>[:<revision>] the revisions to use for fitting.'
epoger@google.com37260002011-08-08 20:27:04 +000050 print ' Negative <revision> is taken as offset from most recent revision.'
bensong@google.com8ccfa552012-08-17 21:42:14 +000051 print '-i <time> the time to ignore (w, c, g, etc).'
52 print ' The flag is ignored when -t is set; otherwise we plot all the'
53 print ' times except the one specified here.'
epoger@google.com5b2e01c2012-06-25 20:29:04 +000054 print '-l <title> title to use for the output graph'
bensong@google.com8ccfa552012-08-17 21:42:14 +000055 print '-m <representation> representation of bench value.'
56 print ' See _ListAlgorithm class in bench_util.py.'
epoger@google.com5b2e01c2012-06-25 20:29:04 +000057 print '-o <path> path to which to write output; writes to stdout if not specified'
58 print '-r <revision>[:<revision>] the revisions to show.'
59 print ' Negative <revision> is taken as offset from most recent revision.'
60 print '-s <setting>[=<value>] a setting to show (alpha, scalar, etc).'
61 print '-t <time> the time to show (w, c, g, etc).'
bungeman@google.com85669f92011-06-17 13:58:14 +000062 print '-x <int> the desired width of the svg.'
63 print '-y <int> the desired height of the svg.'
64 print '--default-setting <setting>[=<value>] setting for those without.'
65
66
67class Label:
68 """The information in a label.
69
70 (str, str, str, str, {str:str})"""
71 def __init__(self, bench, config, time_type, settings):
72 self.bench = bench
73 self.config = config
74 self.time_type = time_type
75 self.settings = settings
76
77 def __repr__(self):
78 return "Label(%s, %s, %s, %s)" % (
79 str(self.bench),
80 str(self.config),
81 str(self.time_type),
82 str(self.settings),
83 )
84
85 def __str__(self):
86 return "%s_%s_%s_%s" % (
87 str(self.bench),
88 str(self.config),
89 str(self.time_type),
90 str(self.settings),
91 )
92
93 def __eq__(self, other):
94 return (self.bench == other.bench and
95 self.config == other.config and
96 self.time_type == other.time_type and
97 self.settings == other.settings)
98
99 def __hash__(self):
100 return (hash(self.bench) ^
101 hash(self.config) ^
102 hash(self.time_type) ^
103 hash(frozenset(self.settings.iteritems())))
104
epoger@google.com37260002011-08-08 20:27:04 +0000105def get_latest_revision(directory):
106 """Returns the latest revision number found within this directory.
107 """
108 latest_revision_found = -1
109 for bench_file in os.listdir(directory):
110 file_name_match = re.match('bench_r(\d+)_(\S+)', bench_file)
111 if (file_name_match is None):
112 continue
113 revision = int(file_name_match.group(1))
114 if revision > latest_revision_found:
115 latest_revision_found = revision
116 if latest_revision_found < 0:
117 return None
118 else:
119 return latest_revision_found
120
bensong@google.com87348162012-08-15 17:31:46 +0000121def parse_dir(directory, default_settings, oldest_revision, newest_revision,
122 rep):
bungeman@google.com85669f92011-06-17 13:58:14 +0000123 """Parses bench data from files like bench_r<revision>_<scalar>.
124
125 (str, {str, str}, Number, Number) -> {int:[BenchDataPoints]}"""
126 revision_data_points = {} # {revision : [BenchDataPoints]}
epoger@google.come9b31fa2013-02-14 20:13:32 +0000127 file_list = os.listdir(directory)
128 file_list.sort()
129 for bench_file in file_list:
bungeman@google.com85669f92011-06-17 13:58:14 +0000130 file_name_match = re.match('bench_r(\d+)_(\S+)', bench_file)
131 if (file_name_match is None):
132 continue
epoger@google.com3d8cd172012-05-11 18:26:16 +0000133
bungeman@google.com85669f92011-06-17 13:58:14 +0000134 revision = int(file_name_match.group(1))
135 scalar_type = file_name_match.group(2)
epoger@google.com3d8cd172012-05-11 18:26:16 +0000136
bungeman@google.com85669f92011-06-17 13:58:14 +0000137 if (revision < oldest_revision or revision > newest_revision):
138 continue
epoger@google.com3d8cd172012-05-11 18:26:16 +0000139
bungeman@google.com85669f92011-06-17 13:58:14 +0000140 file_handle = open(directory + '/' + bench_file, 'r')
epoger@google.com3d8cd172012-05-11 18:26:16 +0000141
bungeman@google.com85669f92011-06-17 13:58:14 +0000142 if (revision not in revision_data_points):
143 revision_data_points[revision] = []
144 default_settings['scalar'] = scalar_type
145 revision_data_points[revision].extend(
bensong@google.com87348162012-08-15 17:31:46 +0000146 bench_util.parse(default_settings, file_handle, rep))
bungeman@google.com85669f92011-06-17 13:58:14 +0000147 file_handle.close()
148 return revision_data_points
149
epoger@google.com3d8cd172012-05-11 18:26:16 +0000150def add_to_revision_data_points(new_point, revision, revision_data_points):
151 """Add new_point to set of revision_data_points we are building up.
152 """
153 if (revision not in revision_data_points):
154 revision_data_points[revision] = []
155 revision_data_points[revision].append(new_point)
156
157def filter_data_points(unfiltered_revision_data_points):
158 """Filter out any data points that are utterly bogus.
159
160 Returns (allowed_revision_data_points, ignored_revision_data_points):
161 allowed_revision_data_points: points that survived the filter
162 ignored_revision_data_points: points that did NOT survive the filter
163 """
164 allowed_revision_data_points = {} # {revision : [BenchDataPoints]}
165 ignored_revision_data_points = {} # {revision : [BenchDataPoints]}
166 revisions = unfiltered_revision_data_points.keys()
167 revisions.sort()
168 for revision in revisions:
169 for point in unfiltered_revision_data_points[revision]:
170 if point.time < MIN_REASONABLE_TIME or point.time > MAX_REASONABLE_TIME:
171 add_to_revision_data_points(point, revision, ignored_revision_data_points)
172 else:
173 add_to_revision_data_points(point, revision, allowed_revision_data_points)
174 return (allowed_revision_data_points, ignored_revision_data_points)
175
epoger@google.com1513f6e2012-06-27 13:38:37 +0000176def get_abs_path(relative_path):
177 """My own implementation of os.path.abspath() that better handles paths
178 which approach Window's 260-character limit.
179 See https://code.google.com/p/skia/issues/detail?id=674
180
181 This implementation adds path components one at a time, resolving the
182 absolute path each time, to take advantage of any chdirs into outer
183 directories that will shorten the total path length.
184
185 TODO: share a single implementation with upload_to_bucket.py, instead
186 of pasting this same code into both files."""
187 if os.path.isabs(relative_path):
188 return relative_path
189 path_parts = relative_path.split(os.sep)
190 abs_path = os.path.abspath('.')
191 for path_part in path_parts:
192 abs_path = os.path.abspath(os.path.join(abs_path, path_part))
193 return abs_path
194
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000195def redirect_stdout(output_path):
196 """Redirect all following stdout to a file.
197
198 You may be asking yourself, why redirect stdout within Python rather than
199 redirecting the script's output in the calling shell?
200 The answer lies in https://code.google.com/p/skia/issues/detail?id=674
201 ('buildbot: windows GenerateBenchGraphs step fails due to filename length'):
202 On Windows, we need to generate the absolute path within Python to avoid
203 the operating system's 260-character pathname limit, including chdirs."""
epoger@google.com1513f6e2012-06-27 13:38:37 +0000204 abs_path = get_abs_path(output_path)
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000205 sys.stdout = open(abs_path, 'w')
206
bungeman@google.com85669f92011-06-17 13:58:14 +0000207def create_lines(revision_data_points, settings
bensong@google.com8ccfa552012-08-17 21:42:14 +0000208 , bench_of_interest, config_of_interest, time_of_interest
209 , time_to_ignore):
epoger@google.com2459a392013-02-14 18:58:05 +0000210 """Convert revision data into a dictionary of line data.
bungeman@google.com85669f92011-06-17 13:58:14 +0000211
bensong@google.com848fa2b2013-03-07 17:12:43 +0000212 Args:
213 revision_data_points: a dictionary with integer keys (revision #) and a
214 list of bench data points as values
215 settings: a dictionary of setting names to value
216 bench_of_interest: optional filter parameters: which bench type is of
217 interest. If None, process them all.
218 config_of_interest: optional filter parameters: which config type is of
219 interest. If None, process them all.
220 time_of_interest: optional filter parameters: which timer type is of
221 interest. If None, process them all.
222 time_to_ignore: optional timer type to ignore
223
224 Returns:
225 a dictionary of this form:
226 keys = Label objects
227 values = a list of (x, y) tuples sorted such that x values increase
228 monotonically
229 """
bungeman@google.com85669f92011-06-17 13:58:14 +0000230 revisions = revision_data_points.keys()
231 revisions.sort()
232 lines = {} # {Label:[(x,y)] | x[n] <= x[n+1]}
233 for revision in revisions:
234 for point in revision_data_points[revision]:
235 if (bench_of_interest is not None and
236 not bench_of_interest == point.bench):
237 continue
238
239 if (config_of_interest is not None and
240 not config_of_interest == point.config):
241 continue
242
243 if (time_of_interest is not None and
244 not time_of_interest == point.time_type):
245 continue
bensong@google.com8ccfa552012-08-17 21:42:14 +0000246 elif (time_to_ignore is not None and
247 time_to_ignore == point.time_type):
248 continue
bungeman@google.com85669f92011-06-17 13:58:14 +0000249
250 skip = False
251 for key, value in settings.items():
252 if key in point.settings and point.settings[key] != value:
253 skip = True
254 break
255 if skip:
256 continue
257
258 line_name = Label(point.bench
259 , point.config
260 , point.time_type
261 , point.settings)
262
263 if line_name not in lines:
264 lines[line_name] = []
265
266 lines[line_name].append((revision, point.time))
267
268 return lines
269
270def bounds(lines):
271 """Finds the bounding rectangle for the lines.
272
273 {Label:[(x,y)]} -> ((min_x, min_y),(max_x,max_y))"""
274 min_x = bench_util.Max
275 min_y = bench_util.Max
276 max_x = bench_util.Min
277 max_y = bench_util.Min
278
279 for line in lines.itervalues():
280 for x, y in line:
281 min_x = min(min_x, x)
282 min_y = min(min_y, y)
283 max_x = max(max_x, x)
284 max_y = max(max_y, y)
285
286 return ((min_x, min_y), (max_x, max_y))
287
288def create_regressions(lines, start_x, end_x):
289 """Creates regression data from line segments.
290
291 ({Label:[(x,y)] | [n].x <= [n+1].x}, Number, Number)
292 -> {Label:LinearRegression}"""
293 regressions = {} # {Label : LinearRegression}
294
295 for label, line in lines.iteritems():
296 regression_line = [p for p in line if start_x <= p[0] <= end_x]
297
298 if (len(regression_line) < 2):
299 continue
300 regression = bench_util.LinearRegression(regression_line)
301 regressions[label] = regression
302
303 return regressions
304
305def bounds_slope(regressions):
306 """Finds the extreme up and down slopes of a set of linear regressions.
307
308 ({Label:LinearRegression}) -> (max_up_slope, min_down_slope)"""
309 max_up_slope = 0
310 min_down_slope = 0
311 for regression in regressions.itervalues():
312 min_slope = regression.find_min_slope()
313 max_up_slope = max(max_up_slope, min_slope)
314 min_down_slope = min(min_down_slope, min_slope)
315
316 return (max_up_slope, min_down_slope)
317
318def main():
319 """Parses command line and writes output."""
320
321 try:
322 opts, _ = getopt.getopt(sys.argv[1:]
bensong@google.com848fa2b2013-03-07 17:12:43 +0000323 , "a:b:c:d:e:f:i:l:m:o:r:s:t:x:y:"
bungeman@google.com85669f92011-06-17 13:58:14 +0000324 , "default-setting=")
325 except getopt.GetoptError, err:
326 print str(err)
327 usage()
328 sys.exit(2)
329
330 directory = None
331 config_of_interest = None
332 bench_of_interest = None
333 time_of_interest = None
bensong@google.com8ccfa552012-08-17 21:42:14 +0000334 time_to_ignore = None
bensong@google.comad0c5d22012-09-13 21:08:52 +0000335 bench_expectations = {}
bensong@google.com848fa2b2013-03-07 17:12:43 +0000336 appengine_url = None # used for adding data to appengine datastore
bensong@google.comb6204b12012-08-16 20:49:28 +0000337 rep = None # bench representation algorithm
epoger@google.com37260002011-08-08 20:27:04 +0000338 revision_range = '0:'
339 regression_range = '0:'
340 latest_revision = None
bungeman@google.com85669f92011-06-17 13:58:14 +0000341 requested_height = None
342 requested_width = None
epoger@google.com37260002011-08-08 20:27:04 +0000343 title = 'Bench graph'
bungeman@google.com85669f92011-06-17 13:58:14 +0000344 settings = {}
345 default_settings = {}
epoger@google.com37260002011-08-08 20:27:04 +0000346
347 def parse_range(range):
348 """Takes '<old>[:<new>]' as a string and returns (old, new).
349 Any revision numbers that are dependent on the latest revision number
350 will be filled in based on latest_revision.
351 """
352 old, _, new = range.partition(":")
353 old = int(old)
354 if old < 0:
355 old += latest_revision;
bungeman@google.com85669f92011-06-17 13:58:14 +0000356 if not new:
epoger@google.com37260002011-08-08 20:27:04 +0000357 new = latest_revision;
358 new = int(new)
359 if new < 0:
360 new += latest_revision;
361 return (old, new)
362
bungeman@google.com85669f92011-06-17 13:58:14 +0000363 def add_setting(settings, setting):
364 """Takes <key>[=<value>] adds {key:value} or {key:True} to settings."""
365 name, _, value = setting.partition('=')
366 if not value:
367 settings[name] = True
368 else:
369 settings[name] = value
bensong@google.comad0c5d22012-09-13 21:08:52 +0000370
371 def read_expectations(expectations, filename):
372 """Reads expectations data from file and put in expectations dict."""
373 for expectation in open(filename).readlines():
374 elements = expectation.strip().split(',')
375 if not elements[0] or elements[0].startswith('#'):
376 continue
377 if len(elements) != 5:
378 raise Exception("Invalid expectation line format: %s" %
379 expectation)
380 bench_entry = elements[0] + ',' + elements[1]
381 if bench_entry in expectations:
382 raise Exception("Dup entries for bench expectation %s" %
383 bench_entry)
384 # [<Bench_BmpConfig_TimeType>,<Platform-Alg>] -> (LB, UB)
385 expectations[bench_entry] = (float(elements[-2]),
386 float(elements[-1]))
387
388 def check_expectations(lines, expectations, newest_revision, key_suffix):
389 """Check if there are benches in latest rev outside expected range."""
390 exceptions = []
391 for line in lines:
392 line_str = str(line)
393 bench_platform_key = (line_str[ : line_str.find('_{')] + ',' +
394 key_suffix)
395 this_revision, this_bench_value = lines[line][-1]
396 if (this_revision != newest_revision or
397 bench_platform_key not in expectations):
398 # Skip benches without value for latest revision.
399 continue
400 this_min, this_max = expectations[bench_platform_key]
401 if this_bench_value < this_min or this_bench_value > this_max:
402 exceptions.append('Bench %s value %s out of range [%s, %s].' %
403 (bench_platform_key, this_bench_value, this_min, this_max))
404 if exceptions:
405 raise Exception('Bench values out of range:\n' +
406 '\n'.join(exceptions))
407
bensong@google.com848fa2b2013-03-07 17:12:43 +0000408 def write_to_appengine(line_data_dict, url, newest_revision, bot):
409 """Writes latest bench values to appengine datastore.
410 line_data_dict: dictionary from create_lines.
411 url: the appengine url used to send bench values to write
412 newest_revision: the latest revision that this script reads
413 bot: the bot platform the bench is run on
414 """
415 data = []
416 for label in line_data_dict.iterkeys():
417 if not label.bench.endswith('.skp') or label.time_type:
418 # filter out non-picture and non-walltime benches
419 continue
420 config = label.config
421 rev, val = line_data_dict[label][-1]
422 # This assumes that newest_revision is >= the revision of the last
423 # data point we have for each line.
424 if rev != newest_revision:
425 continue
426 data.append({'master': 'Skia', 'bot': bot,
427 'test': config + '/' + label.bench.replace('.skp', ''),
428 'revision': rev, 'value': val, 'error': 0})
429 for curr_data in grouper(DATA_POINT_BATCHSIZE, data):
430 req = urllib2.Request(appengine_url,
431 urllib.urlencode({'data': json.dumps(curr_data)}))
432 try:
433 urllib2.urlopen(req)
434 except urllib2.HTTPError, e:
435 sys.stderr.write("HTTPError for JSON data %s: %s\n" % (
436 data, e))
437 except urllib2.URLError, e:
438 sys.stderr.write("URLError for JSON data %s: %s\n" % (
439 data, e))
440 except httplib.HTTPException, e:
441 sys.stderr.write("HTTPException for JSON data %s: %s\n" % (
442 data, e))
443
bungeman@google.com85669f92011-06-17 13:58:14 +0000444 try:
445 for option, value in opts:
bensong@google.com848fa2b2013-03-07 17:12:43 +0000446 if option == "-a":
447 appengine_url = value
448 elif option == "-b":
bungeman@google.com85669f92011-06-17 13:58:14 +0000449 bench_of_interest = value
450 elif option == "-c":
451 config_of_interest = value
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000452 elif option == "-d":
453 directory = value
bensong@google.comad0c5d22012-09-13 21:08:52 +0000454 elif option == "-e":
455 read_expectations(bench_expectations, value)
bungeman@google.com85669f92011-06-17 13:58:14 +0000456 elif option == "-f":
epoger@google.com37260002011-08-08 20:27:04 +0000457 regression_range = value
bensong@google.com8ccfa552012-08-17 21:42:14 +0000458 elif option == "-i":
459 time_to_ignore = value
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000460 elif option == "-l":
461 title = value
bensong@google.com87348162012-08-15 17:31:46 +0000462 elif option == "-m":
463 rep = value
epoger@google.com5b2e01c2012-06-25 20:29:04 +0000464 elif option == "-o":
465 redirect_stdout(value)
466 elif option == "-r":
467 revision_range = value
468 elif option == "-s":
469 add_setting(settings, value)
470 elif option == "-t":
471 time_of_interest = value
bungeman@google.com85669f92011-06-17 13:58:14 +0000472 elif option == "-x":
473 requested_width = int(value)
474 elif option == "-y":
475 requested_height = int(value)
476 elif option == "--default-setting":
477 add_setting(default_settings, value)
478 else:
479 usage()
480 assert False, "unhandled option"
481 except ValueError:
482 usage()
483 sys.exit(2)
epoger@google.comc71174d2011-08-08 17:19:23 +0000484
bungeman@google.com85669f92011-06-17 13:58:14 +0000485 if directory is None:
486 usage()
487 sys.exit(2)
epoger@google.comc71174d2011-08-08 17:19:23 +0000488
bensong@google.com8ccfa552012-08-17 21:42:14 +0000489 if time_of_interest:
490 time_to_ignore = None
491
bensong@google.comad0c5d22012-09-13 21:08:52 +0000492 # The title flag (-l) provided in buildbot slave is in the format
493 # Bench_Performance_for_Skia_<platform>, and we want to extract <platform>
494 # for use in platform_and_alg to track matching benches later. If title flag
495 # is not in this format, there may be no matching benches in the file
496 # provided by the expectation_file flag (-e).
bensong@google.com848fa2b2013-03-07 17:12:43 +0000497 bot = title # To store the platform as bot name
bensong@google.comad0c5d22012-09-13 21:08:52 +0000498 platform_and_alg = title
499 if platform_and_alg.startswith(TITLE_PREAMBLE):
bensong@google.com848fa2b2013-03-07 17:12:43 +0000500 bot = platform_and_alg[TITLE_PREAMBLE_LENGTH:]
501 platform_and_alg = bot + '-' + rep
bensong@google.com8c1de762012-08-15 18:27:38 +0000502 title += ' [representation: %s]' % rep
503
epoger@google.com37260002011-08-08 20:27:04 +0000504 latest_revision = get_latest_revision(directory)
505 oldest_revision, newest_revision = parse_range(revision_range)
506 oldest_regression, newest_regression = parse_range(regression_range)
507
epoger@google.com3d8cd172012-05-11 18:26:16 +0000508 unfiltered_revision_data_points = parse_dir(directory
bungeman@google.com85669f92011-06-17 13:58:14 +0000509 , default_settings
510 , oldest_revision
bensong@google.com87348162012-08-15 17:31:46 +0000511 , newest_revision
512 , rep)
epoger@google.comc71174d2011-08-08 17:19:23 +0000513
epoger@google.com3d8cd172012-05-11 18:26:16 +0000514 # Filter out any data points that are utterly bogus... make sure to report
515 # that we did so later!
516 (allowed_revision_data_points, ignored_revision_data_points) = filter_data_points(
517 unfiltered_revision_data_points)
518
epoger@google.comc71174d2011-08-08 17:19:23 +0000519 # Update oldest_revision and newest_revision based on the data we could find
epoger@google.com3d8cd172012-05-11 18:26:16 +0000520 all_revision_numbers = allowed_revision_data_points.keys()
epoger@google.comc71174d2011-08-08 17:19:23 +0000521 oldest_revision = min(all_revision_numbers)
522 newest_revision = max(all_revision_numbers)
523
epoger@google.com3d8cd172012-05-11 18:26:16 +0000524 lines = create_lines(allowed_revision_data_points
bungeman@google.com85669f92011-06-17 13:58:14 +0000525 , settings
526 , bench_of_interest
527 , config_of_interest
bensong@google.com8ccfa552012-08-17 21:42:14 +0000528 , time_of_interest
529 , time_to_ignore)
epoger@google.comc71174d2011-08-08 17:19:23 +0000530
bungeman@google.com85669f92011-06-17 13:58:14 +0000531 regressions = create_regressions(lines
532 , oldest_regression
533 , newest_regression)
epoger@google.comc71174d2011-08-08 17:19:23 +0000534
epoger@google.com3d8cd172012-05-11 18:26:16 +0000535 output_xhtml(lines, oldest_revision, newest_revision, ignored_revision_data_points,
epoger@google.com37260002011-08-08 20:27:04 +0000536 regressions, requested_width, requested_height, title)
bungeman@google.com85669f92011-06-17 13:58:14 +0000537
bensong@google.com848fa2b2013-03-07 17:12:43 +0000538 if appengine_url:
539 write_to_appengine(lines, appengine_url, newest_revision, bot)
540
bensong@google.comad0c5d22012-09-13 21:08:52 +0000541 check_expectations(lines, bench_expectations, newest_revision,
542 platform_and_alg)
543
bungeman@google.com85669f92011-06-17 13:58:14 +0000544def qa(out):
545 """Stringify input and quote as an xml attribute."""
546 return xml.sax.saxutils.quoteattr(str(out))
547def qe(out):
548 """Stringify input and escape as xml data."""
549 return xml.sax.saxutils.escape(str(out))
550
551def create_select(qualifier, lines, select_id=None):
552 """Output select with options showing lines which qualifier maps to it.
553
554 ((Label) -> str, {Label:_}, str?) -> _"""
555 options = {} #{ option : [Label]}
556 for label in lines.keys():
557 option = qualifier(label)
558 if (option not in options):
559 options[option] = []
560 options[option].append(label)
561 option_list = list(options.keys())
562 option_list.sort()
563 print '<select class="lines"',
564 if select_id is not None:
565 print 'id=%s' % qa(select_id)
566 print 'multiple="true" size="10" onchange="updateSvg();">'
567 for option in option_list:
568 print '<option value=' + qa('[' +
569 reduce(lambda x,y:x+json.dumps(str(y))+',',options[option],"")[0:-1]
570 + ']') + '>'+qe(option)+'</option>'
571 print '</select>'
572
epoger@google.com3d8cd172012-05-11 18:26:16 +0000573def output_ignored_data_points_warning(ignored_revision_data_points):
574 """Write description of ignored_revision_data_points to stdout as xhtml.
575 """
576 num_ignored_points = 0
577 description = ''
578 revisions = ignored_revision_data_points.keys()
579 if revisions:
580 revisions.sort()
581 revisions.reverse()
582 for revision in revisions:
583 num_ignored_points += len(ignored_revision_data_points[revision])
584 points_at_this_revision = []
585 for point in ignored_revision_data_points[revision]:
586 points_at_this_revision.append(point.bench)
587 points_at_this_revision.sort()
588 description += 'r%d: %s\n' % (revision, points_at_this_revision)
589 if num_ignored_points == 0:
590 print 'Did not discard any data points; all were within the range [%d-%d]' % (
591 MIN_REASONABLE_TIME, MAX_REASONABLE_TIME)
592 else:
593 print '<table width="100%" bgcolor="ff0000"><tr><td align="center">'
594 print 'Discarded %d data points outside of range [%d-%d]' % (
595 num_ignored_points, MIN_REASONABLE_TIME, MAX_REASONABLE_TIME)
596 print '</td></tr><tr><td width="100%" align="center">'
597 print ('<textarea rows="4" style="width:97%" readonly="true" wrap="off">'
598 + qe(description) + '</textarea>')
599 print '</td></tr></table>'
600
601def output_xhtml(lines, oldest_revision, newest_revision, ignored_revision_data_points,
epoger@google.com37260002011-08-08 20:27:04 +0000602 regressions, requested_width, requested_height, title):
bungeman@google.com85669f92011-06-17 13:58:14 +0000603 """Outputs an svg/xhtml view of the data."""
604 print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"',
605 print '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
606 print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">'
607 print '<head>'
epoger@google.com3d8cd172012-05-11 18:26:16 +0000608 print '<title>%s</title>' % qe(title)
bungeman@google.com85669f92011-06-17 13:58:14 +0000609 print '</head>'
610 print '<body>'
611
612 output_svg(lines, regressions, requested_width, requested_height)
epoger@google.com3d8cd172012-05-11 18:26:16 +0000613
bungeman@google.com85669f92011-06-17 13:58:14 +0000614 #output the manipulation controls
615 print """
616<script type="text/javascript">//<![CDATA[
617 function getElementsByClass(node, searchClass, tag) {
618 var classElements = new Array();
619 var elements = node.getElementsByTagName(tag);
620 var pattern = new RegExp("^|\\s"+searchClass+"\\s|$");
621 for (var i = 0, elementsFound = 0; i < elements.length; ++i) {
622 if (pattern.test(elements[i].className)) {
623 classElements[elementsFound] = elements[i];
624 ++elementsFound;
625 }
626 }
627 return classElements;
628 }
629 function getAllLines() {
630 var selectElem = document.getElementById('benchSelect');
631 var linesObj = {};
632 for (var i = 0; i < selectElem.options.length; ++i) {
633 var lines = JSON.parse(selectElem.options[i].value);
634 for (var j = 0; j < lines.length; ++j) {
635 linesObj[lines[j]] = true;
636 }
637 }
638 return linesObj;
639 }
640 function getOptions(selectElem) {
641 var linesSelectedObj = {};
642 for (var i = 0; i < selectElem.options.length; ++i) {
643 if (!selectElem.options[i].selected) continue;
644
645 var linesSelected = JSON.parse(selectElem.options[i].value);
646 for (var j = 0; j < linesSelected.length; ++j) {
647 linesSelectedObj[linesSelected[j]] = true;
648 }
649 }
650 return linesSelectedObj;
651 }
652 function objectEmpty(obj) {
653 for (var p in obj) {
654 return false;
655 }
656 return true;
657 }
658 function markSelectedLines(selectElem, allLines) {
659 var linesSelected = getOptions(selectElem);
660 if (!objectEmpty(linesSelected)) {
661 for (var line in allLines) {
662 allLines[line] &= (linesSelected[line] == true);
663 }
664 }
665 }
666 function updateSvg() {
667 var allLines = getAllLines();
668
669 var selects = getElementsByClass(document, 'lines', 'select');
670 for (var i = 0; i < selects.length; ++i) {
671 markSelectedLines(selects[i], allLines);
672 }
673
674 for (var line in allLines) {
675 var svgLine = document.getElementById(line);
676 var display = (allLines[line] ? 'inline' : 'none');
677 svgLine.setAttributeNS(null,'display', display);
678 }
679 }
680
681 function mark(markerId) {
682 for (var line in getAllLines()) {
683 var svgLineGroup = document.getElementById(line);
684 var display = svgLineGroup.getAttributeNS(null,'display');
685 if (display == null || display == "" || display != "none") {
686 var svgLine = document.getElementById(line+'_line');
687 if (markerId == null) {
688 svgLine.removeAttributeNS(null,'marker-mid');
689 } else {
690 svgLine.setAttributeNS(null,'marker-mid', markerId);
691 }
692 }
693 }
694 }
695//]]></script>"""
epoger@google.comc71174d2011-08-08 17:19:23 +0000696
bungeman@google.com85669f92011-06-17 13:58:14 +0000697 all_settings = {}
698 variant_settings = set()
699 for label in lines.keys():
700 for key, value in label.settings.items():
701 if key not in all_settings:
702 all_settings[key] = value
703 elif all_settings[key] != value:
704 variant_settings.add(key)
epoger@google.comc71174d2011-08-08 17:19:23 +0000705
bungeman@google.com752acc72012-09-12 19:34:17 +0000706 print '<table border="0" width="%s">' % requested_width
707 #output column headers
708 print """
709<tr valign="top"><td width="50%">
710<table border="0" width="100%">
711<tr><td align="center"><table border="0">
712<form>
713<tr valign="bottom" align="center">
714<td width="1">Bench&nbsp;Type</td>
715<td width="1">Bitmap Config</td>
716<td width="1">Timer&nbsp;Type (Cpu/Gpu/wall)</td>
717"""
718
bungeman@google.com85669f92011-06-17 13:58:14 +0000719 for k in variant_settings:
bungeman@google.com752acc72012-09-12 19:34:17 +0000720 print '<td width="1">%s</td>' % qe(k)
721
722 print '<td width="1"><!--buttons--></td></tr>'
723
724 #output column contents
725 print '<tr valign="top" align="center">'
726 print '<td width="1">'
727 create_select(lambda l: l.bench, lines, 'benchSelect')
728 print '</td><td width="1">'
729 create_select(lambda l: l.config, lines)
730 print '</td><td width="1">'
731 create_select(lambda l: l.time_type, lines)
732
733 for k in variant_settings:
734 print '</td><td width="1">'
735 create_select(lambda l: l.settings.get(k, " "), lines)
epoger@google.comc71174d2011-08-08 17:19:23 +0000736
737 print '</td><td width="1"><button type="button"',
bungeman@google.com85669f92011-06-17 13:58:14 +0000738 print 'onclick=%s' % qa("mark('url(#circleMark)'); return false;"),
epoger@google.comc71174d2011-08-08 17:19:23 +0000739 print '>Mark Points</button>'
740 print '<button type="button" onclick="mark(null);">Clear Points</button>'
epoger@google.com3d8cd172012-05-11 18:26:16 +0000741 print '</td>'
epoger@google.comc71174d2011-08-08 17:19:23 +0000742 print """
epoger@google.com3d8cd172012-05-11 18:26:16 +0000743</tr>
744</form>
745</table></td></tr>
746<tr><td align="center">
747<hr />
748"""
749
750 output_ignored_data_points_warning(ignored_revision_data_points)
751 print '</td></tr></table>'
752 print '</td><td width="2%"><!--gutter--></td>'
753
754 print '<td><table border="0">'
755 print '<tr><td align="center">%s<br></br>revisions r%s - r%s</td></tr>' % (
756 qe(title),
757 bench_util.CreateRevisionLink(oldest_revision),
758 bench_util.CreateRevisionLink(newest_revision))
759 print """
760<tr><td align="left">
epoger@google.comc71174d2011-08-08 17:19:23 +0000761<p>Brighter red indicates tests that have gotten worse; brighter green
762indicates tests that have gotten better.</p>
763<p>To highlight individual tests, hold down CONTROL and mouse over
764graph lines.</p>
765<p>To highlight revision numbers, hold down SHIFT and mouse over
766the graph area.</p>
767<p>To only show certain tests on the graph, select any combination of
768tests in the selectors at left. (To show all, select all.)</p>
769<p>Use buttons at left to mark/clear points on the lines for selected
770benchmarks.</p>
epoger@google.com3d8cd172012-05-11 18:26:16 +0000771</td></tr>
772</table>
773
epoger@google.comc71174d2011-08-08 17:19:23 +0000774</td>
775</tr>
epoger@google.comc71174d2011-08-08 17:19:23 +0000776</table>
777</body>
778</html>"""
bungeman@google.com85669f92011-06-17 13:58:14 +0000779
780def compute_size(requested_width, requested_height, rev_width, time_height):
781 """Converts potentially empty requested size into a concrete size.
782
783 (Number?, Number?) -> (Number, Number)"""
784 pic_width = 0
785 pic_height = 0
786 if (requested_width is not None and requested_height is not None):
787 pic_height = requested_height
788 pic_width = requested_width
789
790 elif (requested_width is not None):
791 pic_width = requested_width
792 pic_height = pic_width * (float(time_height) / rev_width)
793
794 elif (requested_height is not None):
795 pic_height = requested_height
796 pic_width = pic_height * (float(rev_width) / time_height)
797
798 else:
799 pic_height = 800
800 pic_width = max(rev_width*3
801 , pic_height * (float(rev_width) / time_height))
802
803 return (pic_width, pic_height)
804
805def output_svg(lines, regressions, requested_width, requested_height):
806 """Outputs an svg view of the data."""
807
808 (global_min_x, _), (global_max_x, global_max_y) = bounds(lines)
809 max_up_slope, min_down_slope = bounds_slope(regressions)
810
811 #output
812 global_min_y = 0
813 x = global_min_x
814 y = global_min_y
815 w = global_max_x - global_min_x
816 h = global_max_y - global_min_y
817 font_size = 16
818 line_width = 2
819
820 pic_width, pic_height = compute_size(requested_width, requested_height
821 , w, h)
822
823 def cw(w1):
824 """Converts a revision difference to display width."""
825 return (pic_width / float(w)) * w1
826 def cx(x):
827 """Converts a revision to a horizontal display position."""
828 return cw(x - global_min_x)
829
830 def ch(h1):
831 """Converts a time difference to a display height."""
832 return -(pic_height / float(h)) * h1
833 def cy(y):
834 """Converts a time to a vertical display position."""
835 return pic_height + ch(y - global_min_y)
836
bensong@google.com74267432012-08-30 18:19:02 +0000837 print '<!--Picture height %.2f corresponds to bench value %.2f.-->' % (
838 pic_height, h)
bungeman@google.com85669f92011-06-17 13:58:14 +0000839 print '<svg',
840 print 'width=%s' % qa(str(pic_width)+'px')
841 print 'height=%s' % qa(str(pic_height)+'px')
842 print 'viewBox="0 0 %s %s"' % (str(pic_width), str(pic_height))
843 print 'onclick=%s' % qa(
844 "var event = arguments[0] || window.event;"
845 " if (event.shiftKey) { highlightRevision(null); }"
846 " if (event.ctrlKey) { highlight(null); }"
847 " return false;")
848 print 'xmlns="http://www.w3.org/2000/svg"'
849 print 'xmlns:xlink="http://www.w3.org/1999/xlink">'
850
851 print """
852<defs>
853 <marker id="circleMark"
854 viewBox="0 0 2 2" refX="1" refY="1"
855 markerUnits="strokeWidth"
856 markerWidth="2" markerHeight="2"
857 orient="0">
858 <circle cx="1" cy="1" r="1"/>
859 </marker>
860</defs>"""
861
862 #output the revisions
863 print """
864<script type="text/javascript">//<![CDATA[
865 var previousRevision;
866 var previousRevisionFill;
867 var previousRevisionStroke
868 function highlightRevision(id) {
869 if (previousRevision == id) return;
epoger@google.comc71174d2011-08-08 17:19:23 +0000870
871 document.getElementById('revision').firstChild.nodeValue = 'r' + id;
872 document.getElementById('rev_link').setAttribute('xlink:href',
873 'http://code.google.com/p/skia/source/detail?r=' + id);
bungeman@google.com85669f92011-06-17 13:58:14 +0000874
875 var preRevision = document.getElementById(previousRevision);
876 if (preRevision) {
877 preRevision.setAttributeNS(null,'fill', previousRevisionFill);
878 preRevision.setAttributeNS(null,'stroke', previousRevisionStroke);
879 }
880
881 var revision = document.getElementById(id);
882 previousRevision = id;
883 if (revision) {
884 previousRevisionFill = revision.getAttributeNS(null,'fill');
885 revision.setAttributeNS(null,'fill','rgb(100%, 95%, 95%)');
886
887 previousRevisionStroke = revision.getAttributeNS(null,'stroke');
888 revision.setAttributeNS(null,'stroke','rgb(100%, 90%, 90%)');
889 }
890 }
891//]]></script>"""
892
893 def print_rect(x, y, w, h, revision):
894 """Outputs a revision rectangle in display space,
895 taking arguments in revision space."""
896 disp_y = cy(y)
897 disp_h = ch(h)
898 if disp_h < 0:
899 disp_y += disp_h
900 disp_h = -disp_h
901
902 print '<rect id=%s x=%s y=%s' % (qa(revision), qa(cx(x)), qa(disp_y),),
903 print 'width=%s height=%s' % (qa(cw(w)), qa(disp_h),),
904 print 'fill="white"',
epoger@google.comc71174d2011-08-08 17:19:23 +0000905 print 'stroke="rgb(98%%,98%%,88%%)" stroke-width=%s' % qa(line_width),
bungeman@google.com85669f92011-06-17 13:58:14 +0000906 print 'onmouseover=%s' % qa(
907 "var event = arguments[0] || window.event;"
908 " if (event.shiftKey) {"
909 " highlightRevision('"+str(revision)+"');"
910 " return false;"
911 " }"),
912 print ' />'
913
914 xes = set()
915 for line in lines.itervalues():
916 for point in line:
917 xes.add(point[0])
918 revisions = list(xes)
919 revisions.sort()
920
921 left = x
922 current_revision = revisions[0]
923 for next_revision in revisions[1:]:
924 width = (((next_revision - current_revision) / 2.0)
925 + (current_revision - left))
926 print_rect(left, y, width, h, current_revision)
927 left += width
928 current_revision = next_revision
929 print_rect(left, y, x+w - left, h, current_revision)
epoger@google.comc71174d2011-08-08 17:19:23 +0000930
bungeman@google.com85669f92011-06-17 13:58:14 +0000931 #output the lines
932 print """
933<script type="text/javascript">//<![CDATA[
934 var previous;
935 var previousColor;
936 var previousOpacity;
937 function highlight(id) {
938 if (previous == id) return;
epoger@google.comc71174d2011-08-08 17:19:23 +0000939
bungeman@google.com85669f92011-06-17 13:58:14 +0000940 document.getElementById('label').firstChild.nodeValue = id;
epoger@google.comc71174d2011-08-08 17:19:23 +0000941
bungeman@google.com85669f92011-06-17 13:58:14 +0000942 var preGroup = document.getElementById(previous);
943 if (preGroup) {
944 var preLine = document.getElementById(previous+'_line');
945 preLine.setAttributeNS(null,'stroke', previousColor);
946 preLine.setAttributeNS(null,'opacity', previousOpacity);
epoger@google.comc71174d2011-08-08 17:19:23 +0000947
bungeman@google.com85669f92011-06-17 13:58:14 +0000948 var preSlope = document.getElementById(previous+'_linear');
949 if (preSlope) {
950 preSlope.setAttributeNS(null,'visibility', 'hidden');
951 }
952 }
epoger@google.comc71174d2011-08-08 17:19:23 +0000953
bungeman@google.com85669f92011-06-17 13:58:14 +0000954 var group = document.getElementById(id);
955 previous = id;
956 if (group) {
957 group.parentNode.appendChild(group);
958
959 var line = document.getElementById(id+'_line');
960 previousColor = line.getAttributeNS(null,'stroke');
961 previousOpacity = line.getAttributeNS(null,'opacity');
962 line.setAttributeNS(null,'stroke', 'blue');
963 line.setAttributeNS(null,'opacity', '1');
964
965 var slope = document.getElementById(id+'_linear');
966 if (slope) {
967 slope.setAttributeNS(null,'visibility', 'visible');
968 }
969 }
970 }
971//]]></script>"""
epoger@google.com2459a392013-02-14 18:58:05 +0000972
973 # Add a new element to each item in the 'lines' list: the label in string
974 # form. Then use that element to sort the list.
975 sorted_lines = []
bungeman@google.com85669f92011-06-17 13:58:14 +0000976 for label, line in lines.items():
epoger@google.com2459a392013-02-14 18:58:05 +0000977 sorted_lines.append([str(label), label, line])
978 sorted_lines.sort()
979
980 for label_as_string, label, line in sorted_lines:
981 print '<g id=%s>' % qa(label_as_string)
bungeman@google.com85669f92011-06-17 13:58:14 +0000982 r = 128
983 g = 128
984 b = 128
985 a = .10
986 if label in regressions:
987 regression = regressions[label]
988 min_slope = regression.find_min_slope()
989 if min_slope < 0:
990 d = max(0, (min_slope / min_down_slope))
991 g += int(d*128)
992 a += d*0.9
993 elif min_slope > 0:
994 d = max(0, (min_slope / max_up_slope))
995 r += int(d*128)
996 a += d*0.9
997
998 slope = regression.slope
999 intercept = regression.intercept
1000 min_x = regression.min_x
1001 max_x = regression.max_x
1002 print '<polyline id=%s' % qa(str(label)+'_linear'),
1003 print 'fill="none" stroke="yellow"',
1004 print 'stroke-width=%s' % qa(abs(ch(regression.serror*2))),
1005 print 'opacity="0.5" pointer-events="none" visibility="hidden"',
1006 print 'points="',
1007 print '%s,%s' % (str(cx(min_x)), str(cy(slope*min_x + intercept))),
1008 print '%s,%s' % (str(cx(max_x)), str(cy(slope*max_x + intercept))),
1009 print '"/>'
1010
1011 print '<polyline id=%s' % qa(str(label)+'_line'),
1012 print 'onmouseover=%s' % qa(
1013 "var event = arguments[0] || window.event;"
1014 " if (event.ctrlKey) {"
1015 " highlight('"+str(label).replace("'", "\\'")+"');"
1016 " return false;"
1017 " }"),
1018 print 'fill="none" stroke="rgb(%s,%s,%s)"' % (str(r), str(g), str(b)),
1019 print 'stroke-width=%s' % qa(line_width),
1020 print 'opacity=%s' % qa(a),
1021 print 'points="',
1022 for point in line:
1023 print '%s,%s' % (str(cx(point[0])), str(cy(point[1]))),
1024 print '"/>'
epoger@google.comc71174d2011-08-08 17:19:23 +00001025
bungeman@google.com85669f92011-06-17 13:58:14 +00001026 print '</g>'
epoger@google.comc71174d2011-08-08 17:19:23 +00001027
bungeman@google.com85669f92011-06-17 13:58:14 +00001028 #output the labels
1029 print '<text id="label" x="0" y=%s' % qa(font_size),
1030 print 'font-size=%s> </text>' % qa(font_size)
epoger@google.comc71174d2011-08-08 17:19:23 +00001031
1032 print '<a id="rev_link" xlink:href="" target="_top">'
1033 print '<text id="revision" x="0" y=%s style="' % qa(font_size*2)
1034 print 'font-size: %s; ' % qe(font_size)
1035 print 'stroke: #0000dd; text-decoration: underline; '
1036 print '"> </text></a>'
1037
bungeman@google.com85669f92011-06-17 13:58:14 +00001038 print '</svg>'
epoger@google.comc71174d2011-08-08 17:19:23 +00001039
bungeman@google.com85669f92011-06-17 13:58:14 +00001040if __name__ == "__main__":
1041 main()