utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import io
  2. import os
  3. import sys
  4. import itertools as it
  5. from os.path import dirname, join, abspath, normpath, getctime
  6. from math import ceil, floor, sqrt
  7. from collections import deque
  8. from subprocess import run, PIPE
  9. from IPython.display import Image
  10. import pydotplus.graphviz as pdp
  11. import ROOT
  12. from graph_vals import parse
  13. PRJ_PATH = normpath(join(dirname(abspath(__file__)), "../"))
  14. EXE_PATH = join(PRJ_PATH, "build/main")
  15. PDG = {1: 'd', -1: 'd̄',
  16. 2: 'u', -2: 'ū',
  17. 3: 's', -3: 's̄',
  18. 4: 'c', -4: 'c̄',
  19. 5: 'b', -5: 'b̄',
  20. 6: 't', -6: 't̄',
  21. 11: 'e-', -11: 'e+',
  22. 12: 'ν_e', -12: 'ῡ_e',
  23. 13: 'μ-', -13: 'μ+',
  24. 14: 'ν_μ', -14: 'ῡ_μ',
  25. 15: 'τ-', -15: 'τ+',
  26. 16: 'ν_τ', -16: 'ῡ_τ',
  27. 21: 'gluon',
  28. 22: 'γ',
  29. 23: 'Z0',
  30. 24: 'W+', -24: 'W-',
  31. 25: 'H',
  32. }
  33. SINGLE_PLOT_SIZE = (600, 450)
  34. MAX_WIDTH = 1800
  35. SCALE = .75
  36. CAN_SIZE_DEF = (int(1600*SCALE), int(1200*SCALE))
  37. CANVAS = ROOT.TCanvas("c1", "", *CAN_SIZE_DEF)
  38. ROOT.gStyle.SetPalette(112) # set the "virdidis" color map
  39. VALUES = {}
  40. def clear():
  41. CANVAS.Clear()
  42. CANVAS.SetCanvasSize(*CAN_SIZE_DEF)
  43. def get_color(val, max_val, min_val = 0):
  44. val = (val-min_val)/(max_val-min_val)
  45. val = round(val * (ROOT.gStyle.GetNumberOfColors()-1))
  46. col_idx = ROOT.gStyle.GetColorPalette(val)
  47. col = ROOT.gROOT.GetColor(col_idx)
  48. r = floor(256*col.GetRed())
  49. g = floor(256*col.GetGreen())
  50. b = floor(256*col.GetBlue())
  51. gs = (r + g + b)//3
  52. text_color = 'white' if gs < 100 else 'black'
  53. return '#{:02x}{:02x}{:02x}'.format(r, g, b), text_color
  54. def show_event(dataset, idx):
  55. ids = list(dataset.GenPart_pdgId[idx])
  56. stats = list(dataset.GenPart_status[idx])
  57. energies = list(dataset.GenPart_energy[idx])
  58. links = list(dataset.GenPart_motherIndex[idx])
  59. max_energy = max(energies)
  60. g = pdp.Dot()
  61. for i, id_ in enumerate(ids):
  62. color, text_color = get_color(energies[i], max_energy)
  63. shape = "ellipse" if stats[i] in (1, 23) else "invhouse"
  64. label = "{}({})".format(PDG[id_], stats[i])
  65. # label = PDG[id_]+"({:03e})".format(energies[i])
  66. g.add_node(pdp.Node(str(i), label=label,
  67. style="filled",
  68. shape=shape,
  69. fontcolor=text_color,
  70. fillcolor=color))
  71. for i, mother in enumerate(links):
  72. if mother != -1:
  73. g.add_edge(pdp.Edge(str(mother), str(i)))
  74. return Image(g.create_gif())
  75. def show_value(container):
  76. if type(container) != str:
  77. container = container.GetName().split(':')[1]
  78. g = parse(VALUES[container], container)
  79. return Image(g.create_gif())
  80. class OutputCapture:
  81. def __init__(self):
  82. self.my_stdout = io.StringIO()
  83. self.my_stderr = io.StringIO()
  84. def get_stdout(self):
  85. self.my_stdout.seek(0)
  86. return self.my_stdout.read()
  87. def get_stderr(self):
  88. self.my_stderr.seek(0)
  89. return self.my_stderr.read()
  90. def __enter__(self):
  91. self.stdout = sys.stdout
  92. self.stderr = sys.stderr
  93. sys.stdout = self.my_stdout
  94. sys.stderr = self.my_stderr
  95. def __exit__(self, *args):
  96. sys.stdout = self.stdout
  97. sys.stderr = self.stderr
  98. self.stdout = None
  99. self.stderr = None
  100. def normalize_columns(hist2d):
  101. normHist = ROOT.TH2D(hist2d)
  102. cols, rows = hist2d.GetNbinsX(), hist2d.GetNbinsY()
  103. for col in range(1, cols+1):
  104. sum_ = 0
  105. for row in range(1, rows+1):
  106. sum_ += hist2d.GetBinContent(col, row)
  107. if sum_ == 0:
  108. continue
  109. for row in range(1, rows+1):
  110. norm = hist2d.GetBinContent(col, row) / sum_
  111. normHist.SetBinContent(col, row, norm)
  112. return normHist
  113. class HistCollection:
  114. def __init__(self, sample_name, input_filename):
  115. self.sample_name = sample_name
  116. self.input_filename = input_filename
  117. self.output_filename = self.input_filename.replace(".root", "_result.root")
  118. self.conditional_recompute()
  119. self.load_objects()
  120. HistCollection.add_collection(self)
  121. def conditional_recompute(self):
  122. def recompute():
  123. print("Running analysis for sample: ", self.sample_name)
  124. if run([EXE_PATH, "-s", "-f", self.input_filename]).returncode != 0:
  125. raise RuntimeError(("Failed running analysis code."
  126. " See log file for more information"))
  127. if run(["make"], cwd=join(PRJ_PATH, "build"), stdout=PIPE, stderr=PIPE).returncode != 0:
  128. raise RuntimeError("Failed recompiling analysis code")
  129. if (not os.path.isfile(self.output_filename) or (getctime(EXE_PATH) > getctime(self.output_filename))):
  130. recompute()
  131. else:
  132. print("Loading unchanged result file ", self.output_filename)
  133. def load_objects(self):
  134. file = ROOT.TFile.Open(self.output_filename)
  135. l = file.GetListOfKeys()
  136. self.map = {}
  137. VALUES.update(dict(file.Get("_value_lookup")))
  138. for i in range(l.GetSize()):
  139. name = l.At(i).GetName()
  140. new_name = ":".join((self.sample_name, name))
  141. obj = file.Get(name)
  142. try:
  143. obj.SetName(new_name)
  144. obj.SetDirectory(0) # disconnects Object from file
  145. except AttributeError:
  146. pass
  147. self.map[name] = obj
  148. setattr(self, name, obj)
  149. file.Close()
  150. # Now add these histograms into the current ROOT directory (in memory)
  151. # and remove old versions if needed
  152. for obj in self.map.values():
  153. try:
  154. old_obj = ROOT.gDirectory.Get(obj.GetName())
  155. ROOT.gDirectory.Remove(old_obj)
  156. ROOT.gDirectory.Add(obj)
  157. except AttributeError:
  158. pass
  159. @classmethod
  160. def calc_shape(cls, n_plots):
  161. if n_plots*SINGLE_PLOT_SIZE[0] > MAX_WIDTH:
  162. shape_x = MAX_WIDTH//SINGLE_PLOT_SIZE[0]
  163. shape_y = ceil(n_plots / shape_x)
  164. return (shape_x, shape_y)
  165. else:
  166. return (n_plots, 1)
  167. def draw(self, shape=None):
  168. objs = [obj for obj in self.map.values() if hasattr(obj, "Draw")]
  169. if shape is None:
  170. n_plots = len(objs)
  171. shape = self.calc_shape(n_plots)
  172. CANVAS.Clear()
  173. CANVAS.SetCanvasSize(shape[0]*SINGLE_PLOT_SIZE[0], shape[1]*SINGLE_PLOT_SIZE[1])
  174. CANVAS.Divide(*shape)
  175. i = 1
  176. for hist in objs:
  177. CANVAS.cd(i)
  178. try:
  179. hist.SetStats(False)
  180. except AttributeError:
  181. pass
  182. if type(hist) in (ROOT.TH1I, ROOT.TH1F, ROOT.TH1D):
  183. hist.SetMinimum(0)
  184. hist.Draw(self.get_draw_option(hist))
  185. i += 1
  186. CANVAS.Draw()
  187. @staticmethod
  188. def get_draw_option(obj):
  189. obj_type = type(obj)
  190. if obj_type in (ROOT.TH1F, ROOT.TH1I, ROOT.TH1D):
  191. return ""
  192. elif obj_type in (ROOT.TH2F, ROOT.TH2I, ROOT.TH2D):
  193. return "COLZ"
  194. elif obj_type in (ROOT.TGraph,):
  195. return "A*"
  196. else:
  197. return None
  198. @classmethod
  199. def get_hist_set(cls, attrname):
  200. labels, hists = zip(*[(sample_name, getattr(h, attrname))
  201. for sample_name, h in cls.collections.items()])
  202. return labels, hists
  203. @classmethod
  204. def add_collection(cls, hc):
  205. if not hasattr(cls, "collections"):
  206. cls.collections = {}
  207. cls.collections[hc.sample_name] = hc
  208. @classmethod
  209. def stack_hist(cls,
  210. hist_name,
  211. title="",
  212. enable_fill=False,
  213. normalize_to=0,
  214. draw=False,
  215. draw_canvas=True,
  216. draw_option="",
  217. make_legend=False,
  218. _stacks={}):
  219. labels, hists = cls.get_hist_set(hist_name)
  220. if draw_canvas:
  221. CANVAS.Clear()
  222. CANVAS.SetCanvasSize(SINGLE_PLOT_SIZE[0],
  223. SINGLE_PLOT_SIZE[1])
  224. colors = it.cycle([ROOT.kRed, ROOT.kBlue, ROOT.kGreen])
  225. stack = ROOT.THStack(hist_name+"_stack", title)
  226. if labels is None:
  227. labels = [hist.GetName() for hist in hists]
  228. if type(normalize_to) in (int, float):
  229. normalize_to = [normalize_to]*len(hists)
  230. ens = enumerate(zip(hists, labels, colors, normalize_to))
  231. for i, (hist, label, color, norm) in ens:
  232. hist_copy = hist
  233. hist_copy = hist.Clone(hist.GetName()+"_clone" + draw_option)
  234. hist_copy.SetTitle(label)
  235. if enable_fill:
  236. hist_copy.SetFillColorAlpha(color, 0.75)
  237. hist_copy.SetLineColorAlpha(color, 0.75)
  238. if norm:
  239. integral = hist_copy.Integral()
  240. hist_copy.Scale(norm/integral, "nosw2")
  241. hist_copy.SetStats(True)
  242. stack.Add(hist_copy)
  243. if draw:
  244. stack.Draw(draw_option)
  245. if make_legend:
  246. CANVAS.BuildLegend(0.75, 0.75, 0.95, 0.95, "")
  247. # prevent stack from getting garbage collected
  248. _stacks[stack.GetName()] = stack
  249. if draw_canvas:
  250. CANVAS.Draw()
  251. return stack
  252. @classmethod
  253. def stack_hist_array(cls,
  254. hist_names,
  255. titles,
  256. shape=None, **kwargs):
  257. n_hist = len(hist_names)
  258. if shape is None:
  259. if n_hist <= 4:
  260. shape = (1, n_hist)
  261. else:
  262. shape = (ceil(sqrt(n_hist)),)*2
  263. CANVAS.SetCanvasSize(SINGLE_PLOT_SIZE[0]*shape[0],
  264. SINGLE_PLOT_SIZE[1]*shape[1])
  265. CANVAS.Divide(*shape)
  266. for i, hist_name, title in zip(range(1, n_hist+1), hist_names, titles):
  267. CANVAS.cd(i)
  268. cls.stack_hist(hist_name, title=title, draw=True,
  269. draw_canvas=False, **kwargs)
  270. CANVAS.cd(n_hist).BuildLegend(0.75, 0.75, 0.95, 0.95, "")
  271. pts = deque([], 50)
  272. @classmethod
  273. def hist_array_single(cls,
  274. hist_name,
  275. title=None,
  276. **kwargs):
  277. n_hist = len(cls.collections)
  278. shape = cls.calc_shape(n_hist)
  279. CANVAS.SetCanvasSize(SINGLE_PLOT_SIZE[0]*shape[0],
  280. SINGLE_PLOT_SIZE[1]*shape[1])
  281. CANVAS.Divide(*shape)
  282. labels, hists = cls.get_hist_set(hist_name)
  283. def pave_loc():
  284. hist.Get
  285. for i, label, hist in zip(range(1, n_hist+1), labels, hists):
  286. CANVAS.cd(i)
  287. hist.SetStats(False)
  288. hist.Draw(cls.get_draw_option(hist))
  289. pt = ROOT.TPaveText(0.70, 0.87, 0.85, 0.95, "NDC")
  290. pt.AddText("Dataset: "+label)
  291. pt.Draw()
  292. cls.pts.append(pt)