plotting.py 14 KB

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