view.py 34 KB

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