All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
util.py
Go to the documentation of this file.
1 import ROOT
2 import os
3 from array import array
4 import argparse
5 ROOT.PyConfig.IgnoreCommandLineOptions = True
6 ROOT.gStyle.SetOptStat(0)
7 ROOT.TGaxis.SetMaxDigits(3)
8 
9 def root_env():
10  buildpath = os.environ["SBN_LIB_DIR"]
11  if not buildpath:
12  print "ERROR: SBNDDAQ_ANALYSIS_BUILD_PATH not set"
13  sys.exit()
14  ROOT.gROOT.ProcessLine(".L " + buildpath + "/libsbnanalysis_Event.so")
15  ROOT.gROOT.ProcessLine(".L " + buildpath + "/libsbnanalysis_PandoraTesting_classes.so")
16  ROOT.gROOT.ProcessLine(".L " + buildpath + "/libsbnanalysis_SBNOsc_classes.so")
17  ROOT.gROOT.ProcessLine(".L " + buildpath + "/libsbnanalysis_SBNOscReco_classes.so")
18 
19 def wait(args):
20  if args.wait:
21  raw_input("Press Enter to continue...")
22 
23 def write(args, canvas):
24  if args.output:
25  canvas.SaveAs(args.output)
26 
27 def with_input_args(parser):
28  if "INPUTFILE" in os.environ:
29  parser.add_argument("-i", "--input", default=("input", ROOT.TFile(os.environ["INPUTFILE"])), nargs="+", type=filespec, action=FileSpec)
30  else:
31  parser.add_argument("-i", "--input", required=True, nargs="+", type=filespec, action=FileSpec)
32  return parser
33 
34 class FileSpec(argparse.Action):
35  def __call__(self, parser, namespace, values, option_string=None):
36  if values:
37  for key, val in values:
38  setattr(namespace, key, val)
39 
40 def filespec(inp):
41  split = inp.split(":")
42  if len(split) == 1:
43  return ("input", ROOT.TFile(split[0]))
44  else:
45  return (split[0], ROOT.TFile(split[1]))
46 
47 def get_tobject(args, name):
48  if ":" in name:
49  fname = name.split(":")[0]
50  else:
51  fname = "input"
52  return getattr(args, fname).Get(name.split(":")[-1])
53 
54 def with_text_args(parser):
55  parser.add_argument("-txt", "--text", nargs="+", default=None)
56  parser.add_argument("-tp", "--text_position", default=[0.5,0.4, 0.75, 0.6], type=comma_separated)
57  parser.add_argument("-ts", "--text_size", default=30, type=int)
58  parser.add_argument("-tf", "--text_font", default=43, type=int)
59  parser.add_argument("-tc", "--text_color", default=ROOT.kBlack, type=int)
60  return parser
61 
62 def draw_text(args):
63  textbox = None
64  if args.text:
65  textbox = ROOT.TPaveText(*[float(x) for x in args.text_position])
66  textbox.SetOption("NDC")
67  for text in args.text:
68  textbox.AddText(text)
69  textbox.SetMargin(0)
70  textbox.SetBorderSize(0)
71  textbox.SetTextFont(args.text_font)
72  textbox.SetTextSize(args.text_size)
73  textbox.SetTextColor(args.text_color)
74  textbox.SetFillStyle(0)
75  textbox.Draw()
76  return textbox
77 
78 
79 def with_display_args(parser):
80  parser.add_argument("-w", "--wait", action="store_true")
81  parser.add_argument("-o", "--output", default=None)
82  return parser
83 
84 def with_io_args(parser):
85  parser = with_input_args(parser)
86  parser = with_display_args(parser)
87  return parser
88 
89 def with_graphsize_args(parser):
90  parser.add_argument("-xm", "--x_min", type=float, default=None)
91  parser.add_argument("-xh", "--x_max", type=float, default=None)
92 
93  parser.add_argument("-ym", "--y_min", type=float, default=None)
94  parser.add_argument("-yh", "--y_max", type=float, default=None)
95 
96  parser.add_argument("-zm", "--z_min", type=float, default=None)
97  parser.add_argument("-zh", "--z_max", type=float, default=None)
98  return parser
99 
101  parser.add_argument("-rX", "--rebinX", type=int, default=1)
102  parser.add_argument("-rY", "--rebinY", type=int, default=1)
103  parser.add_argument("-rZ", "--rebinZ", type=int, default=1)
104  parser.add_argument("-pX", "--projectionX", action="store_true")
105  parser.add_argument("-pY", "--projectionY", action="store_true")
106  parser.add_argument("-pZ", "--projectionZ", action="store_true")
107  parser.add_argument("-pXY", "--projectionXY", action="store_true")
108  parser.add_argument("-pYZ", "--projectionYZ", action="store_true")
109  parser.add_argument("-pXZ", "--projectionXZ", action="store_true")
110  return with_graphsize_args(parser)
111 
112 def resize_graph(args, hist):
113  if args.range_lo is not None and args.range_hi is not None:
114  hist.GetXaxis().SetLimits(args.range_lo, args.range_hi)
115  if args.y_min is not None and args.y_max is not None:
116  hist.GetYaxis().SetRangeUser(args.y_min, args.y_max)
117 
118 def resize_histo(args, hist, name_postfix=""):
119  histdim = 0
120  if isinstance(hist, ROOT.TH1D): histdim = 1
121  elif isinstance(hist, ROOT.TH2D): histdim = 2
122  elif isinstance(hist, ROOT.TH3D): histdim = 3
123 
124  axes_ranges = [(args.x_min, args.x_max), (args.y_min, args.y_max), (args.z_min, args.z_max)]
125  for i_axis, (lo, hi) in enumerate(axes_ranges):
126  if lo is not None and hi is not None:
127  if i_axis >= histdim:
128  raise Exception("Error: setting axis (%i) for histogram of dimmension (%i)" % (i_axis, histdim))
129 
130  if i_axis == 0: axis = hist.GetXaxis()
131  elif i_axis == 1: axis = hist.GetYaxis()
132  elif i_axis == 2: axis = hist.GetZaxis()
133 
134  range_lo_ind = None
135  for i in range(1, axis.GetNbins()+1):
136  if range_lo_ind is None and axis.GetBinLowEdge(i) > lo:
137  range_lo_ind = max(0, i-2)
138  if axis.GetBinLowEdge(i) >= hi:
139  range_hi_ind = i
140  break
141  else:
142  range_hi_ind = axis.GetNbins()+1
143  assert(range_lo_ind < range_hi_ind)
144 
145  axis_range = [axis.GetBinLowEdge(i) for i in range(1,axis.GetNbins()+1)] + [axis.GetBinUpEdge(axis.GetNbins())]
146  #new_axis_range = array('d', [axis_range[i] for i in range(range_lo_ind, range_hi_ind)])
147 
148  new_axis_args = [range_hi_ind - range_lo_ind - 1, axis_range[range_lo_ind], axis_range[range_hi_ind-1]]
149  if histdim == 1:
150  new_hist = ROOT.TH1D(hist.GetName() + " resized " + name_postfix, hist.GetTitle() + name_postfix, *new_axis_args)
151  elif histdim == 2:
152  x_axis_args = [hist.GetXaxis().GetNbins(), hist.GetXaxis().GetBinLowEdge(1), hist.GetXaxis().GetBinUpEdge(hist.GetXaxis().GetNbins())]
153  y_axis_args = [hist.GetYaxis().GetNbins(), hist.GetYaxis().GetBinLowEdge(1), hist.GetYaxis().GetBinUpEdge(hist.GetYaxis().GetNbins())]
154  histo_args = new_axis_args + y_axis_args if i_axis == 0 else x_axis_args + new_axis_args
155  new_hist = ROOT.TH2D(hist.GetName() + " resized " + name_postfix, hist.GetTitle() + name_postfix, *histo_args)
156  elif histdim == 3:
157  x_axis_args = [hist.GetXaxis().GetNbins(), hist.GetXaxis().GetBinLowEdge(1), hist.GetXaxis().GetBinUpEdge(hist.GetXaxis().GetNbins())]
158  y_axis_args = [hist.GetYaxis().GetNbins(), hist.GetYaxis().GetBinLowEdge(1), hist.GetYaxis().GetBinUpEdge(hist.GetYaxis().GetNbins())]
159  z_axis_args = [hist.GetZaxis().GetNbins(), hist.GetZaxis().GetBinLowEdge(1), hist.GetZaxis().GetBinUpEdge(hist.GetZaxis().GetNbins())]
160  if i_axis == 0:
161  histo_args = new_axis_args + y_axis_args + z_axis_args
162  elif i_axis == 1:
163  histo_args = x_axis_args + new_axis_args + z_axis_args
164  elif i_axis == 2:
165  histo_args = x_axis_args + y_axis_args + new_axis_args
166  new_hist = ROOT.TH3D(hist.GetName() + " resized " + name_postfix, hist.GetTitle() + name_postfix, *histo_args)
167 
168  for i in range(range_lo_ind+1, range_hi_ind+1):
169  i_set = i - range_lo_ind
170  if histdim == 1:
171  new_hist.SetBinContent(i - range_lo_ind, hist.GetBinContent(i))
172  new_hist.SetBinError(i - range_lo_ind, hist.GetBinError(i))
173  elif histdim == 2:
174  other_axis = hist.GetYaxis() if i_axis == 0 else hist.GetXaxis()
175  for j in range(1, other_axis.GetNbins()+1):
176  i_bin_old = hist.GetBin(i, j) if i_axis == 0 else hist.GetBin(j, i)
177  i_bin_new = new_hist.GetBin(i_set, j) if i_axis == 0 else new_hist.GetBin(j, i_set)
178  new_hist.SetBinContent(i_bin_new, hist.GetBinContent(i_bin_old))
179  new_hist.SetBinError(i_bin_new, hist.GetBinError(i_bin_old))
180  elif histdim == 3:
181  other_axes = [hist.GetXaxis(), hist.GetYaxis(), hist.GetZaxis()]
182  other_axes.pop(i_axis)
183  for j in range(1,other_axes[0].GetNbins()+1):
184  for k in range(1, other_axes[1].GetNbins()+1):
185  old_axes_indices = [j,k]
186  old_axes_indices.insert(i_axis, i)
187 
188  new_axes_indices = [j,k]
189  new_axes_indices.insert(i_axis, i_set)
190 
191  i_bin_old = hist.GetBin(*old_axes_indices)
192  i_bin_new = new_hist.GetBin(*new_axes_indices)
193  new_hist.SetBinContent(i_bin_new, hist.GetBinContent(i_bin_old))
194  new_hist.SetBinError(i_bin_new, hist.GetBinError(i_bin_old))
195  hist = new_hist
196  if args.projectionX:
197  hist = hist.ProjectionX()
198  if args.projectionY:
199  hist = hist.ProjectionY()
200  if args.projectionZ:
201  hist = hist.ProjectionZ()
202  if args.projectionXY:
203  hist = hist.Project3D("yx")
204  if args.projectionYZ:
205  hist = hist.Project3D("zy")
206  if args.projectionXZ:
207  hist = hist.Project3D("zx")
208 
209  if args.rebinX is not None and args.rebinX != 1:
210  hist.RebinX(args.rebinX)
211  if args.rebinY is not None and args.rebinY != 1:
212  hist.RebinY(args.rebinY)
213  if args.rebinZ is not None and args.rebinZ != 1:
214  hist.RebinZ(args.rebinZ)
215  return hist
216 
217 def int_pair(inp):
218  return [int(i) for i in inp.split(",")][:2]
219 
221  parser.add_argument("-yr", "--yrange", default=None, type=int_pair)
222  parser.add_argument("-xt", "--xtitle", default=None)
223  parser.add_argument("-yt", "--ytitle", default=None)
224  parser.add_argument("-yl", "--ylabel", nargs="+", default=None)
225  parser.add_argument("-xl", "--xlabel", nargs="+", default=None)
226  parser.add_argument("-os", "--optstat", default=None)
227  parser.add_argument("-ml", "--margin_left", default=None, type=float)
228  parser.add_argument("-mr", "--margin_right", default=None, type=float)
229  parser.add_argument("-mt", "--margin_top", default=None, type=float)
230  parser.add_argument("-mb", "--margin_bottom", default=None, type=float)
231  return parser
232 
233 def optstat(args):
234  if args.optstat:
235  ROOT.gStyle.SetOptStat(args.optstat)
236 
237 def style(args, canvas, hist):
238  hist.GetYaxis().SetTitleSize(20)
239  hist.GetYaxis().SetTitleFont(43)
240  hist.GetYaxis().SetLabelFont(43)
241  hist.GetYaxis().SetLabelSize(20)
242  hist.GetYaxis().CenterTitle()
243 
244  hist.GetXaxis().SetTitleSize(20)
245  hist.GetXaxis().SetTitleFont(43)
246  hist.GetXaxis().SetLabelFont(43)
247  hist.GetXaxis().SetLabelSize(20)
248  hist.GetXaxis().CenterTitle()
249 
250  if args.margin_left is not None:
251  canvas.SetLeftMargin(args.margin_left)
252  if args.margin_right is not None:
253  canvas.SetRightMargin(args.margin_right)
254  if args.margin_bottom is not None:
255  canvas.SetBottomMargin(args.margin_bottom)
256  if args.margin_top is not None:
257  canvas.SetTopMargin(args.margin_top)
258 
259  if args.xlabel is not None:
260  for i, xlabel in enumerate(args.xlabel):
261  hist.GetXaxis().SetBinLabel(i+1, xlabel)
262  if args.ylabel is not None:
263  for i, ylabel in enumerate(args.ylabel):
264  hist.GetYaxis().SetBinLabel(i+1, ylabel)
265  hist.GetYaxis().LabelsOption("v")
266 
267 
268  if args.xtitle: hist.GetXaxis().SetTitle(args.xtitle)
269  if args.ytitle: hist.GetYaxis().SetTitle(args.ytitle)
270  if args.yrange: hist.GetYaxis().SetRangeUser(*args.yrange)
271 
272 def fillcolors(index):
273  colors = [ROOT.kRed, ROOT.kGreen]
274  return colors[index]
275 
276 def namecolors(name):
277  colors = {
278  "CC": ROOT.kPink+2,
279  "Cosmic": ROOT.kGray+1,
280  "Intime Cosmic": ROOT.kGray+1,
281  "Outtime Cosmic": ROOT.kGray+2,
282  "NC": ROOT.kAzure+3,
283  "Other": ROOT.kRed+2
284  }
285  return colors[name]
286 
288  return inp.split(",")
289 
291  pot = ROOT.TLatex(0.925,0.88,"1x10^{20} POT normalized")
292  pot.SetNDC()
293  pot.SetTextSize(18)
294  pot.SetTextAlign(32)
295  pot.Draw()
296 
298  sbn = ROOT.TLatex(.95, .92, "SBN Simulation")
299  sbn.SetTextColor(kGray+1)
300  sbn.SetNDC()
301  sbn.SetTextSize(20)
302  sbn.SetTextAlign(32)
303  sbn.Draw()
304 
306  exp = ROOT.TLatex(0.22,0.91,"ICARUS Sample")
307  exp.SetNDC()
308  exp.SetTextSize(18)
309  exp.SetTextAlign(12)
310  exp.Draw()
311 
313  exp = ROOT.TLatex(0.22,0.91,"SBND Sample")
314  exp.SetNDC()
315  exp.SetTextSize(18)
316  exp.SetTextAlign(12)
317  exp.Draw()
318 
320  if inp == "ur":
321  return [0.75,0.75,0.95,0.95]
322  elif inp == "ul":
323  return [0.35,0.75,0.15,0.95]
324  elif inp == "um":
325  return [0.4, 0.69, 0.6, 0.89]
326  elif inp == "lr":
327  return [0.75,0.15,0.95,0.35]
328  else:
329  return [float(x) for x in inp.split(",")][:4]
330 
331 def histo_list(inp):
332  inp = inp.split(",")
333  in_parens = False
334  out = []
335  for name in inp:
336  if name.startswith("("):
337  assert(not in_parens)
338  in_parens = True
339  name = name.lstrip("(")
340  out.append([name])
341  elif name.endswith(")"):
342  assert(in_parens)
343  in_parens = False
344  name = name.rstrip(")")
345  out[-1].append(name)
346  elif in_parens:
347  out[-1].append(name)
348  else:
349  out.append([name])
350  return out
351 
352 def validate_hists(names, hists):
353  for nn,hh in zip(names, hists):
354  if isinstance(hh, list):
355  for n,h in zip(nn,hh):
356  if not h:
357  raise Exception("Error: invalid histogram with name (%s)" % n)
358  # raise Exception("Error: invalid histogram (%s) with name (%s)" % (h, n))
359  else:
360  if not hh:
361  raise Exception("Error: invalid histogram with name (%s)" % (nn))
362  #raise Exception("Error: invalid histogram (%s) with name (%s)" % (hh, nn))
363 
364 
def histo_list
Definition: util.py:331
def draw_iclabel
Definition: util.py:305
def root_env
Definition: util.py:9
def legend_position
Definition: util.py:319
def with_input_args
Definition: util.py:27
def validate_hists
Definition: util.py:352
def with_text_args
Definition: util.py:54
def __call__
Definition: util.py:35
def get_tobject
Definition: util.py:47
def style
Definition: util.py:237
def write
Definition: util.py:23
auto enumerate(Iterables &&...iterables)
Range-for loop helper tracking the number of iteration.
Definition: enumerate.h:69
def comma_separated
Definition: util.py:287
def int_pair
Definition: util.py:217
def namecolors
Definition: util.py:276
def with_histostyle_args
Definition: util.py:220
def draw_sbndlabel
Definition: util.py:312
def with_histosize_args
Definition: util.py:100
def wait
Definition: util.py:19
def filespec
Definition: util.py:40
def draw_potlabel
Definition: util.py:290
def optstat
Definition: util.py:233
def with_graphsize_args
Definition: util.py:89
def with_display_args
Definition: util.py:79
def resize_graph
Definition: util.py:112
auto zip(Iterables &&...iterables)
Range-for loop helper iterating across many collections at the same time.
Definition: zip.h:295
def fillcolors
Definition: util.py:272
def draw_sbnlabel
Definition: util.py:297
def draw_text
Definition: util.py:62
def with_io_args
Definition: util.py:84
def resize_histo
Definition: util.py:118