canMan.py
Go to the documentation of this file.
1 from ROOT import *
2 import sys, os, math
3 from collections import OrderedDict
4 
5 def drange(start, stop, step=1):
6  r = float(start)
7  while r < stop:
8  yield r
9  r += step
10 
11 
12 cans = []
13 canNum = 0
14 canPositions = [[10, 10, 600, 450],[615, 10, 600, 450], [10, 480, 600, 450], [615, 480, 600, 450]]
15 
16 
17 
18 
19 def addCan(can):
20  global canNum
21  global cans
22  cans.append(can)
23  canNum +=1
24 
25 def newCan(title):
26  global canNum
27  global cans
28  global canPositions
29 
30  cans.append(TCanvas("can" + str(canNum), title))
31  cans[canNum].SetWindowPosition(canPositions[canNum % 4][0], canPositions[canNum % 4][1])
32  cans[canNum].SetWindowSize(canPositions[canNum % 4][2], canPositions[canNum % 4][3])
33  canNum += 1
34  if canNum % 4 == 0:
35  posUp()
36  return cans[canNum-1]
37 
38 
39 def canUp():
40  for i in range(0, len(cans)):
41  cans[i].RedrawAxis()
42  cans[i].Update()
43 
44 
45 def saveCans(prefix = "", suffix=".pdf"):
46  for i in range(0, len(cans)):
47  cans[i].SaveAs(prefix + cans[i].GetTitle() + suffix)
48 
49 def posUp():
50  global canPositions
51  for i in range(0,len(canPositions)):
52  canPositions[i][0] += 30
53  canPositions[i][1] += 30
54 
56  vec = TVectorD(len(list))
57  for i in range(0, len(list)):
58  vec[i] = list[i]
59  return vec
60 
61 
62 
63 
64 overlayNum = 0
65 legs = []
66 
67 def drawOverlay(listOfHists, name="", opt="", varOpts=[""], colors=[kRed, kBlue -4, kGreen + 2, kMagenta + 1,kOrange+2, kBlack, kViolet - 7], lineStyles=[1], \
68 legEntries = [], logY = False, axisMin = 0, axisMax=None, legPos = "right", legTextSize=0, inputCan=None, legHeight=0.15, legWidth=0.2, supressZero=False,\
69 padFactor=1.1, lineWidths=[gStyle.GetHistLineWidth()], fillStyles=[0], preserveStyle=False, noLeg=False):
70  global overlayNum
71  global legs
72  if logY:
73  supressZero = True
74 
75  histMax = 0
76  histMin = sys.float_info.max
77  for hist in listOfHists:
78  hist.GetYaxis().SetTitleOffset(1.05)
79  if hist.GetBinContent(hist.GetMaximumBin()) > histMax:
80  histMax = hist.GetBinContent(hist.GetMaximumBin())
81  if supressZero:
82  for i in range(1, hist.GetNbinsX()+ 1):
83  content = hist.GetBinContent(i)
84  if content >0 and content < histMin:
85  histMin = content
86  if supressZero:
87  axisMin = 0.9 * histMin
88  if not inputCan:
89  if name == "":
90  can = newCan("Overlay" + str(overlayNum) )
91  else:
92  can = newCan(name + "Overlay")
93  else:
94  can = inputCan
95  can.cd()
96 
97  counter = 0
98 
99  if not axisMax:
100  axisMax = padFactor * histMax
101 
102  if logY:
103  can.SetLogy()
104  if not preserveStyle:
105  for hist in listOfHists:
106  hist.SetLineColor(colors[counter % len(colors)])
107  hist.SetLineWidth(lineWidths[counter % len(lineWidths)])
108  hist.SetLineStyle(lineStyles[counter % len(lineStyles)])
109  if fillStyles[counter % len(fillStyles)]:
110  hist.SetFillStyle(fillStyles[counter % len(fillStyles)])
111  hist.SetFillColor(colors[counter % len(colors)])
112  counter += 1
113  counter = 0
114  for hist in listOfHists:
115  hist.GetYaxis().SetRangeUser(axisMin, axisMax)
116  hist.Draw(opt + varOpts[counter % len(varOpts)])
117  counter += 1
118  if not "SAME" in opt:
119  opt += "SAME"
120 
121  can.Update()
122 
123  if legPos == "right":
124  legs.append(TLegend(0.65, 0.6, 0.65 + legWidth, 0.6 + legHeight))
125  elif legPos == "mid":
126  legs.append(TLegend(0.4, 0.6, 0.4 + legWidth, 0.6 + legHeight))
127  elif legPos =="auto":
128  legs.append(autoPlaceLegend(legWidth, legHeight))
129  elif legPos == "left":
130  legs.append(TLegend(0.15, 0.6, 0.15 + legWidth, 0.6 + legHeight))
131  elif type(legPos) == type([]) and len(legPos) == 2:
132  legs.append(TLegend(legPos[0], legPos[1], legPos[0] + legWidth, legPos[1] + legHeight))
133  else:
134  print "Legend position", legPos, "is invalid."
135 
136  legs[overlayNum].SetFillColor(0)
137  if legTextSize:
138  legs[overlayNum].SetTextSize(legTextSize)
139  counter = 0
140 
141  for hist in listOfHists:
142  legStyle=''
143  if hist.GetFillStyle() != 0:
144  legStyle += 'f'
145  if hist.GetLineWidth() != 0:
146  legStyle += 'l'
147  if len(legEntries) == 0:
148  legs[overlayNum].AddEntry(hist, hist.GetName(), legStyle)
149  else:
150  legs[overlayNum].AddEntry(hist, legEntries[counter], legStyle)
151  counter += 1
152 
153  legs[overlayNum].SetFillStyle(0)
154  for obj in legs[overlayNum].GetListOfPrimitives():
155  if obj.InheritsFrom("TAttFill"):
156  obj.SetFillStyle(0)
157 
158  if not noLeg:
159  legs[overlayNum].Draw()
160 
161  overlayNum += 1
162  listOfHists[0].Draw("sameaxis")
163  return can
164 
165 def drawHists(listOfHists, opt= "", logY=False):
166  for hist in listOfHists:
167  c = newCan(hist.GetName())
168  if logY:
169  c.SetLogy()
170  hist.Draw(opt)
171 
172 def drawHist(hist, opt= "", logY=False):
173  c = newCan(hist.GetName())
174  if logY:
175  c.SetLogy()
176  hist.Draw(opt)
177  return c
178 
179 def getFileId(filePath):
180  fileName = os.path.split(filePath)[1]
181  if "neardet" in fileName: det = "neardet"
182  if "fardet" in fileName : det = "fardet"
183  detPos = fileName.find(det)
184  extPos = fileName.find(".")
185  if "_v" in fileName: extPos = fileName.find("_v")
186  fileId = fileName[detPos:extPos]
187  return fileId
188 
190  def __init__(self, tree, increment=10000):
191  self.entries = float(tree.GetEntries())
192  self.increment = increment
193  self.progress = 0
194 
195 
196  def advance(self):
197  self.progress+=1
198  if not self.progress%self.increment:
199  print "Event: ", self.progress, str(self.progress / self.entries)[:6]
200 
201 
202 def sqr(x):
203  return x*x
204 def sign(x):
205  if x >= 0:
206  return 1
207  return -1
208 
209 def PointDistanceToBox(x, y, x0, y0, x1, y1):
210  # Inside
211  if x > x0 and x < x1 and y > y0 and y < y1:
212  return 0
213 
214  # Corners
215  d = sqr(x-x0)+sqr(y-y0);
216  d = min(d, sqr(x-x1)+sqr(y-y0))
217  d = min(d, sqr(x-x1)+sqr(y-y1))
218  d = min(d, sqr(x-x0)+sqr(y-y1))
219 
220  # Top and bottom edges
221  if x > x0 and x < x1:
222  d = min(d, sqr(y-y0))
223  d = min(d, sqr(y-y1))
224 
225  # Left and right
226  if y > y0 and y < y1:
227  d = min(d, sqr(x-x0))
228  d = min(d, sqr(x-x1))
229 
230 
231  return d;
232 
233 
234 
235 def autoPlaceLegend(dx, dy, gridPoints=30):
236  gPad.Update()
237  # Convert requested width and height into physics coordinates
238  dx *= (gPad.GetX2()-gPad.GetX1())
239  dy *= (gPad.GetY2()-gPad.GetY1())
240 
241  # Range of axes in physics units, if log, these already have the log applied
242  x0 = gPad.GetUxmin()
243  x1 = gPad.GetUxmax()
244  y0 = gPad.GetUymin()
245  y1 = gPad.GetUymax()
246 
247 
248  X = x1-x0
249  Y = y1-y0
250 
251  bestd = 0
252  bestx = 0
253  besty = 0
254  for fallback in [False, True]:
255  if fallback:
256  print "falling back"
257  for x in drange(x0+dx/2, x1-dx/2, X/float(gridPoints)):
258  for y in drange(y0+dy/2, y1-dy/2, Y/float(gridPoints)):
259  d = 999999
260 
261 
262  # Repel from edges
263  """
264 
265  dToEdges = [sqr((x-dx/2-x0)/X), sqr((x+dx/2-x1)/X), sqr((y-dy/2-y0)/Y), sqr((y+dy/2-y1)/Y)]
266  for dToEdge in dToEdges:
267  print dToEdge
268  if math.fabs(dToEdge) < 0.05:
269  d = 0
270  continue
271 
272  """
273 
274  d = min(d, sqr((x-dx/2-x0)/X))
275  d = min(d, sqr((x+dx/2-x1)/X))
276  d = min(d, sqr((y-dy/2-y0)/Y))
277  d = min(d, sqr((y+dy/2-y1)/Y))
278  if d < bestd:
279  continue
280 
281  prims = gPad.GetListOfPrimitives()
282  for obj in prims:
283 
284  if not obj.InheritsFrom(TH1.Class()):
285  continue
286  h = obj
287 
288  for n in range(0, h.GetNbinsX() + 1):
289  px = h.GetBinCenter(n)
290  py = h.GetBinContent(n)
291  if gPad.GetLogy():
292  if py > 0:
293  py = math.log10(py)
294  else:
295  py = gPad.GetUymin()
296  if fallback:
297  d = min(d, sqr((px-x)/X)+sqr((py-y)/Y))
298  else:
299 
300  d = min(d, PointDistanceToBox(px/X, py/Y,
301  (x-dx/2)/X, (y-dy/2)/Y,
302  (x+dx/2)/X, (y+dy/2)/Y))
303 
304  if d < bestd:
305  break;
306 
307  if d < bestd:
308  break;
309 
310 
311  if d > bestd:
312  bestd = d;
313  bestx = x;
314  besty = y;
315 
316 
317 
318 
319  if bestd != 0:
320  break # If we always collide, have to do fallback
321 
322  # Convert to pad coordinates
323  nx = float(bestx-gPad.GetX1())/(gPad.GetX2()-gPad.GetX1());
324  ny = float(besty-gPad.GetY1())/(gPad.GetY2()-gPad.GetY1());
325 
326  ndx = dx/float(gPad.GetX2()-gPad.GetX1());
327  ndy = dy/float(gPad.GetY2()-gPad.GetY1());
328 
329  return TLegend(nx-ndx/2, ny-ndy/2, nx+ndx/2, ny+ndy/2);
330 
331 
332 
333 
334 def drawTwoPad(top, bottom, can=None, titleOffY = 0.035, leftMargin=0.13, topMargin=0.1, bottomFraction=0.4):
335  pixels = 18.
336  labPix = 15.
337  labOff = 5.
338  # GET RID OF IT!
339 
340  if not can:
341  can = newCan(top.GetTitle() +"_split")
342  can.SetBottomMargin(0)
343  can.Divide(1,2, 0,0)
344  c1 = can.cd(1)
345  c1.SetPad(0,bottomFraction,1,1)#0.95)
346  c1.SetFillStyle(0)
347  top.DrawClonePad()
348  c1.SetRightMargin(.05)
349  c1.SetTopMargin(topMargin)
350  c1.SetBottomMargin(0.005)
351  c1.SetLeftMargin(leftMargin)
352 
353  c1.Update()
354  textSizeFac = 1.0/(math.fabs(c1.YtoAbsPixel(c1.GetY2()) - c1.YtoAbsPixel(c1.GetY1())))
355  marginSize = 80
356  textsizeA = pixels/(c1.GetAbsHNDC()*c1.GetWh())
357  textsizeAl = labPix/(c1.GetAbsHNDC()*c1.GetWh())
358  textsizeAo = labOff/(c1.GetWw() * c1.GetAbsWNDC())
359 
360  for obj in c1.GetListOfPrimitives():
361  if obj.InheritsFrom("TH1") or obj.InheritsFrom("TGraph"):
362  obj.GetYaxis().SetTitleSize(textsizeA)
363  obj.GetYaxis().SetLabelSize(textsizeAl)
364  obj.GetYaxis().SetLabelOffset(textsizeAo)
365  obj.GetYaxis().SetTitleOffset(titleOffY / textsizeA)
366  c1.Update()
367 
368  c2 = can.cd(2)
369  c2.SetPad(0,0.0,1,bottomFraction)
370  bottom.DrawClonePad()
371  c2.SetTopMargin(0.025)
372  c2.SetBottomMargin(.22)
373  c2.SetRightMargin(0.05)
374  c2.SetLeftMargin(leftMargin)
375  c2.Update()
376 
377  textsize = pixels/(c2.GetAbsHNDC()*c2.GetWh())
378  textsizel = labPix/(c2.GetAbsHNDC()*c2.GetWh())
379  textsizeo = labOff/(c2.GetWw() * c2.GetAbsWNDC())
380  textsizex = pixels/(c2.GetAbsHNDC()*c2.GetWh())
381  textsizelx = labPix/(c2.GetAbsHNDC()*c2.GetWh())
382  textsizeAl = labPix/(c2.GetAbsHNDC()*c2.GetWh())
383  textsizeox = labOff/(c2.GetWw() * c2.GetAbsWNDC())
384 
385  for obj in c2.GetListOfPrimitives():
386  if obj.InheritsFrom("TH1") or obj.InheritsFrom("TGraph"):
387  obj.GetYaxis().SetTitleSize(textsize)
388  obj.GetYaxis().SetLabelSize(textsizel)
389  obj.GetYaxis().SetLabelOffset(textsizeAo)
390  obj.GetXaxis().SetTitleSize(textsizex)
391  obj.GetXaxis().SetLabelSize(textsizelx)
392  obj.GetXaxis().SetLabelOffset(textsizeox)
393  obj.GetYaxis().SetTitleOffset(titleOffY / textsize)
394  obj.GetXaxis().SetTitleOffset(0.9)
395 
396 
397  c2.Update()
398 
399  return can
400 
401 
402 
403 class Table():
404  def __init__(self):
405  self.table = []
406 
407  def append(self, row):
408  self.table.append(row)
409 
410  def getLatex(self):
411  str = ""
412  table = self.table
413  nCol = len(table[0])
414  colDef = "| " + (" c |" * nCol)
415  str += "\\begin{center} \n \\begin{tabular} {" + colDef + "} \n \hline \n"
416 
417  col_width = [max(len(x) for x in col) for col in zip(*table)]
418  for line in table:
419  str += " " + " & ".join("{:{}}".format(x, col_width[i])
420  for i, x in enumerate(line)) + " \\\\ \hline \n"
421  str += " \\end{tabular} \n \\end{center}"
422  return str
423 
424  def getReadable(self):
425  str = ""
426  table = self.table
427  col_width = [max(len(x) for x in col) for col in zip(*table)]
428  for line in table:
429  str += "| " + " | ".join("{:{}}".format(x, col_width[i])
430  for i, x in enumerate(line)) + " | \n"
431 
432 
433  return str
434 
435  def printLatex(self):
436  print self.getLatex()
437 
438  def printReadable(self):
439  print self.getReadable()
440 
441  def writeLatex(self, outputFile):
442  outputFile.write(self.getReadable())
443 
444  def writeLatex(self, outputFile):
445  outputFile.write(self.getLatex())
446 
447 
448 
449 # The canMan HistSet. Pulls all plottables out of tDirectories.
450 # Does not recurse... maybe that's a good thing.
451 class HistSet:
452  def __init__(self, tDir, color=kBlack, title=None):
453  self.tDir = tDir
454  self.h1 = OrderedDict()
455  self.h2 = OrderedDict()
456  self.h3 = OrderedDict()
457  self.gr = OrderedDict()
458  self.tr = OrderedDict()
459  self.name = tDir.GetName()
460 
461  self.color = color
462  self.title = title
463 
464  for key in self.tDir.GetListOfKeys():
465  h = tDir.Get(key.GetName())
466  if h.InheritsFrom("TH1"):
467  if h.InheritsFrom("TH3"):
468  self.h3[h.GetName()] = h
469  if h.InheritsFrom("TH2"):
470  self.h2[h.GetName()] = h
471  else:
472  self.h1[h.GetName()] = h
473  elif h.InheritsFrom("TGraph"):
474  self.gr[h.GetName()] = h
475  elif h.InheritsFrom("TTree"):
476  self.tr[h.GetName()] = h
477 
def getTVectorFromList(list)
Definition: canMan.py:55
T max(const caf::Proxy< T > &a, T b)
def posUp()
Definition: canMan.py:49
def advance(self)
Definition: canMan.py:196
bin1_2sigma SetFillColor(3)
def addCan(can)
Definition: canMan.py:19
c1 Update()
def writeLatex(self, outputFile)
Definition: canMan.py:441
prelim SetTextSize(2/30.)
def drawHists(listOfHists, opt="", logY=False)
Definition: canMan.py:165
ntuple SetFillStyle(1001)
def printReadable(self)
Definition: canMan.py:438
::xsd::cxx::tree::type type
Definition: Database.h:110
def append(self, row)
Definition: canMan.py:407
def canUp()
Definition: canMan.py:39
def __init__(self)
Definition: canMan.py:404
def sqr(x)
Definition: canMan.py:202
leg AddEntry(GRdata,"data","p")
def newCan(title)
Definition: canMan.py:25
TGraph * join(TGraph *a, TGraph *b, int col)
Definition: contours.C:359
std::string format(const int32_t &value, const int &ndigits=8)
Definition: HexUtils.cpp:14
def PointDistanceToBox(x, y, x0, y0, x1, y1)
Definition: canMan.py:209
def drawOverlay(listOfHists, name="", opt="", varOpts=[""], colors=[kRed, kBlue, kGreen, kMagenta, kOrange, kBlack, kViolet, lineStyles=[1], legEntries=[], logY=False, axisMin=0, axisMax=None, legPos="right", legTextSize=0, inputCan=None, legHeight=0.15, legWidth=0.2, supressZero=False, padFactor=1.1, lineWidths=[gStyle.GetHistLineWidth()], fillStyles=[0], preserveStyle=False, noLeg=False)
Definition: canMan.py:69
def sign(x)
Definition: canMan.py:204
static float min(const float a, const float b, const float c)
Definition: absgeo.cxx:45
def __init__(self, tDir, color=kBlack, title=None)
Definition: canMan.py:452
def autoPlaceLegend(dx, dy, gridPoints=30)
Definition: canMan.py:235
def drawHist(hist, opt="", logY=False)
Definition: canMan.py:172
def saveCans(prefix="", suffix=".pdf")
Definition: canMan.py:45
recTree Draw("energy.numu.trkccE>>precosmics","fdcuts&&preshutdown")
def drange(start, stop, step=1)
Definition: canMan.py:5
cosmicTree SaveAs("cosmicTree.root")
def getReadable(self)
Definition: canMan.py:424
def getFileId(filePath)
Definition: canMan.py:179
def printLatex(self)
Definition: canMan.py:435
def __init__(self, tree, increment=10000)
Definition: canMan.py:190
def getLatex(self)
Definition: canMan.py:410
def drawTwoPad(top, bottom, can=None, titleOffY=0.035, leftMargin=0.13, topMargin=0.1, bottomFraction=0.4)
Definition: canMan.py:334