ATLAS Offline Software
PMGTruthWeightTool.cxx
Go to the documentation of this file.
1 /*
2  Copyright (C) 2002-2023 CERN for the benefit of the ATLAS collaboration
3 */
4 
5 // EDM include(s):
6 #ifndef XAOD_STANDALONE
8  #include "EventInfo/EventInfo.h"
9  #include "EventInfo/EventType.h"
10 #endif
11 
12 // Local include(s):
15 #include <PMGTools/WeightHelpers.h>
18 
20 
21 
22 namespace PMGTools
23 {
25  : asg::AsgMetadataTool(name)
26  {
27  declareProperty("MetaObjectName", m_metaName = "TruthMetaData");
28  }
29 
30 
32  {
33  ATH_MSG_DEBUG("Initialising...");
34 
35  ATH_MSG_INFO("Attempting to retrieve truth meta data from the first file...");
36 
37  // Clear cached weights
39 
41  m_calibCache.initialize (std::move (affSysts),
42  [this] (const CP::SystematicSet& sys,
43  std::size_t& idx) {
44  ATH_MSG_WARNING("Mapping for " << sys.name() << " missing, setting to index 0.");
45  idx = 0;
46  return StatusCode::SUCCESS;
47  });
48 
49  // Try to load MC channel number from file metadata
51 
52  if (m_mcChannelNumber == uint32_t(-1)) {
53  ATH_MSG_WARNING("... MC channel number could not be loaded");
54  } else {
55  ATH_MSG_INFO("... MC channel number identified as " << m_mcChannelNumber);
56  }
57 
58  // Start by trying to load metadata from the store
59  m_metaDataContainer = nullptr;
60  if (inputMetaStore()->contains<xAOD::TruthMetaDataContainer>(m_metaName)) {
62  ATH_MSG_INFO("Loaded xAOD::TruthMetaDataContainer");
63 
64  // Check for incorrectly stored McChannelNumber
66  for (auto truthMetaData : *m_metaDataContainer) {
67  if (truthMetaData->mcChannelNumber() != 0) { m_useChannelZeroInMetaData = false; }
68  }
69  // If we only have one metadata item take MC channel from there if needed
70  if (m_mcChannelNumber == uint32_t(-1) && m_metaDataContainer->size() == 1) {
71  m_mcChannelNumber = m_metaDataContainer->at(0)->mcChannelNumber();
72  ATH_MSG_WARNING("... MC channel number taken from the metadata as " << m_mcChannelNumber);
73  }
74  if (m_useChannelZeroInMetaData) { ATH_MSG_WARNING("MC channel number in TruthMetaData is invalid - assuming that channel 0 has the correct information."); }
75 
76  // Load metadata from TruthMetaDataContainer if we have a valid channel number or if we're going to use 0 anyway
77  // ... otherwise wait until we can load a channel number from EventInfo
79  if (loadMetaData().isFailure()) {
80  ATH_MSG_ERROR("Could not load metadata for MC channel number " << m_mcChannelNumber);
81  return StatusCode::FAILURE;
82  }
83  }
84  } else {
85  // ... now try to load the weight container using the POOL metadata (not possible in AnalysisBase)
86  // see https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/AthAnalysisBase#How_to_read_the_truth_weight_nam
87  if (loadPOOLMetaData().isFailure()) {
88  ATH_MSG_ERROR("Could not load POOL HepMCWeightNames");
89  return StatusCode::FAILURE;
90  }
91  }
92 
93  // Add the affecting systematics to the global registry
95  if (!registry.registerSystematics(*this)) {
96  ATH_MSG_ERROR("unable to register the systematics");
97  return StatusCode::FAILURE;
98  }
99 
100  ATH_MSG_DEBUG("Successfully initialized!");
101 
102  return StatusCode::SUCCESS;
103  }
104 
105 
106  const std::vector<std::string>& PMGTruthWeightTool::getWeightNames() const {
107  return m_weightNames;
108  }
109 
110 
111  float PMGTruthWeightTool::getWeight(const xAOD::EventInfo* evtInfo, const std::string& weightName) const {
112  // Return appropriate weight from EventInfo: this should be identical to the TruthEvent
113  try {
114  return evtInfo->mcEventWeight(m_weightIndices.at(weightName));
115  } catch (const std::out_of_range& e) {
116  // Before throwing an exception, try to recover with bad naming conventions
117  std::string strippedName = RCU::substitute (weightName, " ", "_");
118  std::transform(strippedName.begin(), strippedName.end(), strippedName.begin(),
119  [](unsigned char c){ return std::tolower(c); });
120  for (const std::string &weight : m_weightNames) {
121  std::string modifiedName = RCU::substitute (weight, " ", "_");
122  std::transform(modifiedName.begin(), modifiedName.end(), modifiedName.begin(),
123  [](unsigned char c){ return std::tolower(c); });
124  if (strippedName == modifiedName){
125  ATH_MSG_WARNING("Using weight name \"" << weight << "\" instead of requested \"" << weightName << "\"");
126  return getWeight(evtInfo, weight);
127  }
128  }
129  ATH_MSG_FATAL("Weight \"" + weightName + "\" could not be found");
130  throw std::runtime_error(name() + ": Weight \"" + weightName + "\" could not be found");
131  }
132  }
133 
134 
135  bool PMGTruthWeightTool::hasWeight(const std::string& weightName) const {
136  return (m_weightIndices.count(weightName) > 0);
137  }
138 
139 
141  {
142  const std::size_t *res;
144  return evtInfo->mcEventWeight(*res);
145  }
146 
147 
149  {
150  const std::size_t *res;
152  return *res;
153  }
154 
155 
157  {
159  }
160 
161 
163  {
164  return affectingSystematics();
165  }
166 
167 
169  mcChannelNumber = static_cast<uint32_t>(-1);
170 
171  // Try to load MC channel number from file metadata
172  ATH_MSG_INFO("Attempting to retrieve MC channel number...");
173  const xAOD::FileMetaData *fmd = nullptr;
174  if (inputMetaStore()->contains<xAOD::FileMetaData>("FileMetaData")) {
175  ATH_CHECK(inputMetaStore()->retrieve(fmd, "FileMetaData"));
176  float fltChannelNumber(-1);
177  if (fmd->value(xAOD::FileMetaData::mcProcID, fltChannelNumber)) {
178  mcChannelNumber = static_cast<uint32_t>(fltChannelNumber);
179  return StatusCode::SUCCESS;
180  }
181  }
182  return StatusCode::FAILURE;
183  }
184 
186  {
187  // Detect possible MC channel number change
190 
192  ATH_MSG_ERROR("MC channel number from a new file does not match the previously processed files.");
193  return StatusCode::FAILURE;
194  }
195 
196  return StatusCode::SUCCESS;
197  }
198 
199 
201  // Find the correct truth meta data object
202  uint32_t targetChannelNumber = (m_useChannelZeroInMetaData ? 0 : m_mcChannelNumber);
203  ATH_MSG_INFO("Attempting to load weight meta data from xAOD TruthMetaData for channel " << targetChannelNumber);
204  auto itTruthMetaDataPtr = std::find_if(m_metaDataContainer->begin(), m_metaDataContainer->end(),
205  [targetChannelNumber] (const auto& it) { return it->mcChannelNumber() == targetChannelNumber; }
206  );
207 
208  // If no such object is found then return
209  if (itTruthMetaDataPtr == m_metaDataContainer->end()) {
210  ATH_MSG_ERROR("Could not load weight meta data!");
211  return StatusCode::FAILURE;
212  }
213 
214  // Update cached weight data
215  const std::vector<std::string> &truthWeightNames = (*itTruthMetaDataPtr)->weightNames();
216  for(std::size_t idx = 0; idx < truthWeightNames.size(); ++idx ) {
217  m_weightNames.push_back(truthWeightNames.at(idx));
218  m_weightIndices[truthWeightNames.at(idx)] = idx;
219 
220  std::string sysName = weightNameWithPrefix(truthWeightNames.at(idx));
221  if (!sysName.empty()) {
223  }
224 
225  ANA_MSG_VERBOSE(" " << truthWeightNames.at(idx) << " " << sysName);
226  }
227  return this->validateWeightLocationCaches();
228  }
229 
230 
232  // AnalysisBase can only use the xAOD::TruthMetaDataContainer, so skip this
233 #ifdef XAOD_STANDALONE
234  return StatusCode::SUCCESS;
235 #else
236  ATH_MSG_INFO("Looking for POOL HepMC IOVMetaData...");
237  std::map<std::string, int> hepMCWeightNamesMap;
238  if (AAH::retrieveMetadata("/Generation/Parameters", "HepMCWeightNames", hepMCWeightNamesMap, inputMetaStore()).isFailure()) {
239  ATH_MSG_FATAL("Cannot access metadata " << m_metaName << " and failed to get names from IOVMetadata");
240  return StatusCode::FAILURE;
241  }
242 
243  // Use input map to fill the index map and the weight names
244  ATH_MSG_INFO("Attempting to load weight meta data from HepMC IOVMetaData container");
245  for (auto& kv : hepMCWeightNamesMap) {
246  m_weightNames.push_back(kv.first);
247  m_weightIndices[kv.first] = kv.second;
248 
249  std::string sysName = weightNameWithPrefix(kv.first);
250  if (!sysName.empty()) {
252  }
253 
254  ANA_MSG_VERBOSE(" " << kv.first << " " << sysName);
255  }
256  return this->validateWeightLocationCaches();
257 #endif // XAOD_STANDALONE
258  }
259 
260 
262  // Validate weight caches against one another
263  if (m_weightNames.size() != m_weightIndices.size()) {
264  ATH_MSG_ERROR("Found " << m_weightNames.size() << " but " << m_weightIndices.size() << " weight indices!");
265  return StatusCode::FAILURE;
266  }
267 
268  ATH_MSG_INFO("Successfully loaded information about " << m_weightNames.size() << " weights");
269  return StatusCode::SUCCESS;
270  }
271 
272 
274  m_weightNames.clear();
275  m_weightIndices.clear();
276  }
277 
278 } // namespace PMGTools
python.PyKernel.retrieve
def retrieve(aClass, aKey=None)
Definition: PyKernel.py:110
python.Dso.registry
registry
Definition: Control/AthenaServices/python/Dso.py:159
CaloCondBlobAlgs_fillNoiseFromASCII.sysName
sysName
Definition: CaloCondBlobAlgs_fillNoiseFromASCII.py:93
WeightHelpers.h
Postprocess generator weight names to be name/ROOT friendly.
ATH_MSG_FATAL
#define ATH_MSG_FATAL(x)
Definition: AthMsgStreamMacros.h:34
ATH_MSG_INFO
#define ATH_MSG_INFO(x)
Definition: AthMsgStreamMacros.h:31
CP::SystematicsCache::initialize
void initialize(CP::SystematicSet val_affectingSystematics, std::function< StatusCode(const CP::SystematicSet &sys, CalibData &result)> val_calc) noexcept
initialize with the list of affecting systematics and a function to calculate the calibration data fo...
Definition: SystematicsCache.h:158
xAOD::uint32_t
setEventNumber uint32_t
Definition: EventInfo_v1.cxx:127
AthCommonDataStore< AthCommonMsg< AlgTool > >::declareProperty
Gaudi::Details::PropertyBase & declareProperty(Gaudi::Property< T > &t)
Definition: AthCommonDataStore.h:145
PMGTools::PMGTruthWeightTool::PMGTruthWeightTool
PMGTruthWeightTool(const std::string &name)
Create a proper constructor for Athena.
Definition: PMGTruthWeightTool.cxx:24
PMGTools::PMGTruthWeightTool::hasWeight
virtual bool hasWeight(const std::string &weightName) const override
Implements interface from IPMGTruthWeightTool.
Definition: PMGTruthWeightTool.cxx:135
skel.it
it
Definition: skel.GENtoEVGEN.py:423
asg
Definition: DataHandleTestTool.h:28
PMGTools::PMGTruthWeightTool::m_weightIndices
std::unordered_map< std::string, size_t > m_weightIndices
Weight names to indices of available weights in this file.
Definition: PMGTruthWeightTool.h:113
CP::SystematicSet
Class to wrap a set of SystematicVariations.
Definition: SystematicSet.h:31
asg::AsgMetadataTool::inputMetaStore
MetaStorePtr_t inputMetaStore() const
Accessor for the input metadata store.
Definition: AsgMetadataTool.cxx:88
PMGTools::PMGTruthWeightTool::initialize
virtual StatusCode initialize() override
Function initialising the tool.
Definition: PMGTruthWeightTool.cxx:31
ANA_CHECK
#define ANA_CHECK(EXP)
check whether the given expression was successful
Definition: Control/AthToolSupport/AsgMessaging/AsgMessaging/MessageCheck.h:324
PMGTools::PMGTruthWeightTool::m_calibCache
CP::SystematicsCache< std::size_t > m_calibCache
Systematics to indices of available weights.
Definition: PMGTruthWeightTool.h:116
EventType.h
This class provides general information about an event. It extends EventInfo with a list of sub-evts ...
PMGTools::PMGTruthWeightTool::loadMetaData
StatusCode loadMetaData()
Loads weight information from xAOD::TruthMetaDataContainer.
Definition: PMGTruthWeightTool.cxx:200
CP::SystematicVariation
Definition: SystematicVariation.h:47
PMGTruthWeightTool.h
xAOD::mcChannelNumber
mcChannelNumber
Definition: EventInfo_v1.cxx:197
StringUtil.h
PMGTools::PMGTruthWeightTool::clearWeightLocationCaches
void clearWeightLocationCaches()
Clear caches.
Definition: PMGTruthWeightTool.cxx:273
mapkey::sys
@ sys
Definition: TElectronEfficiencyCorrectionTool.cxx:42
xAOD::FileMetaData_v1::value
bool value(MetaDataType type, std::string &val) const
Get a pre-defined string value out of the object.
Definition: FileMetaData_v1.cxx:195
dqt_zlumi_pandas.weight
int weight
Definition: dqt_zlumi_pandas.py:200
ANA_CHECK_THROW
#define ANA_CHECK_THROW(EXP)
check whether the given expression was successful, throwing an exception on failure
Definition: Control/AthToolSupport/AsgMessaging/AsgMessaging/MessageCheck.h:339
PMGTools::PMGTruthWeightTool::beginInputFile
virtual StatusCode beginInputFile() override
Function called when a new input file is opened.
Definition: PMGTruthWeightTool.cxx:185
PMGTools::PMGTruthWeightTool::getMCChannelNumber
StatusCode getMCChannelNumber(uint32_t &mcChannelNumber)
Helper function for retrieving MC channel number from file metadata.
Definition: PMGTruthWeightTool.cxx:168
ATH_MSG_ERROR
#define ATH_MSG_ERROR(x)
Definition: AthMsgStreamMacros.h:33
SystematicRegistry.h
EL::StatusCode
::StatusCode StatusCode
StatusCode definition for legacy code.
Definition: PhysicsAnalysis/D3PDTools/EventLoop/EventLoop/StatusCode.h:22
ATH_MSG_DEBUG
#define ATH_MSG_DEBUG(x)
Definition: AthMsgStreamMacros.h:29
PMGTools::PMGTruthWeightTool::m_useChannelZeroInMetaData
bool m_useChannelZeroInMetaData
Flag to indicate whether the xAOD::TruthMetaData objects have incorrect McChannelNumber.
Definition: PMGTruthWeightTool.h:107
PMGTools
Tool providing sample cross-sections and k-factors etc.
Definition: AnalysisCommon/PMGTools/PMGTools/IPMGCrossSectionTool.h:15
res
std::pair< std::vector< unsigned int >, bool > res
Definition: JetGroupProductTest.cxx:14
Amg::transform
Amg::Vector3D transform(Amg::Vector3D &v, Amg::Transform3D &tr)
Transform a point from a Trasformation3D.
Definition: GeoPrimitivesHelpers.h:156
PMGTools::PMGTruthWeightTool::getSysWeight
virtual float getSysWeight(const xAOD::EventInfo *evtInfo, const CP::SystematicSet &sys) const override
Implements interface from IPMGTruthWeightTool.
Definition: PMGTruthWeightTool.cxx:140
PMGTools::PMGTruthWeightTool::recommendedSystematics
virtual CP::SystematicSet recommendedSystematics() const override
Implements interface from ISystematicsTool.
Definition: PMGTruthWeightTool.cxx:162
ATH_CHECK
#define ATH_CHECK
Definition: AthCheckMacros.h:40
PMGTools::PMGTruthWeightTool::getSysWeightIndex
virtual size_t getSysWeightIndex(const CP::SystematicSet &sys) const override
Implements interface from IPMGTruthWeightTool.
Definition: PMGTruthWeightTool.cxx:148
xAOD::FileMetaData_v1::mcProcID
@ mcProcID
Same as mc_channel_number [float].
Definition: FileMetaData_v1.h:74
PMGTools::weightNameWithPrefix
std::string weightNameWithPrefix(const std::string &name)
cleanup the weight name and add prefix
Definition: WeightHelpers.cxx:72
xAOD::FileMetaData_v1
Class holding file-level metadata about an xAOD file.
Definition: FileMetaData_v1.h:34
PMGTools::PMGTruthWeightTool::m_metaName
std::string m_metaName
Stores the meta data record name.
Definition: PMGTruthWeightTool.h:98
PMGTools::PMGTruthWeightTool::loadPOOLMetaData
StatusCode loadPOOLMetaData()
Loads weight information from POOL using HepMCWeightNames.
Definition: PMGTruthWeightTool.cxx:231
ANA_MSG_VERBOSE
#define ANA_MSG_VERBOSE(xmsg)
Macro printing verbose messages.
Definition: Control/AthToolSupport/AsgMessaging/AsgMessaging/MessageCheck.h:286
name
std::string name
Definition: Control/AthContainers/Root/debug.cxx:192
PMGTools::PMGTruthWeightTool::m_metaDataContainer
const xAOD::TruthMetaDataContainer * m_metaDataContainer
Ptr to the meta data container for this file.
Definition: PMGTruthWeightTool.h:104
EventInfo.h
xAOD::EventInfo_v1
Class describing the basic event information.
Definition: EventInfo_v1.h:43
AthAnalysisHelper.h
DataVector::end
const_iterator end() const noexcept
Return a const_iterator pointing past the end of the collection.
RCU::substitute
std::string substitute(const std::string &str, const std::string &pattern, const std::string &with)
effects: substitute all occurences of "pattern" with "with" in the string "str" returns: the substitu...
Definition: StringUtil.cxx:24
PMGTools::PMGTruthWeightTool::m_mcChannelNumber
uint32_t m_mcChannelNumber
Current MC channel number.
Definition: PMGTruthWeightTool.h:101
DiTauMassTools::MaxHistStrategyV2::e
e
Definition: PhysicsAnalysis/TauID/DiTauMassTools/DiTauMassTools/HelperFunctions.h:26
FileMetaData.h
PMGTools::PMGTruthWeightTool::m_weightNames
std::vector< std::string > m_weightNames
Available weight names for this file.
Definition: PMGTruthWeightTool.h:110
ATH_MSG_WARNING
#define ATH_MSG_WARNING(x)
Definition: AthMsgStreamMacros.h:32
CP::SystematicRegistry
This module implements the central registry for handling systematic uncertainties with CP tools.
Definition: SystematicRegistry.h:25
LArNewCalib_DelayDump_OFC_Cali.idx
idx
Definition: LArNewCalib_DelayDump_OFC_Cali.py:69
PMGTools::PMGTruthWeightTool::validateWeightLocationCaches
StatusCode validateWeightLocationCaches()
Validate weight caches.
Definition: PMGTruthWeightTool.cxx:261
xAOD::EventInfo_v1::mcEventWeight
float mcEventWeight(size_t i=0) const
The weight of one specific MC event used in the simulation.
Definition: EventInfo_v1.cxx:203
DataVector::at
const T * at(size_type n) const
Access an element, as an rvalue.
CP::SystematicsCache::affectingSystematics
const CP::SystematicSet & affectingSystematics() const noexcept
the list of affecting systematics
Definition: SystematicsCache.h:170
PMGTools::PMGTruthWeightTool::getWeightNames
virtual const std::vector< std::string > & getWeightNames() const override
Implements interface from IPMGTruthWeightTool.
Definition: PMGTruthWeightTool.cxx:106
CP::SystematicsCache::add
StatusCode add(const CP::SystematicSet &sys, CalibData value)
add an individual systematic variation
Definition: SystematicsCache.h:255
CP::SystematicsCache::get
StatusCode get(const CP::SystematicSet &sys, const CalibData *&result) const
get the pointer to the cached calibration data for the given systematic, calculating it if necessary
Definition: SystematicsCache.h:189
python.compressB64.c
def c
Definition: compressB64.py:93
DataVector::size
size_type size() const noexcept
Returns the number of elements in the collection.
PMGTools::PMGTruthWeightTool::affectingSystematics
virtual CP::SystematicSet affectingSystematics() const override
Implements interface from ISystematicsTool.
Definition: PMGTruthWeightTool.cxx:156
PMGTools::PMGTruthWeightTool::getWeight
virtual float getWeight(const xAOD::EventInfo *evtInfo, const std::string &weightName) const override
Implements interface from IPMGTruthWeightTool.
Definition: PMGTruthWeightTool.cxx:111
DataVector::begin
const_iterator begin() const noexcept
Return a const_iterator pointing at the beginning of the collection.
CP::SystematicRegistry::getInstance
static SystematicRegistry & getInstance()
Get the singleton instance of the registry for the curren thread.
Definition: SystematicRegistry.cxx:25
AthAnalysisHelper::retrieveMetadata
static std::string retrieveMetadata(const std::string &folder, const std::string &key, const ServiceHandle< StoreGateSvc > &inputMetaStore)
method that always returns as a string you can use from, e.g, pyROOT with evt = ROOT....
Definition: AthAnalysisHelper.h:254