plotter.py 10 KB

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