ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/stack_from_dc.py
Revision: 1.12
Committed: Fri Nov 9 09:08:00 2012 UTC (12 years, 6 months ago) by nmohr
Content type: text/x-python
Branch: MAIN
Changes since 1.11: +6 -4 lines
Log Message:
Possibility to trim binning

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.11 if ("shape" in pdf):
73     if shapeNui[p+lsyst] > 0.:
74 nmohr 1.4 theVari = 'Up'
75     else:
76     theVari = 'Down'
77     bestNuiVar = theShapes[p+lsyst+theVari].Clone()
78     bestNuiVar.Add(nom,-1.)
79 nmohr 1.11 #print p,lsyst,abs(shapeNui[p+lsyst]),bestNuiVar.Integral()
80     bestNuiVar.Scale(abs(shapeNui[p+lsyst]))
81 nmohr 1.4 if counter == 0:
82     bestNui = bestNuiVar.Clone()
83     else:
84     bestNui.Add(bestNuiVar)
85     counter +=1
86 nmohr 1.10 nom.Add(bestNui)
87 nmohr 1.6 #nom.Scale(theBestFit[p])
88     nom.Scale(theShapes[p].Integral()/nom.Integral()*theBestFit[p])
89 nmohr 1.4 nBins = nom.GetNbinsX()
90     for bin in range(1,nBins+1):
91     nom.SetBinError(bin,theShapes[p].GetBinError(bin))
92     theShapes['%s_%s'%(opts.fit,p)] = nom.Clone()
93     histos = []
94     typs = []
95 nmohr 1.8 sigCount = 0
96 nmohr 1.4 for s in setup:
97 nmohr 1.8 if 'ZH' == s or 'WH' == s:
98     if sigCount ==0:
99     Overlay=copy(theShapes[Dict[s]])
100     else:
101     Overlay.Add(theShapes[Dict[s]])
102     sigCount += 1
103 nmohr 1.4 else:
104     histos.append(theShapes['%s_%s'%(opts.fit,Dict[s])])
105     typs.append(s)
106 nmohr 1.8 return histos,Overlay,typs
107 nmohr 1.4
108 nmohr 1.1
109     def drawFromDC():
110     config = BetterConfigParser()
111     config.read(opts.config)
112 nmohr 1.8 dataname = ''
113     if 'Zmm' in opts.bin: dataname = 'Zmm'
114     elif 'Zee' in opts.bin: dataname = 'Zee'
115 nmohr 1.9 elif 'Wmunu' in opts.bin: dataname = 'Wmn'
116     elif 'Wenu' in opts.bin: dataname = 'Wen'
117 nmohr 1.8 elif 'Znunu' in opts.bin: dataname = 'Znn'
118    
119     var = 'BDT'
120     if dataname == 'Zmm' or dataname == 'Zee': var = 'BDT_Zll'
121     elif dataname == 'Wmn' or dataname == 'Wen': var = 'BDT_Wln'
122     elif dataname == 'Znn':
123     if 'HighPt' in opts.bin: var = 'BDT_ZnnHighPt'
124     if 'LowPt' in opts.bin: var = 'BDT_ZnnLowPt'
125     if 'LowCSV' in opts.bin: var = 'BDT_ZnnLowCSV'
126     if dataname == '' or var == 'BDT': raise RuntimeError, "Did not recognise mode or var from %s" % opts.bin
127    
128 nmohr 1.1 region = 'BDT'
129     ws_var = config.get('plotDef:%s'%var,'relPath')
130 nmohr 1.12 ws_var = ROOT.RooRealVar(ws_var,ws_var,-1.,1.)
131 nmohr 1.1 blind = eval(config.get('Plot:%s'%region,'blind'))
132     Stack=StackMaker(config,var,region,True)
133    
134 nmohr 1.4 preFit = False
135 nmohr 1.6 addName = 'PostFit_%s' %(opts.fit)
136 nmohr 1.4 if not opts.mlfit:
137 nmohr 1.6 addName = 'PreFit'
138 nmohr 1.4 preFit = True
139    
140 nmohr 1.6 Stack.options[6] = '%s_%s_%s.pdf' %(var,opts.bin,addName)
141    
142 nmohr 1.1 log = eval(config.get('Plot:%s'%region,'log'))
143    
144     setup = config.get('Plot_general','setup').split(',')
145 nmohr 1.8 if dataname == 'Zmm' or dataname == 'Zee':
146     setup.remove('Wb')
147     setup.remove('Wlight')
148     setup.remove('WH')
149 nmohr 1.1 Dict = eval(config.get('LimitGeneral','Dict'))
150     lumi = eval(config.get('Plot_general','lumi'))
151    
152     options = copy(opts)
153     options.dataname = "data_obs"
154     options.mass = 0
155     options.format = "%8.3f +/- %6.3f"
156 nmohr 1.2 options.channel = opts.bin
157 nmohr 1.1 options.excludeSyst = []
158     options.norm = False
159     options.stat = False
160     options.bin = True # fake that is a binary output, so that we parse shape lines
161     options.out = "tmp.root"
162     options.fileName = args[0]
163     options.cexpr = False
164     options.fixpars = False
165     options.libs = []
166     options.verbose = 0
167     options.poisson = 0
168     options.nuisancesToExclude = []
169     options.noJMax = None
170 nmohr 1.12 theBinning = ROOT.RooFit.Binning(Stack.nBins,Stack.xMin,Stack.xMax)
171 nmohr 1.1
172     file = open(opts.dc, "r")
173     os.chdir(os.path.dirname(opts.dc))
174     DC = parseCard(file, options)
175     if not DC.hasShapes: DC.hasShapes = True
176     MB = ShapeBuilder(DC, options)
177     theShapes = {}
178     theSyst = {}
179 nmohr 1.4 nuiVar = {}
180 nmohr 1.1 if opts.mlfit:
181     nuiVar = readBestFit(opts.mlfit)
182 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)
183 nmohr 1.1 for b in DC.bins:
184     if options.channel != None and (options.channel != b): continue
185     exps = {}
186     expNui = {}
187     shapeNui = {}
188     for (p,e) in DC.exp[b].items(): # so that we get only self.DC.processes contributing to this bin
189     exps[p] = [ e, [] ]
190     expNui[p] = [ e, [] ]
191     for (lsyst,nofloat,pdf,pdfargs,errline) in DC.systs:
192     if pdf in ('param', 'flatParam'): continue
193     # begin skip systematics
194     skipme = False
195     for xs in options.excludeSyst:
196     if re.search(xs, lsyst):
197     skipme = True
198     if skipme: continue
199     # end skip systematics
200     counter = 0
201     for p in DC.exp[b].keys(): # so that we get only self.DC.processes contributing to this bin
202     if errline[b][p] == 0: continue
203 nmohr 1.7 if p == 'QCD': continue
204 nmohr 1.1 if pdf == 'gmN':
205     exps[p][1].append(1/sqrt(pdfargs[0]+1));
206     elif pdf == 'gmM':
207     exps[p][1].append(errline[b][p]);
208     elif type(errline[b][p]) == list:
209     kmax = max(errline[b][p][0], errline[b][p][1], 1.0/errline[b][p][0], 1.0/errline[b][p][1]);
210     exps[p][1].append(kmax-1.);
211     elif pdf == 'lnN':
212     exps[p][1].append(max(errline[b][p], 1.0/errline[b][p])-1.);
213     if not nuiVar.has_key('%s_%s'%(opts.fit,lsyst)):
214     nui = 0.
215     else:
216     nui= nuiVar['%s_%s'%(opts.fit,lsyst)]
217     expNui[p][1].append(abs(1-errline[b][p])*nui);
218 nmohr 1.11 elif ("shape" in pdf):
219 nmohr 1.7 #print 'shape %s %s: %s'%(pdf,p,lsyst)
220 nmohr 1.1 s0 = MB.getShape(b,p)
221     sUp = MB.getShape(b,p,lsyst+"Up")
222     sDown = MB.getShape(b,p,lsyst+"Down")
223     if (s0.InheritsFrom("RooDataHist")):
224 nmohr 1.12 s0 = ROOT.RooAbsData.createHistogram(s0,p,ws_var,theBinning)
225 nmohr 1.1 s0.SetName(p)
226 nmohr 1.12 sUp = ROOT.RooAbsData.createHistogram(sUp,p+lsyst+'Up',ws_var,theBinning)
227 nmohr 1.1 sUp.SetName(p+lsyst+'Up')
228 nmohr 1.12 sDown = ROOT.RooAbsData.createHistogram(sDown,p+lsyst+'Down',ws_var,theBinning)
229 nmohr 1.1 sDown.SetName(p+lsyst+'Down')
230     theShapes[p] = s0.Clone()
231     theShapes[p+lsyst+'Up'] = sUp.Clone()
232     theShapes[p+lsyst+'Down'] = sDown.Clone()
233     if not nuiVar.has_key('%s_%s'%(opts.fit,lsyst)):
234     nui = 0.
235     else:
236     nui= nuiVar['%s_%s'%(opts.fit,lsyst)]
237 nmohr 1.11 shapeNui[p+lsyst] = nui
238     if not 'CMS_vhbb_stat' in lsyst:
239     if counter == 0:
240     theSyst[lsyst] = s0.Clone()
241     theSyst[lsyst+'Up'] = sUp.Clone()
242     theSyst[lsyst+'Down'] = sDown.Clone()
243     else:
244     theSyst[lsyst].Add(s0)
245     theSyst[lsyst+'Up'].Add(sUp.Clone())
246     theSyst[lsyst+'Down'].Add(sDown.Clone())
247     counter += 1
248    
249 nmohr 1.1 procs = DC.exp[b].keys(); procs.sort()
250 nmohr 1.7 if 'QCD' in procs:
251     procs.remove('QCD')
252 nmohr 1.1 fmt = ("%%-%ds " % max([len(p) for p in procs]))+" "+options.format;
253     #Compute norm uncertainty and best fit
254     theNormUncert = {}
255     theBestFit = {}
256     for p in procs:
257     relunc = sqrt(sum([x*x for x in exps[p][1]]))
258     print fmt % (p, exps[p][0], exps[p][0]*relunc)
259     theNormUncert[p] = relunc
260     absBestFit = sum([x for x in expNui[p][1]])
261     theBestFit[p] = 1.+absBestFit
262    
263     histos = []
264     typs = []
265    
266     setup2=copy(setup)
267    
268     shapesUp = [[] for _ in range(0,len(setup2))]
269     shapesDown = [[] for _ in range(0,len(setup2))]
270    
271 nmohr 1.8 sigCount = 0
272 nmohr 1.1 for p in procs:
273 nmohr 1.2 b = opts.bin
274 nmohr 1.1 for s in setup:
275     if not Dict[s] == p: continue
276 nmohr 1.8 if 'ZH' == s or 'WH' == s:
277     if sigCount ==0:
278     Overlay=copy(theShapes[Dict[s]])
279     else:
280     Overlay.Add(theShapes[Dict[s]])
281     sigCount += 1
282 nmohr 1.1 else:
283     histos.append(theShapes[Dict[s]])
284     typs.append(s)
285     for (lsyst,nofloat,pdf,pdfargs,errline) in DC.systs:
286     if errline[b][p] == 0: continue
287 nmohr 1.7 if ("shape" in pdf) and not 'CMS_vhbb_stat' in lsyst:
288 nmohr 1.1 print 'syst %s'%lsyst
289     shapesUp[setup2.index(s)].append(theShapes[Dict[s]+lsyst+'Up'])
290     shapesDown[setup2.index(s)].append(theShapes[Dict[s]+lsyst+'Down'])
291    
292     #-------------
293     #Compute absolute uncertainty from shapes
294     counter = 0
295     for (lsyst,nofloat,pdf,pdfargs,errline) in DC.systs:
296 nmohr 1.11 sumErr = 0
297     for p in procs:
298     sumErr += errline[b][p]
299     if ("shape" in pdf) and not 'CMS_vhbb_stat' in lsyst and not sumErr == 0:
300 nmohr 1.1 theSystUp = theSyst[lsyst+'Up'].Clone()
301     theSystUp.Add(theSyst[lsyst].Clone(),-1.)
302     theSystUp.Multiply(theSystUp)
303     theSystDown = theSyst[lsyst+'Down'].Clone()
304     theSystDown.Add(theSyst[lsyst].Clone(),-1.)
305     theSystDown.Multiply(theSystDown)
306     if counter == 0:
307     theAbsSystUp = theSystUp.Clone()
308     theAbsSystDown = theSystDown.Clone()
309     else:
310     theAbsSystUp.Add(theSystUp.Clone())
311     theAbsSystDown.Add(theSystDown.Clone())
312     counter +=1
313    
314     #-------------
315     #Best fit for shapes
316 nmohr 1.4 if not preFit:
317 nmohr 1.8 histos, Overlay, typs = getBestFitShapes(procs,theShapes,shapeNui,theBestFit,DC,setup,opts,Dict)
318 nmohr 1.1
319     counter = 0
320     errUp=[]
321     total=[]
322     errDown=[]
323     nBins = histos[0].GetNbinsX()
324     print 'total bins %s'%nBins
325     Error = ROOT.TGraphAsymmErrors(histos[0])
326     theTotalMC = histos[0].Clone()
327     for h in range(1,len(histos)):
328     theTotalMC.Add(histos[h])
329    
330     total = [[]]*nBins
331     errUp = [[]]*nBins
332     errDown = [[]]*nBins
333     for bin in range(1,nBins+1):
334     binError = theTotalMC.GetBinError(bin)
335     if math.isnan(binError):
336     binError = 0.
337     total[bin-1]=theTotalMC.GetBinContent(bin)
338     #Stat uncertainty of the MC outline
339     errUp[bin-1] = [binError]
340     errDown[bin-1] = [binError]
341     #Relative norm uncertainty of the individual MC
342     for h in range(0,len(histos)):
343     errUp[bin-1].append(histos[h].GetBinContent(bin)*theNormUncert[histos[h].GetName()])
344     errDown[bin-1].append(histos[h].GetBinContent(bin)*theNormUncert[histos[h].GetName()])
345     #Shape uncertainty of the MC
346     for bin in range(1,nBins+1):
347     #print sqrt(theSystUp.GetBinContent(bin))
348     errUp[bin-1].append(sqrt(theAbsSystUp.GetBinContent(bin)))
349     errDown[bin-1].append(sqrt(theAbsSystDown.GetBinContent(bin)))
350    
351    
352     #Add all in quadrature
353     totErrUp=[sqrt(sum([x**2 for x in bin])) for bin in errUp]
354     totErrDown=[sqrt(sum([x**2 for x in bin])) for bin in errDown]
355    
356     #Make TGraph with errors
357     for bin in range(1,nBins+1):
358     if not total[bin-1] == 0:
359     point=histos[0].GetXaxis().GetBinCenter(bin)
360     Error.SetPoint(bin-1,point,1)
361     Error.SetPointEYlow(bin-1,totErrDown[bin-1]/total[bin-1])
362     print 'down %s'%(totErrDown[bin-1]/total[bin-1])
363     Error.SetPointEYhigh(bin-1,totErrUp[bin-1]/total[bin-1])
364     print 'up %s'%(totErrUp[bin-1]/total[bin-1])
365    
366     #-----------------------
367     #Read data
368 nmohr 1.2 data0 = MB.getShape(opts.bin,'data_obs')
369 nmohr 1.1 if (data0.InheritsFrom("RooDataHist")):
370 nmohr 1.12 data0 = ROOT.RooAbsData.createHistogram(data0,'data_obs',ws_var,theBinning)
371 nmohr 1.1 data0.SetName('data_obs')
372     datas=[data0]
373     datatyps = [None]
374     datanames=[dataname]
375    
376    
377     if blind:
378     for bin in range(10,datas[0].GetNbinsX()+1):
379     datas[0].SetBinContent(bin,0)
380    
381     histos.append(copy(Overlay))
382 nmohr 1.8 if 'ZH' in setup and 'WH' in setup:
383     typs.append('VH')
384     Stack.setup.remove('ZH')
385     Stack.setup.remove('WH')
386     Stack.setup.insert(0,'VH')
387     elif 'ZH' in setup:
388     typs.append('ZH')
389     elif 'WH' in setup:
390     typs.append('WH')
391 nmohr 1.1
392     Stack.histos = histos
393     Stack.typs = typs
394     Stack.datas = datas
395     Stack.datatyps = datatyps
396     Stack.datanames= datanames
397     Stack.overlay = Overlay
398     Stack.AddErrors=Error
399     Stack.lumi = lumi
400     Stack.doPlot()
401    
402     print 'i am done!\n'
403     #-------------------------------------------------
404    
405    
406     if __name__ == "__main__":
407     drawFromDC()
408     sys.exit(0)