utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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: 'g',
  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. try:
  80. return Image(g.create_gif())
  81. except Exception as e:
  82. print(e)
  83. print(g.to_string())
  84. class OutputCapture:
  85. def __init__(self):
  86. self.my_stdout = io.StringIO()
  87. self.my_stderr = io.StringIO()
  88. def get_stdout(self):
  89. self.my_stdout.seek(0)
  90. return self.my_stdout.read()
  91. def get_stderr(self):
  92. self.my_stderr.seek(0)
  93. return self.my_stderr.read()
  94. def __enter__(self):
  95. self.stdout = sys.stdout
  96. self.stderr = sys.stderr
  97. sys.stdout = self.my_stdout
  98. sys.stderr = self.my_stderr
  99. def __exit__(self, *args):
  100. sys.stdout = self.stdout
  101. sys.stderr = self.stderr
  102. self.stdout = None
  103. self.stderr = None
  104. def normalize_columns(hist2d):
  105. normHist = ROOT.TH2D(hist2d)
  106. cols, rows = hist2d.GetNbinsX(), hist2d.GetNbinsY()
  107. for col in range(1, cols+1):
  108. sum_ = 0
  109. for row in range(1, rows+1):
  110. sum_ += hist2d.GetBinContent(col, row)
  111. if sum_ == 0:
  112. continue
  113. for row in range(1, rows+1):
  114. norm = hist2d.GetBinContent(col, row) / sum_
  115. normHist.SetBinContent(col, row, norm)
  116. return normHist
  117. class HistCollection:
  118. def __init__(self, sample_name, input_filename):
  119. self.sample_name = sample_name
  120. self.input_filename = input_filename
  121. self.output_filename = self.input_filename.replace(".root", "_result.root")
  122. self.conditional_recompute()
  123. self.load_objects()
  124. HistCollection.add_collection(self)
  125. def conditional_recompute(self):
  126. def recompute():
  127. print("Running analysis for sample: ", self.sample_name)
  128. if run([EXE_PATH, "-s", "-f", self.input_filename]).returncode != 0:
  129. raise RuntimeError(("Failed running analysis code."
  130. " See log file for more information"))
  131. if run(["make"], cwd=join(PRJ_PATH, "build"), stdout=PIPE, stderr=PIPE).returncode != 0:
  132. raise RuntimeError("Failed recompiling analysis code")
  133. if (not os.path.isfile(self.output_filename) or (getctime(EXE_PATH) > getctime(self.output_filename))):
  134. recompute()
  135. else:
  136. print("Loading unchanged result file ", self.output_filename)
  137. def load_objects(self):
  138. file = ROOT.TFile.Open(self.output_filename)
  139. l = file.GetListOfKeys()
  140. self.map = {}
  141. VALUES.update(dict(file.Get("_value_lookup")))
  142. for i in range(l.GetSize()):
  143. name = l.At(i).GetName()
  144. new_name = ":".join((self.sample_name, name))
  145. obj = file.Get(name)
  146. try:
  147. obj.SetName(new_name)
  148. obj.SetDirectory(0) # disconnects Object from file
  149. except AttributeError:
  150. pass
  151. self.map[name] = obj
  152. setattr(self, name, obj)
  153. file.Close()
  154. # Now add these histograms into the current ROOT directory (in memory)
  155. # and remove old versions if needed
  156. for obj in self.map.values():
  157. try:
  158. old_obj = ROOT.gDirectory.Get(obj.GetName())
  159. ROOT.gDirectory.Remove(old_obj)
  160. ROOT.gDirectory.Add(obj)
  161. except AttributeError:
  162. pass
  163. @classmethod
  164. def calc_shape(cls, n_plots):
  165. if n_plots*SINGLE_PLOT_SIZE[0] > MAX_WIDTH:
  166. shape_x = MAX_WIDTH//SINGLE_PLOT_SIZE[0]
  167. shape_y = ceil(n_plots / shape_x)
  168. return (shape_x, shape_y)
  169. else:
  170. return (n_plots, 1)
  171. def draw(self, shape=None):
  172. objs = [obj for obj in self.map.values() if hasattr(obj, "Draw")]
  173. if shape is None:
  174. n_plots = len(objs)
  175. shape = self.calc_shape(n_plots)
  176. CANVAS.Clear()
  177. CANVAS.SetCanvasSize(shape[0]*SINGLE_PLOT_SIZE[0], shape[1]*SINGLE_PLOT_SIZE[1])
  178. CANVAS.Divide(*shape)
  179. i = 1
  180. for hist in objs:
  181. CANVAS.cd(i)
  182. try:
  183. hist.SetStats(False)
  184. except AttributeError:
  185. pass
  186. if type(hist) in (ROOT.TH1I, ROOT.TH1F, ROOT.TH1D):
  187. hist.SetMinimum(0)
  188. hist.Draw(self.get_draw_option(hist))
  189. i += 1
  190. CANVAS.Draw()
  191. @staticmethod
  192. def get_draw_option(obj):
  193. obj_type = type(obj)
  194. if obj_type in (ROOT.TH1F, ROOT.TH1I, ROOT.TH1D):
  195. return ""
  196. elif obj_type in (ROOT.TH2F, ROOT.TH2I, ROOT.TH2D):
  197. return "COLZ"
  198. elif obj_type in (ROOT.TGraph,):
  199. return "A*"
  200. else:
  201. return None
  202. @classmethod
  203. def get_hist_set(cls, attrname):
  204. labels, hists = zip(*[(sample_name, getattr(h, attrname))
  205. for sample_name, h in cls.collections.items()])
  206. return labels, hists
  207. @classmethod
  208. def add_collection(cls, hc):
  209. if not hasattr(cls, "collections"):
  210. cls.collections = {}
  211. cls.collections[hc.sample_name] = hc
  212. @classmethod
  213. def stack_hist(cls,
  214. hist_name,
  215. title="",
  216. enable_fill=False,
  217. normalize_to=0,
  218. draw=False,
  219. draw_canvas=True,
  220. draw_option="",
  221. make_legend=False,
  222. _stacks={}):
  223. labels, hists = cls.get_hist_set(hist_name)
  224. if draw_canvas:
  225. CANVAS.Clear()
  226. CANVAS.SetCanvasSize(SINGLE_PLOT_SIZE[0],
  227. SINGLE_PLOT_SIZE[1])
  228. colors = it.cycle([ROOT.kRed, ROOT.kBlue, ROOT.kGreen])
  229. stack = ROOT.THStack(hist_name+"_stack", title)
  230. if labels is None:
  231. labels = [hist.GetName() for hist in hists]
  232. if type(normalize_to) in (int, float):
  233. normalize_to = [normalize_to]*len(hists)
  234. ens = enumerate(zip(hists, labels, colors, normalize_to))
  235. for i, (hist, label, color, norm) in ens:
  236. hist_copy = hist
  237. hist_copy = hist.Clone(hist.GetName()+"_clone" + draw_option)
  238. hist_copy.SetTitle(label)
  239. if enable_fill:
  240. hist_copy.SetFillColorAlpha(color, 0.75)
  241. hist_copy.SetLineColorAlpha(color, 0.75)
  242. if norm:
  243. integral = hist_copy.Integral()
  244. hist_copy.Scale(norm/integral, "nosw2")
  245. hist_copy.SetStats(True)
  246. stack.Add(hist_copy)
  247. if draw:
  248. stack.Draw(draw_option)
  249. if make_legend:
  250. CANVAS.BuildLegend(0.75, 0.75, 0.95, 0.95, "")
  251. # prevent stack from getting garbage collected
  252. _stacks[stack.GetName()] = stack
  253. if draw_canvas:
  254. CANVAS.Draw()
  255. return stack
  256. @classmethod
  257. def stack_hist_array(cls,
  258. hist_names,
  259. titles,
  260. shape=None, **kwargs):
  261. n_hist = len(hist_names)
  262. if shape is None:
  263. if n_hist <= 4:
  264. shape = (1, n_hist)
  265. else:
  266. shape = (ceil(sqrt(n_hist)),)*2
  267. CANVAS.SetCanvasSize(SINGLE_PLOT_SIZE[0]*shape[0],
  268. SINGLE_PLOT_SIZE[1]*shape[1])
  269. CANVAS.Divide(*shape)
  270. for i, hist_name, title in zip(range(1, n_hist+1), hist_names, titles):
  271. CANVAS.cd(i)
  272. cls.stack_hist(hist_name, title=title, draw=True,
  273. draw_canvas=False, **kwargs)
  274. CANVAS.cd(n_hist).BuildLegend(0.75, 0.75, 0.95, 0.95, "")
  275. pts = deque([], 50)
  276. @classmethod
  277. def hist_array_single(cls,
  278. hist_name,
  279. title=None,
  280. **kwargs):
  281. n_hist = len(cls.collections)
  282. shape = cls.calc_shape(n_hist)
  283. CANVAS.SetCanvasSize(SINGLE_PLOT_SIZE[0]*shape[0],
  284. SINGLE_PLOT_SIZE[1]*shape[1])
  285. CANVAS.Divide(*shape)
  286. labels, hists = cls.get_hist_set(hist_name)
  287. def pave_loc():
  288. hist.Get
  289. for i, label, hist in zip(range(1, n_hist+1), labels, hists):
  290. CANVAS.cd(i)
  291. hist.SetStats(False)
  292. hist.Draw(cls.get_draw_option(hist))
  293. pt = ROOT.TPaveText(0.70, 0.87, 0.85, 0.95, "NDC")
  294. pt.AddText("Dataset: "+label)
  295. pt.Draw()
  296. cls.pts.append(pt)