ATLAS Offline Software
Loading...
Searching...
No Matches
MuonAnalysisConfig.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 AnalysisAlgorithmsConfig.ConfigAccumulator import DataType
8from TrackingAnalysisAlgorithms.TrackingAnalysisConfig import InDetTrackCalibrationConfig
9from AthenaConfiguration.Enums import LHCPeriod
10from TrigGlobalEfficiencyCorrection.TriggerLeg_DictHelpers import TriggerDict
11from Campaigns.Utils import Campaign
12from AthenaCommon.Logging import logging
13
14
16 """the ConfigBlock for the muon four-momentum correction"""
17
18 def __init__ (self) :
19 super (MuonMomentumCalibrationConfig, self).__init__ ()
20 self.setBlockName('Muons')
21 self.addOption ('inputContainer', '', type=str,
22 info="the name of the input muon container. If left empty, automatically defaults "
23 "to `AnalysisMuons` for PHYSLITE or `Muons` otherwise.")
24 self.addOption ('containerName', '', type=str,
25 noneAction='error',
26 info="the name of the output container after calibration.")
27 self.addOption ('postfix', "", type=str,
28 info="a postfix to apply to decorations and algorithm names. "
29 "Typically not needed here since the calibration is common to "
30 "all muons.")
31 self.addOption ('minPt', 3.0*GeV, type=float,
32 info=r"$p_\mathrm{T}$ cut (in MeV) to apply to calibrated muons.")
33 self.addOption ('recalibratePhyslite', True, type=bool,
34 info="whether to run the `CP::MuonCalibrationAndSmearingAlg` on "
35 "PHYSLITE derivations.")
36 self.addOption ('maxEta', 2.7, type=float,
37 info=r"maximum muon $\vert\eta\vert$.")
38 self.addOption ('excludeNSWFromPrecisionLayers', False, type=bool,
39 info="only for testing purposes, turn on to ignore NSW hits and "
40 "fix a crash with older derivations (p-tag <p5834).")
41 self.addOption ('calibMode', 'correctData_CB', type=str, info='calibration mode of the `MuonCalibTool` needed to turn on the sagitta bias corrections and to select the muon track calibration type (CB or ID+MS), see https://atlas-mcp.docs.cern.ch/guidelines/muonmomentumcorrections/index.html#cpmuoncalibtool-tool.')
42 self.addOption ('useZeroPixMuons', False, type=bool, info='if True, a second `MuonCalibTool` instance with calibMode=correctData_MSonly is scheduled and applied only to ZeroPixelHit muons.')
43 self.addOption ('zeroPixMuonType', None, type=int, info='muonType value used for the ZeroPix calibration tool. If left as None, the default xAOD::Muon::MuonType::ZeroPixelHit is used.')
44 self.addOption ('decorateTruth', False, type=bool,
45 info="decorate truth particle information on the reconstructed one.")
46 self.addOption ('writeColumnarToolVariables', False, type=bool,
47 info="whether to add variables needed for running the columnar muon tool(s) on the output n-tuple (EXPERIMENTAL).",
48 expertMode=True)
49 self.addOption ('addGlobalFELinksDep', False, type=bool,
50 info="whether to add dependencies for the global FE links (needed for PHYSLITE production)",
51 expertMode=True)
52
53 def instanceName (self) :
54 if self.postfix != "":
55 return self.postfix
56 else :
57 return self.containerName
58
59 def makeAlgs (self, config) :
60
61 log = logging.getLogger('MuonCalibrationConfig')
62
63 #make sure that this is sync with
64 #PhysicsAnalysis/MuonID/MuonIDAnalysis/MuonMomentumCorrections/MuonMomentumCorrections/MuonCalibTool.h#L31-37
65 if self.calibMode == 'correctData_CB':
66 calibMode = 0
67 elif self.calibMode == 'correctData_IDMS':
68 calibMode = 1
69 elif self.calibMode == 'notCorrectData_IDMS':
70 calibMode = 2
71 elif self.calibMode == 'notCorrectData_CB':
72 calibMode = 3
73 elif self.calibMode == 'correctData_IDonly':
74 calibMode = 4
75 elif self.calibMode == 'correctData_MSonly':
76 calibMode = 5
77 else :
78 raise ValueError ("invalid calibMode: \"" + self.calibMode + "\". Allowed values are correctData_CB, correctData_IDMS, notCorrectData_IDMS, notCorrectData_CB, correctData_IDonly, correctData_MSonly")
79
80 inputContainer = "AnalysisMuons" if config.isPhyslite() else "Muons"
82 inputContainer = self.inputContainer
83 config.setSourceName (self.containerName, inputContainer)
84 config.setContainerMeta (self.containerName, 'calibMode', calibMode)
85
86 # Set up a shallow copy to decorate
87 if config.wantCopy (self.containerName) :
88 alg = config.createAlgorithm( 'CP::AsgShallowCopyAlg', 'MuonShallowCopyAlg' )
89 alg.input = config.readName (self.containerName)
90 alg.output = config.copyName (self.containerName)
91 alg.outputType = 'xAOD::MuonContainer'
92 decorationList = ['DFCommonJetDr',
93 'DFCommonMuonPassIDCuts',
94 'DFCommonMuonPassPreselection',
95 'neflowisol20_CloseByCorr',
96 'ptvarcone30_Nonprompt_All_MaxWeightTTVA_pt1000_CloseByCorr',
97 'ptvarcone30_Nonprompt_All_MaxWeightTTVA_pt500_CloseByCorr',
98 'topoetcone20_CloseByCorr']
100 decorationList += ['neutralGlobalFELinks', 'chargedGlobalFELinks']
101 if config.dataType() is not DataType.Data:
102 decorationList += ['TruthLink']
103 if self.addGlobalFELinksDep or config.dataType() is not DataType.Data:
104 alg.declareDecorations = decorationList
105
106 # Set up the eta-cut on all muons prior to everything else
107 alg = config.createAlgorithm( 'CP::AsgSelectionAlg',
108 'MuonEtaCutAlg' )
109 config.addPrivateTool( 'selectionTool', 'CP::AsgPtEtaSelectionTool' )
110 alg.selectionTool.maxEta = self.maxEta
111 alg.selectionDecoration = 'selectEta' + self.postfix + ',as_bits'
112 alg.particles = config.readName (self.containerName)
113 alg.preselection = config.getPreselection (self.containerName, '')
114 config.addSelection (self.containerName, '', alg.selectionDecoration)
115
116 # Set up the muon calibration and smearing algorithm:
117 alg = config.createAlgorithm( 'CP::MuonCalibrationAndSmearingAlg',
118 'MuonCalibrationAndSmearingAlg' )
119 config.addPrivateTool( 'calibrationAndSmearingTool',
120 'CP::MuonCalibTool' )
121
122 alg.calibrationAndSmearingTool.IsRun3Geo = config.geometry() >= LHCPeriod.Run3
123 alg.calibrationAndSmearingTool.calibMode = calibMode
124 if config.geometry() is LHCPeriod.Run4:
125 log.warning("Disabling NSW hits for Run4 geometry")
126 alg.calibrationAndSmearingTool.ExcludeNSWFromPrecisionLayers = True
127 else:
128 alg.calibrationAndSmearingTool.ExcludeNSWFromPrecisionLayers = self.excludeNSWFromPrecisionLayers and (config.geometry() >= LHCPeriod.Run3)
129
130 # Optionally set up a second calibration tool applied only to ZPH muons
131 # The calibMode is set to 'correctData_MSonly'.
133 config.addPrivateTool( 'calibrationAndSmearingTool_ZeroPix',
134 'CP::MuonCalibTool' )
135 alg.calibrationAndSmearingTool_ZeroPix.IsRun3Geo = config.geometry() >= LHCPeriod.Run3
136 alg.calibrationAndSmearingTool_ZeroPix.calibMode = 5 # correctData_MSonly
137 alg.calibrationAndSmearingTool_ZeroPix.ExcludeNSWFromPrecisionLayers = alg.calibrationAndSmearingTool.ExcludeNSWFromPrecisionLayers
138 if self.zeroPixMuonType is not None:
139 alg.zeroPixMuonType = self.zeroPixMuonType
140
141 alg.muons = config.readName (self.containerName)
142 alg.muonsOut = config.copyName (self.containerName)
143 alg.preselection = config.getPreselection (self.containerName, '')
144 if config.isPhyslite() and not self.recalibratePhyslite :
145 alg.skipNominal = True
146
147 # Set up the the pt selection
148 if self.minPt > 0:
149 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'MuonPtCutAlg' )
150 alg.selectionDecoration = 'selectPt' + self.postfix + ',as_bits'
151 config.addPrivateTool( 'selectionTool', 'CP::AsgPtEtaSelectionTool' )
152 alg.particles = config.readName (self.containerName)
153 alg.selectionTool.minPt = self.minPt
154 alg.preselection = config.getPreselection (self.containerName, '')
155 config.addSelection (self.containerName, '', alg.selectionDecoration,
156 preselection = True)
157
158 alg = config.createAlgorithm( 'CP::AsgEnergyDecoratorAlg', 'EnergyDecorator' )
159 alg.particles = config.readName (self.containerName)
160
161 config.addOutputVar (self.containerName, 'pt', 'pt')
162 config.addOutputVar (self.containerName, 'eta', 'eta', noSys=True)
163 config.addOutputVar (self.containerName, 'phi', 'phi', noSys=True)
164 config.addOutputVar (self.containerName, 'e_%SYS%', 'e')
165 config.addOutputVar (self.containerName, 'charge', 'charge', noSys=True)
166
167 # decorate truth information on the reconstructed object:
168 if self.decorateTruth and config.dataType() is not DataType.Data:
169 config.addOutputVar (self.containerName, "truthType", "truth_type", noSys=True)
170 config.addOutputVar (self.containerName, "truthOrigin", "truth_origin", noSys=True)
171
172 config.addOutputVar (self.containerName, 'muonType', 'muonType', noSys=True, enabled=self.writeColumnarToolVariables)
173
174
175class MuonIPCalibrationConfig (ConfigBlock) :
176 """the ConfigBlock for the muon impact parameter correction"""
177
178 def __init__ (self) :
179 super (MuonIPCalibrationConfig, self).__init__ ()
180 self.setBlockName('MuonIPCalibration')
181 self.addDependency('Muons', required=True)
182 self.addDependency('MuonWorkingPointSelection', required=False)
183 self.addOption ('containerName', '', type=str,
184 noneAction='error',
185 info="the name of the output container after calibration.")
186 self.addOption ('postfix', "", type=str,
187 info="a postfix to apply to decorations and algorithm names. "
188 "Typically not needed here since the calibration is common to "
189 "all muons.")
190 self.addOption ('writeTrackD0Z0', False, type = bool,
191 info=r"save the $d_0$ significance and $z_0\sin\theta$ variables.")
192 self.addOption ('runTrackBiasing', False, type=bool,
193 info="This enables the `InDetTrackBiasingTool`, for tracks "
194 "associated to muons")
195
196 def instanceName (self) :
197 return self.containerName + self.postfix
198
199 def makeAlgs (self, config) :
200
201 # Additional decorations
203 alg = config.createAlgorithm( 'CP::AsgLeptonTrackDecorationAlg',
204 'LeptonTrackDecorator' )
205 if config.dataType() is not DataType.Data:
207 InDetTrackCalibrationConfig.makeTrackBiasingTool(config, alg)
208 InDetTrackCalibrationConfig.makeTrackSmearingTool(config, alg)
209 alg.particles = config.readName (self.containerName)
210
211 config.addOutputVar (self.containerName, 'd0_%SYS%', 'd0')
212 config.addOutputVar (self.containerName, 'd0sig_%SYS%', 'd0sig')
213 config.addOutputVar (self.containerName, 'z0_%SYS%', 'z0')
214 config.addOutputVar (self.containerName, 'z0sintheta_%SYS%', 'z0sintheta')
215 config.addOutputVar (self.containerName, 'z0sinthetasig_%SYS%', 'z0sinthetasig')
216
217
219 """the ConfigBlock for the muon working point selection"""
220
221 def __init__ (self) :
222 super (MuonWorkingPointSelectionConfig, self).__init__ ()
223 self.setBlockName('MuonWorkingPointSelection')
224 self.addOption ('containerName', '', type=str,
225 noneAction='error',
226 info="the name of the input container.")
227 self.addOption ('selectionName', '', type=str,
228 noneAction='error',
229 info="the name of the muon selection to define (e.g. `tight` or `loose`).")
230 self.addOption ('postfix', None, type=str,
231 info="a postfix to apply to decorations and algorithm names. "
232 "Typically not needed here as `selectionName` is used internally.")
233 self.addOption ('trackSelection', True, type=bool,
234 info="whether or not to set up an instance of "
235 "`CP::AsgLeptonTrackSelectionAlg`, with the recommended $d_0$ and "
236 r"$z_0\sin\theta$ cuts.")
237 self.addOption ('maxD0Significance', 3, type=float,
238 info="maximum $d_0$ significance used for the track selection.")
239 self.addOption ('maxDeltaZ0SinTheta', 0.5, type=float,
240 info=r"maximum $\Delta z_0\sin\theta$ (in mm) used for the track selection.")
241 self.addOption ('quality', None, type=str,
242 info="the ID WP to use. Supported ID WPs: `Tight`, `Medium`, "
243 "`Loose`, `LowPt`, `HighPt`.")
244 self.addOption ('isolation', None, type=str,
245 info="the isolation WP to use. Supported isolation WPs: "
246 "`PflowLoose_VarRad`, `PflowTight_VarRad`, `Loose_VarRad`, "
247 "`Tight_VarRad`, `NonIso`.")
248 self.addOption ('addSelectionToPreselection', True, type=bool,
249 info="whether to retain only muons satisfying the working point "
250 "requirements.")
251 self.addOption ('isoDecSuffix', '', type=str,
252 info="the `isoDecSuffix` name if using close-by-corrected isolation working points.")
253 self.addOption ('excludeNSWFromPrecisionLayers', False, type=bool,
254 info="only for testing purposes, turn on to ignore NSW hits and "
255 "fix a crash with older derivations (p-tag <p5834).")
256 self.addOption('useLRT', False, type=bool,
257 info="whether to enable LRT handling in CP::MuonSelectionTool")
258
259 def instanceName (self) :
260 if self.postfix is not None:
261 return self.containerName + '_' + self.postfix
262 else:
263 return self.containerName + '_' + self.selectionName
264
265 def makeAlgs (self, config) :
266 log = logging.getLogger('MuonWorkingPointSelectionConfig')
267
268 from xAODMuon.xAODMuonEnums import xAODMuonEnums
269 if self.quality == 'Tight' :
270 quality = xAODMuonEnums.Quality.Tight
271 elif self.quality == 'Medium' :
272 quality = xAODMuonEnums.Quality.Medium
273 elif self.quality == 'Loose' :
274 quality = xAODMuonEnums.Quality.Loose
275 elif self.quality == 'VeryLoose' :
276 quality = xAODMuonEnums.Quality.VeryLoose
277 elif self.quality == 'HighPt' :
278 quality = 4
279 elif self.quality == 'LowPt' :
280 quality = 5
281 else :
282 raise ValueError ("invalid muon quality: \"" + self.quality +
283 "\", allowed values are Tight, Medium, Loose, " +
284 "VeryLoose, HighPt, LowPt")
285
286 # The setup below is inappropriate for Run 1
287 if config.geometry() is LHCPeriod.Run1:
288 raise ValueError ("Can't set up the MuonWorkingPointSelectionConfig with %s, there must be something wrong!" % config.geometry().value)
289
290 postfix = self.postfix
291 if postfix is None :
292 postfix = self.selectionName
293 if postfix != '' and postfix[0] != '_' :
294 postfix = '_' + postfix
295
296 # Set up the track selection algorithm:
298 alg = config.createAlgorithm( 'CP::AsgLeptonTrackSelectionAlg',
299 'MuonTrackSelectionAlg',
300 reentrant=True )
301 alg.selectionDecoration = 'trackSelection' + postfix + ',as_bits'
302 alg.maxD0Significance = self.maxD0Significance
303 alg.maxDeltaZ0SinTheta = self.maxDeltaZ0SinTheta
304 alg.particles = config.readName (self.containerName)
305 alg.preselection = config.getPreselection (self.containerName, '')
306 config.addSelection (self.containerName, self.selectionName, alg.selectionDecoration, preselection=self.addSelectionToPreselection)
307
308 # Setup the muon quality selection
309 alg = config.createAlgorithm( 'CP::MuonSelectionAlgV2',
310 'MuonSelectionAlg' )
311 config.addPrivateTool( 'selectionTool', 'CP::MuonSelectionTool' )
312 alg.selectionTool.MuQuality = quality
313 alg.selectionTool.IsRun3Geo = config.geometry() >= LHCPeriod.Run3
314 alg.selectionTool.UseLRT = self.useLRT
315 if config.geometry() is LHCPeriod.Run4:
316 log.warning("Disabling NSW hits for Run4 geometry")
317 alg.selectionTool.ExcludeNSWFromPrecisionLayers = True
318 else:
319 alg.selectionTool.ExcludeNSWFromPrecisionLayers = self.excludeNSWFromPrecisionLayers and (config.geometry() >= LHCPeriod.Run3)
320 alg.selectionDecoration = 'good_muon' + postfix + ',as_char'
321 alg.badMuonVetoDecoration = 'is_bad' + postfix + ',as_char'
322 alg.muons = config.readName (self.containerName)
323 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
324 config.addSelection (self.containerName, self.selectionName,
325 alg.selectionDecoration,
326 preselection=self.addSelectionToPreselection)
327 if self.quality == 'HighPt':
328 config.addOutputVar (self.containerName, 'is_bad' + postfix, 'is_bad' + postfix)
329
330 # Set up the isolation calculation algorithm:
331 if self.isolation != 'NonIso' :
332 alg = config.createAlgorithm( 'CP::MuonIsolationAlg',
333 'MuonIsolationAlg' )
334 config.addPrivateTool( 'isolationTool', 'CP::IsolationSelectionTool' )
335 alg.isolationTool.MuonWP = self.isolation
336 alg.isolationTool.IsoDecSuffix = self.isoDecSuffix
337 alg.isolationDecoration = 'isolated_muon' + postfix + ',as_char'
338 alg.muons = config.readName (self.containerName)
339 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
340 config.addSelection (self.containerName, self.selectionName,
341 alg.isolationDecoration,
342 preselection=self.addSelectionToPreselection)
343
344
346 """the ConfigBlock for the muon working point efficiency computation"""
347
348 def __init__ (self) :
349 super (MuonWorkingPointEfficiencyConfig, self).__init__ ()
350 self.setBlockName('MuonWorkingPointEfficiency')
351 self.addDependency('MuonWorkingPointSelection', required=True)
352 self.addDependency('EventSelection', required=False)
353 self.addDependency('EventSelectionMerger', required=False)
354 self.addOption ('containerName', '', type=str,
355 noneAction='error',
356 info="the name of the input container.")
357 self.addOption ('selectionName', '', type=str,
358 noneAction='error',
359 info="the name of the muon selection to define (e.g. `tight` or `loose`).")
360 self.addOption ('postfix', None, type=str,
361 info="a postfix to apply to decorations and algorithm names. "
362 "Typically not needed here as `selectionName` is used internally.")
363 self.addOption ('trackSelection', True, type=bool,
364 info="whether or not to set up an instance of "
365 "`CP::AsgLeptonTrackSelectionAlg`, with the recommended $d_0$ and "
366 r"$z_0\sin\theta$ cuts.")
367 self.addOption ('quality', None, type=str,
368 info="the ID WP to use. Supported ID WPs: `Tight`, `Medium`, "
369 "`Loose`, `LowPt`, `HighPt`.")
370 self.addOption ('isolation', None, type=str,
371 info="the isolation WP to use. Supported isolation WPs: "
372 "`PflowLoose_VarRad`, `PflowTight_VarRad`, `Loose_VarRad`, "
373 "`Tight_VarRad`, `NonIso`.")
374 self.addOption ('systematicBreakdown', False, type=bool,
375 info="enables the full breakdown of efficiency SF systematics "
376 "(1 NP per uncertainty source, instead of 1 NP in total).")
377 self.addOption ('noEffSF', False, type=bool,
378 info="disables the calculation of efficiencies and scale factors. "
379 "Experimental! Only useful to test a new WP for which scale "
380 "factors are not available.",
381 expertMode=True)
382 self.addOption ('saveDetailedSF', True, type=bool,
383 info="save all the independent detailed object scale factors.")
384 self.addOption ('saveCombinedSF', False, type=bool,
385 info="save the combined object scale factor.")
386
387 def instanceName (self) :
388 if self.postfix is not None:
389 return self.containerName + '_' + self.postfix
390 else:
391 return self.containerName + '_' + self.selectionName
392
393 def makeAlgs (self, config) :
394
395 # The setup below is inappropriate for Run 1
396 if config.geometry() is LHCPeriod.Run1:
397 raise ValueError ("Can't set up the MuonWorkingPointEfficiencyConfig with %s, there must be something wrong!" % config.geometry().value)
398
399 postfix = self.postfix
400 if postfix is None :
401 postfix = self.selectionName
402 if postfix != '' and postfix[0] != '_' :
403 postfix = '_' + postfix
404
405 sfList = []
406 # Set up the reco/ID efficiency scale factor calculation algorithm:
407 if config.dataType() is not DataType.Data and not self.noEffSF:
408 alg = config.createAlgorithm( 'CP::MuonEfficiencyScaleFactorAlg',
409 'MuonEfficiencyScaleFactorAlgReco' )
410 config.addPrivateTool( 'efficiencyScaleFactorTool',
411 'CP::MuonEfficiencyScaleFactors' )
412 config.setExtraInputs ({('xAOD::EventInfo', 'EventInfo.RandomRunNumber')})
413 alg.scaleFactorDecoration = 'muon_reco_effSF' + postfix + "_%SYS%"
414 alg.outOfValidity = 2 #silent
415 alg.outOfValidityDeco = 'muon_reco_bad_eff' + postfix
416 alg.efficiencyScaleFactorTool.WorkingPoint = self.quality
417 if config.geometry() >= LHCPeriod.Run3:
418 alg.efficiencyScaleFactorTool.CalibrationRelease = '251211_Preliminary_r24run3'
419 else:
420 alg.efficiencyScaleFactorTool.CalibrationRelease = '230213_Preliminary_r22run2_loosefix'
421 alg.efficiencyScaleFactorTool.BreakDownSystematics = self.systematicBreakdown
422 alg.muons = config.readName (self.containerName)
423 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
425 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
426 'reco_effSF' + postfix)
427 sfList += [alg.scaleFactorDecoration]
428
429 # Set up the HighPt-specific BadMuonVeto efficiency scale factor calculation algorithm:
430 if config.dataType() is not DataType.Data and self.quality == 'HighPt' and not self.noEffSF:
431 alg = config.createAlgorithm( 'CP::MuonEfficiencyScaleFactorAlg',
432 'MuonEfficiencyScaleFactorAlgBMVHighPt' )
433 config.addPrivateTool( 'efficiencyScaleFactorTool',
434 'CP::MuonEfficiencyScaleFactors' )
435 alg.scaleFactorDecoration = 'muon_BadMuonVeto_effSF' + postfix + "_%SYS%"
436 alg.outOfValidity = 2 #silent
437 alg.outOfValidityDeco = 'muon_BadMuonVeto_bad_eff' + postfix
438 alg.efficiencyScaleFactorTool.WorkingPoint = 'BadMuonVeto_HighPt'
439 if config.geometry() >= LHCPeriod.Run3:
440 alg.efficiencyScaleFactorTool.CalibrationRelease = '220817_Preliminary_r22run3' # not available as part of '230123_Preliminary_r22run3'!
441 else:
442 alg.efficiencyScaleFactorTool.CalibrationRelease = '230213_Preliminary_r22run2_loosefix'
443 alg.efficiencyScaleFactorTool.BreakDownSystematics = self.systematicBreakdown
444 alg.muons = config.readName (self.containerName)
445 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
446 if self.saveDetailedSF:
447 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
448 'BadMuonVeto_effSF' + postfix)
449 sfList += [alg.scaleFactorDecoration]
450
451 # Set up the isolation efficiency scale factor calculation algorithm:
452 if config.dataType() is not DataType.Data and self.isolation != 'NonIso' and not self.noEffSF:
453 alg = config.createAlgorithm( 'CP::MuonEfficiencyScaleFactorAlg',
454 'MuonEfficiencyScaleFactorAlgIsol' )
455 config.addPrivateTool( 'efficiencyScaleFactorTool',
456 'CP::MuonEfficiencyScaleFactors' )
457 alg.scaleFactorDecoration = 'muon_isol_effSF' + postfix + "_%SYS%"
458 alg.outOfValidity = 2 #silent
459 alg.outOfValidityDeco = 'muon_isol_bad_eff' + postfix
460 alg.efficiencyScaleFactorTool.WorkingPoint = self.isolation + 'Iso'
461 if config.geometry() >= LHCPeriod.Run3:
462 alg.efficiencyScaleFactorTool.CalibrationRelease = '251211_Preliminary_r24run3'
463 else:
464 alg.efficiencyScaleFactorTool.CalibrationRelease = '230213_Preliminary_r22run2_loosefix'
465 alg.efficiencyScaleFactorTool.BreakDownSystematics = self.systematicBreakdown
466 alg.muons = config.readName (self.containerName)
467 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
468 if self.saveDetailedSF:
469 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
470 'isol_effSF' + postfix)
471 sfList += [alg.scaleFactorDecoration]
472
473 # Set up the TTVA scale factor calculation algorithm:
474 if config.dataType() is not DataType.Data and self.trackSelection and not self.noEffSF:
475 alg = config.createAlgorithm( 'CP::MuonEfficiencyScaleFactorAlg',
476 'MuonEfficiencyScaleFactorAlgTTVA' )
477 config.addPrivateTool( 'efficiencyScaleFactorTool',
478 'CP::MuonEfficiencyScaleFactors' )
479 alg.scaleFactorDecoration = 'muon_TTVA_effSF' + postfix + "_%SYS%"
480 alg.outOfValidity = 2 #silent
481 alg.outOfValidityDeco = 'muon_TTVA_bad_eff' + postfix
482 alg.efficiencyScaleFactorTool.WorkingPoint = 'TTVA'
483 if config.geometry() >= LHCPeriod.Run3:
484 alg.efficiencyScaleFactorTool.CalibrationRelease = '251211_Preliminary_r24run3'
485 else:
486 alg.efficiencyScaleFactorTool.CalibrationRelease = '230213_Preliminary_r22run2_loosefix'
487 alg.efficiencyScaleFactorTool.BreakDownSystematics = self.systematicBreakdown
488 alg.muons = config.readName (self.containerName)
489 alg.preselection = config.getPreselection (self.containerName, self.selectionName)
490 if self.saveDetailedSF:
491 config.addOutputVar (self.containerName, alg.scaleFactorDecoration,
492 'TTVA_effSF' + postfix)
493 sfList += [alg.scaleFactorDecoration]
494
495 if config.dataType() is not DataType.Data and not self.noEffSF and self.saveCombinedSF:
496 alg = config.createAlgorithm( 'CP::AsgObjectScaleFactorAlg',
497 'MuonCombinedEfficiencyScaleFactorAlg' )
498 alg.particles = config.readName (self.containerName)
499 alg.inScaleFactors = sfList
500 alg.outScaleFactor = 'effSF' + postfix + '_%SYS%'
501 config.addOutputVar (self.containerName, alg.outScaleFactor, 'effSF' + postfix)
502
503class MuonTriggerAnalysisSFBlock (ConfigBlock):
504
505 def __init__ (self) :
506 super (MuonTriggerAnalysisSFBlock, self).__init__ ()
507 self.addDependency('EventSelection', required=False)
508 self.addDependency('EventSelectionMerger', required=False)
509 self.addOption ('triggerChainsPerYear', {}, type=dict,
510 info="a dictionary with key (string) the year and value (list of "
511 "strings) the trigger chains.")
512 self.addOption ('muonID', '', type=str,
513 info="the muon quality WP to use.")
514 self.addOption ('saveSF', True, type=bool,
515 info="whether to decorate the trigger scale factor.")
516 self.addOption ('saveEff', False, type=bool,
517 info="whether to decorate the trigger MC efficiencies.")
518 self.addOption ('saveEffData', False, type=bool,
519 info="whether to decorate the trigger data efficiencies.")
520 self.addOption ('prefixSF', 'trigEffSF', type=str,
521 info="the decoration prefix for trigger scale factors.")
522 self.addOption ('prefixEff', 'trigEff', type=str,
523 info="the decoration prefix for MC trigger efficiencies.")
524 self.addOption ('prefixEffData', 'trigEffData', type=str,
525 info="the decoration prefix for data trigger efficiencies.")
526 self.addOption ('includeAllYearsPerRun', False, type=bool,
527 info="all configured years in the LHC run will "
528 "be included in all jobs.")
529 self.addOption ('removeHLTPrefix', True, type=bool,
530 info="remove the HLT prefix from trigger chain names.")
531 self.addOption ('containerName', '', type=str,
532 info="the input muon container, with a possible selection, in "
533 "the format `container` or `container.selection`.")
534 self.addOption ('customToolSuffix', '', type=str,
535 expertMode=True, info="EXPERIMENTAL: specify custom suffix for the public tool name")
536 self.addOption ('customInputFolder', '', type=str,
537 expertMode=True, info="EXPERIMENTAL: specify custom input folder")
538 self.addOption ('customInputFilePerYear', {}, type=dict,
539 expertMode=True, info="EXPERIMENTAL: specify custom input file per year")
540
541 def instanceName (self) :
542 return self.containerName + '_' + self.muonID
543
544 def makeAlgs (self, config) :
545
546 if config.dataType() is not DataType.Data:
547
548 # Dictionary from TrigGlobalEfficiencyCorrection/Triggers.cfg
549 # Key is trigger chain (w/o HLT prefix)
550 # Value is empty for single leg trigger or list of legs
551 triggerDict = TriggerDict()
552
554 years = [int(year) for year in self.triggerChainsPerYear.keys()]
555 else:
556 from TriggerAnalysisAlgorithms.TriggerAnalysisSFConfig import (
557 get_input_years)
558 years = get_input_years(config)
559
560 triggerYearStartBoundaries = {
561 2015: 260000,
562 2016: 290000,
563 2017: 324000,
564 2018: 348000,
565 2022: 410000,
566 2023: 450000,
567 2024: 470000,
568 }
569
570 triggerConfigs = {}
571 triggerConfigYears = {}
572 from TriggerAnalysisAlgorithms.TriggerAnalysisConfig import is_year_in_current_period
573 for year in years:
574 if not is_year_in_current_period(config, year):
575 continue
576
577 triggerChains = self.triggerChainsPerYear.get(int(year), self.triggerChainsPerYear.get(str(year), []))
578 for chain in triggerChains:
579 chain = chain.replace(" || ", "_OR_")
580 chain_noHLT = chain.replace("HLT_", "")
581 chain_out = chain_noHLT if self.removeHLTPrefix else chain
582 legs = triggerDict[chain_noHLT]
583 if not legs:
584 if chain_noHLT.startswith('mu') and chain_noHLT[2].isdigit:
585 # Need to support HLT_mu26_ivarmedium_OR_HLT_mu50
586 triggerConfigs[chain_out] = chain
587 if chain_out in triggerConfigYears.keys():
588 triggerConfigYears[chain_out].append(year)
589 else:
590 triggerConfigYears[chain_out] = [year]
591 else:
592 for leg in legs:
593 if leg.startswith('mu') and leg[2].isdigit:
594 # Need to support HLT_mu14_ivarloose
595 leg_out = leg if self.removeHLTPrefix else f"HLT_{leg}"
596 triggerConfigs[leg_out] = f"HLT_{leg}"
597 if leg_out in triggerConfigYears.keys():
598 triggerConfigYears[leg_out].append(year)
599 else:
600 triggerConfigYears[leg_out] = [year]
601
602 if not triggerConfigs:
603 return
604
605 # Make the public tool for this configuration
606 sfTool = config.createPublicTool("CP::MuonTriggerScaleFactors", f"{self.instanceName()}_SFTool{self.customToolSuffix}")
607 # Reproduce config from TrigGlobalEfficiencyAlg
608 sfTool.MuonQuality = self.muonID
609 sfTool.AllowZeroSF = True
610 sfTool.CustomInputFolder = self.customInputFolder
611 sfTool.CustomInputFilePerYear = self.customInputFilePerYear
612 sfTool.Campaign = config.campaign().value
613
614 for trig_short, trig in triggerConfigs.items():
615 alg = config.createAlgorithm('CP::MuonTriggerEfficiencyScaleFactorAlg',
616 'MuonTrigEfficiencyCorrectionsAlg_' + trig_short)
617 alg.efficiencyScaleFactorTool = f"{sfTool.getType()}/{sfTool.getName()}"
618
619 # Avoid warnings for missing triggers
620 if self.includeAllYearsPerRun:
621 alg.minRunNumber = 0
622 alg.maxRunNumber = 999999
623
624 if triggerConfigYears[trig_short][0] != years[0]:
625 alg.minRunNumber = triggerYearStartBoundaries.get(triggerConfigYears[trig_short][0], 999999)
626 if triggerConfigYears[trig_short][-1] != years[-1]:
627 alg.maxRunNumber = triggerYearStartBoundaries.get(triggerConfigYears[trig_short][-1] + 1, 999999)
628 elif config.campaign() is Campaign.MC20a: # to avoid potential corner-cases keep the default config unchanged
629 if triggerConfigYears[trig_short] == [2015]:
630 alg.maxRunNumber = 290000
631 elif triggerConfigYears[trig_short] == [2016]:
632 alg.minRunNumber = 290000
633
634 alg.trigger = trig
635
636 # Some triggers in `250731_SummerUpdate` recommendations are not supported in 2022 period F
637 if config.campaign() is Campaign.MC23a and (trig_short == "HLT_mu8noL1_FSNOSEED" or trig_short == "HLT_mu22_L1MU14FCH"):
638 alg.minRunNumber = 435816 # Start of 2022 period H
639
640 if self.saveSF:
641 alg.scaleFactorDecoration = f"muon_{self.prefixSF}_{trig_short}_%SYS%"
642 if self.saveEff:
643 alg.mcEfficiencyDecoration = f"muon_{self.prefixEff}_{trig_short}_%SYS%"
644 if self.saveEffData:
645 alg.dataEfficiencyDecoration = f"muon_{self.prefixEffData}_{trig_short}_%SYS%"
646 alg.outOfValidity = 2 #silent
647 alg.outOfValidityDeco = f"bad_eff_muontrig_{trig_short}"
648 alg.muons = config.readName (self.containerName)
649 alg.preselection = config.getPreselection (self.containerName, '')
650 if self.saveSF:
651 config.addOutputVar (self.containerName, alg.scaleFactorDecoration, f"{self.prefixSF}_{trig_short}")
652 if self.saveEff:
653 config.addOutputVar (self.containerName, alg.mcEfficiencyDecoration, f"{self.prefixEff}_{trig_short}")
654 if self.saveEffData:
655 config.addOutputVar (self.containerName, alg.dataEfficiencyDecoration, f"{self.prefixEffData}_{trig_short}")
656
657
658class MuonLRTMergedConfig (ConfigBlock) :
659 def __init__ (self) :
660 super (MuonLRTMergedConfig, self).__init__ ()
661 self.addOption (
662 'inputMuons', 'Muons', type=str,
663 noneAction='error',
664 info="the name of the input muon container."
665 )
666 self.addOption (
667 'inputLRTMuons', 'MuonsLRT', type=str,
668 noneAction='error',
669 info="the name of the input LRT muon container."
670 )
671 self.addOption (
672 'containerName', 'Muons_LRTMerged', type=str,
673 noneAction='error',
674 info="the name of the output container after LRT merging."
675 )
676
677 def instanceName (self) :
678 return self.containerName
679
680 def makeAlgs (self, config) :
681
682 if config.isPhyslite() :
683 raise(RuntimeError("Muon LRT merging is not available in Physlite mode"))
684
685 alg = config.createAlgorithm( "CP::MuonLRTMergingAlg", "MuonLRTMergingAlg" )
686 alg.PromptMuonLocation = self.inputMuons
687 alg.LRTMuonLocation = self.inputLRTMuons
688 alg.OutputMuonLocation = self.containerName
689 alg.UseRun3WP = config.geometry() >= LHCPeriod.Run3
690 alg.CreateViewCollection = False
691
692class MuonContainerMergingConfig (ConfigBlock) :
693 def __init__ (self) :
694 super (MuonContainerMergingConfig, self).__init__ ()
695 self.addOption (
696 'inputMuonContainers', [], type=list,
697 noneAction='error',
698 info="list of container names to be merged (of type `xAOD::MuonContainer`)."
699 )
700 self.addOption (
701 'outputMuonLocation', 'MuonsMerged', type=str,
702 noneAction='error',
703 info="the name of the output muon container."
704 )
705 self.addOption (
706 'createViewCollection', True, type=bool,
707 info="whether the output container should be a view container rather than a deep copy."
708 )
709
710 def instanceName (self) :
711 return self.outputMuonLocation
712
713 def makeAlgs (self, config) :
714 alg = config.createAlgorithm( "CP::MuonContainerMergingAlg", "MuonContainerMergingAlg" )
715 alg.InputMuonContainers = self.inputMuonContainers
716 alg.OutputMuonLocation = self.outputMuonLocation
717 alg.CreateViewCollection = self.createViewCollection
718
719@groupBlocks
722 seq.append(MuonIPCalibrationConfig())
723
724@groupBlocks
T * get(TKey *tobj)
get a TObject* from a TKey* (why can't a TObject be a TKey?)
Definition hcg.cxx:132