ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/myutils/StackMaker.py
Revision: 1.3
Committed: Mon Feb 4 14:22:21 2013 UTC (12 years, 3 months ago) by nmohr
Content type: text/x-python
Branch: MAIN
Changes since 1.2: +3 -2 lines
Log Message:
New version of workspace writer

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