plotter.py 9.1 KB

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