view.py 34 KB

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