forked from JanFSchulte/CIAnalysis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.py
executable file
·384 lines (326 loc) · 12 KB
/
helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import ROOT
import gc
from array import array
from ROOT import TCanvas, TPad, TH1F, TH2F, TH1I, THStack, TLegend, TMath
from math import sqrt
from defs import defineMyColors, myColors, fileNames, fileNamesEle, path, crossSections, zScale, zScale2016
from copy import deepcopy
import math, uuid
def totalNumberOfGeneratedEvents(path,muon=True):
"""
path: path to directory containing all sample files
returns dict samples names -> number of simulated events in source sample
"""
from ROOT import TFile
result = {}
for sampleName, filePath in getFilePathsAndSampleNames(path,muon).items():
rootFile = TFile(filePath, "read")
result[sampleName] = rootFile.FindObjectAny("Events").GetBinContent(1)
return result
def negWeightFractions(path,muon=True):
"""
path: path to directory containing all sample files
returns dict samples names -> fraction of events wiBackgrounds2016th negative weights in source sample
"""
from ROOT import TFile
result = {}
for sampleName, filePath in getFilePathsAndSampleNames(path,muon).items():
rootFile = TFile(filePath, "read")
result[sampleName] = rootFile.FindObjectAny("weights").GetBinContent(1)/(rootFile.FindObjectAny("weights").GetBinContent(1)+rootFile.FindObjectAny("weights").GetBinContent(2))
return result
def binning(channel='muon'):
if channel == 'muon':
nbins = 51
m_min = 70.
m_max = 4000.
if channel == 'electron':
return ([j for j in range(50, 120, 5)] +
[j for j in range(120, 150, 5)] +
[j for j in range(150, 200, 10)] +
[j for j in range(200, 600, 20)]+
[j for j in range(600, 900, 30) ]+
[j for j in range(900, 1250, 50)] +
[j for j in range(1250, 1600, 60) ] +
[j for j in range(1600, 1900, 70) ] +
[j for j in range(1900, 4000, 80) ] +
[j for j in range(4000, 5000, 100) ] +
[5000])
# Calculate logarithmic bins
width = (math.log(m_max) - math.log(m_min)) / nbins
logbins = []
# Exceed m_max to start with Z' binning, but reach 5 TeV
for i in range(0, nbins + 8):
logbins.append(int(math.exp(math.log(m_min) + width * i)))
return logbins
def loadHistoFromFile(fileName,histName,rebin,muon=True,logBins=False):
"""
returns histogram from file
"""
from ROOT import TFile, TH1F
rootFile = TFile(path+fileName, "read")
if "saved_hist_for_combine" in fileName or "jets_muons" in fileName or "hist_jets" in fileName:
if muon:
if "be" in histName:
tmpResult = rootFile.Get("jetsBE")
elif "bb" in histName:
tmpResult = rootFile.Get("jetsBB")
else:
tmpResult = rootFile.Get("jets")
else:
if fileName == "hist_jets.root":
if "bbbe" in histName:
tmpResult = rootFile.Get("h_mee_all")
elif "bb" in histName:
tmpResult = rootFile.Get("h_mee_all_BB")
else:
tmpResult = rootFile.Get("h_mee_all_BE")
else:
if "bbbe" in histName:
tmpResult = rootFile.Get("Jets_h_mee_all")
elif "bb" in histName:
tmpResult = rootFile.Get("Jets_h_mee_all_BB")
else:
tmpResult = rootFile.Get("Jets_h_mee_all_BE")
result = tmpResult.Clone("jets")
else:
result = rootFile.Get(histName)
# ~ if logBins and( "Mass" in histName or ("jets" in histName and not ("saved_hist_for_combine" in fileName or "hist_jets" in fileName))):
if logBins and( "Mass" in histName and not ("saved_hist_for_combine" in fileName or "hist_jets" in fileName)):
if not muon:
bng = binning("electron")
else:
bng = binning("muon")
result = result.Rebin(len(bng) - 1, 'hist_' + uuid.uuid4().hex, array('d', bng))
for i in range(0,result.GetNbinsX()):
result.SetBinContent(i,result.GetBinContent(i)/result.GetBinWidth(i))
result.SetBinError(i,result.GetBinError(i)/result.GetBinWidth(i))
else:
result.Rebin(rebin)
result.SetDirectory(0)
return deepcopy(result)
def loadHistoFromFile2D(fileName,histName,rebin):
"""
returns histogram from file
"""
from ROOT import TFile, TH2F
rootFile = TFile(path+fileName, "read")
result = rootFile.Get(histName)
result.SetDirectory(0)
return deepcopy(result)
def loadHistoFromFileProjected(fileName,histName,rebin,binLow,binHigh=-1):
"""
returns histogram from file
"""
from random import randint
from sys import maxsize
name = "%x"%(randint(0, maxsize))
from ROOT import TFile, TH2F
rootFile = TFile(path+fileName, "read")
result = rootFile.Get(histName)
if binHigh == -1:
result = result.ProjectionY(name,int(binLow/100),binHigh)
else:
result = result.ProjectionY(name,result.GetXaxis().FindBin(binLow),result.GetXaxis().FindBin(binHigh-0.001))
result.Rebin(rebin)
result.SetDirectory(0)
return result
def getFilePathsAndSampleNames(path,muon=True):
"""
helper function
path: path to directory containing all sample files
returns: dict of smaple names -> path of .root file (for all samples in path)
"""
result = []
from glob import glob
from re import match
result = {}
for filePath in glob("%s/*.root"%(path)):
if muon:
if "dileptonAna_muons" in filePath and not "SingleMuon" in filePath:
sampleName = filePath.split("/")[-1].split("dileptonAna_muons_")[-1].split(".root")[0]
if "2016_" in sampleName:
if "CI" in sampleName:
sampleName = sampleName.replace("2016_","")
elif "ADD" in sampleName:
sampleName = sampleName.replace("2016_", "")
sampleName = sampleName.replace("LambdaT", "Lam")
else:
sampleName = sampleName.replace("2016_","")+"_2016"
if "2018_" in sampleName:
if "CI" in sampleName:
sampleName = sampleName.replace("2018_","") + "_2018"
elif "ADD" in sampleName:
sampleName = sampleName.replace("2018_", "")
sampleName = sampleName.replace("LambdaT", "Lam")
else:
sampleName = sampleName.replace("2016_","")+"_2016"
result[sampleName] = filePath
else:
if "dileptonAna_electrons" in filePath and not "DoubleElectron" in filePath:
sampleName = filePath.split("/")[-1].split("dileptonAna_electrons_")[-1].split(".root")[0]
if "2016_" in sampleName:
if "CI" in sampleName:
sampleName = sampleName.replace("2016_","")
elif "ADD" in sampleName:
sampleName = sampleName.replace("2016_", "")
sampleName = sampleName.replace("LambdaT", "Lam")
else:
sampleName = sampleName.replace("2016_","")+"_2016"
if "2018_" in sampleName:
if "CI" in sampleName:
sampleName = sampleName.replace("2018_","") + '_2018'
elif "ADD" in sampleName:
sampleName = sampleName.replace("2018_", "")
sampleName = sampleName.replace("LambdaT", "Lam")
else:
sampleName = sampleName.replace("2018_","")+"_2018"
result[sampleName] = filePath
return result
def getHistoFromTree(tree,plot,nEvents = -1):
from ROOT import TH1F
from random import randint
from sys import maxint
if nEvents < 0:
nEvents = maxint
name = "%x"%(randint(0, maxint))
if plot.binning == []:
result = TH1F(name, "", plot.nBins, plot.xMin, plot.xMax)
else:
result = TH1F(name, "", len(plot.binning)-1, array("f",plot.binning))
result.Sumw2()
tree.Draw("%s>>%s"%(plot.variable, name), plot.cut, "goff", nEvents)
result.SetBinContent(plot.nBins,result.GetBinContent(plot.nBins)+result.GetBinContent(plot.nBins+1))
if result.GetBinContent(plot.nBins) >= 0.:
result.SetBinError(plot.nBins,sqrt(result.GetBinContent(plot.nBins)))
else:
result.SetBinError(plot.nBins,0)
return result
def createMyColors():
iIndex = 2000
containerMyColors = []
for color in defineMyColors.keys():
tempColor = ROOT.TColor(iIndex,
float(defineMyColors[color][0]) / 255, float(defineMyColors[color][1]) / 255, float(defineMyColors[color][2]) / 255)
containerMyColors.append(tempColor)
myColors.update({ color: iIndex })
iIndex += 1
return containerMyColors
class Process:
samples = []
label = ""
theColor = 0
theLineColor = 0
histo = None
uncertainty = 0.
scaleFac = 1.
xsecs = []
nEvents = []
negWeightFraction = []
def __init__(self, process,Counts={"none":-1},negWeights={"none":-1}, normalized = False):
self.samples = process.subprocesses
self.label = process.label
self.theColor = process.fillcolor
self.theLineColor = process.linecolor
self.normalized = normalized
self.xsecs = []
self.negWeightFraction = []
self.nEvents = []
for sample in self.samples:
if not "Data" in sample and not "Jets" in sample:
if "ConRL" in sample or "DesRL" in sample:
self.xsecs.append(crossSections[sample.replace('RL',"LR")])
else:
self.xsecs.append(crossSections[sample])
self.negWeightFraction.append(negWeights[sample])
self.nEvents.append(Counts[sample])
def loadHistogram(self,plot,lumi,zScaleFac):
histo = None
if plot.plot2D:
for index, sample in enumerate(self.samples):
if plot.muon:
tempHist = loadHistoFromFile2D(fileNames[sample],plot.histName,plot.rebin)
else:
tempHist = loadHistoFromFile2D(fileNamesEle[sample],plot.histName,plot.rebin)
if not self.normalized:
tempHist.Scale(lumi*self.xsecs[index]/self.nEvents[index]*(1-2*self.negWeightFraction[index])*zScaleFac)
if histo == None:
histo = tempHist.Clone()
else:
histo.Add(tempHist.Clone())
histo.SetFillColor(self.theColor)
histo.SetLineColor(self.theLineColor)
histo.GetXaxis().SetTitle(plot.xaxis)
histo.GetYaxis().SetTitle(plot.yaxis)
else:
for index, sample in enumerate(self.samples):
if plot.muon:
tempHist = loadHistoFromFile(fileNames[sample],plot.histName,plot.rebin,plot.muon,plot.logX)
else:
tempHist = loadHistoFromFile(fileNamesEle[sample],plot.histName,plot.rebin,plot.muon,plot.logX)
if not self.normalized:
tempHist.Scale(lumi*self.xsecs[index]/self.nEvents[index]*(1-2*self.negWeightFraction[index])*zScaleFac)
if histo == None:
histo = tempHist.Clone()
else:
histo.Add(tempHist.Clone())
histo.SetFillColor(self.theColor)
histo.SetLineColor(self.theLineColor)
histo.GetXaxis().SetTitle(plot.xaxis)
histo.GetYaxis().SetTitle(plot.yaxis)
return histo
def loadHistogramProjected(self,plot,lumi,zScaleFac):
histo = None
for index, sample in enumerate(self.samples):
if plot.muon:
tempHist = loadHistoFromFileProjected(fileNames[sample],plot.histName,plot.rebin,plot.projLow,plot.projHigh)
else:
tempHist = loadHistoFromFileProjected(fileNamesEle[sample],plot.histName,plot.rebin,plot.projLow,plot.projHigh)
if len(self.xsecs) > 0:
tempHist.Scale(lumi*self.xsecs[index]/self.nEvents[index]*(1-2*self.negWeightFraction[index])*zScaleFac)
if histo == None:
histo = tempHist.Clone()
else:
histo.Add(tempHist.Clone())
histo.SetFillColor(self.theColor)
histo.SetLineColor(self.theLineColor)
histo.GetXaxis().SetTitle(plot.xaxis)
histo.GetYaxis().SetTitle(plot.yaxis)
return histo
class TheStack:
from ROOT import THStack
theStack = THStack()
theHistogram = None
def __init__(self,processes,lumi,plot,zScaleFac):
self.theStack = THStack()
for process in processes:
temphist = process.loadHistogram(plot,lumi,zScaleFac)
self.theStack.Add(temphist.Clone())
if self.theHistogram == None:
self.theHistogram = temphist.Clone()
else:
self.theHistogram.Add(temphist.Clone())
class TheStack2D:
from ROOT import THStack
theStack = THStack()
theHistogram = None
def __init__(self,processes,lumi,plot,zScale):
self.theStack = THStack()
for process in processes:
temphist = process.loadHistogramProjected(plot,lumi,zScale)
self.theStack.Add(temphist.Clone())
if self.theHistogram == None:
self.theHistogram = temphist.Clone()
else:
self.theHistogram.Add(temphist.Clone())
def getDataHist(plot,files,fromTree=False):
if not fromTree:
histo = loadHistoFromFile(files["data"], plot.histName,plot.rebin,plot.muon)
else:
histo = getHistoFromTree(files["data"], plot)
return histo
def getDataHist2D(plot,files,binLow,binHigh,fromTree=False):
if not fromTree:
histo = loadHistoFromFileProjected(files["data"], plot.histName,plot.rebin,binLow,binHigh)
else:
histo = getHistoFromTree(files["data"], plot)
return histo