ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/OSUT3Analysis/Configuration/scripts/fitMCToData.py
Revision: 1.3
Committed: Sat Apr 13 21:53:52 2013 UTC (12 years ago) by ahart
Content type: text/x-python
Branch: MAIN
CVS Tags: V02-03-02, V02-03-01, V02-03-00, V02-02-00, V02-01-01, V02-01-00, V01-01-00, V01-00-01, V01-00-00, V02-00-00, V00-00-01, V00-01-00
Changes since 1.2: +5 -4 lines
Log Message:
Made the legend titles bold. Impossible to do? MYTH BUSTED

File Contents

# Content
1 #!/usr/bin/env python
2 import sys
3 import os
4 import re
5 from optparse import OptionParser
6 from array import *
7 from decimal import *
8
9 from OSUT3Analysis.Configuration.configurationOptions import *
10 from OSUT3Analysis.Configuration.processingUtilities import *
11
12 ##set default plotting options
13 line_width = 2
14 plotting_options = ""
15
16 parser = OptionParser()
17 parser = set_commandline_arguments(parser)
18
19 parser.add_option("--hist", action="store_true", dest="plot_hist", default=False,
20 help="plot as hollow histograms instead of error bar crosses")
21 parser.add_option("--line-width", dest="line_width",
22 help="set line width (default is 2)")
23 parser.add_option("--pdf", action="store_true", dest="plot_savePdf", default=False,
24 help="save plot as pdf in addition")
25
26 (arguments, args) = parser.parse_args()
27
28 if arguments.localConfig:
29 sys.path.insert(0,os.getcwd())
30 exec("from " + arguments.localConfig.rstrip('.py') + " import *")
31
32 outputFileName = "mc_fit_to_data.root"
33 if arguments.outputFileName:
34 outputFileName = arguments.outputFileName
35 pdfFileName = outputFileName[:-5] + ".pdf"
36
37 condor_dir = set_condor_output_dir(arguments)
38
39 if arguments.makeRatioPlots and arguments.makeDiffPlots:
40 print "You have requested both ratio and difference plots. Will make just ratio plots instead"
41 arguments.makeRatioPlots = False
42
43 from ROOT import TFile, gROOT, gStyle, gDirectory, TStyle, THStack, TH1F, TCanvas, TString, TLegend, TArrow, THStack, TIter, TKey, TPaveLabel, TPaveText, TF1, gPad
44 sys.argv = []
45 gROOT.SetBatch()
46 gStyle.SetOptStat(0)
47 gStyle.SetCanvasBorderMode(0)
48 gStyle.SetPadBorderMode(0)
49 gStyle.SetPadColor(0)
50 gStyle.SetCanvasColor(0)
51 gStyle.SetTextFont(42)
52 gROOT.ForceStyle()
53
54 outputFile = TFile(outputFileName, "RECREATE")
55
56 datasets_needed = []
57 for histogram in input_histograms:
58 for dataset in histogram['datasets']:
59 if dataset not in datasets_needed:
60 datasets_needed.append(dataset)
61 if histogram['target_dataset'] not in datasets_needed:
62 datasets_needed.append(histogram['target_dataset'])
63
64 #weight = intLumi / 10000.0
65 #for dataset in datasets_needed:
66 # dataset_file = "%s/%s.root" % (condor_dir,dataset)
67 # fin = TFile (dataset_file)
68 # flags = fin.Get ("flags")
69 # noWeights = flags and flags.GetBinContent (1)
70 # fin.Close ()
71 #
72 # if types[dataset] != "data" and not noWeights:
73 # os.system("mergeTFileServiceHistograms -i %s -o %s -w %g" % (dataset_file, dataset_file + "_tmp", weight))
74 # else:
75 # os.system("mergeTFileServiceHistograms -i %s -o %s -w %g" % (dataset_file, dataset_file + "_tmp", 1.0))
76
77 for histogram in input_histograms:
78 HistogramsToFit = []
79 HistogramDatasets = []
80 TargetDataset = histogram['target_dataset']
81
82 Stack = []
83 Stack.append (THStack("stack_before",histogram['name']))
84 Stack.append (THStack("stack_after",histogram['name']))
85
86 if(intLumi < 1000.):
87 LumiText = "L_{int} = " + str(intLumi) + " pb^{-1}"
88 else:
89 getcontext().prec = 2
90 LumiInFb = intLumi/1000.
91 LumiText = "L_{int} = " + str(LumiInFb) + " fb^{-1}"
92
93 LumiLabel = TPaveLabel(0.1,0.8,0.34,0.9,LumiText,"NDC")
94 LumiLabel.SetBorderSize(0)
95 LumiLabel.SetFillColor(0)
96 LumiLabel.SetFillStyle(0)
97
98 Label = TPaveText(0.39, 0.7, 0.59, 0.9,"NDC")
99 Label.SetBorderSize(0)
100 Label.SetFillColor(0)
101 Label.SetFillStyle(0)
102 Label.SetTextAlign(12)
103
104 BgMCLegend = TLegend(0.70,0.65,0.94,0.89)
105 BgMCLegend.AddEntry (0, "Data & Bkgd. MC", "H").SetTextFont (62)
106 BgMCLegend.SetBorderSize(0)
107 BgMCLegend.SetFillColor(0)
108 BgMCLegend.SetFillStyle(0)
109
110 scaleFactor = 1
111
112 numBgMCSamples = 0
113 numDataSamples = 0
114 numSignalSamples = 0
115
116 fileName = condor_dir + "/" + histogram['target_dataset'] + ".root"
117 if not os.path.exists(fileName):
118 continue
119 inputFile = TFile(fileName)
120 if inputFile.IsZombie() or not inputFile.GetNkeys():
121 continue
122
123 Target = inputFile.Get("OSUAnalysis/"+histogram['channel']+"/"+histogram['name']).Clone()
124 Target.SetDirectory(0)
125 inputFile.Close()
126
127 numDataSamples += 1
128
129 Target.SetFillStyle(0)
130 Target.SetLineColor(colors[TargetDataset])
131 Target.SetLineStyle(1)
132 Target.SetLineWidth(2)
133
134 BgMCLegend.AddEntry(Target,labels[TargetDataset],"LEP").SetTextFont (42)
135
136 xAxisLabel = Target.GetXaxis().GetTitle()
137 histoTitle = Target.GetTitle()
138
139 if not outputFile.Get ("OSUAnalysis"):
140 outputFile.mkdir ("OSUAnalysis")
141 if not outputFile.Get ("OSUAnalysis/" + histogram['channel']):
142 outputFile.Get ("OSUAnalysis").mkdir (histogram['channel'])
143
144 for dataset in histogram['datasets']:
145 fileName = condor_dir + "/" + dataset + ".root"
146 if not os.path.exists(fileName):
147 continue
148 inputFile = TFile(fileName)
149 if inputFile.IsZombie() or not inputFile.GetNkeys():
150 continue
151
152 Histogram = inputFile.Get("OSUAnalysis/"+histogram['channel']+"/"+histogram['name']).Clone()
153 Histogram.SetDirectory(0)
154 inputFile.Close()
155
156 if arguments.rebinFactor:
157 RebinFactor = int(arguments.rebinFactor)
158 if Histogram.GetNbinsX() >= RebinFactor*10:
159 Histogram.Rebin(RebinFactor)
160
161 numBgMCSamples += 1
162
163 if(arguments.noStack):
164 Histogram.SetFillStyle(0)
165 Histogram.SetLineColor(colors[dataset])
166 Histogram.SetLineWidth(2)
167 BgMCLegend.AddEntry(Histogram,labels[dataset],"L").SetTextFont (42)
168 else:
169 Histogram.SetFillStyle(1001)
170 Histogram.SetFillColor(colors[dataset])
171 Histogram.SetLineColor(1)
172 Histogram.SetLineWidth(1)
173 BgMCLegend.AddEntry(Histogram,labels[dataset],"F").SetTextFont (42)
174 Histogram.SetLineStyle(1)
175
176 HistogramsToFit.append(Histogram)
177 HistogramDatasets.append(dataset)
178
179 def fitf (x, par):
180 xBin = HistogramsToFit[0].FindBin (x[0])
181 value = 0.0
182
183 for i in range (0, len (HistogramsToFit)):
184 value += par[i] * HistogramsToFit[i].GetBinContent (xBin)
185
186 return value
187
188 lowerLimit = Target.GetBinLowEdge (1)
189 upperLimit = Target.GetBinLowEdge (Target.GetNbinsX ()) + Target.GetBinWidth (Target.GetNbinsX ())
190 if 'lowerLimit' in histogram:
191 lowerLimit = histogram['lowerLimit']
192 if 'upperLimit' in histogram:
193 upperLimit = histogram['upperLimit']
194 func = TF1 ("fit", fitf, lowerLimit, upperLimit, len (HistogramsToFit))
195
196 for i in range (0, len (HistogramsToFit)):
197 func.SetParameter (i, 1.0)
198 func.SetParName (i, labels[HistogramDatasets[i]])
199
200 for i in range (0, histogram['iterations'] - 1):
201 print "Iteration " + str (i + 1) + "..."
202 Target.Fit ("fit", "QEMR0")
203 Target.Fit ("fit", "VEMR0")
204
205 func.SetLineWidth (line_width)
206 func.SetLineColor (632)
207
208 Target.SetMarkerStyle (20)
209 Target.SetMarkerColor (1)
210 Target.SetLineColor (1)
211
212 finalMax = 0
213 if not arguments.noStack:
214 for bgMCHist in HistogramsToFit:
215 finalMax += bgMCHist.GetMaximum()
216 else:
217 for bgMCHist in HistogramsToFit:
218 if(bgMCHist.GetMaximum() > finalMax):
219 finalMax = bgMCHist.GetMaximum()
220 if(Target.GetMaximum() > finalMax):
221 finalMax = Target.GetMaximum()
222
223 Target.SetMaximum(1.1*finalMax)
224 Target.SetMinimum(0.0001)
225
226 Canvas = TCanvas(histogram['name'])
227 Canvas.cd (1)
228 Target.Draw ()
229 func.Draw (plotting_options + "same")
230
231 outputFile.cd ("OSUAnalysis/" + histogram['channel'])
232 Canvas.Write ()
233 if arguments.plot_savePdf:
234 if histogram == input_histograms[0]:
235 Canvas.Print (pdfFileName + "(", "pdf")
236 else:
237 Canvas.Print (pdfFileName, "pdf")
238 Target.SetStats (0)
239
240 for i in range (0, 2):
241
242 if i == 1:
243 for j in range (0, len (HistogramsToFit)):
244 HistogramsToFit[j].Scale (func.GetParameter (j))
245
246 for bgMCHist in HistogramsToFit:
247 if not arguments.noStack:
248 Stack[i].Add(bgMCHist)
249
250 makeRatioPlots = arguments.makeRatioPlots
251 makeDiffPlots = arguments.makeDiffPlots
252 if i == 0:
253 Canvas = TCanvas(histogram['name'] + "_Before")
254 if i == 1:
255 Canvas = TCanvas(histogram['name'] + "_After")
256 if makeRatioPlots or makeDiffPlots:
257 Canvas.SetFillStyle(0)
258 Canvas.Divide(1,2)
259 Canvas.cd(1)
260 gPad.SetPad(0.01,0.25,0.99,0.99)
261 gPad.SetMargin(0.1,0.05,0.02,0.07)
262 gPad.SetFillStyle(0)
263 gPad.Update()
264 gPad.Draw()
265 Canvas.cd(2)
266 gPad.SetPad(0.01,0.01,0.99,0.25)
267 #format: gPad.SetMargin(l,r,b,t)
268 gPad.SetMargin(0.1,0.05,0.4,0.02)
269 gPad.SetFillStyle(0)
270 gPad.SetGridy(1)
271 gPad.Update()
272 gPad.Draw()
273
274 Canvas.cd(1)
275
276 if not arguments.noStack:
277 Stack[i].SetTitle(histoTitle)
278 Stack[i].Draw("HIST")
279 Stack[i].GetXaxis().SetTitle(xAxisLabel)
280 Stack[i].SetMaximum(1.1*finalMax)
281 Stack[i].SetMinimum(0.0001)
282 if makeRatioPlots or makeDiffPlots:
283 Stack[i].GetHistogram().GetXaxis().SetLabelSize(0)
284 else:
285 HistogramsToFit[0].SetTitle(histoTitle)
286 HistogramsToFit[0].Draw("HIST")
287 HistogramsToFit[0].GetXaxis().SetTitle(xAxisLabel)
288 HistogramsToFit[0].SetMaximum(1.1*finalMax)
289 HistogramsToFit[0].SetMinimum(0.0001)
290 for bgMCHist in HistogramsToFit:
291 bgMCHist.Draw("HIST SAME")
292
293 dataYield = Target.Integral (1, Target.GetNbinsX ())
294 mcYield = 0.0
295 for bgMCHist in HistogramsToFit:
296 mcYield += bgMCHist.Integral (1, bgMCHist.GetNbinsX ())
297 Label.Clear ()
298 if i == 0:
299 Label.AddText ("Before Fit to Data")
300 if i == 1:
301 Label.AddText ("After Fit to Data")
302 Label.AddText ("data yield: " + '%.1f' % dataYield)
303 Label.AddText ("MC yield: " + '%.1f' % mcYield)
304
305 Target.Draw("E SAME")
306 BgMCLegend.Draw()
307 LumiLabel.Draw()
308 Label.Draw()
309
310 if makeRatioPlots or makeDiffPlots:
311 Canvas.cd(2)
312 BgSum = Stack[i].GetStack().Last()
313 Comparison = Target.Clone()
314 Comparison.Add(BgSum,-1)
315 if not makeDiffPlots:
316 Comparison.Divide(BgSum)
317 Comparison.SetTitle("")
318 Comparison.GetXaxis().SetTitle(xAxisLabel)
319 if makeRatioPlots:
320 Comparison.GetYaxis().SetTitle("#frac{Data-MC}{MC}")
321 elif makeDiffPlots:
322 Comparison.GetYaxis().SetTitle("Data-MC")
323 Comparison.GetYaxis().CenterTitle()
324 Comparison.GetYaxis().SetTitleSize(0.1)
325 Comparison.GetYaxis().SetTitleOffset(0.35)
326 Comparison.GetXaxis().SetTitleSize(0.15)
327 Comparison.GetYaxis().SetLabelSize(0.1)
328 Comparison.GetXaxis().SetLabelSize(0.15)
329 if makeRatioPlots:
330 Comparison.GetYaxis().SetRangeUser(-1,1)
331 elif makeDiffPlots:
332 YMax = Comparison.GetMaximum()
333 YMin = Comparison.GetMinimum()
334 if YMax <= 0 and YMin <= 0:
335 Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
336 elif YMax >= 0 and YMin >= 0:
337 Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
338 else: #axis crosses y=0
339 if abs(YMax) > abs(YMin):
340 Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
341 else:
342 Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)
343
344 Comparison.GetYaxis().SetNdivisions(205)
345 Comparison.Draw()
346
347 outputFile.cd ("OSUAnalysis/" + histogram['channel'])
348 if i == 0:
349 Canvas.Write (histogram['name'] + "_Before")
350 if arguments.plot_savePdf:
351 Canvas.Print (pdfFileName, "pdf")
352 if i == 1:
353 Canvas.Write (histogram['name'] + "_After")
354 if arguments.plot_savePdf:
355 if histogram == input_histograms[-1]:
356 Canvas.Print (pdfFileName + ")", "pdf")
357 else:
358 Canvas.Print (pdfFileName, "pdf")
359
360 outputFile.Close ()
361
362 #for dataset in datasets_needed:
363 # dataset_file = "%s/%s.root_tmp" % (condor_dir,dataset)
364 # os.remove(dataset_file)