ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/OSUT3Analysis/Configuration/scripts/makePlots.py
Revision: 1.37
Committed: Fri May 31 14:28:09 2013 UTC (11 years, 11 months ago) by lantonel
Content type: text/x-python
Branch: MAIN
Changes since 1.36: +35 -5 lines
Log Message:
ratio plots now merge bins until the the error < 10%

File Contents

# Content
1 #!/usr/bin/env python
2 import sys
3 import os
4 import re
5 from math import *
6 from array import *
7 from decimal import *
8 from optparse import OptionParser
9 from OSUT3Analysis.Configuration.configurationOptions import *
10 from OSUT3Analysis.Configuration.processingUtilities import *
11
12
13
14 ### parse the command-line options
15
16 parser = OptionParser()
17 parser = set_commandline_arguments(parser)
18 (arguments, args) = parser.parse_args()
19
20 if arguments.localConfig:
21 sys.path.append(os.getcwd())
22 exec("from " + arguments.localConfig.rstrip('.py') + " import *")
23
24
25 #### deal with conflicting arguments
26 if arguments.normalizeToData and arguments.normalizeToUnitArea:
27 print "Conflicting normalizations requsted, will normalize to unit area"
28 arguments.normalizeToData = False
29 if arguments.normalizeToData and arguments.noStack:
30 print "You have asked to scale non-stacked backgrounds to data. This is a very strange request. Will normalize to unit area instead"
31 arguments.normalizeToData = False
32 arguments.normalizeToUnitArea = True
33 if arguments.makeRatioPlots and arguments.makeDiffPlots:
34 print "You have requested both ratio and difference plots. Will make just ratio plots instead"
35 arguments.makeRatioPlots = False
36
37
38 from ROOT import TFile, gROOT, gStyle, gDirectory, TStyle, THStack, TH1F, TCanvas, TString, TLegend, TLegendEntry, THStack, TIter, TKey, TPaveLabel, gPad
39
40
41 ### setting ROOT options so our plots will look awesome and everyone will love us
42
43 gROOT.SetBatch()
44 gStyle.SetOptStat(0)
45 gStyle.SetCanvasBorderMode(0)
46 gStyle.SetPadBorderMode(0)
47 gStyle.SetPadColor(0)
48 gStyle.SetCanvasColor(0)
49 gStyle.SetTextFont(42)
50 gStyle.SetCanvasDefH(600)
51 gStyle.SetCanvasDefW(600)
52 gStyle.SetCanvasDefX(0)
53 gStyle.SetCanvasDefY(0)
54 gStyle.SetPadTopMargin(0.05)
55 gStyle.SetPadBottomMargin(0.13)
56 gStyle.SetPadLeftMargin(0.15)
57 gStyle.SetPadRightMargin(0.05)
58 gStyle.SetTitleColor(1, "XYZ")
59 gStyle.SetTitleFont(42, "XYZ")
60 gStyle.SetTitleSize(0.05, "XYZ")
61 gStyle.SetTitleXOffset(0.95)
62 gStyle.SetTitleYOffset(1.25)
63 gStyle.SetTextAlign(22)
64 gStyle.SetLabelColor(1, "XYZ")
65 gStyle.SetLabelFont(42, "XYZ")
66 gStyle.SetLabelOffset(0.007, "XYZ")
67 gStyle.SetLabelSize(0.05, "XYZ")
68 gStyle.SetAxisColor(1, "XYZ")
69 gStyle.SetStripDecimals(True)
70 gStyle.SetTickLength(0.03, "XYZ")
71 gStyle.SetNdivisions(510, "XYZ")
72 gStyle.SetPadTickX(1)
73 gStyle.SetPadTickY(1)
74 gROOT.ForceStyle()
75
76
77 #set the text for the luminosity label
78 if(intLumi < 1000.):
79 LumiText = "L_{int} = " + str(intLumi) + " pb^{-1}"
80 LumiText = "L_{int} = " + str.format('{0:.1f}', LumiInPb) + " pb^{-1}"
81 else:
82 LumiInFb = intLumi/1000.
83 LumiText = "L_{int} = " + str.format('{0:.1f}', LumiInFb) + " fb^{-1}"
84
85
86 #bestest place for lumi. label, in top left corner
87 topLeft_x_left = 0.1375839
88 topLeft_x_right = 0.4580537
89 topLeft_y_bottom = 0.8479021
90 topLeft_y_top = 0.9475524
91 topLeft_y_offset = 0.035
92
93
94 ##########################################################################################################################################
95 ##########################################################################################################################################
96 ##########################################################################################################################################
97
98 # some fancy-ass code from Andrzej Zuranski to merge bins in the ratio plot until the error goes below some threshold
99 def ratioHistogram( dataHist, mcHist, relErrMax=0.10):
100
101 def groupR(group):
102 Data,MC = [float(sum(hist.GetBinContent(i) for i in group)) for hist in [dataHist,mcHist]]
103 return (Data-MC)/MC if MC else 0
104
105 def groupErr(group):
106 Data,MC = [float(sum(hist.GetBinContent(i) for i in group)) for hist in [dataHist,mcHist]]
107 dataErr2,mcErr2 = [sum(hist.GetBinError(i)**2 for i in group) for hist in [dataHist,mcHist]]
108 return abs(math.sqrt( (dataErr2+mcErr2)/(Data-MC)**2 + mcErr2/MC**2 ) * (Data-MC)/MC) if Data and MC else 0
109
110 def regroup(groups):
111 err,iG = max( (groupErr(g),groups.index(g)) for g in groups )
112 if err < relErrMax or len(groups)<3 : return groups
113 iH = max( [iG-1,iG+1], key = lambda i: groupErr(groups[i]) if 0<=i<len(groups) else -1 )
114 iLo,iHi = sorted([iG,iH])
115 return regroup(groups[:iLo] + [groups[iLo]+groups[iHi]] + groups[iHi+1:])
116
117 groups = regroup( [(i,) for i in range(1,1+dataHist.GetNbinsX())] )
118 ratio = TH1F("ratio","",len(groups), array('d', [dataHist.GetBinLowEdge(min(g)) for g in groups ] + [dataHist.GetXaxis().GetBinUpEdge(dataHist.GetNbinsX())]) )
119 for i,g in enumerate(groups) :
120 ratio.SetBinContent(i+1,groupR(g))
121 ratio.SetBinError(i+1,groupErr(g))
122 ratio.SetLineColor(1)
123 ratio.SetLineWidth(2)
124
125 return ratio
126
127 ##########################################################################################################################################
128 ##########################################################################################################################################
129 ##########################################################################################################################################
130
131
132 def MakeOneDHist(pathToDir,histogramName):
133
134
135 numBgMCSamples = 0
136 numDataSamples = 0
137 numSignalSamples = 0
138
139 Stack = THStack("stack",histogramName)
140
141 LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC")
142 LumiLabel.SetBorderSize(0)
143 LumiLabel.SetTextSize(0.32)
144 LumiLabel.SetFillColor(0)
145 LumiLabel.SetFillStyle(0)
146
147 NormLabel = TPaveLabel()
148 NormLabel.SetDrawOption("NDC")
149 NormLabel.SetX1NDC(topLeft_x_left)
150 NormLabel.SetX2NDC(topLeft_x_right)
151
152 NormLabel.SetBorderSize(0)
153 NormLabel.SetTextSize(0.32)
154 NormLabel.SetFillColor(0)
155 NormLabel.SetFillStyle(0)
156
157 NormText = ""
158 if arguments.normalizeToUnitArea:
159 NormText = "Scaled to unit area"
160 elif arguments.normalizeToData:
161 NormText = "MC scaled to data"
162 NormLabel.SetLabel(NormText)
163
164
165 BgMCLegend = TLegend()
166 BgTitle = BgMCLegend.AddEntry(0, "Data & Bkgd. MC", "H")
167 BgTitle.SetTextAlign(22)
168 BgTitle.SetTextFont(62)
169 BgMCLegend.SetBorderSize(0)
170 BgMCLegend.SetFillColor(0)
171 BgMCLegend.SetFillStyle(0)
172 SignalMCLegend = TLegend()
173 SignalTitle = SignalMCLegend.AddEntry(0, "Signal MC", "H")
174 SignalTitle.SetTextAlign(22)
175 SignalTitle.SetTextFont(62)
176 SignalMCLegend.SetBorderSize(0)
177 SignalMCLegend.SetFillColor(0)
178 SignalMCLegend.SetFillStyle(0)
179
180 outputFile.cd(pathToDir)
181 Canvas = TCanvas(histogramName)
182 BgMCHistograms = []
183 BgMCLegendEntries = []
184 SignalMCHistograms = []
185 SignalMCLegendEntries = []
186 DataHistograms = []
187 DataLegendEntries = []
188
189
190 backgroundIntegral = 0
191 dataIntegral = 0
192 scaleFactor = 1
193
194 for sample in processed_datasets: # loop over different samples as listed in configurationOptions.py
195 dataset_file = "%s/%s.root" % (condor_dir,sample)
196 inputFile = TFile(dataset_file)
197 Histogram = inputFile.Get(pathToDir+"/"+histogramName).Clone()
198 Histogram.SetDirectory(0)
199 inputFile.Close()
200 if arguments.rebinFactor:
201 RebinFactor = int(arguments.rebinFactor)
202 #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
203 if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle.find("GenMatch") is -1:
204 Histogram.Rebin(RebinFactor)
205
206 xAxisLabel = Histogram.GetXaxis().GetTitle()
207 histoTitle = Histogram.GetTitle()
208
209 legLabel = labels[sample]
210 if (arguments.printYields):
211 yieldHist = Histogram.Integral()
212 legLabel = legLabel + " (%.1f)" % yieldHist
213
214 if( types[sample] == "bgMC"):
215
216 numBgMCSamples += 1
217 backgroundIntegral += Histogram.Integral()
218
219 Histogram.SetLineStyle(1)
220 if(arguments.noStack):
221 Histogram.SetFillStyle(0)
222 Histogram.SetLineColor(colors[sample])
223 Histogram.SetLineWidth(2)
224 else:
225 Histogram.SetFillStyle(1001)
226 Histogram.SetFillColor(colors[sample])
227 Histogram.SetLineColor(1)
228 Histogram.SetLineWidth(1)
229
230 BgMCLegendEntries.append(legLabel)
231 BgMCHistograms.append(Histogram)
232
233
234 elif( types[sample] == "signalMC"):
235
236 numSignalSamples += 1
237
238 Histogram.SetFillStyle(0)
239 Histogram.SetLineColor(colors[sample])
240 Histogram.SetLineStyle(1)
241 Histogram.SetLineWidth(2)
242 if(arguments.normalizeToUnitArea and Histogram.Integral() > 0):
243 Histogram.Scale(1./Histogram.Integral())
244
245 SignalMCLegendEntries.append(legLabel)
246 SignalMCHistograms.append(Histogram)
247
248 elif( types[sample] == "data"):
249
250 numDataSamples += 1
251 dataIntegral += Histogram.Integral()
252
253 Histogram.SetFillStyle(0)
254 Histogram.SetLineColor(colors[sample])
255 Histogram.SetLineStyle(1)
256 Histogram.SetLineWidth(2)
257 if(arguments.normalizeToUnitArea and Histogram.Integral() > 0):
258 Histogram.Scale(1./Histogram.Integral())
259
260 DataLegendEntries.append(legLabel)
261 DataHistograms.append(Histogram)
262
263 #scaling histograms as per user's specifications
264 if dataIntegral > 0 and backgroundIntegral > 0:
265 scaleFactor = dataIntegral/backgroundIntegral
266 for bgMCHist in BgMCHistograms:
267 if arguments.normalizeToData:
268 bgMCHist.Scale(scaleFactor)
269
270 if arguments.normalizeToUnitArea and not arguments.noStack and backgroundIntegral > 0:
271 bgMCHist.Scale(1./backgroundIntegral)
272 elif arguments.normalizeToUnitArea and arguments.noStack and bgMCHist.Integral() > 0:
273 bgMCHist.Scale(1./bgMCHist.Integral())
274
275 if not arguments.noStack:
276 Stack.Add(bgMCHist)
277
278
279
280 ### formatting data histograms and adding to legend
281 legendIndex = 0
282 for Histogram in DataHistograms:
283 BgMCLegend.AddEntry(Histogram,DataLegendEntries[legendIndex],"LEP").SetTextFont (42)
284 legendIndex = legendIndex+1
285
286
287 ### creating the histogram to represent the statistical errors on the stack
288 if numBgMCSamples is not 0 and not arguments.noStack:
289 ErrorHisto = BgMCHistograms[0].Clone("errors")
290 ErrorHisto.SetFillStyle(3001)
291 ErrorHisto.SetFillColor(13)
292 ErrorHisto.SetLineWidth(0)
293 BgMCLegend.AddEntry(ErrorHisto,"Stat. Errors","F").SetTextFont (42)
294 for Histogram in BgMCHistograms:
295 if Histogram is not BgMCHistograms[0]:
296 ErrorHisto.Add(Histogram)
297
298
299 ### formatting bgMC histograms and adding to legend
300 legendIndex = numBgMCSamples-1
301 for Histogram in reversed(BgMCHistograms):
302 if(arguments.noStack):
303 BgMCLegend.AddEntry(Histogram,BgMCLegendEntries[legendIndex],"L").SetTextFont (42)
304 else:
305 BgMCLegend.AddEntry(Histogram,BgMCLegendEntries[legendIndex],"F").SetTextFont (42)
306 legendIndex = legendIndex-1
307
308
309 ### formatting signalMC histograms and adding to legend
310 legendIndex = 0
311 for Histogram in SignalMCHistograms:
312 SignalMCLegend.AddEntry(Histogram,SignalMCLegendEntries[legendIndex],"L").SetTextFont (42)
313 legendIndex = legendIndex+1
314
315
316 ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
317 finalMax = 0
318 if numBgMCSamples is not 0 and not arguments.noStack:
319 finalMax = ErrorHisto.GetMaximum() + ErrorHisto.GetBinError(ErrorHisto.GetMaximumBin())
320 else:
321 for bgMCHist in BgMCHistograms:
322 if(bgMCHist.GetMaximum() > finalMax):
323 finalMax = bgMCHist.GetMaximum()
324 for signalMCHist in SignalMCHistograms:
325 if(signalMCHist.GetMaximum() > finalMax):
326 finalMax = signalMCHist.GetMaximum()
327 for dataHist in DataHistograms:
328 if(dataHist.GetMaximum() > finalMax):
329 finalMax = dataHist.GetMaximum() + dataHist.GetBinError(dataHist.GetMaximumBin())
330 finalMax = 1.15*finalMax
331
332
333 ### Drawing histograms to canvas
334
335 outputFile.cd(pathToDir)
336
337 makeRatioPlots = arguments.makeRatioPlots
338 makeDiffPlots = arguments.makeDiffPlots
339
340 if numBgMCSamples is 0 or numDataSamples is not 1:
341 makeRatioPlots = False
342 makeDiffPlots = False
343 if makeRatioPlots or makeDiffPlots:
344 Canvas.SetFillStyle(0)
345 Canvas.Divide(1,2)
346 Canvas.cd(1)
347 gPad.SetPad(0.01,0.25,0.99,0.99)
348 gPad.SetMargin(0.1,0.05,0.02,0.07)
349 gPad.SetFillStyle(0)
350 gPad.Update()
351 gPad.Draw()
352 Canvas.cd(2)
353 gPad.SetPad(0.01,0.01,0.99,0.25)
354 #format: gPad.SetMargin(l,r,b,t)
355 gPad.SetMargin(0.1,0.05,0.4,0.02)
356 gPad.SetFillStyle(0)
357 gPad.SetGridy(1)
358 gPad.Update()
359 gPad.Draw()
360
361 Canvas.cd(1)
362
363 if numBgMCSamples is not 0: # the first thing to draw to the canvas is a bgMC sample
364
365
366 if not arguments.noStack: # draw unstacked background samples
367 Stack.SetTitle(histoTitle)
368 Stack.Draw("HIST")
369 Stack.GetXaxis().SetTitle(xAxisLabel)
370 Stack.SetMaximum(finalMax)
371 Stack.SetMinimum(0.0001)
372 if makeRatioPlots or makeDiffPlots:
373 Stack.GetHistogram().GetXaxis().SetLabelSize(0)
374 #draw shaded error bands
375 ErrorHisto.Draw("A E2 SAME")
376
377 else: #draw the stacked backgrounds
378 BgMCHistograms[0].SetTitle(histoTitle)
379 BgMCHistograms[0].Draw("HIST")
380 BgMCHistograms[0].GetXaxis().SetTitle(xAxisLabel)
381 BgMCHistograms[0].SetMaximum(finalMax)
382 BgMCHistograms[0].SetMinimum(0.0001)
383 for bgMCHist in BgMCHistograms:
384 bgMCHist.Draw("A HIST SAME")
385
386 for signalMCHist in SignalMCHistograms:
387 signalMCHist.Draw("A HIST SAME")
388 for dataHist in DataHistograms:
389 dataHist.Draw("A E SAME")
390
391
392 elif numSignalSamples is not 0: # the first thing to draw to the canvas is a signalMC sample
393 SignalMCHistograms[0].SetTitle(histoTitle)
394 SignalMCHistograms[0].Draw("HIST")
395 SignalMCHistograms[0].GetXaxis().SetTitle(xAxisLabel)
396 SignalMCHistograms[0].SetMaximum(finalMax)
397 SignalMCHistograms[0].SetMinimum(0.0001)
398
399 for signalMCHist in SignalMCHistograms:
400 if(signalMCHist is not SignalMCHistograms[0]):
401 signalMCHist.Draw("A HIST SAME")
402 for dataHist in DataHistograms:
403 dataHist.Draw("A E SAME")
404
405
406 elif(numDataSamples is not 0): # the first thing to draw to the canvas is a data sample
407 DataHistograms[0].SetTitle(histoTitle)
408 DataHistograms[0].Draw("E")
409 DataHistograms[0].GetXaxis().SetTitle(xAxisLabel)
410 DataHistograms[0].SetMaximum(finalMax)
411 DataHistograms[0].SetMinimum(0.0001)
412 for dataHist in DataHistograms:
413 if(dataHist is not DataHistograms[0]):
414 dataHist.Draw("A E SAME")
415
416
417
418 #legend coordinates, empirically determined :-)
419 x_left = 0.6761745
420 x_right = 0.9328859
421 x_width = x_right - x_left
422 y_max = 0.9335664
423 entry_height = 0.05
424
425 if(numBgMCSamples is not 0 or numDataSamples is not 0): #then draw the data & bgMC legend
426
427 numExtraEntries = 1 # count the legend title
428 BgMCLegend.SetX1NDC(x_left)
429 if numBgMCSamples > 0:
430 numExtraEntries = numExtraEntries + 1 # count the stat. errors entry
431
432 BgMCLegend.SetY1NDC(y_max-entry_height*(numExtraEntries+numBgMCSamples+numDataSamples))
433 BgMCLegend.SetX2NDC(x_right)
434 BgMCLegend.SetY2NDC(y_max)
435 BgMCLegend.Draw()
436
437 if(numSignalSamples is not 0): #then draw the signalMC legend to the left of the other one
438 SignalMCLegend.SetX1NDC(x_left-x_width)
439 SignalMCLegend.SetY1NDC(y_max-entry_height*(1+numSignalSamples)) # add one for the title
440 SignalMCLegend.SetX2NDC(x_left)
441 SignalMCLegend.SetY2NDC(y_max)
442 SignalMCLegend.Draw()
443
444 elif numSignalSamples is not 0: #draw the signalMC legend in the upper right corner
445 SignalMCLegend.SetX1NDC(x_left)
446 SignalMCLegend.SetY1NDC(y_max-entry_height*(1+numSignalSamples)) # add one for the title
447 SignalMCLegend.SetX2NDC(x_right)
448 SignalMCLegend.SetY2NDC(y_max)
449 SignalMCLegend.Draw()
450
451
452 if not arguments.normalizeToUnitArea or numDataSamples > 0: #don't draw the lumi label if there's no data and it's scaled to unit area
453 LumiLabel.Draw()
454 if arguments.normalizeToUnitArea or arguments.normalizeToData:
455 #move the normalization label down before drawing if we drew the lumi. label
456 NormLabel.SetY1NDC(topLeft_y_bottom-topLeft_y_offset)
457 NormLabel.SetY2NDC(topLeft_y_top-topLeft_y_offset)
458 NormLabel.Draw()
459
460 elif arguments.normalizeToUnitArea or arguments.normalizeToData:
461 NormLabel.SetY1NDC(topLeft_y_bottom)
462 NormLabel.SetY2NDC(topLeft_y_top)
463 NormLabel.Draw()
464
465
466 if makeRatioPlots or makeDiffPlots:
467 Canvas.cd(2)
468 BgSum = Stack.GetStack().Last()
469 Comparison = ratioHistogram(DataHistograms[0],BgSum)
470 Comparison.GetXaxis().SetTitle(xAxisLabel)
471 if makeRatioPlots:
472 Comparison.GetYaxis().SetTitle("#frac{Data-MC}{MC}")
473 elif makeDiffPlots:
474 Comparison.GetYaxis().SetTitle("Data-MC")
475 Comparison.GetYaxis().CenterTitle()
476 Comparison.GetYaxis().SetTitleSize(0.1)
477 Comparison.GetYaxis().SetTitleOffset(0.35)
478 Comparison.GetXaxis().SetTitleSize(0.15)
479 Comparison.GetYaxis().SetLabelSize(0.1)
480 Comparison.GetXaxis().SetLabelSize(0.15)
481 if makeRatioPlots:
482 Comparison.GetYaxis().SetRangeUser(-1.15,1.15)
483 elif makeDiffPlots:
484 YMax = Comparison.GetMaximum()
485 YMin = Comparison.GetMinimum()
486 if YMax <= 0 and YMin <= 0:
487 Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
488 elif YMax >= 0 and YMin >= 0:
489 Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
490 else: #axis crosses y=0
491 if abs(YMax) > abs(YMin):
492 Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
493 else:
494 Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)
495
496 Comparison.GetYaxis().SetNdivisions(205)
497 Comparison.Draw()
498
499 Canvas.Write()
500 if arguments.savePDFs:
501 pathToDirString = pathToDir.replace(' ','_').replace('<','lt').replace('>','gt').replace('(','').replace(')','').replace('=','eq')
502 Canvas.SaveAs(condor_dir+"/stacked_histograms_pdfs/"+pathToDirString+"/"+histogramName+".pdf")
503
504
505 ##########################################################################################################################################
506 ##########################################################################################################################################
507 ##########################################################################################################################################
508
509 def MakeTwoDHist(pathToDir,histogramName):
510 numBgMCSamples = 0
511 numDataSamples = 0
512 numSignalSamples = 0
513
514 LumiLabel = TPaveLabel(0.1,0.8,0.34,0.9,LumiText,"NDC")
515 LumiLabel.SetBorderSize(0)
516 LumiLabel.SetFillColor(0)
517 LumiLabel.SetFillStyle(0)
518
519 BgMCLegend = TLegend(0.76,0.65,0.99,0.9)
520 BgMCLegend.AddEntry (0, "Data & Bkgd. MC", "H").SetTextFont (62)
521 BgMCLegend.SetBorderSize(0)
522 BgMCLegend.SetFillColor(0)
523 BgMCLegend.SetFillStyle(0)
524 SignalMCLegend = TLegend(0.76,0.135,0.99,0.377)
525 SignalMCLegend.AddEntry (0, "Signal MC", "H").SetTextFont (62)
526 SignalMCLegend.SetBorderSize(0)
527 SignalMCLegend.SetFillColor(0)
528 SignalMCLegend.SetFillStyle(0)
529
530 outputFile.cd(pathToDir)
531 Canvas = TCanvas(histogramName)
532 Canvas.SetRightMargin(0.2413793);
533 BgMCHistograms = []
534 SignalMCHistograms = []
535 DataHistograms = []
536
537 for sample in processed_datasets: # loop over different samples as listed in configurationOptions.py
538 dataset_file = "%s/%s.root" % (condor_dir,sample)
539 inputFile = TFile(dataset_file)
540 Histogram = inputFile.Get(pathToDir+"/"+histogramName).Clone()
541 Histogram.SetDirectory(0)
542 RebinFactor = int(arguments.rebinFactor)
543 if arguments.rebinFactor and Histogram.GetNbinsX() >= RebinFactor*10 and Histogram.GetNbinsY() >= RebinFactor*10:
544 Histogram.Rebin2D(RebinFactor)
545 inputFile.Close()
546 xAxisLabel = Histogram.GetXaxis().GetTitle()
547 yAxisLabel = Histogram.GetYaxis().GetTitle()
548 histoTitle = Histogram.GetTitle()
549
550 if( types[sample] == "bgMC"):
551
552 numBgMCSamples += 1
553 Histogram.SetMarkerColor(colors[sample])
554 Histogram.SetFillColor(colors[sample])
555 BgMCLegend.AddEntry(Histogram,labels[sample],"F").SetTextFont (42)
556 BgMCHistograms.append(Histogram)
557
558 elif( types[sample] == "signalMC"):
559
560 numSignalSamples += 1
561 Histogram.SetMarkerColor(colors[sample])
562 Histogram.SetFillColor(colors[sample])
563 SignalMCLegend.AddEntry(Histogram,labels[sample],"F").SetTextFont (42)
564 SignalMCHistograms.append(Histogram)
565
566 elif( types[sample] == "data"):
567
568 numDataSamples += 1
569 Histogram.SetMarkerColor(colors[sample])
570 Histogram.SetFillColor(colors[sample])
571 BgMCLegend.AddEntry(Histogram,labels[sample],"F").SetTextFont (42)
572 DataHistograms.append(Histogram)
573
574
575 outputFile.cd(pathToDir)
576
577 if(numBgMCSamples is not 0):
578 BgMCHistograms[0].SetTitle(histoTitle)
579 BgMCHistograms[0].GetXaxis().SetTitle(xAxisLabel)
580 BgMCHistograms[0].GetYaxis().SetTitle(yAxisLabel)
581 BgMCHistograms[0].Draw()
582 for signalMCHist in SignalMCHistograms:
583 signalMCHist.Draw("SAME")
584 for dataHist in DataHistograms:
585 dataHist.Draw("SAME")
586
587 elif(numSignalSamples is not 0):
588 SignalMCHistograms[0].SetTitle(histoTitle)
589 SignalMCHistograms[0].Draw()
590 SignalMCHistograms[0].GetXaxis().SetTitle(xAxisLabel)
591 SignalMCHistograms[0].GetYaxis().SetTitle(yAxisLabel)
592 for signalMCHist in SignalMCHistograms:
593 if(signalMCHist is not SignalMCHistograms[0]):
594 signalMCHist.Draw("SAME")
595 for dataHist in DataHistograms:
596 dataHist.Draw("SAME")
597
598 elif(numDataSamples is not 0):
599 DataHistograms[0].SetTitle(histoTitle)
600 DataHistograms[0].GetXaxis().SetTitle(xAxisLabel)
601 DataHistograms[0].GetYaxis().SetTitle(yAxisLabel)
602 DataHistograms[0].Draw()
603 for dataHist in DataHistograms:
604 if(dataHist is not DataHistograms[0]):
605 dataHist.Draw("SAME")
606
607
608 if(numBgMCSamples is not 0 or numDataSamples is not 0):
609 BgMCLegend.Draw()
610 if(numSignalSamples is not 0):
611 SignalMCLegend.Draw()
612 if not arguments.normalizeToUnitArea or numDataSamples > 0:
613 LumiLabel.Draw()
614
615 Canvas.Write()
616
617
618
619
620 ##########################################################################################################################################
621 ##########################################################################################################################################
622 ##########################################################################################################################################
623
624 processed_datasets = []
625
626 condor_dir = set_condor_output_dir(arguments)
627
628 #### check which input datasets have valid output files
629 for sample in datasets:
630 fileName = condor_dir + "/" + sample + ".root"
631 if not os.path.exists(fileName):
632 continue
633 testFile = TFile(fileName)
634 if testFile.IsZombie() or not testFile.GetNkeys():
635 continue
636 processed_datasets.append(sample)
637
638 if len(processed_datasets) is 0:
639 sys.exit("No datasets have been processed")
640
641
642 #### make output file
643 outputFileName = "stacked_histograms.root"
644 if arguments.outputFileName:
645 outputFileName = arguments.outputFileName
646
647 outputFile = TFile(condor_dir + "/" + outputFileName, "RECREATE")
648
649
650
651 #### use the first input file as a template and make stacked versions of all its histograms
652 inputFile = TFile(condor_dir + "/" + processed_datasets[0] + ".root")
653 inputFile.cd()
654 outputFile.cd()
655
656 if arguments.savePDFs:
657 os.system("rm -r %s/stacked_histograms_pdfs" % (condor_dir))
658 os.system("mkdir %s/stacked_histograms_pdfs" % (condor_dir))
659
660
661 #get root directory in the first layer, generally "OSUAnalysis"
662 for key in inputFile.GetListOfKeys():
663 if (key.GetClassName() != "TDirectoryFile"):
664 continue
665 rootDirectory = key.GetName()
666 outputFile.mkdir(rootDirectory)
667 if arguments.savePDFs:
668 os.system("mkdir %s/stacked_histograms_pdfs/%s" % (condor_dir,rootDirectory.replace(' ','_').replace('<','lt').replace('>','gt').replace('(','').replace(')','').replace('=','eq')))
669
670 #cd to root directory and look for histograms
671 inputFile.cd(rootDirectory)
672 for key2 in gDirectory.GetListOfKeys():
673
674 if re.match ('TH1', key2.GetClassName()): # found a 1-D histogram
675 MakeOneDHist(rootDirectory,key2.GetName())
676 elif re.match ('TH2', key2.GetClassName()) and arguments.draw2DPlots: # found a 2-D histogram
677 MakeTwoDHist(rootDirectory,key2.GetName())
678
679 elif (key2.GetClassName() == "TDirectoryFile"): # found a directory, cd there and look for histograms
680 level2Directory = rootDirectory+"/"+key2.GetName()
681
682 #make a corresponding directory in the output file
683 outputFile.cd(rootDirectory)
684 gDirectory.mkdir(key2.GetName())
685 if arguments.savePDFs:
686 os.system("mkdir %s/stacked_histograms_pdfs/%s" % (condor_dir,level2Directory.replace(' ','_').replace('<','lt').replace('>','gt').replace('(','').replace(')','').replace('=','eq')))
687
688 #####################################################
689 ### This layer is typically the "channels" layer ###
690 #####################################################
691
692 inputFile.cd(level2Directory)
693 for key3 in gDirectory.GetListOfKeys():
694 if re.match ('TH1', key3.GetClassName()): # found a 1-D histogram
695 MakeOneDHist(level2Directory,key3.GetName())
696 elif re.match ('TH2', key3.GetClassName()) and arguments.draw2DPlots: # found a 2-D histogram
697 MakeTwoDHist(level2Directory,key3.GetName())
698
699 elif (key3.GetClassName() == "TDirectoryFile"): # found a directory, cd there and look for histograms
700 level3Directory = level2Directory+"/"+key3.GetName()
701
702 #make a corresponding directory in the output file
703 outputFile.cd(level2Directory)
704 gDirectory.mkdir(key3.GetName())
705 if arguments.savePDFs:
706 os.system("mkdir %s/stacked_histograms_pdfs/%s" % (condor_dir,level3Directory.replace(' ','_').replace('<','lt').replace('>','gt').replace('(','').replace(')','').replace('=','eq')))
707
708 #################################################
709 ### This layer is typically the "cuts" layer ###
710 #################################################
711
712 inputFile.cd(level3Directory)
713 for key3 in gDirectory.GetListOfKeys():
714 if re.match ('TH1', key3.GetClassName()): # found a 1-D histogram
715 MakeOneDHist(level3Directory,key3.GetName())
716 elif re.match ('TH2', key3.GetClassName()) and arguments.draw2DPlots: # found a 2-D histogram
717 MakeTwoDHist(level3Directory,key3.GetName())
718
719
720 outputFile.Close()