ATLAS Offline Software
Loading...
Searching...
No Matches
ElectronPhotonVariableNFCorrectionTool Class Reference

Normalizing Flows-based correction tool for photon MC shower shape variables. More...

#include <ElectronPhotonVariableNFCorrectionTool.h>

Inheritance diagram for ElectronPhotonVariableNFCorrectionTool:
Collaboration diagram for ElectronPhotonVariableNFCorrectionTool:

Classes

struct  SSAccessors
 Accessor used to decorate photons per shower shape variable. More...

Public Member Functions

 ElectronPhotonVariableNFCorrectionTool (const std::string &name)
 Standard constructor.
 ~ElectronPhotonVariableNFCorrectionTool ()
 Standard destructor.
virtual StatusCode initialize () override
 Initialize the class instance.
virtual const CP::CorrectionCode applyCorrection (xAOD::Photon &photon) const override
 Apply the Normalizing Flow correction to the passed photon.
virtual const CP::CorrectionCode applyCorrection (xAOD::Electron &electron) const override
 Not supported, so electrons cannot be corrected by this tool.
virtual const CP::CorrectionCode correctedCopy (const xAOD::Photon &in_photon, xAOD::Photon *&out_photon) const override
 Make a corrected copy of the passed photon.
virtual const CP::CorrectionCode correctedCopy (const xAOD::Electron &in_electron, xAOD::Electron *&out_electron) const override
 Not supported, so electrons cannot be corrected by this tool.
virtual void print () const
 Print the state of the tool.
ServiceHandle< StoreGateSvc > & evtStore ()
 The standard StoreGateSvc (event store) Returns (kind of) a pointer to the StoreGateSvc.
const ServiceHandle< StoreGateSvc > & detStore () const
 The standard StoreGateSvc/DetectorStore Returns (kind of) a pointer to the StoreGateSvc.
virtual StatusCode sysInitialize () override
 Perform system initialization for an algorithm.
virtual StatusCode sysStart () override
 Handle START transition.
virtual std::vector< Gaudi::DataHandle * > inputHandles () const override
 Return this algorithm's input handles.
virtual std::vector< Gaudi::DataHandle * > outputHandles () const override
 Return this algorithm's output handles.
Gaudi::Details::PropertyBase & declareProperty (Gaudi::Property< T, V, H > &t)
void updateVHKA (Gaudi::Details::PropertyBase &)
MsgStream & msg () const
bool msgLvl (const MSG::Level lvl) const
Additional helper functions, not directly mimicking Athena
template<class T>
const T * getProperty (const std::string &name) const
 Get one of the tool's properties.
const std::string & msg_level_name () const __attribute__((deprecated))
 A deprecated function for getting the message level's name.
const std::string & getName (const void *ptr) const
 Get the name of an object that is / should be in the event store.
SG::sgkey_t getKey (const void *ptr) const
 Get the (hashed) key of an object that is in the event store.

Protected Member Functions

void renounceArray (SG::VarHandleKeyArray &handlesArray)
 remove all handles from I/O resolution
std::enable_if_t< std::is_void_v< std::result_of_t< decltype(&T::renounce)(T)> > &&!std::is_base_of_v< SG::VarHandleKeyArray, T > &&std::is_base_of_v< Gaudi::DataHandle, T >, void > renounce (T &h)
void extraDeps_update_handler (Gaudi::Details::PropertyBase &ExtraDeps)
 Add StoreName to extra input/output deps as needed.

Private Types

enum class  ApplyToMode { TruthPhotons , All }
 NF will be applied only for TruthPhotons, or for All photons. More...
enum class  FoldStrategy { Unknown , EventNumber , EventNumberPhi }
 Fold selection strategy. More...
typedef ServiceHandle< StoreGateSvc > StoreGateSvc_t

Private Member Functions

bool passPhotonSelection (const xAOD::Photon &photon) const
 Returns true if the photon passes the pT and truthType selection.
bool passShowerShapeCuts (const std::vector< float > &ss) const
 Returns true if the shower shapes pass the cuts removing default values.
CP::CorrectionCode applyFallbackFudge (xAOD::Photon &photon, const std::vector< float > &ss) const
 Apply the fallback fudge tool to a photon failing only the shower shape cuts.
int selectFold (unsigned long long eventNumber, float phi) const
 Select fold index for the current event/photon.
FoldStrategy parseFoldStrategy (const std::string &s) const
 Parse fold strategy string from config.
Gaudi::Details::PropertyBase & declareGaudiProperty (Gaudi::Property< T, V, H > &hndl, const SG::VarHandleKeyType &)
 specialization for handling Gaudi::Property<SG::VarHandleKey>

Private Attributes

Gaudi::Property< std::string > m_configFile {this, "ConfigFile", "", "The configuration file for Normalizing Flows to use"}
 The configuration file for the tool, application mode and minimum photon pT cut in MeV.
Gaudi::Property< int > m_nFoldsOverride {this, "NFoldsOverride", -1, "If > 0, override the number of folds to use instead of the value from the config file (must not exceed NFolds in the config)"}
Gaudi::Property< std::string > m_applyToStr {this, "ApplyTo", "TruthPhotons", "TruthPhotons or All"}
Gaudi::Property< float > m_pTcutMeV {this, "pTcut", 10000.f, "Min photon pT in MeV"}
int m_nFolds {0}
 Number of model folds configured (must match tool handle array sizes).
std::string m_onnxPattern
 Models path pattern string from config.
SG::ReadHandleKey< xAOD::EventInfo > m_eventInfoKey {this, "EventInfoKey", "EventInfo", "EventInfo key"}
 ReadHandleKey for EventInfo used for fold selection.
ApplyToMode m_applyToMode {ApplyToMode::TruthPhotons}
bool m_applyShowerShapeCuts {true}
 Cuts applied to remove default values of shower shapes.
ToolHandle< IElectronPhotonShowerShapeFudgeTool > m_fallbackFudgeTool {this, "FallbackFudgeTool", "", "Fudge tool applied to photons which fail the shower shape cuts"}
 Fudge tool used for photons failing the shower shape cuts, empty = no fallback.
FoldStrategy m_foldStrategy {FoldStrategy::EventNumber}
 Selected fold strategy (configured via FoldStrategy in the config).
ToolHandleArray< AthOnnx::IOnnxRuntimeInferenceTool > m_onnxToolsForward {this, "OnnxInferenceToolsForward", {}, "Forward ONNX tools per fold"}
 ToolHandleArray for forward ONNX models (one tool per fold).
ToolHandleArray< AthOnnx::IOnnxRuntimeInferenceTool > m_onnxToolsBackward {this, "OnnxInferenceToolsBackward", {}, "Backward ONNX tools per fold"}
 ToolHandleArray for backward ONNX models (one tool per fold).
std::vector< SSAccessors > m_accessors
 Per-variable accessors aligned with s_ssVarNames.
StoreGateSvc_t m_evtStore
 Pointer to StoreGate (event store by default).
StoreGateSvc_t m_detStore
 Pointer to StoreGate (detector store by default).
std::vector< SG::VarHandleKeyArray * > m_vhka
bool m_varHandleArraysDeclared

Static Private Attributes

static constexpr float s_defaultValueThreshold = -100.f
 Original values of weta1 and wtots1 below this threshold are default values and are not fudged.
static const std::vector< std::string > s_ssVarNames
 List of shower shape variable names (order must match model I/O).
static const std::vector< xAOD::EgammaParameters::ShowerShapeType > s_ssEnums
 Egamma shower shape enum mapping for reading/writing values (order matches s_ssVarNames).

Detailed Description

Normalizing Flows-based correction tool for photon MC shower shape variables.

The tool applies a two-step NF mapping using ONNX Runtime inference:

  • Forward model: maps shower shape tenzor -> latent representation (z)
  • Backward model: maps latent representation (z) -> corrected shower shape tenzor

The correction is applied to the photon shower shape variables listed in s_ssVarNames (the order should correspond to order in a model).

The ONNX models are provided per-fold via ToolHandleArray, and the fold is selected event-by-event using EventInfo::eventNumber() (optionally including phi).

Author
Katerina Kazakova kater.nosp@m.ina..nosp@m.kazak.nosp@m.ova@.nosp@m.cern..nosp@m.ch
Date
February 2026

Definition at line 53 of file ElectronPhotonVariableNFCorrectionTool.h.

Member Typedef Documentation

◆ StoreGateSvc_t

typedef ServiceHandle<StoreGateSvc> AthCommonDataStore< AthCommonMsg< AlgTool > >::StoreGateSvc_t
privateinherited

Definition at line 376 of file AthCommonDataStore.h.

Member Enumeration Documentation

◆ ApplyToMode

NF will be applied only for TruthPhotons, or for All photons.

Enumerator
TruthPhotons 
All 

Definition at line 120 of file ElectronPhotonVariableNFCorrectionTool.h.

120{ TruthPhotons, All };

◆ FoldStrategy

Fold selection strategy.

  • EventNumber : fold = eventNumber % NFolds
  • EventNumberPhi : fold = (eventNumber + floor((phi + pi)*100)) % NFolds
Enumerator
Unknown 
EventNumber 
EventNumberPhi 

Definition at line 148 of file ElectronPhotonVariableNFCorrectionTool.h.

148{ Unknown, EventNumber, EventNumberPhi };
struct TBPatternUnitContext Unknown

Constructor & Destructor Documentation

◆ ElectronPhotonVariableNFCorrectionTool()

ElectronPhotonVariableNFCorrectionTool::ElectronPhotonVariableNFCorrectionTool ( const std::string & name)

Standard constructor.

Parameters
nameInternal name of the tool instance

Definition at line 43 of file ElectronPhotonVariableNFCorrectionTool.cxx.

43 :
44 AsgTool(name)
45{}
AsgTool(const std::string &name)
Constructor specifying the tool instance's name.
Definition AsgTool.cxx:58

◆ ~ElectronPhotonVariableNFCorrectionTool()

ElectronPhotonVariableNFCorrectionTool::~ElectronPhotonVariableNFCorrectionTool ( )
inline

Standard destructor.

Definition at line 65 of file ElectronPhotonVariableNFCorrectionTool.h.

65{};

Member Function Documentation

◆ applyCorrection() [1/2]

const CP::CorrectionCode ElectronPhotonVariableNFCorrectionTool::applyCorrection ( xAOD::Electron & electron) const
overridevirtual

Not supported, so electrons cannot be corrected by this tool.

Implements IElectronPhotonShowerShapeFudgeTool.

Definition at line 419 of file ElectronPhotonVariableNFCorrectionTool.cxx.

420{
421 ATH_MSG_ERROR("ElectronPhotonVariableNFCorrectionTool does not support electrons.");
423}
#define ATH_MSG_ERROR(x,...)
@ Error
Some error happened during the object correction.

◆ applyCorrection() [2/2]

const CP::CorrectionCode ElectronPhotonVariableNFCorrectionTool::applyCorrection ( xAOD::Photon & photon) const
overridevirtual

Apply the Normalizing Flow correction to the passed photon.

Parameters
photonThe photon to be corrected

Reads the configured shower-shape variables from the photon, runs forward and backward ONNX inference for the selected fold, and overwrites the photon shower-shape values with the corrected outputs.

Implements IElectronPhotonShowerShapeFudgeTool.

Definition at line 255 of file ElectronPhotonVariableNFCorrectionTool.cxx.

256{
257
258 const size_t nSS = s_ssEnums.size();
259 std::vector<float> ss(nSS);
260
261 // Read shower shapes, then store original values
262 for (size_t i = 0; i < nSS; ++i) {
263 ss[i] = photon.showerShapeValue(s_ssEnums[i]);
264 (*m_accessors[i].original)(photon) = ss[i];
265 }
266
267
268 static const SG::Decorator<char> dec_pass("NFCorrectedShowerShapes");
269 static const SG::Decorator<char> dec_fudged("FallbackFudgedShowerShapes");
270
271 // Photon selection
272 const bool passPhoton = passPhotonSelection(photon);
273 const bool passSS = passPhoton && passShowerShapeCuts(ss);
274 const bool fallback = passPhoton && !passSS && !m_fallbackFudgeTool.empty();
275
276 dec_pass(photon) = passSS ? 1 : 0;
277 dec_fudged(photon) = fallback ? 1 : 0;
278
279 if (fallback) {
280 // NF is not applied because of the shower shape cuts, so use fudging instead
281 return applyFallbackFudge(photon, ss);
282 }
283
284 if (!passSS) {
285 // If selection is not passed, then SS value will be same to original
287 }
288
289
290 // Get event info and select fold
291 SG::ReadHandle<xAOD::EventInfo> h(m_eventInfoKey);
292 if (!h.isValid()) {
293 ATH_MSG_ERROR("Failed to read EventInfo via key " << m_eventInfoKey.key());
295 }
296
297 const unsigned long long eventNumber = h->eventNumber();
298 float ptGeV = photon.pt() / 1000.0f;
299 const float phi = static_cast<float>(photon.phi());
300 const int fold = selectFold(eventNumber, phi);
301
302
303 if (fold < 0 || fold >= m_nFolds) {
304 ATH_MSG_ERROR("Selected fold " << fold << " out of range [0," << (m_nFolds-1) << "]");
306 }
307
308
309 // Kinematic inputs
310 const bool isConv = photon.conversionType() != xAOD::EgammaParameters::unconverted;
311 std::vector<float> kinematic = {
312 ptGeV,
313 static_cast<float>(photon.eta()),
314 static_cast<float>(photon.phi()),
315 static_cast<float>(isConv)
316 };
317
318 // Forward inference
319 std::vector<Ort::Value> inputTensors;
320
321 const auto& onnxToolForward = m_onnxToolsForward[fold];
322
323 // index 0 is for kinematics
324 int64_t batchSizeKin = onnxToolForward->getBatchSize(
325 static_cast<int64_t>(kinematic.size()), 0);
326 if (onnxToolForward->addInput(inputTensors, kinematic, 0, batchSizeKin).isFailure()) {
327 ATH_MSG_ERROR("Fold " << fold << ": failed to add kinematic input tensor");
329 }
330
331 // index 1 is for shower shape varibales
332 int64_t batchSizeSS = onnxToolForward->getBatchSize(
333 static_cast<int64_t>(ss.size()), 1);
334 if (onnxToolForward->addInput(inputTensors, ss, 1, batchSizeSS).isFailure()) {
335 ATH_MSG_ERROR("Fold " << fold << ": failed to add shower shape input tensor");
337 }
338
339 std::vector<Ort::Value> outputTensors;
340 std::vector<float> outputData;
341 if (onnxToolForward->addOutput(outputTensors, outputData, 0, batchSizeKin).isFailure()) {
342 ATH_MSG_ERROR("Fold " << fold << ": failed to add forward output tensor");
344 }
345
346 if (onnxToolForward->inference(inputTensors, outputTensors).isFailure()) {
347 ATH_MSG_ERROR("Fold " << fold << ": forward inference failed");
349 }
350
351 float* zPtr = outputTensors[0].GetTensorMutableData<float>();
352 std::vector<float> zVec(zPtr, zPtr + nSS);
353
354
355 // Backward inference
356 std::vector<Ort::Value> inputTensorsBack;
357 std::vector<Ort::Value> outputTensorsBack;
358 std::vector<float> outputDataBack;
359
360 const auto& onnxToolBackward = m_onnxToolsBackward[fold];
361
362 // index 0 is for kinematics
363 int64_t batchSizeKinBack = onnxToolBackward->getBatchSize(
364 static_cast<int64_t>(kinematic.size()), 0);
365 if (onnxToolBackward->addInput(inputTensorsBack, kinematic, 0, batchSizeKinBack).isFailure()) {
366 ATH_MSG_ERROR("Fold " << fold << ": failed to add kinematic input tensor for backward model");
368 }
369
370 // index 1 is for shower shapes in latent space
371 int64_t batchSizeZBack = onnxToolBackward->getBatchSize(static_cast<int64_t>(zVec.size()), 1);
372
373 if (onnxToolBackward->addInput(inputTensorsBack, zVec, 1, batchSizeZBack).isFailure()) {
374 ATH_MSG_ERROR("Fold " << fold << ": failed to add z input tensor for backward model");
376 }
377
378 // index 2 is for original shower shapes (models use them to cut on std values [-5, 5])
379 if (onnxToolBackward->addInput(inputTensorsBack, ss, 2, batchSizeKinBack).isFailure()) {
380 ATH_MSG_ERROR("Fold " << fold << ": failed to add original SS input tensor for backward model");
382 }
383
384 if (onnxToolBackward->addOutput(outputTensorsBack, outputDataBack, 0, batchSizeZBack).isFailure()) {
385 ATH_MSG_ERROR("Fold " << fold << ": failed to add backward output tensor");
387 }
388
389 if (onnxToolBackward->inference(inputTensorsBack, outputTensorsBack).isFailure()) {
390 ATH_MSG_ERROR("Fold " << fold << ": backward inference failed");
392 }
393
394 const auto infoB = outputTensorsBack[0].GetTensorTypeAndShapeInfo();
395 const auto nElB = infoB.GetElementCount();
396 if (nElB != nSS) {
397 ATH_MSG_ERROR("Fold "<<fold <<": backward output has " <<nElB<< " elements, expected "<<nSS);
399 }
400
401 // Write corrected shower shapes
402 float* corrPtr = outputTensorsBack[0].GetTensorMutableData<float>();
403 for (size_t i = 0; i < nSS; ++i) {
404 photon.setShowerShapeValue(corrPtr[i], s_ssEnums[i]);
405 }
406
407 // Keep fracs1 (index 8) = 0 untouched (NF smears it)
408 if (ss[8] == 0.f) {
409 photon.setShowerShapeValue(0.f, s_ssEnums[8]);
410 }
411
412 ATH_MSG_DEBUG("NF correction applied successfully");
413
414
416}
Scalar phi() const
phi method
#define ATH_MSG_DEBUG(x,...)
static Double_t ss
@ Ok
The correction was done successfully.
std::vector< SSAccessors > m_accessors
Per-variable accessors aligned with s_ssVarNames.
ToolHandleArray< AthOnnx::IOnnxRuntimeInferenceTool > m_onnxToolsForward
ToolHandleArray for forward ONNX models (one tool per fold).
bool passShowerShapeCuts(const std::vector< float > &ss) const
Returns true if the shower shapes pass the cuts removing default values.
SG::ReadHandleKey< xAOD::EventInfo > m_eventInfoKey
ReadHandleKey for EventInfo used for fold selection.
int selectFold(unsigned long long eventNumber, float phi) const
Select fold index for the current event/photon.
ToolHandleArray< AthOnnx::IOnnxRuntimeInferenceTool > m_onnxToolsBackward
ToolHandleArray for backward ONNX models (one tool per fold).
static const std::vector< xAOD::EgammaParameters::ShowerShapeType > s_ssEnums
Egamma shower shape enum mapping for reading/writing values (order matches s_ssVarNames).
int m_nFolds
Number of model folds configured (must match tool handle array sizes).
bool passPhotonSelection(const xAOD::Photon &photon) const
Returns true if the photon passes the pT and truthType selection.
CP::CorrectionCode applyFallbackFudge(xAOD::Photon &photon, const std::vector< float > &ss) const
Apply the fallback fudge tool to a photon failing only the shower shape cuts.
ToolHandle< IElectronPhotonShowerShapeFudgeTool > m_fallbackFudgeTool
Fudge tool used for photons failing the shower shape cuts, empty = no fallback.
SG::Decorator< T, ALLOC > Decorator
Helper class to provide type-safe access to aux data, specialized for JaggedVecElt.
Definition AuxElement.h:576
@ unconverted
unconverted photon

◆ applyFallbackFudge()

CP::CorrectionCode ElectronPhotonVariableNFCorrectionTool::applyFallbackFudge ( xAOD::Photon & photon,
const std::vector< float > & ss ) const
private

Apply the fallback fudge tool to a photon failing only the shower shape cuts.

weta1 and wtots1 are kept at their original values if these are below s_defaultValueThreshold

Definition at line 121 of file ElectronPhotonVariableNFCorrectionTool.cxx.

124{
125 if (m_fallbackFudgeTool->applyCorrection(photon) != CP::CorrectionCode::Ok) {
126 ATH_MSG_ERROR("Fallback fudge tool failed to correct photon");
128 }
129
130 // Keep default values of weta1 (index 1) and wtots1 (index 4) untouched
131 for (size_t i : {size_t(1), size_t(4)}) {
132 if (ss[i] < s_defaultValueThreshold) {
133 photon.setShowerShapeValue(ss[i], s_ssEnums[i]);
134 }
135 }
136 // Keep fracs1 (index 8) = 0 untouched (fudging smears it)
137 if (ss[8] == 0.f) {
138 photon.setShowerShapeValue(0.f, s_ssEnums[8]);
139 }
140
141 ATH_MSG_DEBUG("Photon failed shower shape cuts: fallback fudge correction applied");
143}
static constexpr float s_defaultValueThreshold
Original values of weta1 and wtots1 below this threshold are default values and are not fudged.

◆ correctedCopy() [1/2]

const CP::CorrectionCode ElectronPhotonVariableNFCorrectionTool::correctedCopy ( const xAOD::Electron & in_electron,
xAOD::Electron *& out_electron ) const
overridevirtual

Not supported, so electrons cannot be corrected by this tool.

Implements IElectronPhotonShowerShapeFudgeTool.

Definition at line 435 of file ElectronPhotonVariableNFCorrectionTool.cxx.

437{
438 ATH_MSG_ERROR("ElectronPhotonVariableNFCorrectionTool cannot correct electrons.");
439 out_electron = new xAOD::Electron(in_electron);
441}
Electron_v1 Electron
Definition of the current "egamma version".

◆ correctedCopy() [2/2]

const CP::CorrectionCode ElectronPhotonVariableNFCorrectionTool::correctedCopy ( const xAOD::Photon & in_photon,
xAOD::Photon *& out_photon ) const
overridevirtual

Make a corrected copy of the passed photon.

Parameters
in_photonThe original photon to copy
out_photonThe corrected copy

Implements IElectronPhotonShowerShapeFudgeTool.

Definition at line 426 of file ElectronPhotonVariableNFCorrectionTool.cxx.

428{
429
430 out_photon = new xAOD::Photon(in_photon);
431 return applyCorrection(*out_photon);
432}
virtual const CP::CorrectionCode applyCorrection(xAOD::Photon &photon) const override
Apply the Normalizing Flow correction to the passed photon.
Photon_v1 Photon
Definition of the current "egamma version".

◆ declareGaudiProperty()

Gaudi::Details::PropertyBase & AthCommonDataStore< AthCommonMsg< AlgTool > >::declareGaudiProperty ( Gaudi::Property< T, V, H > & hndl,
const SG::VarHandleKeyType &  )
inlineprivateinherited

specialization for handling Gaudi::Property<SG::VarHandleKey>

Definition at line 156 of file AthCommonDataStore.h.

158 {
160 hndl.value(),
161 hndl.documentation());
162
163 }
Gaudi::Details::PropertyBase & declareProperty(Gaudi::Property< T, V, H > &t)

◆ declareProperty()

Gaudi::Details::PropertyBase & AthCommonDataStore< AthCommonMsg< AlgTool > >::declareProperty ( Gaudi::Property< T, V, H > & t)
inlineinherited

Definition at line 145 of file AthCommonDataStore.h.

145 {
146 typedef typename SG::HandleClassifier<T>::type htype;
148 }
Gaudi::Details::PropertyBase & declareGaudiProperty(Gaudi::Property< T, V, H > &hndl, const SG::VarHandleKeyType &)
specialization for handling Gaudi::Property<SG::VarHandleKey>

◆ detStore()

const ServiceHandle< StoreGateSvc > & AthCommonDataStore< AthCommonMsg< AlgTool > >::detStore ( ) const
inlineinherited

The standard StoreGateSvc/DetectorStore Returns (kind of) a pointer to the StoreGateSvc.

Definition at line 95 of file AthCommonDataStore.h.

◆ evtStore()

ServiceHandle< StoreGateSvc > & AthCommonDataStore< AthCommonMsg< AlgTool > >::evtStore ( )
inlineinherited

The standard StoreGateSvc (event store) Returns (kind of) a pointer to the StoreGateSvc.

Definition at line 85 of file AthCommonDataStore.h.

◆ extraDeps_update_handler()

void AthCommonDataStore< AthCommonMsg< AlgTool > >::extraDeps_update_handler ( Gaudi::Details::PropertyBase & ExtraDeps)
protectedinherited

Add StoreName to extra input/output deps as needed.

use the logic of the VarHandleKey to parse the DataObjID keys supplied via the ExtraInputs and ExtraOuputs Properties to add the StoreName if it's not explicitly given

◆ getKey()

SG::sgkey_t asg::AsgTool::getKey ( const void * ptr) const
inherited

Get the (hashed) key of an object that is in the event store.

This is a bit of a special one. StoreGateSvc and xAOD::Event both provide ways for getting the SG::sgkey_t key for an object that is in the store, based on a bare pointer. But they provide different interfaces for doing so.

In order to allow tools to efficiently perform this operation, they can use this helper function.

See also
asg::AsgTool::getName
Parameters
ptrThe bare pointer to the object that the event store should know about
Returns
The hashed key of the object in the store. If not found, an invalid (zero) key.

Definition at line 119 of file AsgTool.cxx.

119 {
120
121#ifdef XAOD_STANDALONE
122 // In case we use @c xAOD::Event, we have a direct function call
123 // for this.
124 return evtStore()->event()->getKey( ptr );
125#else
126 const SG::DataProxy* proxy = evtStore()->proxy( ptr );
127 return ( proxy == nullptr ? 0 : proxy->sgkey() );
128#endif // XAOD_STANDALONE
129 }
ServiceHandle< StoreGateSvc > & evtStore()

◆ getName()

const std::string & asg::AsgTool::getName ( const void * ptr) const
inherited

Get the name of an object that is / should be in the event store.

This is a bit of a special one. StoreGateSvc and xAOD::Event both provide ways for getting the std::string name for an object that is in the store, based on a bare pointer. But they provide different interfaces for doing so.

In order to allow tools to efficiently perform this operation, they can use this helper function.

See also
asg::AsgTool::getKey
Parameters
ptrThe bare pointer to the object that the event store should know about
Returns
The string name of the object in the store. If not found, an empty string.

Definition at line 106 of file AsgTool.cxx.

106 {
107
108#ifdef XAOD_STANDALONE
109 // In case we use @c xAOD::Event, we have a direct function call
110 // for this.
111 return evtStore()->event()->getName( ptr );
112#else
113 const SG::DataProxy* proxy = evtStore()->proxy( ptr );
114 static const std::string dummy = "";
115 return ( proxy == nullptr ? dummy : proxy->name() );
116#endif // XAOD_STANDALONE
117 }

◆ getProperty()

template<class T>
const T * asg::AsgTool::getProperty ( const std::string & name) const
inherited

Get one of the tool's properties.

◆ initialize()

StatusCode ElectronPhotonVariableNFCorrectionTool::initialize ( void )
overridevirtual

Initialize the class instance.

Reads the configuration file set via setProperty("ConfigFile", ...) function and sets up the class instance accordingly.

The configuration provides:

  • SimulationType: FS/AF3
  • NFolds: number of folds (must match number of ONNX tools configured)
  • ONNXnamePattern: pattern string (informational; tool arrays are configured externally)
  • FoldStrategy: eventNumber or eventNumber_phi
  • ApplyTo: TruthPhotons/All

Reimplemented from asg::AsgTool.

Definition at line 147 of file ElectronPhotonVariableNFCorrectionTool.cxx.

148{
149 if (m_configFile.empty()) {
150 ATH_MSG_ERROR("ConfigFile property is empty. Please provide a config file to the tool.");
151 return StatusCode::FAILURE;
152 }
153
154 std::string resolvedConfig = PathResolverFindCalibFile(m_configFile);
155 if (resolvedConfig.empty()) {
156 ATH_MSG_ERROR("Failed to resolve config file \"" << m_configFile << "\"");
157 return StatusCode::FAILURE;
158 }
159 ATH_MSG_DEBUG("Use configuration file " << m_configFile);
160
161 TEnv env;
162 env.ReadFile(resolvedConfig.c_str(), kEnvLocal);
163 env.IgnoreDuplicates(false);
164
165 const int nFoldsConfig = env.GetValue("NFolds", 0);
166 if (nFoldsConfig <= 0) {
167 ATH_MSG_ERROR("NFolds not set or invalid in config: " << resolvedConfig);
168 return StatusCode::FAILURE;
169 }
170
171 if (m_nFoldsOverride > 0) {
172 if (m_nFoldsOverride > nFoldsConfig) {
173 ATH_MSG_ERROR("NFoldsOverride (" << m_nFoldsOverride.value() << ") exceeds NFolds in config (" << nFoldsConfig << ")");
174 return StatusCode::FAILURE;
175 }
177 } else {
178 m_nFolds = nFoldsConfig;
179 }
180
181 TString pattern = env.GetValue("ONNXnamePattern", "");
182 if (pattern.IsNull()) {
183 ATH_MSG_ERROR("ONNXnamePattern not set in config: " << resolvedConfig);
184 return StatusCode::FAILURE;
185 }
186 m_onnxPattern = pattern.Data();
187
188
189 TString fs = env.GetValue("FoldStrategy", "eventNumber");
190 std::string fsStr = fs.Data();
191
193
195 ATH_MSG_ERROR("FoldStrategy must be 'eventNumber' or 'eventNumber_phi', but got '" << fsStr << "' in config: " << resolvedConfig);
196 return StatusCode::FAILURE;
197 }
198
199
200 ATH_MSG_VERBOSE("NFolds = " << m_nFolds << ", pattern = " << m_onnxPattern << ", FoldStrategy = " << fsStr);
201
202 if (static_cast<int>(m_onnxToolsForward.size()) != m_nFolds ||
203 static_cast<int>(m_onnxToolsBackward.size()) != m_nFolds) {
204 ATH_MSG_ERROR("Expected "<<m_nFolds<<" forward/backward tools, "<< "but got "<<m_onnxToolsForward.size()<<" / "<< m_onnxToolsBackward.size());
205 return StatusCode::FAILURE;
206 }
207
208
210 else if (m_applyToStr == "All") m_applyToMode = ApplyToMode::All;
211 else {
212 ATH_MSG_ERROR("ApplyTo must be TruthPhotons or All, but got '" << m_applyToStr << "'");
213 return StatusCode::FAILURE;
214 }
215
216 // Cuts on SS vars to remove default values
217 m_applyShowerShapeCuts = (env.GetValue("ApplyShowerShapeCuts", 1) == 1);
218
219 ATH_MSG_INFO("ApplyTo = " << m_applyToStr << ", pTcut=" << m_pTcutMeV << " MeV, ApplyShowerShapeCuts=" << m_applyShowerShapeCuts);
220
221
222 ATH_CHECK(m_onnxToolsForward.retrieve());
223 ATH_CHECK(m_onnxToolsBackward.retrieve());
224
225 if (!m_fallbackFudgeTool.empty()) {
226 ATH_CHECK(m_fallbackFudgeTool.retrieve());
227 ATH_MSG_INFO("Photons failing shower shape cuts will be corrected with fallback fudge tool " << m_fallbackFudgeTool.name());
228 }
229
230 if (msgLvl(MSG::DEBUG)) {
231 for (int i = 0; i < m_nFolds; ++i) {
232 ATH_MSG_VERBOSE("Fold " << i << " forward model info:");
233 m_onnxToolsForward[i]->printModelInfo();
234 ATH_MSG_VERBOSE("Fold " << i << " backward model info:");
235 m_onnxToolsBackward[i]->printModelInfo();
236 }
237 }
238
239 // Prepare decorations for each shower shape
240 m_accessors.resize(s_ssVarNames.size());
241 for (size_t i = 0; i < s_ssVarNames.size(); ++i) {
242 const std::string& var = s_ssVarNames[i];
243 m_accessors[i].original = std::make_unique<SG::Accessor<float>>(var + "_original");
244 }
245
246 ATH_CHECK(m_eventInfoKey.initialize());
247
248 ATH_MSG_INFO("NF correction tool initialized with " << m_nFolds << " folds. ");
249
250 return StatusCode::SUCCESS;
251}
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_VERBOSE(x,...)
#define ATH_MSG_INFO(x,...)
static Double_t fs
std::string PathResolverFindCalibFile(const std::string &logical_file_name)
bool msgLvl(const MSG::Level lvl) const
static const std::vector< std::string > s_ssVarNames
List of shower shape variable names (order must match model I/O).
FoldStrategy parseFoldStrategy(const std::string &s) const
Parse fold strategy string from config.
std::string m_onnxPattern
Models path pattern string from config.
bool m_applyShowerShapeCuts
Cuts applied to remove default values of shower shapes.
Gaudi::Property< std::string > m_configFile
The configuration file for the tool, application mode and minimum photon pT cut in MeV.
FoldStrategy m_foldStrategy
Selected fold strategy (configured via FoldStrategy in the config).

◆ inputHandles()

virtual std::vector< Gaudi::DataHandle * > AthCommonDataStore< AthCommonMsg< AlgTool > >::inputHandles ( ) const
overridevirtualinherited

Return this algorithm's input handles.

We override this to include handle instances from key arrays if they have not yet been declared. See comments on updateVHKA.

◆ msg()

MsgStream & AthCommonMsg< AlgTool >::msg ( ) const
inlineinherited

Definition at line 24 of file AthCommonMsg.h.

24 {
25 return this->msgStream();
26 }

◆ msg_level_name()

const std::string & asg::AsgTool::msg_level_name ( ) const
inherited

A deprecated function for getting the message level's name.

Instead of using this, weirdly named function, user code should get the string name of the current minimum message level (in case they really need it...), with:

MSG::name( msg().level() )

This function's name doesn't follow the ATLAS coding rules, and as such will be removed in the not too distant future.

Returns
The string name of the current minimum message level that's printed

Definition at line 101 of file AsgTool.cxx.

101 {
102
103 return MSG::name( msg().level() );
104 }
MsgStream & msg() const
const std::string & name(Level lvl)
Convenience function for translating message levels to strings.
Definition MsgLevel.cxx:19

◆ msgLvl()

bool AthCommonMsg< AlgTool >::msgLvl ( const MSG::Level lvl) const
inlineinherited

Definition at line 30 of file AthCommonMsg.h.

30 {
31 return this->msgLevel(lvl);
32 }

◆ outputHandles()

virtual std::vector< Gaudi::DataHandle * > AthCommonDataStore< AthCommonMsg< AlgTool > >::outputHandles ( ) const
overridevirtualinherited

Return this algorithm's output handles.

We override this to include handle instances from key arrays if they have not yet been declared. See comments on updateVHKA.

◆ parseFoldStrategy()

ElectronPhotonVariableNFCorrectionTool::FoldStrategy ElectronPhotonVariableNFCorrectionTool::parseFoldStrategy ( const std::string & s) const
private

Parse fold strategy string from config.

Definition at line 64 of file ElectronPhotonVariableNFCorrectionTool.cxx.

65{
66 if (s == "eventNumber") return FoldStrategy::EventNumber;
67 if (s == "eventNumber_phi") return FoldStrategy::EventNumberPhi;
68 ATH_MSG_WARNING("Unknown FoldStrategy '" << s << "'");
70}
#define ATH_MSG_WARNING(x,...)

◆ passPhotonSelection()

bool ElectronPhotonVariableNFCorrectionTool::passPhotonSelection ( const xAOD::Photon & photon) const
private

Returns true if the photon passes the pT and truthType selection.

Definition at line 72 of file ElectronPhotonVariableNFCorrectionTool.cxx.

73{
74 // pT cut
75 if (photon.pt() < m_pTcutMeV) return false;
76
77 // TruthType cut
79 static const SG::Accessor<int> acc_truthType("truthType");
80 if (!acc_truthType.isAvailable(photon)) {
81 ATH_MSG_WARNING("ApplyTo = TruthPhotons but truthType not available — skipping photon");
82 return false;
83 }
84 int truthType = acc_truthType(photon);
85 if (truthType < 13 || truthType > 15) return false;
86 }
87
88 return true;
89}
int truthType(const U &p)

◆ passShowerShapeCuts()

bool ElectronPhotonVariableNFCorrectionTool::passShowerShapeCuts ( const std::vector< float > & ss) const
private

Returns true if the shower shapes pass the cuts removing default values.

Definition at line 91 of file ElectronPhotonVariableNFCorrectionTool.cxx.

92{
93 if (!m_applyShowerShapeCuts) return true;
94
95 // weta2
96 if (ss[0] <= -10.f || ss[0] >= 10.f) return false;
97 // weta1
98 if (ss[1] <= -10.f || ss[1] >= 10.f) return false;
99 // Rphi
100 if (ss[2] <= -10.f || ss[2] >= 10.f) return false;
101 // Reta
102 if (ss[3] <= -10.f || ss[3] >= 10.f) return false;
103 // wtots1
104 if (ss[4] < -2.f || ss[4] >= 10.f) return false;
105 // Rhad
106 if (ss[5] < -2.f || ss[5] > 2.f) return false;
107 // Rhad1
108 if (ss[6] < -2.f || ss[6] > 2.f) return false;
109 // f1
110 if (ss[7] <= -2.f || ss[7] >= 2.f) return false;
111 // fracs1
112 if (ss[8] <= -2.f || ss[8] >= 5.f) return false;
113 // DeltaE
114 if (ss[9] < 0.f || ss[9] >= 5000.f) return false;
115 // Eratio
116 if (ss[10] < 0.f || ss[10] > 1.f) return false;
117
118 return true;
119}

◆ print()

◆ renounce()

std::enable_if_t< std::is_void_v< std::result_of_t< decltype(&T::renounce)(T)> > &&!std::is_base_of_v< SG::VarHandleKeyArray, T > &&std::is_base_of_v< Gaudi::DataHandle, T >, void > AthCommonDataStore< AthCommonMsg< AlgTool > >::renounce ( T & h)
inlineprotectedinherited

Definition at line 368 of file AthCommonDataStore.h.

369 {
370 h.renounce();
372 }
std::enable_if_t< std::is_void_v< std::result_of_t< decltype(&T::renounce)(T)> > &&!std::is_base_of_v< SG::VarHandleKeyArray, T > &&std::is_base_of_v< Gaudi::DataHandle, T >, void > renounce(T &h)

◆ renounceArray()

void AthCommonDataStore< AthCommonMsg< AlgTool > >::renounceArray ( SG::VarHandleKeyArray & handlesArray)
inlineprotectedinherited

remove all handles from I/O resolution

Definition at line 352 of file AthCommonDataStore.h.

352 {
354 }

◆ selectFold()

int ElectronPhotonVariableNFCorrectionTool::selectFold ( unsigned long long eventNumber,
float phi ) const
private

Select fold index for the current event/photon.

Parameters
eventNumberEventInfo::eventNumber()
phiPhoton phi in radians
Returns
Fold index in [0, NFolds-1]

Definition at line 48 of file ElectronPhotonVariableNFCorrectionTool.cxx.

49{
50 if (m_nFolds <= 1) return 0;
51
52 unsigned long long key = eventNumber;
53
55 const long long phiBin = static_cast<long long>(std::floor((phi + static_cast<float>(M_PI)) * 100.0f));
56 key = eventNumber + static_cast<unsigned long long>(phiBin);
57 }
58
59 return static_cast<int>(key % m_nFolds);
60}
#define M_PI
setSAddress setEtaMS setDirPhiMS setDirZMS setBarrelRadius setEndcapAlpha setEndcapRadius setPhiMap phiBin

◆ sysInitialize()

virtual StatusCode AthCommonDataStore< AthCommonMsg< AlgTool > >::sysInitialize ( )
overridevirtualinherited

Perform system initialization for an algorithm.

We override this to declare all the elements of handle key arrays at the end of initialization. See comments on updateVHKA.

Reimplemented in asg::AsgMetadataTool, AthCheckedComponent< AthAlgTool >, and AthCheckedComponent<::AthAlgTool >.

◆ sysStart()

virtual StatusCode AthCommonDataStore< AthCommonMsg< AlgTool > >::sysStart ( )
overridevirtualinherited

Handle START transition.

We override this in order to make sure that conditions handle keys can cache a pointer to the conditions container.

◆ updateVHKA()

void AthCommonDataStore< AthCommonMsg< AlgTool > >::updateVHKA ( Gaudi::Details::PropertyBase & )
inlineinherited

Definition at line 298 of file AthCommonDataStore.h.

298 {
299 for (auto &a : m_vhka) {
301 for (auto k : keys) {
302 k->setOwner(this);
303 }
304 }
305 }
std::vector< SG::VarHandleKeyArray * > m_vhka

Member Data Documentation

◆ m_accessors

std::vector<SSAccessors> ElectronPhotonVariableNFCorrectionTool::m_accessors
private

Per-variable accessors aligned with s_ssVarNames.

Definition at line 180 of file ElectronPhotonVariableNFCorrectionTool.h.

◆ m_applyShowerShapeCuts

bool ElectronPhotonVariableNFCorrectionTool::m_applyShowerShapeCuts {true}
private

Cuts applied to remove default values of shower shapes.

Definition at line 124 of file ElectronPhotonVariableNFCorrectionTool.h.

124{true};

◆ m_applyToMode

ApplyToMode ElectronPhotonVariableNFCorrectionTool::m_applyToMode {ApplyToMode::TruthPhotons}
private

◆ m_applyToStr

Gaudi::Property<std::string> ElectronPhotonVariableNFCorrectionTool::m_applyToStr {this, "ApplyTo", "TruthPhotons", "TruthPhotons or All"}
private

Definition at line 107 of file ElectronPhotonVariableNFCorrectionTool.h.

107{this, "ApplyTo", "TruthPhotons", "TruthPhotons or All"};

◆ m_configFile

Gaudi::Property<std::string> ElectronPhotonVariableNFCorrectionTool::m_configFile {this, "ConfigFile", "", "The configuration file for Normalizing Flows to use"}
private

The configuration file for the tool, application mode and minimum photon pT cut in MeV.

Definition at line 105 of file ElectronPhotonVariableNFCorrectionTool.h.

105{this, "ConfigFile", "", "The configuration file for Normalizing Flows to use"};

◆ m_detStore

StoreGateSvc_t AthCommonDataStore< AthCommonMsg< AlgTool > >::m_detStore
privateinherited

Pointer to StoreGate (detector store by default).

Definition at line 381 of file AthCommonDataStore.h.

◆ m_eventInfoKey

SG::ReadHandleKey<xAOD::EventInfo> ElectronPhotonVariableNFCorrectionTool::m_eventInfoKey {this, "EventInfoKey", "EventInfo", "EventInfo key"}
private

ReadHandleKey for EventInfo used for fold selection.

Definition at line 117 of file ElectronPhotonVariableNFCorrectionTool.h.

117{this, "EventInfoKey", "EventInfo", "EventInfo key"};

◆ m_evtStore

StoreGateSvc_t AthCommonDataStore< AthCommonMsg< AlgTool > >::m_evtStore
privateinherited

Pointer to StoreGate (event store by default).

Definition at line 378 of file AthCommonDataStore.h.

◆ m_fallbackFudgeTool

ToolHandle<IElectronPhotonShowerShapeFudgeTool> ElectronPhotonVariableNFCorrectionTool::m_fallbackFudgeTool {this, "FallbackFudgeTool", "", "Fudge tool applied to photons which fail the shower shape cuts"}
private

Fudge tool used for photons failing the shower shape cuts, empty = no fallback.

Definition at line 138 of file ElectronPhotonVariableNFCorrectionTool.h.

138{this, "FallbackFudgeTool", "", "Fudge tool applied to photons which fail the shower shape cuts"};

◆ m_foldStrategy

FoldStrategy ElectronPhotonVariableNFCorrectionTool::m_foldStrategy {FoldStrategy::EventNumber}
private

Selected fold strategy (configured via FoldStrategy in the config).

Definition at line 151 of file ElectronPhotonVariableNFCorrectionTool.h.

◆ m_nFolds

int ElectronPhotonVariableNFCorrectionTool::m_nFolds {0}
private

Number of model folds configured (must match tool handle array sizes).

Definition at line 111 of file ElectronPhotonVariableNFCorrectionTool.h.

111{0};

◆ m_nFoldsOverride

Gaudi::Property<int> ElectronPhotonVariableNFCorrectionTool::m_nFoldsOverride {this, "NFoldsOverride", -1, "If > 0, override the number of folds to use instead of the value from the config file (must not exceed NFolds in the config)"}
private

Definition at line 106 of file ElectronPhotonVariableNFCorrectionTool.h.

106{this, "NFoldsOverride", -1, "If > 0, override the number of folds to use instead of the value from the config file (must not exceed NFolds in the config)"};

◆ m_onnxPattern

std::string ElectronPhotonVariableNFCorrectionTool::m_onnxPattern
private

Models path pattern string from config.

Definition at line 114 of file ElectronPhotonVariableNFCorrectionTool.h.

◆ m_onnxToolsBackward

ToolHandleArray<AthOnnx::IOnnxRuntimeInferenceTool> ElectronPhotonVariableNFCorrectionTool::m_onnxToolsBackward {this, "OnnxInferenceToolsBackward", {}, "Backward ONNX tools per fold"}
private

ToolHandleArray for backward ONNX models (one tool per fold).

Definition at line 166 of file ElectronPhotonVariableNFCorrectionTool.h.

166{this, "OnnxInferenceToolsBackward", {}, "Backward ONNX tools per fold"};

◆ m_onnxToolsForward

ToolHandleArray<AthOnnx::IOnnxRuntimeInferenceTool> ElectronPhotonVariableNFCorrectionTool::m_onnxToolsForward {this, "OnnxInferenceToolsForward", {}, "Forward ONNX tools per fold"}
private

ToolHandleArray for forward ONNX models (one tool per fold).

Definition at line 164 of file ElectronPhotonVariableNFCorrectionTool.h.

164{this, "OnnxInferenceToolsForward", {}, "Forward ONNX tools per fold"};

◆ m_pTcutMeV

Gaudi::Property<float> ElectronPhotonVariableNFCorrectionTool::m_pTcutMeV {this, "pTcut", 10000.f, "Min photon pT in MeV"}
private

Definition at line 108 of file ElectronPhotonVariableNFCorrectionTool.h.

108{this, "pTcut", 10000.f, "Min photon pT in MeV"};

◆ m_varHandleArraysDeclared

bool AthCommonDataStore< AthCommonMsg< AlgTool > >::m_varHandleArraysDeclared
privateinherited

Definition at line 387 of file AthCommonDataStore.h.

◆ m_vhka

std::vector<SG::VarHandleKeyArray*> AthCommonDataStore< AthCommonMsg< AlgTool > >::m_vhka
privateinherited

Definition at line 386 of file AthCommonDataStore.h.

◆ s_defaultValueThreshold

float ElectronPhotonVariableNFCorrectionTool::s_defaultValueThreshold = -100.f
staticconstexprprivate

Original values of weta1 and wtots1 below this threshold are default values and are not fudged.

Definition at line 141 of file ElectronPhotonVariableNFCorrectionTool.h.

◆ s_ssEnums

const std::vector< xAOD::EgammaParameters::ShowerShapeType > ElectronPhotonVariableNFCorrectionTool::s_ssEnums
staticprivate
Initial value:
= {
}
@ wtots1
shower width is determined in a window detaxdphi = 0,0625 ×~0,2, corresponding typically to 20 strips...
@ f1
E1/E = fraction of energy reconstructed in the first sampling, where E1 is energy in all strips belon...
Definition EgammaEnums.h:53
@ Eratio
(emaxs1-e2tsts1)/(emaxs1+e2tsts1)
@ DeltaE
e2tsts1-emins1
@ fracs1
shower shape in the shower core : [E(+/-3)-E(+/-1)]/E(+/-1), where E(+/-n) is the energy in ± n strip...
@ weta2
the lateral width is calculated with a window of 3x5 cells using the energy weighted sum over all cel...
@ weta1
shower width using +/-3 strips around the one with the maximal energy deposit: w3 strips = sqrt{sum(E...
Definition EgammaEnums.h:98

Egamma shower shape enum mapping for reading/writing values (order matches s_ssVarNames).

Definition at line 27 of file ElectronPhotonVariableNFCorrectionTool.h.

◆ s_ssVarNames

const std::vector< std::string > ElectronPhotonVariableNFCorrectionTool::s_ssVarNames
staticprivate
Initial value:
= {
"weta2", "weta1", "Rphi", "Reta", "wtots1", "Rhad", "Rhad1", "f1", "fracs1", "DeltaE", "Eratio"
}

List of shower shape variable names (order must match model I/O).

Definition at line 22 of file ElectronPhotonVariableNFCorrectionTool.h.


The documentation for this class was generated from the following files: