root.py
Go to the documentation of this file.
1 import ROOT
2 
3 
4 def open_file(fileuri, mode = "READONLY"):
5  tfile = ROOT.TFile.Open(fileuri, mode)
6  if not tfile:
7  raise IOError('failed to open %s' % fileuri)
8  return tfile
9 
10 
11 def load_obj(tfile, name):
12  obj = tfile.Get(name)
13  if not obj:
14  raise IOError('failed to get hist "%s" from %s' % (name, fileuri))
15  obj.SetDirectory(0)
16  return obj
17 
18 
19 def save(obj, fname):
20  tfile = ROOT.TFile.Open(fname, "recreate")
21  if not tfile:
22  raise IOError('failed to open %s' % fname)
23  obj.SetDirectory(tfile)
24  tfile.Write()
25  tfile.Close();
26 
27 
28 def is_hist(obj):
29  if obj.InheritsFrom("TKey"):
30  return obj.GetClassName()[:3] in ["TH1", "TH2", "TH3"]
31  return obj.InheritsFrom("TH1")
32 
33 def hist_to_dict(hist):
34  '''
35  Return data structure summarizing the histogram.
36  '''
37  ndim = int(hist.ClassName()[2])
38  dims = list()
39  for idim in range(ndim):
40  letter = "XYZ"[idim]
41  nbins = getattr(hist, "GetNbins"+letter)()
42  axis = getattr(hist, "Get"+letter+"axis")()
43  lo = axis.GetBinLowEdge(1);
44  hi = axis.GetBinUpEdge(nbins);
45  dim = dict(letter=letter, nbins=nbins, min=lo, max=hi, rms=hist.GetRMS(idim+1))
46  dims.append(dim)
47 
48  return dict(axis=dims, name=hist.GetName(), title=hist.GetTitle(),
49  integ=hist.Integral(),
50  min=hist.GetMinimum(), max=hist.GetMaximum())
51 
52 
53 def resize_hist2f(hist, xrebin, yrebin):
54  '''
55  Rebin 2D histogram. This is dog slow.
56  '''
57  xaxis = hist.GetXaxis()
58  nbinsx = hist.GetNbinsX()
59  yaxis = hist.GetYaxis()
60  nbinsy = hist.GetNbinsY()
61 
62  h = ROOT.TH2F(hist.GetName(), hist.GetTitle(),
63  int(round(nbinsx/xrebin)), xaxis.GetBinLowEdge(1), xaxis.GetBinUpEdge(nbinsx),
64  int(round(nbinsy/yrebin)), yaxis.GetBinLowEdge(1), yaxis.GetBinUpEdge(nbinsy))
65 
66  xaxis_new = h.GetXaxis()
67  yaxis_new = h.GetYaxis()
68 
69  for ixbin in range(hist.GetNbinsX()):
70  x = xaxis.GetBinCenter(ixbin+1)
71  ix = xaxis_new.FindBin(x)
72  print x,ix
73  for iybin in range(hist.GetNbinsY()):
74  y = yaxis.GetBinCenter(iybin+1)
75  iy = yaxis_new.FindBin(y)
76  val = hist.GetBinContent(ixbin+1, iybin+1)
77  ibin = h.GetBin(ix,iy)
78  h.AddBinContent(ibin, val)
79  return h
80 
def is_hist(obj)
Definition: root.py:28
def save(obj, fname)
Definition: root.py:19
def load_obj(tfile, name)
Definition: root.py:11
def open_file(fileuri, mode="READONLY")
Definition: root.py:4
def resize_hist2f(hist, xrebin, yrebin)
Definition: root.py:53
def hist_to_dict(hist)
Definition: root.py:33