ATLAS Offline Software
Loading...
Searching...
No Matches
JetAnalysisConfig.py
Go to the documentation of this file.
1# Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
2
3
4
5# AnaAlgorithm import(s):
6from AnalysisAlgorithmsConfig.ConfigBlock import ConfigBlock
7from AnalysisAlgorithmsConfig.ConfigSequence import groupBlocks
8from AnalysisAlgorithmsConfig.ConfigAccumulator import (
9 DataType, ConfigDeprecationWarning, JetUncertaintyWarning)
10from AthenaCommon.SystemOfUnits import GeV
11from AthenaConfiguration.Enums import LHCPeriod
12import re
13import warnings
14
15# FTAG decorations on the UFO large-R jets, used by the Xbb calibration (GN3XPV01_hbb_bjr)
16_largeRJetFTagDecorations = ['bJR10v01_pt', 'bJR10v01_mass'] + [
17 f'GN3XPV01_p{flavour}' for flavour in
18 ['hbb', 'hcc', 'htautauhad', 'qcdbb', 'qcdbx', 'qcdcx', 'qcdll', 'top', 'Wqq']]
19
20
21def _resolveJetCollectionName(jetCollection):
22 """Map the PHYSLITE jet collection aliases onto the actual collection names."""
23 if jetCollection == "AnalysisJets":
24 return "AntiKt4EMPFlowJets"
25 elif jetCollection == "AnalysisLargeRJets":
26 return "AntiKt10UFOCSSKSoftDropBeta100Zcut10Jets"
27 return jetCollection
28
29
30def _addJetUncertaintiesTool(config, alg, toolName, jetCollectionName, configFile,
31 calibArea, mcType, isData, pseudoData):
32 """Add a private JetUncertaintiesTool to `alg` under property `toolName`
33 and configure it."""
34 config.addPrivateTool( toolName, 'JetUncertaintiesTool' )
35 tool = getattr(alg, toolName)
36 tool.JetDefinition = jetCollectionName[:-4]
37 tool.ConfigFile = configFile
38 if calibArea is not None:
39 tool.CalibArea = calibArea
40 tool.MCType = mcType
41 tool.IsData = isData
42 tool.PseudoDataJERsmearingMode = pseudoData
43 return tool
44
45
46def _parseJetCollection(jetCollection):
47 """Parse a jet collection name into its components.
48
49 Returns (radius, jetInput, trim, hasBTag) where:
50 radius -- the jet radius parameter (2, 4, 6, or 10)
51 jetInput -- the input type string (e.g. 'EMPFlow', 'UFO', ...)
52 trim -- the trimming suffix string, or None
53 hasBTag -- whether the original collection name had a '_BTagging' suffix
54 """
55 hasBTag = False
56 btIndex = jetCollection.find('_BTagging')
57 if btIndex != -1:
58 jetCollection = jetCollection[:btIndex]
59 hasBTag = True
60
61 jetCollectionName = _resolveJetCollectionName(jetCollection)
62
63 collection_pattern = re.compile(
64 r"AntiKt(\d+)(EMTopo|EMPFlow|LCTopo|TrackCaloCluster|UFO|Track|HI)"
65 r"(TrimmedPtFrac5SmallR20|CSSKSoftDropBeta100Zcut10)?Jets")
66 match = collection_pattern.match(jetCollectionName)
67 if not match:
68 raise ValueError(
69 f"Jet collection {jetCollectionName} does not match expected pattern!")
70 radius = int(match.group(1))
71 if radius not in [2, 4, 6, 10]:
72 raise ValueError(
73 f"Jet collection has unsupported radius '{radius}'!")
74 jetInput = match.group(2)
75 trim = match.group(3)
76 return radius, jetInput, trim, hasBTag
77
78
79class PreJetAnalysisConfig (ConfigBlock) :
80 """the ConfigBlock for the common preprocessing of jet sequences"""
81
82 def __init__ (self) :
83 super().__init__()
84 self.addOption ('containerName', '', type=str,
85 noneAction='error',
86 info="the name of the output container after calibration.",
87 meta={'role':'container'})
88 self.addOption ('jetCollection', '', type=str,
89 noneAction='error',
90 info="the jet container to run on. It is interpreted to determine "
91 "the correct config blocks to call for small- or large-R jets.")
92 self.addOption('outputTruthLabelIDs', False, type=bool,
93 info='enable or disable `HadronConeExclTruthLabelID` and `PartonTruthLabelID` decorations.')
94 self.addOption ('runOriginalObjectLink', False, type=bool,
95 info='sets up an instance of `CP::AsgOriginalObjectLinkAlg` to link systematically-varied containers to the base one.')
96 self.addOption ('runGhostMuonAssociation', None, type=bool,
97 info="whether to set up the jet-ghost-muon association algorithm "
98 "`CP::JetGhostMuonAssociationAlg`. If left empty, automatically defaults to `False` for PHYSLITE and `True` otherwise.")
99 self.addOption ('runTruthJetTagging', True, type=bool,
100 info="whether to set up the jet truth tagging algorithm "
101 "`CP::JetTruthTagAlg`.")
102
103 def instanceName (self) :
104 """Return the instance name for this block"""
105 return self.containerName
106
107 def makeAlgs (self, config) :
108
109
110 if config.isPhyslite() and self.jetCollection == 'AntiKt4EMPFlowJets' :
111 config.setSourceName (self.containerName, "AnalysisJets", originalName = self.jetCollection)
112 elif config.isPhyslite() and self.jetCollection == 'AntiKt10UFOCSSKSoftDropBeta100Zcut10Jets' :
113 config.setSourceName (self.containerName, "AnalysisLargeRJets", originalName = self.jetCollection)
114 else :
115 config.setSourceName (self.containerName, self.jetCollection, originalName = self.jetCollection)
116
117 # Parse and store jet collection metadata for downstream blocks
118 radius, jetInput, trim, hasBTag = _parseJetCollection(self.jetCollection)
119 config.setContainerMeta(self.containerName, 'jetRadius', radius)
120 config.setContainerMeta(self.containerName, 'jetInput', jetInput)
121 config.setContainerMeta(self.containerName, 'jetTrim', trim)
122 config.setContainerMeta(self.containerName, 'hasBTag', hasBTag)
123 config.setContainerMeta(self.containerName, 'jetCollectionName',
125
126 # Relink original jets in case of b-tagging calibration
127 if self.runOriginalObjectLink or hasBTag :
128 alg = config.createAlgorithm( 'CP::AsgOriginalObjectLinkAlg',
129 'JetOriginalObjectLinkAlg',
130 reentrant=True )
131 alg.baseContainerName = self.jetCollection
132 alg.particles = config.readName (self.containerName)
133 if config.wantCopy (self.containerName) :
134 alg.particlesOut = config.copyName (self.containerName)
135 alg.preselection = config.getPreselection (self.containerName, '')
136
137 # Set up the jet ghost muon association algorithm:
138 if (self.runGhostMuonAssociation is None and not config.isPhyslite()) or \
139 (self.runGhostMuonAssociation is True):
140 alg = config.createAlgorithm( 'CP::JetGhostMuonAssociationAlg',
141 'JetGhostMuonAssociationAlg' )
142 alg.jets = config.readName (self.containerName)
143 if config.isPhyslite():
144 alg.muons = "AnalysisMuons"
145 if config.wantCopy (self.containerName) :
146 alg.jetsOut = config.copyName (self.containerName)
147 taggerName = "GN2HLv01" if config.geometry() >= LHCPeriod.Run4 else "GN2v01"
148 extraInputs = [
149 ( 'xAOD::JetContainer' , f"StoreGateSvc+{self.jetCollection}.DFCommonJets_jetClean_LooseBad"),
150 ( 'xAOD::JetContainer' , f"StoreGateSvc+{self.jetCollection}.DFCommonJets_jetClean_TightBad"),
151 ( 'xAOD::JetContainer' , f"StoreGateSvc+{self.jetCollection}.{taggerName}_pb"),
152 ( 'xAOD::JetContainer' , f"StoreGateSvc+{self.jetCollection}.{taggerName}_pc"),
153 ( 'xAOD::JetContainer' , f"StoreGateSvc+{self.jetCollection}.{taggerName}_ptau"),
154 ( 'xAOD::JetContainer' , f"StoreGateSvc+{self.jetCollection}.{taggerName}_pu")]
155 config.setExtraInputs (extraInputs)
156
157 if self.runTruthJetTagging and config.dataType() is not DataType.Data:
158 # Decorate jets with isHS labels (required to retrieve Jvt SFs)
159 alg = config.createAlgorithm( 'CP::JetDecoratorAlg', 'JetPileupLabelAlg' )
160 config.addPrivateTool( 'decorator', 'JetPileupLabelingTool' )
161 alg.jets = config.readName (self.containerName)
162 alg.jetsOut = config.copyName (self.containerName)
163 alg.decorator.RecoJetContainer = alg.jetsOut.replace ('%SYS%', 'NOSYS')
164 alg.decorator.SuppressOutputDependence=True
165 if self.jetCollection == 'AntiKt10UFOCSSKSoftDropBeta100Zcut10Jets' :
166 extraInputs = [
167 ( 'xAOD::JetContainer' , f"StoreGateSvc+{self.jetCollection}.{decoration}")
168 for decoration in _largeRJetFTagDecorations]
169 config.setExtraInputs (extraInputs)
170
171 # Set up shallow copy if needed and not yet done
172 if config.wantCopy (self.containerName) :
173 alg = config.createAlgorithm( 'CP::AsgShallowCopyAlg', 'JetShallowCopyAlg' )
174 alg.input = config.readName (self.containerName)
175 alg.output = config.copyName (self.containerName)
176 alg.outputType = 'xAOD::JetContainer'
177 if self.jetCollection == 'AntiKt10UFOCSSKSoftDropBeta100Zcut10Jets' :
178 alg.declareDecorations = _largeRJetFTagDecorations
179
180 config.addOutputVar (self.containerName, 'pt', 'pt', auxType="float")
181 config.addOutputVar (self.containerName, 'eta', 'eta', noSys=True, auxType="float")
182 config.addOutputVar (self.containerName, 'phi', 'phi', noSys=True, auxType="float")
183 config.addOutputVar (self.containerName, 'charge', 'charge', noSys=True, enabled=False)
184
185
186 if self.outputTruthLabelIDs and config.dataType() is not DataType.Data:
187 config.addOutputVar (self.containerName, 'HadronConeExclTruthLabelID', 'HadronConeExclTruthLabelID', noSys=True, auxType="int")
188 config.addOutputVar (self.containerName, 'PartonTruthLabelID', 'PartonTruthLabelID', noSys=True, auxType="int")
189
190
191
192class SmallRJetAnalysisConfig (ConfigBlock) :
193 """the ConfigBlock for the small-r jet sequence"""
194
195 def __init__ (self) :
196 super().__init__()
197 self.addOption ('containerName', '', type=str,
198 noneAction='error',
199 info="the name of the output container after calibration.",
200 meta={'role':'container'})
201 self.addOption ('jetCollection', '', type=str,
202 noneAction='error',
203 info="the jet container to run on. It is interpreted to determine "
204 "the correct config blocks to call for small- or large-R jets.")
205 self.addOption ('runJvtUpdate', False, type=bool,
206 info="whether to update the JVT.")
207 self.addOption ('runNNJvtUpdate', True, type=bool,
208 info="whether to update the NN-JVT.")
209 self.addOption ('runJvtSelection', True, type=bool,
210 info="whether to run JVT selection.")
211 self.addOption ('runFJvtSelection', False, type=bool,
212 info="whether to run forward JVT selection.")
213 self.addOption ('jvtWP', "FixedEffPt", type=str,
214 info="which Jvt WP to apply.",
215 meta={'choices':(['FixedEffPt'],1)})
216 self.addOption ('fJvtWP', "Loose", type=str,
217 info="which fJvt WP to apply.",
218 meta={'choices':(['Loose','Tight','Tighter'],1)})
219 self.addOption ('runJvtEfficiency', True, type=bool,
220 info="whether to calculate the JVT efficiency.")
221 self.addOption ('runFJvtEfficiency', False, type=bool,
222 info="whether to calculate the forward JVT efficiency.")
223 self.addOption ('runUncertainties', True, type=bool,
224 info="whether to configure JetUncertaintiesTool.", expertMode=True)
225 self.addOption('uncertaintyAnalysisFiles', None, type=dict,
226 info="dictionary of dsids with entry corresponding to file containing gluon fraction histograms needed to calculate an analysis specific "
227 "jet flavor composition uncertainty.")
228 self.addOption ('systematicsModelJES', "Category", type=str,
229 info="the NP reduction scheme to use for JES: All, Global, Category, "
230 "Scenario. The default is Category.")
231 self.addOption ('systematicsModelJER', "Full", type=str,
232 info="the NP reduction scheme to use for JER: All, Full, Simple. The "
233 "default is Full.",
234 meta={'choices':(['All','Full','Simple'],1)})
235 self.addOption ('runJERsystematicsOnData', False, type=bool,
236 info="whether to run the All/Full JER model variations also on data samples. Expert option!",
237 expertMode=True)
238 self.addOption ('recalibratePhyslite', True, type=bool,
239 info="whether to run the `CP::JetCalibrationAlg` on PHYSLITE derivations.")
240 # Calibration tool options
241 self.addOption ('calibToolConfigFile', None, type=str,
242 info="the name of the config file to use for the jet calibration "
243 "tool. Expert option to override JetETmiss recommendations.",
244 expertMode=True)
245 self.addOption ('calibToolCalibArea', None, type=str,
246 info="name of the CVMFS area to use for the jet calibration "
247 "tool. Expert option to override JetETmiss recommendations.",
248 expertMode=True)
249 self.addOption ('calibToolCalibSeq', None, type=str,
250 info="name of the sequence to use for the jet calibration "
251 "tool (e.g. `JetArea_Residual_EtaJES_GSC`). Expert option to override "
252 "JetETmiss recommendations.",
253 expertMode=True)
254 # Uncertainties tool options
255 self.addOption ('uncertToolConfigPath', None, type=str,
256 info="name (str) of the config file to use for the jet uncertainty "
257 "tool. Expert option to override JetETmiss recommendations. The "
258 "default is None.",
259 expertMode=True)
260 self.addOption ('uncertToolCalibArea', None, type=str,
261 info="name (str) of the CVMFS area to use for the jet uncertainty "
262 "tool. Expert option to override JetETmiss recommendations. The "
263 "default is None.",
264 expertMode=True)
265 self.addOption ('uncertToolMCType', None, type=str,
266 info="data type (str) to use for the jet uncertainty tool (e.g. "
267 "'AF3' or 'MC16'). Expert option to override JetETmiss "
268 "recommendations. The default is None.",
269 expertMode=True)
270
271 def instanceName (self) :
272 """Return the instance name for this block"""
273 return self.containerName
274
275 def getUncertaintyToolSettings(self, config):
276
277 # Retrieve appropriate JES/JER recommendations for the JetUncertaintiesTool.
278 # We do this separately from the tool declaration, as we may need to set uo
279 # two such tools, but they have to be private.
280
281 jetInput = config.getContainerMeta(self.containerName, 'jetInput', failOnMiss=True)
282 # Config file:
283 config_file = None
284 if self.systematicsModelJES == "All" and self.systematicsModelJER == "All":
285 config_file = "R4_AllNuisanceParameters_AllJERNP.config"
286 elif "Scenario" in self.systematicsModelJES:
287 if self.systematicsModelJER != "Simple":
288 raise ValueError(
289 "Invalid uncertainty configuration - Scenario* systematicsModelJESs can "
290 "only be used together with the Simple systematicsModelJER")
291 config_file = f"R4_{self.systematicsModelJES}_SimpleJER.config"
292 elif self.systematicsModelJES in ["Global", "Category"] and self.systematicsModelJER in ["Simple", "Full"]:
293 config_file = f"R4_{self.systematicsModelJES}Reduction_{self.systematicsModelJER}JER.config"
294 else:
295 raise ValueError(
296 "Invalid combination of systematicsModelJES and systematicsModelJER settings: "
297 f"systematicsModelJES: {self.systematicsModelJES}, systematicsModelJER: {self.systematicsModelJER}" )
298
299 # Calibration area:
300 calib_area = None
301 if self.uncertToolCalibArea is not None:
302 calib_area = self.uncertToolCalibArea
303
304 # Expert override for config path:
305 if self.uncertToolConfigPath is not None:
306 config_file = self.uncertToolConfigPath
307 else:
308 if config.geometry() is LHCPeriod.Run2:
309 if config.dataType() is DataType.FastSim:
310 config_file = "rel22/Fall2024_PreRec/" + config_file
311 else:
312 if jetInput == "HI":
313 config_file = "HIJetUncertainties/Spring2023/HI" + config_file
314 else:
315 config_file = "rel22/Summer2023_PreRec/" + config_file
316 else:
317 if config.dataType() is DataType.FastSim:
318 config_file = "rel22/Winter2025_AF3_PreRec/" + config_file
319 else:
320 if jetInput == "HI":
321 config_file = "HIJetUncertainties/Spring2023/HI" + config_file
322 else:
323 config_file = "rel22/Winter2025_PreRec/" + config_file
324
325 # MC type:
326 mc_type = None
327 if self.uncertToolMCType is not None:
328 mc_type = self.uncertToolMCType
329 else:
330 if config.geometry() is LHCPeriod.Run2:
331 if config.dataType() is DataType.FastSim:
332 mc_type = "AF3"
333 else:
334 mc_type = "MC20"
335 else:
336 if config.dataType() is DataType.FastSim:
337 mc_type = "MC23AF3"
338 else:
339 if jetInput == "HI":
340 mc_type = "MC16"
341 else:
342 mc_type = "MC23"
343
344 return config_file, calib_area, mc_type
345
346
347 def createUncertaintyTool(self, jetUncertaintiesAlg, config, jetCollectionName, doPseudoData=False):
348
349 # Create an instance of JetUncertaintiesTool, following JetETmiss recommendations.
350 # To run Jet Energy Resolution (JER) uncertainties in the "Full" or "All" schemes,
351 # we need two sets of tools: one configured as normal (MC), the other with the
352 # exact same settings but pretending to run on data (pseudo-data).
353 # This is achieved by passing "isPseudoData=True" to the arguments.
354
355 # Retrieve the common configuration settings
356 configFile, calibArea, mcType = self.getUncertaintyToolSettings(config)
357
358 # The main tool for all JES+JER combinations
359 tool = _addJetUncertaintiesTool(config, jetUncertaintiesAlg, 'uncertaintiesTool',
360 jetCollectionName, configFile, calibArea, mcType,
361 isData=(config.dataType() is DataType.Data),
362 pseudoData=False)
363 from PathResolver import PathResolver
364 if self.uncertaintyAnalysisFiles is not None:
365 if config.dsid() in self.uncertaintyAnalysisFiles:
366 tool.AnalysisFile = PathResolver.FindCalibFile(self.uncertaintyAnalysisFiles[config.dsid()])
367
368 if config.dataType() is DataType.Data and not (doPseudoData and self.runJERsystematicsOnData):
369 # we don't want any systematics on data if we're not using the right JER model!
370 jetUncertaintiesAlg.affectingSystematicsFilter = '.*'
371 if config.dataType() is not DataType.Data and doPseudoData and not self.runJERsystematicsOnData:
372 # The secondary tool for pseudo-data JER smearing
373 _addJetUncertaintiesTool(config, jetUncertaintiesAlg, 'uncertaintiesToolPD',
374 jetCollectionName, configFile, calibArea, mcType,
375 isData=True, pseudoData=True)
376
377
378 def makeAlgs (self, config) :
379
380 # Self-select: only run for radius-4 jets
381 if config.getContainerMeta(self.containerName, 'jetRadius', failOnMiss=True) != 4:
382 return
383
384
385 jetCollectionName = config.getContainerMeta(self.containerName, 'jetCollectionName', failOnMiss=True)
386
387 jetInput = config.getContainerMeta(self.containerName, 'jetInput', failOnMiss=True)
388
389 if jetInput not in ["EMTopo", "EMPFlow", "HI"]:
390 raise ValueError(
391 f"Unsupported input type '{jetInput}' for R=0.4 jets!" )
392
393 if self.jvtWP not in ["FixedEffPt"]:
394 raise ValueError(
395 f"Unsupported NNJvt WP '{self.jvtWP}'" )
396
397 if self.fJvtWP not in ["Loose", "Tight", "Tighter"]:
398 raise ValueError(
399 f"Unsupported fJvt WP '{self.fJvtWP}'" )
400
401 if not config.isPhyslite() or self.recalibratePhyslite:
402 # Create calibration tool as public so it can be shared
403 # (e.g. with FTAG1LITE's JetCalibratedPtDecoratorAlg).
404 # Must be created before the algorithm so EventLoop
405 # initialises the tool first.
406 calibToolName = 'JetCalibTool_' + jetCollectionName[:-4]
407 calibTool = config.createPublicTool( 'JetCalibrationTool', calibToolName )
408 calibTool.JetCollection = jetCollectionName[:-4]
409 # Get the correct string to use in the config file name
410 if jetInput == "EMPFlow":
411 if config.geometry() is LHCPeriod.Run2:
412 configFile = "PreRec_R22_PFlow_ResPU_EtaJES_GSC_February23_230215.config"
413 calibTool.CalibArea = "00-04-82"
414 elif config.geometry() >= LHCPeriod.Run3:
415 configFile = "AntiKt4EMPFlow_MC23a_PreRecR22_Phase2_CalibConfig_ResPU_EtaJES_GSC_241208_InSitu.config"
416 calibTool.CalibArea = "00-04-83"
417 elif jetInput == "HI":
418 if config.geometry() is LHCPeriod.Run2:
419 configFile = "JES_MC16_HI_Jan2021_5TeV.config"
420 elif config.geometry() is LHCPeriod.Run3:
421 configFile = "AntiKt4HI_MC23_EtaJES_Run3PreRec_Run2VJet_Run3EtaInt_5p36TeV.config"
422 calibTool.CalibArea = "00-04-83"
423 else:
424 raise ValueError(
425 f"Unsupported geometry '{config.geometry()}' for HI jet calibration!")
426 else:
427 if config.dataType() is DataType.FastSim:
428 configFile = f"JES_MC16Recommendation_AFII_{jetInput}_Apr2019_Rel21.config"
429 else:
430 configFile = f"JES_MC16Recommendation_Consolidated_{jetInput}_Apr2019_Rel21.config"
431 if self.calibToolCalibArea is not None:
432 calibTool.CalibArea = self.calibToolCalibArea
433 if self.calibToolConfigFile is not None:
434 configFile = self.calibToolConfigFile
435 calibTool.ConfigFile = configFile
436 if config.dataType() is DataType.Data:
437 if jetInput == "HI":
438 calibTool.CalibSequence = 'EtaJES_Insitu'
439 else:
440 calibTool.CalibSequence = 'JetArea_Residual_EtaJES_GSC_Insitu'
441 else:
442 if jetInput == "EMPFlow":
443 calibTool.CalibSequence = 'JetArea_Residual_EtaJES_GSC'
444 elif jetInput == "HI":
445 calibTool.CalibSequence = 'EtaJES'
446 else:
447 calibTool.CalibSequence = 'JetArea_Residual_EtaJES_GSC_Smear'
448 if self.calibToolCalibSeq is not None:
449 calibTool.CalibSequence = self.calibToolCalibSeq
450 calibTool.IsData = (config.dataType() is DataType.Data)
451 # Prepare the jet calibration algorithm
452 alg = config.createAlgorithm( 'CP::JetCalibrationAlg', 'JetCalibrationAlg' )
453 alg.HIsetup = jetInput == "HI"
454 alg.calibrationTool = f'{calibTool.getType()}/{calibTool.getName()}'
455 alg.jets = config.readName (self.containerName)
456 alg.jetsOut = config.copyName (self.containerName)
457
458 # Jet uncertainties
460 alg = config.createAlgorithm( 'CP::JetUncertaintiesAlg', 'JetUncertaintiesAlg' )
461 self.createUncertaintyTool(alg, config, jetCollectionName, doPseudoData=( self.systematicsModelJER in ["Full","All"] ))
462 alg.jets = config.readName (self.containerName)
463 alg.jetsOut = config.copyName (self.containerName)
464 alg.preselection = config.getPreselection (self.containerName, '')
465
466 # Set up the JVT update algorithm:
467 if self.runJvtUpdate :
468 alg = config.createAlgorithm( 'CP::JvtUpdateAlg', 'JvtUpdateAlg' )
469 config.addPrivateTool( 'jvtTool', 'JetVertexTaggerTool' )
470 alg.jvtTool.JetContainer = self.jetCollection
471 alg.jvtTool.SuppressInputDependence=True
472 alg.jets = config.readName (self.containerName)
473 alg.jetsOut = config.copyName (self.containerName)
474 alg.preselection = config.getPreselection (self.containerName, '')
475
477 assert jetInput=="EMPFlow", "NN JVT only defined for PFlow jets"
478 alg = config.createAlgorithm( 'CP::JetDecoratorAlg', 'NNJvtUpdateAlg' )
479 config.addPrivateTool( 'decorator', 'JetPileupTag::JetVertexNNTagger' )
480 alg.jets = config.readName (self.containerName)
481 alg.jetsOut = config.copyName (self.containerName)
482 # Set this actually to the *output* collection
483 alg.decorator.JetContainer = alg.jetsOut.replace ('%SYS%', 'NOSYS')
484 alg.decorator.SuppressInputDependence=True
485 alg.decorator.SuppressOutputDependence=True
486
487 # Set up the jet efficiency scale factor calculation algorithm
488 # Change the truthJetCollection property to AntiKt4TruthWZJets if preferred
490 assert jetInput=="EMPFlow", "NNJvt WPs and SFs only valid for PFlow jets"
491 warnings.warn_explicit(
492 "jvtWP, runJvtSelection and runJvtEfficiency"
493 " are deprecated - please use a"
494 " JVTWorkingPoint block instead.",
495 ConfigDeprecationWarning, filename='', lineno=0)
496
497 alg = config.createAlgorithm('CP::AsgSelectionAlg', 'JvtSelectionAlg')
498 config.addPrivateTool('selectionTool', 'CP::NNJvtSelectionTool')
499 alg.selectionTool.JetContainer = config.readName(self.containerName)
500 alg.selectionTool.JvtMomentName = "NNJvt"
501 alg.selectionTool.WorkingPoint = self.jvtWP
502 alg.selectionTool.MaxPtForJvt = 60*GeV
503 alg.selectionDecoration = "jvt_selection,as_char"
504 alg.particles = config.readName(self.containerName)
505
506 if self.runJvtEfficiency and config.dataType() is not DataType.Data:
507 alg = config.createAlgorithm( 'CP::JvtEfficiencyAlg', 'JvtEfficiencyAlg' )
508 config.addPrivateTool( 'efficiencyTool', 'CP::NNJvtEfficiencyTool' )
509 alg.efficiencyTool.JetContainer = config.readName(self.containerName)
510 alg.efficiencyTool.MaxPtForJvt = 60*GeV
511 alg.efficiencyTool.WorkingPoint = self.jvtWP
512 if config.geometry() is LHCPeriod.Run2:
513 alg.efficiencyTool.SFFile = "JetJvtEfficiency/May2024/NNJvtSFFile_Run2_EMPFlow.root"
514 else:
515 alg.efficiencyTool.SFFile = "JetJvtEfficiency/May2024/NNJvtSFFile_Run3_EMPFlow.root"
516 alg.selection = 'jvt_selection,as_char'
517 alg.scaleFactorDecoration = 'jvt_effSF_%SYS%'
518 alg.outOfValidity = 2
519 alg.outOfValidityDeco = 'no_jvt'
520 alg.skipBadEfficiency = False
521 alg.jets = config.readName (self.containerName)
522 alg.preselection = config.getPreselection (self.containerName, '')
523 config.addOutputVar (self.containerName, alg.scaleFactorDecoration, 'jvtEfficiency', auxType="float")
524 config.addSelection (self.containerName, 'baselineJvt', 'jvt_selection,as_char', preselection=False)
525
527 assert jetInput=="EMPFlow", "fJvt WPs and SFs only valid for PFlow jets"
528 warnings.warn_explicit(
529 "fJvtWP, runFJvtSelection and runFJvtEfficiency"
530 " are deprecated - please use a"
531 " FJVTWorkingPoint block instead.",
532 ConfigDeprecationWarning, filename='', lineno=0)
533
534 alg = config.createAlgorithm('CP::AsgSelectionAlg', 'FJvtSelectionAlg')
535 config.addPrivateTool('selectionTool', 'CP::FJvtSelectionTool')
536 alg.selectionTool.JetContainer = config.readName(self.containerName)
537 alg.selectionTool.JvtMomentName = "DFCommonJets_fJvt"
538 alg.selectionTool.WorkingPoint = self.fJvtWP
539 alg.selectionDecoration = "fjvt_selection,as_char"
540 alg.particles = config.readName(self.containerName)
541
542 if self.runFJvtEfficiency and config.dataType() is not DataType.Data:
543 alg = config.createAlgorithm( 'CP::JvtEfficiencyAlg', 'FJvtEfficiencyAlg' )
544 config.addPrivateTool( 'efficiencyTool', 'CP::FJvtEfficiencyTool' )
545 alg.efficiencyTool.JetContainer = config.readName(self.containerName)
546 alg.efficiencyTool.WorkingPoint = self.fJvtWP
547 if config.geometry() is LHCPeriod.Run2:
548 alg.efficiencyTool.SFFile = "JetJvtEfficiency/May2024/fJvtSFFile_Run2_EMPFlow.root"
549 else:
550 alg.efficiencyTool.SFFile = "JetJvtEfficiency/May2024/fJvtSFFile_Run3_EMPFlow.root"
551 alg.selection = 'fjvt_selection,as_char'
552 alg.scaleFactorDecoration = 'fjvt_effSF_%SYS%'
553 alg.outOfValidity = 2
554 alg.outOfValidityDeco = 'no_fjvt'
555 alg.skipBadEfficiency = False
556 alg.jets = config.readName (self.containerName)
557 alg.preselection = config.getPreselection (self.containerName, '')
558 config.addOutputVar (self.containerName, alg.scaleFactorDecoration, 'fjvtEfficiency', auxType="float")
559 config.addSelection (self.containerName, 'baselineFJvt', 'fjvt_selection,as_char', preselection=False)
560
561 # Additional decorations
562 alg = config.createAlgorithm( 'CP::AsgEnergyDecoratorAlg', 'AsgEnergyDecoratorAlg' )
563 alg.particles = config.readName (self.containerName)
564
565 config.addOutputVar (self.containerName, 'e_%SYS%', 'e', auxType="float")
566
567
568class RScanJetAnalysisConfig (ConfigBlock) :
569 """the ConfigBlock for the r-scan jet sequence"""
570
571 def __init__ (self) :
572 super().__init__()
573 self.addOption ('containerName', '', type=str,
574 noneAction='error',
575 info="the name of the output container after calibration.",
576 meta={'role':'container'})
577 self.addOption ('jetCollection', '', type=str,
578 noneAction='error',
579 info="the jet container to run on. It is interpreted to determine "
580 "the correct config blocks to call for small- or large-R jets.")
581 self.addOption ('recalibratePhyslite', True, type=bool,
582 info="whether to run the CP::JetCalibrationAlg on PHYSLITE "
583 "derivations. The default is True.")
584
585 def instanceName (self) :
586 """Return the instance name for this block"""
587 return self.containerName
588
589 def makeAlgs (self, config) :
590
591 # Self-select: only run for r-scan jets (radius 2 or 6)
592 radius = config.getContainerMeta(self.containerName, 'jetRadius', failOnMiss=True)
593 if radius not in [2, 6]:
594 return
595
596 jetCollectionName = config.getContainerMeta(self.containerName, 'jetCollectionName', failOnMiss=True)
597
598 jetInput = config.getContainerMeta(self.containerName, 'jetInput', failOnMiss=True)
599
600 if not config.isPhyslite() or self.recalibratePhyslite:
601 if jetInput not in ["LCTopo", "HI"]:
602 raise ValueError(
603 f"Unsupported input type '{jetInput}' for R-scan jets!" )
604 # Create calibration tool before algorithm (EventLoop ordering)
605 calibToolName = 'JetCalibTool_' + jetCollectionName[:-4]
606 calibTool = config.createPublicTool( 'JetCalibrationTool', calibToolName )
607 calibTool.JetCollection = jetCollectionName[:-4]
608 if jetInput=="LCTopo":
609 calibTool.ConfigFile = \
610 f"JES_MC16Recommendation_Rscan{radius}LC_Feb2022_R21.config"
611 if config.dataType() is DataType.Data:
612 calibTool.CalibSequence = "JetArea_Residual_EtaJES_GSC_Insitu"
613 else:
614 calibTool.CalibSequence = "JetArea_Residual_EtaJES_GSC_Smear"
615 elif jetInput=="HI":
616 calibTool.ConfigFile = \
617 "JES_MC16_HI_Jan2021_5TeV.config"
618 if config.dataType() is DataType.Data:
619 calibTool.CalibSequence = "EtaJES_Insitu"
620 else:
621 calibTool.CalibSequence = "EtaJES"
622 calibTool.IsData = (config.dataType() is DataType.Data)
623 # Prepare the jet calibration algorithm
624 alg = config.createAlgorithm( 'CP::JetCalibrationAlg', 'JetCalibrationAlg' )
625 alg.HIsetup = jetInput == "HI"
626 alg.calibrationTool = f'{calibTool.getType()}/{calibTool.getName()}'
627 alg.jets = config.readName (self.containerName)
628 warnings.warn_explicit(
629 "Uncertainties for R-Scan jets are not yet released!",
630 JetUncertaintyWarning, filename='', lineno=0)
631
632
633class LargeRJetAnalysisConfig (ConfigBlock) :
634 """the ConfigBlock for the large-r jet sequence"""
635
636 def __init__ (self) :
637 super().__init__()
638 self.addOption ('containerName', '', type=str,
639 noneAction='error',
640 info="the name of the output container after calibration.",
641 meta={'role':'container'})
642 self.addOption ('jetCollection', '', type=str,
643 noneAction='error',
644 info="the jet container to run on. It is interpreted to determine "
645 "the correct config blocks to call for small- or large-R jets.")
646 self.addOption ('recalibratePhyslite', True, type=bool,
647 info="whether to run the CP::JetCalibrationAlg on PHYSLITE "
648 "derivations. The default is True.")
649 self.addOption ('runUncertainties', True, type=bool,
650 info="whether to configure JetUncertaintiesTool.", expertMode=True )
651 self.addOption ('systematicsModelJER', "Full", type=str,
652 info="the NP reduction scheme to use for JER: Full, Simple. The default is Full.",
653 meta={'choices':(['Simple','Full'],1)})
654 self.addOption ('systematicsModelJMS', "Full", type=str,
655 info="the NP reduction scheme to use for JMS: Full, Simple. The default is Full.",
656 meta={'choices':(['Simple','Full'],1)})
657 self.addOption ('systematicsModelJMR', "Full", type=str,
658 info="the NP reduction scheme to use for JMR: Full, Simple. The default is Full.",
659 meta={'choices':(['Full','Simple'],1)})
660 self.addOption ('runJERsystematicsOnData', False, type=bool,
661 info="whether to run the All/Full JER model variations also on data samples. Expert option!",
662 expertMode=True)
663 # Adding these options to override the jet uncertainty config file when we have new recommendations
664 # Calibration tool options
665 self.addOption ('calibToolConfigFile', None, type=str,
666 info="name of the config file to use for the jet calibration "
667 "tool. Expert option to override JetETmiss recommendations.",
668 expertMode=True)
669 self.addOption ('calibToolCalibArea', None, type=str,
670 info="name of the CVMFS area to use for the jet calibration "
671 "tool. Expert option to override JetETmiss recommendations.",
672 expertMode=True)
673 self.addOption ('calibToolCalibSeq', None, type=str,
674 info="name of the sequence to use for the jet calibration "
675 "tool (e.g. `JetArea_Residual_EtaJES_GSC`). Expert option to override "
676 "JetETmiss recommendations.",
677 expertMode=True)
678 # Uncertainties tool options
679 self.addOption ('uncertToolConfigPath', None, type=str,
680 info="name of the config file to use for the JES, JER, and JMS uncertainty "
681 "tool. Expert option to override JetETmiss recommendations.",
682 expertMode=True)
683 self.addOption ('uncertToolConfigPathJMR', None, type=str,
684 info="name of the config file to use for the JMR uncertainty "
685 "tool. Expert option to override JetETmiss recommendations.",
686 expertMode=True)
687 self.addOption ('uncertToolCalibArea', None, type=str,
688 info="name (str) of the CVMFS area to use for the jet uncertainty "
689 "tool. Expert option to override JetETmiss recommendations. The "
690 "default is None.",
691 expertMode=True)
692 self.addOption ('uncertToolMCType', None, type=str,
693 info="data type (str) to use for the jet uncertainty tool (e.g. "
694 "'AF3' or 'MC16'). Expert option to override JetETmiss "
695 "recommendations. The default is None.",
696 expertMode=True)
697 self.addOption ('minPt', 200.*GeV, type=float,
698 info=r"the minimum $p_\mathrm{T}$ cut (in MeV) to apply to calibrated large-R jets.")
699 self.addOption ('maxPt', 3000.*GeV, type=float,
700 info=r"the maximum $p_\mathrm{T}$ cut (in MeV) to apply to calibrated large-R jets.")
701 self.addOption ('maxEta', 0., type=float,
702 info=r"the maximum $\vert\eta\vert$ cut to apply to calibrated large-R jets.")
703 self.addOption ('maxRapidity', 2., type=float,
704 info="the maximum rapidity cut to apply to calibrated large-R jets.")
705 self.addOption ('minMass', 40.*GeV, type=float,
706 info="the minimum mass cut (in MeV) to apply to calibrated large-R jets.")
707 self.addOption ('maxMass', 600.*GeV, type=float,
708 info="the maximum mass cut (in MeV) to apply to calibrated large-R jets.")
709
710 def instanceName (self) :
711 """Return the instance name for this block"""
712 return self.containerName
713
714 def getUncertaintyToolSettings(self, config):
715 # Retrieve appropriate JES/JER recommendations for the JetUncertaintiesTool.
716 # We do this separately from the tool declaration, as we may need to set uo
717 # two such tools, but they have to be private.
718
719
720 # Config file:
721 config_file = None
722 if self.systematicsModelJER in ["Simple", "Full"] and self.systematicsModelJMS in ["Simple", "Full"]:
723 config_file = f"R10_CategoryJES_{self.systematicsModelJER}JER_{self.systematicsModelJMS}JMS.config"
724 else:
725 raise ValueError(
726 "Invalid request for systematicsModelJER/JMS settings: "
727 f"systematicsModelJER = '{self.systematicsModelJER}', "
728 f"systematicsModelJMS = '{self.systematicsModelJMS}'" )
729 if self.uncertToolConfigPath is not None:
730 # Expert override
731 config_file = self.uncertToolConfigPath
732 else:
733 if config.geometry() in [LHCPeriod.Run2, LHCPeriod.Run3]:
734 config_file = "rel22/Summer2025_PreRec/" + config_file
735 else:
736 warnings.warn_explicit(
737 "Uncertainties for UFO jets are not available for Run 4!",
738 JetUncertaintyWarning, filename='', lineno=0)
739
740
741 # Calibration area:
742 calib_area = None
743 if self.uncertToolCalibArea is not None:
744 calib_area = self.uncertToolCalibArea
745
746 # MC type:
747 if self.uncertToolMCType is not None:
748 mc_type = self.uncertToolMCType
749 else:
750 if config.dataType() is DataType.FastSim:
751 if config.geometry() is LHCPeriod.Run2:
752 mc_type = "MC20AF3"
753 else:
754 mc_type = "MC23AF3"
755 else:
756 if config.geometry() is LHCPeriod.Run2:
757 mc_type = "MC20"
758 else:
759 mc_type = "MC23"
760
761 return config_file, calib_area, mc_type
762
763 def createUncertaintyTool(self, jetUncertaintiesAlg, config, jetCollectionName, doPseudoData=False):
764 '''
765 Create instance(s) of JetUncertaintiesTool following JetETmiss recommendations.
766
767 JER uncertainties under the "Full" scheme must be run on MC samples twice:
768 1. Normal (MC) mode,
769 2. Pseudodata (PD) mode, as if the events are Data.
770 '''
771
772 # Retrieve the common configuration settings
773 configFile, calibArea, mcType = self.getUncertaintyToolSettings(config)
774
775 # The main tool for all JER combinations
776 _addJetUncertaintiesTool(config, jetUncertaintiesAlg, 'uncertaintiesTool',
777 jetCollectionName, configFile, calibArea, mcType,
778 isData=(config.dataType() is DataType.Data),
779 pseudoData=False)
780
781 # JER smearing on data
782 if config.dataType() is DataType.Data and not (doPseudoData and self.runJERsystematicsOnData):
783 # we don't want any systematics on data if we're not using the right JER model!
784 jetUncertaintiesAlg.affectingSystematicsFilter = '.*'
785
786 if config.dataType() is not DataType.Data and doPseudoData and not self.runJERsystematicsOnData:
787 # The secondary tool for pseudo-data JER smearing
788 _addJetUncertaintiesTool(config, jetUncertaintiesAlg, 'uncertaintiesToolPD',
789 jetCollectionName, configFile, calibArea, mcType,
790 isData=True, pseudoData=True)
791
792 def createFFSmearingTool(self, jetFFSmearingAlg, config):
793 # Retrieve appropriate large-R jet mass resolution recommendations for the FFJetSmearingTool.
794
795 # Config file:
796 if self.systematicsModelJMR in ["Simple", "Full"]:
797 config_file = f"R10_{self.systematicsModelJMR}JMR.config"
798 else:
799 raise ValueError(
800 f"Invalid request for systematicsModelJMR settings: {self.systematicsModelJMR}"
801 )
802
803 # Expert override for config path:
804 if self.uncertToolConfigPathJMR is not None:
805 config_file = self.uncertToolConfigPathJMR
806 else:
807 config_file = "rel22/Summer2025_PreRec/" + config_file
808 if config.geometry() is LHCPeriod.Run4:
809 warnings.warn_explicit(
810 "Uncertainties for UFO jets are not for Run 4!",
811 JetUncertaintyWarning, filename='', lineno=0)
812
813 # MC type:
814 if config.geometry() is LHCPeriod.Run2:
815 if config.dataType() is DataType.FastSim:
816 mc_type = "MC20AF3"
817 else:
818 mc_type = "MC20"
819 elif config.geometry() >= LHCPeriod.Run3:
820 if config.dataType() is DataType.FastSim:
821 mc_type = "MC23AF3"
822 else:
823 mc_type = "MC23"
824
825 # Set up the FF smearing tool
826 config.addPrivateTool( 'FFSmearingTool', 'CP::FFJetSmearingTool')
827 jetFFSmearingAlg.FFSmearingTool.MassDef = "UFO"
828 jetFFSmearingAlg.FFSmearingTool.MCType = mc_type
829 jetFFSmearingAlg.FFSmearingTool.ConfigFile = config_file
830
831 def makeAlgs (self, config) :
832
833 # Self-select: only run for large-R (radius 10) jets
834 if config.getContainerMeta(self.containerName, 'jetRadius', failOnMiss=True) != 10:
835 return
836
837 jetCollectionName = config.getContainerMeta(self.containerName, 'jetCollectionName', failOnMiss=True)
838
839 jetInput = config.getContainerMeta(self.containerName, 'jetInput', failOnMiss=True)
840 trim = config.getContainerMeta(self.containerName, 'jetTrim', failOnMiss=True)
841
842 if jetInput not in ["UFO"]:
843 raise ValueError(f"Invalid input type '{jetInput}' for large-R jets!" )
844
845 if not trim:
846 raise ValueError("Untrimmed large-R jets are not supported!")
847
848 configFile = "JES_MC20PreRecommendation_R10_UFO_CSSK_SoftDrop_JMS_R21Insitu_26Nov2024.config"
849 calibArea = "00-04-83"
850 if self.calibToolConfigFile is not None:
851 configFile = self.calibToolConfigFile
852
853 if config.dataType() is not DataType.Data:
854 calibSeq = "EtaJES_JMS"
855 else:
856 calibSeq = "EtaJES_JMS_Insitu"
857 if self.calibToolCalibSeq is not None:
858 calibSeq = self.calibToolCalibSeq
859
860 if self.calibToolCalibArea is not None:
861 calibArea = self.calibToolCalibArea
862
863 if not config.isPhyslite() or self.recalibratePhyslite:
864 # Create calibration tool before algorithm (EventLoop ordering)
865 calibToolName = 'JetCalibTool_' + jetCollectionName[:-4]
866 calibTool = config.createPublicTool( 'JetCalibrationTool', calibToolName )
867
868 calibTool.JetCollection = jetCollectionName[:-4]
869
870 calibTool.ConfigFile = configFile
871
872 calibTool.CalibSequence = calibSeq
873
874 if calibArea is not None:
875 calibTool.CalibArea = calibArea
876
877 calibTool.IsData = (config.dataType() is DataType.Data)
878 # Prepare the jet calibration algorithm
879 alg = config.createAlgorithm( 'CP::JetCalibrationAlg', 'JetCalibrationAlg' )
880 alg.calibrationTool = f'{calibTool.getType()}/{calibTool.getName()}'
881 alg.jets = config.readName(self.containerName)
882 alg.jetsOut = config.copyName(self.containerName)
883
884 # Jet uncertainties
885 if config.dataType() in [DataType.FullSim, DataType.FastSim] and self.runUncertainties:
886 alg = config.createAlgorithm( 'CP::JetUncertaintiesAlg', 'JetUncertaintiesAlg' )
887 self.createUncertaintyTool(alg, config, jetCollectionName, doPseudoData=( self.systematicsModelJER in ["Full","All"] ))
888
889 # R=1.0 jets have a validity range
890 alg.outOfValidity = 2 # SILENT
891 alg.outOfValidityDeco = 'outOfValidity'
892
893 alg.jets = config.readName (self.containerName)
894 alg.jetsOut = config.copyName (self.containerName)
895 alg.preselection = config.getPreselection (self.containerName, '')
896
897 if config.dataType() is not DataType.Data:
898 # set up the FF smearing algorithm
899 alg = config.createAlgorithm( 'CP::JetFFSmearingAlg', 'JetFFSmearingAlg' )
900 self.createFFSmearingTool(alg, config)
901 alg.outOfValidity = 2 # SILENT
902 alg.outOfValidityDeco = 'outOfValidityJMR'
903 alg.jets = config.readName (self.containerName)
904 alg.jetsOut = config.copyName (self.containerName)
905 alg.preselection = config.getPreselection (self.containerName, '')
906
907 if self.minPt > 0 or self.maxPt > 0 or self.maxEta > 0 or self.maxRapidity > 0:
908 # Set up the the pt-eta selection
909 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'JetPtEtaCutAlg' )
910 alg.selectionDecoration = 'selectPtEta,as_bits'
911 config.addPrivateTool( 'selectionTool', 'CP::AsgPtEtaSelectionTool' )
912 alg.selectionTool.minPt = self.minPt
913 alg.selectionTool.maxPt = self.maxPt
914 alg.selectionTool.maxEta = self.maxEta
915 alg.selectionTool.maxRapidity = self.maxRapidity
916 alg.particles = config.readName (self.containerName)
917 alg.preselection = config.getPreselection (self.containerName, '')
918 config.addSelection (self.containerName, '', alg.selectionDecoration,
919 preselection=True)
920
921 if self.minMass > 0 or self.maxMass > 0:
922 # Set up the the mass selection
923 alg = config.createAlgorithm( 'CP::AsgSelectionAlg', 'JetMassCutAlg' )
924 alg.selectionDecoration = 'selectMass,as_bits'
925 config.addPrivateTool( 'selectionTool', 'CP::AsgMassSelectionTool' )
926 alg.selectionTool.minM = self.minMass
927 alg.selectionTool.maxM = self.maxMass
928 alg.particles = config.readName (self.containerName)
929 alg.preselection = config.getPreselection (self.containerName, '')
930 config.addSelection (self.containerName, '', alg.selectionDecoration,
931 preselection=True)
932
933 config.addOutputVar (self.containerName, 'm', 'm', auxType="float")
934
935class _JvtWorkingPointBase (ConfigBlock) :
936 """common base for the Jvt and fJvt working point config blocks
937
938 The concrete blocks combine one of these bases with a parameter class
939 (`_NNJvtParameters` or `_FJvtParameters`)."""
940
941 def __init__ (self) :
942 super().__init__()
943 self.setBlockName(self.__class__.__name__)
944 self.addOption ('containerName', '', type=str,
945 noneAction='error',
946 info="the name of the input container.",
947 meta={'role':'containerRef'})
948 self.addOption ('selectionName', '', type=str,
949 noneAction='error',
950 info="the name of the jet selection to define (e.g. `tight` or `loose`).",
951 meta={'role':'selection'})
952 self.addOption (self._wpOption, '', type=str,
953 noneAction='error',
954 info=self._wpInfo,
955 meta={'choices':(self._wpChoices,1)})
956 self.addOption ('useSuffix', True, type=bool,
957 info="whether the working point name is to be used as suffix ."
958 "Not to be disabled if multiple working points are scheduled.")
959
960 def instanceName (self) :
961 return self.containerName + '_' + self.selectionName
962
963 def workingPoint (self) :
964 return getattr(self, self._wpOption)
965
966 def suffix (self) :
967 return f"_{self.workingPoint()}" if self.useSuffix else ""
968
969
971 """common base for the Jvt and fJvt working point selection blocks"""
972
973 def makeAlgs (self, config) :
974
975 suffix = self.suffix()
976 decorationName = f"{self._prefix}_selection{suffix},as_char"
977 selectionName = self.selectionName
978
979 alg = config.createAlgorithm('CP::AsgSelectionAlg', f'{self._algPrefix}SelectionAlg_{self.workingPoint()}')
980 config.addPrivateTool('selectionTool', self._selectionTool)
981 alg.selectionTool.JetContainer = config.readName(self.containerName)
982 alg.selectionTool.JvtMomentName = self._momentName
983 alg.selectionTool.WorkingPoint = self.workingPoint()
984 if self._maxPtForJvt is not None:
985 alg.selectionTool.MaxPtForJvt = self._maxPtForJvt
986 alg.selectionDecoration = decorationName
987 alg.particles = config.readName(self.containerName)
988
989 config.addSelection (self.containerName, selectionName, decorationName, preselection=False)
990
991
993 """common base for the Jvt and fJvt working point efficiency blocks"""
994
995 def __init__ (self) :
996 super().__init__()
997 self.addDependency('EventSelection', required=False)
998 self.addDependency('EventSelectionMerger', required=False)
999 self.addOption ('noEffSF', False, type=bool,
1000 info="disables the calculation of efficiencies and scale factors. "
1001 "Only useful to test a new WP for which scale factors are not available.",
1002 expertMode=True)
1003
1004 def makeAlgs (self, config) :
1005
1006 suffix = self.suffix()
1007 decorationName = f"{self._prefix}_selection{suffix},as_char"
1008
1009 if not self.noEffSF and config.dataType() is not DataType.Data:
1010 alg = config.createAlgorithm( 'CP::JvtEfficiencyAlg', f'{self._algPrefix}EfficiencyAlg_{self.workingPoint()}' )
1011 config.addPrivateTool( 'efficiencyTool', self._efficiencyTool )
1012 alg.efficiencyTool.JetContainer = config.readName(self.containerName)
1013 if self._maxPtForJvt is not None:
1014 alg.efficiencyTool.MaxPtForJvt = self._maxPtForJvt
1015 alg.efficiencyTool.WorkingPoint = self.workingPoint()
1016 if config.geometry() is LHCPeriod.Run2:
1017 alg.efficiencyTool.SFFile = f"JetJvtEfficiency/May2024/{self._sfFileStem}_Run2_EMPFlow.root"
1018 else:
1019 alg.efficiencyTool.SFFile = f"JetJvtEfficiency/May2024/{self._sfFileStem}_Run3_EMPFlow.root"
1020 alg.selection = decorationName
1021 alg.scaleFactorDecoration = f'{self._prefix}_effSF{suffix}_%SYS%'
1022 alg.outOfValidity = 2
1023 alg.outOfValidityDeco = f'no_{self._prefix}{suffix}'
1024 alg.skipBadEfficiency = False
1025 alg.jets = config.readName (self.containerName)
1026 alg.preselection = config.getPreselection (self.containerName, '')
1027
1028 config.addOutputVar (self.containerName, alg.scaleFactorDecoration, f'{self._prefix}Efficiency{suffix}', auxType="float")
1029
1030
1032 """common base for the Jvt and fJvt event working point efficiency blocks"""
1033
1034 def __init__ (self) :
1035 super().__init__()
1036 self.addDependency(f'{self._algPrefix}WorkingPointEfficiencyConfig', required=True)
1037 self.addDependency('OverlapRemoval', required=False)
1038 self.addDependency('EventSelection', required=False)
1039 self.addDependency('EventSelectionMerger', required=False)
1040 self.addOption ('noEffSF', False, type=bool,
1041 info="disables the calculation of efficiencies and scale factors. "
1042 "Only useful to test a new WP for which scale factors are not available.",
1043 expertMode=True)
1044 self.addOption ('eventSF', True, type=bool,
1045 info="add calculation of event-level efficiency SF.")
1046
1047 def makeAlgs (self, config) :
1048
1049 if (not self.noEffSF and self.eventSF and
1050 config.dataType() is not DataType.Data):
1051 suffix = self.suffix()
1052 alg = config.createAlgorithm( 'CP::AsgEventScaleFactorAlg', f'{self._eventSFAlgPrefix}_{self.workingPoint()}' )
1053 preselection = config.getFullSelection (self.containerName, '')
1054 alg.preselection = preselection + f'&&no_{self._prefix}{suffix}' if preselection else f'no_{self._prefix}{suffix}'
1055 alg.scaleFactorInputDecoration = f'{self._prefix}_effSF{suffix}_%SYS%'
1056 alg.scaleFactorOutputDecoration = f'{self._prefix}_effSF{suffix}_%SYS%'
1057 alg.particles = config.readName (self.containerName)
1058
1059 config.addOutputVar('EventInfo', alg.scaleFactorOutputDecoration, f'weight_{self._prefix}_effSF{suffix}', auxType="float")
1060
1061
1063 """the parameters specific to the (NN)Jvt working point blocks"""
1064 _prefix = 'jvt'
1065 _algPrefix = 'Jvt'
1066 _eventSFAlgPrefix = 'JvtEventScaleFactorAlg'
1067 _wpOption = 'jvtWP'
1068 _wpInfo = "the NNJvt WP to use. Supported WPs: `FixedEffPt`."
1069 _wpChoices = ['FixedEffPt']
1070 _selectionTool = 'CP::NNJvtSelectionTool'
1071 _efficiencyTool = 'CP::NNJvtEfficiencyTool'
1072 _momentName = "NNJvt"
1073 _maxPtForJvt = 60*GeV
1074 _sfFileStem = "NNJvtSFFile"
1075
1076
1078 """the parameters specific to the fJvt working point blocks"""
1079 _prefix = 'fjvt'
1080 _algPrefix = 'FJvt'
1081 _eventSFAlgPrefix = 'ForwardJvtEventScaleFactorAlg'
1082 _wpOption = 'fjvtWP'
1083 _wpInfo = "the fJvt WP to use. Supported WPs: `Loose`, `Tight`, `Tighter`."
1084 _wpChoices = ['Loose','Tight','Tighter']
1085 _selectionTool = 'CP::FJvtSelectionTool'
1086 _efficiencyTool = 'CP::FJvtEfficiencyTool'
1087 _momentName = "DFCommonJets_fJvt"
1088 _maxPtForJvt = None
1089 _sfFileStem = "fJvtSFFile"
1090
1091
1093 """the ConfigBlock for the Jvt working point selection"""
1094
1095
1096class JvtWorkingPointEfficiencyConfig (_NNJvtParameters, _JvtWorkingPointEfficiencyBase) :
1097 """the ConfigBlock for the Jvt working point efficiency"""
1098
1099
1101 """the ConfigBlock for the event Jvt working point efficiency"""
1102
1103
1105 """the ConfigBlock for the fJvt working point selection"""
1106
1107
1109 """the ConfigBlock for the fJvt working point efficiency"""
1110
1111
1113 """the ConfigBlock for the event fJvt working point efficiency"""
1114
1115
1116@groupBlocks
1117def Jets(seq):
1118 seq.append(PreJetAnalysisConfig())
1119 seq.append(SmallRJetAnalysisConfig())
1120 seq.append(RScanJetAnalysisConfig())
1121 seq.append(LargeRJetAnalysisConfig())
1122
1123@groupBlocks
1125 seq.append(JvtWorkingPointSelectionConfig())
1128
1129@groupBlocks
static std::string FindCalibFile(const std::string &logical_file_name)
createFFSmearingTool(self, jetFFSmearingAlg, config)
createUncertaintyTool(self, jetUncertaintiesAlg, config, jetCollectionName, doPseudoData=False)
createUncertaintyTool(self, jetUncertaintiesAlg, config, jetCollectionName, doPseudoData=False)
Definition Jets.py:1
_parseJetCollection(jetCollection)
_resolveJetCollectionName(jetCollection)
_addJetUncertaintiesTool(config, alg, toolName, jetCollectionName, configFile, calibArea, mcType, isData, pseudoData)