xls-report.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. #!/usr/bin/env python
  2. """
  3. This script can generate XLS reports from OpenCV tests' XML output files.
  4. To use it, first, create a directory for each machine you ran tests on.
  5. Each such directory will become a sheet in the report. Put each XML file
  6. into the corresponding directory.
  7. Then, create your configuration file(s). You can have a global configuration
  8. file (specified with the -c option), and per-sheet configuration files, which
  9. must be called sheet.conf and placed in the directory corresponding to the sheet.
  10. The settings in the per-sheet configuration file will override those in the
  11. global configuration file, if both are present.
  12. A configuration file must consist of a Python dictionary. The following keys
  13. will be recognized:
  14. * 'comparisons': [{'from': string, 'to': string}]
  15. List of configurations to compare performance between. For each item,
  16. the sheet will have a column showing speedup from configuration named
  17. 'from' to configuration named "to".
  18. * 'configuration_matchers': [{'properties': {string: object}, 'name': string}]
  19. Instructions for matching test run property sets to configuration names.
  20. For each found XML file:
  21. 1) All attributes of the root element starting with the prefix 'cv_' are
  22. placed in a dictionary, with the cv_ prefix stripped and the cv_module_name
  23. element deleted.
  24. 2) The first matcher for which the XML's file property set contains the same
  25. keys with equal values as its 'properties' dictionary is searched for.
  26. A missing property can be matched by using None as the value.
  27. Corollary 1: you should place more specific matchers before less specific
  28. ones.
  29. Corollary 2: an empty 'properties' dictionary matches every property set.
  30. 3) If a matching matcher is found, its 'name' string is presumed to be the name
  31. of the configuration the XML file corresponds to. A warning is printed if
  32. two different property sets match to the same configuration name.
  33. 4) If a such a matcher isn't found, if --include-unmatched was specified, the
  34. configuration name is assumed to be the relative path from the sheet's
  35. directory to the XML file's containing directory. If the XML file isinstance
  36. directly inside the sheet's directory, the configuration name is instead
  37. a dump of all its properties. If --include-unmatched wasn't specified,
  38. the XML file is ignored and a warning is printed.
  39. * 'configurations': [string]
  40. List of names for compile-time and runtime configurations of OpenCV.
  41. Each item will correspond to a column of the sheet.
  42. * 'module_colors': {string: string}
  43. Mapping from module name to color name. In the sheet, cells containing module
  44. names from this mapping will be colored with the corresponding color. You can
  45. find the list of available colors here:
  46. <http://www.simplistix.co.uk/presentations/python-excel.pdf>.
  47. * 'sheet_name': string
  48. Name for the sheet. If this parameter is missing, the name of sheet's directory
  49. will be used.
  50. * 'sheet_properties': [(string, string)]
  51. List of arbitrary (key, value) pairs that somehow describe the sheet. Will be
  52. dumped into the first row of the sheet in string form.
  53. Note that all keys are optional, although to get useful results, you'll want to
  54. specify at least 'configurations' and 'configuration_matchers'.
  55. Finally, run the script. Use the --help option for usage information.
  56. """
  57. from __future__ import division
  58. import ast
  59. import errno
  60. import fnmatch
  61. import logging
  62. import numbers
  63. import os, os.path
  64. import re
  65. from argparse import ArgumentParser
  66. from glob import glob
  67. from itertools import ifilter
  68. import xlwt
  69. from testlog_parser import parseLogFile
  70. re_image_size = re.compile(r'^ \d+ x \d+$', re.VERBOSE)
  71. re_data_type = re.compile(r'^ (?: 8 | 16 | 32 | 64 ) [USF] C [1234] $', re.VERBOSE)
  72. time_style = xlwt.easyxf(num_format_str='#0.00')
  73. no_time_style = xlwt.easyxf('pattern: pattern solid, fore_color gray25')
  74. failed_style = xlwt.easyxf('pattern: pattern solid, fore_color red')
  75. noimpl_style = xlwt.easyxf('pattern: pattern solid, fore_color orange')
  76. style_dict = {"failed": failed_style, "noimpl":noimpl_style}
  77. speedup_style = time_style
  78. good_speedup_style = xlwt.easyxf('font: color green', num_format_str='#0.00')
  79. bad_speedup_style = xlwt.easyxf('font: color red', num_format_str='#0.00')
  80. no_speedup_style = no_time_style
  81. error_speedup_style = xlwt.easyxf('pattern: pattern solid, fore_color orange')
  82. header_style = xlwt.easyxf('font: bold true; alignment: horizontal centre, vertical top, wrap True')
  83. subheader_style = xlwt.easyxf('alignment: horizontal centre, vertical top')
  84. class Collector(object):
  85. def __init__(self, config_match_func, include_unmatched):
  86. self.__config_cache = {}
  87. self.config_match_func = config_match_func
  88. self.include_unmatched = include_unmatched
  89. self.tests = {}
  90. self.extra_configurations = set()
  91. # Format a sorted sequence of pairs as if it was a dictionary.
  92. # We can't just use a dictionary instead, since we want to preserve the sorted order of the keys.
  93. @staticmethod
  94. def __format_config_cache_key(pairs, multiline=False):
  95. return (
  96. ('{\n' if multiline else '{') +
  97. (',\n' if multiline else ', ').join(
  98. (' ' if multiline else '') + repr(k) + ': ' + repr(v) for (k, v) in pairs) +
  99. ('\n}\n' if multiline else '}')
  100. )
  101. def collect_from(self, xml_path, default_configuration):
  102. run = parseLogFile(xml_path)
  103. module = run.properties['module_name']
  104. properties = run.properties.copy()
  105. del properties['module_name']
  106. props_key = tuple(sorted(properties.iteritems())) # dicts can't be keys
  107. if props_key in self.__config_cache:
  108. configuration = self.__config_cache[props_key]
  109. else:
  110. configuration = self.config_match_func(properties)
  111. if configuration is None:
  112. if self.include_unmatched:
  113. if default_configuration is not None:
  114. configuration = default_configuration
  115. else:
  116. configuration = Collector.__format_config_cache_key(props_key, multiline=True)
  117. self.extra_configurations.add(configuration)
  118. else:
  119. logging.warning('failed to match properties to a configuration: %s',
  120. Collector.__format_config_cache_key(props_key))
  121. else:
  122. same_config_props = [it[0] for it in self.__config_cache.iteritems() if it[1] == configuration]
  123. if len(same_config_props) > 0:
  124. logging.warning('property set %s matches the same configuration %r as property set %s',
  125. Collector.__format_config_cache_key(props_key),
  126. configuration,
  127. Collector.__format_config_cache_key(same_config_props[0]))
  128. self.__config_cache[props_key] = configuration
  129. if configuration is None: return
  130. module_tests = self.tests.setdefault(module, {})
  131. for test in run.tests:
  132. test_results = module_tests.setdefault((test.shortName(), test.param()), {})
  133. new_result = test.get("gmean") if test.status == 'run' else test.status
  134. test_results[configuration] = min(
  135. test_results.get(configuration), new_result,
  136. key=lambda r: (1, r) if isinstance(r, numbers.Number) else
  137. (2,) if r is not None else
  138. (3,)
  139. ) # prefer lower result; prefer numbers to errors and errors to nothing
  140. def make_match_func(matchers):
  141. def match_func(properties):
  142. for matcher in matchers:
  143. if all(properties.get(name) == value
  144. for (name, value) in matcher['properties'].iteritems()):
  145. return matcher['name']
  146. return None
  147. return match_func
  148. def main():
  149. arg_parser = ArgumentParser(description='Build an XLS performance report.')
  150. arg_parser.add_argument('sheet_dirs', nargs='+', metavar='DIR', help='directory containing perf test logs')
  151. arg_parser.add_argument('-o', '--output', metavar='XLS', default='report.xls', help='name of output file')
  152. arg_parser.add_argument('-c', '--config', metavar='CONF', help='global configuration file')
  153. arg_parser.add_argument('--include-unmatched', action='store_true',
  154. help='include results from XML files that were not recognized by configuration matchers')
  155. arg_parser.add_argument('--show-times-per-pixel', action='store_true',
  156. help='for tests that have an image size parameter, show per-pixel time, as well as total time')
  157. args = arg_parser.parse_args()
  158. logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
  159. if args.config is not None:
  160. with open(args.config) as global_conf_file:
  161. global_conf = ast.literal_eval(global_conf_file.read())
  162. else:
  163. global_conf = {}
  164. wb = xlwt.Workbook()
  165. for sheet_path in args.sheet_dirs:
  166. try:
  167. with open(os.path.join(sheet_path, 'sheet.conf')) as sheet_conf_file:
  168. sheet_conf = ast.literal_eval(sheet_conf_file.read())
  169. except IOError as ioe:
  170. if ioe.errno != errno.ENOENT: raise
  171. sheet_conf = {}
  172. logging.debug('no sheet.conf for %s', sheet_path)
  173. sheet_conf = dict(global_conf.items() + sheet_conf.items())
  174. config_names = sheet_conf.get('configurations', [])
  175. config_matchers = sheet_conf.get('configuration_matchers', [])
  176. collector = Collector(make_match_func(config_matchers), args.include_unmatched)
  177. for root, _, filenames in os.walk(sheet_path):
  178. logging.info('looking in %s', root)
  179. for filename in fnmatch.filter(filenames, '*.xml'):
  180. if os.path.normpath(sheet_path) == os.path.normpath(root):
  181. default_conf = None
  182. else:
  183. default_conf = os.path.relpath(root, sheet_path)
  184. collector.collect_from(os.path.join(root, filename), default_conf)
  185. config_names.extend(sorted(collector.extra_configurations - set(config_names)))
  186. sheet = wb.add_sheet(sheet_conf.get('sheet_name', os.path.basename(os.path.abspath(sheet_path))))
  187. sheet_properties = sheet_conf.get('sheet_properties', [])
  188. sheet.write(0, 0, 'Properties:')
  189. sheet.write(0, 1,
  190. 'N/A' if len(sheet_properties) == 0 else
  191. ' '.join(str(k) + '=' + repr(v) for (k, v) in sheet_properties))
  192. sheet.row(2).height = 800
  193. sheet.panes_frozen = True
  194. sheet.remove_splits = True
  195. sheet_comparisons = sheet_conf.get('comparisons', [])
  196. row = 2
  197. col = 0
  198. for (w, caption) in [
  199. (2500, 'Module'),
  200. (10000, 'Test'),
  201. (2000, 'Image\nwidth'),
  202. (2000, 'Image\nheight'),
  203. (2000, 'Data\ntype'),
  204. (7500, 'Other parameters')]:
  205. sheet.col(col).width = w
  206. if args.show_times_per_pixel:
  207. sheet.write_merge(row, row + 1, col, col, caption, header_style)
  208. else:
  209. sheet.write(row, col, caption, header_style)
  210. col += 1
  211. for config_name in config_names:
  212. if args.show_times_per_pixel:
  213. sheet.col(col).width = 3000
  214. sheet.col(col + 1).width = 3000
  215. sheet.write_merge(row, row, col, col + 1, config_name, header_style)
  216. sheet.write(row + 1, col, 'total, ms', subheader_style)
  217. sheet.write(row + 1, col + 1, 'per pixel, ns', subheader_style)
  218. col += 2
  219. else:
  220. sheet.col(col).width = 4000
  221. sheet.write(row, col, config_name, header_style)
  222. col += 1
  223. col += 1 # blank column between configurations and comparisons
  224. for comp in sheet_comparisons:
  225. sheet.col(col).width = 4000
  226. caption = comp['to'] + '\nvs\n' + comp['from']
  227. if args.show_times_per_pixel:
  228. sheet.write_merge(row, row + 1, col, col, caption, header_style)
  229. else:
  230. sheet.write(row, col, caption, header_style)
  231. col += 1
  232. row += 2 if args.show_times_per_pixel else 1
  233. sheet.horz_split_pos = row
  234. sheet.horz_split_first_visible = row
  235. module_colors = sheet_conf.get('module_colors', {})
  236. module_styles = {module: xlwt.easyxf('pattern: pattern solid, fore_color {}'.format(color))
  237. for module, color in module_colors.iteritems()}
  238. for module, tests in sorted(collector.tests.iteritems()):
  239. for ((test, param), configs) in sorted(tests.iteritems()):
  240. sheet.write(row, 0, module, module_styles.get(module, xlwt.Style.default_style))
  241. sheet.write(row, 1, test)
  242. param_list = param[1:-1].split(', ') if param.startswith('(') and param.endswith(')') else [param]
  243. image_size = next(ifilter(re_image_size.match, param_list), None)
  244. if image_size is not None:
  245. (image_width, image_height) = map(int, image_size.split('x', 1))
  246. sheet.write(row, 2, image_width)
  247. sheet.write(row, 3, image_height)
  248. del param_list[param_list.index(image_size)]
  249. data_type = next(ifilter(re_data_type.match, param_list), None)
  250. if data_type is not None:
  251. sheet.write(row, 4, data_type)
  252. del param_list[param_list.index(data_type)]
  253. sheet.row(row).write(5, ' | '.join(param_list))
  254. col = 6
  255. for c in config_names:
  256. if c in configs:
  257. sheet.write(row, col, configs[c], style_dict.get(configs[c], time_style))
  258. else:
  259. sheet.write(row, col, None, no_time_style)
  260. col += 1
  261. if args.show_times_per_pixel:
  262. sheet.write(row, col,
  263. xlwt.Formula('{0} * 1000000 / ({1} * {2})'.format(
  264. xlwt.Utils.rowcol_to_cell(row, col - 1),
  265. xlwt.Utils.rowcol_to_cell(row, 2),
  266. xlwt.Utils.rowcol_to_cell(row, 3)
  267. )),
  268. time_style
  269. )
  270. col += 1
  271. col += 1 # blank column
  272. for comp in sheet_comparisons:
  273. cmp_from = configs.get(comp["from"])
  274. cmp_to = configs.get(comp["to"])
  275. if isinstance(cmp_from, numbers.Number) and isinstance(cmp_to, numbers.Number):
  276. try:
  277. speedup = cmp_from / cmp_to
  278. sheet.write(row, col, speedup, good_speedup_style if speedup > 1.1 else
  279. bad_speedup_style if speedup < 0.9 else
  280. speedup_style)
  281. except ArithmeticError as e:
  282. sheet.write(row, col, None, error_speedup_style)
  283. else:
  284. sheet.write(row, col, None, no_speedup_style)
  285. col += 1
  286. row += 1
  287. if row % 1000 == 0: sheet.flush_row_data()
  288. wb.save(args.output)
  289. if __name__ == '__main__':
  290. main()