ATLAS Offline Software
Loading...
Searching...
No Matches
PhotonAnalysisConfig.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 Campaigns.Utils import Campaign
9from AnalysisAlgorithmsConfig.ConfigAccumulator import (
10 DataType, Run4FallbackWarning, TestingOnlyWarning)
11import warnings
12
13import ROOT
14
15# E/gamma import(s).
16from xAODEgamma.xAODEgammaParameters import xAOD
17
18from RootUtils.LoadEnumHeader import loadEnumHeader
19loadEnumHeader ('ElectronPhotonSelectorTools/egammaPIDdefs.h')
20
22
23class PhotonCalibrationConfig (ConfigBlock) :
24 """the ConfigBlock for the photon four-momentum correction"""
25
26 def __init__ (self) :
27 super (PhotonCalibrationConfig, self).__init__ ()
28 self.setBlockName('Photons')
29 self.addOption ('containerName', '', type=str,
30 noneAction='error',
31 info="the name of the output container after calibration.",
32 meta={'role':'container'})
33 self.addOption ('ESModel', '', type=str,
34 info="flag for EGamma calibration. If left empty, uses the current recommendations.")
35 self.addOption ('decorrelationModel', '1NP_v1', type=str,
36 info="decorrelation model for the EGamma energy scale. Supported choices are: `FULL_v1`, `1NP_v1`.",
37 meta={'choices':(['FULL_v1','1NP_v1'],1)})
38 self.addOption ('postfix', '', type=str,
39 info="a postfix to apply to decorations and algorithm names. "
40 "Typically not needed here since the calibration is common to "
41 "all photons.")
42 self.addOption ('crackVeto', False, type=bool,
43 info=r"whether to perform LAr crack veto based on the cluster $\eta$, "
44 r"i.e. remove photons within $1.37<\vert\eta\vert<1.52$.")
45 self.addOption ('enableCleaning', True, type=bool,
46 info="whether to enable photon cleaning (`DFCommonPhotonsCleaning`).")
47 self.addOption ('cleaningAllowLate', False, type=bool,
48 info="whether to ignore timing information in cleaning "
49 "(`DFCommonPhotonsCleaningNoTime`).")
50 self.addOption ('recomputeIsEM', False, type=bool,
51 info="whether to recompute the photon shower shape fudge "
52 "corrections (sets up an instance of `CP::PhotonShowerShapeFudgeAlg`) or rely on derivation flags.")
53 self.addOption ('recalibratePhyslite', True, type=bool,
54 info="whether to recalibrate PHYSLITE derivations, i.e. run the "
55 "`CP::EgammaCalibrationAndSmearingAlg` on the nominal. If `False` "
56 "the nominal stored in the PHYSLITE is used, and only the "
57 "systematic variations are recomputed.")
58 self.addOption ('minPt', 10*GeV, type=float,
59 info=r"the minimum $p_\mathrm{T}$ cut (in MeV) to apply to calibrated photons.")
60 self.addOption ('maxEta', 2.37, type=float,
61 info=r"maximum photon $\vert\eta\vert$.")
62 self.addOption ('forceFullSimConfigForP4', False, type=bool,
63 info="whether to force the tool to use the configuration meant for "
64 "full simulation samples for 4-vector corrections. Only for testing purposes.")
65 self.addOption ('forceFullSimConfigForIso', False, type=bool,
66 info="whether to force the tool to use the configuration meant for "
67 "full simulation samples for isolation corrections. Only for testing purposes.")
68 self.addOption ('applyIsolationCorrection', True, type=bool,
69 info="whether to apply the isolation corrections.")
70 self.addOption ('splitCalibrationAndSmearing', False, type=bool,
71 info="whether to split the `EgammaCalibrationAndSmearingTool` "
72 "into two steps. The first step applies a baseline calibration that "
73 "is not affected by systematics. The second step then applies the "
74 "systematics-dependent corrections. The net effect is that the "
75 "slower first step only has to be run once, while the second is run "
76 "once per systematic. On PHYSLITE with `recalibratePhyslite=False` "
77 "the first step is skipped, and for simulation the second step "
78 "starts from the `E_mva_only` stored in the PHYSLITE. ATLASG-2358.")
79 self.addOption ('decorateTruth', False, type=bool,
80 info="decorate the truth particle information on the reconstructed one.")
81 self.addOption ('decorateCaloClusterEta', False, type=bool,
82 info=r"decorate the calo-cluster $\eta$.")
83 self.addOption ('decorateEmva', False, type=bool,
84 info="decorate `E_mva_only` on the photons (needed for columnar tools/PHYSLITE).")
85 self.addOption ('addGlobalFELinksDep', False, type=bool,
86 info="whether to add dependencies for the global FE links (needed for PHYSLITE production)",
87 expertMode=True)
88
89 def instanceName (self) :
90 """Return the instance name for this block"""
91 return self.containerName + self.postfix
92
93
94 def makeCalibrationAndSmearingAlg (self, config, name) :
95 """Create the calibration and smearing algorithm
96
97 Factoring this out into its own function, as we want to
98 instantiate it in multiple places"""
99
100 # Set up the calibration and smearing algorithm:
101 alg = config.createAlgorithm( 'CP::EgammaCalibrationAndSmearingAlg', name )
102 config.addPrivateTool( 'calibrationAndSmearingTool',
103 'CP::EgammaCalibrationAndSmearingTool' )
104 # Set default ESModel per period
105 if self.ESModel:
106 alg.calibrationAndSmearingTool.ESModel = self.ESModel
107 else:
108 if config.geometry() is LHCPeriod.Run2:
109 alg.calibrationAndSmearingTool.ESModel = 'es2023_R22_Run2_v1'
110 elif config.geometry() is LHCPeriod.Run3:
111 alg.calibrationAndSmearingTool.ESModel = 'es2024_Run3_v0'
112 elif config.geometry() is LHCPeriod.Run4:
113 warnings.warn_explicit(
114 "No ESModel set for Run4, using Run3 model",
115 Run4FallbackWarning, filename='', lineno=0)
116 alg.calibrationAndSmearingTool.ESModel = 'es2024_Run3_v0'
117 else:
118 raise ValueError (f"Can't set up the PhotonCalibrationConfig with {config.geometry().value}, "
119 "there must be something wrong!")
120
121 alg.calibrationAndSmearingTool.decorrelationModel = self.decorrelationModel
122 alg.calibrationAndSmearingTool.useFastSim = (
124 else int( config.dataType() is DataType.FastSim ))
125 alg.calibrationAndSmearingTool.decorateEmva = self.decorateEmva
126 # only photons are calibrated here, so skip loading the electron BDTs
127 alg.calibrationAndSmearingTool.DoElectronMVACalibration = False
128 # the tool must not re-add the cells lost to the timing cut if the
129 # egamma AODFix already corrected the clusters upstream
130 if 'egClusterL2_3Fix' in config.flags.Input.AODFixesDone :
131 alg.calibrationAndSmearingTool.FixForMissingCells = False
132 alg.egammas = config.readName (self.containerName)
133 alg.egammasOut = config.copyName (self.containerName)
134 alg.preselection = config.getPreselection (self.containerName, '')
135
136 config.setContainerMeta (self.containerName, 'ESModel', alg.calibrationAndSmearingTool.ESModel, allowOverwrite=True)
137 config.setContainerMeta (self.containerName, 'decorrelationModel', alg.calibrationAndSmearingTool.decorrelationModel, allowOverwrite=True)
138
139 return alg
140
141
142 def makeAlgs (self, config) :
143
144 postfix = self.postfix
145 if postfix != '' and postfix[0] != '_' :
146 postfix = '_' + postfix
147
149 warnings.warn_explicit(
150 "You are running PhotonCalibrationConfig forcing"
151 " full sim config for P4 corrections."
152 " This is only intended to be used for testing purposes.",
153 TestingOnlyWarning, filename='', lineno=0)
154
155 if config.isPhyslite() :
156 config.setSourceName (self.containerName, "AnalysisPhotons")
157 else :
158 config.setSourceName (self.containerName, "Photons")
159
160 cleaningWP = 'NoTime' if self.cleaningAllowLate else ''
161
162 # Decorate calo cluster eta if required
164 alg = config.createAlgorithm( 'CP::EgammaCaloClusterEtaAlg',
165 'PhotonEgammaCaloClusterEtaAlg',
166 reentrant=True )
167 alg.particles = config.readName(self.containerName)
168 config.addOutputVar (self.containerName, 'caloEta2', 'caloEta2', noSys=True, auxType='float')
169
170 # Set up a shallow copy to decorate
171 if config.wantCopy (self.containerName) :
172 alg = config.createAlgorithm( 'CP::AsgShallowCopyAlg', 'PhotonShallowCopyAlg' )
173 alg.input = config.readName (self.containerName)
174 alg.output = config.copyName (self.containerName)
175 alg.outputType = 'xAOD::PhotonContainer'
176 decorationList = ['DFCommonPhotonsCleaning',
177 'ptcone20_CloseByCorr',
178 'topoetcone20_CloseByCorr',
179 'topoetcone40_CloseByCorr']
181 decorationList += ['neutralGlobalFELinks', 'chargedGlobalFELinks']
182 if config.dataType() is not DataType.Data:
183 decorationList += ['TruthLink']
184 alg.declareDecorations = decorationList
185
186 # Set up the eta-cut on all photons prior to everything else
187 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'PhotonEtaCutAlg' )
188 alg.selectionDecoration = 'selectEta' + postfix + ',as_bits'
189 config.addPrivateTool( 'selectionTool', 'CP::AsgPtEtaSelectionTool' )
190 alg.selectionTool.maxEta = self.maxEta
191 if self.crackVeto:
192 alg.selectionTool.etaGapLow = 1.37
193 alg.selectionTool.etaGapHigh = 1.52
194 alg.selectionTool.useClusterEta = True
195 alg.particles = config.readName (self.containerName)
196 alg.preselection = config.getPreselection (self.containerName, '')
197 config.addSelection (self.containerName, '', alg.selectionDecoration)
198
199 # Setup shower shape fudge
200 if self.recomputeIsEM and config.dataType() is DataType.FullSim:
201 alg = config.createAlgorithm( 'CP::PhotonShowerShapeFudgeAlg',
202 'PhotonShowerShapeFudgeAlg' )
203 config.addPrivateTool( 'showerShapeFudgeTool',
204 'ElectronPhotonVariableCorrectionTool' )
205 if config.geometry() is LHCPeriod.Run2:
206 alg.showerShapeFudgeTool.ConfigFile = \
207 'EGammaVariableCorrection/TUNE25/ElPhVariableNominalCorrection.conf'
208 if config.geometry() is LHCPeriod.Run3:
209 if config.campaign() in (Campaign.MC23a, Campaign.MC23d):
210 alg.showerShapeFudgeTool.ConfigFile = \
211 'EGammaVariableCorrection/TUNE28AD/ElPhVariableNominalCorrection.conf'
212 else:
213 alg.showerShapeFudgeTool.ConfigFile = \
214 'EGammaVariableCorrection/TUNE28EG/ElPhVariableNominalCorrection.conf'
215 alg.photons = config.readName (self.containerName)
216 alg.photonsOut = config.copyName (self.containerName)
217 alg.preselection = config.getPreselection (self.containerName, '')
218
219 # Select photons only with good object quality.
220 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'PhotonObjectQualityAlg' )
221 config.setExtraInputs ({('xAOD::EventInfo', 'EventInfo.RandomRunNumber')})
222 alg.selectionDecoration = 'goodOQ' + postfix + ',as_bits'
223 config.addPrivateTool( 'selectionTool', 'CP::EgammaIsGoodOQSelectionTool' )
224 alg.selectionTool.Mask = xAOD.EgammaParameters.BADCLUSPHOTON
225 alg.particles = config.readName (self.containerName)
226 alg.preselection = config.getPreselection (self.containerName, '')
227 config.addSelection (self.containerName, '', alg.selectionDecoration)
228
229 # Select clean photons
231 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'PhotonCleaningAlg' )
232 config.addPrivateTool( 'selectionTool', 'CP::AsgFlagSelectionTool' )
233 alg.selectionDecoration = 'isClean' + postfix + ',as_bits'
234 alg.selectionTool.selectionFlags = ['DFCommonPhotonsCleaning' + cleaningWP]
235 alg.particles = config.readName (self.containerName)
236 alg.preselection = config.getPreselection (self.containerName, '')
237 config.addSelection (self.containerName, '', alg.selectionDecoration)
238
239 # Change the origin of Photons from (0,0,0) to (0,0,z)
240 # where z comes from the position of a vertex
241 # Default the one tagged as Primary
242 alg = config.createAlgorithm( 'CP::PhotonOriginCorrectionAlg',
243 'PhotonOriginCorrectionAlg',
244 reentrant=True )
245 alg.photons = config.readName (self.containerName)
246 alg.photonsOut = config.copyName (self.containerName)
247 alg.preselection = config.getPreselection (self.containerName, '')
248
250 # Set up the calibration and smearing algorithm:
251 alg = self.makeCalibrationAndSmearingAlg (config, 'PhotonCalibrationAndSmearingAlg')
252 if config.isPhyslite() and not self.recalibratePhyslite :
253 alg.skipNominal = True
254 else:
255 # This splits the EgammaCalibrationAndSmearingTool into two
256 # steps. The first step applies a baseline calibration that
257 # is not affected by systematics. The second step then
258 # applies the systematics dependent corrections. The net
259 # effect is that the slower first step only has to be run
260 # once, while the second is run once per systematic.
261 #
262 # On PHYSLITE the output of the first step is already
263 # available: in data it is the final energy, which is what is
264 # stored, and in simulation it is the energy after the MVA
265 # calibration, which is stored as `E_mva_only`. So if the
266 # PHYSLITE is not to be recalibrated, the first step is
267 # skipped, and in simulation the second step starts from `E_mva_only`.
268 #
269 # See: ATLASG-2358
270 skipBaseStep = config.isPhyslite() and not self.recalibratePhyslite
271
272 if not skipBaseStep :
273 # Set up the calibration algorithm:
274 alg = self.makeCalibrationAndSmearingAlg (config, 'PhotonBaseCalibrationAlg')
275 # turn off systematics for the calibration step
276 alg.noToolSystematics = True
277 # turn off smearing for the calibration step
278 alg.calibrationAndSmearingTool.doSmearing = False
279 if config.dataType() is DataType.FastSim :
280 # don't correct FastSim samples twice
281 alg.calibrationAndSmearingTool.useFastSim = 0
282
283 # Set up the smearing algorithm:
284 alg = self.makeCalibrationAndSmearingAlg (config, 'PhotonCalibrationSystematicsAlg')
285 # turn off scale corrections for the smearing step
286 alg.calibrationAndSmearingTool.doScaleCorrection = False
287 alg.calibrationAndSmearingTool.useMVACalibration = False
288 alg.calibrationAndSmearingTool.decorateEmva = False
289 if skipBaseStep and config.dataType() is not DataType.Data :
290 # the first step is not run, start from its output
291 alg.calibrationAndSmearingTool.startFromEmva = True
292 if config.dataType() is DataType.Data :
293 # these have already been applied to data in the first step
294 alg.calibrationAndSmearingTool.useIntermoduleCorrection = False
295 alg.calibrationAndSmearingTool.usePhiUniformCorrection = False
296 alg.calibrationAndSmearingTool.useCaloDistPhiUnifCorrection = False
297 alg.calibrationAndSmearingTool.doADCLinearityCorrection = False
298 alg.calibrationAndSmearingTool.useGainCorrection = False
299
301 warnings.warn_explicit(
302 "You are not applying the isolation corrections."
303 " This is only intended to be used for testing purposes.",
304 TestingOnlyWarning, filename='', lineno=0)
305
306 if self.minPt > 0:
307
308 # Set up the the pt selection
309 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'PhotonPtCutAlg' )
310 alg.selectionDecoration = 'selectPt' + postfix + ',as_bits'
311 config.addPrivateTool( 'selectionTool', 'CP::AsgPtEtaSelectionTool' )
312 alg.selectionTool.minPt = self.minPt
313 alg.particles = config.readName (self.containerName)
314 alg.preselection = config.getPreselection (self.containerName, '')
315 config.addSelection (self.containerName, '', alg.selectionDecoration,
316 preselection=True)
317
318 # Set up the isolation correction algorithm.
320
322 warnings.warn_explicit(
323 "You are running PhotonCalibrationConfig forcing"
324 " full sim config for isolation corrections."
325 " This is only intended to be used for testing purposes.",
326 TestingOnlyWarning, filename='', lineno=0)
327
328 alg = config.createAlgorithm( 'CP::EgammaIsolationCorrectionAlg',
329 'PhotonIsolationCorrectionAlg' )
330 config.addPrivateTool( 'isolationCorrectionTool',
331 'CP::IsolationCorrectionTool' )
332 alg.isolationCorrectionTool.IsMC = config.dataType() is not DataType.Data
333 alg.isolationCorrectionTool.AFII_corr = (
335 else config.dataType() is DataType.FastSim)
336 AODfixes = config.flags.Input.AODFixesDone
337 if "egammatopoIsoFix" in AODfixes:
338 alg.isolationCorrectionTool.FixTimingIssueInCore = False
339 else:
340 alg.isolationCorrectionTool.FixTimingIssueInCore = True
341 alg.egammas = config.readName (self.containerName)
342 alg.egammasOut = config.copyName (self.containerName)
343 alg.preselection = config.getPreselection (self.containerName, '')
344
345 # Additional decorations
346 alg = config.createAlgorithm( 'CP::AsgEnergyDecoratorAlg', 'EnergyDecorator' )
347 alg.particles = config.readName (self.containerName)
348
349 config.addOutputVar (self.containerName, 'pt', 'pt', auxType='float')
350 config.addOutputVar (self.containerName, 'eta', 'eta', noSys=True, auxType='float')
351 config.addOutputVar (self.containerName, 'phi', 'phi', noSys=True, auxType='float')
352 config.addOutputVar (self.containerName, 'e_%SYS%', 'e', auxType='float')
353 config.addOutputVar (self.containerName, 'caloClusterEnergyReso_%SYS%', 'caloClusterEnergyReso', noSys=True, auxType='float')
354
355 # decorate truth information on the reconstructed object:
356 if self.decorateTruth and config.dataType() is not DataType.Data:
357 config.addOutputVar (self.containerName, "truthType", "truth_type", noSys=True, auxType='int')
358 config.addOutputVar (self.containerName, "truthOrigin", "truth_origin", noSys=True, auxType='int')
359
360
362 """the ConfigBlock for the photon working point selection"""
363
364 def __init__ (self) :
365 super (PhotonWorkingPointSelectionConfig, self).__init__ ()
366 self.setBlockName('PhotonWorkingPointSelection')
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 photon 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 ('qualityWP', None, type=str,
380 info="the ID WP to use. Supported ID WPs: `Tight`, `Medium`, `Loose`, `NoID`.",
381 expertMode=['NoID'],
382 meta={'choices':(['Tight','Medium','Loose','NoID'],1)})
383 self.addOption ('isolationWP', None, type=str,
384 info="the isolation WP to use. Supported isolation WPs: "
385 "`FixedCutLoose`, `FixedCutTight`, `TightCaloOnly`, `NonIso`.",
386 meta={'choices':(['FixedCutLoose','FixedCutTight','TightCaloOnly','NonIso'],1)})
387 self.addOption ('addSelectionToPreselection', True, type=bool,
388 info="whether to retain only photons satisfying the working point "
389 "requirements.")
390 self.addOption ('closeByCorrection', False, type=bool,
391 info="whether to use close-by-corrected isolation working points.")
392 self.addOption ('recomputeIsEM', False, type=bool,
393 info="whether to rerun the cut-based selection (`True`), or rely on derivation flags (`False`).")
394 self.addOption ('doFSRSelection', False, type=bool,
395 info="whether to accept additional photons close to muons for the "
396 "purpose of FSR corrections to these muons. Expert feature "
397 "requested by the H4l analysis running on PHYSLITE.",
398 expertMode=True)
399 self.addOption ('muonsForFSRSelection', None, type=str,
400 info="the name of the muon container to use for the FSR selection. "
401 "If not specified, AnalysisMuons is used.",
402 expertMode=True,
403 meta={'role':'containerRef'})
404
405 def instanceName (self) :
406 """Return the instance name for this block"""
407 if self.postfix is not None :
408 return self.containerName + '_' + self.selectionName + self.postfix
409 return self.containerName + '_' + self.selectionName
410
411 def makeAlgs (self, config) :
412
413 # The setup below is inappropriate for Run 1
414 if config.geometry() is LHCPeriod.Run1:
415 raise ValueError ("Can't set up the PhotonWorkingPointConfig with %s, there must be something wrong!" % config.geometry().value)
416
417 postfix = self.postfix
418 if postfix is None :
419 postfix = self.selectionName
420 if postfix != '' and postfix[0] != '_' :
421 postfix = '_' + postfix
422
423 if self.qualityWP == 'Tight' :
424 quality = ROOT.egammaPID.PhotonTight
425 elif self.qualityWP == 'Medium' :
426 quality = ROOT.egammaPID.PhotonMedium
427 elif self.qualityWP == 'Loose' :
428 quality = ROOT.egammaPID.PhotonLoose
429 elif self.qualityWP == 'NoID':
430 quality = None
432 raise ValueError('NoID WP cannot be recomputed.')
433 else :
434 raise Exception (f'unknown photon quality working point "{self.qualityWP}" should be Tight, Medium or Loose')
435
436 # Set up the photon selection algorithm:
437 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'PhotonIsEMSelectorAlg' )
438 alg.selectionDecoration = 'selectEM' + postfix + ',as_char'
439 if self.recomputeIsEM:
440 # Rerun the cut-based ID
441 config.addPrivateTool( 'selectionTool', 'AsgPhotonIsEMSelector' )
442 alg.selectionTool.isEMMask = quality
443 if config.geometry() is LHCPeriod.Run2:
444 if self.qualityWP == 'Tight':
445 alg.selectionTool.ConfigFile = 'ElectronPhotonSelectorTools/offline/mc20_20240510/PhotonIsEMTightSelectorCutDefs_pTdep_mc20_smooth.conf'
446 elif self.qualityWP == 'Loose':
447 alg.selectionTool.ConfigFile = 'ElectronPhotonSelectorTools/offline/mc15_20150712/PhotonIsEMLooseSelectorCutDefs.conf'
448 elif self.qualityWP == 'Medium':
449 alg.selectionTool.ConfigFile = 'ElectronPhotonSelectorTools/offline/mc20_20240510/PhotonIsEMMediumSelectorCutDefs_pTdep_smooth.conf'
450 if config.geometry() is LHCPeriod.Run3:
451 if self.qualityWP == 'Tight':
452 alg.selectionTool.ConfigFile = 'ElectronPhotonSelectorTools/offline/mc23_20260924/PhotonIsEMTightSelectorCutDefs.conf'
453 elif self.qualityWP == 'Loose':
454 alg.selectionTool.ConfigFile = 'ElectronPhotonSelectorTools/offline/mc15_20150712/PhotonIsEMLooseSelectorCutDefs.conf'
455 elif self.qualityWP == 'Medium':
456 raise ValueError('No Medium menu available for Run-3. Please get in contact with egamma')
457 else:
458 # Select from Derivation Framework flags
459 config.addPrivateTool( 'selectionTool', 'CP::AsgFlagSelectionTool' )
460 if quality is not None:
461 dfFlag = 'DFCommonPhotonsIsEM' + self.qualityWP
462 alg.selectionTool.selectionFlags = [ dfFlag ]
463 alg.particles = config.readName (self.containerName)
464 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
465
466 # Set up the FSR selection
468 # wpSelection needs the ',as_char' suffix so SysReadSelectionHandle knows the type
469 wpDecoration = alg.selectionDecoration
470 wpDecorationName = wpDecoration.split(',')[0]
471 # Insert FSR before the postfix (e.g., selectEM_loose -> selectEMFSR_loose)
472 underscorePos = wpDecorationName.find('_')
473 if underscorePos < 0:
474 underscorePos = len(wpDecorationName)
475 outputDecorationName = wpDecorationName[:underscorePos] + 'FSR' + wpDecorationName[underscorePos:]
476
477 alg = config.createAlgorithm( 'CP::EgammaFSRForMuonsCollectorAlg', 'EgammaFSRForMuonsCollectorAlg')
478 alg.wpSelection = wpDecoration # Input: read the WP selection (with type suffix)
479 alg.selectionDecoration = outputDecorationName # Output: combined WP||FSR (name only for SysWriteDecorHandle)
480 alg.ElectronOrPhotonContKey = config.readName (self.containerName)
481 if self.muonsForFSRSelection is not None:
482 alg.MuonContKey = config.readName (self.muonsForFSRSelection)
483
484 # Register the FSR COMBINED selection
485 config.addSelection (self.containerName, self.selectionName,
486 alg.selectionDecoration + ',as_char',
487 preselection=self.addSelectionToPreselection)
488 else:
489 # No FSR - register the WP selection directly
490 config.addSelection (self.containerName, self.selectionName, alg.selectionDecoration,
491 preselection=self.addSelectionToPreselection)
492
493 # Set up the isolation selection algorithm:
494 if self.isolationWP != 'NonIso' :
495 alg = config.createAlgorithm( 'CP::EgammaIsolationSelectionAlg',
496 'PhotonIsolationSelectionAlg' )
497 alg.selectionDecoration = 'isolated' + postfix + ',as_char'
498 config.addPrivateTool( 'selectionTool', 'CP::IsolationSelectionTool' )
499 alg.selectionTool.PhotonWP = self.isolationWP
501 alg.selectionTool.IsoDecSuffix = "CloseByCorr"
502 alg.isPhoton = True
503 alg.egammas = config.readName (self.containerName)
504 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
505 config.addSelection (self.containerName, self.selectionName, alg.selectionDecoration,
506 preselection=self.addSelectionToPreselection)
507
508
510 """the ConfigBlock for the photon working point efficiency computation"""
511
512 def __init__ (self) :
513 super (PhotonWorkingPointEfficiencyConfig, self).__init__ ()
514 self.setBlockName('PhotonWorkingPointEfficiency')
515 self.addDependency('PhotonWorkingPointSelection', required=True)
516 self.addDependency('EventSelection', required=False)
517 self.addDependency('EventSelectionMerger', required=False)
518 self.addOption ('containerName', '', type=str,
519 noneAction='error',
520 info="the name of the input container.",
521 meta={'role':'containerRef'})
522 self.addOption ('selectionName', '', type=str,
523 noneAction='error',
524 info="the name of the photon selection to define (e.g. `tight` or "
525 "`loose`).",
526 meta={'role':'selection'})
527 self.addOption ('postfix', None, type=str,
528 info="a postfix to apply to decorations and algorithm names. "
529 "Typically not needed here as `selectionName` is used internally.")
530 self.addOption ('qualityWP', None, type=str,
531 info="the ID WP to use. Supported ID WPs: `Tight`, `Medium`, `Loose`, `NoID`.",
532 expertMode=['NoID'],
533 meta={'choices':(['Tight','Medium','Loose','NoID'],1)})
534 self.addOption ('isolationWP', None, type=str,
535 info="the isolation WP to use. Supported isolation WPs: "
536 "`FixedCutLoose`, `FixedCutTight`, `TightCaloOnly`, `NonIso`.",
537 meta={'choices':(['FixedCutLoose','FixedCutTight','TightCaloOnly','NonIso'],1)})
538 self.addOption ('noEffSFForID', False, type=bool,
539 info="disables the calculation of ID efficiencies and scale factors. "
540 "Experimental! only useful to test a new WP for which scale "
541 "factors are not available.",
542 expertMode=True)
543 self.addOption ('noEffSFForIso', False, type=bool,
544 info="disables the calculation of isolation efficiencies and scale factors. "
545 "Experimental! only useful to test a new WP for which scale "
546 "factors are not available.",
547 expertMode=True)
548 self.addOption ('saveDetailedSF', True, type=bool,
549 info="save all the independent detailed object scale factors.")
550 self.addOption ('saveCombinedSF', False, type=bool,
551 info="save the combined object scale factor.")
552 self.addOption ('forceFullSimConfigForID', False, type=bool,
553 info="whether to force the ID tool to use the configuration meant "
554 "for full simulation samples. Only for testing purposes.")
555 self.addOption ('forceFullSimConfigForIso', False, type=bool,
556 info="whether to force the isolation tool to use the configuration meant "
557 "for full simulation samples. Only for testing purposes.")
558
559 def instanceName (self) :
560 """Return the instance name for this block"""
561 if self.postfix is not None :
562 return self.containerName + '_' + self.selectionName + self.postfix
563 return self.containerName + '_' + self.selectionName
564
565 def makeAlgs (self, config) :
566
567 # The setup below is inappropriate for Run 1
568 if config.geometry() is LHCPeriod.Run1:
569 raise ValueError ("Can't set up the PhotonWorkingPointConfig with %s, there must be something wrong!" % config.geometry().value)
570
572 warnings.warn_explicit(
573 "You are running PhotonWorkingPointConfig forcing"
574 " full sim config for ID."
575 " This is only intended to be used for testing purposes.",
576 TestingOnlyWarning, filename='', lineno=0)
577
579 warnings.warn_explicit(
580 "You are running PhotonWorkingPointConfig forcing"
581 " full sim config for Iso."
582 " This is only intended to be used for testing purposes.",
583 TestingOnlyWarning, filename='', lineno=0)
584
585 postfix = self.postfix
586 if postfix is None :
587 postfix = self.selectionName
588 if postfix != '' and postfix[0] != '_' :
589 postfix = '_' + postfix
590
591 sfList = []
592 # Set up the ID/reco photon efficiency correction algorithm:
593 if config.dataType() is not DataType.Data and self.qualityWP != 'NoID' and not self.noEffSFForID:
594 alg = config.createAlgorithm( 'CP::PhotonEfficiencyCorrectionAlg',
595 'PhotonEfficiencyCorrectionAlgID' )
596 config.addPrivateTool( 'efficiencyCorrectionTool',
597 'CP::AsgPhotonEfficiencyCorrectionTool' )
598 alg.scaleFactorDecoration = 'ph_id_effSF' + postfix + '_%SYS%'
599 if config.dataType() is DataType.FastSim:
600 alg.efficiencyCorrectionTool.ForceDataType = (
601 PATCore.ParticleDataType.Full if self.forceFullSimConfigForID else
602 PATCore.ParticleDataType.Fast)
603 elif config.dataType() is DataType.FullSim:
604 alg.efficiencyCorrectionTool.ForceDataType = \
605 PATCore.ParticleDataType.Full
606 alg.efficiencyCorrectionTool.MapFilePath = 'PhotonEfficiencyCorrection/2015_2025/rel22.2/2026_Run3Consolidated_Recommendation_v1/map0.txt'
607 alg.outOfValidity = 2 #silent
608 alg.outOfValidityDeco = 'ph_id_bad_eff' + postfix
609 alg.photons = config.readName (self.containerName)
610 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
612 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
613 'id_effSF' + postfix, auxType='float')
614 sfList += [alg.scaleFactorDecoration]
615
616 # Set up the ISO photon efficiency correction algorithm:
617 if config.dataType() is not DataType.Data and self.isolationWP != 'NonIso' and not self.noEffSFForIso:
618 alg = config.createAlgorithm( 'CP::PhotonEfficiencyCorrectionAlg',
619 'PhotonEfficiencyCorrectionAlgIsol' )
620 config.addPrivateTool( 'efficiencyCorrectionTool',
621 'CP::AsgPhotonEfficiencyCorrectionTool' )
622 alg.scaleFactorDecoration = 'ph_isol_effSF' + postfix + '_%SYS%'
623 if config.dataType() is DataType.FastSim:
624 alg.efficiencyCorrectionTool.ForceDataType = (
625 PATCore.ParticleDataType.Full if self.forceFullSimConfigForIso else
626 PATCore.ParticleDataType.Fast)
627 elif config.dataType() is DataType.FullSim:
628 alg.efficiencyCorrectionTool.ForceDataType = \
629 PATCore.ParticleDataType.Full
630 alg.efficiencyCorrectionTool.IsoKey = self.isolationWP.replace("FixedCut","")
631 alg.efficiencyCorrectionTool.MapFilePath = 'PhotonEfficiencyCorrection/2015_2025/rel22.2/2022_Summer_Prerecom_v1/map1.txt'
632 alg.outOfValidity = 2 #silent
633 alg.outOfValidityDeco = 'ph_isol_bad_eff' + postfix
634 alg.photons = config.readName (self.containerName)
635 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
636 if self.saveDetailedSF:
637 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
638 'isol_effSF' + postfix, auxType='float')
639 sfList += [alg.scaleFactorDecoration]
640
641 doCombEffSF = not self.noEffSFForID or not self.noEffSFForIso
642 if config.dataType() is not DataType.Data and doCombEffSF and self.saveCombinedSF:
643 alg = config.createAlgorithm( 'CP::AsgObjectScaleFactorAlg',
644 'PhotonCombinedEfficiencyScaleFactorAlg' )
645 alg.particles = config.readName (self.containerName)
646 alg.inScaleFactors = sfList
647 alg.outScaleFactor = 'effSF' + postfix + '_%SYS%'
648 config.addOutputVar (self.containerName, alg.outScaleFactor, 'effSF' + postfix, auxType='float')
649
650
651@groupBlocks
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition hcg.cxx:312