HandyFuncs.py
Go to the documentation of this file.
1 from ROOT import *
2 from array import array
3 import os, math
4 #import progressbar as pb
5 
6 def PrintError(val, err):
7  precision = max(int(-math.log10(err)), 0)+1
8  form = "{0:.%if} #pm {1:.%if}" % (precision, precision)
9  return form.format(val, err)
10 
11 
12 def printlist(mylist):
13  rows, columns = os.popen('stty size', 'r').read().split()
14  maxw = max(map(len,mylist))
15  ncols = int(columns)/(maxw+1)
16 
17  col = 0
18  for word in mylist:
19  print word.ljust(maxw), " ",
20  col += 1
21  if col >= ncols:
22  print ""
23  col = 0
24  print ""
25 
26 
27 def CenterTitles(histo):
28  histo.GetXaxis().CenterTitle()
29  histo.GetYaxis().CenterTitle()
30  histo.GetZaxis().CenterTitle()
31 
32 
33 def GetHists(c1):
34  prims = list(c1.GetListOfPrimitives())
35  return filter(lambda x: x.InheritsFrom("TH1"), prims)
36 
37 
38 def VerticalRange(hists, xrange=(0,0), ratio=False, forceOne=True, ignoreError=False, maxerr=0.25, absMax=-999, absMin=-999, buffer=0.05, verbose=0, log=False):
39  if xrange == (0,0):
40  minbin = 1
41  maxbin = hists[0].GetNbinsX()
42  else:
43  minbin = hists[0].FindBin(xrange[0])
44  maxbin = hists[0].FindBin(xrange[1])
45 
46  min = 999999.
47  max = -999999.
48 
49  if verbose: print "Running VerticalRange between", minbin, maxbin, "for", len(hists), "histograms"
50 
51  for hist in hists:
52  for b in range(minbin, maxbin+1):
53  denom = hist.GetBinContent(b)
54  if denom == 0: denom = 0.00001
55  errratio = abs(hist.GetBinError(b) / denom)
56 
57  if ignoreError:
58  lowval = hist.GetBinContent(b)
59  highval = hist.GetBinContent(b)
60  else:
61  lowval = hist.GetBinContent(b) - hist.GetBinError(b)
62  highval = hist.GetBinContent(b) + hist.GetBinError(b)
63  #print "Bin = %i, Cont = %f, Low = %f, High = %f, ER = %f" %(b, hist.GetBinContent(b), lowval, highval, errratio)
64 
65  if (errratio < maxerr) or ignoreError:
66  if lowval < min and not (hist.GetBinContent(b) == 0 and (ratio or log) ):
67  min = lowval
68  if verbose: print " ",hist.GetName(), ":", "new min", min
69  if highval > max:
70  max = highval
71  if verbose: print " ",hist.GetName(), ":", "new max", max
72 
73  if ratio:
74  if forceOne:
75  if min > 1: min = 1
76  if max < 1: max = 1
77  adjust = (max - min)*buffer/2.
78  max = max + adjust
79  min = min - adjust
80  elif log:
81  min = log10(min)
82  max = log10(max)
83  adjust = (max - min)*buffer/2.
84  max = max + adjust
85  min = min - adjust
86  max = 10**max
87  min = 10**min
88  else:
89  min = 0
90  max = (1+buffer)*max
91 
92 
93  if absMax != -999:
94  if max > absMax:
95  max = absMax
96  if absMin != -999:
97  if min < absMin:
98  min = absMin
99 
100 
101  if verbose: print "Final Min = %f, Max = %f" %(min, max)
102  for hist in hists:
103  hist.SetMinimum(min)
104  hist.SetMaximum(max)
105 
106 
107 def HorizontalRange(hists, mustinclude=[]):
108  low = 1e90
109  high = -1e90
110 
111  for hist in hists:
112  mean = hist.GetMean()
113  rms = hist.GetRMS()
114  low = min(low, mean-2*rms)
115  high = max(high, mean+2*rms)
116 
117  for m in mustinclude:
118  low = min(low, m)
119  high = max(high, m)
120 
121 
122  adjust = (high-low)*0.05
123  low -= adjust
124  high += adjust
125 
126  for hist in hists:
127  hist.GetXaxis().SetRangeUser(low,high)
128 
129 
130 def ChisqCount(h1, h2):
131  sum1 = 0
132  sum2 = 0
133  w1 = 0
134  w2 = 0
135 
136  for bin in range(1, h1.GetNbinsX()+1):
137  sum1 += h1.GetBinContent(bin)
138  sum2 += h2.GetBinContent(bin)
139  ew1 = h1.GetBinError(bin)
140  ew2 = h2.GetBinError(bin)
141  w1 += ew1*ew1
142  w2 += ew2*ew2
143 
144  # My simple chisquared method
145  delta = sum1 - sum2
146  sigmasq = w1 + w2
147  chi2 = delta*delta / sigmasq
148  prob = TMath.Prob(chi2, 1)
149 
150  return prob
151 
152 def MakeGradient(nsteps, start, end):
153  from ROOT import TColor
154  r1, g1, b1 = start
155  r2, g2, b2 = end
156 
157 # print start, "to", end
158 
159 
160  gradient = []
161 
162  rstep = float(r2 - r1)/float(nsteps-1)
163  gstep = float(g2 - g1)/float(nsteps-1)
164  bstep = float(b2 - b1)/float(nsteps-1)
165 
166 # print "steps", rstep, gstep, bstep
167 
168  for i in range(nsteps):
169  r = r1 + rstep*i
170  g = g1 + gstep*i
171  b = b1 + bstep*i
172  color = TColor.GetColor(r, g, b)
173 # print "(%.2f, %.2f, %.2f) = %i" %(r,g,b, color)
174  gradient.append(color)
175 
176  return gradient
177 
178 def Intersections(hist, value, interp = False):
179  intersections = []
180  for xb in range(1,hist.GetNbinsX()):
181  x1 = hist.GetXaxis().GetBinLowEdge(xb)
182  y1 = hist.GetBinContent(xb)
183  x2 = hist.GetXaxis().GetBinLowEdge(xb+1)
184  y2 = hist.GetBinContent(xb+1)
185  x3 = hist.GetXaxis().GetBinLowEdge(xb+2)
186  lowleft = (y1 < value and y2 > value)
187  lowright = (y1 > value and y2 < value)
188 
189  if lowleft or lowright:
190  if interp:
191  intersections += [ Interpolate(x1, y1, x2, y2, value) ]
192  elif lowleft:
193  intersections += [ x3 ]
194  elif lowright:
195  intersections += [ x2 ]
196 
197  return intersections
198 
199 def gIntersections(graph, value, xrng, nsteps=1000):
200  intersections = []
201 
202  xmin, xmax = xrng
203  xstp = (xmax - xmin)/(nsteps - 1)
204 
205  for xi in range(nsteps-1):
206  x1 = xmin + (xi+0)*xstp
207  x2 = xmin + (xi+1)*xstp
208  y1 = graph.Eval(x1)
209  y2 = graph.Eval(x2)
210  lowleft = (y1 < value and y2 > value)
211  lowright = (y1 > value and y2 < value)
212 
213  if lowleft or lowright:
214  intersections += [ Interpolate(x1, y1, x2, y2, value) ]
215  return intersections
216 
217 
218 def Interpolate(x1, y1, x2, y2, yvalue):
219  m = (y2-y1)/(x2-x1)
220  return x1 + (yvalue-y1)/m
221 
222 
223 '''
224 # Very handy, but you need to install the ProgressBar package
225 def pbloop(iterable, name = "Entries"):
226  widgets = [ name+': ',pb.Value(), '/', pb.Total(), ' ', pb.Percentage(), ' ',
227  pb.Bar(marker='=',left='[',right=']'),
228  ' ',pb.ETA() ]
229  pbar = pb.ProgressBar(widgets=widgets, maxval=len(iterable), term_width=100)
230  pbar.start()
231  for i, val in enumerate(iterable):
232  pbar.update(i)
233  yield val
234  pbar.finish()
235  print ""
236 '''
237 
238 
239 def BinWidthNormalize(h, width = -1):
240  if width < 0:
241  width = h.GetBinWidth(1)
242 
243  for i in range(1, h.GetNbinsX()+1):
244  wi = h.GetBinWidth(i)
245  w = wi/width
246  c = h.GetBinContent(i)
247  e = h.GetBinError(i)
248  h.SetBinContent(i, c/w)
249  h.SetBinError(i, e/w)
250 
251 
252 
253 def MakeBins(bmin, bmax, nbins, log=False):
254  bins = []
255  if log:
256  bmin = log10(bmin)
257  bmax = log10(bmax)
258  bins = [ x*(bmax-bmin)/(nbins - 1.) + bmin for x in range(nbins) ]
259  if log:
260  bins = map(lambda x: 10.**x, bins)
261  return array('d',bins)
262 
263 
264 
265 def DrawDiv(x, c1):
266  c1.cd()
267  c1.Update()
268  ldiv = TLine(x, c1.GetUymin(), x, c1.GetUymax())
269  ldiv.SetLineStyle(7)
270  ldiv.SetLineWidth(2)
271  ldiv.Draw()
272  return ldiv
273 
274 def DrawLine(c1, val = 0):
275  c1.cd()
276  c1.Update()
277  ldiv = TLine(c1.GetUxmin(), val, c1.GetUxmax(), val)
278  ldiv.SetLineStyle(1)
279  ldiv.SetLineWidth(1)
280  ldiv.Draw()
281  return ldiv
282 
283 def mean(lst):
284  return sum(lst)/len(lst)
285 
286 def stdev(lst):
287  m = mean(lst)
288  return sqrt( sum(map(lambda x: (x-m)**2, lst)) / (len(lst)-1.) )
289 
290 def rms(lst):
291  return sqrt( sum(map(lambda x: (x)**2, lst)) / len(lst) )
292 
293 
294 def ProfileX(hist):
295  axis = hist.GetXaxis()
296  axisother = hist.GetYaxis()
297 
298  prof = TH1D(hist.GetName()+"_profX", hist.GetTitle(), axis.GetNbins(), axis.GetBinLowEdge(1), axis.GetBinLowEdge(axis.GetNbins()+1))
299  prof.SetXTitle(axis.GetTitle())
300 
301  for nb in range(1, axis.GetNbins()+1):
302  val = 99999999.
303  for nbo in range(1, axisother.GetNbins()+1):
304  val = min(val, hist.GetBinContent(nb, nbo))
305  prof.SetBinContent(nb, val)
306 
307  return prof
308 
309 
310 def ProfileY(hist):
311  axis = hist.GetYaxis()
312  axisother = hist.GetXaxis()
313 
314  prof = TH1D(hist.GetName()+"_profX", hist.GetTitle(), axis.GetNbins(), axis.GetBinLowEdge(1), axis.GetBinLowEdge(axis.GetNbins()+1))
315  prof.SetXTitle(axis.GetTitle())
316 
317  for nb in range(1, axis.GetNbins()+1):
318  val = 99999999.
319  for nbo in range(1, axisother.GetNbins()+1):
320  val = min(val, hist.GetBinContent(nbo, nb))
321  prof.SetBinContent(nb, val)
322 
323  return prof
324 
def PrintError(val, err)
Definition: HandyFuncs.py:6
def CenterTitles(histo)
Definition: HandyFuncs.py:27
def stdev(lst)
Definition: HandyFuncs.py:286
T sqrt(T number)
Definition: d0nt_math.hpp:156
void abs(TH1 *hist)
def rms(lst)
Definition: HandyFuncs.py:290
def DrawLine(c1, val=0)
Definition: HandyFuncs.py:274
def HorizontalRange(hists, mustinclude=[])
Definition: HandyFuncs.py:107
Module that kips a configurable number of events between each that it allows through. Note that this module really skips (N-1) events, it uses a simple modular division as its critera. This module will cut down the data sample to 1/N of its original size.
def GetHists(c1)
Definition: HandyFuncs.py:33
def MakeGradient(nsteps, start, end)
Definition: HandyFuncs.py:152
def ProfileY(hist)
Definition: HandyFuncs.py:310
def DrawDiv(x, c1)
Definition: HandyFuncs.py:265
def MakeBins(bmin, bmax, nbins, log=False)
Definition: HandyFuncs.py:253
def Interpolate(x1, y1, x2, y2, yvalue)
Definition: HandyFuncs.py:218
def BinWidthNormalize(h, width=-1)
Definition: HandyFuncs.py:239
static float min(const float a, const float b, const float c)
Definition: absgeo.cxx:45
def VerticalRange(hists, xrange=(0, 0), ratio=False, forceOne=True, ignoreError=False, maxerr=0.25, absMax=-999, absMin=-999, buffer=0.05, verbose=0, log=False)
Definition: HandyFuncs.py:38
def ChisqCount(h1, h2)
Definition: HandyFuncs.py:130
T log10(T number)
Definition: d0nt_math.hpp:120
def gIntersections(graph, value, xrng, nsteps=1000)
Definition: HandyFuncs.py:199
def Intersections(hist, value, interp=False)
Definition: HandyFuncs.py:178
def mean(lst)
Definition: HandyFuncs.py:283
Double_t sum
Definition: plot.C:31
T max(sqlite3 *const db, std::string const &table_name, std::string const &column_name)
Definition: statistics.h:68
def ProfileX(hist)
Definition: HandyFuncs.py:294
def printlist(mylist)
Definition: HandyFuncs.py:12