plotter.py 15 KB

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