ATLAS Offline Software
Loading...
Searching...
No Matches
MetaDataAlg.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
3*/
4#include "MetaDataAlg.h"
5
13
14
15namespace {
16 std::string ReplaceExpInString(std::string str, const std::string &exp, const std::string &rep) {
17 size_t ExpPos = str.find(exp);
18 if (ExpPos == std::string::npos) return str;
19 str.replace(ExpPos,exp.size(),rep);
20 if (str.find(exp) != std::string::npos) return ReplaceExpInString(std::move(str), exp, rep);
21 return str;
22 }
23
24}
25namespace MuonVal{
26
28 ATH_MSG_INFO("Initializing " << name() << "...");
29 ATH_CHECK(m_infoKey.initialize());
30 m_MetaDataTree = std::make_unique<MuonTesterTree>("MetaDataTree", m_stream);
31 ATH_CHECK(m_MetaDataTree->init(this));
32
33 if (!m_prwTool.empty()) {
34 ATH_CHECK(m_prwTool.retrieve());
35 m_hasPrwTool = true;
36 }
37 if (m_storeLHE && !m_isData) {
38 std::map<std::string, int> weight_names{};
39 AthAnalysisHelper::retrieveMetadata("/Generation/Parameters", "HepMCWeightNames", weight_names).isSuccess();
40 EventInfoBranch::setNumLHE(weight_names.size());
41 }
42 return StatusCode::SUCCESS;
43}
44
46 if (m_sim_meta.empty() == m_run_meta.empty()) {
47 ATH_MSG_FATAL("Found run and simulation meta data");
48 return StatusCode::FAILURE;
49 }
51 m_MetaDataTree->newScalar<bool>("isData", m_isData);
52 m_MetaDataTree->newScalar<bool>("isDerivedAOD", m_isDerivedAOD);
55 ATH_CHECK(m_MetaDataTree->write());
56 m_MetaDataTree.reset();
57
58 return StatusCode::SUCCESS;
59}
60
61StatusCode MetaDataAlg::execute(const EventContext& ctx) {
62 ATH_MSG_DEBUG("Executing " << name() << "...");
63 setFilterPassed(true, ctx);
64
66 if (!evtInfo.isValid()) {
67 ATH_MSG_FATAL("Failed to retrieve " << m_infoKey.fullKey());
68 return StatusCode::FAILURE;
69 }
70
71 bool isData = !evtInfo->eventType(xAOD::EventInfo::IS_SIMULATION);
72
73 int mc_channel = !isData ? evtInfo->mcChannelNumber() : 0.;
74 unsigned int run_number = evtInfo->runNumber();
75 if (isData) {
76 std::string trigger_stream{};
77 ATH_CHECK(AthAnalysisHelper::retrieveMetadata("/TagInfo", "triggerStreamOfFile", trigger_stream));
78
79 std::vector<RunMetaData>::iterator itr =
80 std::find_if(m_run_meta.begin(), m_run_meta.end(), [&run_number, &trigger_stream](const RunMetaData& meta) {
81 return meta.run_number == run_number && meta.trigger_stream == trigger_stream;
82 });
83 if (itr == m_run_meta.end()) {
84 ATH_MSG_WARNING("No meta data information is available for " << run_number << ". Please check on which stream you're running");
85 m_run_meta.emplace_back(run_number, trigger_stream);
86 itr = m_run_meta.end() - 1;
87 }
88 itr->proc_events += 1;
89 itr->processed_blocks.insert(evtInfo->lumiBlock());
90 if (!itr->has_book_keeper) {
91 itr->total_lumi_blocks.insert(evtInfo->lumiBlock());
92 itr->tot_events += 1;
93 }
94 } else {
95 const unsigned int num_lhe = !m_storeLHE ? 1 : evtInfo->mcEventWeights().size();
96 for (unsigned int lhe_var = 0; lhe_var < num_lhe; ++lhe_var) {
97 std::vector<SimMetaData>::iterator itr =
98 std::find_if(m_sim_meta.begin(), m_sim_meta.end(), [&mc_channel, &run_number, &lhe_var](const SimMetaData& meta) {
99 return meta.mc_channel == mc_channel && meta.prw_channel == run_number && meta.variation_number == lhe_var;
100 });
101 if (itr == m_sim_meta.end()) {
102 ATH_MSG_WARNING("Failed to retrieve a proper meta data for dsid: " << mc_channel << " period: " << run_number
103 << " lhe weight: " << lhe_var);
104 m_sim_meta.emplace_back(mc_channel, run_number);
105 itr = m_sim_meta.end() - 1;
106 itr->weight_name = "IncompleteMetaData";
107 itr->variation_number = lhe_var;
108 }
109 itr->proc_events += 1;
110 if (itr->has_book_keeper) continue;
111 if (!itr->warned) {
112 ATH_MSG_WARNING("Cut book keeper has not been loaded for sample DSID: "
113 << itr->mc_channel << " period: " << itr->prw_channel << " lhe variation: " << lhe_var);
114 itr->warned = true;
115 }
116 itr->tot_events += 1;
117 const double weight = evtInfo->mcEventWeight(lhe_var);
118 itr->sum_w += weight;
119 itr->sum_w_squared += weight * weight;
120 }
121 }
122
123 return StatusCode::SUCCESS;
124}
125const xAOD::CutBookkeeper* MetaDataAlg::RetrieveCutBookKeeper(const std::string& Stream, const std::string& cbk_name) const {
126 const xAOD::CutBookkeeper* all = nullptr;
128 const xAOD::CutBookkeeperContainer* bks = nullptr;
129 if (!inputMetaStore()->retrieve(bks, "CutBookkeepers").isSuccess()) {
130 ATH_MSG_WARNING("Could not retrieve the CutBookKeeperContainer. Although it should be there");
131 return all;
132 }
133 int maxCycle = -1; // need to find the max cycle where input stream is StreamAOD and the name is AllExecutedEvents
134 for (const xAOD::CutBookkeeper* cbk : *bks) {
135 ATH_MSG_INFO("Check cutbook keeper "<<cbk->inputStream()<<" name: "<<cbk->name()<<" cycle: "<<cbk->cycle());
136 if (cbk->inputStream() == Stream && cbk->name() == cbk_name && cbk->cycle() > maxCycle) {
137 maxCycle = cbk->cycle();
138 all = cbk;
139 }
140 }
141 } else ATH_MSG_WARNING("The CutBookkeepers are not present in the file ");
142 if (!all) ATH_MSG_DEBUG("Failed to retrieve cut book keeper for Stream: "<<Stream<<" cbk_name: "<<cbk_name);
143 return all;
144}
146 //
147 // This method is called at the start of each input file, even if
148 // the input file contains no events. Accumulate metadata information here
149 //
150 const EventStreamInfo* esi = nullptr;
151 ATH_CHECK(inputMetaStore()->retrieve(esi));
152 if (esi->getEventTypes().size() > 1) { ATH_MSG_WARNING("There seem to be more event types than one"); }
153 if (esi->getEventTypes().size() == 0) {
154 ATH_MSG_FATAL("The EventTypes() container of the EventStreamInfo is empty! Something wrong with the input file?");
155 return StatusCode::FAILURE;
156 }
157
158 bool isData = !esi->getEventTypes().begin()->test(EventType::IS_SIMULATION);
159
160 const xAOD::FileMetaData* fmd = nullptr;
161 if (inputMetaStore()->contains<xAOD::FileMetaData>("FileMetaData")) ATH_CHECK(inputMetaStore()->retrieve(fmd, "FileMetaData"));
162 if (!fmd) {
163 ATH_MSG_WARNING("FileMetaData not found in input file, setting m_isDerivedAOD=false.");
164 // m_isDerivedAOD = false;
165 } else {
166 std::string dataType{};
167 if (!(fmd->value(xAOD::FileMetaData::MetaDataType::dataType, dataType))) {
168 ATH_MSG_WARNING("MetaDataType::dataType not found in xAOD::FileMetaData, setting m_isDerivedAOD=false.");
169 // m_isDerivedAOD = false;
170 }
171 ATH_MSG_DEBUG("Data type is " << dataType);
172 }
173 const xAOD::CutBookkeeper* all{nullptr};
174 std::string cbk_stream{};
175 using namespace std::literals;
176 for (const std::string & trial: {"StreamAOD"s, "StreamESD"s, "unknownStream"s }) {
177 all = RetrieveCutBookKeeper(trial);
178 cbk_stream = trial;
179 if (all) break;
180 }
181 const bool contains_keeper = all != nullptr;
182 if (!contains_keeper) {
183 ATH_MSG_WARNING("No Common CutBook keeper has been found");
184 }
186 if (isData) {
187 std::string trigger_stream{};
188 ATH_CHECK(AthAnalysisHelper::retrieveMetadata("/TagInfo", "triggerStreamOfFile", trigger_stream));
189 unsigned int run_number = (*esi->getRunNumbers().begin());
190 std::vector<RunMetaData>::iterator itr =
191 std::find_if(m_run_meta.begin(), m_run_meta.end(), [&run_number, &trigger_stream](const RunMetaData& meta) {
192 return meta.run_number == run_number && trigger_stream == meta.trigger_stream;
193 });
195 if (itr == m_run_meta.end()) {
196 m_run_meta.emplace_back(run_number, trigger_stream);
197 itr = m_run_meta.end() - 1;
198 }
199
201 for (const auto& Lumi : esi->getLumiBlockNumbers()) { itr->total_lumi_blocks.insert(Lumi); }
202 itr->has_book_keeper = contains_keeper;
203 if (contains_keeper) itr->tot_events += all->nAcceptedEvents();
204 } else {
205 int dsid = esi->getEventTypes().begin()->mc_channel_number();
206 unsigned int run = (*esi->getRunNumbers().begin());
207 ATH_MSG_DEBUG("DSID: "<<dsid<<" prw number: "<<run);
209 std::vector<std::string> weight_names{};
210 if (m_storeLHE) {
211 std::map<std::string, int> weight_map{};
212 AthAnalysisHelper::retrieveMetadata("/Generation/Parameters", "HepMCWeightNames", weight_map).isSuccess();
213 weight_names.resize(weight_map.size());
214 for (const auto& w_pair : weight_map) { weight_names[w_pair.second] = w_pair.first; }
215 if (weight_names.empty()) {
216 ATH_MSG_WARNING("No weight names extracted from the meta data ");
217 weight_names.push_back("");
218 }
219 } else
220 weight_names.push_back("");
221
222 for (unsigned int lhe_var = 0; lhe_var < weight_names.size(); ++lhe_var) {
223 const std::string& lhe_weight = weight_names[lhe_var];
224 std::vector<SimMetaData>::iterator itr =
225 std::find_if(m_sim_meta.begin(), m_sim_meta.end(), [&dsid, &run, &lhe_var](const SimMetaData& meta) {
226 return meta.mc_channel == dsid && meta.prw_channel == run && meta.variation_number == lhe_var;
227 });
228 if (itr == m_sim_meta.end()) {
229 m_sim_meta.emplace_back(dsid, run);
230 itr = m_sim_meta.end() - 1;
231 itr->weight_name = weight_names[lhe_var];
232 itr->variation_number = lhe_var;
233 if (m_hasPrwTool) itr->prw_lumi = m_prwTool->expert()->GetIntegratedLumi(run, 0, -1);
234 }
235
236 const xAOD::CutBookkeeper* mc_keeper = lhe_var == 0 ? all : nullptr;
237 if (lhe_var) {
238 std::vector<std::string> cb_names;
239 cb_names.emplace_back(lhe_weight);
240 cb_names.emplace_back("LHE3Weight_" + ReplaceExpInString(lhe_weight, ".", ""));
241 cb_names.push_back(ReplaceExpInString(cb_names.back(), " ", ""));
242 cb_names.emplace_back("AllExecutedEvents_NonNominalMCWeight_" + std::to_string(lhe_var));
243 for (const std::string& cb_name : cb_names) {
244 mc_keeper = RetrieveCutBookKeeper(cbk_stream, cb_name);
245 if (mc_keeper) {
246 ATH_MSG_DEBUG("Found LHE cut book keeper " << cb_name);
247 break;
248 }
249 }
250 }
251
252 itr->has_book_keeper = (mc_keeper != nullptr);
253
254 if (itr->has_book_keeper) {
255 //coverity[FORWARD_NULL:FALSE]
256 itr->tot_events += mc_keeper->nAcceptedEvents();
257 itr->sum_w += mc_keeper->sumOfEventWeights();
258 itr->sum_w_squared += mc_keeper->sumOfEventWeightsSquared();
259 }
260 }
261 }
262 std::sort(m_sim_meta.begin(), m_sim_meta.end());
263 std::sort(m_run_meta.begin(), m_run_meta.end());
264 if (m_sim_meta.empty() == m_run_meta.empty()) {
265 ATH_MSG_FATAL("Found run and simulation meta data");
266 return StatusCode::FAILURE;
267 }
268 if (m_run_meta.empty() == m_isData) {
269 ATH_MSG_FATAL("Metadata is inconsistent with the configuration");
270 return StatusCode::FAILURE;
271 }
272 return StatusCode::SUCCESS;
273}
275
276 ScalarBranch<Long64_t>& tot_ev {m_MetaDataTree->newScalar<Long64_t>("TotalEvents")};
277 ScalarBranch<Long64_t>& proc_ev {m_MetaDataTree->newScalar<Long64_t>("ProcessedEvents")};
278 ScalarBranch<unsigned int>& run_number{m_MetaDataTree->newScalar<unsigned int>("runNumber")};
279
280 SetBranch<unsigned int>& tot_lumi{m_MetaDataTree->newSet<unsigned int>("TotalLumiBlocks")};
281 SetBranch<unsigned int>& proc_lumi{m_MetaDataTree->newSet<unsigned int>("ProcessedLumiBlocks")};
282 ScalarBranch<std::string>& stream_name{m_MetaDataTree->newScalar<std::string>("triggerStream")};
283 ATH_CHECK(m_MetaDataTree->init(this));
284 for (const RunMetaData& meta : m_run_meta) {
285 run_number = meta.run_number;
286 tot_ev = meta.tot_events;
287 proc_ev = meta.proc_events;
288 stream_name = meta.trigger_stream;
289 tot_lumi = meta.total_lumi_blocks;
290 proc_lumi = meta.processed_blocks;
291 m_MetaDataTree->fill(Gaudi::Hive::currentContext());
292 }
293 return StatusCode::SUCCESS;
294}
296 m_MetaDataTree->newScalar<bool>("isAF2", m_isAF2);
297 ScalarBranch<Long64_t>& tot_ev {m_MetaDataTree->newScalar<Long64_t>("TotalEvents")};
298 ScalarBranch<Long64_t>& proc_ev {m_MetaDataTree->newScalar<Long64_t>("ProcessedEvents")};
299 ScalarBranch<unsigned int>& run_number{m_MetaDataTree->newScalar<unsigned int>("runNumber")};
300
301 ScalarBranch<double>& sum_w{m_MetaDataTree->newScalar<double>("TotalSumW")};
302 ScalarBranch<double>& sum_w2{m_MetaDataTree->newScalar<double>("TotalSumW2")};
303 ScalarBranch<double>& prw_lumi{m_MetaDataTree->newScalar<double>("prwLuminosity")};
304
305 ScalarBranch<int>& mc_dsid{m_MetaDataTree->newScalar<int>("mcChannelNumber")};
306 ScalarBranch<unsigned int>& lhe_var{m_MetaDataTree->newScalar<unsigned int>("LheId")};
307 ScalarBranch<std::string>& stream_name{m_MetaDataTree->newScalar<std::string>("LheWeightName")};
308
309 if (!m_hasPrwTool) m_MetaDataTree->disableBranch(prw_lumi.name());
310 ATH_CHECK(m_MetaDataTree->init(this));
311
312 for (const SimMetaData& meta : m_sim_meta) {
313 run_number = meta.prw_channel;
314 mc_dsid = meta.mc_channel;
315 lhe_var = meta.variation_number;
316
317 prw_lumi = meta.prw_lumi;
318 sum_w = meta.sum_w;
319 sum_w2 = meta.sum_w_squared;
320 stream_name = meta.weight_name;
321
322 tot_ev = meta.tot_events;
323 proc_ev = meta.proc_events;
324 m_MetaDataTree->fill(Gaudi::Hive::currentContext());
325 }
326 return StatusCode::SUCCESS;
327}
328}
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_FATAL(x)
#define ATH_MSG_INFO(x)
#define ATH_MSG_WARNING(x)
#define ATH_MSG_DEBUG(x)
This file contains the class definition for the EventStreamInfo class.
Handle class for reading from StoreGate.
void setFilterPassed(bool state) const
const ServiceHandle< StoreGateSvc > & inputMetaStore() const
Const accessor for the input metadata store.
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....
This class provides the summary information stored for data written as a Event Stream.
const std::set< unsigned int > & getLumiBlockNumbers() const
const std::set< unsigned int > & getRunNumbers() const
const std::set< EventType > & getEventTypes() const
static const EventTypeCode IS_SIMULATION
true: IS_SIMULATION, false: IS_DATA
Definition EventType.h:156
static void setNumLHE(unsigned int numLHE) ATLAS_THREAD_SAFE
Specify the number of LHE variations that are available in the sample.
std::vector< SimMetaData > m_sim_meta
StatusCode beginInputFile() override
Function called when a new input file is opened user can read input metadata from inputMetaStore().
Gaudi::Property< bool > m_isData
Definition MetaDataAlg.h:32
const xAOD::CutBookkeeper * RetrieveCutBookKeeper(const std::string &stream, const std::string &cbk_name="AllExecutedEvents") const
StatusCode finalize() override
StatusCode fillSimulationTree()
StatusCode initialize() override
std::vector< RunMetaData > m_run_meta
std::unique_ptr< MuonTesterTree > m_MetaDataTree
Meta data tree object.
Definition MetaDataAlg.h:43
SG::ReadHandleKey< xAOD::EventInfo > m_infoKey
Definition MetaDataAlg.h:27
Gaudi::Property< bool > m_storeLHE
Store LHE weights.
Definition MetaDataAlg.h:38
Gaudi::Property< bool > m_isAF2
On AFII simulation.
Definition MetaDataAlg.h:36
StatusCode execute(const EventContext &ctx) override
Execute method.
StatusCode fillDataTree()
Gaudi::Property< bool > m_isDerivedAOD
Is derived DAOD property.
Definition MetaDataAlg.h:34
ToolHandle< CP::IPileupReweightingTool > m_prwTool
Definition MetaDataAlg.h:40
Gaudi::Property< std::string > m_stream
Output file stream.
Definition MetaDataAlg.h:29
std::string name() const override final
Returns the name of the branch.
virtual bool isValid() override final
Can the handle be successfully dereferenced?
double sumOfEventWeightsSquared() const
Get the sum-of-(event-weights-squared) that this CutBookkeeper has seen.
double sumOfEventWeights() const
Get the sum-of-event-weights that this CutBookkeeper has seen.
uint64_t nAcceptedEvents() const
Get the number of accepted events that this CutBookkeeper has seen.
@ IS_SIMULATION
true: simulation, false: data
@ dataType
Data type that's in the file [string].
bool value(MetaDataType type, std::string &val) const
Get a pre-defined string value out of the object.
bool contains(const std::string &s, const std::string &regx)
does a string contain the substring
Definition hcg.cxx:116
std::string ReplaceExpInString(std::string str, const std::string &exp, const std::string &rep)
Replaces all expressions an string by something else.
Class to store array like branches into the n-tuples.
Definition HitValAlg.cxx:19
-diff
void sort(typename DataModel_detail::iterator< DVL > beg, typename DataModel_detail::iterator< DVL > end)
Specialization of sort for DataVector/List.
CutBookkeeper_v1 CutBookkeeper
Define the latest version of the CutBookkeeper class.
FileMetaData_v1 FileMetaData
Declare the latest version of the class.
CutBookkeeperContainer_v1 CutBookkeeperContainer
Define the latest version of the CutBookkeeperContainer class.
Helper structs to cache the meta-data for simulation and recorded data.
Definition MetaDataAlg.h:47
int run(int argc, char *argv[])