-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathcorrection.py
2145 lines (1970 loc) · 87.2 KB
/
correction.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import importlib.resources
import cloudpickle, gzip, contextlib
import copy, os, re, warnings
import numpy as np
import awkward as ak
import uproot
import correctionlib
from coffea.lookup_tools import extractor, txt_converters, rochester_lookup
from coffea.lumi_tools import LumiMask
from coffea.jetmet_tools.CorrectedMETFactory import corrected_polar_met
from coffea.analysis_tools import Weights
from coffea.btag_tools import BTagScaleFactor
from BTVNanoCommissioning.helpers.func import update, _compile_jec_, _load_jmefactory
from BTVNanoCommissioning.helpers.cTagSFReader import getSF
from BTVNanoCommissioning.utils.AK4_parameters import correction_config as config
def load_SF(year, campaign, syst=False):
"""
Load scale factors (SF) for a given year and campaign.
This function reads scale factors from the specified campaign configuration and returns them in a suitable format.
It handles different types of scale factors, such as pileup weights, and checks for the existence of files in
the jsonpog-integration directory or custom files.
Example:
```python
## Initialization, add EGM map from correctionlib
correction_map["EGM"] = correctionlib.CorrectionSet.from_file(
f"src/BTVNanoCommissioning/jsonpog-integration/POG/EGM/{campaign}/electron.json.gz"
)
## Initialization, add EGM map from custom file by extractor
ext = extractor()
ext.add_weight_sets(["eleID EGamma2D {filename}.root"])
ext.finalize()
correction_map["EGM"] = ext.make_evaluator()
```
Parameters:
year (str): The year for which to load the scale factors.
campaign (str): The name of the campaign for which to load the scale factors.
syst (bool, optional): A flag to indicate whether to load systematic variations. Default is False.
Returns:
dict: A dictionary containing the scale factors, where keys are the relevant identifiers and values are the scale factors.
Raises:
FileNotFoundError: If the specified file does not exist.
ValueError: If the file content is not in the expected format.
KeyError: If the specified campaign or year is not found in the configuration.
"""
# read the configuration file to get the correct SFs
correct_map = {"campaign": campaign}
for SF in config[campaign].keys():
if SF == "lumiMask":
continue
## pileup weight
if SF == "PU":
## Check whether files in jsonpog-integration exist
if os.path.exists(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/LUM/{year}_{campaign}"
):
correct_map["PU"] = correctionlib.CorrectionSet.from_file(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/LUM/{year}_{campaign}/puWeights.json.gz"
)
## Otherwise custom files
else:
_pu_path = f"BTVNanoCommissioning.data.PU.{campaign}"
with importlib.resources.path(
_pu_path, config[campaign]["PU"]
) as filename:
if str(filename).endswith(".pkl.gz"):
with gzip.open(filename) as fin:
correct_map["PU"] = cloudpickle.load(fin)[
"2017_pileupweight"
]
elif str(filename).endswith(".json.gz"):
correct_map["PU"] = correctionlib.CorrectionSet.from_file(
str(filename)
)
elif str(filename).endswith(".histo.root"):
ext = extractor()
ext.add_weight_sets([f"* * {filename}"])
ext.finalize()
correct_map["PU"] = ext.make_evaluator()
## btag weight
elif SF == "BTV":
if "btag" in config[campaign]["BTV"].keys() and config[campaign]["BTV"][
"btag"
].endswith(".json.gz"):
correct_map["btag"] = correctionlib.CorrectionSet.from_file(
importlib.resources.path(
f"BTVNanoCommissioning.data.BTV.{year}_{campaign}", filename
)
)
if "ctag" in config[campaign]["BTV"].keys() and config[campaign]["BTV"][
"ctag"
].endswith(".json.gz"):
correct_map["btag"] = correctionlib.CorrectionSet.from_file(
importlib.resources.path(
f"BTVNanoCommissioning.data.BTV.{year}_{campaign}", filename
)
)
if os.path.exists(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/BTV/{year}_{campaign}"
):
correct_map["btag"] = correctionlib.CorrectionSet.from_file(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/BTV/{year}_{campaign}/btagging.json.gz"
)
correct_map["ctag"] = correctionlib.CorrectionSet.from_file(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/BTV/{year}_{campaign}/ctagging.json.gz"
)
else:
correct_map["btag"] = {}
correct_map["ctag"] = {}
correct_map["btv_cfg"] = config[campaign]["BTV"]
_btag_path = f"BTVNanoCommissioning.data.BTV.{year}_{campaign}"
for tagger in config[campaign]["BTV"]:
with importlib.resources.path(
_btag_path, config[campaign]["BTV"][tagger]
) as filename:
if "B" in tagger:
if filename.endswith(".json.gz"):
correct_map["btag"] = (
correctionlib.CorrectionSet.from_file(filename)
)
else:
correct_map["btag"][tagger] = BTagScaleFactor(
filename,
BTagScaleFactor.RESHAPE,
methods="iterativefit,iterativefit,iterativefit",
)
else:
if filename.endswith(".json.gz"):
correct_map["ctag"] = (
correctionlib.CorrectionSet.from_file(filename)
)
else:
correct_map["ctag"][tagger] = BTagScaleFactor(
filename,
BTagScaleFactor.RESHAPE,
methods="iterativefit,iterativefit,iterativefit",
)
## lepton SFs
elif SF == "LSF":
correct_map["MUO_cfg"] = {
mu: f
for mu, f in config[campaign]["LSF"].items()
if "mu" in mu and "_json" not in mu
}
correct_map["EGM_cfg"] = {
e: f
for e, f in config[campaign]["LSF"].items()
if "ele" in e and "_json" not in e
}
## Muon
if os.path.exists(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/MUO/{year}_{campaign}"
):
correct_map["MUO"] = correctionlib.CorrectionSet.from_file(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/MUO/{year}_{campaign}/muon_Z.json.gz"
)
if os.path.exists(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/EGM/{year}_{campaign}"
):
correct_map["EGM"] = correctionlib.CorrectionSet.from_file(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/EGM/{year}_{campaign}/electron.json.gz"
)
if any(
np.char.find(np.array(list(config[campaign]["LSF"].keys())), "mu_json")
!= -1
):
correct_map["MUO"] = correctionlib.CorrectionSet.from_file(
f"src/BTVNanoCommissioning/data/LSF/{year}_{campaign}/{config[campaign]['LSF']['mu_json']}"
)
if any(
np.char.find(np.array(list(config[campaign]["LSF"].keys())), "ele_json")
!= -1
):
correct_map["EGM"] = correctionlib.CorrectionSet.from_file(
f"src/BTVNanoCommissioning/data/LSF/{year}_{campaign}/{config[campaign]['LSF']['ele_json']}"
)
### Check if any custom corrections needed
# FIXME: (some low pT muons not supported in jsonpog-integration at the moment)
if (
"histo.json" in "\t".join(list(config[campaign]["LSF"].values()))
or "histo.txt" in "\t".join(list(config[campaign]["LSF"].values()))
or "histo.root" in "\t".join(list(config[campaign]["LSF"].values()))
):
_mu_path = f"BTVNanoCommissioning.data.LSF.{campaign}"
ext = extractor()
with contextlib.ExitStack() as stack:
inputs, real_paths = [
k
for k in correct_map["MUO_cfg"].keys()
if "histo.json" in correct_map["MUO_cfg"][k]
or "histo.txt" in correct_map["MUO_cfg"][k]
or "histo.root" in correct_map["MUO_cfg"][k]
], [
stack.enter_context(importlib.resources.path(_mu_path, f))
for f in correct_map["MUO_cfg"].values()
if ".json" in f or ".txt" in f or ".root" in f
]
inputs = [
i.split(" ")[0] + " *" if "_low" in i else i for i in inputs
]
ext.add_weight_sets(
[
f"{paths} {file}"
for paths, file in zip(inputs, real_paths)
if "histo.json" in str(file)
or "histo.txt" in str(file)
or "histo.root" in str(file)
]
)
if syst:
ext.add_weight_sets(
paths.split(" ")[0]
+ "_error "
+ paths.split(" ")[1]
+ "_error "
+ file
for paths, file in zip(inputs, real_paths)
if ".root" in str(file)
)
ext.finalize()
correct_map["MUO_custom"] = ext.make_evaluator()
_ele_path = f"BTVNanoCommissioning.data.LSF.{campaign}"
ext = extractor()
with contextlib.ExitStack() as stack:
inputs, real_paths = [
k
for k in correct_map["EGM_cfg"].keys()
if "histo.json" in correct_map["EGM_cfg"][k]
or "histo.txt" in correct_map["EGM_cfg"][k]
or "histo.root" in correct_map["EGM_cfg"][k]
], [
stack.enter_context(importlib.resources.path(_ele_path, f))
for f in correct_map["EGM_cfg"].values()
if "histo.json" in f or ".txt" in f or ".root" in f
]
ext.add_weight_sets(
[
f"{paths} {file}"
for paths, file in zip(inputs, real_paths)
if "histo.json" in str(file)
or "histo.txt" in str(file)
or "histo.root" in str(file)
]
)
if syst:
ext.add_weight_sets(
paths.split(" ")[0]
+ "_error "
+ paths.split(" ")[1]
+ "_error "
+ file
for paths, file in zip(inputs, real_paths)
if ".root" in str(file)
)
ext.finalize()
correct_map["EGM_custom"] = ext.make_evaluator()
## rochester muon momentum correction
elif SF == "roccor":
if "2016postVFP_UL" == campaign:
filename = "RoccoR2016bUL.txt"
elif "2016preVFP_UL" in campaign:
filename = "RoccoR2016aUL.txt"
elif "2017_UL" in campaign:
filename = "RoccoR2017UL.txt"
if "2018_UL" in campaign:
filename = "RoccoR2018UL.txt"
full_path = "src/BTVNanoCommissioning/data/LSF/roccor/" + filename
rochester_data = txt_converters.convert_rochester_file(
full_path, loaduncs=True
)
correct_map["roccor"] = rochester_lookup.rochester_lookup(rochester_data)
## JME corrections
elif SF == "JME":
if "name" in config[campaign]["JME"].keys():
if not os.path.exists(
f"src/BTVNanoCommissioning/data/JME/{year}_{campaign}/jec_compiled_{config[campaign]['JME']['name']}.pkl.gz"
):
_compile_jec_(
year,
campaign,
config[campaign]["JME"],
f"jec_compiled_{config[campaign]['JME']['name']}",
)
correct_map["JME"] = _load_jmefactory(
year,
campaign,
f"jec_compiled_{config[campaign]['JME']['name']}.pkl.gz",
)
elif os.path.exists(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/JME/{year}_{campaign}/jet_jerc.json.gz"
):
correct_map["JME"] = correctionlib.CorrectionSet.from_file(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/JME/{year}_{campaign}/jet_jerc.json.gz"
)
correct_map["JME_cfg"] = config[campaign]["JME"]
for dataset in correct_map["JME_cfg"].keys():
if (
np.all(
np.char.find(
np.array(list(correct_map["JME"].keys())),
correct_map["JME_cfg"][dataset],
)
)
== -1
):
raise (
f"{dataset} has no JEC map : {correct_map['JME_cfg'][dataset]} available"
)
elif SF == "JMAR":
if os.path.exists(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/JME/{year}_{campaign}/jmar.json.gz"
):
correct_map["JMAR_cfg"] = {
j: f for j, f in config[campaign]["JMAR"].items()
}
correct_map["JMAR"] = correctionlib.CorrectionSet.from_file(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/JME/{year}_{campaign}/jmar.json.gz"
)
elif SF == "jetveto":
if os.path.exists(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/JME/{year}_{campaign}/jetvetomaps.json.gz"
):
correct_map["jetveto"] = correctionlib.CorrectionSet.from_file(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/JME/{year}_{campaign}/jetvetomaps.json.gz"
)
else:
ext = extractor()
with contextlib.ExitStack() as stack:
ext.add_weight_sets(
[
f"{run} {stack.enter_context(importlib.resources.path(f'BTVNanoCommissioning.data.JME.{year}_{campaign}',file))}"
for run, file in config[campaign]["jetveto"].items()
]
)
ext.finalize()
correct_map["jetveto_cfg"] = {
j: f for j, f in config[campaign]["jetveto"].items()
}
correct_map["jetveto"] = ext.make_evaluator()
return correct_map
def load_lumi(campaign):
"""
Load luminosity mask for a given campaign.
This function reads the luminosity mask file for the specified campaign and returns a `LumiMask` object.
Parameters:
campaign (str): The name of the campaign for which to load the luminosity mask.
Returns:
LumiMask: An object representing the luminosity mask for the specified campaign.
Raises:
KeyError: If the specified campaign is not found in the configuration.
FileNotFoundError: If the luminosity mask file does not exist.
"""
_lumi_path = "BTVNanoCommissioning.data.lumiMasks"
with importlib.resources.path(_lumi_path, config[campaign]["lumiMask"]) as filename:
return LumiMask(filename)
##JEC
# FIXME: would be nicer if we can move to correctionlib in the future together with factory and workable
def add_jec_variables(jets, event_rho):
jets["pt_raw"] = (1 - jets.rawFactor) * jets.pt
jets["mass_raw"] = (1 - jets.rawFactor) * jets.mass
if hasattr(jets, "genJetIdxG"):
jets["pt_gen"] = ak.values_astype(
ak.fill_none(jets.matched_gen.pt, 0), np.float32
)
else:
jets["pt_gen"] = ak.zeros_like(jets.pt)
jets["event_rho"] = ak.broadcast_arrays(event_rho, jets.pt)[0]
return jets
## Jet Veto
def jetveto(jets, correct_map):
"""
Apply a veto to jets based on predefined transverse momentum (pt) and pseudorapidity (eta) thresholds.
This function filters out jets that do not meet the predefined pt and eta criteria. It also utilizes a correction map
to apply additional corrections or selections to the jets.
Parameters:
jets (iterable): A collection of jet objects or dictionaries containing jet properties.
correct_map (dict): A dictionary containing correction factors or additional selection criteria for the jets.
Returns:
jets: A jets of jets that pass the predefined pt and eta criteria and any additional criteria from the correction map.
Raises:
TypeError: If the jets parameter is not an iterable.
KeyError: If the jet objects do not contain the required 'pt' or 'eta' properties.
"""
if "correctionlib" in str(
type(correct_map["jetveto"][list(correct_map["jetveto"].keys())[0]])
):
j, nj = ak.flatten(jets), ak.num(jets)
return ak.unflatten(
correct_map["jetveto"][list(correct_map["jetveto"].keys())[0]].evaluate(
"jetvetomap",
np.clip(j.eta, -5.191, 5.191),
np.clip(j.phi, -3.141592, 3.141592),
),
nj,
)
else:
return ak.where(
correct_map["jetveto"][list(correct_map["jetveto"].keys())[0]](
jets.phi, jets.eta
)
> 0,
ak.ones_like(jets.eta),
ak.zeros_like(jets.eta),
)
# from https://gitlab.cern.ch/cms-nanoAOD/jsonpog-integration/-/blob/master/examples/jercExample.py
def get_corr_inputs(input_dict, corr_obj, jersyst="nom"):
"""
Helper function for getting values of input variables
given a dictionary and a correction object.
"""
input_values = []
for inputs in corr_obj.inputs:
if "systematic" in inputs.name:
input_values.append(jersyst)
else:
input_values.append(
np.array(
input_dict[
inputs.name.replace("Jet", "")
.replace("Pt", "pt")
.replace("Phi", "phi")
.replace("Eta", "eta")
.replace("Mass", "mass")
.replace("Rho", "rho")
.replace("A", "area")
]
)
)
return input_values
cset_jersmear = (
correctionlib.CorrectionSet.from_file(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/JME/jer_smear.json.gz"
)
if os.path.exists(
f"/cvmfs/cms.cern.ch/rsync/cms-nanoAOD/jsonpog-integration/POG/JME/jer_smear.json.gz"
)
else {"JERSmear": None}
)
sf_jersmear = cset_jersmear["JERSmear"]
## JERC
def JME_shifts(
shifts,
correct_map,
events,
year,
campaign,
isRealData,
systematic=False,
exclude_jetveto=False,
):
"""
Apply Jet Energy Corrections (JEC) and Jet Energy Resolutions (JER) shifts to events.
This function applies JEC and JER shifts to the jets in the events based on the provided correction map and campaign.
It handles both real data and simulated data, and can optionally apply systematic variations and exclude jet vetoes.
Parameters:
shifts (list): A list of shift types to apply (e.g., 'up', 'down').
correct_map (dict): A dictionary containing correction factors and settings for JEC and JER.
events (awkward.Array): An array of events containing jet information.
year (str): The year for which to apply the corrections.
campaign (str): The name of the campaign for which to apply the corrections.
isRealData (bool): A flag indicating whether the data is real or simulated.
systematic (bool, optional): A flag to indicate whether to apply systematic variations. Default is False.
exclude_jetveto (bool, optional): A flag to indicate whether to exclude jet vetoes. Default is False.
Returns:
awkward.Array: The events array with applied JEC and JER shifts.
Raises:
KeyError: If required keys are missing in the correct_map.
ValueError: If the campaign is not recognized or supported.
"""
dataset = events.metadata["dataset"]
jecname = ""
# https://cms-jerc.web.cern.ch/JECUncertaintySources/, currently no recommendation of reduced/ full split sources
syst_list = [
i.split("_")[3]
for i in correct_map["JME"].keys()
if "MC" in i and "L1" not in i and "L2" not in i and "L3" not in i
]
if "JME" in correct_map.keys():
## correctionlib
if "JME_cfg" in correct_map.keys():
if isRealData:
jecname = [
v
for k, v in correct_map["JME_cfg"].items()
if k in events.metadata["dataset"]
]
if len(jecname) > 1:
raise ValueError("Multiple uncertainties match to this era")
elif len(jecname) == 0:
raise ValueError(
"Available JEC variations in this era are not compatible with this file. Did you choose the correct dataset-era combination?"
)
else:
jecname = jecname[0] + "_DATA"
else:
jecname = correct_map["JME_cfg"]["MC"].split(" ")[0] + "_MC"
jrname = correct_map["JME_cfg"]["MC"].split(" ")[1] + "_MC"
# store the original jet info
nocorrjet = events.Jet
nocorrjet["pt_raw"] = (1 - nocorrjet["rawFactor"]) * nocorrjet["pt"]
nocorrjet["mass_raw"] = (1 - nocorrjet["rawFactor"]) * nocorrjet["mass"]
nocorrjet["rho"] = ak.broadcast_arrays(
events.fixedGridRhoFastjetAll, nocorrjet.pt
)[0]
nocorrjet["EventID"] = ak.broadcast_arrays(events.event, nocorrjet.pt)[0]
if not isRealData:
genjetidx = ak.where(nocorrjet.genJetIdx == -1, 0, nocorrjet.genJetIdx)
nocorrjet["Genpt"] = ak.where(
nocorrjet.genJetIdx == -1, -1, events.GenJet[genjetidx].pt
)
jets = copy.copy(nocorrjet)
jets["orig_pt"] = ak.values_astype(nocorrjet["pt"], np.float32)
## flatten jets
j, nj = ak.flatten(nocorrjet), ak.num(nocorrjet)
# JEC
JECcorr = correct_map["JME"].compound[f"{jecname}_L1L2L3Res_AK4PFPuppi"]
JEC_input = get_corr_inputs(j, JECcorr)
JECflatCorrFactor = JECcorr.evaluate(*JEC_input)
## JER
if isRealData:
# In data only the JEC is applied
corrFactor = JECflatCorrFactor
else:
JERSF = correct_map["JME"][f"{jrname}_ScaleFactor_AK4PFPuppi"]
JERptres = correct_map["JME"][f"{jrname}_PtResolution_AK4PFPuppi"]
## For MC, correct the jet pT with JEC first
j["pt"] = j["pt_raw"] * JECflatCorrFactor
j["mass"] = j["mass_raw"] * JECflatCorrFactor
JERSF_input = get_corr_inputs(j, JERSF)
JERptres_input = get_corr_inputs(j, JERptres)
j["JER"] = JERptres.evaluate(*JERptres_input)
j["JERSF"] = JERSF.evaluate(*JERSF_input)
JERsmear_input = get_corr_inputs(j, sf_jersmear)
corrFactor = JECflatCorrFactor * sf_jersmear.evaluate(*JERsmear_input)
corrFactor = ak.unflatten(corrFactor, nj)
jets["pt"] = ak.values_astype(nocorrjet["pt_raw"] * corrFactor, np.float32)
jets["mass"] = ak.values_astype(
nocorrjet["mass_raw"] * corrFactor, np.float32
)
# MET correction, from MET correct factory
# https://github.com/CoffeaTeam/coffea/blob/d7d02634a8d268b130a4d71f76d8eba6e6e27b96/coffea/jetmet_tools/CorrectedMETFactory.py#L105
nocorrmet = events.PuppiMET if int(year) > 2020 else events.MET
met = copy.copy(nocorrmet)
metinfo = [nocorrmet.pt, nocorrmet.phi, jets.pt, jets.phi, jets.pt_raw]
met["pt"], met["phi"] = (
ak.values_astype(corrected_polar_met(*metinfo).pt, np.float32),
ak.values_astype(corrected_polar_met(*metinfo).phi, np.float32),
)
met["orig_pt"], met["orig_phi"] = nocorrmet["pt"], nocorrmet["phi"]
## JEC variations
if not isRealData and systematic != False:
if systematic != "JERC_split":
jesuncmap = correct_map["JME"][f"{jecname}_Total_AK4PFPuppi"]
jesunc = ak.unflatten(jesuncmap.evaluate(j.eta, j.pt), nj)
unc_jets, unc_met = {}, {}
for var in ["up", "down"]:
fac = 1.0 if var == "up" else -1.0
# JES total
unc_jets[f"JES_Total{var}"] = copy.copy(nocorrjet)
unc_met[f"JES_Total{var}"] = copy.copy(nocorrmet)
unc_jets[f"JES_Total{var}"]["pt"] = ak.values_astype(
jets["pt"]
* (ak.unflatten(JECflatCorrFactor, nj) + fac * jesunc),
np.float32,
)
unc_jets[f"JES_Total{var}"]["mass"] = ak.values_astype(
jets["mass"]
* (ak.unflatten(JECflatCorrFactor, nj) + fac * jesunc),
np.float32,
)
unc_met[f"JES_Total{var}"]["pt"] = corrected_polar_met(
nocorrmet.pt,
nocorrmet.phi,
unc_jets[f"JES_Total{var}"]["pt"],
jets.phi,
jets.pt_raw,
).pt
unc_met[f"JES_Total{var}"]["phi"] = corrected_polar_met(
nocorrmet.pt,
nocorrmet.phi,
unc_jets[f"JES_Total{var}"]["pt"],
jets.phi,
jets.pt_raw,
).phi
JERSF_input_var = get_corr_inputs(j, JERSF, var)
## JER variations
unc_jets[f"JER{var}"] = copy.copy(nocorrjet)
unc_met[f"JER{var}"] = copy.copy(nocorrmet)
j["JERSF"] = JERSF.evaluate(*JERSF_input_var)
JERsmear_input_var = get_corr_inputs(j, sf_jersmear)
unc_jets[f"JER{var}"]["pt"] = jets["pt"] * ak.unflatten(
JECflatCorrFactor
* sf_jersmear.evaluate(*JERsmear_input_var),
nj,
)
unc_jets[f"JER{var}"]["mass"] = jets["mass"] * ak.unflatten(
JECflatCorrFactor
* sf_jersmear.evaluate(*JERsmear_input_var),
nj,
)
unc_met[f"JER{var}"]["pt"] = corrected_polar_met(
nocorrmet.pt,
nocorrmet.phi,
unc_jets[f"JER{var}"]["pt"],
jets.phi,
jets.pt_raw,
).pt
unc_met[f"JER{var}"]["phi"] = corrected_polar_met(
nocorrmet.pt,
nocorrmet.phi,
unc_jets[f"JER{var}"]["pt"],
jets.phi,
jets.pt_raw,
).phi
jets["JES_Total"] = ak.zip(
{
"up": unc_jets["JES_Totalup"],
"down": unc_jets["JES_Totaldown"],
}
)
jets["JER"] = ak.zip(
{
"up": unc_jets["JERup"],
"down": unc_jets["JERdown"],
}
)
met["JES_Total"] = ak.zip(
{
"up": unc_met["JES_Totalup"],
"down": unc_met["JES_Totaldown"],
}
)
met["JER"] = ak.zip(
{
"up": unc_met["JERup"],
"down": unc_met["JERdown"],
}
)
else:
raise NotImplementedError
else:
if isRealData:
if "2016preVFP_UL" == campaign:
if "2016B" in dataset or "2016C" in dataset or "2016D" in dataset:
jecname = "BCD"
elif "2016E" in dataset or "2016F" in dataset:
jecname = "EF"
elif "2016postVFP_UL" == campaign:
jecname = "FGH"
elif campaign == "Rereco17_94X":
jecname = ""
elif campaign == "Summer23":
if "v4" in dataset:
jecname = "Cv4"
else:
jecname = "Cv123"
elif re.search(r"[Rr]un20\d{2}([A-Z])", dataset):
jecname = re.search(r"[Rr]un20\d{2}([A-Z])", dataset).group(1)
else:
print("No valid jec name")
raise NameError
jecname = "data" + jecname
else:
jecname = "MC"
jets = correct_map["JME"]["jet_factory"][jecname].build(
add_jec_variables(events.Jet, events.fixedGridRhoFastjetAll),
lazy_cache=events.caches[0],
)
met = correct_map["JME"]["met_factory"].build(events.PuppiMET, jets, {})
## systematics
if not isRealData:
if systematic != False:
if systematic == "split":
for jes in met.fields:
if "JES" not in jes or "Total" in jes:
continue
shifts += [
(
{
"Jet": jets[jes]["up"],
"MET": met[jes]["up"],
},
f"{jes}Up",
),
(
{
"Jet": jets[jes]["down"],
"MET": met[jes]["down"],
},
f"{jes}Down",
),
]
else:
if "JES_Total" in jets.fields:
shifts += [
(
{
"Jet": jets.JES_Total.up,
"MET": met.JES_Total.up,
},
"JESUp",
),
(
{
"Jet": jets.JES_Total.down,
"MET": met.JES_Total.down,
},
"JESDown",
),
]
if "MET_UnclusteredEnergy" in met.fields:
shifts += [
(
{
"Jet": jets,
"MET": met.MET_UnclusteredEnergy.up,
},
"UESUp",
),
(
{
"Jet": jets,
"MET": met.MET_UnclusteredEnergy.down,
},
"UESDown",
),
]
if "JER" in jets.fields:
shifts += [
(
{
"Jet": jets.JER.up,
"MET": met.JER.up,
},
"JERUp",
),
(
{
"Jet": jets.JER.down,
"MET": met.JER.down,
},
"JERDown",
),
]
else:
met = events.PuppiMET
jets = events.Jet
# perform jet veto
if "jetveto" in correct_map.keys():
jets = update(jets, {"veto": jetveto(jets, correct_map)})
if "Summer22" in campaign:
jets = jets[jets.veto != 1]
shifts.insert(0, ({"Jet": jets, "MET": met}, None))
return shifts
## Muon Rochester correction
def Roccor_shifts(shifts, correct_map, events, isRealData, systematic=False):
"""
Apply Rochester corrections (Roccor) shifts to muons in events.
This function applies Rochester corrections to the muons in the events based on the provided correction map and campaign.
It handles both real data and simulated data, and can optionally apply systematic variations.
Parameters:
shifts (list): A list of shift types to apply (e.g., 'up', 'down').
correct_map (dict): A dictionary containing correction factors and settings for Rochester corrections.
events (awkward.Array): An array of events containing muon information.
campaign (str): The name of the campaign for which to apply the corrections.
isRealData (bool): A flag indicating whether the data is real or simulated.
systematic (bool, optional): A flag to indicate whether to apply systematic variations. Default is False.
Returns:
awkward.Array: The events array with applied Rochester corrections.
Raises:
KeyError: If required keys are missing in the correct_map.
ValueError: If the campaign is not recognized or supported.
"""
mu = events.Muon
if isRealData:
SF = correct_map["roccor"].kScaleDT(
events.Muon.charge, events.Muon.pt, events.Muon.eta, events.Muon.phi
)
else:
hasgen = ~np.isnan(ak.fill_none(events.Muon.matched_gen.pt, np.nan))
mc_kspread = correct_map["roccor"].kSpreadMC(
events.Muon.charge[hasgen],
events.Muon.pt[hasgen],
events.Muon.eta[hasgen],
events.Muon.phi[hasgen],
events.Muon.matched_gen.pt[hasgen],
)
mc_rand = np.random.rand(len(ak.flatten(events.Muon.pt, axis=1)))
mc_rand = ak.unflatten(mc_rand, ak.num(events.Muon.pt))
mc_ksmear = correct_map["roccor"].kSmearMC(
events.Muon.charge[~hasgen],
events.Muon.pt[~hasgen],
events.Muon.eta[~hasgen],
events.Muon.phi[~hasgen],
events.Muon.nTrackerLayers[~hasgen],
mc_rand[~hasgen],
)
SF = np.array(ak.flatten(ak.ones_like(events.Muon.pt)))
hasgen_flat = np.array(ak.flatten(hasgen))
SF[hasgen_flat] = np.array(ak.flatten(mc_kspread))
SF[~hasgen_flat] = np.array(ak.flatten(mc_ksmear))
SF = ak.unflatten(SF, ak.num(events.Muon.pt))
mu["pt"] = SF * events.Muon.pt
# add rochester correction to shift
for i in range(len(shifts)):
shifts[i][0]["Muon"] = mu
if systematic:
if isRealData:
err = correct_map["roccor"].kScaleDTerror(
events.Muon.charge, events.Muon.pt, events.Muon.eta, events.Muon.phi
)
else:
mc_errspread = correct_map["roccor"].kSpreadMCerror(
events.Muon.charge[hasgen],
events.Muon.pt[hasgen],
events.Muon.eta[hasgen],
events.Muon.phi[hasgen],
events.Muon.matched_gen.pt[hasgen],
)
mc_errsmear = correct_map["roccor"].kSmearMCerror(
events.Muon.charge[~hasgen],
events.Muon.pt[~hasgen],
events.Muon.eta[~hasgen],
events.Muon.phi[~hasgen],
events.Muon.nTrackerLayers[~hasgen],
mc_rand[~hasgen],
)
err = np.array(ak.flatten(ak.ones_like(events.Muon.pt)))
err[hasgen_flat] = np.array(ak.flatten(mc_errspread))
err[~hasgen_flat] = np.array(ak.flatten(mc_errsmear))
err = ak.unflatten(err, ak.num(events.Muon.pt))
muup, mudown = events.Muon, events.Muon
muup["pt"] = (SF + err) * events.Muon.pt
mudown["pt"] = (SF - err) * events.Muon.pt
shifts += [
(
{"Jet": shifts[0][0]["Jet"], "MET": shifts[0][0]["MET"], "Muon": muup},
"RoccorUp",
)
]
shifts += [
(
{
"Jet": shifts[0][0]["Jet"],
"MET": shifts[0][0]["MET"],
"Muon": mudown,
},
"RoccorDown",
)
]
return shifts
def puwei(nPU, correct_map, weights, syst=False):
"""
Return pileup weight
Parameters
----------
nPU: ak.Array
correct_map : dict
weights : coffea.analysis_tool.weights
syst: "split", "weight_only"
Apply pileup weights to events based on the number of primary vertices (nPU).
This function applies pileup weights to the events using the provided correction map and weights.
It can optionally apply systematic variations.
Parameters:
nPU (awkward.Array(int)): The number of primary vertices in the event.
correct_map (dict): A dictionary containing correction factors and settings for pileup weights.
weights (): A dictionary to store the calculated weights.
syst (bool, optional): A flag to indicate whether to apply systematic variations. Default is False.
Returns:
None: The function modifies the weights dictionary in place.
Raises:
KeyError: If required keys are missing in the correct_map.
ValueError: If the nPU value is not recognized or supported.
"""
if "correctionlib" in str(type(correct_map["PU"])):
if syst:
return weights.add(
"puweight",
correct_map["PU"][list(correct_map["PU"].keys())[0]].evaluate(
nPU, "nominal"
),
correct_map["PU"][list(correct_map["PU"].keys())[0]].evaluate(
nPU, "up"
),
correct_map["PU"][list(correct_map["PU"].keys())[0]].evaluate(
nPU, "down"
),
)
else:
return weights.add(
"puweight",
correct_map["PU"][list(correct_map["PU"].keys())[0]].evaluate(
nPU, "nominal"
),
)
else:
if syst:
weights.add(
"puweight",
correct_map["PU"]["PU"](nPU),
correct_map["PU"]["PUup"](nPU),
correct_map["PU"]["PUdown"](nPU),
)
else:
weights.add("puweight", correct_map["PU"]["PU"](nPU))
def btagSFs(jet, correct_map, weights, SFtype, syst=False):
"""
Apply b-tagging scale factors (SFs) to a single jet.