canMan.py
Go to the documentation of this file.
1 from ROOT import *
2 import sys, os, math
3 
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 newCan(title):
20  global canNum
21  global cans
22  global canPositions
23 
24  cans.append(TCanvas("can" + str(canNum), title))
25  cans[canNum].SetWindowPosition(canPositions[canNum % 4][0], canPositions[canNum % 4][1])
26  cans[canNum].SetWindowSize(canPositions[canNum % 4][2], canPositions[canNum % 4][3])
27  canNum += 1
28  if canNum % 4 == 0:
29  posUp()
30  return cans[canNum-1]
31 
32 
33 def canUp():
34  for i in range(0, len(cans)):
35  cans[i].RedrawAxis()
36  cans[i].Update()
37 
38 
39 def saveCans(prefix = "", suffix=".pdf"):
40  for i in range(0, len(cans)):
41  cans[i].SaveAs(prefix + cans[i].GetTitle() + suffix)
42 
43 def posUp():
44  global canPositions
45  for i in range(0,len(canPositions)):
46  canPositions[i][0] += 30
47  canPositions[i][1] += 30
48 
50  vec = TVectorD(len(list))
51  for i in range(0, len(list)):
52  vec[i] = list[i]
53  return vec
54 
55 
56 
57 
58 overlayNum = 0
59 legs = []
60 
61 def drawOverlay(listOfHists, name="", opt="hist", varOpts=[""], colors=[kRed, kBlue -4, kGreen + 2, kMagenta + 1,kOrange+2, kBlack, kViolet - 7], lineStyles=[1], \
62 legEntries = [], logY = False, axisMin = 0, legPos = "right", legTextSize=0, inputCan=None, legHeight=0.15, legWidth=0.2, supressZero=False,\
63 padFactor=1.1, lineWidths=[gStyle.GetHistLineWidth()], fillStyles=[0], preserveStyle=False,
64 yOffset=1.05):
65  global overlayNum
66  global legs
67  if logY:
68  supressZero = True
69 
70  histMax = 0
71  histMin = sys.float_info.max
72  for hist in listOfHists:
73  hist.GetYaxis().SetTitleOffset(yOffset)
74  if hist.GetBinContent(hist.GetMaximumBin()) > histMax:
75  histMax = hist.GetBinContent(hist.GetMaximumBin())
76  if supressZero:
77  for i in range(1, hist.GetNbinsX()+ 1):
78  content = hist.GetBinContent(i)
79  if content >0 and content < histMin:
80  histMin = content
81  if supressZero:
82  axisMin = 0.9 * histMin
83  if not inputCan:
84  if name == "":
85  can = newCan("Overlay" + str(overlayNum) )
86  else:
87  can = newCan(name + "Overlay")
88  else:
89  can = inputCan
90  can.cd()
91 
92  counter = 0
93 
94  if logY:
95  can.SetLogy()
96  if not preserveStyle:
97  for hist in listOfHists:
98  hist.SetLineColor(colors[counter % len(colors)])
99  hist.SetLineWidth(lineWidths[counter % len(lineWidths)])
100  hist.SetLineStyle(lineStyles[counter % len(lineStyles)])
101  if fillStyles[counter % len(fillStyles)]:
102  hist.SetFillStyle(fillStyles[counter % len(fillStyles)])
103  hist.SetFillColor(colors[counter % len(colors)])
104  counter += 1
105  counter = 0
106  for hist in listOfHists:
107  hist.GetYaxis().SetRangeUser(axisMin, padFactor * histMax)
108  hist.Draw(opt + varOpts[counter % len(varOpts)])
109  line = TLine(0,1,10,0)
110  line.SetLineWidth(3)
111  line.SetLineColor(kGray)
112  line.SetLineStyle(2)
113  # line.DrawLineNDC(2,pow(listOfHists[0].GetMaximum(),0.58),10,pow(listOfHists[0].GetMaximum(),0.58))
114  if hist.GetSize() > 40:
115  line.DrawLineNDC(0.863,0.1,0.863,0.9)
116  else:
117  line.DrawLineNDC(0.72,0.1,0.72,0.9)
118  line.Draw("same")
119 
120  counter += 1
121  if not "SAME" in opt:
122  opt += "SAME"
123 
124  can.Update()
125 
126  if legPos == "right":
127  legs.append(TLegend(0.65, 0.6, 0.65 + legWidth, 0.6 + legHeight))
128  elif legPos == "mid":
129  legs.append(TLegend(0.4, 0.6, 0.4 + legWidth, 0.6 + legHeight))
130  elif legPos =="auto":
131  legs.append(autoPlaceLegend(legWidth, legHeight))
132  elif legPos == "left":
133  legs.append(TLegend(0.15, 0.6, 0.15 + legWidth, 0.6 + legHeight))
134  elif type(legPos) == type([]) and len(legPos) == 2:
135  legs.append(TLegend(legPos[0], legPos[1], legPos[0] + legWidth, legPos[1] + legHeight))
136  else:
137  print "Legend position", legPos, "is invalid."
138 
139  legs[overlayNum].SetFillColor(0)
140  if legTextSize:
141  legs[overlayNum].SetTextSize(legTextSize)
142  counter = 0
143 
144  for hist in listOfHists:
145  legStyle=''
146  if hist.GetFillStyle != 0:
147  legStyle += 'f'
148  if hist.GetLineWidth != 0:
149  legStyle += 'l'
150  if len(legEntries) == 0:
151  legs[overlayNum].AddEntry(hist, hist.GetName(), legStyle)
152  else:
153  legs[overlayNum].AddEntry(hist, legEntries[counter], legStyle)
154  counter += 1
155 
156 
157  legs[overlayNum].Draw()
158  overlayNum += 1
159  listOfHists[0].Draw("sameaxis")
160  return can
161 
162 def drawHists(listOfHists, opt= "", logY=False):
163  for hist in listOfHists:
164  c = newCan(hist.GetName())
165  if logY:
166  c.SetLogy()
167  hist.Draw(opt)
168 
169 def drawHist(hist, opt= "", logY=False):
170  c = newCan(hist.GetName())
171  if logY:
172  c.SetLogy()
173  hist.Draw(opt)
174  return c
175 
176 def getFileId(filePath):
177  fileName = os.path.split(filePath)[1]
178  extPos = fileName.find(".")
179  fileId = fileName[0:extPos]
180  return fileId
181 
183  def __init__(self, tree, increment=10000):
184  self.entries = float(tree.GetEntries())
185  self.increment = increment
186  self.progress = 0
187 
188 
189  def advance(self):
190  self.progress+=1
191  if not self.progress%self.increment:
192  print "Event: ", self.progress, str(self.progress / self.entries)[:6]
193 
194 
195 def sqr(x):
196  return x*x
197 def sign(x):
198  if x >= 0:
199  return 1
200  return -1
201 
202 def PointDistanceToBox(x, y, x0, y0, x1, y1):
203  # Inside
204  if x > x0 and x < x1 and y > y0 and y < y1:
205  return 0
206 
207  # Corners
208  d = sqr(x-x0)+sqr(y-y0);
209  d = min(d, sqr(x-x1)+sqr(y-y0))
210  d = min(d, sqr(x-x1)+sqr(y-y1))
211  d = min(d, sqr(x-x0)+sqr(y-y1))
212 
213  # Top and bottom edges
214  if x > x0 and x < x1:
215  d = min(d, sqr(y-y0))
216  d = min(d, sqr(y-y1))
217 
218  # Left and right
219  if y > y0 and y < y1:
220  d = min(d, sqr(x-x0))
221  d = min(d, sqr(x-x1))
222 
223 
224  return d;
225 
226 
227 
228 def autoPlaceLegend(dx, dy, gridPoints=30):
229  gPad.Update()
230  # Convert requested width and height into physics coordinates
231  dx *= (gPad.GetX2()-gPad.GetX1())
232  dy *= (gPad.GetY2()-gPad.GetY1())
233 
234  # Range of axes in physics units, if log, these already have the log applied
235  x0 = gPad.GetUxmin()
236  x1 = gPad.GetUxmax()
237  y0 = gPad.GetUymin()
238  y1 = gPad.GetUymax()
239 
240 
241  X = x1-x0
242  Y = y1-y0
243 
244  bestd = 0
245  bestx = 0
246  besty = 0
247  for fallback in [False, True]:
248  if fallback:
249  print "falling back"
250  for x in drange(x0+dx/2, x1-dx/2, X/float(gridPoints)):
251  for y in drange(y0+dy/2, y1-dy/2, Y/float(gridPoints)):
252  d = 999999
253 
254 
255  # Repel from edges
256  """
257 
258  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)]
259  for dToEdge in dToEdges:
260  print dToEdge
261  if math.fabs(dToEdge) < 0.05:
262  d = 0
263  continue
264 
265  """
266 
267  d = min(d, sqr((x-dx/2-x0)/X))
268  d = min(d, sqr((x+dx/2-x1)/X))
269  d = min(d, sqr((y-dy/2-y0)/Y))
270  d = min(d, sqr((y+dy/2-y1)/Y))
271  if d < bestd:
272  continue
273 
274  prims = gPad.GetListOfPrimitives()
275  for obj in prims:
276 
277  if not obj.InheritsFrom(TH1.Class()):
278  continue
279  h = obj
280 
281  for n in range(0, h.GetNbinsX() + 1):
282  px = h.GetBinCenter(n)
283  py = h.GetBinContent(n)
284  if gPad.GetLogy():
285  if py > 0:
286  py = math.log10(py)
287  else:
288  py = gPad.GetUymin()
289  if fallback:
290  d = min(d, sqr((px-x)/X)+sqr((py-y)/Y))
291  else:
292 
293  d = min(d, PointDistanceToBox(px/X, py/Y,
294  (x-dx/2)/X, (y-dy/2)/Y,
295  (x+dx/2)/X, (y+dy/2)/Y))
296 
297  if d < bestd:
298  break;
299 
300  if d < bestd:
301  break;
302 
303 
304  if d > bestd:
305  bestd = d;
306  bestx = x;
307  besty = y;
308 
309 
310 
311 
312  if bestd != 0:
313  break # If we always collide, have to do fallback
314 
315  # Convert to pad coordinates
316  nx = float(bestx-gPad.GetX1())/(gPad.GetX2()-gPad.GetX1());
317  ny = float(besty-gPad.GetY1())/(gPad.GetY2()-gPad.GetY1());
318 
319  ndx = dx/float(gPad.GetX2()-gPad.GetX1());
320  ndy = dy/float(gPad.GetY2()-gPad.GetY1());
321 
322  return TLegend(nx-ndx/2, ny-ndy/2, nx+ndx/2, ny+ndy/2);
323 
324 
325 
326 class Table():
327  def __init__(self):
328  self.table = []
329 
330  def append(self, row):
331  self.table.append(row)
332 
333  def getLatex(self):
334  str = ""
335  table = self.table
336  nCol = len(table[0])
337  colDef = "| " + (" c |" * nCol)
338  str += "\\begin{center} \n \\begin{tabular} {" + colDef + "} \n \hline \n"
339 
340  col_width = [max(len(x) for x in col) for col in zip(*table)]
341  for line in table:
342  str += " " + " & ".join("{:{}}".format(x, col_width[i])
343  for i, x in enumerate(line)) + " \\\\ \hline \n"
344  str += " \\end{tabular} \n \\end{center}"
345  return str
346 
347  def getReadable(self):
348  str = ""
349  table = self.table
350  col_width = [max(len(x) for x in col) for col in zip(*table)]
351  for line in table:
352  str += "| " + " | ".join("{:{}}".format(x, col_width[i])
353  for i, x in enumerate(line)) + " | \n"
354 
355 
356  return str
357 
358  def printLatex(self):
359  print self.getLatex()
360 
361  def printReadable(self):
362  print self.getReadable()
363 
364  def writeLatex(self, outputFile):
365  outputFile.write(self.getReadable())
366 
367  def writeLatex(self, outputFile):
368  outputFile.write(self.getLatex())
tree Draw("slc.nhit")
def getFileId(filePath)
Definition: canMan.py:176
def advance(self)
Definition: canMan.py:189
bin1_2sigma SetFillColor(3)
c1 Update()
def writeLatex(self, outputFile)
Definition: canMan.py:364
def canUp()
Definition: canMan.py:33
prelim SetTextSize(2/30.)
def posUp()
Definition: canMan.py:43
def drange(start, stop, step=1)
Definition: canMan.py:5
def autoPlaceLegend(dx, dy, gridPoints=30)
Definition: canMan.py:228
def printReadable(self)
Definition: canMan.py:361
def drawHists(listOfHists, opt="", logY=False)
Definition: canMan.py:162
def append(self, row)
Definition: canMan.py:330
def __init__(self)
Definition: canMan.py:327
leg AddEntry(GRdata,"data","p")
std::string format(const int32_t &value, const int &ndigits=8)
Definition: HexUtils.cpp:14
def getTVectorFromList(list)
Definition: canMan.py:49
static float min(const float a, const float b, const float c)
Definition: absgeo.cxx:45
def sqr(x)
Definition: canMan.py:195
def saveCans(prefix="", suffix=".pdf")
Definition: canMan.py:39
cosmicTree SaveAs("cosmicTree.root")
def getReadable(self)
Definition: canMan.py:347
T max(sqlite3 *const db, std::string const &table_name, std::string const &column_name)
Definition: statistics.h:68
def printLatex(self)
Definition: canMan.py:358
def drawHist(hist, opt="", logY=False)
Definition: canMan.py:169
def __init__(self, tree, increment=10000)
Definition: canMan.py:183
def newCan(title)
Definition: canMan.py:19
def drawOverlay(listOfHists, name="", opt="hist", varOpts=[""], colors=[kRed, kBlue, kGreen, kMagenta, kOrange, kBlack, kViolet, lineStyles=[1], legEntries=[], logY=False, axisMin=0, legPos="right", legTextSize=0, inputCan=None, legHeight=0.15, legWidth=0.2, supressZero=False, padFactor=1.1, lineWidths=[gStyle.GetHistLineWidth()], fillStyles=[0], preserveStyle=False, yOffset=1.05)
Definition: canMan.py:64
def getLatex(self)
Definition: canMan.py:333
def PointDistanceToBox(x, y, x0, y0, x1, y1)
Definition: canMan.py:202
def sign(x)
Definition: canMan.py:197