plotter.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. #!/usr/bin/env python3
  2. import math
  3. import matplotlib as mpl
  4. # mpl.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})
  5. # mpl.rc('font', **{'family': 'serif', 'serif': ['Palatino']})
  6. mpl.rc('text', usetex=True)
  7. mpl.rc('figure', dpi=200)
  8. mpl.rc('savefig', dpi=200)
  9. def add_decorations(axes, luminosity, energy):
  10. cms_prelim = r'{\raggedright{}\textsf{\textbf{CMS}}\\ \emph{Preliminary}}'
  11. axes.text(0.01, 0.98, cms_prelim,
  12. horizontalalignment='left',
  13. verticalalignment='top',
  14. transform=axes.transAxes)
  15. lumi = ""
  16. energy_str = ""
  17. if luminosity is not None:
  18. lumi = r'${} \mathrm{{fb}}^{{-1}}$'.format(luminosity)
  19. if energy is not None:
  20. energy_str = r'({} TeV)'.format(energy)
  21. axes.text(1, 1, ' '.join([lumi, energy_str]),
  22. horizontalalignment='right',
  23. verticalalignment='bottom',
  24. transform=axes.transAxes)
  25. def to_bin_list(th1, include_errors=False):
  26. bins = []
  27. for i in range(th1.GetNbinsX()):
  28. center = th1.GetBinCenter(i + 1)
  29. width = th1.GetBinWidth(i + 1)
  30. content = th1.GetBinContent(i + 1)
  31. if include_errors:
  32. error = th1.GetBinError(i + 1)
  33. bins.append((center-width/2, center+width/2, (content, error)))
  34. else:
  35. bins.append((center-width/2, center+width/2, content))
  36. return bins
  37. def histogram(th1, include_errors=False):
  38. edges = []
  39. values = []
  40. bin_list = to_bin_list(th1, include_errors)
  41. for (l_edge, _, val) in bin_list:
  42. edges.append(l_edge)
  43. values.append(val)
  44. edges.append(bin_list[-1][1])
  45. return values, edges
  46. def plot_histogram(h1, *args, axes=None, norm=None, include_errors=False, **kwargs):
  47. """ Plots a 1D ROOT histogram object using matplotlib """
  48. import numpy as np
  49. bins, edges = histogram(h1, include_errors=include_errors)
  50. if norm is not None:
  51. scale = norm/np.sum(bins)
  52. bins = [(bin*scale, err*scale) for (bin, err) in bins]
  53. bins, errs = list(zip(*bins))
  54. left, right = np.array(edges[:-1]), np.array(edges[1:])
  55. X = np.array([left, right]).T.flatten()
  56. Y = np.array([bins, bins]).T.flatten()
  57. if axes is None:
  58. import matplotlib.pyplot as plt
  59. axes = plt.gca()
  60. axes.set_xlabel(kwargs.pop('xlabel', ''))
  61. axes.set_ylabel(kwargs.pop('ylabel', ''))
  62. axes.set_title(kwargs.pop('title', ''))
  63. axes.plot(X, Y, *args, linewidth=1, **kwargs)
  64. if include_errors:
  65. axes.errorbar(0.5*(left+right), bins, yerr=errs,
  66. color='k', marker=None, linestyle='None',
  67. barsabove=True, elinewidth=.7, capsize=1)
  68. def histogram2d(th2, include_errors=False):
  69. """ converts TH2 object to something amenable to
  70. plotting w/ matplotlab's pcolormesh
  71. """
  72. import numpy as np
  73. nbins_x = th2.GetNbinsX()
  74. nbins_y = th2.GetNbinsY()
  75. xs = np.zeros((nbins_y, nbins_x), np.float64)
  76. ys = np.zeros((nbins_y, nbins_x), np.float64)
  77. zs = np.zeros((nbins_y, nbins_x), np.float64)
  78. for i in range(nbins_x):
  79. for j in range(nbins_y):
  80. xs[j][i] = th2.GetXaxis().GetBinLowEdge(i+1)
  81. ys[j][i] = th2.GetYaxis().GetBinLowEdge(j+1)
  82. zs[j][i] = th2.GetBinContent(i+1, j+1)
  83. return xs, ys, zs
  84. def plot_histogram2d(th2, *args, axes=None, **kwargs):
  85. """ Plots a 2D ROOT histogram object using matplotlib """
  86. if axes is None:
  87. import matplotlib.pyplot as plt
  88. axes = plt.gca()
  89. axes.set_xlabel(kwargs.pop('xlabel', ''))
  90. axes.set_ylabel(kwargs.pop('ylabel', ''))
  91. axes.set_title(kwargs.pop('title', ''))
  92. axes.pcolormesh(*histogram2d(th2))
  93. # axes.colorbar() TODO: Re-enable this
  94. class StackHist:
  95. def __init__(self, title=""):
  96. self.title = title
  97. self.xlabel = ""
  98. self.ylabel = ""
  99. self.xlim = (None, None)
  100. self.ylim = (None, None)
  101. self.logx = False
  102. self.logy = False
  103. self.backgrounds = []
  104. self.signal = None
  105. self.signal_stack = True
  106. self.data = None
  107. def add_mc_background(self, th1, label, lumi=None, plot_color=''):
  108. self.backgrounds.append((label, lumi, to_bin_list(th1), plot_color))
  109. def set_mc_signal(self, th1, label, lumi=None, stack=True, scale=1, plot_color=''):
  110. self.signal = (label, lumi, to_bin_list(th1), plot_color)
  111. self.signal_stack = stack
  112. self.signal_scale = scale
  113. def set_data(self, th1, lumi=None, plot_color=''):
  114. self.data = ('data', lumi, to_bin_list(th1), plot_color)
  115. self.luminosity = lumi
  116. def _verify_binning_match(self):
  117. bins_count = [len(bins) for _, _, bins, _ in self.backgrounds]
  118. if self.signal is not None:
  119. bins_count.append(len(self.signal[2]))
  120. if self.data is not None:
  121. bins_count.append(len(self.data[2]))
  122. n_bins = bins_count[0]
  123. if any(bin_count != n_bins for bin_count in bins_count):
  124. raise ValueError("all histograms must have the same number of bins")
  125. self.n_bins = n_bins
  126. def save(self, filename, **kwargs):
  127. import matplotlib.pyplot as plt
  128. plt.ioff()
  129. fig = plt.figure()
  130. ax = fig.gca()
  131. self.do_draw(ax, **kwargs)
  132. fig.savefig("figures/"+filename, transparent=True)
  133. plt.close(fig)
  134. plt.ion()
  135. def do_draw(self, axes):
  136. self.axeses = [axes]
  137. self._verify_binning_match()
  138. bottoms = [0]*self.n_bins
  139. if self.logx:
  140. axes.set_xscale('log')
  141. if self.logy:
  142. axes.set_yscale('log')
  143. def draw_bar(label, lumi, bins, plot_color, scale=1, stack=True, **kwargs):
  144. if stack:
  145. lefts = []
  146. widths = []
  147. heights = []
  148. for left, right, content in bins:
  149. lefts.append(left)
  150. widths.append(right-left)
  151. if lumi is not None:
  152. content *= self.luminosity/lumi
  153. content *= scale
  154. heights.append(content)
  155. axes.bar(lefts, heights, widths, bottoms, label=label, color=plot_color, **kwargs)
  156. for i, (_, _, content) in enumerate(bins):
  157. if lumi is not None:
  158. content *= self.luminosity/lumi
  159. content *= scale
  160. bottoms[i] += content
  161. else:
  162. xs = [bins[0][0] - (bins[0][1]-bins[0][0])/2]
  163. ys = [0]
  164. for left, right, content in bins:
  165. width2 = (right-left)/2
  166. if lumi is not None:
  167. content *= self.luminosity/lumi
  168. content *= scale
  169. xs.append(left-width2)
  170. ys.append(content)
  171. xs.append(right-width2)
  172. ys.append(content)
  173. xs.append(bins[-1][0] + (bins[-1][1]-bins[-1][0])/2)
  174. ys.append(0)
  175. axes.plot(xs, ys, label=label, color=plot_color, **kwargs)
  176. if self.signal is not None and self.signal_stack:
  177. label, lumi, bins, plot_color = self.signal
  178. if self.signal_scale != 1:
  179. label = r"{}$\times{:d}$".format(label, self.signal_scale)
  180. draw_bar(label, lumi, bins, plot_color, scale=self.signal_scale, hatch='/')
  181. for background in self.backgrounds:
  182. draw_bar(*background)
  183. if self.signal is not None and not self.signal_stack:
  184. # draw_bar(*self.signal, stack=False, color='k')
  185. label, lumi, bins, plot_color = self.signal
  186. if self.signal_scale != 1:
  187. label = r"{}$\times{:d}$".format(label, self.signal_scale)
  188. draw_bar(label, lumi, bins, plot_color, scale=self.signal_scale, stack=False)
  189. axes.set_title(self.title)
  190. axes.set_xlabel(self.xlabel)
  191. axes.set_ylabel(self.ylabel)
  192. axes.set_xlim(*self.xlim)
  193. # axes.set_ylim(*self.ylim)
  194. if self.logy:
  195. axes.set_ylim(None, math.exp(math.log(max(bottoms))*1.4))
  196. else:
  197. axes.set_ylim(None, max(bottoms)*1.2)
  198. axes.legend(frameon=True, ncol=2)
  199. add_decorations(axes, self.luminosity, self.energy)
  200. def draw(self, axes, save=False, filename=None, **kwargs):
  201. self.do_draw(axes, **kwargs)
  202. if save:
  203. if filename is None:
  204. filename = "".join(c for c in self.title if c.isalnum() or c in (' ._+-'))+".png"
  205. self.save(filename, **kwargs)
  206. class StackHistWithSignificance(StackHist):
  207. def __init__(self, *args, **kwargs):
  208. super().__init__(*args, **kwargs)
  209. def do_draw(self, axes, bin_significance=True, low_cut_significance=False, high_cut_significance=False):
  210. bottom_box, _, top_box = axes.get_position().splity(0.28, 0.30)
  211. axes.set_position(top_box)
  212. super().do_draw(axes)
  213. axes.set_xticks([])
  214. rhs_color = '#cc6600'
  215. bottom = axes.get_figure().add_axes(bottom_box)
  216. bottom_rhs = bottom.twinx()
  217. bgs = [0]*self.n_bins
  218. for (_, _, bins, _) in self.backgrounds:
  219. for i, (left, right, value) in enumerate(bins):
  220. bgs[i] += value
  221. sigs = [0]*self.n_bins
  222. if bin_significance:
  223. xs = []
  224. for i, (left, right, value) in enumerate(self.signal[2]):
  225. sigs[i] += value
  226. xs.append(left)
  227. xs, ys = zip(*[(x, sig/(sig+bg)) for x, sig, bg in zip(xs, sigs, bgs) if (sig+bg) > 0])
  228. bottom.plot(xs, ys, '.k')
  229. if high_cut_significance:
  230. # s/(s+b) for events passing a minimum cut requirement
  231. min_bg = [sum(bgs[i:]) for i in range(self.n_bins)]
  232. min_sig = [sum(sigs[i:]) for i in range(self.n_bins)]
  233. min_xs, min_ys = zip(*[(x, sig/math.sqrt(sig+bg)) for x, sig, bg in zip(xs, min_sig, min_bg)
  234. if (sig+bg) > 0])
  235. bottom_rhs.plot(min_xs, min_ys, '->', color=rhs_color)
  236. if low_cut_significance:
  237. # s/(s+b) for events passing a maximum cut requirement
  238. max_bg = [sum(bgs[:i]) for i in range(self.n_bins)]
  239. max_sig = [sum(sigs[:i]) for i in range(self.n_bins)]
  240. max_xs, max_ys = zip(*[(x, sig/math.sqrt(sig+bg)) for x, sig, bg in zip(xs, max_sig, max_bg)
  241. if (sig+bg) > 0])
  242. bottom_rhs.plot(max_xs, max_ys, '-<', color=rhs_color)
  243. bottom.set_ylabel(r'$S/(S+B)$')
  244. bottom.set_xlim(axes.get_xlim())
  245. bottom.set_ylim((0, 1.1))
  246. if low_cut_significance or high_cut_significance:
  247. bottom_rhs.set_ylabel(r'$S/\sqrt{S+B}$')
  248. bottom_rhs.yaxis.label.set_color(rhs_color)
  249. bottom_rhs.tick_params(axis='y', colors=rhs_color, size=4, width=1.5)
  250. # bottom.grid()
  251. if __name__ == '__main__':
  252. import matplotlib.pyplot as plt
  253. from utils import ResultSet
  254. rs_TTZ = ResultSet("TTZ", "../data/TTZToLLNuNu_treeProducerSusyMultilepton_tree.root")
  255. rs_TTW = ResultSet("TTW", "../data/TTWToLNu_treeProducerSusyMultilepton_tree.root")
  256. rs_TTH = ResultSet("TTH", "../data/TTHnobb_mWCutfix_ext1_treeProducerSusyMultilepton_tree.root")
  257. rs_TTTT = ResultSet("TTTT", "../data/TTTT_ext_treeProducerSusyMultilepton_tree.root")
  258. sh = StackHist('B-Jet Multiplicity')
  259. sh.add_mc_background(rs_TTZ.b_jet_count, 'TTZ', lumi=40)
  260. sh.add_mc_background(rs_TTW.b_jet_count, 'TTW', lumi=40)
  261. sh.add_mc_background(rs_TTH.b_jet_count, 'TTH', lumi=40)
  262. sh.set_mc_signal(rs_TTTT.b_jet_count, 'TTTT', lumi=40, scale=10)
  263. sh.luminosity = 40
  264. sh.energy = 13
  265. sh.xlabel = 'B-Jet Count'
  266. sh.ylabel = r'\# Events'
  267. sh.xlim = (-.5, 9.5)
  268. sh.signal_stack = False
  269. fig = plt.figure()
  270. sh.draw(fig.gca())
  271. plt.show()
  272. # sh.add_data(rs_TTZ.b_jet_count, 'TTZ')