plotting.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. """
  2. plotting.py
  3. The functions in this module are meant for plotting the histogram objects created via
  4. filval.histogram
  5. """
  6. from collections import defaultdict
  7. from itertools import zip_longest
  8. from io import BytesIO
  9. from base64 import b64encode
  10. import numpy as np
  11. import matplotlib.pyplot as plt
  12. from markdown import Markdown
  13. import latexipy as lp
  14. from filval.histogram import (hist, hist2d, hist_bin_centers, hist_fit,
  15. hist_norm, hist_stats)
  16. __all__ = ['Plot',
  17. 'decl_plot',
  18. 'grid_plot',
  19. 'render_plots',
  20. 'generate_dashboard',
  21. 'hist_plot',
  22. 'hist_plot_stack',
  23. 'hist2d_plot',
  24. 'hists_to_table']
  25. class Plot:
  26. def __init__(self, subplots, name, title=None, docs="N/A", arg_dicts=None):
  27. self.subplots = subplots
  28. self.name = name
  29. self.title = title
  30. self.docs = docs
  31. self.arg_dicts = arg_dicts if arg_dicts is not None else {}
  32. MD = Markdown(extensions=['mdx_math'],
  33. extension_configs={'mdx_math': {'enable_dollar_delimiter': True}})
  34. lp.latexify(params={'pgf.texsystem': 'pdflatex',
  35. 'text.usetex': True,
  36. 'font.family': 'serif',
  37. 'pgf.preamble': [],
  38. 'font.size': 15,
  39. 'axes.labelsize': 15,
  40. 'axes.titlesize': 13,
  41. 'legend.fontsize': 13,
  42. 'xtick.labelsize': 11,
  43. 'ytick.labelsize': 11,
  44. 'figure.dpi': 150,
  45. 'savefig.transparent': False,
  46. },
  47. new_backend='TkAgg')
  48. def _fn_call_to_dict(fn, *args, **kwargs):
  49. from inspect import signature
  50. from html import escape
  51. pnames = list(signature(fn).parameters)
  52. pvals = list(args) + list(kwargs.values())
  53. return {escape(str(k)): escape(str(v)) for k, v in zip(pnames, pvals)}
  54. def _process_docs(fn):
  55. from inspect import getdoc
  56. raw = getdoc(fn)
  57. if raw:
  58. return MD.convert(raw)
  59. else:
  60. return None
  61. def decl_plot(fn):
  62. from functools import wraps
  63. @wraps(fn)
  64. def f(*args, **kwargs):
  65. txt = fn(*args, **kwargs)
  66. argdict = _fn_call_to_dict(fn, *args, **kwargs)
  67. docs = _process_docs(fn)
  68. if not txt:
  69. txt = ''
  70. txt = MD.convert(txt)
  71. return argdict, docs, txt
  72. return f
  73. def generate_dashboard(plots, title, output='dashboard.html', template='dashboard.j2',
  74. source=None, ana_source=None, config=None):
  75. from jinja2 import Environment, PackageLoader, select_autoescape
  76. from os.path import join, isdir
  77. from os import mkdir
  78. from urllib.parse import quote
  79. env = Environment(
  80. loader=PackageLoader('filval', 'templates'),
  81. autoescape=select_autoescape(['htm', 'html', 'xml']),
  82. )
  83. env.globals.update({'quote': quote,
  84. 'enumerate': enumerate,
  85. 'zip': zip,
  86. })
  87. def get_by_n(objects, n=2):
  88. objects = list(objects)
  89. while objects:
  90. yield objects[:n]
  91. objects = objects[n:]
  92. if source is not None:
  93. with open(source, 'r') as f:
  94. source = f.read()
  95. if config is not None:
  96. with open(config, 'r') as f:
  97. config = f.read()
  98. if not isdir('output'):
  99. mkdir('output')
  100. dashboard_path = join('output', output)
  101. with open(dashboard_path, 'w') as tempout:
  102. templ = env.get_template(template)
  103. tempout.write(templ.render(
  104. plots=get_by_n(plots, 3),
  105. title=title,
  106. source=source,
  107. ana_source=ana_source,
  108. config=config
  109. ))
  110. return dashboard_path
  111. def _add_stats(hist, title=''):
  112. fmt = r'''\begin{{eqnarray*}}
  113. \sum{{x_i}} &=& {sum:5.3f} \\
  114. \sum{{\Delta x_i \cdot x_i}} &=& {int:5.3G} \\
  115. \mu &=& {mean:5.3G} \\
  116. \sigma^2 &=& {var:5.3G} \\
  117. \sigma &=& {std:5.3G}
  118. \end{{eqnarray*}}'''
  119. txt = fmt.format(**hist_stats(hist), title=title)
  120. txt = txt.replace('\n', ' ')
  121. plt.text(0.7, 0.9, txt,
  122. bbox={'facecolor': 'white',
  123. 'alpha': 0.7,
  124. 'boxstyle': 'square,pad=0.8'},
  125. transform=plt.gca().transAxes,
  126. verticalalignment='top',
  127. horizontalalignment='left',
  128. size='small')
  129. if title:
  130. plt.text(0.72, 0.97, title,
  131. bbox={'facecolor': 'white',
  132. 'alpha': 0.8},
  133. transform=plt.gca().transAxes,
  134. verticalalignment='top',
  135. horizontalalignment='left')
  136. def grid_plot(subplots):
  137. if any(len(row) != len(subplots[0]) for row in subplots):
  138. raise ValueError('make_plot requires a rectangular list-of-lists as '
  139. 'input. Fill empty slots with None')
  140. def calc_row_span(fig, row, col):
  141. span = 1
  142. for r in range(row + 1, len(fig)):
  143. if fig[r][col] == 'FU':
  144. span += 1
  145. else:
  146. break
  147. return span
  148. def calc_column_span(fig, row, col):
  149. span = 1
  150. for c in range(col + 1, len(fig[row])):
  151. if fig[row][c] == 'FL':
  152. span += 1
  153. else:
  154. break
  155. return span
  156. rows = len(subplots)
  157. cols = len(subplots[0])
  158. argdicts = defaultdict(list)
  159. docs = defaultdict(list)
  160. txts = defaultdict(list)
  161. for i in range(rows):
  162. for j in range(cols):
  163. cell = subplots[i][j]
  164. if cell in ('FL', 'FU', None):
  165. continue
  166. if not isinstance(cell, list):
  167. cell = [cell]
  168. column_span = calc_column_span(subplots, i, j)
  169. row_span = calc_row_span(subplots, i, j)
  170. plt.subplot2grid((rows, cols), (i, j),
  171. colspan=column_span, rowspan=row_span)
  172. for plot in cell:
  173. if len(plot) == 1:
  174. plot_fn, args, kwargs = plot[0], (), {}
  175. elif len(plot) == 2:
  176. plot_fn, args, kwargs = plot[0], plot[1], {}
  177. elif len(plot) == 3:
  178. plot_fn, args, kwargs = plot[0], plot[1], plot[2]
  179. else:
  180. raise ValueError('Plot tuple must be of format (func), '
  181. f'or (func, tuple), or (func, tuple, dict). Got {plot}')
  182. this_args, this_docs, txt = plot_fn(*args, **kwargs)
  183. argdicts[(i, j)].append(this_args)
  184. docs[(i, j)].append(this_docs)
  185. txts[(i, j)].append(txt)
  186. return argdicts, docs, txts
  187. def render_plots(plots, exts=('png',), scale=1.0, to_disk=True):
  188. for plot in plots:
  189. print(f'Building plot {plot.name}')
  190. plot.data = None
  191. if to_disk:
  192. with lp.figure(plot.name.replace(' ', '_'), directory='output/figures',
  193. exts=exts,
  194. size=(scale * 10, scale * 10)):
  195. argdicts, docs, txts = grid_plot(plot.subplots)
  196. else:
  197. out = BytesIO()
  198. with lp.mem_figure(out,
  199. ext=exts[0],
  200. size=(scale * 10, scale * 10)):
  201. argdicts, docs, txts = grid_plot(plot.subplots)
  202. out.seek(0)
  203. plot.data = b64encode(out.read()).decode()
  204. plot.argdicts = argdicts
  205. plot.docs = docs
  206. plot.txts = txts
  207. def add_decorations(axes, luminosity, energy):
  208. cms_prelim = r'{\raggedright{}\textsf{\textbf{CMS}}\\ \emph{Preliminary}}'
  209. axes.text(0.01, 0.98, cms_prelim,
  210. horizontalalignment='left',
  211. verticalalignment='top',
  212. transform=axes.transAxes)
  213. lumi = ""
  214. energy_str = ""
  215. if luminosity is not None:
  216. lumi = r'${} \mathrm{{fb}}^{{-1}}$'.format(luminosity)
  217. if energy is not None:
  218. energy_str = r'({} TeV)'.format(energy)
  219. axes.text(1, 1, ' '.join([lumi, energy_str]),
  220. horizontalalignment='right',
  221. verticalalignment='bottom',
  222. transform=axes.transAxes)
  223. def hist_plot(h, *args, norm=None, include_errors=False,
  224. log=False, xlim=None, ylim=None, fit=None,
  225. grid=False, stats=False, **kwargs):
  226. """ Plots a 1D ROOT histogram object using matplotlib """
  227. from inspect import signature
  228. if norm:
  229. h = hist_norm(h, norm)
  230. values, errors, edges = h
  231. scale = 1. if norm is None else norm / np.sum(values)
  232. values = [val * scale for val in values]
  233. errors = [val * scale for val in errors]
  234. left, right = np.array(edges[:-1]), np.array(edges[1:])
  235. x = np.array([left, right]).T.flatten()
  236. y = np.array([values, values]).T.flatten()
  237. ax = plt.gca()
  238. ax.set_xlabel(kwargs.pop('xlabel', ''))
  239. ax.set_ylabel(kwargs.pop('ylabel', ''))
  240. title = kwargs.pop('title', '')
  241. if xlim is not None:
  242. ax.set_xlim(xlim)
  243. if ylim is not None:
  244. ax.set_ylim(ylim)
  245. # elif not log:
  246. # axes.set_ylim((0, None))
  247. ax.plot(x, y, *args, linewidth=1, **kwargs)
  248. if include_errors:
  249. ax.errorbar(hist_bin_centers(h), values, yerr=errors,
  250. color='k', marker=None, linestyle='None',
  251. barsabove=True, elinewidth=.7, capsize=1)
  252. if log:
  253. ax.set_yscale('log')
  254. if fit:
  255. f, p0 = fit
  256. popt, pcov = hist_fit(h, f, p0)
  257. fit_xs = np.linspace(x[0], x[-1], 100)
  258. fit_ys = f(fit_xs, *popt)
  259. ax.plot(fit_xs, fit_ys, '--g')
  260. arglabels = list(signature(f).parameters)[1:]
  261. label_txt = "\n".join('{:7s}={: 0.2G}'.format(label, value)
  262. for label, value in zip(arglabels, popt))
  263. ax.text(0.60, 0.95, label_txt, va='top', transform=ax.transAxes,
  264. fontsize='medium', family='monospace', usetex=False)
  265. if stats:
  266. _add_stats(h, title)
  267. else:
  268. ax.set_title(title)
  269. ax.grid(grid, color='#E0E0E0')
  270. def hist2d_plot(h, txt_format=None, colorbar=False, **kwargs):
  271. """ Plots a 2D ROOT histogram object using matplotlib """
  272. try:
  273. values, errors, xs, ys = h
  274. except (TypeError, ValueError):
  275. values, errors, xs, ys = hist2d(h)
  276. plt.xlabel(kwargs.pop('xlabel', ''))
  277. plt.ylabel(kwargs.pop('ylabel', ''))
  278. plt.title(kwargs.pop('title', ''))
  279. plt.pcolormesh(xs, ys, values, **kwargs)
  280. if txt_format is not None:
  281. cmap = plt.get_cmap()
  282. min_, max_ = float(np.min(values)), float(np.max(values))
  283. def get_intensity(val):
  284. cmap_idx = int((cmap.N-1) * (val - min_) / (max_-min_))
  285. color = cmap.colors[cmap_idx]
  286. return color[0]*0.25 + color[1]*0.5 + color[2]*0.25
  287. for idx_row in range(values.shape[0]):
  288. for idx_col in range(values.shape[1]):
  289. x_mid = (xs[idx_row, idx_col] + xs[idx_row, idx_col+1]) / 2
  290. y_mid = (ys[idx_row, idx_col] + ys[idx_row+1, idx_col]) / 2
  291. val = txt_format.format(values[idx_row, idx_col])
  292. txt_color = 'w' if get_intensity(values[idx_row, idx_col]) < 0.5 else 'k'
  293. plt.text(x_mid, y_mid, val, verticalalignment='center', horizontalalignment='center',
  294. color=txt_color, fontsize=12)
  295. if colorbar:
  296. plt.colorbar()
  297. def hist_plot_stack(hists: list, labels: list = None):
  298. """
  299. Creates a stacked histogram in the current axes.
  300. :param hists: list of histogram
  301. :param labels:
  302. :return:
  303. """
  304. if len(hists) == 0:
  305. return
  306. if len(set([len(hist[0]) for hist in hists])) != 1:
  307. raise ValueError("all histograms must have the same number of bins")
  308. if labels is None:
  309. labels = [None for _ in hists]
  310. if len(labels) != len(hists):
  311. raise ValueError("Label mismatch")
  312. bottoms = [0 for _ in hists[0][0]]
  313. for hist, label in zip(hists, labels):
  314. centers = []
  315. widths = []
  316. heights = []
  317. for left, right, content in zip(hist[2][:-1], hist[2][1:], hist[0]):
  318. centers.append((right + left) / 2)
  319. widths.append(right - left)
  320. heights.append(content)
  321. plt.bar(centers, heights, widths, bottoms, label=label)
  322. for i, content in enumerate(hist[0]):
  323. bottoms[i] += content
  324. def hists_to_table(hists, row_labels=(), column_labels=(), format="{:.2f}"):
  325. table = ['<table class="table table-condensed">']
  326. if column_labels:
  327. table.append('<thead><tr>')
  328. if row_labels:
  329. table.append('<th></th>')
  330. table.extend(f'<th>{label}</th>' for label in column_labels)
  331. table.append('</tr></thead>')
  332. table.append('<tbody>\n')
  333. for row_label, (vals, *_) in zip_longest(row_labels, hists):
  334. table.append('<tr>')
  335. if row_label:
  336. table.append(f'<td><strong>{row_label}</strong></td>')
  337. table.extend(('<td>'+format.format(val)+'</td>') for val in vals)
  338. table.append('</tr>\n')
  339. table.append('</tbody></table>')
  340. return ''.join(table)