ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/stack_from_dc.py
Revision: 1.9
Committed: Wed Nov 7 10:27:40 2012 UTC (12 years, 6 months ago) by nmohr
Content type: text/x-python
Branch: MAIN
Changes since 1.8: +2 -2 lines
Log Message:
Fix naming in Wln

File Contents

# User Rev Content
1 nmohr 1.1 #!/usr/bin/env python
2     import pickle
3     import ROOT
4     from BetterConfigParser import BetterConfigParser
5     import sys, os
6     from optparse import OptionParser
7     from copy import copy,deepcopy
8     from StackMaker import StackMaker
9     from math import sqrt
10     import math
11     from HiggsAnalysis.CombinedLimit.DatacardParser import *
12     from HiggsAnalysis.CombinedLimit.ShapeTools import *
13    
14     ROOT.gROOT.SetBatch(True)
15     ROOT.gSystem.Load("libHiggsAnalysisCombinedLimit.so")
16    
17     #CONFIGURE
18     argv = sys.argv
19     parser = OptionParser()
20     parser.add_option("-D", "--datacard", dest="dc", default="",
21     help="Datacard to be plotted")
22     parser.add_option("-B", "--bin", dest="bin", default="",
23     help="DC bin to plot")
24     parser.add_option("-M", "--mlfit", dest="mlfit", default="",
25     help="mlfit file for nuisances")
26     parser.add_option("-F", "--fitresult", dest="fit", default="s",
27     help="Fit result to be used, 's' (signal+background) or 'b' (background only), default is 's'")
28     parser.add_option("-C", "--config", dest="config", default=[], action="append",
29     help="configuration file")
30     (opts, args) = parser.parse_args(argv)
31    
32    
33     def readBestFit(theFile):
34     file = ROOT.TFile(theFile)
35 nmohr 1.4 if file == None: raise RuntimeError, "Cannot open file %s" % theFile
36 nmohr 1.1 fit_s = file.Get("fit_s")
37     fit_b = file.Get("fit_b")
38     prefit = file.Get("nuisances_prefit")
39     if fit_s == None or fit_s.ClassName() != "RooFitResult": raise RuntimeError, "File %s does not contain the output of the signal fit 'fit_s'" % args[0]
40     if fit_b == None or fit_b.ClassName() != "RooFitResult": raise RuntimeError, "File %s does not contain the output of the background fit 'fit_b'" % args[0]
41     if prefit == None or prefit.ClassName() != "RooArgSet": raise RuntimeError, "File %s does not contain the prefit nuisances 'nuisances_prefit'" % args[0]
42    
43     isFlagged = {}
44     table = {}
45     fpf_b = fit_b.floatParsFinal()
46     fpf_s = fit_s.floatParsFinal()
47     nuiVariation = {}
48     for i in range(fpf_s.getSize()):
49     nuis_s = fpf_s.at(i)
50     name = nuis_s.GetName();
51     nuis_b = fpf_b.find(name)
52     nuis_p = prefit.find(name)
53     if nuis_p != None:
54     mean_p, sigma_p = (nuis_p.getVal(), nuis_p.getError())
55     for fit_name, nuis_x in [('b', nuis_b), ('s',nuis_s)]:
56     if nuis_p != None:
57     valShift = (nuis_x.getVal() - mean_p)/sigma_p
58     #sigShift = nuis_x.getError()/sigma_p
59     print fit_name, name
60     print valShift
61     nuiVariation['%s_%s'%(fit_name,name)] = valShift
62     #print valShift
63     return nuiVariation
64    
65 nmohr 1.6 def getBestFitShapes(procs,theShapes,shapeNui,theBestFit,DC,setup,opts,Dict):
66 nmohr 1.4 b = opts.bin
67     for p in procs:
68     counter = 0
69     nom = theShapes[p].Clone()
70     for (lsyst,nofloat,pdf,pdfargs,errline) in DC.systs:
71     if errline[b][p] == 0: continue
72 nmohr 1.7 if ("shape" in pdf) and not 'CMS_vhbb_stat' in lsyst:
73 nmohr 1.4 if shapeNui > 0.:
74     theVari = 'Up'
75     else:
76     theVari = 'Down'
77     bestNuiVar = theShapes[p+lsyst+theVari].Clone()
78     bestNuiVar.Add(nom,-1.)
79     bestNuiVar.Scale(abs(shapeNui[p]))
80     if counter == 0:
81     bestNui = bestNuiVar.Clone()
82     else:
83     bestNui.Add(bestNuiVar)
84     counter +=1
85     nom.Add(bestNui)
86 nmohr 1.6 #nom.Scale(theBestFit[p])
87     nom.Scale(theShapes[p].Integral()/nom.Integral()*theBestFit[p])
88 nmohr 1.4 nBins = nom.GetNbinsX()
89     for bin in range(1,nBins+1):
90     nom.SetBinError(bin,theShapes[p].GetBinError(bin))
91     theShapes['%s_%s'%(opts.fit,p)] = nom.Clone()
92     histos = []
93     typs = []
94 nmohr 1.8 sigCount = 0
95 nmohr 1.4 for s in setup:
96 nmohr 1.8 if 'ZH' == s or 'WH' == s:
97     if sigCount ==0:
98     Overlay=copy(theShapes[Dict[s]])
99     else:
100     Overlay.Add(theShapes[Dict[s]])
101     sigCount += 1
102 nmohr 1.4 else:
103     histos.append(theShapes['%s_%s'%(opts.fit,Dict[s])])
104     typs.append(s)
105 nmohr 1.8 return histos,Overlay,typs
106 nmohr 1.4
107 nmohr 1.1
108     def drawFromDC():
109     config = BetterConfigParser()
110     config.read(opts.config)
111 nmohr 1.8 dataname = ''
112     if 'Zmm' in opts.bin: dataname = 'Zmm'
113     elif 'Zee' in opts.bin: dataname = 'Zee'
114 nmohr 1.9 elif 'Wmunu' in opts.bin: dataname = 'Wmn'
115     elif 'Wenu' in opts.bin: dataname = 'Wen'
116 nmohr 1.8 elif 'Znunu' in opts.bin: dataname = 'Znn'
117    
118     var = 'BDT'
119     if dataname == 'Zmm' or dataname == 'Zee': var = 'BDT_Zll'
120     elif dataname == 'Wmn' or dataname == 'Wen': var = 'BDT_Wln'
121     elif dataname == 'Znn':
122     if 'HighPt' in opts.bin: var = 'BDT_ZnnHighPt'
123     if 'LowPt' in opts.bin: var = 'BDT_ZnnLowPt'
124     if 'LowCSV' in opts.bin: var = 'BDT_ZnnLowCSV'
125     if dataname == '' or var == 'BDT': raise RuntimeError, "Did not recognise mode or var from %s" % opts.bin
126    
127 nmohr 1.1 region = 'BDT'
128     ws_var = config.get('plotDef:%s'%var,'relPath')
129     blind = eval(config.get('Plot:%s'%region,'blind'))
130     Stack=StackMaker(config,var,region,True)
131    
132 nmohr 1.4 preFit = False
133 nmohr 1.6 addName = 'PostFit_%s' %(opts.fit)
134 nmohr 1.4 if not opts.mlfit:
135 nmohr 1.6 addName = 'PreFit'
136 nmohr 1.4 preFit = True
137    
138 nmohr 1.6 Stack.options[6] = '%s_%s_%s.pdf' %(var,opts.bin,addName)
139    
140 nmohr 1.1 log = eval(config.get('Plot:%s'%region,'log'))
141    
142     setup = config.get('Plot_general','setup').split(',')
143 nmohr 1.8 if dataname == 'Zmm' or dataname == 'Zee':
144     setup.remove('Wb')
145     setup.remove('Wlight')
146     setup.remove('WH')
147 nmohr 1.1 Dict = eval(config.get('LimitGeneral','Dict'))
148     lumi = eval(config.get('Plot_general','lumi'))
149    
150     options = copy(opts)
151     options.dataname = "data_obs"
152     options.mass = 0
153     options.format = "%8.3f +/- %6.3f"
154 nmohr 1.2 options.channel = opts.bin
155 nmohr 1.1 options.excludeSyst = []
156     options.norm = False
157     options.stat = False
158     options.bin = True # fake that is a binary output, so that we parse shape lines
159     options.out = "tmp.root"
160     options.fileName = args[0]
161     options.cexpr = False
162     options.fixpars = False
163     options.libs = []
164     options.verbose = 0
165     options.poisson = 0
166     options.nuisancesToExclude = []
167     options.noJMax = None
168    
169     file = open(opts.dc, "r")
170     os.chdir(os.path.dirname(opts.dc))
171     DC = parseCard(file, options)
172     if not DC.hasShapes: DC.hasShapes = True
173     MB = ShapeBuilder(DC, options)
174     theShapes = {}
175     theSyst = {}
176 nmohr 1.4 nuiVar = {}
177 nmohr 1.1 if opts.mlfit:
178     nuiVar = readBestFit(opts.mlfit)
179 nmohr 1.8 if not opts.bin in DC.bins: raise RuntimeError, "Cannot open find %s in bins %s of %s" % (opts.bin,DC.bins,opts.dc)
180 nmohr 1.1 for b in DC.bins:
181     if options.channel != None and (options.channel != b): continue
182     exps = {}
183     expNui = {}
184     shapeNui = {}
185     for (p,e) in DC.exp[b].items(): # so that we get only self.DC.processes contributing to this bin
186     exps[p] = [ e, [] ]
187     expNui[p] = [ e, [] ]
188     for (lsyst,nofloat,pdf,pdfargs,errline) in DC.systs:
189     if pdf in ('param', 'flatParam'): continue
190     # begin skip systematics
191     skipme = False
192     for xs in options.excludeSyst:
193     if re.search(xs, lsyst):
194     skipme = True
195     if skipme: continue
196     # end skip systematics
197     counter = 0
198     for p in DC.exp[b].keys(): # so that we get only self.DC.processes contributing to this bin
199     if errline[b][p] == 0: continue
200 nmohr 1.7 if p == 'QCD': continue
201 nmohr 1.1 if pdf == 'gmN':
202     exps[p][1].append(1/sqrt(pdfargs[0]+1));
203     elif pdf == 'gmM':
204     exps[p][1].append(errline[b][p]);
205     elif type(errline[b][p]) == list:
206     kmax = max(errline[b][p][0], errline[b][p][1], 1.0/errline[b][p][0], 1.0/errline[b][p][1]);
207     exps[p][1].append(kmax-1.);
208     elif pdf == 'lnN':
209     exps[p][1].append(max(errline[b][p], 1.0/errline[b][p])-1.);
210     if not nuiVar.has_key('%s_%s'%(opts.fit,lsyst)):
211     nui = 0.
212     else:
213     nui= nuiVar['%s_%s'%(opts.fit,lsyst)]
214     expNui[p][1].append(abs(1-errline[b][p])*nui);
215 nmohr 1.7 elif ("shape" in pdf) and not 'CMS_vhbb_stat' in lsyst:
216     #print 'shape %s %s: %s'%(pdf,p,lsyst)
217 nmohr 1.1 s0 = MB.getShape(b,p)
218     sUp = MB.getShape(b,p,lsyst+"Up")
219     sDown = MB.getShape(b,p,lsyst+"Down")
220     if (s0.InheritsFrom("RooDataHist")):
221     s0 = ROOT.RooAbsData.createHistogram(s0,ws_var)
222     s0.SetName(p)
223     sUp = ROOT.RooAbsData.createHistogram(sUp,ws_var)
224     sUp.SetName(p+lsyst+'Up')
225     sDown = ROOT.RooAbsData.createHistogram(sDown,ws_var)
226     sDown.SetName(p+lsyst+'Down')
227     theShapes[p] = s0.Clone()
228     theShapes[p+lsyst+'Up'] = sUp.Clone()
229     theShapes[p+lsyst+'Down'] = sDown.Clone()
230     if not nuiVar.has_key('%s_%s'%(opts.fit,lsyst)):
231     nui = 0.
232     else:
233     nui= nuiVar['%s_%s'%(opts.fit,lsyst)]
234     shapeNui[p] = nui
235     if counter == 0:
236     theSyst[lsyst] = s0.Clone()
237     theSyst[lsyst+'Up'] = sUp.Clone()
238     theSyst[lsyst+'Down'] = sDown.Clone()
239     else:
240     theSyst[lsyst].Add(s0)
241     theSyst[lsyst+'Up'].Add(sUp.Clone())
242     theSyst[lsyst+'Down'].Add(sDown.Clone())
243     counter += 1
244     procs = DC.exp[b].keys(); procs.sort()
245 nmohr 1.7 if 'QCD' in procs:
246     procs.remove('QCD')
247 nmohr 1.1 fmt = ("%%-%ds " % max([len(p) for p in procs]))+" "+options.format;
248     #Compute norm uncertainty and best fit
249     theNormUncert = {}
250     theBestFit = {}
251     for p in procs:
252     relunc = sqrt(sum([x*x for x in exps[p][1]]))
253     print fmt % (p, exps[p][0], exps[p][0]*relunc)
254     theNormUncert[p] = relunc
255     absBestFit = sum([x for x in expNui[p][1]])
256     theBestFit[p] = 1.+absBestFit
257    
258     histos = []
259     typs = []
260    
261     setup2=copy(setup)
262    
263     shapesUp = [[] for _ in range(0,len(setup2))]
264     shapesDown = [[] for _ in range(0,len(setup2))]
265    
266 nmohr 1.8 sigCount = 0
267 nmohr 1.1 for p in procs:
268 nmohr 1.2 b = opts.bin
269 nmohr 1.1 for s in setup:
270     if not Dict[s] == p: continue
271 nmohr 1.8 if 'ZH' == s or 'WH' == s:
272     if sigCount ==0:
273     Overlay=copy(theShapes[Dict[s]])
274     else:
275     Overlay.Add(theShapes[Dict[s]])
276     sigCount += 1
277 nmohr 1.1 else:
278     histos.append(theShapes[Dict[s]])
279     typs.append(s)
280     for (lsyst,nofloat,pdf,pdfargs,errline) in DC.systs:
281     if errline[b][p] == 0: continue
282 nmohr 1.7 if ("shape" in pdf) and not 'CMS_vhbb_stat' in lsyst:
283 nmohr 1.1 print 'syst %s'%lsyst
284     shapesUp[setup2.index(s)].append(theShapes[Dict[s]+lsyst+'Up'])
285     shapesDown[setup2.index(s)].append(theShapes[Dict[s]+lsyst+'Down'])
286    
287     #-------------
288     #Compute absolute uncertainty from shapes
289     counter = 0
290     for (lsyst,nofloat,pdf,pdfargs,errline) in DC.systs:
291 nmohr 1.7 if ("shape" in pdf) and not 'CMS_vhbb_stat' in lsyst:
292 nmohr 1.1 theSystUp = theSyst[lsyst+'Up'].Clone()
293     theSystUp.Add(theSyst[lsyst].Clone(),-1.)
294     theSystUp.Multiply(theSystUp)
295     theSystDown = theSyst[lsyst+'Down'].Clone()
296     theSystDown.Add(theSyst[lsyst].Clone(),-1.)
297     theSystDown.Multiply(theSystDown)
298     if counter == 0:
299     theAbsSystUp = theSystUp.Clone()
300     theAbsSystDown = theSystDown.Clone()
301     else:
302     theAbsSystUp.Add(theSystUp.Clone())
303     theAbsSystDown.Add(theSystDown.Clone())
304     counter +=1
305    
306     #-------------
307     #Best fit for shapes
308 nmohr 1.4 if not preFit:
309 nmohr 1.8 histos, Overlay, typs = getBestFitShapes(procs,theShapes,shapeNui,theBestFit,DC,setup,opts,Dict)
310 nmohr 1.1
311     counter = 0
312     errUp=[]
313     total=[]
314     errDown=[]
315     nBins = histos[0].GetNbinsX()
316     print 'total bins %s'%nBins
317     Error = ROOT.TGraphAsymmErrors(histos[0])
318     theTotalMC = histos[0].Clone()
319     for h in range(1,len(histos)):
320     theTotalMC.Add(histos[h])
321    
322     total = [[]]*nBins
323     errUp = [[]]*nBins
324     errDown = [[]]*nBins
325     for bin in range(1,nBins+1):
326     binError = theTotalMC.GetBinError(bin)
327     if math.isnan(binError):
328     binError = 0.
329     total[bin-1]=theTotalMC.GetBinContent(bin)
330     #Stat uncertainty of the MC outline
331     errUp[bin-1] = [binError]
332     errDown[bin-1] = [binError]
333     #Relative norm uncertainty of the individual MC
334     for h in range(0,len(histos)):
335     errUp[bin-1].append(histos[h].GetBinContent(bin)*theNormUncert[histos[h].GetName()])
336     errDown[bin-1].append(histos[h].GetBinContent(bin)*theNormUncert[histos[h].GetName()])
337     #Shape uncertainty of the MC
338     for bin in range(1,nBins+1):
339     #print sqrt(theSystUp.GetBinContent(bin))
340     errUp[bin-1].append(sqrt(theAbsSystUp.GetBinContent(bin)))
341     errDown[bin-1].append(sqrt(theAbsSystDown.GetBinContent(bin)))
342    
343    
344     #Add all in quadrature
345     totErrUp=[sqrt(sum([x**2 for x in bin])) for bin in errUp]
346     totErrDown=[sqrt(sum([x**2 for x in bin])) for bin in errDown]
347    
348     #Make TGraph with errors
349     for bin in range(1,nBins+1):
350     if not total[bin-1] == 0:
351     point=histos[0].GetXaxis().GetBinCenter(bin)
352     Error.SetPoint(bin-1,point,1)
353     Error.SetPointEYlow(bin-1,totErrDown[bin-1]/total[bin-1])
354     print 'down %s'%(totErrDown[bin-1]/total[bin-1])
355     Error.SetPointEYhigh(bin-1,totErrUp[bin-1]/total[bin-1])
356     print 'up %s'%(totErrUp[bin-1]/total[bin-1])
357    
358     #-----------------------
359     #Read data
360 nmohr 1.2 data0 = MB.getShape(opts.bin,'data_obs')
361 nmohr 1.1 if (data0.InheritsFrom("RooDataHist")):
362     data0 = ROOT.RooAbsData.createHistogram(data0,ws_var)
363     data0.SetName('data_obs')
364     datas=[data0]
365     datatyps = [None]
366     datanames=[dataname]
367    
368    
369     if blind:
370     for bin in range(10,datas[0].GetNbinsX()+1):
371     datas[0].SetBinContent(bin,0)
372    
373     histos.append(copy(Overlay))
374 nmohr 1.8 if 'ZH' in setup and 'WH' in setup:
375     typs.append('VH')
376     Stack.setup.remove('ZH')
377     Stack.setup.remove('WH')
378     Stack.setup.insert(0,'VH')
379     elif 'ZH' in setup:
380     typs.append('ZH')
381     elif 'WH' in setup:
382     typs.append('WH')
383 nmohr 1.1
384     Stack.histos = histos
385     Stack.typs = typs
386     Stack.datas = datas
387     Stack.datatyps = datatyps
388     Stack.datanames= datanames
389     Stack.overlay = Overlay
390     Stack.AddErrors=Error
391     Stack.lumi = lumi
392     Stack.doPlot()
393    
394     print 'i am done!\n'
395     #-------------------------------------------------
396    
397    
398     if __name__ == "__main__":
399     drawFromDC()
400     sys.exit(0)