ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/workspace_datacard.py
Revision: 1.61
Committed: Thu Nov 1 12:50:27 2012 UTC (12 years, 6 months ago) by peller
Content type: text/x-python
Branch: MAIN
Changes since 1.60: +3 -3 lines
Log Message:
added sys factor feature to play with shape sys

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