ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/workspace_datacard.py
Revision: 1.53
Committed: Thu Oct 18 14:43:33 2012 UTC (12 years, 6 months ago) by peller
Content type: text/x-python
Branch: MAIN
Changes since 1.52: +127 -28 lines
Log Message:
bin transformation

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