ATLAS Offline Software
Loading...
Searching...
No Matches
ElectronAnalysisConfig.py
Go to the documentation of this file.
1# Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
2
3# AnaAlgorithm import(s):
4from AnalysisAlgorithmsConfig.ConfigBlock import ConfigBlock
5from AnalysisAlgorithmsConfig.ConfigSequence import groupBlocks
6from AthenaCommon.SystemOfUnits import GeV
7from AthenaConfiguration.Enums import LHCPeriod
8from AnalysisAlgorithmsConfig.ConfigAccumulator import (
9 DataType, ElectronEfficiencyCorrelationWarning,
10 Run4FallbackWarning, TestingOnlyWarning,
11 Run2OnlyFeatureWarning, TriggerSFWarning)
12import warnings
13from TrackingAnalysisAlgorithms.TrackingAnalysisConfig import InDetTrackCalibrationConfig
14from TrigGlobalEfficiencyCorrection.TriggerLeg_DictHelpers import TriggerDict, MapKeysDict
15from AthenaCommon.Logging import logging
16
17# E/gamma import(s).
18from xAODEgamma.xAODEgammaParameters import xAOD
19
21
22
24 """the ConfigBlock for the electron four-momentum correction"""
25
26 def __init__ (self) :
27 super (ElectronMomentumCalibrationConfig, self).__init__ ()
28 self.setBlockName('Electrons')
29 self.addOption ('inputContainer', '', type=str,
30 info="the name of the input electron container. If left empty, automatically defaults "
31 "to `AnalysisElectrons` for PHYSLITE or `Electrons` otherwise.")
32 self.addOption ('containerName', '', type=str,
33 noneAction='error',
34 info="the name of the output container after calibration.",
35 meta={'role':'container'})
36 self.addOption ('ESModel', '', type=str,
37 info="flag for Egamma calibration. If left empty, use the current recommendations.")
38 self.addOption ('decorrelationModel', '1NP_v1', type=str,
39 info="decorrelation model for the EGamma energy scale. Supported choices are: `1NP_v1`, `FULL_v1`.",
40 meta={'choices':(['1NP_v1','FULL_v1'],1)})
41 self.addOption ('postfix', '', type=str,
42 info="a postfix to apply to decorations and algorithm names. Typically "
43 "not needed here since the calibration is common to all electrons.")
44 self.addOption ('crackVeto', False, type=bool,
45 info=r"whether to perform LAr crack veto based on the cluster $\eta$, "
46 r"i.e. remove electrons within $1.37<\vert\eta\vert<1.52$.")
47 self.addOption ('isolationCorrection', True, type=bool,
48 info="whether or not to perform isolation corrections (leakage "
49 "corrections), i.e. set up an instance of "
50 "`CP::EgammaIsolationCorrectionAlg`.",
51 expertMode=True)
52 self.addOption ('recalibratePhyslite', True, type=bool,
53 info="whether to recalibrate PHYSLITE derivations, i.e. run the "
54 "`CP::EgammaCalibrationAndSmearingAlg` on the nominal. If `False` "
55 "the nominal stored in the PHYSLITE is used, and only the "
56 "systematic variations are recomputed.")
57 self.addOption ('minPt', 4.5*GeV, type=float,
58 info=r"the minimum $p_\mathrm{T}$ cut (in MeV) to apply to calibrated electrons.")
59 self.addOption ('maxEta', 2.47, type=float,
60 info=r"maximum electron $\vert\eta\vert$.")
61 self.addOption ('forceFullSimConfigForP4', False, type=bool,
62 info="whether to force the tool to use the configuration meant for "
63 "full simulation samples for 4-vector corrections. Only for testing purposes.")
64 self.addOption ('forceFullSimConfigForIso', False, type=bool,
65 info="whether to force the tool to use the configuration meant for "
66 "full simulation samples for isolation corrections. Only for testing purposes.")
67 self.addOption ('splitCalibrationAndSmearing', False, type=bool,
68 info="whether to split the `EgammaCalibrationAndSmearingTool` "
69 "into two steps. The first step applies a baseline calibration that "
70 "is not affected by systematics. The second step then applies the "
71 "systematics-dependent corrections. The net effect is that the "
72 "slower first step only has to be run once, while the second is run "
73 "once per systematic. On PHYSLITE with `recalibratePhyslite=False` "
74 "the first step is skipped, and for simulation the second step "
75 "starts from the `E_mva_only` stored in the PHYSLITE. ATLASG-2358.")
76 self.addOption ('decorateTruth', False, type=bool,
77 info="decorate truth particle information on the reconstructed one.")
78 self.addOption ('decorateCaloClusterEta', False, type=bool,
79 info=r"decorate the calo cluster $\eta$.")
80 self.addOption ('decorateEmva', False, type=bool,
81 info="decorate `E_mva_only` on the electrons (needed for columnar tools/PHYSLITE).")
82 self.addOption ('decorateSamplingPattern', False, type=bool,
83 info="decorate `samplingPattern` on the clusters (meant for PHYSLITE).")
84 self.addOption ('addGlobalFELinksDep', False, type=bool,
85 info="whether to add dependencies for the global FE links (needed for PHYSLITE production)",
86 expertMode=True)
87
88 def instanceName (self) :
89 """Return the instance name for this block"""
90 return self.containerName + self.postfix
91
92 def makeCalibrationAndSmearingAlg (self, config, name) :
93 """Create the calibration and smearing algorithm
94
95 Factoring this out into its own function, as we want to
96 instantiate it in multiple places"""
97
98 # Set up the calibration and smearing algorithm:
99 alg = config.createAlgorithm( 'CP::EgammaCalibrationAndSmearingAlg', name )
100 config.addPrivateTool( 'calibrationAndSmearingTool',
101 'CP::EgammaCalibrationAndSmearingTool' )
102 # Set default ESModel per period
103 if self.ESModel:
104 alg.calibrationAndSmearingTool.ESModel = self.ESModel
105 else:
106 if config.geometry() is LHCPeriod.Run2:
107 alg.calibrationAndSmearingTool.ESModel = 'es2023_R22_Run2_v1'
108 elif config.geometry() is LHCPeriod.Run3:
109 alg.calibrationAndSmearingTool.ESModel = 'es2024_Run3_v0'
110 elif config.geometry() is LHCPeriod.Run4:
111 warnings.warn_explicit(
112 "No ESModel set for Run4, using Run 3 model instead",
113 Run4FallbackWarning, filename='', lineno=0)
114 alg.calibrationAndSmearingTool.ESModel = 'es2024_Run3_v0'
115 else:
116 raise ValueError (f"Can't set up the ElectronCalibrationConfig with {config.geometry().value}, "
117 "there must be something wrong!")
118
119 alg.calibrationAndSmearingTool.decorrelationModel = self.decorrelationModel
120 alg.calibrationAndSmearingTool.useFastSim = (
122 else int( config.dataType() is DataType.FastSim ))
123 alg.calibrationAndSmearingTool.decorateEmva = self.decorateEmva
124 # only electrons are calibrated here, so skip loading the photon BDTs
125 alg.calibrationAndSmearingTool.DoPhotonMVACalibration = False
126 # the tool must not re-add the cells lost to the timing cut if the
127 # egamma AODFix already corrected the clusters upstream
128 if 'egClusterL2_3Fix' in config.flags.Input.AODFixesDone :
129 alg.calibrationAndSmearingTool.FixForMissingCells = False
130 alg.egammas = config.readName (self.containerName)
131 alg.egammasOut = config.copyName (self.containerName)
132 alg.preselection = config.getPreselection (self.containerName, '')
133
134 config.setContainerMeta (self.containerName, 'ESModel', alg.calibrationAndSmearingTool.ESModel, allowOverwrite=True)
135 config.setContainerMeta (self.containerName, 'decorrelationModel', alg.calibrationAndSmearingTool.decorrelationModel, allowOverwrite=True)
136
137 return alg
138
139
140 def makeAlgs (self, config) :
141
143 warnings.warn_explicit(
144 "You are running ElectronCalibrationConfig forcing full sim"
145 " config. This is only intended to be used for testing"
146 " purposes.",
147 TestingOnlyWarning, filename='', lineno=0)
148
149 inputContainer = "AnalysisElectrons" if config.isPhyslite() else "Electrons"
151 inputContainer = self.inputContainer
152 config.setSourceName (self.containerName, inputContainer)
153
154 # Decorate calo cluster eta if required
156 alg = config.createAlgorithm( 'CP::EgammaCaloClusterEtaAlg',
157 'ElectronEgammaCaloClusterEtaAlg',
158 reentrant=True )
159 alg.particles = config.readName(self.containerName)
160 config.addOutputVar (self.containerName, 'caloEta2', 'caloEta2', noSys=True, auxType='float')
161
163 config.createAlgorithm( 'CP::EgammaSamplingPatternDecoratorAlg', 'EgammaSamplingPatternDecoratorAlg' )
164
165 # Set up a shallow copy to decorate
166 if config.wantCopy (self.containerName) :
167 alg = config.createAlgorithm( 'CP::AsgShallowCopyAlg', 'ElectronShallowCopyAlg' )
168 alg.input = config.readName (self.containerName)
169 alg.output = config.copyName (self.containerName)
170 alg.outputType = 'xAOD::ElectronContainer'
171 decorationList = ['DFCommonElectronsLHLoose',
172 'neflowisol20',
173 'ptcone20_Nonprompt_All_MaxWeightTTVALooseCone_pt500',
174 'ptvarcone30_Nonprompt_All_MaxWeightTTVALooseCone_pt500',
175 'ptcone20_Nonprompt_All_MaxWeightTTVALooseCone_pt1000_CloseByCorr',
176 'ptvarcone30_Nonprompt_All_MaxWeightTTVALooseCone_pt1000_CloseByCorr',
177 'topoetcone20_CloseByCorr','DFCommonAddAmbiguity',
178 'PLIT_PLITel_pelxpromp', 'PLIT_PLITel_pnpxall']
180 decorationList += ['neutralGlobalFELinks', 'chargedGlobalFELinks']
181 if config.dataType() is not DataType.Data:
182 decorationList += ['TruthLink']
183 alg.declareDecorations = decorationList
184
185 # Set up the eta-cut on all electrons prior to everything else
186 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'ElectronEtaCutAlg' )
187 alg.selectionDecoration = 'selectEta' + self.postfix + ',as_bits'
188 config.addPrivateTool( 'selectionTool', 'CP::AsgPtEtaSelectionTool' )
189 alg.selectionTool.maxEta = self.maxEta
190 if self.crackVeto:
191 alg.selectionTool.etaGapLow = 1.37
192 alg.selectionTool.etaGapHigh = 1.52
193 alg.selectionTool.useClusterEta = True
194 alg.particles = config.readName (self.containerName)
195 alg.preselection = config.getPreselection (self.containerName, '')
196 config.addSelection (self.containerName, '', alg.selectionDecoration)
197
198 # Select electrons only with good object quality.
199 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'ElectronObjectQualityAlg' )
200 config.setExtraInputs ({('xAOD::EventInfo', 'EventInfo.RandomRunNumber')})
201 alg.selectionDecoration = 'goodOQ' + self.postfix + ',as_bits'
202 config.addPrivateTool( 'selectionTool', 'CP::EgammaIsGoodOQSelectionTool' )
203 alg.selectionTool.Mask = xAOD.EgammaParameters.BADCLUSELECTRON
204 alg.particles = config.readName (self.containerName)
205 alg.preselection = config.getPreselection (self.containerName, '')
206 config.addSelection (self.containerName, '', alg.selectionDecoration)
207
209 # Set up the calibration and smearing algorithm:
210 alg = self.makeCalibrationAndSmearingAlg (config, 'ElectronCalibrationAndSmearingAlg')
211 if config.isPhyslite() and not self.recalibratePhyslite :
212 alg.skipNominal = True
213 else:
214 # This splits the EgammaCalibrationAndSmearingTool into two
215 # steps. The first step applies a baseline calibration that
216 # is not affected by systematics. The second step then
217 # applies the systematics dependent corrections. The net
218 # effect is that the slower first step only has to be run
219 # once, while the second is run once per systematic.
220 #
221 # On PHYSLITE the output of the first step is already
222 # available: in data it is the final energy, which is what is
223 # stored, and in simulation it is the energy after the MVA
224 # calibration, which is stored as `E_mva_only`. So if the
225 # PHYSLITE is not to be recalibrated, the first step is
226 # skipped, and in simulation the second step starts from `E_mva_only`.
227 #
228 # See: ATLASG-2358
229 skipBaseStep = config.isPhyslite() and not self.recalibratePhyslite
230
231 if not skipBaseStep :
232 # Set up the calibration algorithm:
233 alg = self.makeCalibrationAndSmearingAlg (config, 'ElectronBaseCalibrationAlg')
234 # turn off systematics for the calibration step
235 alg.noToolSystematics = True
236 # turn off smearing for the calibration step
237 alg.calibrationAndSmearingTool.doSmearing = False
238 if config.dataType() is DataType.FastSim :
239 # don't correct FastSim samples twice
240 alg.calibrationAndSmearingTool.useFastSim = 0
241
242 # Set up the smearing algorithm:
243 alg = self.makeCalibrationAndSmearingAlg (config, 'ElectronCalibrationSystematicsAlg')
244 # turn off scale corrections for the smearing step
245 alg.calibrationAndSmearingTool.doScaleCorrection = False
246 alg.calibrationAndSmearingTool.useMVACalibration = False
247 alg.calibrationAndSmearingTool.decorateEmva = False
248 if skipBaseStep and config.dataType() is not DataType.Data :
249 # the first step is not run, start from its output
250 alg.calibrationAndSmearingTool.startFromEmva = True
251 if config.dataType() is DataType.Data :
252 # these have already been applied to data in the first step
253 alg.calibrationAndSmearingTool.useIntermoduleCorrection = False
254 alg.calibrationAndSmearingTool.usePhiUniformCorrection = False
255 alg.calibrationAndSmearingTool.useCaloDistPhiUnifCorrection = False
256 alg.calibrationAndSmearingTool.doADCLinearityCorrection = False
257 alg.calibrationAndSmearingTool.useGainCorrection = False
258
259 if self.minPt > 0 :
260 # Set up the the pt selection
261 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'ElectronPtCutAlg' )
262 alg.selectionDecoration = 'selectPt' + self.postfix + ',as_bits'
263 config.addPrivateTool( 'selectionTool', 'CP::AsgPtEtaSelectionTool' )
264 alg.selectionTool.minPt = self.minPt
265 alg.particles = config.readName (self.containerName)
266 alg.preselection = config.getPreselection (self.containerName, '')
267 config.addSelection (self.containerName, '', alg.selectionDecoration,
268 preselection=True)
269
270 # Set up the isolation correction algorithm:
272 alg = config.createAlgorithm( 'CP::EgammaIsolationCorrectionAlg',
273 'ElectronIsolationCorrectionAlg' )
274 config.addPrivateTool( 'isolationCorrectionTool',
275 'CP::IsolationCorrectionTool' )
276 alg.isolationCorrectionTool.IsMC = config.dataType() is not DataType.Data
277 alg.isolationCorrectionTool.AFII_corr = (
278 0 if self.forceFullSimConfigForIso
279 else config.dataType() is DataType.FastSim)
280 AODfixes = config.flags.Input.AODFixesDone
281 if "egammatopoIsoFix" in AODfixes:
282 alg.isolationCorrectionTool.FixTimingIssueInCore = False
283 else:
284 alg.isolationCorrectionTool.FixTimingIssueInCore = True
285 alg.isolationCorrectionTool.ToolVer = "REL22"
286 alg.isolationCorrectionTool.CorrFile = "IsolationCorrections/v6/isolation_ptcorrections_rel22_mc20.root"
287 alg.egammas = config.readName (self.containerName)
288 alg.egammasOut = config.copyName (self.containerName)
289 alg.egammasType = 'xAOD::ElectronContainer'
290 alg.preselection = config.getPreselection (self.containerName, '')
291 else:
292 warnings.warn_explicit(
293 "You are not applying the isolation corrections."
294 " This is only intended to be used for testing purposes.",
295 TestingOnlyWarning, filename='', lineno=0)
296
297 alg = config.createAlgorithm( 'CP::AsgEnergyDecoratorAlg', 'EnergyDecorator' )
298 alg.particles = config.readName(self.containerName)
299
300 config.addOutputVar (self.containerName, 'pt', 'pt', auxType='float')
301 config.addOutputVar (self.containerName, 'eta', 'eta', noSys=True, auxType='float')
302 config.addOutputVar (self.containerName, 'phi', 'phi', noSys=True, auxType='float')
303 config.addOutputVar (self.containerName, 'e_%SYS%', 'e', auxType='float')
304 config.addOutputVar (self.containerName, 'charge', 'charge', noSys=True, auxType='float')
305 config.addOutputVar (self.containerName, 'caloClusterEnergyReso_%SYS%', 'caloClusterEnergyReso', noSys=True, auxType='float')
306
307 # decorate truth information on the reconstructed object:
308 if self.decorateTruth and config.dataType() is not DataType.Data:
309 config.addOutputVar (self.containerName, "truthType", "truth_type", noSys=True, auxType='int')
310 config.addOutputVar (self.containerName, "truthOrigin", "truth_origin", noSys=True, auxType='int')
311
312 config.addOutputVar (self.containerName, "firstEgMotherPdgId", "truth_firstEgMotherPdgId", noSys=True, auxType='int')
313 config.addOutputVar (self.containerName, "firstEgMotherTruthOrigin", "truth_firstEgMotherTruthOrigin", noSys=True, auxType='int')
314 config.addOutputVar (self.containerName, "firstEgMotherTruthType", "truth_firstEgMotherTruthType", noSys=True, auxType='int')
315
316
317class ElectronIPCalibrationConfig (ConfigBlock) :
318 """the ConfigBlock for the electron impact parameter correction"""
319
320 def __init__ (self) :
321 super (ElectronIPCalibrationConfig, self).__init__ ()
322 self.setBlockName('ElectronIPCalibration')
323 self.addDependency('Electrons', required=True)
324 self.addDependency('ElectronWorkingPointSelection', required=False)
325 self.addOption ('containerName', '', type=str,
326 noneAction='error',
327 info="the name of the output container after calibration.",
328 meta={'role':'container'})
329 self.addOption ('postfix', '', type=str,
330 info="a postfix to apply to decorations and algorithm names. Typically "
331 "not needed here since the calibration is common to all electrons.")
332 self.addOption ('runTrackBiasing', False, type=bool,
333 info="This enables the `InDetTrackBiasingTool`, for "
334 "tracks associated to electrons")
335 self.addOption ('writeTrackD0Z0', False, type = bool,
336 info=r"save the $d_0$ significance and $z_0\sin\theta$ variables.")
337
338 def instanceName (self) :
339 """Return the instance name for this block"""
340 return self.containerName + self.postfix
341
342 def makeAlgs (self, config) :
343
344 # Additional decorations
346 alg = config.createAlgorithm( 'CP::AsgLeptonTrackDecorationAlg',
347 'LeptonTrackDecorator' )
348 if config.dataType() is not DataType.Data:
350 InDetTrackCalibrationConfig.makeTrackBiasingTool(config, alg)
351 InDetTrackCalibrationConfig.makeTrackSmearingTool(config, alg)
352 alg.particles = config.readName (self.containerName)
353
354 config.addOutputVar (self.containerName, 'd0_%SYS%', 'd0', auxType='float')
355 config.addOutputVar (self.containerName, 'd0sig_%SYS%', 'd0sig', auxType='float')
356 config.addOutputVar (self.containerName, 'z0_%SYS%', 'z0', auxType='float')
357 config.addOutputVar (self.containerName, 'z0sintheta_%SYS%', 'z0sintheta', auxType='float')
358 config.addOutputVar (self.containerName, 'z0sinthetasig_%SYS%', 'z0sinthetasig', auxType='float')
359
360
362 """the ConfigBlock for the electron working point selection"""
363
364 def __init__ (self) :
365 super (ElectronWorkingPointSelectionConfig, self).__init__ ()
366 self.setBlockName('ElectronWorkingPointSelection')
367 self.addOption ('containerName', '', type=str,
368 noneAction='error',
369 info="the name of the input container.",
370 meta={'role':'containerRef'})
371 self.addOption ('selectionName', '', type=str,
372 noneAction='error',
373 info="the name of the electron selection to define (e.g. `tight` or "
374 "`loose`).",
375 meta={'role':'selection'})
376 self.addOption ('postfix', None, type=str,
377 info="a postfix to apply to decorations and algorithm names. "
378 "Typically not needed here as `selectionName` is used internally.")
379 self.addOption ('trackSelection', True, type=bool,
380 info="whether or not to set up an instance of "
381 "`CP::AsgLeptonTrackSelectionAlg`, with the recommended $d_0$ and "
382 r"$z_0\sin\theta$ cuts.")
383 self.addOption ('maxD0Significance', 5, type=float,
384 info="maximum $d_0$ significance used for the track selection.")
385 self.addOption ('maxDeltaZ0SinTheta', 0.5, type=float,
386 info=r"maximum $z_0\sin\theta$ (in mm) used for the track selection.")
387 self.addOption ('identificationWP', None, type=str,
388 info="the ID WP to use. Supported ID WPs: `TightLH`, "
389 "`MediumLH`, `LooseBLayerLH`, `TightDNN`, `MediumDNN`, `LooseDNN`, "
390 "`TightNoCFDNN`, `MediumNoCFDNN`, `VeryLooseNoCF97DNN`, `NoID`.",
391 expertMode=["NoID"],
392 meta={'choices':(['MediumLH', 'LooseBLayerLH', 'TightDNN', 'MediumDNN', 'LooseDNN',
393 'TightNoCFDNN', 'MediumNoCFDNN', 'VeryLooseNoCF97DNN', 'NoID'],1)})
394 self.addOption ('isolationWP', None, type=str,
395 info="the isolation WP to use. Supported isolation WPs: "
396 "`HighPtCaloOnly`, `Loose_VarRad`, `Tight_VarRad`, `TightTrackOnly_"
397 "VarRad`, `TightTrackOnly_FixedRad`, `NonIso`.",
398 meta={'choices':(['HighPtCaloOnly', 'Loose_VarRad', 'Tight_VarRad', 'TightTrackOnly_VarRad',
399 'TightTrackOnly_FixedRad', 'NonIso'],1)})
400 self.addOption ('convSelection', None, type=str,
401 info="enter additional selection to use for conversions. To be used with "
402 "`TightLH` or will crash. Supported keywords:"
403 "`Veto`, `MatConv`, `GammaStar`.",
404 meta={'choices':(['Veto', 'MatConv', 'GammaStar'],1)})
405 self.addOption ('addSelectionToPreselection', True, type=bool,
406 info="whether to retain only electrons satisfying the working point "
407 "requirements.")
408 self.addOption ('closeByCorrection', False, type=bool,
409 info="whether to use close-by-corrected isolation working points.")
410 self.addOption ('recomputeID', False, type=bool,
411 info="whether to rerun the ID LH/DNN, or rely on derivation flags.")
412 self.addOption ('chargeIDSelectionRun2', False, type=bool,
413 info="whether to run the ECIDS tool. Only available for Run 2.")
414 self.addOption ('recomputeChargeID', False, type=bool,
415 info="whether to rerun the ECIDS, or rely on derivation flags.")
416 self.addOption ('doFSRSelection', False, type=bool,
417 info="whether to accept additional electrons close to muons for "
418 "the purpose of FSR corrections to these muons. Expert feature "
419 "requested by the H4l analysis running on PHYSLITE.",
420 expertMode=True)
421 self.addOption ('muonsForFSRSelection', None, type=str,
422 info="the name of the muon container to use for the FSR selection. "
423 "If not specified, AnalysisMuons is used.",
424 expertMode=True)
425 self.addOption ('mainElectronContainer', None, type=str,
426 info="the name of the main electron container to use for the SiHit selection. "
427 "If not specified, this defaults to AnalysisElectrons.",
428 expertMode=True)
429
430 def instanceName (self) :
431 """Return the instance name for this block"""
432 if self.postfix is not None :
433 return self.containerName + '_' + self.selectionName + self.postfix
434 return self.containerName + '_' + self.selectionName
435
436 def makeAlgs (self, config) :
437
438 selectionPostfix = self.selectionName
439 if selectionPostfix != '' and selectionPostfix[0] != '_' :
440 selectionPostfix = '_' + selectionPostfix
441
442 # The setup below is inappropriate for Run 1
443 if config.geometry() is LHCPeriod.Run1:
444 raise ValueError ("Can't set up the ElectronWorkingPointSelectionConfig with %s, there must be something wrong!" % config.geometry().value)
445
446 if self.identificationWP is None:
447 raise ValueError ("ElectronWorkingPointSelectionConfig: the identificationWP option must be set")
448 if self.identificationWP == 'NoID' and self.doFSRSelection:
449 raise ValueError ("ElectronWorkingPointSelectionConfig: doFSRSelection requires an ID working point, "
450 "it can't be used with identificationWP='NoID'")
451
452 postfix = self.postfix
453 if postfix is None :
454 postfix = self.selectionName
455 if postfix != '' and postfix[0] != '_' :
456 postfix = '_' + postfix
457
458 # Set up the track selection algorithm:
460 alg = config.createAlgorithm( 'CP::AsgLeptonTrackSelectionAlg',
461 'ElectronTrackSelectionAlg',
462 reentrant=True )
463 alg.selectionDecoration = 'trackSelection' + postfix + ',as_bits'
464 alg.maxD0Significance = self.maxD0Significance
465 alg.maxDeltaZ0SinTheta = self.maxDeltaZ0SinTheta
466 alg.particles = config.readName (self.containerName)
467 alg.preselection = config.getPreselection (self.containerName, '')
468 config.addSelection (self.containerName, self.selectionName, alg.selectionDecoration,
469 preselection=self.addSelectionToPreselection)
470
471 if 'LH' in self.identificationWP:
472 # Set up the likelihood ID selection algorithm
473 # It is safe to do this before calibration, as the cluster E is used
474 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'ElectronLikelihoodAlg' )
475 alg.selectionDecoration = 'selectLikelihood' + selectionPostfix + ',as_char'
476 if self.recomputeID:
477 # Rerun the likelihood ID
478 config.addPrivateTool( 'selectionTool', 'AsgElectronLikelihoodTool' )
479 alg.selectionTool.primaryVertexContainer = 'PrimaryVertices'
480 # Here we have to match the naming convention of EGSelectorConfigurationMapping.h
481 # which differ from the one used for scale factors
482 if config.geometry() >= LHCPeriod.Run3:
483 if 'HI' not in self.identificationWP:
484 alg.selectionTool.WorkingPoint = self.identificationWP.replace("BLayer","BL") + 'Electron'
485 else:
486 alg.selectionTool.WorkingPoint = self.identificationWP.replace('_HI', 'Electron_HI')
487 elif config.geometry() is LHCPeriod.Run2:
488 alg.selectionTool.WorkingPoint = self.identificationWP.replace("BLayer","BL") + 'Electron_Run2'
489 else:
490 # Select from Derivation Framework flags
491 config.addPrivateTool( 'selectionTool', 'CP::AsgFlagSelectionTool' )
492 dfFlag = "DFCommonElectronsLH" + self.identificationWP.split('LH')[0]
493 dfFlag = dfFlag.replace("BLayer","BL")
494 alg.selectionTool.selectionFlags = [dfFlag]
495 elif 'SiHit' in self.identificationWP:
496 # Only want SiHit electrons, so veto loose LH electrons
497 algVeto = config.createAlgorithm( 'CP::AsgSelectionAlg', 'ElectronLikelihoodAlgVeto')
498 algVeto.selectionDecoration = 'selectLikelihoodVeto' + postfix + ',as_char'
499 config.addPrivateTool( 'selectionTool', 'CP::AsgFlagSelectionTool' )
500 algVeto.selectionTool.selectionFlags = ["DFCommonElectronsLHLoose"]
501 algVeto.selectionTool.invertFlags = [True]
502 algVeto.particles = config.readName (self.containerName)
503 algVeto.preselection = config.getPreselection (self.containerName, self.selectionName)
504 # add the veto as a selection
505 config.addSelection (self.containerName, self.selectionName, algVeto.selectionDecoration,
506 preselection=self.addSelectionToPreselection)
507
508 # Select SiHit electrons using IsEM bits
509 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'ElectronLikelihoodAlg' )
510 alg.selectionDecoration = 'selectSiHit' + selectionPostfix + ',as_char'
511 # Select from Derivation Framework IsEM bits
512 config.addPrivateTool( 'selectionTool', 'CP::AsgMaskSelectionTool' )
513 dfVar = "DFCommonElectronsLHLooseBLIsEMValue"
514 alg.selectionTool.selectionVars = [dfVar]
515 mask = 0x6 # IsEM bits 1 and 2
516 alg.selectionTool.selectionMasks = [mask]
517 elif 'DNN' in self.identificationWP:
519 raise ValueError('DNN is not intended to be used with '
520 '`chargeIDSelectionRun2` option as there are '
521 'DNN WPs containing charge flip rejection.')
522 # Set up the DNN ID selection algorithm
523 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'ElectronDNNAlg' )
524 alg.selectionDecoration = 'selectDNN' + selectionPostfix + ',as_char'
525 if self.recomputeID:
526 # Rerun the DNN ID
527 config.addPrivateTool( 'selectionTool', 'AsgElectronSelectorTool' )
528 # Here we have to match the naming convention of ElectronPhotonSelectorTools/Root/EGSelectorConfigurationMapping.h
529 alg.selectionTool.WorkingPoint = self.identificationWP + 'Electron'
530 else:
531 # Select from Derivation Framework flags
532 config.addPrivateTool( 'selectionTool', 'CP::AsgFlagSelectionTool' )
533 dfFlag = "DFCommonElectronsDNN" + self.identificationWP.split('DNN')[0]
534 alg.selectionTool.selectionFlags = [dfFlag]
535 elif self.identificationWP == 'NoID':
536 alg = None
537 else:
538 raise ValueError (f"Electron ID working point '{self.identificationWP}' is not recognised!")
539
540 wpDecoration = None
541 if alg is not None:
542 wpDecoration = alg.selectionDecoration
543 alg.particles = config.readName (self.containerName)
544 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
545 # Don't register WP selection here if FSR enabled - FSR algorithm will create combined selection
546 if not self.doFSRSelection:
547 config.addSelection (self.containerName, self.selectionName, alg.selectionDecoration,
548 preselection=self.addSelectionToPreselection)
549
550 # maintain order of selections
551 if 'SiHit' in self.identificationWP:
552 # Set up the ElectronSiHitDecAlg algorithm to decorate SiHit electrons with a minimal amount of information:
553 algDec = config.createAlgorithm( 'CP::ElectronSiHitDecAlg', 'ElectronSiHitDecAlg' )
554 selDec = 'siHitEvtHasLeptonPair' + selectionPostfix + ',as_char'
555 algDec.selectionName = selDec.split(",")[0]
556 algDec.ElectronContainer = config.readName (self.containerName)
557 if self.muonsForFSRSelection is not None:
558 algDec.AnalMuonContKey = config.readName (self.muonsForFSRSelection)
559 if self.mainElectronContainer is not None:
560 algDec.AnalElectronContKey = config.readName (self.mainElectronContainer)
561 # Set flag to only collect SiHit electrons for events with an electron or muon pair to minimize size increase from SiHit electrons
562 algDec.RequireTwoLeptons = True
563 config.addSelection (self.containerName, self.selectionName, selDec,
564 preselection=self.addSelectionToPreselection)
565
566 # Additional selection for conversions and gamma*
567 if self.convSelection is not None:
568 # skip if not applied together with TightLH
569 if self.identificationWP != 'TightLH':
570 raise ValueError(f"convSelection can only be used with TightLH ID, "
571 f"whereas {self.identificationWP} has been selected. convSelection option will be ignored.")
572 # check if allowed value
573 allowedValues = ["Veto", "GammaStar", "MatConv"]
574 if self.convSelection not in allowedValues:
575 raise ValueError(f"convSelection has been set to {self.convSelection}, which is not a valid option. "
576 f"convSelection option must be one of {allowedValues}.")
577
578 # ambiguityType == 0
579 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'ElectronAmbiguityTypeAlg' )
580 alg.selectionDecoration = 'selectAmbiguityType' + selectionPostfix + ',as_char'
581 config.addPrivateTool( 'selectionTool', 'CP::AsgNumDecorationSelectionToolUInt8' )
582 alg.selectionTool.decorationName = "ambiguityType"
583 alg.selectionTool.doEqual = True
584 alg.selectionTool.equal = 0
585 alg.particles = config.readName (self.containerName)
586 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
587 config.addSelection (self.containerName, self.selectionName, alg.selectionDecoration,
588 preselection=self.addSelectionToPreselection)
589
590 # DFCommonAddAmbiguity selection
591 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'ElectronDFCommonAddAmbiguityAlg' )
592 alg.selectionDecoration = 'selectDFCommonAddAmbiguity' + selectionPostfix + ',as_char'
593 config.addPrivateTool( 'selectionTool', 'CP::AsgNumDecorationSelectionToolInt' )
594 alg.selectionTool.decorationName = "DFCommonAddAmbiguity"
595 if self.convSelection == "Veto":
596 alg.selectionTool.doMax = True
597 alg.selectionTool.max = 1
598 elif self.convSelection == "GammaStar":
599 alg.selectionTool.doEqual = True
600 alg.selectionTool.equal = 1
601 elif self.convSelection == "MatConv":
602 alg.selectionTool.doEqual = True
603 alg.selectionTool.equal = 2
604 alg.particles = config.readName (self.containerName)
605 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
606 config.addSelection (self.containerName, self.selectionName, alg.selectionDecoration,
607 preselection=self.addSelectionToPreselection)
608
609 # Set up the FSR selection
610 if self.doFSRSelection :
611 # wpSelection needs the type suffix so SysReadSelectionHandle knows the type
612 # selectionDecoration needs name only for SysWriteDecorHandle
613 wpDecorationName = wpDecoration.split(',')[0]
614 # Insert FSR before the postfix (e.g., selectSiHit_SiHits -> selectSiHitFSR_SiHits)
615 underscorePos = wpDecorationName.find('_')
616 if underscorePos < 0:
617 underscorePos = len(wpDecorationName)
618 outputDecorationName = wpDecorationName[:underscorePos] + 'FSR' + wpDecorationName[underscorePos:]
619 alg = config.createAlgorithm( 'CP::EgammaFSRForMuonsCollectorAlg', 'EgammaFSRForMuonsCollectorAlg' )
620 alg.wpSelection = wpDecoration # Input: read the WP selection (with type suffix)
621 alg.selectionDecoration = outputDecorationName # Output: combined WP||FSR (or WP&&!FSR for vetoFSR) (name only)
622 alg.ElectronOrPhotonContKey = config.readName (self.containerName)
623 if self.muonsForFSRSelection is not None:
624 alg.MuonContKey = config.readName (self.muonsForFSRSelection)
625 # For SiHit electrons, set flag to remove FSR electrons.
626 # For standard electrons, FSR electrons need to be added as they may be missed by the standard selection.
627 # For SiHit electrons FSR electrons are generally always selected, so they should be removed since they will be in the standard electron container.
628 if 'SiHit' in self.identificationWP:
629 alg.vetoFSR = True
630
631 # Register the FSR COMBINED selection
632 config.addSelection (self.containerName, self.selectionName,
633 alg.selectionDecoration + ',as_char',
634 preselection=self.addSelectionToPreselection)
635
636 # Set up the isolation selection algorithm:
637 if self.isolationWP != 'NonIso' :
638 alg = config.createAlgorithm( 'CP::EgammaIsolationSelectionAlg',
639 'ElectronIsolationSelectionAlg' )
640 alg.selectionDecoration = 'isolated' + selectionPostfix + ',as_char'
641 config.addPrivateTool( 'selectionTool', 'CP::IsolationSelectionTool' )
642 alg.selectionTool.ElectronWP = self.isolationWP
644 alg.selectionTool.IsoDecSuffix = "CloseByCorr"
645 alg.egammas = config.readName (self.containerName)
646 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
647 config.addSelection (self.containerName, self.selectionName, alg.selectionDecoration,
648 preselection=self.addSelectionToPreselection)
649
650 if self.chargeIDSelectionRun2 and config.geometry() >= LHCPeriod.Run3:
651 warnings.warn_explicit(
652 "ECIDS is only available for Run 2 and will not have any"
653 " effect in Run 3.",
654 Run2OnlyFeatureWarning, filename='', lineno=0)
655
656 # Select electrons only if they don't appear to have flipped their charge.
657 if self.chargeIDSelectionRun2 and config.geometry() < LHCPeriod.Run3:
658 alg = config.createAlgorithm( 'CP::AsgSelectionAlg',
659 'ElectronChargeIDSelectionAlg' )
660 alg.selectionDecoration = 'chargeID' + selectionPostfix + ',as_char'
662 # Rerun the ECIDS BDT
663 config.addPrivateTool( 'selectionTool',
664 'AsgElectronChargeIDSelectorTool' )
665 alg.selectionTool.TrainingFile = \
666 'ElectronPhotonSelectorTools/ChargeID/ECIDS_20180731rel21Summer2018.root'
667 alg.selectionTool.WorkingPoint = 'Loose'
668 alg.selectionTool.CutOnBDT = -0.337671 # Loose 97%
669 else:
670 # Select from Derivation Framework flags
671 config.addPrivateTool( 'selectionTool', 'CP::AsgFlagSelectionTool' )
672 alg.selectionTool.selectionFlags = ["DFCommonElectronsECIDS"]
673
674 alg.particles = config.readName (self.containerName)
675 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
676 config.addSelection (self.containerName, self.selectionName, alg.selectionDecoration,
677 preselection=self.addSelectionToPreselection)
678
679
681 """the ConfigBlock for the electron working point efficiency computation"""
682
683 def __init__(self) :
684 super (ElectronWorkingPointEfficiencyConfig, self).__init__ ()
685 self.setBlockName('ElectronWorkingPointEfficiency')
686 self.addDependency('ElectronWorkingPointSelection', required=True)
687 self.addDependency('EventSelection', required=False)
688 self.addDependency('EventSelectionMerger', required=False)
689 self.addOption ('containerName', '', type=str,
690 noneAction='error',
691 info="the name of the input container.",
692 meta={'role':'containerRef'})
693 self.addOption ('selectionName', '', type=str,
694 noneAction='error',
695 info="the name of the electron selection to define (e.g. `tight` or "
696 "`loose`).",
697 meta={'role':'selection'})
698 self.addOption ('postfix', None, type=str,
699 info="a postfix to apply to decorations and algorithm names. "
700 "Typically not needed here as `selectionName` is used internally.")
701 self.addOption ('identificationWP', None, type=str,
702 info="the ID WP to use. Supported ID WPs: `TightLH`, "
703 "`MediumLH`, `LooseBLayerLH`, `TightDNN`, `MediumDNN`, `LooseDNN`, "
704 "`TightNoCFDNN`, `MediumNoCFDNN`, `VeryLooseNoCF97DNN`, `NoID`.",
705 expertMode=["NoID"],
706 meta={'choices':(['MediumLH', 'LooseBLayerLH', 'TightDNN', 'MediumDNN', 'LooseDNN',
707 'TightNoCFDNN', 'MediumNoCFDNN', 'VeryLooseNoCF97DNN', 'NoID'],1)})
708 self.addOption ('isolationWP', None, type=str,
709 info="the isolation WP to use. Supported isolation WPs: "
710 "`HighPtCaloOnly`, `Loose_VarRad`, `Tight_VarRad`, `TightTrackOnly_"
711 "VarRad`, `TightTrackOnly_FixedRad`, `NonIso`.",
712 meta={'choices':(['HighPtCaloOnly', 'Loose_VarRad', 'Tight_VarRad', 'TightTrackOnly_VarRad',
713 'TightTrackOnly_FixedRad', 'NonIso'],1)})
714 self.addOption ('noEffSF', False, type=bool,
715 info="disables the calculation of efficiencies and scale factors. "
716 "Experimental! only useful to test a new WP for which scale "
717 "factors are not available.",
718 expertMode=True)
719 self.addOption ('chargeIDSelectionRun2', False, type=bool,
720 info="whether to run the ECIDS tool. Only available for Run 2.")
721 self.addOption ('saveDetailedSF', True, type=bool,
722 info="save all the independent detailed object scale factors.")
723 self.addOption ('saveCombinedSF', False, type=bool,
724 info="save the combined object scale factor.")
725 self.addOption ('forceFullSimConfig', False, type=bool,
726 info="whether to force the tool to use the configuration meant for "
727 "full simulation samples. Only for testing purposes.")
728 self.addOption ('correlationModelId', 'SIMPLIFIED', type=str,
729 info="the correlation model to use for ID scale factors. "
730 "Supported models: `SIMPLIFIED`, `FULL`, `TOTAL`, `TOYS`.",
731 meta={'choices':(['SIMPLIFIED','FULL','TOTAL','TOYS'],1)})
732 self.addOption ('correlationModelIso', 'SIMPLIFIED', type=str,
733 info="the correlation model to use for isolation scale factors, "
734 "Supported models: `SIMPLIFIED`, `FULL`, `TOTAL`, `TOYS`.",
735 meta={'choices':(['SIMPLIFIED','FULL','TOTAL','TOYS'],1)})
736 self.addOption ('correlationModelReco', 'SIMPLIFIED', type=str,
737 info="the correlation model to use for reconstruction scale factors. "
738 "Supported models: `SIMPLIFIED`, `FULL`, `TOTAL`, `TOYS`.",
739 meta={'choices':(['SIMPLIFIED','FULL','TOTAL','TOYS'],1)})
740 self.addOption('addChargeMisIDSF', False, type=bool,
741 info="adds scale factors for charge-misID.")
742
743 def instanceName (self) :
744 """Return the instance name for this block"""
745 if self.postfix is not None :
746 return self.containerName + '_' + self.selectionName + self.postfix
747 return self.containerName + '_' + self.selectionName
748
749 def makeAlgs (self, config) :
750
752 warnings.warn_explicit(
753 "You are running ElectronWorkingPointSelectionConfig forcing"
754 " full sim config. This is only intended to be used for"
755 " testing purposes.",
756 TestingOnlyWarning, filename='', lineno=0)
757
758 selectionPostfix = self.selectionName
759 if selectionPostfix != '' and selectionPostfix[0] != '_' :
760 selectionPostfix = '_' + selectionPostfix
761
762 # The setup below is inappropriate for Run 1
763 if config.geometry() is LHCPeriod.Run1:
764 raise ValueError ("Can't set up the ElectronWorkingPointSelectionConfig with %s, there must be something wrong!" % config.geometry().value)
765
766 if self.identificationWP is None:
767 raise ValueError ("ElectronWorkingPointEfficiencyConfig: the identificationWP option must be set")
768
769 postfix = self.postfix
770 if postfix is None :
771 postfix = self.selectionName
772 if postfix != '' and postfix[0] != '_' :
773 postfix = '_' + postfix
774
775 correlationModels = ["SIMPLIFIED", "FULL", "TOTAL", "TOYS"]
776 map_file = 'ElectronEfficiencyCorrection/2015_2025/rel22.2/2026_Run2Run3_Recommendation_v3/map1.txt'
777 sfList = []
778 # Set up the RECO electron efficiency correction algorithm:
779 if config.dataType() is not DataType.Data and not self.noEffSF:
780 alg = config.createAlgorithm( 'CP::ElectronEfficiencyCorrectionAlg',
781 'ElectronEfficiencyCorrectionAlgReco' )
782 config.addPrivateTool( 'efficiencyCorrectionTool',
783 'CP::AsgElectronEfficiencyCorrectionTool' )
784 alg.scaleFactorDecoration = 'el_reco_effSF' + selectionPostfix + '_%SYS%'
785 alg.efficiencyCorrectionTool.MapFilePath = map_file
786 alg.efficiencyCorrectionTool.RecoKey = "Reconstruction"
787 if self.correlationModelReco not in correlationModels:
788 raise ValueError('Invalid correlation model for reconstruction efficiency, '
789 f'has to be one of: {", ".join(correlationModels)}')
790 if config.geometry() >= LHCPeriod.Run3 and self.correlationModelReco != "TOTAL":
791 warnings.warn_explicit(
792 "Only TOTAL correlation model is currently supported "
793 "for reconstruction efficiency correction in Run 3."
794 f"Your choice {self.correlationModelReco} will be "
795 "overwritten with TOTAL",
796 ElectronEfficiencyCorrelationWarning,
797 filename='', lineno=0)
798 alg.efficiencyCorrectionTool.CorrelationModel = "TOTAL"
799 else:
800 alg.efficiencyCorrectionTool.CorrelationModel = self.correlationModelReco
801 if config.dataType() is DataType.FastSim:
802 alg.efficiencyCorrectionTool.ForceDataType = (
803 PATCore.ParticleDataType.Full if self.forceFullSimConfig
804 else PATCore.ParticleDataType.Fast)
805 elif config.dataType() is DataType.FullSim:
806 alg.efficiencyCorrectionTool.ForceDataType = \
807 PATCore.ParticleDataType.Full
808 alg.outOfValidity = 2 #silent
809 alg.outOfValidityDeco = 'el_reco_bad_eff' + selectionPostfix
810 alg.electrons = config.readName (self.containerName)
811 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
813 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
814 'reco_effSF' + postfix, auxType='float')
815 sfList += [alg.scaleFactorDecoration]
816
817 # Set up the ID electron efficiency correction algorithm:
818 if config.dataType() is not DataType.Data and not self.noEffSF and self.identificationWP != 'NoID':
819
820 alg = config.createAlgorithm( 'CP::ElectronEfficiencyCorrectionAlg',
821 'ElectronEfficiencyCorrectionAlgID' )
822 config.addPrivateTool( 'efficiencyCorrectionTool',
823 'CP::AsgElectronEfficiencyCorrectionTool' )
824 alg.scaleFactorDecoration = 'el_id_effSF' + selectionPostfix + '_%SYS%'
825 alg.efficiencyCorrectionTool.MapFilePath = map_file
826 alg.efficiencyCorrectionTool.IdKey = self.identificationWP
827 if self.correlationModelId not in correlationModels:
828 raise ValueError('Invalid correlation model for identification efficiency, '
829 f'has to be one of: {", ".join(correlationModels)}')
830 alg.efficiencyCorrectionTool.CorrelationModel = self.correlationModelId
831 if config.dataType() is DataType.FastSim:
832 alg.efficiencyCorrectionTool.ForceDataType = (
833 PATCore.ParticleDataType.Full if self.forceFullSimConfig
834 else PATCore.ParticleDataType.Fast)
835 elif config.dataType() is DataType.FullSim:
836 alg.efficiencyCorrectionTool.ForceDataType = \
837 PATCore.ParticleDataType.Full
838 alg.outOfValidity = 2 #silent
839 alg.outOfValidityDeco = 'el_id_bad_eff' + selectionPostfix
840 alg.electrons = config.readName (self.containerName)
841 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
842 if self.saveDetailedSF:
843 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
844 'id_effSF' + postfix, auxType='float')
845 sfList += [alg.scaleFactorDecoration]
846
847 # Set up the ISO electron efficiency correction algorithm:
848 if config.dataType() is not DataType.Data and self.isolationWP != 'NonIso' and not self.noEffSF:
849 alg = config.createAlgorithm( 'CP::ElectronEfficiencyCorrectionAlg',
850 'ElectronEfficiencyCorrectionAlgIsol' )
851 config.addPrivateTool( 'efficiencyCorrectionTool',
852 'CP::AsgElectronEfficiencyCorrectionTool' )
853 alg.scaleFactorDecoration = 'el_isol_effSF' + selectionPostfix + '_%SYS%'
854 alg.efficiencyCorrectionTool.MapFilePath = map_file
855 alg.efficiencyCorrectionTool.IdKey = self.identificationWP
856 alg.efficiencyCorrectionTool.IsoKey = self.isolationWP
857 if self.correlationModelIso not in correlationModels:
858 raise ValueError('Invalid correlation model for isolation efficiency, '
859 f'has to be one of: {", ".join(correlationModels)}')
860 if config.geometry() >= LHCPeriod.Run3 and self.correlationModelIso != 'TOTAL':
861 warnings.warn_explicit(
862 "Only TOTAL correlation model is currently supported "
863 "for isolation efficiency correction in Run 3."
864 f"Your choice {self.correlationModelIso} will be "
865 "overwritten with TOTAL",
866 ElectronEfficiencyCorrelationWarning,
867 filename='', lineno=0)
868 alg.efficiencyCorrectionTool.CorrelationModel = "TOTAL"
869 else:
870 alg.efficiencyCorrectionTool.CorrelationModel = self.correlationModelIso
871 if config.dataType() is DataType.FastSim:
872 alg.efficiencyCorrectionTool.ForceDataType = (
873 PATCore.ParticleDataType.Full if self.forceFullSimConfig
874 else PATCore.ParticleDataType.Fast)
875 elif config.dataType() is DataType.FullSim:
876 alg.efficiencyCorrectionTool.ForceDataType = \
877 PATCore.ParticleDataType.Full
878 alg.outOfValidity = 2 #silent
879 alg.outOfValidityDeco = 'el_isol_bad_eff' + selectionPostfix
880 alg.electrons = config.readName (self.containerName)
881 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
882 if self.saveDetailedSF:
883 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
884 'isol_effSF' + postfix, auxType='float')
885 sfList += [alg.scaleFactorDecoration]
886
887 if (self.chargeIDSelectionRun2 and config.geometry() < LHCPeriod.Run3 and
888 config.dataType() is not DataType.Data and not self.noEffSF):
889 alg = config.createAlgorithm( 'CP::ElectronEfficiencyCorrectionAlg',
890 'ElectronEfficiencyCorrectionAlgEcids' )
891 config.addPrivateTool( 'efficiencyCorrectionTool',
892 'CP::AsgElectronEfficiencyCorrectionTool' )
893 alg.scaleFactorDecoration = 'el_ecids_effSF' + selectionPostfix + '_%SYS%'
894 if self.isolationWP != 'Tight_VarRad':
895 raise ValueError('ECIDS SFs are supported only for Tight_VarRad isolation.')
896 if self.identificationWP == 'LooseBLayerLH':
897 ecids_lh = 'loose'
898 elif self.identificationWP == 'MediumLH':
899 ecids_lh = 'medium'
900 elif self.identificationWP == 'TightLH':
901 ecids_lh = 'tight'
902 else:
903 raise ValueError('ECIDS SFs are supported only for ID LooseBLayerLH, MediumLH, or TightLH')
904
905 alg.efficiencyCorrectionTool.CorrelationModel = "TOTAL"
906 alg.efficiencyCorrectionTool.CorrectionFileNameList = \
907 [f'ElectronEfficiencyCorrection/2015_2025/rel22.2/2025_Run2Rel22_Recommendation_v2/ecids/efficiencySF.ChargeID.{ecids_lh}_ECIDS_Tight_VarRad.root']
908 if config.dataType() is DataType.FastSim:
909 alg.efficiencyCorrectionTool.ForceDataType = (
910 PATCore.ParticleDataType.Full if self.forceFullSimConfig
911 else PATCore.ParticleDataType.Fast)
912 elif config.dataType() is DataType.FullSim:
913 alg.efficiencyCorrectionTool.ForceDataType = \
914 PATCore.ParticleDataType.Full
915 alg.outOfValidity = 2 #silent
916 alg.outOfValidityDeco = 'el_ecids_bad_eff' + selectionPostfix
917 alg.electrons = config.readName (self.containerName)
918 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
919 if self.saveDetailedSF:
920 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
921 'ecids_effSF' + postfix, auxType='float')
922 sfList += [alg.scaleFactorDecoration]
923
924 if self.addChargeMisIDSF and config.dataType() is not DataType.Data and not self.noEffSF and config.geometry() >= LHCPeriod.Run3:
925 warnings.warn_explicit(
926 "Charge mis-ID SFs are only available for Run 2 and will not"
927 " have any effect in Run 3.",
928 Run2OnlyFeatureWarning, filename='', lineno=0)
929
930 elif self.addChargeMisIDSF and config.dataType() is not DataType.Data and not self.noEffSF and config.geometry() < LHCPeriod.Run3:
931 alg = config.createAlgorithm( 'CP::ElectronEfficiencyCorrectionAlg',
932 'ElectronEfficiencyCorrectionAlgMisid' )
933 config.addPrivateTool( 'efficiencyCorrectionTool',
934 'CP::ElectronChargeEfficiencyCorrectionTool' )
935 alg.scaleFactorDecoration = 'el_charge_misid_effSF' + selectionPostfix + '_%SYS%'
936 if self.isolationWP != 'Tight_VarRad':
937 raise ValueError('Charge mis-ID SFs are supported only for Tight_VarRad isolation.')
938 if self.identificationWP == 'LooseBLayerLH':
939 misid_lh = 'LooseAndBLayerLLH'
940 elif self.identificationWP == 'MediumLH':
941 misid_lh = 'MediumLLH'
942 elif self.identificationWP == 'TightLH':
943 misid_lh = 'TightLLH'
944 else:
945 raise ValueError('Charge mis-ID SFs are supported only for ID LooseBLayerLH, MediumLH, or TightLH')
946 misid_suffix = '_ECIDSloose' if self.chargeIDSelectionRun2 else ''
947
948 alg.efficiencyCorrectionTool.CorrectionFileName = \
949 f'ElectronEfficiencyCorrection/2015_2025/rel22.2/2025_Run2Rel22_Recommendation_v2/charge_misID/chargeEfficiencySF.{misid_lh}_d0z0_TightVarRad{misid_suffix}.root'
950 if config.dataType() is DataType.FastSim:
951 alg.efficiencyCorrectionTool.ForceDataType = (
952 PATCore.ParticleDataType.Full if self.forceFullSimConfig
953 else PATCore.ParticleDataType.Fast)
954 elif config.dataType() is DataType.FullSim:
955 alg.efficiencyCorrectionTool.ForceDataType = \
956 PATCore.ParticleDataType.Full
957 alg.outOfValidity = 2 #silent
958 alg.outOfValidityDeco = 'el_misid_bad_eff' + selectionPostfix
959 alg.electrons = config.readName (self.containerName)
960 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
961 if self.saveDetailedSF:
962 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
963 'charge_misid_effSF' + postfix, auxType='float')
964 sfList += [alg.scaleFactorDecoration]
965
966 if config.dataType() is not DataType.Data and not self.noEffSF and self.saveCombinedSF:
967 alg = config.createAlgorithm( 'CP::AsgObjectScaleFactorAlg',
968 'ElectronCombinedEfficiencyScaleFactorAlg' )
969 alg.particles = config.readName (self.containerName)
970 alg.inScaleFactors = sfList
971 alg.outScaleFactor = 'effSF' + postfix + '_%SYS%'
972 config.addOutputVar (self.containerName, alg.outScaleFactor, 'effSF' + postfix, auxType='float')
973
975
976 def __init__ (self) :
977 super (ElectronTriggerAnalysisSFBlock, self).__init__ ()
978 self.addDependency('EventSelection', required=False)
979 self.addDependency('EventSelectionMerger', required=False)
980 self.addOption ('triggerChainsPerYear', {}, type=dict,
981 info="a dictionary with key (string) the year and value (list of "
982 "strings) the trigger chains.")
983 self.addOption ('electronID', '', type=str,
984 info="the electron ID WP to use.")
985 self.addOption ('electronIsol', '', type=str,
986 info="the electron isolation WP to use.")
987 self.addOption ('saveEff', False, type=bool,
988 info="define whether we decorate also the trigger scale efficiency.")
989 self.addOption ('prefixSF', 'trigEffSF', type=str,
990 info="the decoration prefix for trigger scale factors.")
991 self.addOption ('prefixEff', 'trigEff', type=str,
992 info="the decoration prefix for MC trigger efficiencies.")
993 self.addOption ('includeAllYearsPerRun', False, type=bool,
994 info="all configured years in the LHC run will "
995 "be included in all jobs.")
996 self.addOption ('removeHLTPrefix', True, type=bool,
997 info="remove the HLT prefix from trigger chain names.")
998 self.addOption ('useToolKeyAsOutput', False, type=bool,
999 info="use the tool trigger key as output.")
1000 self.addOption ('containerName', '', type=str,
1001 info="the input electron container, with a possible selection, in "
1002 "the format `container` or `container.selection`.",
1003 meta={'role':'containerRef'})
1004
1005 def instanceName (self) :
1006 """Return the instance name for this block"""
1007 return self.containerName
1008
1009 def makeAlgs (self, config) :
1010
1011 if config.dataType() is not DataType.Data:
1012 log = logging.getLogger('ElectronTriggerSFConfig')
1013
1015 log.warning('`includeAllYearsPerRun` is set to True, but `useToolKeyAsOutput` is set to False. '
1016 'This will cause multiple branches to be written out with the same content.')
1017
1018 # Dictionary from TrigGlobalEfficiencyCorrection/Triggers.cfg
1019 # Key is trigger chain (w/o HLT prefix)
1020 # Value is empty for single leg trigger or list of legs
1021 triggerDict = TriggerDict()
1022
1023 # currently recommended versions
1024 version_Run2 = "2015_2025/rel22.2/2025_Run2Rel22_Recommendation_v3"
1025 map_Run2 = f"ElectronEfficiencyCorrection/{version_Run2}/map1.txt"
1026 version_Run3 = "2015_2025/rel22.2/2026_Run3_Consolidated_Trigger_Recommendation_v1"
1027 map_Run3 = f"ElectronEfficiencyCorrection/{version_Run3}/map1.txt"
1028
1029 version = version_Run2 if config.geometry() is LHCPeriod.Run2 else version_Run3
1030 # Dictionary from TrigGlobalEfficiencyCorrection/MapKeys.cfg
1031 # Key is year_leg
1032 # Value is list of configs available, first one will be used
1033 mapKeysDict = MapKeysDict(version)
1034
1035 # helper function for leg filtering, very hardcoded but allows autoconfiguration
1036 def filterConfFromMap(conf, electronMapKeys):
1037 if not conf:
1038 raise ValueError("No configuration found for trigger chain.")
1039 if len(conf) == 1:
1040 return conf[0]
1041
1042 for c in conf:
1043 if c in electronMapKeys:
1044 return c
1045
1046 return conf[0]
1047
1049 years = [int(year) for year in self.triggerChainsPerYear.keys()]
1050 else:
1051 from TriggerAnalysisAlgorithms.TriggerAnalysisSFConfig import (
1052 get_input_years)
1053 years = get_input_years(config)
1054
1055 # prepare keys
1056 import ROOT
1057 triggerChainsPerYear_Run2 = {}
1058 triggerChainsPerYear_Run3 = {}
1059 for year, chains in self.triggerChainsPerYear.items():
1060 if not chains:
1061 warnings.warn_explicit(
1062 f"No trigger chains configured for year {year}."
1063 " Assuming this is intended, no Electron trigger SF"
1064 " will be computed.",
1065 TriggerSFWarning, filename='', lineno=0)
1066 continue
1067
1068 chains_split = [chain.replace("HLT_", "").replace(" || ", "_OR_") for chain in chains]
1069 if int(year) >= 2022:
1070 triggerChainsPerYear_Run3[str(year)] = ' || '.join(chains_split)
1071 else:
1072 triggerChainsPerYear_Run2[str(year)] = ' || '.join(chains_split)
1073 electronMapKeys_Run2 = ROOT.std.map("string", "string")()
1074 electronMapKeys_Run3 = ROOT.std.map("string", "string")()
1075
1076 sc_Run2 = ROOT.TrigGlobalEfficiencyCorrectionTool.suggestElectronMapKeys(triggerChainsPerYear_Run2, version_Run2, electronMapKeys_Run2)
1077 sc_Run3 = ROOT.TrigGlobalEfficiencyCorrectionTool.suggestElectronMapKeys(triggerChainsPerYear_Run3, version_Run3, electronMapKeys_Run3)
1078 if sc_Run2.code() != 2 or sc_Run3.code() != 2:
1079 raise RuntimeError("Failed to suggest electron map keys")
1080 electronMapKeys = dict(electronMapKeys_Run2) | dict(electronMapKeys_Run3)
1081
1082 # collect configurations
1083 from TriggerAnalysisAlgorithms.TriggerAnalysisConfig import is_year_in_current_period
1084 triggerConfigs = {}
1085 for year in years:
1086 if not is_year_in_current_period(config, year):
1087 continue
1088
1089 triggerChains = self.triggerChainsPerYear.get(int(year), self.triggerChainsPerYear.get(str(year), []))
1090 for chain in triggerChains:
1091 chain = chain.replace(" || ", "_OR_")
1092 chain_noHLT = chain.replace("HLT_", "")
1093 chain_out = chain_noHLT if self.removeHLTPrefix else chain
1094 legs = triggerDict[chain_noHLT]
1095 if not legs:
1096 if chain_noHLT[0] == 'e' and chain_noHLT[1].isdigit():
1097 chain_key = f"{year}_{chain_noHLT}"
1098 chain_conf = mapKeysDict[chain_key][0]
1099 triggerConfigs[chain_conf if self.useToolKeyAsOutput else chain_out] = chain_conf
1100 else:
1101 for leg in legs:
1102 if leg[0] == 'e' and leg[1].isdigit():
1103 leg_out = leg if self.removeHLTPrefix else f"HLT_{leg}"
1104 leg_key = f"{year}_{leg}"
1105 leg_conf = filterConfFromMap(mapKeysDict[leg_key], electronMapKeys)
1106 triggerConfigs[leg_conf if self.useToolKeyAsOutput else leg_out] = leg_conf
1107
1108 decorations = [self.prefixSF]
1109 if self.saveEff:
1110 decorations += [self.prefixEff]
1111
1112 for label, conf in triggerConfigs.items():
1113 for deco in decorations:
1114 alg = config.createAlgorithm('CP::ElectronEfficiencyCorrectionAlg',
1115 'EleTrigEfficiencyCorrectionsAlg' + deco +
1116 '_' + label)
1117 config.addPrivateTool( 'efficiencyCorrectionTool',
1118 'CP::AsgElectronEfficiencyCorrectionTool' )
1119
1120 # Reproduce config from TrigGlobalEfficiencyAlg
1121 alg.efficiencyCorrectionTool.MapFilePath = map_Run3 if config.geometry() is LHCPeriod.Run3 else map_Run2
1122 alg.efficiencyCorrectionTool.IdKey = self.electronID.replace("LH","") if config.geometry() is LHCPeriod.Run2 else self.electronID
1123 alg.efficiencyCorrectionTool.IsoKey = self.electronIsol
1124 alg.efficiencyCorrectionTool.TriggerKey = (
1125 ("Eff_" if deco == self.prefixEff else "") + conf)
1126 alg.efficiencyCorrectionTool.CorrelationModel = "TOTAL"
1127 alg.efficiencyCorrectionTool.ForceDataType = \
1128 PATCore.ParticleDataType.Full
1129
1130 alg.scaleFactorDecoration = f"el_{deco}_{label}_%SYS%"
1131
1132 alg.outOfValidity = 2 #silent
1133 alg.outOfValidityDeco = f"bad_eff_ele{deco}_{label}"
1134 alg.electrons = config.readName (self.containerName)
1135 alg.preselection = config.getPreselection (self.containerName, "")
1136 config.addOutputVar (self.containerName, alg.scaleFactorDecoration, f"{deco}_{label}", auxType='float')
1137
1138
1139class ElectronLRTMergedConfig (ConfigBlock) :
1140 def __init__ (self) :
1141 super (ElectronLRTMergedConfig, self).__init__ ()
1142 self.addOption (
1143 'inputElectrons', 'Electrons', type=str,
1144 noneAction='error',
1145 info="the name of the input electron container.",
1146 meta={'role':'containerRef'}
1147 )
1148 self.addOption (
1149 'inputLRTElectrons', 'LRTElectrons', type=str,
1150 noneAction='error',
1151 info="the name of the input LRT electron container."
1152 )
1153 self.addOption (
1154 'containerName', 'Electrons_LRTMerged', type=str,
1155 noneAction='error',
1156 info="the name of the output container after LRT merging.",
1157 meta={'role':'container'}
1158 )
1159
1160 def instanceName (self) :
1161 """Return the instance name for this block"""
1162 return self.containerName
1163
1164 def makeAlgs (self, config) :
1165
1166 if config.isPhyslite() :
1167 raise(RuntimeError("Electron LRT merging is not available in Physlite mode"))
1168
1169 alg = config.createAlgorithm( "CP::ElectronLRTMergingAlg", "ElectronLRTMergingAlg" )
1170 alg.PromptElectronLocation = self.inputElectrons
1171 alg.LRTElectronLocation = self.inputLRTElectrons
1172 alg.OutputCollectionName = self.containerName
1173 alg.CreateViewCollection = False
1174
1175@groupBlocks
1178 seq.append(ElectronIPCalibrationConfig())
1179
1180@groupBlocks
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition hcg.cxx:312
T * get(TKey *tobj)
get a TObject* from a TKey* (why can't a TObject be a TKey?)
Definition hcg.cxx:132
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:179