view.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. #
  2. # Metrix++, Copyright 2009-2019, Metrix++ Project
  3. # Link: https://github.com/metrixplusplus/metrixplusplus
  4. #
  5. # This file is a part of Metrix++ Tool.
  6. #
  7. import logging
  8. import sys
  9. import mpp.api
  10. import mpp.utils
  11. import mpp.cout
  12. DIGIT_COUNT = 8
  13. class Plugin(mpp.api.Plugin, mpp.api.IConfigurable, mpp.api.IRunable):
  14. MODE_NEW = 0x01
  15. MODE_TOUCHED = 0x03
  16. MODE_ALL = 0x07
  17. def declare_configuration(self, parser):
  18. self.parser = parser
  19. parser.add_option("--format", "--ft", default='txt', choices=['txt', 'xml', 'python'],
  20. help="Format of the output data. "
  21. "Possible values are 'xml', 'txt' or 'python' [default: %default]")
  22. parser.add_option("--nest-regions", "--nr", action="store_true", default=False,
  23. help="If the option is set (True), data for regions is exported in the form of a tree. "
  24. "Otherwise, all regions are exported in plain list. [default: %default]")
  25. parser.add_option("--max-distribution-rows", "--mdr", type=int, default=20,
  26. help="Maximum number of rows in distribution tables. "
  27. "If it is set to 0, the tool does not optimize the size of distribution tables [default: %default]")
  28. parser.add_option("--scope-mode", "--sm", default='all', choices=['new', 'touched', 'all'],
  29. help="Defines the analysis scope mode. "
  30. "'all' - all available regions and files are taken into account, "
  31. "'new' - only new regions and files are taken into account, "
  32. "'touched' - only new and modified regions and files are taken into account. "
  33. "Modes 'new' and 'touched' may require more time for processing than mode 'all' "
  34. "[default: %default]")
  35. def configure(self, options):
  36. self.out_format = options.__dict__['format']
  37. self.nest_regions = options.__dict__['nest_regions']
  38. self.dist_columns = options.__dict__['max_distribution_rows']
  39. if options.__dict__['scope_mode'] == 'new':
  40. self.mode = self.MODE_NEW
  41. elif options.__dict__['scope_mode'] == 'touched':
  42. self.mode = self.MODE_TOUCHED
  43. elif options.__dict__['scope_mode'] == 'all':
  44. self.mode = self.MODE_ALL
  45. if self.mode != self.MODE_ALL and options.__dict__['db_file_prev'] == None:
  46. self.parser.error("option --scope-mode: The mode '" + options.__dict__['scope_mode'] + "' requires '--db-file-prev' option set")
  47. def run(self, args):
  48. loader_prev = self.get_plugin('mpp.dbf').get_loader_prev()
  49. loader = self.get_plugin('mpp.dbf').get_loader()
  50. paths = None
  51. if len(args) == 0:
  52. paths = [""]
  53. else:
  54. paths = args
  55. (result, exit_code) = export_to_str(self.out_format,
  56. paths,
  57. loader,
  58. loader_prev,
  59. self.nest_regions,
  60. self.dist_columns,
  61. self.mode)
  62. print(result)
  63. return exit_code
  64. def export_to_str(out_format, paths, loader, loader_prev, nest_regions, dist_columns, mode):
  65. exit_code = 0
  66. result = ""
  67. if out_format == 'xml':
  68. result += "<view>\n"
  69. elif out_format == 'python':
  70. result += "{'view': ["
  71. for (ind, path) in enumerate(paths):
  72. path = mpp.utils.preprocess_path(path)
  73. aggregated_data, aggregated_data_prev = load_aggregated_data_with_mode(loader, loader_prev, path , mode)
  74. aggregated_data_tree = {}
  75. subdirs = []
  76. subfiles = []
  77. if aggregated_data != None:
  78. aggregated_data_tree = aggregated_data.get_data_tree()
  79. subdirs = sorted(aggregated_data.get_subdirs())
  80. subfiles = sorted(aggregated_data.get_subfiles())
  81. else:
  82. mpp.utils.report_bad_path(path)
  83. exit_code += 1
  84. aggregated_data_tree = append_suppressions(path, aggregated_data_tree, loader, mode)
  85. if aggregated_data_prev != None:
  86. aggregated_data_prev_tree = aggregated_data_prev.get_data_tree()
  87. aggregated_data_prev_tree = append_suppressions(path, aggregated_data_prev_tree, loader_prev, mode)
  88. aggregated_data_tree = append_diff(aggregated_data_tree,
  89. aggregated_data_prev_tree)
  90. aggregated_data_tree = compress_dist(aggregated_data_tree, dist_columns)
  91. file_data = loader.load_file_data(path)
  92. file_data_tree = {}
  93. if file_data != None:
  94. file_data_tree = file_data.get_data_tree()
  95. file_data_prev = loader_prev.load_file_data(path)
  96. append_regions(file_data_tree, file_data, file_data_prev, nest_regions)
  97. data = {"info": {"path": path, "id": ind + 1},
  98. "aggregated-data": aggregated_data_tree,
  99. "file-data": file_data_tree,
  100. "subdirs": subdirs,
  101. "subfiles": subfiles}
  102. if out_format == 'txt':
  103. cout_txt(data, loader)
  104. elif out_format == 'xml':
  105. result += mpp.utils.serialize_to_xml(data, root_name = "data", digitCount = DIGIT_COUNT) + "\n"
  106. elif out_format == 'python':
  107. postfix = ""
  108. if ind < len(paths) - 1:
  109. postfix = ", "
  110. result += mpp.utils.serialize_to_python(data, root_name = "data") + postfix
  111. if out_format == 'xml':
  112. result += "</view>"
  113. elif out_format == 'python':
  114. result += "]}"
  115. return (result, exit_code)
  116. def load_aggregated_data_with_mode(loader, loader_prev, path, mode):
  117. if mode == Plugin.MODE_ALL:
  118. aggregated_data = loader.load_aggregated_data(path)
  119. aggregated_data_prev = loader_prev.load_aggregated_data(path)
  120. else:
  121. assert(mode == Plugin.MODE_NEW or mode == Plugin.MODE_TOUCHED)
  122. class AggregatedFilteredData(mpp.api.AggregatedData):
  123. def __init__(self, loader, path):
  124. super(AggregatedFilteredData, self).__init__(loader, path)
  125. self.in_processing_mode = True
  126. for name in loader.iterate_namespace_names():
  127. namespace = loader.get_namespace(name)
  128. for field in namespace.iterate_field_names():
  129. if namespace.get_field_python_type(field) == str:
  130. # skip string type fields
  131. continue
  132. self.set_data(name, field, {
  133. 'count': 0,
  134. 'nonzero': namespace.is_field_non_zero(field),
  135. 'min': None,
  136. 'max': None,
  137. 'total': 0.0,
  138. 'avg': None,
  139. 'distribution-bars': {},
  140. 'sup': 0
  141. })
  142. def get_data_tree(self, namespaces=None):
  143. self.in_processing_mode = False
  144. # need to convert distribution map to a list and calculate average
  145. for name in loader.iterate_namespace_names():
  146. namespace = loader.get_namespace(name)
  147. for field in namespace.iterate_field_names():
  148. if namespace.get_field_python_type(field) == str:
  149. # skip string type fields
  150. continue
  151. data = self.get_data(name, field)
  152. bars_list = []
  153. for metric_value in sorted(data['distribution-bars'].keys()):
  154. bars_list.append({'metric': metric_value,
  155. 'count': data['distribution-bars'][metric_value],
  156. 'ratio': ((float(data['distribution-bars'][metric_value]) /
  157. float(data['count'])))})
  158. data['distribution-bars'] = bars_list
  159. if data['count'] != 0:
  160. data['avg'] = float(data['total']) / float(data['count'])
  161. self.set_data(name, field, data)
  162. return super(AggregatedFilteredData, self).get_data_tree(namespaces=namespaces)
  163. def _append_data(self, orig_data):
  164. # flag to protect ourselves from getting incomplete data
  165. # the workflow in this tool: append data first and after get it using get_data_tree()
  166. assert(self.in_processing_mode == True)
  167. sup_data = orig_data.get_data('std.suppress', 'list')
  168. data = orig_data.get_data_tree()
  169. for namespace in list(data.keys()):
  170. for field in list(data[namespace].keys()):
  171. aggr_data = self.get_data(namespace, field)
  172. metric_value = data[namespace][field]
  173. if isinstance(metric_value, str):
  174. # skip string type fields
  175. continue
  176. if aggr_data['min'] == None or aggr_data['min'] > metric_value:
  177. aggr_data['min'] = metric_value
  178. if aggr_data['max'] == None or aggr_data['max'] < metric_value:
  179. aggr_data['max'] = metric_value
  180. aggr_data['count'] += 1
  181. aggr_data['total'] += metric_value
  182. # average is calculated later on get_data_tree
  183. if metric_value not in list(aggr_data['distribution-bars'].keys()):
  184. aggr_data['distribution-bars'][metric_value] = 0
  185. aggr_data['distribution-bars'][metric_value] += 1
  186. if sup_data != None:
  187. if sup_data.find('[{0}:{1}]'.format(namespace, field)) != -1:
  188. aggr_data['sup'] += 1
  189. self.set_data(namespace, field, aggr_data)
  190. def _append_file_data(self, file_data):
  191. self._append_data(file_data)
  192. for region in file_data.iterate_regions():
  193. self._append_data(region)
  194. result = AggregatedFilteredData(loader, path)
  195. result_prev = AggregatedFilteredData(loader_prev, path)
  196. prev_file_ids = set()
  197. file_data_iterator = loader.iterate_file_data(path)
  198. if file_data_iterator != None:
  199. for file_data in file_data_iterator:
  200. file_data_prev = loader_prev.load_file_data(file_data.get_path())
  201. if file_data_prev != None:
  202. prev_file_ids.add(file_data_prev.get_id())
  203. if (file_data_prev == None and (mode == Plugin.MODE_NEW or mode == Plugin.MODE_TOUCHED)):
  204. # new file and required mode matched
  205. logging.info("Processing: " + file_data.get_path() + " [new]")
  206. result._append_file_data(file_data)
  207. elif (file_data.get_checksum() != file_data_prev.get_checksum()):
  208. # modified file and required mode matched
  209. logging.info("Processing: " + file_data.get_path() + " [modified]")
  210. # append file data without appending regions...
  211. if (mode == Plugin.MODE_TOUCHED):
  212. # if required mode matched
  213. result._append_data(file_data)
  214. result_prev._append_data(file_data_prev)
  215. # process regions separately
  216. matcher = mpp.utils.FileRegionsMatcher(file_data, file_data_prev)
  217. prev_reg_ids = set()
  218. for region in file_data.iterate_regions():
  219. prev_id = matcher.get_prev_id(region.get_id())
  220. if prev_id != None:
  221. prev_reg_ids.add(prev_id)
  222. if (matcher.is_matched(region.get_id()) == False and
  223. (mode == Plugin.MODE_NEW or mode == Plugin.MODE_TOUCHED)):
  224. # new region
  225. logging.debug("Processing region: " + region.get_name() + " [new]")
  226. result._append_data(region)
  227. elif matcher.is_modified(region.get_id()) and mode == Plugin.MODE_TOUCHED:
  228. # modified region
  229. logging.debug("Processing region: " + region.get_name() + " [modified]")
  230. result._append_data(region)
  231. result_prev._append_data(file_data_prev.get_region(prev_id))
  232. if mode == Plugin.MODE_TOUCHED:
  233. for region_prev in file_data_prev.iterate_regions():
  234. if region_prev.get_id() not in prev_reg_ids:
  235. # deleted region
  236. logging.debug("Processing region: " + region_prev.get_name() + " [deleted]")
  237. result_prev._append_data(region_prev)
  238. if mode == Plugin.MODE_TOUCHED:
  239. file_data_prev_iterator = loader_prev.iterate_file_data(path)
  240. if file_data_prev_iterator != None:
  241. for file_data_prev in file_data_prev_iterator:
  242. if file_data_prev.get_id() not in prev_file_ids:
  243. # deleted file and required mode matched
  244. logging.info("Processing: " + file_data_prev.get_path() + " [deleted]")
  245. result_prev._append_file_data(file_data_prev)
  246. return (result, result_prev)
  247. return (aggregated_data, aggregated_data_prev)
  248. def append_regions(file_data_tree, file_data, file_data_prev, nest_regions):
  249. regions_matcher = None
  250. if file_data_prev != None:
  251. file_data_tree = append_diff(file_data_tree,
  252. file_data_prev.get_data_tree())
  253. regions_matcher = mpp.utils.FileRegionsMatcher(file_data, file_data_prev)
  254. if nest_regions == False:
  255. regions = []
  256. for region in file_data.iterate_regions():
  257. region_data_tree = region.get_data_tree()
  258. is_modified = None
  259. if regions_matcher != None and regions_matcher.is_matched(region.get_id()):
  260. region_data_prev = file_data_prev.get_region(regions_matcher.get_prev_id(region.get_id()))
  261. region_data_tree = append_diff(region_data_tree,
  262. region_data_prev.get_data_tree())
  263. is_modified = regions_matcher.is_modified(region.get_id())
  264. regions.append({"info": {"name" : region.name,
  265. 'type': mpp.api.Region.T().to_str(region.get_type()),
  266. 'modified': is_modified,
  267. 'cursor' : region.cursor,
  268. 'line_begin': region.line_begin,
  269. 'line_end': region.line_end,
  270. 'offset_begin': region.begin,
  271. 'offset_end': region.end},
  272. "data": region_data_tree})
  273. file_data_tree['regions'] = regions
  274. else:
  275. def append_rec(region_id, file_data_tree, file_data, file_data_prev):
  276. region = file_data.get_region(region_id)
  277. region_data_tree = region.get_data_tree()
  278. is_modified = None
  279. if regions_matcher != None and regions_matcher.is_matched(region.get_id()):
  280. region_data_prev = file_data_prev.get_region(regions_matcher.get_prev_id(region.get_id()))
  281. region_data_tree = append_diff(region_data_tree,
  282. region_data_prev.get_data_tree())
  283. is_modified = regions_matcher.is_modified(region.get_id())
  284. result = {"info": {"name" : region.name,
  285. 'type' : mpp.api.Region.T().to_str(region.get_type()),
  286. 'modified': is_modified,
  287. 'cursor' : region.cursor,
  288. 'line_begin': region.line_begin,
  289. 'line_end': region.line_end,
  290. 'offset_begin': region.begin,
  291. 'offset_end': region.end},
  292. "data": region_data_tree,
  293. "subregions": []}
  294. for sub_id in file_data.get_region(region_id).iterate_subregion_ids():
  295. result['subregions'].append(append_rec(sub_id, file_data_tree, file_data, file_data_prev))
  296. return result
  297. file_data_tree['regions'] = []
  298. file_data_tree['regions'].append(append_rec(1, file_data_tree, file_data, file_data_prev))
  299. def append_diff(main_tree, prev_tree):
  300. assert(main_tree != None)
  301. assert(prev_tree != None)
  302. for name in list(main_tree.keys()):
  303. if name not in list(prev_tree.keys()):
  304. continue
  305. for field in list(main_tree[name].keys()):
  306. if field not in list(prev_tree[name].keys()):
  307. continue
  308. if isinstance(main_tree[name][field], dict) and isinstance(prev_tree[name][field], dict):
  309. diff = {}
  310. for key in list(main_tree[name][field].keys()):
  311. if key not in list(prev_tree[name][field].keys()):
  312. continue
  313. main_val = main_tree[name][field][key]
  314. prev_val = prev_tree[name][field][key]
  315. if main_val == None:
  316. main_val = 0
  317. if prev_val == None:
  318. prev_val = 0
  319. if isinstance(main_val, list) and isinstance(prev_val, list):
  320. main_tree[name][field][key] = append_diff_list(main_val, prev_val)
  321. else:
  322. diff[key] = main_val - prev_val
  323. main_tree[name][field]['__diff__'] = diff
  324. elif (not isinstance(main_tree[name][field], dict)) and (not isinstance(prev_tree[name][field], dict)):
  325. if '__diff__' not in main_tree[name]:
  326. main_tree[name]['__diff__'] = {}
  327. main_tree[name]['__diff__'][field] = main_tree[name][field] - prev_tree[name][field]
  328. return main_tree
  329. def append_diff_list(main_list, prev_list):
  330. merged_list = {}
  331. for bar in main_list:
  332. merged_list[bar['metric']] = {'count': bar['count'], '__diff__':bar['count'], 'ratio': bar['ratio']}
  333. for bar in prev_list:
  334. if bar['metric'] in list(merged_list.keys()):
  335. merged_list[bar['metric']]['__diff__'] = \
  336. merged_list[bar['metric']]['count'] - bar['count']
  337. else:
  338. merged_list[bar['metric']] = {'count': 0, '__diff__':-bar['count'], 'ratio': 0}
  339. result = []
  340. for metric in sorted(merged_list.keys()):
  341. result.append({'metric':metric,
  342. 'count':merged_list[metric]['count'],
  343. 'ratio':merged_list[metric]['ratio'],
  344. '__diff__':merged_list[metric]['__diff__']})
  345. return result
  346. def append_suppressions(path, data, loader, mode):
  347. if mode == Plugin.MODE_ALL:
  348. # in other modes, suppressions are appended during data loading
  349. for namespace in list(data.keys()):
  350. for field in list(data[namespace].keys()):
  351. selected_data = loader.load_selected_data('std.suppress',
  352. fields = ['list'],
  353. path=path,
  354. filters = [('list', 'LIKE', '%[{0}:{1}]%'.format(namespace, field))])
  355. if selected_data == None:
  356. data[namespace][field]['sup'] = 0
  357. else:
  358. count = 0
  359. for each in selected_data:
  360. each = each # used
  361. count += 1
  362. data[namespace][field]['sup'] = count
  363. return data
  364. def compress_dist(data, columns):
  365. if columns == 0:
  366. return data
  367. for namespace in list(data.keys()):
  368. for field in list(data[namespace].keys()):
  369. metric_data = data[namespace][field]
  370. distr = metric_data['distribution-bars']
  371. columns = float(columns) # to trigger floating calculations
  372. if metric_data['count'] == 0:
  373. continue
  374. new_dist = []
  375. remaining_count = metric_data['count']
  376. next_consume = None
  377. next_bar = None
  378. max_count = -sys.maxsize - 1
  379. min_count = sys.maxsize
  380. sum_ratio = 0
  381. for (ind, bar) in enumerate(distr):
  382. if next_bar == None:
  383. # start new bar
  384. next_bar = {'count': bar['count'],
  385. 'ratio': bar['ratio'],
  386. 'metric_s': bar['metric'],
  387. 'metric_f': bar['metric']}
  388. if '__diff__' in list(bar.keys()):
  389. next_bar['__diff__'] = bar['__diff__']
  390. next_consume = int(remaining_count/ (columns - len(new_dist)))
  391. else:
  392. # merge to existing bar
  393. next_bar['count'] += bar['count']
  394. next_bar['ratio'] += bar['ratio']
  395. next_bar['metric_f'] = bar['metric']
  396. if '__diff__' in list(bar.keys()):
  397. next_bar['__diff__'] += bar['__diff__']
  398. next_consume -= bar['count']
  399. if (next_consume <= 0 # consumed enough
  400. or (ind + 1) == len(distr)): # or the last bar
  401. # append to new distribution
  402. if isinstance(next_bar['metric_s'], float):
  403. next_bar['metric_s'] = "{0:.4f}".format(next_bar['metric_s'])
  404. next_bar['metric_f'] = "{0:.4f}".format(next_bar['metric_f'])
  405. else:
  406. next_bar['metric_s'] = str(next_bar['metric_s'])
  407. next_bar['metric_f'] = str(next_bar['metric_f'])
  408. if next_bar['metric_s'] == next_bar['metric_f']:
  409. next_bar['metric'] = next_bar['metric_s']
  410. else:
  411. next_bar['metric'] = next_bar['metric_s'] + "-" + next_bar['metric_f']
  412. del next_bar['metric_s']
  413. del next_bar['metric_f']
  414. new_dist.append(next_bar)
  415. sum_ratio += next_bar['ratio']
  416. if max_count < next_bar['count']:
  417. max_count = next_bar['count']
  418. if min_count > next_bar['count'] and next_bar['count'] != 0:
  419. min_count = next_bar['count']
  420. remaining_count -= next_bar['count']
  421. next_bar = None
  422. # check that consumed all
  423. assert((ind + 1) != len(distr) or remaining_count == 0)
  424. if remaining_count == 0:
  425. break
  426. if (float(max_count - min_count) / metric_data['count'] < 0.05 and
  427. metric_data['count'] > columns and
  428. len(new_dist) > 1):
  429. # trick here:
  430. # if all bars are even in the new distribution AND
  431. # there are many items in the distribution (> max distribution rows),
  432. # it is better to do linear compression instead
  433. new_dist = []
  434. step = int(round(float(metric_data['max'] - metric_data['min']) / columns))
  435. next_end_limit = metric_data['min']
  436. next_bar = None
  437. for (ind, bar) in enumerate(distr):
  438. if next_bar == None:
  439. # start new bar
  440. next_bar = {'count': bar['count'],
  441. 'ratio': bar['ratio'],
  442. 'metric_s': next_end_limit,
  443. 'metric_f': bar['metric']}
  444. if '__diff__' in list(bar.keys()):
  445. next_bar['__diff__'] = bar['__diff__']
  446. next_end_limit += step
  447. else:
  448. # merge to existing bar
  449. next_bar['count'] += bar['count']
  450. next_bar['ratio'] += bar['ratio']
  451. next_bar['metric_f'] = bar['metric']
  452. if '__diff__' in list(bar.keys()):
  453. next_bar['__diff__'] += bar['__diff__']
  454. if (next_bar['metric_f'] >= next_end_limit # consumed enough
  455. or (ind + 1) == len(distr)): # or the last bar
  456. if (ind + 1) != len(distr):
  457. next_bar['metric_f'] = next_end_limit
  458. # append to new distribution
  459. if isinstance(next_bar['metric_s'], float):
  460. next_bar['metric_s'] = "{0:.4f}".format(next_bar['metric_s'])
  461. next_bar['metric_f'] = "{0:.4f}".format(next_bar['metric_f'])
  462. else:
  463. next_bar['metric_s'] = str(next_bar['metric_s'])
  464. next_bar['metric_f'] = str(next_bar['metric_f'])
  465. next_bar['metric'] = next_bar['metric_s'] + "-" + next_bar['metric_f']
  466. del next_bar['metric_s']
  467. del next_bar['metric_f']
  468. new_dist.append(next_bar)
  469. next_bar = None
  470. data[namespace][field]['distribution-bars'] = new_dist
  471. return data
  472. def cout_txt_regions(path, regions, indent = 0):
  473. for region in regions:
  474. details = [
  475. ('Region name', region['info']['name']),
  476. ('Region type', region['info']['type']),
  477. ('Offsets', str(region['info']['offset_begin']) + "-" + str(region['info']['offset_end'])),
  478. ('Line numbers', str(region['info']['line_begin']) + "-" + str(region['info']['line_end'])),
  479. ('Modified', str(region['info']['modified']))
  480. ]
  481. for namespace in sorted(list(region['data'].keys())):
  482. diff_data = {}
  483. if '__diff__' in list(region['data'][namespace].keys()):
  484. diff_data = region['data'][namespace]['__diff__']
  485. for field in sorted(list(region['data'][namespace].keys())):
  486. diff_str = ""
  487. if field == '__diff__':
  488. continue
  489. if field in list(diff_data.keys()):
  490. diff_str = " [" + ("+" if diff_data[field] >= 0 else "") + str(diff_data[field]) + "]"
  491. details.append((namespace + ":" + field, str(region['data'][namespace][field]) + diff_str))
  492. mpp.cout.notify(path,
  493. region['info']['cursor'],
  494. mpp.cout.SEVERITY_INFO,
  495. "Metrics per '" + region['info']['name']+ "' region",
  496. details,
  497. indent=indent)
  498. if 'subregions' in list(region.keys()):
  499. cout_txt_regions(path, region['subregions'], indent=indent+1)
  500. def cout_txt(data, loader):
  501. details = []
  502. for key in list(data['file-data'].keys()):
  503. if key == 'regions':
  504. cout_txt_regions(data['info']['path'], data['file-data'][key])
  505. else:
  506. namespace = key
  507. diff_data = {}
  508. if '__diff__' in list(data['file-data'][namespace].keys()):
  509. diff_data = data['file-data'][namespace]['__diff__']
  510. for field in sorted(list(data['file-data'][namespace].keys())):
  511. diff_str = ""
  512. if field == '__diff__':
  513. continue
  514. if field in list(diff_data.keys()):
  515. diff_str = " [" + ("+" if diff_data[field] >= 0 else "") + str(diff_data[field]) + "]"
  516. details.append((namespace + ":" + field, str(data['file-data'][namespace][field]) + diff_str))
  517. if len(details) > 0:
  518. mpp.cout.notify(data['info']['path'],
  519. 0,
  520. mpp.cout.SEVERITY_INFO,
  521. "Metrics per file",
  522. details)
  523. attr_map = {'total': 'Total',
  524. 'avg': 'Average',
  525. 'min': 'Minimum',
  526. 'max': 'Maximum',
  527. }
  528. for namespace in sorted(list(data['aggregated-data'].keys())):
  529. for field in sorted(list(data['aggregated-data'][namespace].keys())):
  530. details = []
  531. diff_data = {}
  532. if '__diff__' in list(data['aggregated-data'][namespace][field].keys()):
  533. diff_data = data['aggregated-data'][namespace][field]['__diff__']
  534. for attr in ['avg', 'min', 'max', 'total']:
  535. diff_str = ""
  536. if attr in list(diff_data.keys()):
  537. if isinstance(diff_data[attr], float):
  538. diff_str = " [" + ("+" if diff_data[attr] >= 0 else "") + str(round(diff_data[attr], DIGIT_COUNT)) + "]"
  539. else:
  540. diff_str = " [" + ("+" if diff_data[attr] >= 0 else "") + str(diff_data[attr]) + "]"
  541. if attr == 'avg' and data['aggregated-data'][namespace][field]['nonzero'] == True:
  542. diff_str += " (excluding zero metric values)"
  543. if isinstance(data['aggregated-data'][namespace][field][attr], float):
  544. # round the data to reach same results on platforms with different precision
  545. details.append((attr_map[attr], str(round(data['aggregated-data'][namespace][field][attr], DIGIT_COUNT)) + diff_str))
  546. else:
  547. details.append((attr_map[attr], str(data['aggregated-data'][namespace][field][attr]) + diff_str))
  548. measured = data['aggregated-data'][namespace][field]['count']
  549. if 'count' in list(diff_data.keys()):
  550. diff_str = ' [{0:{1}}]'.format(diff_data['count'], '+' if diff_data['count'] >= 0 else '')
  551. sup_diff_str = ""
  552. if 'sup' in list(diff_data.keys()):
  553. sup_diff_str = ' [{0:{1}}]'.format(diff_data['sup'], '+' if diff_data['sup'] >= 0 else '')
  554. elem_name = 'regions'
  555. if loader.get_namespace(namespace).are_regions_supported() == False:
  556. elem_name = 'files'
  557. details.append(('Distribution',
  558. '{0}{1} {2} in total (including {3}{4} suppressed)'.format(measured,
  559. diff_str,
  560. elem_name,
  561. data['aggregated-data'][namespace][field]['sup'],
  562. sup_diff_str)))
  563. details.append((' Metric value', 'Ratio : R-sum : Number of ' + elem_name))
  564. count_str_len = len(str(measured))
  565. sum_ratio = 0
  566. for bar in data['aggregated-data'][namespace][field]['distribution-bars']:
  567. sum_ratio += bar['ratio']
  568. diff_str = ""
  569. if '__diff__' in list(bar.keys()):
  570. if bar['__diff__'] >= 0:
  571. diff_str = ' [+{0:<{1}}]'.format(bar['__diff__'], count_str_len)
  572. else:
  573. diff_str = ' [{0:<{1}}]'.format(bar['__diff__'], count_str_len+1)
  574. if isinstance(bar['metric'], float):
  575. metric_str = "{0:.4f}".format(bar['metric'])
  576. else:
  577. metric_str = str(bar['metric'])
  578. metric_str = (" " * (mpp.cout.DETAILS_OFFSET - len(metric_str) - 1)) + metric_str
  579. count_str = str(bar['count'])
  580. count_str = ((" " * (count_str_len - len(count_str))) + count_str + diff_str + "\t")
  581. details.append((metric_str,
  582. "{0:.3f}".format(bar['ratio']) + " : " + "{0:.3f}".format(sum_ratio) + " : " +
  583. count_str + ('|' * int(bar['ratio']*100))))
  584. mpp.cout.notify(data['info']['path'],
  585. '', # no line number
  586. mpp.cout.SEVERITY_INFO,
  587. "Overall metrics for '" + namespace + ":" + field + "' metric",
  588. details)
  589. details = []
  590. for each in sorted(data['subdirs']):
  591. details.append(('Directory', each))
  592. for each in sorted(data['subfiles']):
  593. details.append(('File', each))
  594. if len(details) > 0:
  595. mpp.cout.notify(data['info']['path'],
  596. '', # no line number
  597. mpp.cout.SEVERITY_INFO,
  598. "Directory content:",
  599. details)