ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/workspace_datacard.py
Revision: 1.67
Committed: Wed Jan 16 16:22:47 2013 UTC (12 years, 3 months ago) by peller
Content type: text/x-python
Branch: MAIN
CVS Tags: workingVersionAfterHCP
Changes since 1.66: +22 -28 lines
Log Message:
reorganized the whole repository. Macros im myutils, config files in subdirectories. Config file split in parts. Path config file restructured. Moved all path options to the path config. Changed the code accordingly.

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