Newer
Older

Florian Alexander Mausolf
committed
import numpy as np
import os
from scipy.interpolate import interp1d
import correctionlib
import awkward as ak
from higgs_dna.utils.misc_utils import choose_jet
import logging
logger = logging.getLogger(__name__)

Florian Alexander Mausolf
committed
def SF_photon_ID(
photons, weights, year="2017", WP="Loose", is_correction=True, **kwargs
):

Jan Lukas Spah
committed
"""

Jan Lukas Spah
committed
Applies the photon ID scale-factor and corresponding uncertainties for the customised cut on the EGamma MVA ID (Run 3)
JLS removed the support for the EGamma MVA ID SFs from https://gitlab.cern.ch/cms-nanoAOD/jsonpog-integration for Run 2 for now as this is not commonly used in the Hgg group
Take action yourself or contact us if you need those!

Jan Lukas Spah
committed
"""

Jan Lukas Spah
committed
# era/year defined as parameter of the function
avail_years = ["2022preEE", "2022postEE"]
if year not in avail_years:
print(f"\n WARNING: only scale corrections for the year strings {avail_years} are already implemented! \n Exiting. \n")
print("If you need the SFs for the central Egamma MVA ID for Run 2 UL, take action yourself or contact us!")
exit()

Jan Lukas Spah
committed

Jan Lukas Spah
committed
if year == "2022preEE":
json_file = os.path.join(os.path.dirname(__file__), "JSONs/SF_photon_ID/2022/PhotonIDMVA_2022PreEE.json")
elif year == "2022postEE":
json_file = os.path.join(os.path.dirname(__file__), "JSONs/SF_photon_ID/2022/PhotonIDMVA_2022PostEE.json")

Tiziano Bevilacqua
committed

Jan Lukas Spah
committed
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
evaluator = correctionlib.CorrectionSet.from_file(json_file)["PhotonIDMVA_SF"]
# In principle, we should use the fully correct formula https://indico.cern.ch/event/1360948/contributions/5783762/attachments/2788516/4870824/24_02_02_HIG-23-014_PreAppPres.pdf#page=7
# However, if the SF is pt-binned, the approximation of the multiplication of the two SFs is fully exact
if "2022" in year:
if is_correction:
# only calculate correction to nominal weight
sf_lead = evaluator.evaluate(
abs(photons["pho_lead"].ScEta), photons["pho_lead"].pt, "nominal"
)
sf_sublead = evaluator.evaluate(
abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].pt, "nominal"
)
sf = sf_lead * sf_sublead
sfup, sfdown = None, None
else:
# only calculate systs
sf = np.ones(len(weights._weight))
sf_lead = evaluator.evaluate(
abs(photons["pho_lead"].ScEta), photons["pho_lead"].pt, "nominal"
)
sf_sublead = evaluator.evaluate(
abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].pt, "nominal"
)
_sf = sf_lead * sf_sublead
sf_unc_lead = evaluator.evaluate(
abs(photons["pho_lead"].ScEta), photons["pho_lead"].pt, "uncertainty"
)
sf_unc_sublead = evaluator.evaluate(
abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].pt, "uncertainty"
)

Tiziano Bevilacqua
committed
sfup = (sf_lead + sf_unc_lead) * (sf_sublead + sf_unc_sublead) / _sf

Jan Lukas Spah
committed

Tiziano Bevilacqua
committed
sfdown = (sf_lead - sf_unc_lead) * (sf_sublead - sf_unc_sublead) / _sf

Jan Lukas Spah
committed
weights.add(name="SF_photon_ID", weight=sf, weightUp=sfup, weightDown=sfdown)
return weights
def Pileup(events, weights, year, is_correction=True, **kwargs):

Florian Alexander Mausolf
committed
"""
Function to apply either the pileup correction to MC to make it match the pileup profile of a certain year/period,
or the respective uncertainties.

Tiziano Bevilacqua
committed
The parameter `year` needs to be specified as one of ["2022preEE", "2022postEE", "23preBPix", "23postBPix"] for Run-3 or ["2016preVFP", "2016postVFP", "2017", "2018"] for Run-2.
By now, the Run-2 and Run-3 up to 2023D files are available from LUM POG in the correctionlib format...
The pileup histos for Run-3 were produced by Junquan, the JSONs for Run-2 and Run-3 first need to be pulled with `scripts/pull_files.py`!

Florian Alexander Mausolf
committed
"""

Tiziano Bevilacqua
committed
path_to_json = os.path.join(os.path.dirname(__file__), "../systematics/JSONs/pileup/pileup_{}.json.gz".format(year))
if "16" in year:
name = "Collisions16_UltraLegacy_goldenJSON"
elif "17" in year:
name = "Collisions17_UltraLegacy_goldenJSON"
elif "18" in year:
name = "Collisions18_UltraLegacy_goldenJSON"
elif "22preEE" in year:
name = "Collisions2022_355100_357900_eraBCD_GoldenJson"
elif "22postEE" in year:
name = "Collisions2022_359022_362760_eraEFG_GoldenJson"
elif "23preBPix" in year:
name = "Collisions2023_366403_369802_eraBC_GoldenJson"
elif "23postBPix" in year:
name = "Collisions2023_369803_370790_eraD_GoldenJson"
evaluator = correctionlib.CorrectionSet.from_file(path_to_json)[name]
if is_correction:
sf = evaluator.evaluate(events.Pileup.nTrueInt, "nominal")
sfup, sfdown = None, None

Florian Alexander Mausolf
committed
else:

Tiziano Bevilacqua
committed
sf = np.ones(len(weights._weight))
sf_nom = evaluator.evaluate(events.Pileup.nTrueInt, "nominal")

Tiziano Bevilacqua
committed
sfup = evaluator.evaluate(events.Pileup.nTrueInt, "up") / sf_nom
sfdown = evaluator.evaluate(events.Pileup.nTrueInt, "down") / sf_nom
weights.add(name="Pileup", weight=sf, weightUp=sfup, weightDown=sfdown)

Florian Alexander Mausolf
committed
return weights
def LooseMvaSF(photons, weights, year="2017", is_correction=True, **kwargs):
"""
LooseMvaSF: correction to the event weight on a per photon level, impacting one of the high importance input variable of the DiphotonBDT, binned in eta and r9.
for original implementation look at: https://github.com/cms-analysis/flashgg/blob/2677dfea2f0f40980993cade55144636656a8a4f/Systematics/python/flashggDiPhotonSystematics2017_Legacy_cfi.py
And for presentation on the study: https://indico.cern.ch/event/963617/contributions/4103623/attachments/2141570/3608645/Zee_Validation_UL2017_Update_09112020_Prasant.pdf

Florian Alexander Mausolf
committed
2022: up to this point, it applies the 2017 SF with the new formula for combining the SF for the diphoton candidate.
"""
# era/year defined as parameter of the function, only 2017 is implemented up to now
avail_years = ["2016", "2016preVFP", "2016postVFP", "2017", "2018", "2022preEE", "2022postEE"]
print(f"\n WARNING: only LooseMvaSF corrections for the year strings {avail_years} are already implemented! \n Exiting. \n")
elif "2016" in year:
year = "2016"

Florian Alexander Mausolf
committed
# make this read the 2022 files when available!
# 2017 file should be renamed with the year in its name...
json_file = os.path.join(os.path.dirname(__file__), f"JSONs/LooseMvaSF/{year}/LooseMvaSF_{year}.json")

Florian Alexander Mausolf
committed
evaluator = correctionlib.CorrectionSet.from_file(json_file)["LooseMvaSF"]

Florian Alexander Mausolf
committed
if is_correction:
# only calculate correction to nominal weight
sf_lead = evaluator.evaluate(
"nominal", photons["pho_lead"].ScEta, photons["pho_lead"].r9
)
sf_sublead = evaluator.evaluate(
"nominal", photons["pho_sublead"].ScEta, photons["pho_sublead"].r9
)
sf = sf_lead * sf_sublead

Florian Alexander Mausolf
committed
sfup, sfdown = None, None

Florian Alexander Mausolf
committed
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
else:
# only calculate systs
sf = np.ones(len(weights._weight))
sf_lead = evaluator.evaluate(
"nominal", photons["pho_lead"].ScEta, photons["pho_lead"].r9
)
sf_sublead = evaluator.evaluate(
"nominal", photons["pho_sublead"].ScEta, photons["pho_sublead"].r9
)
_sf = sf_lead * sf_sublead
sfup_lead = evaluator.evaluate(
"up", photons["pho_lead"].ScEta, photons["pho_lead"].r9
)
sfup_sublead = evaluator.evaluate(
"up", photons["pho_sublead"].ScEta, photons["pho_sublead"].r9
)
sfup = sfup_lead * sfup_sublead / _sf
sfdown_lead = evaluator.evaluate(
"down", photons["pho_lead"].ScEta, photons["pho_lead"].r9
)
sfdown_sublead = evaluator.evaluate(
"down", photons["pho_sublead"].ScEta, photons["pho_sublead"].r9
)
sfdown = sfdown_lead * sfdown_sublead / _sf
elif "2022" in year:

Florian Alexander Mausolf
committed
if is_correction:
# only calculate correction to nominal weight
# ToDo: include pT!!!
sf_lead_p_lead = evaluator.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9 # photons["pho_lead"].pt
)
sf_lead_p_sublead = evaluator.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9 # photons["pho_sublead"].pt
)
sf_sublead_p_lead = evaluator.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9 # photons["pho_lead"].pt
)
sf_sublead_p_sublead = evaluator.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9 # photons["pho_sublead"].pt
)
sf = sf_lead_p_lead * sf_sublead_p_sublead + sf_lead_p_sublead * sf_sublead_p_lead - sf_lead_p_lead * sf_lead_p_sublead

Florian Alexander Mausolf
committed
sfup, sfdown = None, None

Florian Alexander Mausolf
committed
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
else:
# only calculate systs
sf = np.ones(len(weights._weight))
# get nominal SF to divide it out
sf_lead_p_lead = evaluator.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9 # photons["pho_lead"].pt
)
sf_lead_p_sublead = evaluator.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9 # photons["pho_sublead"].pt
)
sf_sublead_p_lead = evaluator.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9 # photons["pho_lead"].pt
)
sf_sublead_p_sublead = evaluator.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9 # photons["pho_sublead"].pt
)
_sf = sf_lead_p_lead * sf_sublead_p_sublead + sf_lead_p_sublead * sf_sublead_p_lead - sf_lead_p_lead * sf_lead_p_sublead
# up SF
sfup_lead_p_lead = evaluator.evaluate(
"up", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9 # photons["pho_lead"].pt
)
sfup_lead_p_sublead = evaluator.evaluate(
"up", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9 # photons["pho_sublead"].pt
)
sfup_sublead_p_lead = evaluator.evaluate(
"up", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9 # photons["pho_lead"].pt
)
sfup_sublead_p_sublead = evaluator.evaluate(
"up", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9 # photons["pho_sublead"].pt
)
sfup = (sfup_lead_p_lead * sfup_sublead_p_sublead + sfup_lead_p_sublead * sfup_sublead_p_lead - sfup_lead_p_lead * sfup_lead_p_sublead) / _sf
# down SF
sfdown_lead_p_lead = evaluator.evaluate(
"down", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9 # photons["pho_lead"].pt
)
sfdown_lead_p_sublead = evaluator.evaluate(
"down", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9 # photons["pho_sublead"].pt
)
sfdown_sublead_p_lead = evaluator.evaluate(
"down", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9 # photons["pho_lead"].pt
)
sfdown_sublead_p_sublead = evaluator.evaluate(
"down", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9 # photons["pho_sublead"].pt
)
sfdown = (sfdown_lead_p_lead * sfdown_sublead_p_sublead + sfdown_lead_p_sublead * sfdown_sublead_p_lead - sfdown_lead_p_lead * sfdown_lead_p_sublead) / _sf
weights.add(name="LooseMvaSF", weight=sf, weightUp=sfup, weightDown=sfdown)
return weights
def ElectronVetoSF(photons, weights, year="2017", is_correction=True, **kwargs):
"""
ElectronVetoSF: correction to the event weight on a per photon level, Conversion safe veto efficiency with event counting method: To check if the FSR photons are passing the e-veto or not.
binned in abs(SCeta) and r9.
for original implementation look at: https://github.com/cms-analysis/flashgg/blob/2677dfea2f0f40980993cade55144636656a8a4f/Systematics/python/flashggDiPhotonSystematics2017_Legacy_cfi.py
And for presentation on the study: https://indico.cern.ch/event/961164/contributions/4089584/attachments/2135019/3596299/Zmmg_UL2017%20With%20CorrMC_Hgg%20(02.11.2020).pdf
"""
# era/year defined as parameter of the function
avail_years = ["2016", "2016preVFP", "2016postVFP", "2017", "2018", "2022preEE", "2022postEE"]
print(f"\n WARNING: only eVetoSF corrections for the year strings {avail_years} are already implemented! \n Exiting. \n")
elif "2016" in year:
year = "2016"

Florian Alexander Mausolf
committed
# 2017 file should be renamed with the year in its name...
json_file = os.path.join(os.path.dirname(__file__), f"JSONs/ElectronVetoSF/{year}/eVetoSF_{year}.json")

Florian Alexander Mausolf
committed
evaluator = correctionlib.CorrectionSet.from_file(json_file)["ElectronVetoSF"]
if is_correction:
# only calculate correction to nominal weight
sf_lead = evaluator.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9
)
sf_sublead = evaluator.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9
)
sf = sf_lead * sf_sublead

Florian Alexander Mausolf
committed
sfup, sfdown = None, None

Florian Alexander Mausolf
committed
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
else:
# only calculate systs
sf = np.ones(len(weights._weight))
sf_lead = evaluator.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9
)
sf_sublead = evaluator.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9
)
_sf = sf_lead * sf_sublead
sfup_lead = evaluator.evaluate(
"up", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9
)
sfup_sublead = evaluator.evaluate(
"up", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9
)
sfup = sfup_lead * sfup_sublead / _sf
sfdown_lead = evaluator.evaluate(
"down", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9
)
sfdown_sublead = evaluator.evaluate(
"down", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9
)
sfdown = sfdown_lead * sfdown_sublead / _sf
elif "2022" in year:
# presentation of SF: https://indico.cern.ch/event/1360961/#173-run-3-electron-veto-sfs
if year == "2022preEE":
json_file = os.path.join(os.path.dirname(__file__), "JSONs/ElectronVetoSF/2022/preEE_CSEV_SFcorrections.json")

Florian Alexander Mausolf
committed
if year == "2022postEE":
json_file = os.path.join(os.path.dirname(__file__), "JSONs/ElectronVetoSF/2022/postEE_CSEV_SFcorrections.json")

Florian Alexander Mausolf
committed
evaluator = correctionlib.CorrectionSet.from_file(json_file)["CSEV_SFs"]

Florian Alexander Mausolf
committed
if is_correction:
# only calculate correction to nominal weight
sf_lead = evaluator.evaluate(
abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, "nominal"
)
sf_sublead = evaluator.evaluate(
abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, "nominal"
)
sf = sf_lead * sf_sublead

Florian Alexander Mausolf
committed
sfup, sfdown = None, None

Florian Alexander Mausolf
committed
else:
# only calculate systs
sf = np.ones(len(weights._weight))
sf_lead = evaluator.evaluate(
abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, "nominal"
)
sf_sublead = evaluator.evaluate(
abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, "nominal"
)
_sf = sf_lead * sf_sublead
unc_lead = evaluator.evaluate(
abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, "uncertainty"
)
unc_sublead = evaluator.evaluate(
abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, "uncertainty"
)
sfup = (sf_lead + unc_lead) * (sf_sublead + unc_sublead) / _sf
sfdown = (sf_lead - unc_lead) * (sf_sublead - unc_sublead) / _sf
weights.add(name="ElectronVetoSF", weight=sf, weightUp=sfup, weightDown=sfdown)
return weights
def PreselSF(photons, weights, year="2017", is_correction=True, **kwargs):
"""
Preselection SF: correction to the event weight on a per photon level for UL2017. Dt:17/11/2020
Binned in abs(SCeta) and r9.
For original implementation look at: https://github.com/cms-analysis/flashgg/blob/2677dfea2f0f40980993cade55144636656a8a4f/Systematics/python/flashggDiPhotonSystematics2017_Legacy_cfi.py
Link to the Presentation: https://indico.cern.ch/event/963617/contributions/4103623/attachments/2141570/3608645/Zee_Validation_UL2017_Update_09112020_Prasant.pdf
"""

Jan Lukas Spah
committed
# era/year defined as parameter of the function
avail_years = ["2016", "2016preVFP", "2016postVFP", "2017", "2018", "2022preEE", "2022postEE"]
print(f"\n WARNING: only PreselSF corrections for the year strings {avail_years} are already implemented! \n Exiting. \n")
elif "2016" in year:
year = "2016"
if year in ["2016", "2017", "2018"]:
json_file = os.path.join(os.path.dirname(__file__), f"JSONs/Preselection/{year}/PreselSF_{year}.json")

Jan Lukas Spah
committed
elif year == "2022preEE":
json_file = os.path.join(os.path.dirname(__file__), "JSONs/Preselection/2022/Preselection_2022PreEE.json")
elif year == "2022postEE":
json_file = os.path.join(os.path.dirname(__file__), "JSONs/Preselection/2022/Preselection_2022PostEE.json")

Tiziano Bevilacqua
committed

Jan Lukas Spah
committed
evaluator = correctionlib.CorrectionSet.from_file(json_file)["PreselSF"]
elif "2022" in year:
evaluator = correctionlib.CorrectionSet.from_file(json_file)["Preselection_SF"]

Florian Alexander Mausolf
committed
if is_correction:
# only calculate correction to nominal weight
sf_lead = evaluator.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9
)
sf_sublead = evaluator.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9
)
sf = sf_lead * sf_sublead

Florian Alexander Mausolf
committed
sfup, sfdown = None, None

Florian Alexander Mausolf
committed
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
else:
# only calculate systs
sf = np.ones(len(weights._weight))
sf_lead = evaluator.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9
)
sf_sublead = evaluator.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9
)
_sf = sf_lead * sf_sublead
sfup_lead = evaluator.evaluate(
"up", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9
)
sfup_sublead = evaluator.evaluate(
"up", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9
)
sfup = sfup_lead * sfup_sublead / _sf
sfdown_lead = evaluator.evaluate(
"down", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9
)
sfdown_sublead = evaluator.evaluate(
"down", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9
)
sfdown = sfdown_lead * sfdown_sublead / _sf

Jan Lukas Spah
committed
# In principle, we should use the fully correct formula https://indico.cern.ch/event/1360948/contributions/5783762/attachments/2788516/4870824/24_02_02_HIG-23-014_PreAppPres.pdf#page=7
# However, if the SF is pt-binned, the approximation of the multiplication of the two SFs is fully exact

Florian Alexander Mausolf
committed
elif "2022" in year:
if is_correction:
# only calculate correction to nominal weight

Jan Lukas Spah
committed
sf_lead = evaluator.evaluate(
abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt, "nominal"

Florian Alexander Mausolf
committed
)

Jan Lukas Spah
committed
sf_sublead = evaluator.evaluate(
abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt, "nominal"

Florian Alexander Mausolf
committed
)

Jan Lukas Spah
committed
sf = sf_lead * sf_sublead

Florian Alexander Mausolf
committed
sfup, sfdown = None, None

Florian Alexander Mausolf
committed
else:
# only calculate systs

Jan Lukas Spah
committed
# Slightly different calculation compared to 2017
# In the 2022 JSONs, the delta is saved as the uncertainty, not the up/down variations of (SF+-delta) themselves
# Note that the uncertainty is assumed to be symmetric

Florian Alexander Mausolf
committed

Jan Lukas Spah
committed
sf = np.ones(len(weights._weight))
sf_lead = evaluator.evaluate(
abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt, "nominal"

Florian Alexander Mausolf
committed
)

Jan Lukas Spah
committed
sf_sublead = evaluator.evaluate(
abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt, "nominal"

Florian Alexander Mausolf
committed
)

Jan Lukas Spah
committed
_sf = sf_lead * sf_sublead

Florian Alexander Mausolf
committed

Jan Lukas Spah
committed
sf_unc_lead = evaluator.evaluate(
abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt, "uncertainty"

Florian Alexander Mausolf
committed
)

Jan Lukas Spah
committed
sf_unc_sublead = evaluator.evaluate(
abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt, "uncertainty"

Florian Alexander Mausolf
committed
)

Jan Lukas Spah
committed

Tiziano Bevilacqua
committed
sfup = (sf_lead + sf_unc_lead) * (sf_sublead + sf_unc_sublead) / _sf

Jan Lukas Spah
committed

Tiziano Bevilacqua
committed
sfdown = (sf_lead - sf_unc_lead) * (sf_sublead - sf_unc_sublead) / _sf
weights.add(name="PreselSF", weight=sf, weightUp=sfup, weightDown=sfdown)
return weights
def TriggerSF(photons, weights, year="2017", is_correction=True, **kwargs):
"""
Trigger SF: for full 2017 legacy B-F dataset. Trigger scale factors for use without HLT applied in MC
Binned in abs(SCeta), r9 and pt.
For original implementation look at: https://github.com/cms-analysis/flashgg/blob/2677dfea2f0f40980993cade55144636656a8a4f/Systematics/python/flashggDiPhotonSystematics2017_Legacy_cfi.py
"""
# era/year defined as parameter of the function
avail_years = ["2016", "2016preVFP", "2016postVFP", "2017", "2018", "2022preEE", "2022postEE"]
print(f"\n WARNING: only TriggerSF corrections for the year strings {avail_years} are already implemented! \n Exiting. \n")
elif "2016" in year:
year = "2016"
json_file_lead = os.path.join(os.path.dirname(__file__), f"JSONs/TriggerSF/{year}/TriggerSF_lead_{year}.json")
json_file_sublead = os.path.join(os.path.dirname(__file__), f"JSONs/TriggerSF/{year}/TriggerSF_sublead_{year}.json")
evaluator_lead = correctionlib.CorrectionSet.from_file(json_file_lead)["TriggerSF"]
evaluator_sublead = correctionlib.CorrectionSet.from_file(json_file_sublead)["TriggerSF"]

Florian Alexander Mausolf
committed
if is_correction:
# only calculate correction to nominal weight
sf_lead = evaluator_lead.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt
)
sf_sublead = evaluator_sublead.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt
)
sf = sf_lead * sf_sublead

Florian Alexander Mausolf
committed
sfup, sfdown = None, None

Florian Alexander Mausolf
committed
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
else:
# only calculate systs
sf = np.ones(len(weights._weight))
sf_lead = evaluator_lead.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt
)
sf_sublead = evaluator_sublead.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt
)
_sf = sf_lead * sf_sublead
sfup_lead = evaluator_lead.evaluate(
"up", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt
)
sfup_sublead = evaluator_sublead.evaluate(
"up", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt
)
sfup = sfup_lead * sfup_sublead / _sf
sfdown_lead = evaluator_lead.evaluate(
"down", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt
)
sfdown_sublead = evaluator_sublead.evaluate(
"down", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt
)
sfdown = sfdown_lead * sfdown_sublead / _sf
elif "2022" in year:
sf_lead_p_lead = evaluator_lead.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt
)
sf_lead_p_sublead = evaluator_lead.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt
)
sf_sublead_p_lead = evaluator_sublead.evaluate(
"nominal", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt
)
sf_sublead_p_sublead = evaluator_sublead.evaluate(
"nominal", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt
)

Florian Alexander Mausolf
committed
if is_correction:
# only calculate correction to nominal weight
sf = sf_lead_p_lead * sf_sublead_p_sublead + sf_lead_p_sublead * sf_sublead_p_lead - sf_lead_p_lead * sf_lead_p_sublead

Florian Alexander Mausolf
committed
sfup, sfdown = None, None
else:
# only calculate systs
sf = np.ones(len(weights._weight))
# get nominal SF to divide it out
_sf = sf_lead_p_lead * sf_sublead_p_sublead + sf_lead_p_sublead * sf_sublead_p_lead - sf_lead_p_lead * sf_lead_p_sublead
# up SF
sfup_lead_p_lead = evaluator_lead.evaluate(
"up", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt
)
sfup_lead_p_sublead = evaluator_lead.evaluate(
"up", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt

Florian Alexander Mausolf
committed
)
sfup_sublead_p_lead = evaluator_sublead.evaluate(
"up", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt

Florian Alexander Mausolf
committed
)
sfup_sublead_p_sublead = evaluator_sublead.evaluate(
"up", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt
)
sfup = (sfup_lead_p_lead * sfup_sublead_p_sublead + sfup_lead_p_sublead * sfup_sublead_p_lead - sfup_lead_p_lead * sfup_lead_p_sublead) / _sf
# down SF
sfdown_lead_p_lead = evaluator_lead.evaluate(
"down", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt
)
sfdown_lead_p_sublead = evaluator_lead.evaluate(
"down", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt

Florian Alexander Mausolf
committed
)
sfdown_sublead_p_lead = evaluator_sublead.evaluate(
"down", abs(photons["pho_lead"].ScEta), photons["pho_lead"].r9, photons["pho_lead"].pt

Florian Alexander Mausolf
committed
)
sfdown_sublead_p_sublead = evaluator_sublead.evaluate(
"down", abs(photons["pho_sublead"].ScEta), photons["pho_sublead"].r9, photons["pho_sublead"].pt
)
sfdown = (sfdown_lead_p_lead * sfdown_sublead_p_sublead + sfdown_lead_p_sublead * sfdown_sublead_p_lead - sfdown_lead_p_lead * sfdown_lead_p_sublead) / _sf
weights.add(name="TriggerSF", weight=sf, weightUp=sfup, weightDown=sfdown)
return weights
def NNLOPS(
events, dataset_name, weights, is_correction=True, generator="mcatnlo", **kwargs
):
"""
--- NNLOPS reweighting for ggH events to be applied to NLO Madgraph (and Powheg).
Swap generator argument to 'powheg' if to be applied to powheg events
Reweight event based on truth Higgs pt and number of jets, extracted from HTXS object
Constructs njet-dependent linear splines based on input data, functions of Higgs pt
Reweighting is applied always if correction is specified in runner JSON.
Warning is thrown if ggh or glugluh is not in the name.
"""
json_file = os.path.join(os.path.dirname(__file__), "JSONs/NNLOPS_reweight.json")
if is_correction:
if 'ggh' not in dataset_name.lower() and 'glugluh' not in dataset_name.lower():
logger.info(f"\n WARNING: You specified NNLOPS reweighting for dataset with {dataset_name} but this does not appear like a ggF sample. Consider checking your runner JSON Proceed with caution.")
# Extract NNLOPS weights from json file
with open(json_file, "r") as jf:
nnlops_reweight = json.load(jf)
# Load reweight factors for specific generator
nnlops_reweight = nnlops_reweight[generator]
# Build linear splines for different njet bins
spline_0jet = interp1d(
nnlops_reweight["0jet"]["pt"], nnlops_reweight["0jet"]["weight"]
)
spline_1jet = interp1d(
nnlops_reweight["1jet"]["pt"], nnlops_reweight["1jet"]["weight"]
)
spline_2jet = interp1d(
nnlops_reweight["2jet"]["pt"], nnlops_reweight["2jet"]["weight"]
)
spline_ge3jet = interp1d(
nnlops_reweight["3jet"]["pt"], nnlops_reweight["3jet"]["weight"]
)
# Load truth Higgs pt and njets (pt>30) from events
higgs_pt = events.HTXS.Higgs_pt
njets30 = events.HTXS.njets30
# Extract scale factors from splines and mask for different jet bins
# Define maximum pt values as interpolated splines only go up so far
sf = (
(njets30 == 0) * spline_0jet(np.minimum(np.array(higgs_pt), 125.0))
+ (njets30 == 1) * spline_1jet(np.minimum(np.array(higgs_pt), 625.0))
+ (njets30 == 2) * spline_2jet(np.minimum(np.array(higgs_pt), 800.0))
+ (njets30 >= 3) * spline_ge3jet(np.minimum(np.array(higgs_pt), 925.0))
)
raise RuntimeError(
"NNLOPS reweighting is only a flat correction, not a systematic"
)
weights.add("NNLOPS", sf, None, None)
return weights
def AlphaS(photons, events, weights, dataset_name, **kwargs):
"""
AlphaS weights variations are the last two of the PDF replicas, e.g.,
https://github.com/cms-sw/cmssw/blob/d37d2797dffc978a78da2fafec3ba480071a0e67/PhysicsTools/NanoAOD/python/genWeightsTable_cfi.py#L10
https://lhapdfsets.web.cern.ch/current/NNPDF31_nnlo_as_0118_mc_hessian_pdfas/NNPDF31_nnlo_as_0118_mc_hessian_pdfas.info
"""
systematic = "AlphaS Weight"
try:
weights.add(
name="AlphaS",
weight=np.ones(len(events)),
weightUp=events.LHEPdfWeight[:, -1],
weightDown=events.LHEPdfWeight[:, -2],
logger.debug(
f"No LHEPdf Weights in dataset {dataset_name}, skip systematic: {systematic}"
)
return weights
return weights
def PartonShower(photons, events, weights, dataset_name, **kwargs):
Parton Shower weights:
https://github.com/cms-sw/cmssw/blob/caeae4110ddbada1cfdac195404b3c618584e8fb/PhysicsTools/NanoAOD/plugins/GenWeightsTableProducer.cc#L533-L534
systematic = "PartonShower weight"
weightUp=events.PSWeight[:, 0],
weightDown=events.PSWeight[:, 2],
weightUp=events.PSWeight[:, 1],
weightDown=events.PSWeight[:, 3],
logger.debug(
f"No PS Weights in dataset {dataset_name}, skip systematic: {systematic}"
)
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
def bTagShapeSF(events, weights, is_correction=True, year="2017", **kwargs):
avail_years = ["2016preVFP", "2016postVFP", "2017", "2018", "2022preEE", "2022postEE", "2023preBPix", "2023postBPix"]
if year not in avail_years:
print(f"\n WARNING: only scale corrections for the year strings {avail_years} are already implemented! \n Exiting. \n")
exit()
btag_systematics = [
"lf",
"hf",
"cferr1",
"cferr2",
"lfstats1",
"lfstats2",
"hfstats1",
"hfstats2",
"jes",
]
inputFilePath = "JSONs/bTagSF/"
btag_correction_configs = {
"2016preVFP": {
"file": os.path.join(
inputFilePath , "2016preVFP_UL/btagging.json.gz"
),
"method": "deepJet_shape",
"systs": btag_systematics,
},
"2016postVFP": {
"file": os.path.join(
inputFilePath , "2016postVFP_UL/btagging.json.gz"
),
"method": "deepJet_shape",
"systs": btag_systematics,
},
"2017": {
"file": os.path.join(
inputFilePath , "2017_UL/btagging.json.gz"
),
"method": "deepJet_shape",
"systs": btag_systematics,
},
"2018": {
"file": os.path.join(
inputFilePath , "2018_UL/btagging.json.gz"
),
"method": "deepJet_shape",
"systs": btag_systematics,
},
"2022preEE":{
"file": os.path.join(
inputFilePath , "2022_Summer22/btagging.json.gz"
),
"method": "deepJet_shape",
"systs": btag_systematics,
},
"2022postEE":{
"file": os.path.join(
inputFilePath , "2022_Summer22EE/btagging.json.gz"
),
"method": "deepJet_shape",
"systs": btag_systematics,
},
"2023preBPix":{
"file": os.path.join(
inputFilePath , "2023_Summer23/btagging.json.gz"
),
"method": "deepJet_shape",
"systs": btag_systematics,
},
"2023postBPix":{
"file": os.path.join(
inputFilePath , "2023_Summer23BPix/btagging.json.gz"
),
"method": "deepJet_shape",
"systs": btag_systematics,
},
}
jsonpog_file = os.path.join(
os.path.dirname(__file__), btag_correction_configs[year]["file"]
)
evaluator = correctionlib.CorrectionSet.from_file(jsonpog_file)[
btag_correction_configs[year]["method"]
]
dummy_sf = ak.ones_like(events["event"])
relevant_jets = events["sel_jets"][
np.abs(events["sel_jets"].eta) < 2.5
]
# only calculate correction to nominal weight
# we will evaluate the scale factors relative to all jets to be multiplied
jet_pt = relevant_jets.pt
jet_eta = np.abs(relevant_jets.eta)
jet_hFlav = relevant_jets.hFlav
jet_btagDeepFlavB = relevant_jets.btagDeepFlavB
# Convert the jets in one dimension array and store the orignal structure of the ak array in counts
flat_jet_pt = ak.flatten(jet_pt)
flat_jet_eta = ak.flatten(jet_eta)
flat_jet_btagDeepFlavB = ak.flatten(jet_btagDeepFlavB)
flat_jet_hFlav = ak.flatten(jet_hFlav)
counts = ak.num(jet_hFlav)
logger.info("Warning: you have to normalise b-tag weights afterwards so that they do not change the yield!")

Mintu Kumar
committed
Weight_Name = ""

Mintu Kumar
committed
Weight_Name = "bTagSF"
_sf = []
# Evluate the scale factore per jet and unflatten the scale fatores in original structure
_sf = ak.unflatten(
evaluator.evaluate(
"central",
flat_jet_hFlav,
flat_jet_eta,
flat_jet_pt,
flat_jet_btagDeepFlavB,
),
counts
)
# Multiply the scale factore of all jets in a even
sf = ak.prod(_sf,axis=1)
sfs_up = [None for _ in btag_systematics]
sfs_down = [None for _ in btag_systematics]
else:

Mintu Kumar
committed
Weight_Name = "bTagSF_sys"
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
# only calculate correction to nominal weight
# replace by accessing partial weight!
_sf = []
# Evluate the scale factore per jet and unflatten the scale fatores in original structure
_sf_central = evaluator.evaluate(
"central",
flat_jet_hFlav,
flat_jet_eta,
flat_jet_pt,
flat_jet_btagDeepFlavB,
)
# Multiply the scale factore of all jets in a even
sf = ak.values_astype(dummy_sf, np.float)
sf_central = ak.prod(
ak.unflatten(_sf_central, counts),
axis=1
)
variations = {}
# Define a condiation based the jet flavour because the json file are defined for the 4(c),5(b),0(lf) flavour jets
flavour_condition = np.logical_or(jet_hFlav < 4,jet_hFlav > 5)
# Replace the flavour to 0 (lf) if the jet flavour is neither 4 nor 5
jet_hFlav_JSONrestricted = ak.where(flavour_condition, 0 ,jet_hFlav)
flat_jet_hFlav_JSONrestricted = ak.flatten(jet_hFlav_JSONrestricted)
# We need a dmmy sf array set to one to multiply for flavour dependent systentic variation
flat_dummy_sf = ak.ones_like(flat_jet_hFlav_JSONrestricted)
for syst_name in btag_correction_configs[year]["systs"]:
# we will append the scale factors relative to all jets to be multiplied
_sfup = []
_sfdown = []
variations[syst_name] = {}
if "cferr" in syst_name:
# we to remember which jet is correspond to c(hadron flv 4) jets
cjet_masks = flat_jet_hFlav_JSONrestricted == 4
flat_jet_hFlavC_JSONrestricted = ak.where(flat_jet_hFlav_JSONrestricted != 4, 4 ,flat_jet_hFlav_JSONrestricted)
_Csfup = evaluator.evaluate(
"up_" + syst_name,
flat_jet_hFlavC_JSONrestricted,
flat_jet_eta,
flat_jet_pt,
flat_jet_btagDeepFlavB,
)
_Csfdown = evaluator.evaluate(
"down_" + syst_name,
flat_jet_hFlavC_JSONrestricted,
flat_jet_eta,
flat_jet_pt,
flat_jet_btagDeepFlavB,
)
_Csfup = ak.where(
cjet_masks,
_Csfup,
flat_dummy_sf,
)
_Csfdown = ak.where(
cjet_masks,
_Csfdown,
flat_dummy_sf,
)
# Replace all the calculated sf with 1 when there is light jet or with flavour b otherwise keep the cerntral weight
_sfcentral_Masked_notC = ak.where(
~cjet_masks,
_sf_central,
flat_dummy_sf,
)
_sfup = ak.unflatten(np.multiply(_sfcentral_Masked_notC,_Csfup),counts)
_sfdown = ak.unflatten(np.multiply(_sfcentral_Masked_notC,_Csfdown),counts)
else:
# We to remember which jet is correspond to c(hadron flv 4) jets
cjet_masks = flat_jet_hFlav_JSONrestricted == 4
flat_jet_hFlavNonC_JSONrestricted = ak.where(cjet_masks, 0 ,flat_jet_hFlav_JSONrestricted)
_NonCsfup = evaluator.evaluate(
"up_" + syst_name,
flat_jet_hFlavNonC_JSONrestricted,
flat_jet_eta,
flat_jet_pt,
flat_jet_btagDeepFlavB,
)
_NonCsfdown = evaluator.evaluate(
"down_" + syst_name,
flat_jet_hFlavNonC_JSONrestricted,
flat_jet_eta,
flat_jet_pt,
flat_jet_btagDeepFlavB,
)
_NonCsfup = ak.where(
~cjet_masks,
_NonCsfup,
flat_dummy_sf,
)
_NonCsfdown = ak.where(
~cjet_masks,
_NonCsfdown,
flat_dummy_sf,
)
# Replace all the calculated sf with 1 when there is c jet otherwise keep the cerntral weight
_sfcentral_Masked_C = ak.where(
cjet_masks,
_sf_central,
flat_dummy_sf,
)
_sfup = ak.unflatten(np.multiply(_sfcentral_Masked_C,_NonCsfup),counts)
_sfdown = ak.unflatten(np.multiply(_sfcentral_Masked_C,_NonCsfdown),counts)
sf_up = ak.prod(_sfup,axis=1)
sf_down = ak.prod(_sfdown,axis=1)
variations[syst_name]["up"] = sf_up
variations[syst_name]["down"] = sf_down
# coffea weights.add_multivariation() wants a list of arrays for the multiple up and down variations
# we devide sf_central because cofea processor save the up and down vartion by multiplying the central weights
sfs_up = [variations[syst_name]["up"] / sf_central for syst_name in btag_systematics]
sfs_down = [variations[syst_name]["down"] / sf_central for syst_name in btag_systematics]
weights.add_multivariation(

Mintu Kumar
committed
name=Weight_Name,
weight=sf,
modifierNames=btag_systematics,
weightsUp=sfs_up,
weightsDown=sfs_down,
shift=False,
)
return weights
def cTagSF(events, weights, is_correction=True, year="2017", **kwargs):
"""
Add c-tagging reshaping SFs as from /https://github.com/higgs-charm/flashgg/blob/dev/cH_UL_Run2_withBDT/Systematics/scripts/applyCTagCorrections.py
BTV scale factor Wiki: https://btv-wiki.docs.cern.ch/ScaleFactors/
events must contain jet objects, moreover evaluation of SFs works by calculating the scale factors for all the jets in the event,
to do this in columnar style the only thing I could think of was to pad the jet collection to the max(n_jets) keep track of the "fake jets" introduced
by this procedure and fill these position wit 1s before actually setting the weights in the collection. If someone has better ideas I'm open for suggestions
"""
# era/year defined as parameter of the function, only Run2 is implemented up to now
avail_years = ["2016preVFP", "2016postVFP", "2017", "2018"]
if year not in avail_years:
print(f"\n WARNING: only scale corrections for the year strings {avail_years} are already implemented! \n Exiting. \n")
exit()
ctag_systematics = [
"Extrap",
"Interp",
"LHEScaleWeight_muF",
"LHEScaleWeight_muR",
"PSWeightFSR",
"PSWeightISR",
"PUWeight",
"Stat",
"XSec_BRUnc_DYJets_b",
"XSec_BRUnc_DYJets_c",
"XSec_BRUnc_WJets_c",
"jer",
"jesTotal",