ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/workspace_datacard.py
Revision: 1.38
Committed: Thu Sep 27 07:34:26 2012 UTC (12 years, 7 months ago) by peller
Content type: text/x-python
Branch: MAIN
Changes since 1.37: +0 -1 lines
Log Message:
plotting tools

File Contents

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