ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/stack_from_dc.py
Revision: 1.16
Committed: Sun Mar 24 22:22:27 2013 UTC (12 years, 1 month ago) by bortigno
Content type: text/x-python
Branch: MAIN
CVS Tags: hcp_Unblind, lhcp_11April, LHCP_PreAppFixAfterFreeze, LHCP_PreAppFreeze
Changes since 1.15: +37 -14 lines
Log Message:
@ADD possibility to plot different varibales, mainly for control regions datacards

File Contents

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