ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/myutils/StackMaker.py
Revision: 1.9
Committed: Wed Mar 6 16:22:27 2013 UTC (12 years, 2 months ago) by peller
Content type: text/x-python
Branch: MAIN
Changes since 1.8: +1 -1 lines
Log Message:
me again, about the blind opt...sorry

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