ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/OSUT3Analysis/Configuration/scripts/makePlots.py
Revision: 1.39
Committed: Tue Jun 4 08:02:28 2013 UTC (11 years, 11 months ago) by wulsin
Content type: text/x-python
Branch: MAIN
Changes since 1.38: +3 -2 lines
Log Message:
add -R, --ratioYRange option to set the maximum range of the ratio plot

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 RatioYRange = float(arguments.ratioYRange)
483 Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange)
484 elif makeDiffPlots:
485 YMax = Comparison.GetMaximum()
486 YMin = Comparison.GetMinimum()
487 if YMax <= 0 and YMin <= 0:
488 Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
489 elif YMax >= 0 and YMin >= 0:
490 Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
491 else: #axis crosses y=0
492 if abs(YMax) > abs(YMin):
493 Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
494 else:
495 Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)
496
497 Comparison.GetYaxis().SetNdivisions(205)
498 Comparison.Draw()
499
500 Canvas.Write()
501 if arguments.savePDFs:
502 pathToDirString = pathToDir.replace(' ','_').replace('<','lt').replace('>','gt').replace('(','').replace(')','').replace('=','eq')
503 Canvas.SaveAs(condor_dir+"/stacked_histograms_pdfs/"+pathToDirString+"/"+histogramName+".pdf")
504
505
506 ##########################################################################################################################################
507 ##########################################################################################################################################
508 ##########################################################################################################################################
509
510 def MakeTwoDHist(pathToDir,histogramName):
511 numBgMCSamples = 0
512 numDataSamples = 0
513 numSignalSamples = 0
514
515 LumiLabel = TPaveLabel(0.1,0.8,0.34,0.9,LumiText,"NDC")
516 LumiLabel.SetBorderSize(0)
517 LumiLabel.SetFillColor(0)
518 LumiLabel.SetFillStyle(0)
519
520 BgMCLegend = TLegend(0.76,0.65,0.99,0.9)
521 BgMCLegend.AddEntry (0, "Data & Bkgd. MC", "H").SetTextFont (62)
522 BgMCLegend.SetBorderSize(0)
523 BgMCLegend.SetFillColor(0)
524 BgMCLegend.SetFillStyle(0)
525 SignalMCLegend = TLegend(0.76,0.135,0.99,0.377)
526 SignalMCLegend.AddEntry (0, "Signal MC", "H").SetTextFont (62)
527 SignalMCLegend.SetBorderSize(0)
528 SignalMCLegend.SetFillColor(0)
529 SignalMCLegend.SetFillStyle(0)
530
531 outputFile.cd(pathToDir)
532 Canvas = TCanvas(histogramName)
533 Canvas.SetRightMargin(0.2413793);
534 BgMCHistograms = []
535 SignalMCHistograms = []
536 DataHistograms = []
537
538 for sample in processed_datasets: # loop over different samples as listed in configurationOptions.py
539 dataset_file = "%s/%s.root" % (condor_dir,sample)
540 inputFile = TFile(dataset_file)
541 Histogram = inputFile.Get(pathToDir+"/"+histogramName).Clone()
542 Histogram.SetDirectory(0)
543 RebinFactor = int(arguments.rebinFactor)
544 if arguments.rebinFactor and Histogram.GetNbinsX() >= RebinFactor*10 and Histogram.GetNbinsY() >= RebinFactor*10:
545 Histogram.Rebin2D(RebinFactor)
546 inputFile.Close()
547 xAxisLabel = Histogram.GetXaxis().GetTitle()
548 yAxisLabel = Histogram.GetYaxis().GetTitle()
549 histoTitle = Histogram.GetTitle()
550
551 if( types[sample] == "bgMC"):
552
553 numBgMCSamples += 1
554 Histogram.SetMarkerColor(colors[sample])
555 Histogram.SetFillColor(colors[sample])
556 BgMCLegend.AddEntry(Histogram,labels[sample],"F").SetTextFont (42)
557 BgMCHistograms.append(Histogram)
558
559 elif( types[sample] == "signalMC"):
560
561 numSignalSamples += 1
562 Histogram.SetMarkerColor(colors[sample])
563 Histogram.SetFillColor(colors[sample])
564 SignalMCLegend.AddEntry(Histogram,labels[sample],"F").SetTextFont (42)
565 SignalMCHistograms.append(Histogram)
566
567 elif( types[sample] == "data"):
568
569 numDataSamples += 1
570 Histogram.SetMarkerColor(colors[sample])
571 Histogram.SetFillColor(colors[sample])
572 BgMCLegend.AddEntry(Histogram,labels[sample],"F").SetTextFont (42)
573 DataHistograms.append(Histogram)
574
575
576 outputFile.cd(pathToDir)
577
578 if(numBgMCSamples is not 0):
579 BgMCHistograms[0].SetTitle(histoTitle)
580 BgMCHistograms[0].GetXaxis().SetTitle(xAxisLabel)
581 BgMCHistograms[0].GetYaxis().SetTitle(yAxisLabel)
582 BgMCHistograms[0].Draw()
583 for signalMCHist in SignalMCHistograms:
584 signalMCHist.Draw("SAME")
585 for dataHist in DataHistograms:
586 dataHist.Draw("SAME")
587
588 elif(numSignalSamples is not 0):
589 SignalMCHistograms[0].SetTitle(histoTitle)
590 SignalMCHistograms[0].Draw()
591 SignalMCHistograms[0].GetXaxis().SetTitle(xAxisLabel)
592 SignalMCHistograms[0].GetYaxis().SetTitle(yAxisLabel)
593 for signalMCHist in SignalMCHistograms:
594 if(signalMCHist is not SignalMCHistograms[0]):
595 signalMCHist.Draw("SAME")
596 for dataHist in DataHistograms:
597 dataHist.Draw("SAME")
598
599 elif(numDataSamples is not 0):
600 DataHistograms[0].SetTitle(histoTitle)
601 DataHistograms[0].GetXaxis().SetTitle(xAxisLabel)
602 DataHistograms[0].GetYaxis().SetTitle(yAxisLabel)
603 DataHistograms[0].Draw()
604 for dataHist in DataHistograms:
605 if(dataHist is not DataHistograms[0]):
606 dataHist.Draw("SAME")
607
608
609 if(numBgMCSamples is not 0 or numDataSamples is not 0):
610 BgMCLegend.Draw()
611 if(numSignalSamples is not 0):
612 SignalMCLegend.Draw()
613 if not arguments.normalizeToUnitArea or numDataSamples > 0:
614 LumiLabel.Draw()
615
616 Canvas.Write()
617
618
619
620
621 ##########################################################################################################################################
622 ##########################################################################################################################################
623 ##########################################################################################################################################
624
625 processed_datasets = []
626
627 condor_dir = set_condor_output_dir(arguments)
628
629 #### check which input datasets have valid output files
630 for sample in datasets:
631 fileName = condor_dir + "/" + sample + ".root"
632 if not os.path.exists(fileName):
633 continue
634 testFile = TFile(fileName)
635 if testFile.IsZombie() or not testFile.GetNkeys():
636 continue
637 processed_datasets.append(sample)
638
639 if len(processed_datasets) is 0:
640 sys.exit("No datasets have been processed")
641
642
643 #### make output file
644 outputFileName = "stacked_histograms.root"
645 if arguments.outputFileName:
646 outputFileName = arguments.outputFileName
647
648 outputFile = TFile(condor_dir + "/" + outputFileName, "RECREATE")
649
650
651
652 #### use the first input file as a template and make stacked versions of all its histograms
653 inputFile = TFile(condor_dir + "/" + processed_datasets[0] + ".root")
654 inputFile.cd()
655 outputFile.cd()
656
657 if arguments.savePDFs:
658 os.system("rm -r %s/stacked_histograms_pdfs" % (condor_dir))
659 os.system("mkdir %s/stacked_histograms_pdfs" % (condor_dir))
660
661
662 #get root directory in the first layer, generally "OSUAnalysis"
663 for key in inputFile.GetListOfKeys():
664 if (key.GetClassName() != "TDirectoryFile"):
665 continue
666 rootDirectory = key.GetName()
667 outputFile.mkdir(rootDirectory)
668 if arguments.savePDFs:
669 os.system("mkdir %s/stacked_histograms_pdfs/%s" % (condor_dir,rootDirectory.replace(' ','_').replace('<','lt').replace('>','gt').replace('(','').replace(')','').replace('=','eq')))
670
671 #cd to root directory and look for histograms
672 inputFile.cd(rootDirectory)
673 for key2 in gDirectory.GetListOfKeys():
674
675 if re.match ('TH1', key2.GetClassName()): # found a 1-D histogram
676 MakeOneDHist(rootDirectory,key2.GetName())
677 elif re.match ('TH2', key2.GetClassName()) and arguments.draw2DPlots: # found a 2-D histogram
678 MakeTwoDHist(rootDirectory,key2.GetName())
679
680 elif (key2.GetClassName() == "TDirectoryFile"): # found a directory, cd there and look for histograms
681 level2Directory = rootDirectory+"/"+key2.GetName()
682
683 #make a corresponding directory in the output file
684 outputFile.cd(rootDirectory)
685 gDirectory.mkdir(key2.GetName())
686 if arguments.savePDFs:
687 os.system("mkdir %s/stacked_histograms_pdfs/%s" % (condor_dir,level2Directory.replace(' ','_').replace('<','lt').replace('>','gt').replace('(','').replace(')','').replace('=','eq')))
688
689 #####################################################
690 ### This layer is typically the "channels" layer ###
691 #####################################################
692
693 inputFile.cd(level2Directory)
694 for key3 in gDirectory.GetListOfKeys():
695 if re.match ('TH1', key3.GetClassName()): # found a 1-D histogram
696 MakeOneDHist(level2Directory,key3.GetName())
697 elif re.match ('TH2', key3.GetClassName()) and arguments.draw2DPlots: # found a 2-D histogram
698 MakeTwoDHist(level2Directory,key3.GetName())
699
700 elif (key3.GetClassName() == "TDirectoryFile"): # found a directory, cd there and look for histograms
701 level3Directory = level2Directory+"/"+key3.GetName()
702
703 #make a corresponding directory in the output file
704 outputFile.cd(level2Directory)
705 gDirectory.mkdir(key3.GetName())
706 if arguments.savePDFs:
707 os.system("mkdir %s/stacked_histograms_pdfs/%s" % (condor_dir,level3Directory.replace(' ','_').replace('<','lt').replace('>','gt').replace('(','').replace(')','').replace('=','eq')))
708
709 #################################################
710 ### This layer is typically the "cuts" layer ###
711 #################################################
712
713 inputFile.cd(level3Directory)
714 for key3 in gDirectory.GetListOfKeys():
715 if re.match ('TH1', key3.GetClassName()): # found a 1-D histogram
716 MakeOneDHist(level3Directory,key3.GetName())
717 elif re.match ('TH2', key3.GetClassName()) and arguments.draw2DPlots: # found a 2-D histogram
718 MakeTwoDHist(level3Directory,key3.GetName())
719
720
721 outputFile.Close()