plotter.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. #!/usr/bin/env python3
  2. from collections import defaultdict
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. from markdown import Markdown
  6. import latexipy as lp
  7. from filval.histogram_utils import (hist, hist2d, hist_bin_centers, hist_fit,
  8. hist_normalize, hist_stats)
  9. __all__ = ['Plot',
  10. 'decl_plot',
  11. 'grid_plot',
  12. 'save_plots',
  13. 'hist_plot',
  14. 'hist2d_plot']
  15. class Plot:
  16. def __init__(self, subplots, name, title=None, docs="N/A", argdicts={}):
  17. self.subplots = subplots
  18. self.name = name
  19. self.title = title
  20. self.docs = docs
  21. self.argdicts = argdicts
  22. MD = Markdown(extensions=['mdx_math'],
  23. extension_configs={'mdx_math': {'enable_dollar_delimiter': True}})
  24. lp.latexify(params={'pgf.texsystem': 'pdflatex',
  25. 'text.usetex': True,
  26. 'font.family': 'serif',
  27. 'pgf.preamble': [],
  28. 'font.size': 15,
  29. 'axes.labelsize': 15,
  30. 'axes.titlesize': 13,
  31. 'legend.fontsize': 13,
  32. 'xtick.labelsize': 11,
  33. 'ytick.labelsize': 11,
  34. 'figure.dpi': 150,
  35. 'savefig.transparent': False,
  36. },
  37. new_backend='TkAgg')
  38. def _fn_call_to_dict(fn, *args, **kwargs):
  39. from inspect import signature
  40. pnames = list(signature(fn).parameters)
  41. pvals = list(args)+list(kwargs.values())
  42. return {k: v for k, v in zip(pnames, pvals)}
  43. def _process_docs(fn):
  44. from inspect import getdoc
  45. raw = getdoc(fn)
  46. if raw:
  47. return MD.convert(raw)
  48. else:
  49. return None
  50. def decl_plot(fn):
  51. from functools import wraps
  52. @wraps(fn)
  53. def f(*args, **kwargs):
  54. fn(*args, **kwargs)
  55. argdict = _fn_call_to_dict(fn, *args, **kwargs)
  56. docs = _process_docs(fn)
  57. return argdict, docs
  58. return f
  59. def _add_stats(hist, title=''):
  60. fmt = r'''\begin{{eqnarray*}}
  61. \sum{{x_i}} &=& {sum:5.3f} \\
  62. \sum{{\Delta x_i \cdot x_i}} &=& {int:5.3G} \\
  63. \mu &=& {mean:5.3G} \\
  64. \sigma^2 &=& {var:5.3G} \\
  65. \sigma &=& {std:5.3G}
  66. \end{{eqnarray*}}'''
  67. txt = fmt.format(**hist_stats(hist), title=title)
  68. txt = txt.replace('\n', ' ')
  69. plt.text(0.7, 0.9, txt,
  70. bbox={'facecolor': 'white',
  71. 'alpha': 0.7,
  72. 'boxstyle': 'square,pad=0.8'},
  73. transform=plt.gca().transAxes,
  74. verticalalignment='top',
  75. horizontalalignment='left',
  76. size='small')
  77. if title:
  78. plt.text(0.72, 0.97, title,
  79. bbox={'facecolor': 'white',
  80. 'alpha': 0.8},
  81. transform=plt.gca().transAxes,
  82. verticalalignment='top',
  83. horizontalalignment='left')
  84. def grid_plot(subplots):
  85. if any(len(row) != len(subplots[0]) for row in subplots):
  86. raise ValueError("make_plot requires a rectangular list-of-lists as "
  87. "input. Fill empty slots with None")
  88. def calc_rowspan(fig, row, col):
  89. span = 1
  90. for r in range(row+1, len(fig)):
  91. if fig[r][col] == "FU":
  92. span += 1
  93. else:
  94. break
  95. return span
  96. def calc_colspan(fig, row, col):
  97. span = 1
  98. for c in range(col+1, len(fig[row])):
  99. if fig[row][c] == "FL":
  100. span += 1
  101. else:
  102. break
  103. return span
  104. rows = len(subplots)
  105. cols = len(subplots[0])
  106. argdicts = defaultdict(list)
  107. docs = defaultdict(list)
  108. for i in range(rows):
  109. for j in range(cols):
  110. cell = subplots[i][j]
  111. if cell in ("FL", "FU", None):
  112. continue
  113. if not isinstance(cell, list):
  114. cell = [cell]
  115. colspan = calc_colspan(subplots, i, j)
  116. rowspan = calc_rowspan(subplots, i, j)
  117. plt.subplot2grid((rows, cols), (i, j),
  118. colspan=colspan, rowspan=rowspan)
  119. for plot in cell:
  120. plot_fn, args, kwargs = plot
  121. this_args, this_docs = plot_fn(*args, **kwargs)
  122. argdicts[(i, j)].append(this_args)
  123. docs[(i, j)].append(this_docs)
  124. return argdicts, docs
  125. def save_plots(plots, exts=['png'], scale=1.0):
  126. for plot in plots:
  127. print(f'Building plot {plot.name}')
  128. with lp.figure(plot.name, directory='output/figures',
  129. exts=exts,
  130. size=(scale*10, scale*10)):
  131. argdicts, docs = grid_plot(plot.subplots)
  132. plot.argdicts = argdicts
  133. plot.docs = docs
  134. def add_decorations(axes, luminosity, energy):
  135. cms_prelim = r'{\raggedright{}\textsf{\textbf{CMS}}\\ \emph{Preliminary}}'
  136. axes.text(0.01, 0.98, cms_prelim,
  137. horizontalalignment='left',
  138. verticalalignment='top',
  139. transform=axes.transAxes)
  140. lumi = ""
  141. energy_str = ""
  142. if luminosity is not None:
  143. lumi = r'${} \mathrm{{fb}}^{{-1}}$'.format(luminosity)
  144. if energy is not None:
  145. energy_str = r'({} TeV)'.format(energy)
  146. axes.text(1, 1, ' '.join([lumi, energy_str]),
  147. horizontalalignment='right',
  148. verticalalignment='bottom',
  149. transform=axes.transAxes)
  150. def hist_plot(h, *args, axes=None, norm=None, include_errors=False,
  151. log=False, fig=None, xlim=None, ylim=None, fit=None,
  152. grid=False, stats=True, **kwargs):
  153. """ Plots a 1D ROOT histogram object using matplotlib """
  154. from inspect import signature
  155. if norm:
  156. h = hist_normalize(h, norm)
  157. values, errors, edges = h
  158. scale = 1. if norm is None else norm/np.sum(values)
  159. values = [val*scale for val in values]
  160. errors = [val*scale for val in errors]
  161. left, right = np.array(edges[:-1]), np.array(edges[1:])
  162. X = np.array([left, right]).T.flatten()
  163. Y = np.array([values, values]).T.flatten()
  164. if axes is None:
  165. import matplotlib.pyplot as plt
  166. axes = plt.gca()
  167. axes.set_xlabel(kwargs.pop('xlabel', ''))
  168. axes.set_ylabel(kwargs.pop('ylabel', ''))
  169. title = kwargs.pop('title', '')
  170. if xlim is not None:
  171. axes.set_xlim(xlim)
  172. if ylim is not None:
  173. axes.set_ylim(ylim)
  174. # elif not log:
  175. # axes.set_ylim((0, None))
  176. axes.plot(X, Y, *args, linewidth=1, **kwargs)
  177. if include_errors:
  178. axes.errorbar(hist_bin_centers(h), values, yerr=errors,
  179. color='k', marker=None, linestyle='None',
  180. barsabove=True, elinewidth=.7, capsize=1)
  181. if log:
  182. axes.set_yscale('log')
  183. if fit:
  184. f, p0 = fit
  185. popt, pcov = hist_fit(h, f, p0)
  186. fit_xs = np.linspace(X[0], X[-1], 100)
  187. fit_ys = f(fit_xs, *popt)
  188. axes.plot(fit_xs, fit_ys, '--g')
  189. arglabels = list(signature(f).parameters)[1:]
  190. label_txt = "\n".join('{:7s}={: 0.2G}'.format(label, value)
  191. for label, value in zip(arglabels, popt))
  192. axes.text(0.60, 0.95, label_txt, va='top', transform=axes.transAxes,
  193. fontsize='medium', family='monospace', usetex=False)
  194. if stats:
  195. _add_stats(h, title)
  196. else:
  197. axes.set_title(title)
  198. axes.grid(grid, color='#E0E0E0')
  199. def hist2d_plot(h, *args, axes=None, **kwargs):
  200. """ Plots a 2D ROOT histogram object using matplotlib """
  201. try:
  202. values, errors, xs, ys = h
  203. except (TypeError, ValueError):
  204. values, errors, xs, ys = hist2d(h)
  205. if axes is None:
  206. import matplotlib.pyplot as plt
  207. axes = plt.gca()
  208. axes.set_xlabel(kwargs.pop('xlabel', ''))
  209. axes.set_ylabel(kwargs.pop('ylabel', ''))
  210. axes.set_title(kwargs.pop('title', ''))
  211. axes.pcolormesh(xs, ys, values,)
  212. # axes.colorbar() TODO: Re-enable this
  213. class StackHist:
  214. def __init__(self, title=""):
  215. raise NotImplementedError("need to fix to not use to_bin_list")
  216. self.title = title
  217. self.xlabel = ""
  218. self.ylabel = ""
  219. self.xlim = (None, None)
  220. self.ylim = (None, None)
  221. self.logx = False
  222. self.logy = False
  223. self.backgrounds = []
  224. self.signal = None
  225. self.signal_stack = True
  226. self.data = None
  227. def add_mc_background(self, th1, label, lumi=None, plot_color=''):
  228. self.backgrounds.append((label, lumi, hist(th1), plot_color))
  229. def set_mc_signal(self, th1, label, lumi=None, stack=True, scale=1, plot_color=''):
  230. self.signal = (label, lumi, hist(th1), plot_color)
  231. self.signal_stack = stack
  232. self.signal_scale = scale
  233. def set_data(self, th1, lumi=None, plot_color=''):
  234. self.data = ('data', lumi, hist(th1), plot_color)
  235. self.luminosity = lumi
  236. def _verify_binning_match(self):
  237. bins_count = [len(bins) for _, _, bins, _ in self.backgrounds]
  238. if self.signal is not None:
  239. bins_count.append(len(self.signal[2]))
  240. if self.data is not None:
  241. bins_count.append(len(self.data[2]))
  242. n_bins = bins_count[0]
  243. if any(bin_count != n_bins for bin_count in bins_count):
  244. raise ValueError("all histograms must have the same number of bins")
  245. self.n_bins = n_bins
  246. def save(self, filename, **kwargs):
  247. import matplotlib.pyplot as plt
  248. plt.ioff()
  249. fig = plt.figure()
  250. ax = fig.gca()
  251. self.do_draw(ax, **kwargs)
  252. fig.savefig("figures/"+filename, transparent=True)
  253. plt.close(fig)
  254. plt.ion()
  255. def do_draw(self, axes):
  256. self.axeses = [axes]
  257. self._verify_binning_match()
  258. bottoms = [0]*self.n_bins
  259. if self.logx:
  260. axes.set_xscale('log')
  261. if self.logy:
  262. axes.set_yscale('log')
  263. def draw_bar(label, lumi, bins, plot_color, scale=1, stack=True, **kwargs):
  264. if stack:
  265. lefts = []
  266. widths = []
  267. heights = []
  268. for left, right, content in bins:
  269. lefts.append(left)
  270. widths.append(right-left)
  271. if lumi is not None:
  272. content *= self.luminosity/lumi
  273. content *= scale
  274. heights.append(content)
  275. axes.bar(lefts, heights, widths, bottoms, label=label, color=plot_color, **kwargs)
  276. for i, (_, _, content) in enumerate(bins):
  277. if lumi is not None:
  278. content *= self.luminosity/lumi
  279. content *= scale
  280. bottoms[i] += content
  281. else:
  282. xs = [bins[0][0] - (bins[0][1]-bins[0][0])/2]
  283. ys = [0]
  284. for left, right, content in bins:
  285. width2 = (right-left)/2
  286. if lumi is not None:
  287. content *= self.luminosity/lumi
  288. content *= scale
  289. xs.append(left-width2)
  290. ys.append(content)
  291. xs.append(right-width2)
  292. ys.append(content)
  293. xs.append(bins[-1][0] + (bins[-1][1]-bins[-1][0])/2)
  294. ys.append(0)
  295. axes.plot(xs, ys, label=label, color=plot_color, **kwargs)
  296. if self.signal is not None and self.signal_stack:
  297. label, lumi, bins, plot_color = self.signal
  298. if self.signal_scale != 1:
  299. label = r"{}$\times{:d}$".format(label, self.signal_scale)
  300. draw_bar(label, lumi, bins, plot_color, scale=self.signal_scale, hatch='/')
  301. for background in self.backgrounds:
  302. draw_bar(*background)
  303. if self.signal is not None and not self.signal_stack:
  304. # draw_bar(*self.signal, stack=False, color='k')
  305. label, lumi, bins, plot_color = self.signal
  306. if self.signal_scale != 1:
  307. label = r"{}$\times{:d}$".format(label, self.signal_scale)
  308. draw_bar(label, lumi, bins, plot_color, scale=self.signal_scale, stack=False)
  309. axes.set_title(self.title)
  310. axes.set_xlabel(self.xlabel)
  311. axes.set_ylabel(self.ylabel)
  312. axes.set_xlim(*self.xlim)
  313. # axes.set_ylim(*self.ylim)
  314. if self.logy:
  315. axes.set_ylim(None, np.exp(np.log(max(bottoms))*1.4))
  316. else:
  317. axes.set_ylim(None, max(bottoms)*1.2)
  318. axes.legend(frameon=True, ncol=2)
  319. add_decorations(axes, self.luminosity, self.energy)
  320. def draw(self, axes, save=False, filename=None, **kwargs):
  321. self.do_draw(axes, **kwargs)
  322. if save:
  323. if filename is None:
  324. filename = "".join(c for c in self.title if c.isalnum() or c in (' ._+-'))+".png"
  325. self.save(filename, **kwargs)
  326. class StackHistWithSignificance(StackHist):
  327. def __init__(self, *args, **kwargs):
  328. super().__init__(*args, **kwargs)
  329. def do_draw(self, axes, bin_significance=True, low_cut_significance=False, high_cut_significance=False):
  330. bottom_box, _, top_box = axes.get_position().splity(0.28, 0.30)
  331. axes.set_position(top_box)
  332. super().do_draw(axes)
  333. axes.set_xticks([])
  334. rhs_color = '#cc6600'
  335. bottom = axes.get_figure().add_axes(bottom_box)
  336. bottom_rhs = bottom.twinx()
  337. bgs = [0]*self.n_bins
  338. for (_, _, bins, _) in self.backgrounds:
  339. for i, (left, right, value) in enumerate(bins):
  340. bgs[i] += value
  341. sigs = [0]*self.n_bins
  342. if bin_significance:
  343. xs = []
  344. for i, (left, right, value) in enumerate(self.signal[2]):
  345. sigs[i] += value
  346. xs.append(left)
  347. xs, ys = zip(*[(x, sig/(sig+bg)) for x, sig, bg in zip(xs, sigs, bgs) if (sig+bg) > 0])
  348. bottom.plot(xs, ys, '.k')
  349. if high_cut_significance:
  350. # s/(s+b) for events passing a minimum cut requirement
  351. min_bg = [sum(bgs[i:]) for i in range(self.n_bins)]
  352. min_sig = [sum(sigs[i:]) for i in range(self.n_bins)]
  353. min_xs, min_ys = zip(*[(x, sig/np.sqrt(sig+bg)) for x, sig, bg in zip(xs, min_sig, min_bg)
  354. if (sig+bg) > 0])
  355. bottom_rhs.plot(min_xs, min_ys, '->', color=rhs_color)
  356. if low_cut_significance:
  357. # s/(s+b) for events passing a maximum cut requirement
  358. max_bg = [sum(bgs[:i]) for i in range(self.n_bins)]
  359. max_sig = [sum(sigs[:i]) for i in range(self.n_bins)]
  360. max_xs, max_ys = zip(*[(x, sig/np.sqrt(sig+bg)) for x, sig, bg in zip(xs, max_sig, max_bg)
  361. if (sig+bg) > 0])
  362. bottom_rhs.plot(max_xs, max_ys, '-<', color=rhs_color)
  363. bottom.set_ylabel(r'$S/(S+B)$')
  364. bottom.set_xlim(axes.get_xlim())
  365. bottom.set_ylim((0, 1.1))
  366. if low_cut_significance or high_cut_significance:
  367. bottom_rhs.set_ylabel(r'$S/\sqrt{S+B}$')
  368. bottom_rhs.yaxis.label.set_color(rhs_color)
  369. bottom_rhs.tick_params(axis='y', colors=rhs_color, size=4, width=1.5)
  370. # bottom.grid()
  371. if __name__ == '__main__':
  372. import matplotlib.pyplot as plt
  373. from utils import ResultSet
  374. rs_TTZ = ResultSet("TTZ", "../data/TTZToLLNuNu_treeProducerSusyMultilepton_tree.root")
  375. rs_TTW = ResultSet("TTW", "../data/TTWToLNu_treeProducerSusyMultilepton_tree.root")
  376. rs_TTH = ResultSet("TTH", "../data/TTHnobb_mWCutfix_ext1_treeProducerSusyMultilepton_tree.root")
  377. rs_TTTT = ResultSet("TTTT", "../data/TTTT_ext_treeProducerSusyMultilepton_tree.root")
  378. sh = StackHist('B-Jet Multiplicity')
  379. sh.add_mc_background(rs_TTZ.b_jet_count, 'TTZ', lumi=40)
  380. sh.add_mc_background(rs_TTW.b_jet_count, 'TTW', lumi=40)
  381. sh.add_mc_background(rs_TTH.b_jet_count, 'TTH', lumi=40)
  382. sh.set_mc_signal(rs_TTTT.b_jet_count, 'TTTT', lumi=40, scale=10)
  383. sh.luminosity = 40
  384. sh.energy = 13
  385. sh.xlabel = 'B-Jet Count'
  386. sh.ylabel = r'\# Events'
  387. sh.xlim = (-.5, 9.5)
  388. sh.signal_stack = False
  389. fig = plt.figure()
  390. sh.draw(fig.gca())
  391. plt.show()
  392. # sh.add_data(rs_TTZ.b_jet_count, 'TTZ')