ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/workspace_datacard.py
Revision: 1.58
Committed: Fri Oct 26 08:43:27 2012 UTC (12 years, 6 months ago) by peller
Content type: text/x-python
Branch: MAIN
Changes since 1.57: +12 -1 lines
Log Message:
different extrapolation uncert. for pt_regions

File Contents

# User Rev Content
1 peller 1.8 #!/usr/bin/env python
2 peller 1.53 import os, sys, ROOT, warnings, pickle
3 peller 1.1 from ROOT import TFile
4     from array import array
5     from math import sqrt
6     from copy import copy
7     #suppres the EvalInstace conversion warning bug
8     warnings.filterwarnings( action='ignore', category=RuntimeWarning, message='creating converter.*' )
9 nmohr 1.31 from optparse import OptionParser
10 nmohr 1.20 from BetterConfigParser import BetterConfigParser
11 peller 1.1 from samplesclass import sample
12     from mvainfos import mvainfo
13     from progbar import progbar
14     from printcolor import printc
15 peller 1.13 from gethistofromtree import getHistoFromTree, orderandadd
16 peller 1.1
17     #CONFIGURE
18 nmohr 1.31 argv = sys.argv
19     parser = OptionParser()
20     parser.add_option("-P", "--path", dest="path", default="",
21     help="path to samples")
22     parser.add_option("-V", "--var", dest="variable", default="",
23     help="variable for shape analysis")
24     parser.add_option("-C", "--config", dest="config", default=[], action="append",
25     help="configuration file")
26     (opts, args) = parser.parse_args(argv)
27     if opts.config =="":
28     opts.config = "config"
29     print opts.config
30 nmohr 1.20 config = BetterConfigParser()
31 nmohr 1.31 config.read(opts.config)
32     anaTag = config.get("Analysis","tag")
33 peller 1.30
34 peller 1.36
35     # -------------------- parsing configuration and options: (an ugly spaghetti code section) ----------------------------------------------------------------------
36 peller 1.1 #get locations:
37     Wdir=config.get('Directories','Wdir')
38 peller 1.42 vhbbpath=config.get('Directories','vhbbpath')
39 nmohr 1.46 samplesinfo=config.get('Directories','samplesinfo')
40 peller 1.1 #systematics
41     systematics=config.get('systematics','systematics')
42     systematics=systematics.split(' ')
43     weightF=config.get('Weights','weightF')
44 nmohr 1.31 path=opts.path
45     var=opts.variable
46 peller 1.1 plot=config.get('Limit',var)
47 nmohr 1.46 infofile = open(samplesinfo,'r')
48 peller 1.1 info = pickle.load(infofile)
49     infofile.close()
50     options = plot.split(',')
51 bortigno 1.7 if len(options) < 12:
52     print "You have to choose option[11]: either Mjj or BDT"
53     sys.exit("You have to choose option[11]: either Mjj or BDT")
54 peller 1.1 name=options[1]
55     title = options[2]
56 peller 1.54 nBinsRB=int(options[3])
57     nBins= int(config.get('LimitGeneral','BDTbinning'))
58 peller 1.1 xMin=float(options[4])
59     xMax=float(options[5])
60 peller 1.29 SIG=options[9]
61 peller 1.1 data=options[10]
62 bortigno 1.7 anType=options[11]
63 peller 1.13 RCut=options[7]
64 peller 1.29 setup=eval(config.get('LimitGeneral','setup'))
65 peller 1.13 ROOToutname = options[6]
66 peller 1.58
67     if 'HighPtLooseBTag' in ROOToutname:
68     pt_region = 'HighPtLooseBTag'
69     elif 'HighPt' in ROOToutname:
70     pt_region = 'HighPt'
71     elif 'LowPt' in ROOToutname:
72     pt_region = 'LowPt'
73     else:
74     print "Unknown Pt region"
75     sys.exit("Unknown Pt region")
76    
77 peller 1.13 outpath=config.get('Directories','limits')
78     outfile = ROOT.TFile(outpath+'vhbb_TH_'+ROOToutname+'.root', 'RECREATE')
79 peller 1.29 systematicsnaming=eval(config.get('LimitGeneral','systematicsnaming7TeV'))
80 peller 1.44
81     TrainFlag = eval(config.get('Analysis','TrainFlag'))
82    
83    
84 peller 1.54
85 peller 1.30 if anaTag =='8TeV':
86 peller 1.29 systematicsnaming=eval(config.get('LimitGeneral','systematicsnaming8TeV'))
87 peller 1.44 elif not anaTag =='7TeV':
88 peller 1.30 print "What is your Analysis Tag in config? (anaTag)"
89     sys.exit("What is your Analysis Tag in config? (anaTag)")
90 peller 1.29 scaling=eval(config.get('LimitGeneral','scaling'))
91 peller 1.44
92     if TrainFlag:
93     MC_rescale_factor=2.
94     print 'I RESCALE BY 2.0'
95     else: MC_rescale_factor = 1.
96    
97 peller 1.29 rescaleSqrtN=eval(config.get('LimitGeneral','rescaleSqrtN'))
98 peller 1.11 if 'RTight' in RCut:
99 nmohr 1.17 Datacradbin=options[10]
100 peller 1.11 elif 'RMed' in RCut:
101 nmohr 1.17 Datacradbin=options[10]
102 peller 1.11 else:
103     Datacradbin=options[10]
104 peller 1.36 blind=eval(config.get('LimitGeneral','blind'))
105     BKGlist = eval(config.get('LimitGeneral','BKG'))
106     #Groups for adding samples together
107     Group = eval(config.get('LimitGeneral','Group'))
108     #naming for DC
109     Dict= eval(config.get('LimitGeneral','Dict'))
110     weightF_sys = eval(config.get('LimitGeneral','weightF_sys'))
111     binstat = eval(config.get('LimitGeneral','binstat'))
112 nmohr 1.37 addSample_sys = None if not config.has_option('LimitGeneral','addSample_sys') else eval(config.get('LimitGeneral','addSample_sys'))
113 peller 1.36 bdt = False
114     mjj = False
115     #print str(anType)
116     #print len(options)
117     if str(anType) == 'BDT':
118     bdt = True
119     systematics = eval(config.get('LimitGeneral','sys_BDT'))
120     elif str(anType) == 'Mjj':
121     mjj = True
122     systematics = eval(config.get('LimitGeneral','sys_Mjj'))
123     sys_cut_suffix=eval(config.get('LimitGeneral','sys_cut_suffix'))
124    
125 peller 1.56 rebin_active=eval(config.get('LimitGeneral','rebin_active'))
126 peller 1.36
127 peller 1.57 signal_inject=config.get('LimitGeneral','signal_inject')
128    
129 nmohr 1.24
130 peller 1.53 class Rebinner:
131 peller 1.56 def __init__(self,nBins,lowedgearray,active=True):
132 peller 1.53 self.lowedgearray=lowedgearray
133     self.nBins=nBins
134 peller 1.56 self.active=active
135 peller 1.53 def rebin(self, histo):
136 peller 1.56 if not self.active: return histo
137 peller 1.53 histo.Rebin(self.nBins,'hnew',self.lowedgearray)
138     binhisto=ROOT.gDirectory.Get('hnew')
139     newhisto=ROOT.TH1F('new','new',self.nBins,self.lowedgearray[0],self.lowedgearray[-1])
140 peller 1.56 newhisto.Sumw2()
141 peller 1.53 for bin in range(0,self.nBins+1):
142     newhisto.SetBinContent(bin,binhisto.GetBinContent(bin))
143     newhisto.SetBinError(bin,binhisto.GetBinError(bin))
144     newhisto.SetName(binhisto.GetName())
145     newhisto.SetTitle(binhisto.GetTitle())
146     return newhisto
147    
148    
149 peller 1.23
150 peller 1.36 # -------------------- generate the Workspace with all Histograms: ----------------------------------------------------------------------
151 peller 1.11
152     WS = ROOT.RooWorkspace('%s'%Datacradbin,'%s'%Datacradbin) #Zee
153 peller 1.1 print 'WS initialized'
154 bortigno 1.7 disc= ROOT.RooRealVar(name,name,xMin,xMax)
155 peller 1.1 obs = ROOT.RooArgList(disc)
156     ROOT.gROOT.SetStyle("Plain")
157     datas = []
158     datatyps =[]
159     histos = []
160     typs = []
161 nmohr 1.37 hNames = []
162 nmohr 1.39 aNames = []
163 peller 1.1 statUps=[]
164     statDowns=[]
165 nmohr 1.15 if blind:
166 peller 1.29 printc('red','', 'I AM BLINDED!')
167 peller 1.53
168    
169    
170     #---- get the BKG for the rebinning calculation----
171     counterRB=0
172 peller 1.57 injection = False
173 peller 1.53
174     for job in info:
175     if eval(job.active):
176     if job.subsamples:
177     for subsample in range(0,len(job.subnames)):
178     if job.subnames[subsample] in BKGlist:
179     hTemp, typ = getHistoFromTree(job,path,config,options,MC_rescale_factor,subsample)
180     if counterRB == 0:
181     hDummyRB = copy(hTemp)
182     else:
183     hDummyRB.Add(hTemp)
184     counterRB += 1
185    
186     else:
187     if job.name in BKGlist:
188     hTemp, typ = getHistoFromTree(job,path,config,options,MC_rescale_factor)
189     if counterRB == 0:
190     hDummyRB = copy(hTemp)
191     else:
192     hDummyRB.Add(hTemp)
193     counterRB += 1
194 peller 1.57
195    
196     elif job.name == signal_inject:
197     inject_SIG, _ = getHistoFromTree(job,path,config,options,MC_rescale_factor)
198     injection = True
199    
200 peller 1.53 ErrorR=0
201     ErrorL=0
202     TotR=0
203     TotL=0
204 peller 1.54 binR=nBinsRB
205 peller 1.53 binL=1
206     rel=1.0
207     #---- from right
208 peller 1.56 while rel > 0.35:
209 peller 1.53 TotR+=hDummyRB.GetBinContent(binR)
210     ErrorR=sqrt(ErrorR**2+hDummyRB.GetBinError(binR)**2)
211     binR-=1
212     if not TotR == 0 and not ErrorR == 0:
213     rel=ErrorR/TotR
214     #print rel
215     print 'upper bin is %s'%binR
216    
217     #---- from left
218     rel=1.0
219 peller 1.56 while rel > 0.35:
220 peller 1.53 TotL+=hDummyRB.GetBinContent(binL)
221     ErrorL=sqrt(ErrorL**2+hDummyRB.GetBinError(binL)**2)
222     binL+=1
223     if not TotL == 0 and not ErrorL == 0:
224     rel=ErrorL/TotL
225     #print rel
226     print 'lower bin is %s'%binL
227    
228     inbetween=binR-binL
229 peller 1.54 stepsize=int(inbetween)/(int(nBins)-2)
230     modulo = int(inbetween)%(int(nBins)-2)
231 peller 1.53
232     print'stepsize %s'% stepsize
233     print 'modulo %s'%modulo
234    
235 peller 1.55 binlist=[binL]
236 peller 1.54 for i in range(0,int(nBins)-3):
237 peller 1.53 binlist.append(binlist[-1]+stepsize)
238     binlist[-1]+=modulo
239     binlist.append(binR)
240 peller 1.54 binlist.append(nBinsRB+1)
241 peller 1.53
242     print binlist
243 peller 1.56 myBinning=Rebinner(int(nBins),array('d',[-1.0]+[hDummyRB.GetBinLowEdge(i) for i in binlist]),rebin_active)
244 peller 1.53 #--------------------------------------------------
245    
246 peller 1.57
247     if injection: hDummyRB.Add(inject_SIG)
248 peller 1.54 hDummy=myBinning.rebin(hDummyRB)
249 peller 1.53
250    
251 peller 1.33 if weightF_sys:
252 peller 1.48 weightF_sys_UP=config.get('Weights','weightF_sys_UP')
253     weightF_sys_DOWN=config.get('Weights','weightF_sys_DOWN')
254 peller 1.33 weightF_sys_Ups = []
255     weightF_sys_Downs = []
256 nmohr 1.37 if addSample_sys:
257     sTyps = []
258     addSample_sys_histos = []
259     aSample_sys_Ups = []
260     aSample_sys_Downs = []
261 peller 1.33
262 peller 1.1 for job in info:
263 peller 1.28 if eval(job.active):
264 peller 1.29 if job.subsamples:
265     for subsample in range(0,len(job.subnames)):
266     if job.subnames[subsample] in BKGlist:
267 peller 1.45 print 'getting %s'%job.subnames[subsample]
268 nmohr 1.31 hTemp, typ = getHistoFromTree(job,path,config,options,MC_rescale_factor,subsample)
269 peller 1.45 print hTemp.Integral()
270 peller 1.53 histos.append(myBinning.rebin(hTemp))
271 peller 1.29 typs.append(Group[job.subnames[subsample]])
272 nmohr 1.37 hNames.append(job.subnames[subsample])
273 peller 1.33 if weightF_sys:
274 peller 1.48 hTempWU, _ = getHistoFromTree(job,path,config,options,MC_rescale_factor,subsample,'weightF_sys_UP')
275 peller 1.53 weightF_sys_Ups.append(myBinning.rebin(hTempWU))
276 peller 1.48 hTempWD, _ = getHistoFromTree(job,path,config,options,MC_rescale_factor,subsample,'weightF_sys_DOWN')
277 peller 1.53 weightF_sys_Downs.append(myBinning.rebin(hTempWD))
278 peller 1.48
279 peller 1.29 elif job.subnames[subsample] == SIG:
280 peller 1.45 hNames.append(job.subnames[subsample])
281     print 'getting %s'%job.subnames[subsample]
282 nmohr 1.31 hTemp, typ = getHistoFromTree(job,path,config,options,MC_rescale_factor,subsample)
283 peller 1.45 print hTemp.Integral()
284 peller 1.53 histos.append(myBinning.rebin(hTemp))
285 peller 1.29 typs.append(Group[job.subnames[subsample]])
286 peller 1.33 if weightF_sys:
287 peller 1.48 hTempWU, _ = getHistoFromTree(job,path,config,options,MC_rescale_factor,subsample,'weightF_sys_UP')
288 peller 1.53 weightF_sys_Ups.append(myBinning.rebin(hTempWU))
289 peller 1.48 hTempWD, _ = getHistoFromTree(job,path,config,options,MC_rescale_factor,subsample,'weightF_sys_DOWN')
290 peller 1.53 weightF_sys_Downs.append(myBinning.rebin(hTempWD))
291 nmohr 1.41 if addSample_sys and job.subnames[subsample] in addSample_sys.values():
292 nmohr 1.40 aNames.append(job.subnames[subsample])
293 nmohr 1.51 hTempS, s_ = getHistoFromTree(job,path,config,options,MC_rescale_factor,subsample)
294 peller 1.53 addSample_sys_histos.append(myBinning.rebin(hTempS))
295 peller 1.29
296     else:
297     if job.name in BKGlist:
298     #print job.getpath()
299 peller 1.45 print 'getting %s'%job.name
300 nmohr 1.31 hTemp, typ = getHistoFromTree(job,path,config,options,MC_rescale_factor)
301 peller 1.53 histos.append(myBinning.rebin(hTemp))
302 peller 1.45 print hTemp.Integral()
303 peller 1.33 typs.append(Group[job.name])
304 peller 1.42 hNames.append(job.name)
305 peller 1.33 if weightF_sys:
306 peller 1.48 hTempWU, _ = getHistoFromTree(job,path,config,options,MC_rescale_factor,-1,'weightF_sys_UP')
307 peller 1.53 weightF_sys_Ups.append(myBinning.rebin(hTempWU))
308 peller 1.48 hTempWD, _ = getHistoFromTree(job,path,config,options,MC_rescale_factor,-1,'weightF_sys_DOWN')
309 peller 1.55 weightF_sys_Downs.append(myBinning.rebin(hTempWD))
310 peller 1.33
311 peller 1.29 elif job.name == SIG:
312 peller 1.45 print 'getting %s'%job.name
313 nmohr 1.31 hTemp, typ = getHistoFromTree(job,path,config,options,MC_rescale_factor)
314 peller 1.53 histos.append(myBinning.rebin(hTemp))
315 peller 1.45 print hTemp.Integral()
316 peller 1.33 typs.append(Group[job.name])
317 nmohr 1.37 hNames.append(job.name)
318 peller 1.33 if weightF_sys:
319 peller 1.48 hTempWU, _ = getHistoFromTree(job,path,config,options,MC_rescale_factor,-1,'weightF_sys_UP')
320 peller 1.53 weightF_sys_Ups.append(myBinning.rebin(hTempWU))
321 peller 1.48 hTempWD, _ = getHistoFromTree(job,path,config,options,MC_rescale_factor,-1,'weightF_sys_DOWN')
322 peller 1.53 weightF_sys_Downs.append(myBinning.rebin(hTempWD))
323 peller 1.33
324 peller 1.29 elif job.name in data:
325     #print 'DATA'
326 peller 1.45 print 'getting %s'%job.name
327 nmohr 1.31 hTemp, typ = getHistoFromTree(job,path,config,options)
328 peller 1.53 datas.append(myBinning.rebin(hTemp))
329 peller 1.45 print hTemp.Integral()
330 peller 1.29 datatyps.append(typ)
331 nmohr 1.40
332 peller 1.43 if addSample_sys and job.name in addSample_sys.values():
333 peller 1.42 aNames.append(job.name)
334     hTempS, s_ = getHistoFromTree(job,path,config,options,MC_rescale_factor)
335 peller 1.53 addSample_sys_histos.append(myBinning.rebin(hTempS))
336 peller 1.1
337     MC_integral=0
338     MC_entries=0
339     for histo in histos:
340     MC_integral+=histo.Integral()
341 peller 1.45 print 'histo integral %s'%histo.Integral()
342 peller 1.36 printc('green','', 'MC integral = %s'%MC_integral)
343    
344 nmohr 1.37 def getAlternativeShapes(histos,altHistos,hNames,aNames,addSample_sys):
345 nmohr 1.51 theHistosUp = []
346     theHistosDown = []
347     for histo in histos:
348     theHistosUp.append(histo.Clone())
349     theHistosDown.append(histo.Clone())
350 nmohr 1.37 for name in addSample_sys.keys():
351     print name
352 nmohr 1.51 hVar = altHistos[aNames.index(addSample_sys[name])].Clone()
353     hNom = histos[hNames.index(name)].Clone()
354     hAlt = hNom.Clone()
355     hNom.Add(hVar,-1.)
356     hAlt.Add(hNom)
357     for bin in range(0,nBins):
358     if hAlt.GetBinContent(bin) < 0.: hAlt.SetBinContent(bin,0.)
359     theHistosUp[hNames.index(name)] = hVar.Clone()
360     theHistosDown[hNames.index(name)] = hAlt.Clone()
361 nmohr 1.37 return theHistosUp, theHistosDown
362    
363 peller 1.13 #order and add together
364 peller 1.33 typs2=copy(typs)
365 nmohr 1.37 typs3=copy(typs)
366     typs4=copy(typs)
367 peller 1.48 typs5=copy(typs)
368 nmohr 1.40 if addSample_sys:
369     aSampleUp, aSampleDown = getAlternativeShapes(histos,addSample_sys_histos,hNames,aNames,addSample_sys)
370 peller 1.13 histos, typs = orderandadd(histos,typs,setup)
371 nmohr 1.37 if weightF_sys:
372 peller 1.48 weightF_sys_Ups,_=orderandadd(weightF_sys_Ups,typs2,setup)
373     weightF_sys_Downs,_=orderandadd(weightF_sys_Downs,typs3,setup)
374    
375 nmohr 1.37 if addSample_sys:
376 peller 1.48 aSampleUp,aNames=orderandadd(aSampleUp,typs4,setup)
377     aSampleDown,aNames=orderandadd(aSampleDown,typs5,setup)
378 peller 1.1
379     for i in range(0,len(histos)):
380 peller 1.29 newname=Dict[typs[i]]
381     histos[i].SetName(newname)
382 peller 1.5 #histos[i].SetDirectory(outfile)
383     outfile.cd()
384 peller 1.1 histos[i].Write()
385 nmohr 1.22 errorsum=0
386     total=0
387     for j in range(histos[i].GetNbinsX()+1):
388     errorsum=errorsum+(histos[i].GetBinError(j))**2
389     errorsum=sqrt(errorsum)
390     total=histos[i].Integral()
391 peller 1.35
392 peller 1.36 if binstat: #treating statistics in single bins
393 peller 1.35 for bin in range(0,nBins):
394     statUps.append(histos[i].Clone())
395     statDowns.append(histos[i].Clone())
396     statUps[i*nBins+bin].SetName('%sCMS_vhbb_stats_%s_%s_%sUp'%(newname,newname,bin,options[10]))
397     statDowns[i*nBins+bin].SetName('%sCMS_vhbb_stats_%s_%s_%sDown'%(newname,newname,bin,options[10]))
398     #shift up and down with statistical error
399     if rescaleSqrtN:
400     statUps[i*nBins+bin].SetBinContent(bin,statUps[i*nBins+bin].GetBinContent(bin)+statUps[i*nBins+bin].GetBinError(bin)/total*errorsum)
401     statDowns[i*nBins+bin].SetBinContent(bin,statDowns[i*nBins+bin].GetBinContent(bin)-statDowns[i*nBins+bin].GetBinError(bin)/total*errorsum)
402     else:
403     statUps[i*nBins+bin].SetBinContent(bin,statUps[i*nBins+bin].GetBinContent(bin)+statUps[i*nBins+bin].GetBinError(bin))
404     statDowns[i*nBins+bin].SetBinContent(bin,statDowns[i*nBins+bin].GetBinContent(bin)-statDowns[i*nBins+bin].GetBinError(bin))
405     statUps[i*nBins+bin].Write()
406     statDowns[i*nBins+bin].Write()
407     histPdf = ROOT.RooDataHist(newname,newname,obs,histos[i])
408     #UP stats of MCs
409     RooStatsUp = ROOT.RooDataHist('%sCMS_vhbb_stats_%s_%s_%sUp'%(newname,newname,bin,options[10]),'%sCMS_vhbb_stats_%s_%s_%sUp'%(newname,newname,bin,options[10]),obs, statUps[i*nBins+bin])
410     #DOWN stats of MCs
411     RooStatsDown = ROOT.RooDataHist('%sCMS_vhbb_stats_%s_%s_%sDown'%(newname,newname,bin,options[10]),'%sCMS_vhbb_stats_%s_%s_%sDown'%(newname,newname,bin,options[10]),obs, statDowns[i*nBins+bin])
412     getattr(WS,'import')(histPdf)
413     getattr(WS,'import')(RooStatsUp)
414     getattr(WS,'import')(RooStatsDown)
415 peller 1.13
416 peller 1.35 else:
417     statUps.append(histos[i].Clone())
418     statDowns.append(histos[i].Clone())
419     statUps[i].SetName('%sCMS_vhbb_stats_%s_%sUp'%(newname,newname,options[10]))
420     statDowns[i].SetName('%sCMS_vhbb_stats_%s_%sDown'%(newname,newname,options[10]))
421     #shift up and down with statistical error
422     for j in range(histos[i].GetNbinsX()+1):
423     if rescaleSqrtN:
424     statUps[i].SetBinContent(j,statUps[i].GetBinContent(j)+statUps[i].GetBinError(j)/total*errorsum)
425     statDowns[i].SetBinContent(j,statDowns[i].GetBinContent(j)-statDowns[i].GetBinError(j)/total*errorsum)
426     else:
427     statUps[i].SetBinContent(j,statUps[i].GetBinContent(j)+statUps[i].GetBinError(j))
428     statDowns[i].SetBinContent(j,statDowns[i].GetBinContent(j)-statDowns[i].GetBinError(j))
429 peller 1.47 #if statDowns[i].GetBinError(j)<0.: statDowns[i].SetBinContent(j,0.)
430 peller 1.35 statUps[i].Write()
431     statDowns[i].Write()
432     histPdf = ROOT.RooDataHist(newname,newname,obs,histos[i])
433     #UP stats of MCs
434     RooStatsUp = ROOT.RooDataHist('%sCMS_vhbb_stats_%s_%sUp'%(newname,newname,options[10]),'%sCMS_vhbb_stats_%s_%sUp'%(newname,newname,options[10]),obs, statUps[i])
435     #DOWN stats of MCs
436     RooStatsDown = ROOT.RooDataHist('%sCMS_vhbb_stats_%s_%sDown'%(newname,newname,options[10]),'%sCMS_vhbb_stats_%s_%sDown'%(newname,newname,options[10]),obs, statDowns[i])
437     getattr(WS,'import')(histPdf)
438     getattr(WS,'import')(RooStatsUp)
439     getattr(WS,'import')(RooStatsDown)
440    
441     #And now WeightF sys
442 peller 1.33 if weightF_sys:
443 peller 1.49 weightF_sys_Downs[i].SetName('%sUEPSDown'%(newname))
444     weightF_sys_Ups[i].SetName('%sUEPSUp'%(newname))
445 peller 1.33 weightF_sys_Ups[i].Write()
446 peller 1.35 weightF_sys_Downs[i].Write()
447 peller 1.49 RooWeightFUp = ROOT.RooDataHist('%sUEPSUp'%(newname),'%sUEPSUp'%(newname),obs, weightF_sys_Ups[i])
448     RooWeightFDown = ROOT.RooDataHist('%sUEPSDown'%(newname),'%sUEPSDown'%(newname),obs, weightF_sys_Downs[i])
449 peller 1.33 getattr(WS,'import')(RooWeightFUp)
450     getattr(WS,'import')(RooWeightFDown)
451 nmohr 1.37 #And now Additional sample sys
452     if addSample_sys:
453     aSample_sys_Downs.append(aSampleUp[i].Clone())
454     aSample_sys_Ups.append(aSampleDown[i].Clone())
455     aSample_sys_Downs[i].SetName('%sCMS_vhbb_model_%sDown'%(newname,newname))
456     aSample_sys_Ups[i].SetName('%sCMS_vhbb_model_%sUp'%(newname,newname))
457     aSample_sys_Ups[i].Write()
458     aSample_sys_Downs[i].Write()
459     RooSampleUp = ROOT.RooDataHist('%sCMS_vhbb_model_%sUp'%(newname,newname),'%sCMS_vhbb_model_%sUp'%(newname,newname),obs, aSample_sys_Ups[i])
460     RooSampleDown = ROOT.RooDataHist('%sCMS_vhbb_model_%sDown'%(newname,newname),'%sCMS_vhbb_model_%sDown'%(newname,newname),obs, aSample_sys_Downs[i])
461     getattr(WS,'import')(RooSampleUp)
462     getattr(WS,'import')(RooSampleDown)
463 peller 1.1
464    
465     #HISTOGRAMM of DATA
466 peller 1.54 d1 = datas[0]
467     if len(datas)>1:
468     for i in range(1,len(datas)):
469     d1.Add(datas[i],1)
470 peller 1.13 printc('green','','\nDATA integral = %s\n'%d1.Integral())
471 peller 1.1 flow = d1.GetEntries()-d1.Integral()
472     if flow > 0:
473 peller 1.13 printc('red','','U/O flow: %s'%flow)
474 peller 1.29 d1.SetName(Dict['Data'])
475 peller 1.5 outfile.cd()
476 peller 1.47 #d1.Write()
477    
478 peller 1.36
479 nmohr 1.15 if blind:
480 peller 1.47 print 'toy data integral: %s'%hDummy.Integral()
481 peller 1.29 hDummy.SetName(Dict['Data'])
482     histPdf = ROOT.RooDataHist(Dict['Data'],Dict['Data'],obs,hDummy)
483 nmohr 1.25 #rooDummy = ROOT.RooDataHist('data_obs','data_obs',obs,hDummy)
484     #toy = ROOT.RooHistPdf('data_obs','data_obs',ROOT.RooArgSet(obs),rooDummy)
485     #rooDataSet = toy.generate(ROOT.RooArgSet(obs),int(d1.Integral()))
486     #histPdf = ROOT.RooDataHist('data_obs','data_obs',ROOT.RooArgSet(obs),rooDataSet.reduce(ROOT.RooArgSet(obs)))
487 peller 1.47 hDummy.Write()
488 nmohr 1.15 else:
489 peller 1.29 histPdf = ROOT.RooDataHist(Dict['Data'],Dict['Data'],obs,d1)
490 peller 1.47 d1.Write()
491 peller 1.1 #ROOT.RooAbsData.plotOn(histPdf,frame)
492     getattr(WS,'import')(histPdf)
493    
494     #SYSTEMATICS:
495     UD = ['Up','Down']
496     systhistosarray=[]
497 peller 1.13 Coco=0 #iterates over (all systematics) * (up,down)
498 nmohr 1.22 nominalShape = options[0]
499 bortigno 1.7
500     for sys in systematics:
501 peller 1.36 for Q in UD: # Q = 'Up' and 'Down'
502 peller 1.32 #options[7] ist der CutString name
503     new_cut=sys_cut_suffix[sys]
504     new_options = copy(options)
505     if not new_cut == 'nominal':
506 peller 1.34 old_str,new_str=new_cut.split('>')
507     new_options[7]=[options[7],old_str,new_str.replace('?',Q)]
508 peller 1.1 ff=options[0].split('.')
509 bortigno 1.7 if bdt == True:
510 peller 1.52 #options[0] ist die treeVar
511 peller 1.13 ff[1]='%s_%s'%(sys,Q.lower())
512 peller 1.32 new_options[0]=nominalShape.replace('.nominal','.%s_%s'%(sys,Q.lower()))
513 bortigno 1.7 elif mjj == True:
514 peller 1.52 if sys == 'JER' or sys == 'JES':
515     ff[0]='H_%s'%(sys)
516     ff[1]='mass_%s'%(Q.lower())
517     new_options[0]='.'.join(ff)
518     else: pass
519 peller 1.1
520 peller 1.8 print '\n'
521 peller 1.13 printc('blue','','\t--> doing systematic %s %s'%(sys,Q.lower()))
522 peller 1.1
523     systhistosarray.append([])
524     typsX = []
525    
526     for job in info:
527 peller 1.29 if eval(job.active):
528     if job.subsamples:
529     for subsample in range(0,len(job.subnames)):
530     if job.subnames[subsample] in BKGlist:
531 peller 1.32 hTemp, typ = getHistoFromTree(job,path,config,new_options,MC_rescale_factor,subsample)
532 peller 1.53 systhistosarray[Coco].append(myBinning.rebin(hTemp))
533 peller 1.29 typsX.append(Group[job.subnames[subsample]])
534     elif job.subnames[subsample] == SIG:
535 peller 1.32 hTemp, typ = getHistoFromTree(job,path,config,new_options,MC_rescale_factor,subsample)
536 peller 1.53 systhistosarray[Coco].append(myBinning.rebin(hTemp))
537 peller 1.29 typsX.append(Group[job.subnames[subsample]])
538    
539     else:
540     if job.name in BKGlist:
541 peller 1.32 hTemp, typ = getHistoFromTree(job,path,config,new_options,MC_rescale_factor)
542 peller 1.53 systhistosarray[Coco].append(myBinning.rebin(hTemp))
543 peller 1.29 typsX.append(Group[job.name])
544     elif job.name == SIG:
545 peller 1.32 hTemp, typ = getHistoFromTree(job,path,config,new_options,MC_rescale_factor)
546 peller 1.53 systhistosarray[Coco].append(myBinning.rebin(hTemp))
547 peller 1.29 typsX.append(Group[job.name])
548    
549 peller 1.1 MC_integral=0
550     for histoX in systhistosarray[Coco]:
551     MC_integral+=histoX.Integral()
552 peller 1.13 printc('green','', 'MC integral = %s'%MC_integral)
553     systhistosarray[Coco], typsX = orderandadd(systhistosarray[Coco],typsX,setup)
554 peller 1.29
555 peller 1.36 if scaling: #rescaling after the sys has been propagated through the BDT with a scaling
556 peller 1.13 for i in range(0,len(systhistosarray[Coco])):
557     for bin in range(0,histos[i].GetSize()):
558     A=systhistosarray[Coco][i].GetBinContent(bin)
559     B=histos[i].GetBinContent(bin)
560     systhistosarray[Coco][i].SetBinContent(bin,B+((A-B)/4.))
561 nmohr 1.24 # finaly lpop over histos
562 peller 1.1 for i in range(0,len(systhistosarray[Coco])):
563 peller 1.29 systhistosarray[Coco][i].SetName('%s%s%s'%(Dict[typs[i]],systematicsnaming[sys],Q))
564 peller 1.5 outfile.cd()
565 peller 1.13 systhistosarray[Coco][i].Write()
566 peller 1.29 histPdf = ROOT.RooDataHist('%s%s%s'%(Dict[typs[i]],systematicsnaming[sys],Q),'%s%s%s'%(Dict[typs[i]],systematicsnaming[sys],Q),obs,systhistosarray[Coco][i])
567 peller 1.1 getattr(WS,'import')(histPdf)
568     Coco+=1
569     WS.writeToFile(outpath+'vhbb_WS_'+ROOToutname+'.root')
570    
571 peller 1.36
572    
573     # -------------------- write DATAcard: ----------------------------------------------------------------------
574 peller 1.29 columns=len(setup)
575    
576 nmohr 1.18 if '8TeV' in options[10]:
577 peller 1.42 pier = open(vhbbpath+'/python/pier8TeV.txt','r')
578 nmohr 1.18 else:
579 peller 1.42 pier = open(vhbbpath+'/python/pier.txt','r')
580 peller 1.1 scalefactors=pier.readlines()
581     pier.close()
582     f = open(outpath+'vhbb_DC_'+ROOToutname+'.txt','w')
583     f.write('imax\t1\tnumber of channels\n')
584 peller 1.29 f.write('jmax\t%s\tnumber of backgrounds (\'*\' = automatic)\n'%(columns-1))
585 peller 1.1 f.write('kmax\t*\tnumber of nuisance parameters (sources of systematical uncertainties)\n\n')
586 peller 1.11 if bdt==True:
587     f.write('shapes * * vhbb_WS_%s.root $CHANNEL:$PROCESS $CHANNEL:$PROCESS$SYSTEMATIC\n\n'%ROOToutname)
588     else:
589     f.write('shapes * * vhbb_TH_%s.root $PROCESS $PROCESS$SYSTEMATIC\n\n'%ROOToutname)
590     f.write('bin\t%s\n\n'%Datacradbin)
591 nmohr 1.25 if blind:
592     f.write('observation\t%s\n\n'%(hDummy.Integral()))
593     else:
594     f.write('observation\t%s\n\n'%(int(d1.Integral())))
595 peller 1.14
596 peller 1.29 f.write('bin')
597     for c in range(0,columns): f.write('\t%s'%Datacradbin)
598     f.write('\n')
599    
600     f.write('process')
601     for c in setup: f.write('\t%s'%Dict[c])
602     f.write('\n')
603    
604     f.write('process')
605     for c in range(0,columns): f.write('\t%s'%c)
606     f.write('\n')
607    
608     f.write('rate')
609     for c in range(0,columns): f.write('\t%s'%histos[c].Integral())
610     f.write('\n')
611    
612 peller 1.58 InUse=eval(config.get('Datacard','InUse_%s'pt_region))
613 peller 1.29 #Parse from config
614     for item in InUse:
615     f.write(item)
616     what=eval(config.get('Datacard',item))
617     f.write('\t%s'%what['type'])
618     for c in setup:
619     if c in what:
620     if item == 'CMS_eff_e' and 'Zmm' in options[10]: f.write('\t-')
621     elif item == 'CMS_eff_m' and 'Zee' in options[10]: f.write('\t-')
622     elif item == 'CMS_trigger_e' and 'Zmm' in options[10]: f.write('\t-')
623     elif item == 'CMS_trigger_m' and 'Zee' in options[10]: f.write('\t-')
624     else:
625     f.write('\t%s'%what[c])
626     else:
627     f.write('\t-')
628     f.write('\n')
629    
630     #Write shape stats and sys
631 peller 1.35 if binstat:
632     for c in setup:
633     for bin in range(0,nBins):
634     f.write('CMS_vhbb_stats_%s_%s_%s\tshape'%(Dict[c], bin, options[10]))
635     for it in range(0,columns):
636     if it == setup.index(c):
637     f.write('\t1.0')
638     else:
639     f.write('\t-')
640     f.write('\n')
641    
642     else:
643     for c in setup:
644     f.write('CMS_vhbb_stats_%s_%s\tshape'%(Dict[c], options[10]))
645     for it in range(0,columns):
646     if it == setup.index(c):
647     f.write('\t1.0')
648     else:
649     f.write('\t-')
650     f.write('\n')
651 peller 1.29
652 peller 1.33 if weightF_sys:
653 peller 1.50 f.write('UEPS\tshape')
654 peller 1.33 for it in range(0,columns): f.write('\t1.0')
655     f.write('\n')
656    
657 nmohr 1.37 if addSample_sys:
658 nmohr 1.51 alreadyAdded = []
659 nmohr 1.37 for newSample in addSample_sys.iterkeys():
660 nmohr 1.51 for c in setup:
661     if not c == Group[newSample]: continue
662     if Dict[c] in alreadyAdded: continue
663 nmohr 1.37 f.write('CMS_vhbb_model_%s\tshape'%(Dict[c]))
664     for it in range(0,columns):
665     if it == setup.index(c):
666     f.write('\t1.0')
667     else:
668     f.write('\t-')
669     f.write('\n')
670 nmohr 1.51 alreadyAdded.append(Dict[c])
671 peller 1.33
672 peller 1.45 if scaling: sys_factor=1.0
673 peller 1.29 else: sys_factor=1.0
674     for sys in systematics:
675     f.write('%s\tshape'%systematicsnaming[sys])
676     for c in range(0,columns): f.write('\t%s'%sys_factor)
677     f.write('\n')
678 peller 1.1 f.close()
679 nmohr 1.31 outfile.Close()