plotting.py 13 KB

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