view.py 33 KB

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