forked from conformist89/sfs_workspace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_crosspog_json.py
417 lines (370 loc) · 12.7 KB
/
create_crosspog_json.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import correctionlib._core as core
import correctionlib.schemav2 as schema
import correctionlib.JSONEncoder as JSONEncoder
from workspace_reader import WorkspaceReader
import ROOT
import json
import os
import yaml
# set epsilon value to avoid giant scale factors
epsilon = 0.0001
class CorrectionSet(object):
def __init__(self, name):
self.name = name
self.corrections = []
def add_correction_file(self, correction_file):
with open(correction_file) as file:
data = json.load(file)
corr = schema.Correction.parse_obj(data)
self.add_correction(corr)
def add_correction(self, correction):
if isinstance(correction, dict):
self.corrections.append(correction)
elif isinstance(correction, Correction):
self.corrections.append(correction.correctionset)
else:
raise TypeError(
"Correction must be a Correction object or a dictionary, not {}".format(
type(correction)
)
)
def write_json(self, outputfile):
# Create the JSON object
cset = schema.CorrectionSet(
schema_version=schema.VERSION, corrections=self.corrections
)
print(f">>> Writing {outputfile}...")
JSONEncoder.write(cset, outputfile)
JSONEncoder.write(cset, outputfile + ".gz")
class Correction(object):
def __init__(
self,
tag,
name,
outdir,
configfile,
era,
fname="",
data_only=False,
verbose=False,
):
self.tag = tag
self.name = name
self.outdir = outdir
self.configfile = configfile
self.ptbinning = []
self.etabinning = []
self.inputfiles = []
self.correction = None
self.era = era
self.header = ""
self.fname = fname
self.info = ""
self.verbose = verbose
self.data_only = data_only
self.correctionset = None
self.inputobjects = {}
self.types = ["Data", "Embedding", "DY"]
def __repr__(self) -> str:
return "Correction({})".format(self.name)
def __str__(self) -> str:
return "Correction({})".format(self.name)
def parse_config(self):
pass
def setup_scheme(self):
pass
def generate_sfs(self):
pass
def generate_scheme(self):
pass
class pt_eta_correction(Correction):
def __init__(
self,
tag,
name,
configfile,
era,
outdir,
fname="",
data_only=False,
verbose=False,
):
super(pt_eta_correction, self).__init__(
tag,
name,
outdir,
configfile,
era,
fname,
data_only,
verbose,
)
if self.data_only:
self.types = ["Data"]
def set_workspace(self):
self.workspace = WorkspaceReader("/work/olavoryk/corr_lib_com/htt_scalefactors_UL_"+str(self.era).replace("UL","")+".root")
def parse_config(self):
config = yaml.safe_load(open(self.configfile))
self.ptbinning = config[self.name]["bins_x"]
self.etabinning = config[self.name]["bins_y"]
basename = str(os.path.basename(self.configfile)).split("_")[1]
self.info = config[self.name]["info"]
self.header = config[self.name]["header"]
def GetFromTFile(self, inputfile, object):
print("Getting ", object, "from ", inputfile)
f = ROOT.TFile(inputfile)
obj = f.Get(object).Clone()
f.Close()
return obj
def setup_scheme(self):
self.correctionset = {
"version": 0,
"name": self.name,
"description": self.info,
"inputs": [
{
"name": "pt",
"type": "real",
"description": "Reconstructed muon pT",
},
{
"name": "abs(eta)",
"type": "real",
"description": "Reconstructed muon eta",
},
],
"output": {
"name": "sf",
"type": "real",
"description": "pT-eta-dependent scale factor",
},
"data": None,
}
if not self.data_only:
self.correctionset["inputs"].append(
{
"name": "type",
"type": "string",
"description": "Type of correction: Embedding or MC",
}
)
def generate_sfs(self):
sfs = {}
if self.data_only:
sfs = {
"nodetype": "binning",
"input": "pt",
"edges": self.ptbinning,
"flow": "clamp",
"content": [
{
"nodetype": "binning",
"input": "abs(eta)",
"edges": self.etabinning,
"flow": "clamp",
"content" : self.workspace.get_emb_id_sel( pt, self.etabinning)
}
for pt in self.ptbinning[:-1]
],
}
else:
# without data only, we add both the mc and the embedding sfs
sfs = {
"nodetype": "binning",
"input": "pt",
"edges": self.ptbinning,
"flow": "clamp",
"content": [
{
"nodetype": "binning",
"input": "abs(eta)",
"edges": self.etabinning,
"flow": "clamp",
"content": [
{
"nodetype": "category",
"input": "type",
"content": [
{
"key": "mc",
"value": self.workspace.get_sfs_2D( pt, eta, self.name, "mc")
},
{
"key": "emb",
"value": self.workspace.get_sfs_2D( pt, eta, self.name, "emb")
},
],
}
for eta in self.etabinning[:-1]
],
}
for pt in self.ptbinning[:-1]
],
}
return schema.Binning.parse_obj(sfs)
def generate_scheme(self):
self.parse_config()
self.setup_scheme()
self.set_workspace()
self.correctionset["data"] = self.generate_sfs()
output_corr = schema.Correction.parse_obj(self.correctionset)
self.correction = output_corr
# print(JSONEncoder.dumps(self.correction))
def write_scheme(self):
if self.verbose >= 2:
print(JSONEncoder.dumps(self.correction))
elif self.verbose >= 1:
print(self.correction)
if self.fname:
print(f">>> Writing {self.fname}...")
JSONEncoder.write(self.correction, self.fname)
class emb_doublemuon_correction(Correction):
def __init__(
self,
tag,
name,
configfile,
era,
outdir,
triggernames,
fname="",
data_only=True,
verbose=False,
):
super(emb_doublemuon_correction, self).__init__(
tag,
name,
outdir,
configfile,
era,
fname,
data_only,
verbose,
)
self.types = ["Data"]
self.names = triggernames
def set_workspace(self):
self.workspace = WorkspaceReader("/work/olavoryk/corr_lib_com/htt_scalefactors_UL_"+str(self.era).replace("UL","")+".root")
def parse_config(self):
config = yaml.safe_load(open(self.configfile))
self.ptbinning = config[self.name]["bins_x"]
self.etabinning = config[self.name]["bins_y"]
basename = (
str(os.path.basename(self.configfile)).split("_")[1].replace(".yaml", "")
)
self.info = config[self.name]["info"]
self.header = config[self.name]["header"]
def setup_scheme(self):
self.correctionset = {
"version": 0,
"name": self.name,
"description": self.info,
"inputs": [
{
"name": "pt_1",
"type": "real",
"description": "Reconstructed leading genparticle pT",
},
{
"name": "abs(eta_1)",
"type": "real",
"description": "Reconstructed leading genparticle eta",
},
{
"name": "pt_2",
"type": "real",
"description": "Reconstructed trailing genparticle pT",
},
{
"name": "abs(eta_2)",
"type": "real",
"description": "Reconstructed trailing genparticle eta",
},
],
"output": {
"name": "sf",
"type": "real",
"description": "pT-eta-dependent scale factor",
},
"data": None,
}
if not self.data_only:
self.correctionset["inputs"].append(
{
"name": "type",
"type": "string",
"description": "Type of correction: Embedding or MC",
}
)
def generate_sfs(self):
if self.data_only:
sfs = schema.Binning.parse_obj(
{
"nodetype": "binning",
"input": "pt_1",
"edges": self.ptbinning,
"flow": "clamp",
"content": [
{
"nodetype": "binning",
"input": "abs(eta_1)",
"edges": self.etabinning,
"flow": "clamp",
"content": [
{
"nodetype": "binning",
"input": "pt_2",
"edges": self.ptbinning,
"flow": "clamp",
"content": [
{
"nodetype": "binning",
"input": "abs(eta_2)",
"edges": self.etabinning,
"flow": "clamp",
"content" : self.workspace.get_emb_sel_sfs( pt_1, eta_1, pt_2, self.etabinning)
}
for pt_2 in self.ptbinning[:-1]
],
}
for eta_1 in self.etabinning[:-1]
],
}
for pt_1 in self.ptbinning[:-1]
],
}
)
else:
raise Exception("Not implemented")
return sfs
def generate_scheme(self):
self.parse_config()
self.setup_scheme()
self.set_workspace()
self.correctionset["data"] = self.generate_sfs()
output_corr = schema.Correction.parse_obj(self.correctionset)
self.correction = output_corr
def write_scheme(self):
if self.verbose >= 2:
print(JSONEncoder.dumps(self.correction))
elif self.verbose >= 1:
print(self.correction)
if self.fname:
print(f">>> Writing {self.fname}...")
JSONEncoder.write(self.correction, self.fname)
if __name__ == "__main__":
ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gROOT.SetBatch(ROOT.kTRUE)
# for keeping the histograms in memory
ROOT.TH1.AddDirectory(0)
test = pt_eta_correction(
tag="test",
name="EmbID_pt_eta_bins",
outdir="output/jsons",
configfile="settings/settings_embeddingselection_2018UL.yaml",
era="2018UL",
fname="{}/{}.json".format("output/jsons", "test"),
data_only=True,
verbose=False,
)
test.generate_scheme()