ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/myutils/StackMaker.py
Revision: 1.6
Committed: Fri Feb 8 10:01:26 2013 UTC (12 years, 3 months ago) by nmohr
Content type: text/x-python
Branch: MAIN
Changes since 1.5: +32 -0 lines
Log Message:
Add comparison plot

File Contents

# User Rev Content
1 peller 1.1 import ROOT
2 nmohr 1.3 ROOT.gROOT.SetBatch(True)
3 peller 1.1 import sys,os
4     from BetterConfigParser import BetterConfigParser
5     import TdrStyles
6     from Ratio import getRatio
7 peller 1.4 from HistoMaker import HistoMaker
8 peller 1.1
9     class StackMaker:
10     def __init__(self, config, var,region,SignalRegion):
11     section='Plot:%s'%region
12     self.var = var
13     self.SignalRegion=SignalRegion
14     self.normalize = eval(config.get(section,'Normalize'))
15     self.log = eval(config.get(section,'log'))
16     if config.has_option('plotDef:%s'%var,'log') and not self.log:
17     self.log = eval(config.get('plotDef:%s'%var,'log'))
18     self.blind = eval(config.get(section,'blind'))
19     self.setup=config.get('Plot_general','setup')
20     if self.log:
21     self.setup=config.get('Plot_general','setupLog')
22     self.setup=self.setup.split(',')
23     if not SignalRegion: self.setup.remove('ZH')
24     self.rebin = 1
25     if config.has_option(section,'rebin'):
26     self.rebin = eval(config.get(section,'rebin'))
27     if config.has_option(section,'nBins'):
28     self.nBins = int(eval(config.get(section,'nBins'))/self.rebin)
29     else:
30     self.nBins = int(eval(config.get('plotDef:%s'%var,'nBins'))/self.rebin)
31     print self.nBins
32     if config.has_option(section,'min'):
33     self.xMin = eval(config.get(section,'min'))
34     else:
35     self.xMin = eval(config.get('plotDef:%s'%var,'min'))
36     if config.has_option(section,'max'):
37     self.xMax = eval(config.get(section,'max'))
38     else:
39     self.xMax = eval(config.get('plotDef:%s'%var,'max'))
40     self.name = config.get('plotDef:%s'%var,'relPath')
41     self.mass = config.get(section,'Signal')
42     data = config.get(section,'Datas')
43     if '<mass>' in self.name:
44     self.name = self.name.replace('<mass>',self.mass)
45     print self.name
46 nmohr 1.2 cut = config.get('Cuts',region)
47 peller 1.1 if config.has_option(section, 'Datacut'):
48 nmohr 1.2 cut=config.get(section, 'Datacut')
49    
50 peller 1.1 self.colorDict=eval(config.get('Plot_general','colorDict'))
51     self.typLegendDict=eval(config.get('Plot_general','typLegendDict'))
52     self.anaTag = config.get("Analysis","tag")
53     self.xAxis = config.get('plotDef:%s'%var,'xAxis')
54 nmohr 1.5 self.options = {'var': self.name,'name':'','xAxis': self.xAxis, 'nBins': self.nBins, 'xMin': self.xMin, 'xMax': self.xMax,'pdfName': '%s_%s_%s.pdf'%(region,var,self.mass),'cut':cut,'mass': self.mass, 'data': data, 'blind': self.blind}
55 nmohr 1.2 self.options['weight'] = config.get('Weights','weightF')
56 peller 1.1 self.plotDir = config.get('Directories','plotpath')
57     self.maxRatioUncert = 0.5
58     if self.SignalRegion:
59     self.maxRatioUncert = 1000.
60     self.config = config
61     self.datas = None
62     self.datatyps = None
63     self.overlay = None
64     self.lumi = None
65     self.histos = None
66     self.typs = None
67     self.AddErrors = None
68     print self.setup
69    
70 nmohr 1.2 @staticmethod
71     def myText(txt="CMS Preliminary",ndcX=0,ndcY=0,size=0.8):
72 peller 1.1 ROOT.gPad.Update()
73     text = ROOT.TLatex()
74     text.SetNDC()
75     text.SetTextColor(ROOT.kBlack)
76     text.SetTextSize(text.GetTextSize()*size)
77     text.DrawLatex(ndcX,ndcY,txt)
78     return text
79    
80 nmohr 1.6 def doCompPlot(self,aStack,l):
81     c = ROOT.TCanvas(self.var+'Comp','',600,600)
82     c.SetFillStyle(4000)
83     c.SetFrameFillStyle(1000)
84     c.SetFrameFillColor(0)
85     k=len(self.histos)
86     l.Clear()
87     maximum = 0.
88     for j in range(0,k):
89     #print histos[j].GetBinContent(1)
90     i=k-j-1
91     self.histos[i].SetLineColor(int(self.colorDict[self.typs[i]]))
92     self.histos[i].SetFillColor(0)
93     self.histos[i].SetLineWidth(3)
94     if self.histos[i].Integral() > 0.:
95     self.histos[i].Scale(1./self.histos[i].Integral())
96     if self.histos[i].GetMaximum() > maximum:
97     maximum = self.histos[i].GetMaximum()
98     l.AddEntry(self.histos[j],self.typLegendDict[self.typs[j]],'l')
99     aStack.SetMinimum(0.)
100     aStack.SetMaximum(maximum*1.5)
101     aStack.GetXaxis().SetTitle(self.xAxis)
102     aStack.Draw('HISTNOSTACK')
103     if self.overlay:
104     if self.overlay.Integral() > 0.:
105     self.overlay.Scale(1./self.overlay.Integral())
106     self.overlay.Draw('hist,same')
107     l.AddEntry(self.overlay,self.typLegendDict['Overlay'],'L')
108     l.Draw()
109     name = '%s/comp_%s' %(self.plotDir,self.options['pdfName'])
110     c.Print(name)
111 peller 1.1
112     def doPlot(self):
113     TdrStyles.tdrStyle()
114 peller 1.4 histo_dict = HistoMaker.orderandadd([{self.typs[i]:self.histos[i]} for i in range(len(self.histos))],self.setup)
115     #sort
116     self.histos=[histo_dict[key] for key in self.setup]
117     self.typs=self.setup
118 peller 1.1
119     c = ROOT.TCanvas(self.var,'', 600, 600)
120     c.SetFillStyle(4000)
121     c.SetFrameFillStyle(1000)
122     c.SetFrameFillColor(0)
123    
124     oben = ROOT.TPad('oben','oben',0,0.3 ,1.0,1.0)
125     oben.SetBottomMargin(0)
126     oben.SetFillStyle(4000)
127     oben.SetFrameFillStyle(1000)
128     oben.SetFrameFillColor(0)
129     unten = ROOT.TPad('unten','unten',0,0.0,1.0,0.3)
130     unten.SetTopMargin(0.)
131     unten.SetBottomMargin(0.35)
132     unten.SetFillStyle(4000)
133     unten.SetFrameFillStyle(1000)
134     unten.SetFrameFillColor(0)
135    
136     oben.Draw()
137     unten.Draw()
138    
139     oben.cd()
140     allStack = ROOT.THStack(self.var,'')
141     l = ROOT.TLegend(0.63, 0.55,0.92,0.92)
142     l.SetLineWidth(2)
143     l.SetBorderSize(0)
144     l.SetFillColor(0)
145     l.SetFillStyle(4000)
146     l.SetTextFont(62)
147     l.SetTextSize(0.035)
148     MC_integral=0
149     MC_entries=0
150    
151     for histo in self.histos:
152     MC_integral+=histo.Integral()
153     print "\033[1;32m\n\tMC integral = %s\033[1;m"%MC_integral
154    
155     #ORDER AND ADD TOGETHER
156     #print typs
157     #print setup
158    
159    
160     if not 'DYc' in self.typs: self.typLegendDict.update({'DYlight':self.typLegendDict['DYlc']})
161     print self.typLegendDict
162    
163     k=len(self.histos)
164    
165     for j in range(0,k):
166     #print histos[j].GetBinContent(1)
167     i=k-j-1
168     self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
169     self.histos[i].SetLineColor(1)
170     allStack.Add(self.histos[i])
171    
172     d1 = ROOT.TH1F('noData','noData',self.nBins,self.xMin,self.xMax)
173     datatitle='Data'
174     addFlag = ''
175     if 'Zee' in self.datanames and 'Zmm' in self.datanames:
176     addFlag = 'Z(l^{-}l^{+})H(b#bar{b})'
177     elif 'Zee' in self.datanames:
178     addFlag = 'Z(e^{-}e^{+})H(b#bar{b})'
179     elif 'Zmm' in self.datanames:
180     addFlag = 'Z(#mu^{-}#mu^{+})H(b#bar{b})'
181     elif 'Znn' in self.datanames:
182     addFlag = 'Z(#nu#nu)H(b#bar{b})'
183     elif 'Wmn' in self.datanames:
184     addFlag = 'W(#mu#nu)H(b#bar{b})'
185     elif 'Wen' in self.datanames:
186     addFlag = 'W(e#nu)H(b#bar{b})'
187     for i in range(0,len(self.datas)):
188     d1.Add(self.datas[i],1)
189     print "\033[1;32m\n\tDATA integral = %s\033[1;m"%d1.Integral()
190     flow = d1.GetEntries()-d1.Integral()
191     if flow > 0:
192     print "\033[1;31m\tU/O flow: %s\033[1;m"%flow
193    
194     if self.overlay:
195     self.overlay.SetLineColor(2)
196     self.overlay.SetLineWidth(2)
197     self.overlay.SetFillColor(0)
198     self.overlay.SetFillStyle(4000)
199     self.overlay.SetNameTitle('Overlay','Overlay')
200    
201     l.AddEntry(d1,datatitle,'P')
202     for j in range(0,k):
203     l.AddEntry(self.histos[j],self.typLegendDict[self.typs[j]],'F')
204     if self.overlay:
205     l.AddEntry(self.overlay,self.typLegendDict['Overlay'],'L')
206    
207     if self.normalize:
208     if MC_integral != 0: stackscale=d1.Integral()/MC_integral
209     if self.overlay:
210     self.overlay.Scale(stackscale)
211     stackhists=allStack.GetHists()
212     for blabla in stackhists:
213     if MC_integral != 0: blabla.Scale(stackscale)
214    
215     #if self.SignalRegion:
216     # allMC=allStack.GetStack().At(allStack.GetStack().GetLast()-1).Clone()
217     #else:
218     allMC=allStack.GetStack().Last().Clone()
219    
220     allStack.SetTitle()
221     allStack.Draw("hist")
222     allStack.GetXaxis().SetTitle('')
223     yTitle = 'Entries'
224     if not '/' in yTitle:
225     yAppend = '%.2f' %(allStack.GetXaxis().GetBinWidth(1))
226     yTitle = '%s / %s' %(yTitle, yAppend)
227     allStack.GetYaxis().SetTitle(yTitle)
228     allStack.GetXaxis().SetRangeUser(self.xMin,self.xMax)
229     allStack.GetYaxis().SetRangeUser(0,20000)
230     theErrorGraph = ROOT.TGraphErrors(allMC)
231     theErrorGraph.SetFillColor(ROOT.kGray+3)
232     theErrorGraph.SetFillStyle(3013)
233     theErrorGraph.Draw('SAME2')
234     l.AddEntry(theErrorGraph,"MC uncert. (stat.)","fl")
235     Ymax = max(allStack.GetMaximum(),d1.GetMaximum())*1.7
236     if self.log:
237     allStack.SetMinimum(0.1)
238     Ymax = Ymax*ROOT.TMath.Power(10,1.2*(ROOT.TMath.Log(1.2*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.2*0.1)
239     ROOT.gPad.SetLogy()
240     allStack.SetMaximum(Ymax)
241     c.Update()
242     ROOT.gPad.SetTicks(1,1)
243     #allStack.Draw("hist")
244     l.SetFillColor(0)
245     l.SetBorderSize(0)
246    
247     if self.overlay:
248     self.overlay.Draw('hist,same')
249     d1.Draw("E,same")
250     l.Draw()
251    
252     tPrel = self.myText("CMS Preliminary",0.17,0.88,1.04)
253     tLumi = self.myText("#sqrt{s} = %s, L = %s fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.83)
254     tAddFlag = self.myText(addFlag,0.17,0.78)
255    
256     unten.cd()
257     ROOT.gPad.SetTicks(1,1)
258    
259     l2 = ROOT.TLegend(0.5, 0.82,0.92,0.95)
260     l2.SetLineWidth(2)
261     l2.SetBorderSize(0)
262     l2.SetFillColor(0)
263     l2.SetFillStyle(4000)
264     l2.SetTextFont(62)
265     #l2.SetTextSize(0.035)
266     l2.SetNColumns(2)
267    
268    
269     ratio, error = getRatio(d1,allMC,self.xMin,self.xMax,"",self.maxRatioUncert)
270     ksScore = d1.KolmogorovTest( allMC )
271     chiScore = d1.Chi2Test( allMC , "UWCHI2/NDF")
272     print ksScore
273     print chiScore
274     ratio.SetStats(0)
275     ratio.GetXaxis().SetTitle(self.xAxis)
276     ratioError = ROOT.TGraphErrors(error)
277     ratioError.SetFillColor(ROOT.kGray+3)
278     ratioError.SetFillStyle(3013)
279     ratio.Draw("E1")
280    
281    
282    
283     if not self.AddErrors == None:
284     self.AddErrors.SetFillColor(5)
285     self.AddErrors.SetFillStyle(1001)
286     self.AddErrors.Draw('SAME2')
287    
288     l2.AddEntry(self.AddErrors,"MC uncert. (stat. + syst.)","f")
289    
290     #ksScore = d1.KolmogorovTest( self.AddErrors )
291     #chiScore = d1.Chi2Test( self.AddErrors , "UWCHI2/NDF")
292    
293    
294     l2.AddEntry(ratioError,"MC uncert. (stat.)","f")
295    
296     l2.Draw()
297    
298     ratioError.Draw('SAME2')
299     ratio.Draw("E1SAME")
300     ratio.SetTitle("")
301     m_one_line = ROOT.TLine(self.xMin,1,self.xMax,1)
302     m_one_line.SetLineStyle(ROOT.kDashed)
303     m_one_line.Draw("Same")
304    
305     if not self.blind:
306     tKsChi = self.myText("#chi_{#nu}^{2} = %.3f K_{s} = %.3f"%(chiScore,ksScore),0.17,0.9,1.5)
307     t0 = ROOT.TText()
308     t0.SetTextSize(ROOT.gStyle.GetLabelSize()*2.4)
309     t0.SetTextFont(ROOT.gStyle.GetLabelFont())
310     if not self.log:
311     t0.DrawTextNDC(0.1059,0.96, "0")
312     if not os.path.exists(self.plotDir):
313     os.makedirs(os.path.dirname(self.plotDir))
314 nmohr 1.2 name = '%s/%s' %(self.plotDir,self.options['pdfName'])
315 peller 1.1 c.Print(name)
316 nmohr 1.6 self.doCompPlot(allStack,l)