ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/myutils/StackMaker.py
Revision: 1.5
Committed: Thu Feb 7 15:50:12 2013 UTC (12 years, 3 months ago) by nmohr
Content type: text/x-python
Branch: MAIN
Changes since 1.4: +1 -3 lines
Log Message:
Bugfix binning

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    
81     def doPlot(self):
82     TdrStyles.tdrStyle()
83 peller 1.4 histo_dict = HistoMaker.orderandadd([{self.typs[i]:self.histos[i]} for i in range(len(self.histos))],self.setup)
84     #sort
85     self.histos=[histo_dict[key] for key in self.setup]
86     self.typs=self.setup
87 peller 1.1
88     c = ROOT.TCanvas(self.var,'', 600, 600)
89     c.SetFillStyle(4000)
90     c.SetFrameFillStyle(1000)
91     c.SetFrameFillColor(0)
92    
93     oben = ROOT.TPad('oben','oben',0,0.3 ,1.0,1.0)
94     oben.SetBottomMargin(0)
95     oben.SetFillStyle(4000)
96     oben.SetFrameFillStyle(1000)
97     oben.SetFrameFillColor(0)
98     unten = ROOT.TPad('unten','unten',0,0.0,1.0,0.3)
99     unten.SetTopMargin(0.)
100     unten.SetBottomMargin(0.35)
101     unten.SetFillStyle(4000)
102     unten.SetFrameFillStyle(1000)
103     unten.SetFrameFillColor(0)
104    
105     oben.Draw()
106     unten.Draw()
107    
108     oben.cd()
109     allStack = ROOT.THStack(self.var,'')
110     l = ROOT.TLegend(0.63, 0.55,0.92,0.92)
111     l.SetLineWidth(2)
112     l.SetBorderSize(0)
113     l.SetFillColor(0)
114     l.SetFillStyle(4000)
115     l.SetTextFont(62)
116     l.SetTextSize(0.035)
117     MC_integral=0
118     MC_entries=0
119    
120     for histo in self.histos:
121     MC_integral+=histo.Integral()
122     print "\033[1;32m\n\tMC integral = %s\033[1;m"%MC_integral
123    
124     #ORDER AND ADD TOGETHER
125     #print typs
126     #print setup
127    
128    
129     if not 'DYc' in self.typs: self.typLegendDict.update({'DYlight':self.typLegendDict['DYlc']})
130     print self.typLegendDict
131    
132     k=len(self.histos)
133    
134     for j in range(0,k):
135     #print histos[j].GetBinContent(1)
136     i=k-j-1
137     self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
138     self.histos[i].SetLineColor(1)
139     allStack.Add(self.histos[i])
140    
141     d1 = ROOT.TH1F('noData','noData',self.nBins,self.xMin,self.xMax)
142     datatitle='Data'
143     addFlag = ''
144     if 'Zee' in self.datanames and 'Zmm' in self.datanames:
145     addFlag = 'Z(l^{-}l^{+})H(b#bar{b})'
146     elif 'Zee' in self.datanames:
147     addFlag = 'Z(e^{-}e^{+})H(b#bar{b})'
148     elif 'Zmm' in self.datanames:
149     addFlag = 'Z(#mu^{-}#mu^{+})H(b#bar{b})'
150     elif 'Znn' in self.datanames:
151     addFlag = 'Z(#nu#nu)H(b#bar{b})'
152     elif 'Wmn' in self.datanames:
153     addFlag = 'W(#mu#nu)H(b#bar{b})'
154     elif 'Wen' in self.datanames:
155     addFlag = 'W(e#nu)H(b#bar{b})'
156     for i in range(0,len(self.datas)):
157     d1.Add(self.datas[i],1)
158     print "\033[1;32m\n\tDATA integral = %s\033[1;m"%d1.Integral()
159     flow = d1.GetEntries()-d1.Integral()
160     if flow > 0:
161     print "\033[1;31m\tU/O flow: %s\033[1;m"%flow
162    
163     if self.overlay:
164     self.overlay.SetLineColor(2)
165     self.overlay.SetLineWidth(2)
166     self.overlay.SetFillColor(0)
167     self.overlay.SetFillStyle(4000)
168     self.overlay.SetNameTitle('Overlay','Overlay')
169    
170     l.AddEntry(d1,datatitle,'P')
171     for j in range(0,k):
172     l.AddEntry(self.histos[j],self.typLegendDict[self.typs[j]],'F')
173     if self.overlay:
174     l.AddEntry(self.overlay,self.typLegendDict['Overlay'],'L')
175    
176     if self.normalize:
177     if MC_integral != 0: stackscale=d1.Integral()/MC_integral
178     if self.overlay:
179     self.overlay.Scale(stackscale)
180     stackhists=allStack.GetHists()
181     for blabla in stackhists:
182     if MC_integral != 0: blabla.Scale(stackscale)
183    
184     #if self.SignalRegion:
185     # allMC=allStack.GetStack().At(allStack.GetStack().GetLast()-1).Clone()
186     #else:
187     allMC=allStack.GetStack().Last().Clone()
188    
189     allStack.SetTitle()
190     allStack.Draw("hist")
191     allStack.GetXaxis().SetTitle('')
192     yTitle = 'Entries'
193     if not '/' in yTitle:
194     yAppend = '%.2f' %(allStack.GetXaxis().GetBinWidth(1))
195     yTitle = '%s / %s' %(yTitle, yAppend)
196     allStack.GetYaxis().SetTitle(yTitle)
197     allStack.GetXaxis().SetRangeUser(self.xMin,self.xMax)
198     allStack.GetYaxis().SetRangeUser(0,20000)
199     theErrorGraph = ROOT.TGraphErrors(allMC)
200     theErrorGraph.SetFillColor(ROOT.kGray+3)
201     theErrorGraph.SetFillStyle(3013)
202     theErrorGraph.Draw('SAME2')
203     l.AddEntry(theErrorGraph,"MC uncert. (stat.)","fl")
204     Ymax = max(allStack.GetMaximum(),d1.GetMaximum())*1.7
205     if self.log:
206     allStack.SetMinimum(0.1)
207     Ymax = Ymax*ROOT.TMath.Power(10,1.2*(ROOT.TMath.Log(1.2*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.2*0.1)
208     ROOT.gPad.SetLogy()
209     allStack.SetMaximum(Ymax)
210     c.Update()
211     ROOT.gPad.SetTicks(1,1)
212     #allStack.Draw("hist")
213     l.SetFillColor(0)
214     l.SetBorderSize(0)
215    
216     if self.overlay:
217     self.overlay.Draw('hist,same')
218     d1.Draw("E,same")
219     l.Draw()
220    
221     tPrel = self.myText("CMS Preliminary",0.17,0.88,1.04)
222     tLumi = self.myText("#sqrt{s} = %s, L = %s fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.83)
223     tAddFlag = self.myText(addFlag,0.17,0.78)
224    
225     unten.cd()
226     ROOT.gPad.SetTicks(1,1)
227    
228     l2 = ROOT.TLegend(0.5, 0.82,0.92,0.95)
229     l2.SetLineWidth(2)
230     l2.SetBorderSize(0)
231     l2.SetFillColor(0)
232     l2.SetFillStyle(4000)
233     l2.SetTextFont(62)
234     #l2.SetTextSize(0.035)
235     l2.SetNColumns(2)
236    
237    
238     ratio, error = getRatio(d1,allMC,self.xMin,self.xMax,"",self.maxRatioUncert)
239     ksScore = d1.KolmogorovTest( allMC )
240     chiScore = d1.Chi2Test( allMC , "UWCHI2/NDF")
241     print ksScore
242     print chiScore
243     ratio.SetStats(0)
244     ratio.GetXaxis().SetTitle(self.xAxis)
245     ratioError = ROOT.TGraphErrors(error)
246     ratioError.SetFillColor(ROOT.kGray+3)
247     ratioError.SetFillStyle(3013)
248     ratio.Draw("E1")
249    
250    
251    
252     if not self.AddErrors == None:
253     self.AddErrors.SetFillColor(5)
254     self.AddErrors.SetFillStyle(1001)
255     self.AddErrors.Draw('SAME2')
256    
257     l2.AddEntry(self.AddErrors,"MC uncert. (stat. + syst.)","f")
258    
259     #ksScore = d1.KolmogorovTest( self.AddErrors )
260     #chiScore = d1.Chi2Test( self.AddErrors , "UWCHI2/NDF")
261    
262    
263     l2.AddEntry(ratioError,"MC uncert. (stat.)","f")
264    
265     l2.Draw()
266    
267     ratioError.Draw('SAME2')
268     ratio.Draw("E1SAME")
269     ratio.SetTitle("")
270     m_one_line = ROOT.TLine(self.xMin,1,self.xMax,1)
271     m_one_line.SetLineStyle(ROOT.kDashed)
272     m_one_line.Draw("Same")
273    
274     if not self.blind:
275     tKsChi = self.myText("#chi_{#nu}^{2} = %.3f K_{s} = %.3f"%(chiScore,ksScore),0.17,0.9,1.5)
276     t0 = ROOT.TText()
277     t0.SetTextSize(ROOT.gStyle.GetLabelSize()*2.4)
278     t0.SetTextFont(ROOT.gStyle.GetLabelFont())
279     if not self.log:
280     t0.DrawTextNDC(0.1059,0.96, "0")
281     if not os.path.exists(self.plotDir):
282     os.makedirs(os.path.dirname(self.plotDir))
283 nmohr 1.2 name = '%s/%s' %(self.plotDir,self.options['pdfName'])
284 peller 1.1 c.Print(name)