ATLAS Offline Software
Loading...
Searching...
No Matches
TruthParentDecoratorAlg.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
3*/
5
8
9#include <format>
10#include <limits>
11#include <set>
12#include <stdexcept>
13
14// structure to hold info on a matched parent particle
16{
19 float deltaR;
20 unsigned int parent_index;
21 std::set<int> cascade_pids;
22};
23
24namespace {
25
26 using Barcodex = TruthParentDecoratorAlg::Barcodex;
30 using parent_mask_t = unsigned long long;
31
32 parent_mask_t matchMask(const std::vector<MatchedParent>& matches) {
33 parent_mask_t mask = 0x0;
34 for (const auto& match: matches) {
35 constexpr size_t max_idx = std::numeric_limits<decltype(mask)>::digits;
36 if (match.parent_index >= max_idx) {
37 throw std::runtime_error(
38 "parent index overflowed the match mask "
39 "[index: " + std::to_string(match.parent_index) +
40 " , max_mask: " + std::to_string(max_idx) + "]");
41 }
42 mask |= (parent_mask_t{1} << match.parent_index);
43 }
44 return mask;
45 }
46
47 // debugging functions
48 std::string join(const std::vector<std::string>& v, const std::string& sep = ", ") {
49 std::string out;
50 for (unsigned int pos = 0; pos < v.size(); pos++) {
51 out.append(v.at(pos));
52 if (pos + 1 < v.size()) out.append(sep);
53 }
54 return out;
55 }
56 template <typename T>
57 std::vector<std::string> stringify(const T& container) {
58 std::vector<std::string> out;
59 for (const auto& v: container) out.push_back(std::to_string(v));
60 return out;
61 }
62 // debugging function, not used now
63 [[maybe_unused]]
64 std::string listAllChildren(const xAOD::TruthParticle* p) {
65 std::vector<std::string> output;
66 for (unsigned int child_n = 0; child_n < p->nChildren(); child_n++) {
67 output.push_back(std::to_string(p->child(child_n)->pdgId()));
68 }
69 if (output.empty()) return "none";
70 return "[" + join(output) + "]";
71 }
72
73
74 // debugging functions using MsgStream
75 void logInputs(MsgStream& msg,SG::ReadHandle<JC>& targets,SG::ReadHandle<TPC>& truth,std::vector<SG::ReadHandle<TPC>>& cascades_raw,const MSG::Level level = MSG::DEBUG)
76 {
77 if (msg.level() > level) return;
78 unsigned int n_cascade_candidates = 0;
79 for (auto& cascade: cascades_raw) {
80 n_cascade_candidates += cascade->size();
81 }
82 msg << level <<
83 "n_targets: " << targets->size() << ", "
84 "n_parents: " << truth->size() << ", "
85 "n_cascade_candidates: " << n_cascade_candidates <<
86 endmsg;
87 }
88 void logIPMap(MsgStream& msg,const IPMap& ipmap,const MSG::Level level = MSG::VERBOSE)
89 {
90 if (msg.level() > level) return;
91 for (const auto& [barcode, children]: ipmap) {
92 std::set<int> ids;
93 for (const xAOD::TruthParticle* dup: children) ids.insert(dup->pdgId());
94 msg << level << "barcode: " << barcode << ", n_dup: " << children.size()
95 << " idg_ids: [" << join(stringify(ids)) << "]" << endmsg;
96 }
97 }
98
99
100 // functions to traverse barcodex and disambiguate the selected
101 // child
102 std::map<int, std::set<int>> findAllDescendants(int parent, const Barcodex& barcodex, std::set<int> history = {})
103 {
104 using return_t = std::map<int,std::set<int>>;
105 auto itr = barcodex.find(parent);
106 if (itr == barcodex.end()) {
107 auto hist = stringify(history);
108 throw std::runtime_error(
109 "can't find barcode " + std::to_string(parent) + " history:"
110 " {" + join(hist) + "}");
111 }
112 const std::set<int>& children = itr->second;
113 if (children.empty()) return return_t{{parent, history}};
114 if (!history.insert(parent).second) {
115 auto hist = stringify(history);
116 throw std::runtime_error("found cycle, tried to add " + std::to_string(parent) + " to {" + join(hist) + "}");
117 }
118 return_t all_children;
119 for (int child: children) {
120 // We don't just merge the children here in case there are
121 // multiple histories that lead to the same discendent. Instead
122 // we merge the histories of all descendents.
123 for (auto& [dec, dh]: findAllDescendants(child, barcodex, history)) {
124 all_children[dec].merge(dh);
125 }
126 }
127 return all_children;
128 }
129
130
131 const xAOD::TruthParticle* selectChild(const IPMap::mapped_type& barkids)
132 {
133 const xAOD::TruthParticle* child = *barkids.begin();
134 if (barkids.size() > 1) {
135 std::set<int> pdg_ids;
136 TLorentzVector sum_p4;
137 // look at duplicates, take the one with the most children
138 for (const xAOD::TruthParticle* dupkid: barkids) {
139 sum_p4 += dupkid->p4();
140 pdg_ids.insert(dupkid->pdgId());
141 if (dupkid->nChildren() > child->nChildren()) child = dupkid;
142 }
143 if (pdg_ids.size() != 1) {
144 throw std::runtime_error("same barcode, different pdgid: [" + join(stringify(pdg_ids)) + "]");
145 }
146 if (float dr = child->p4().DeltaR(sum_p4); dr > 0.001) {
147 throw std::runtime_error( "Same barcode, different vector: { deltaR: " + std::to_string(dr) + ", pdgid: " + std::to_string(child->pdgId()) + "}"
148 );
149 }
150 }
151 return child;
152 }
153
154
155 bool isOriginal(const xAOD::TruthParticle* p) {
156 for (unsigned int parent_n = 0; parent_n < p->nParents(); parent_n++) {
157 const xAOD::TruthParticle* parent = p->parent(parent_n);
158 if (!parent) throw std::runtime_error("broken truth record");
159 if (parent->pdgId() == p->pdgId()) return false;
160 }
161 return true;
162 }
163
164
165 // these functions are for dealing with specific vertices
166
167 const xAOD::TruthParticle* getParent(const xAOD::TruthParticle* p) {
168 if (int n_parents = p->nParents(); n_parents != 1) {
169 throw std::logic_error("can't get parent [n_parents: " + std::to_string(n_parents) + "]");
170 }
171 return p->parent(0);
172 }
173 bool isSoftLepton(const xAOD::TruthParticle* p) {
174 const xAOD::TruthParticle* parent = getParent(p);
175 return (parent->hasCharm() || parent->hasBottom()) && p->isChLepton();
176 }
177 bool isSoftCharm(const xAOD::TruthParticle* p) {
178 const xAOD::TruthParticle* parent = getParent(p);
179 return parent->hasBottom() && p->hasCharm();
180 }
181
182}
183
184
185// cascade count decorator
186CascadeCountDecorator::CascadeCountDecorator( const std::string& name, const std::vector<int>& pids):
187 m_pids(pids.begin(), pids.end()),
188 m_dec(name),
189 // also hang on to the auxid so we can lock it later
190 m_auxid(SG::AuxTypeRegistry::instance().findAuxID(name))
191{
192}
193void CascadeCountDecorator::decorate(const SG::AuxElement& target,const std::vector<MatchedParent>& parents) const
194{
195 unsigned char n_match = 0;
196 for (const auto& parent: parents) {
197 for (const auto& pid: m_pids) {
198 if (parent.cascade_pids.contains(pid)) n_match++;
199 }
200 }
201 m_dec(target) = n_match;
202}
204{
205 m_dec(target) = 0;
206}
208{
209 // We're locking a decoration on a const container, which would be a
210 // problem if they were made by anyone else since someone else might
211 // be messing with them. But here it shouldn't be a problem since we
212 // made them.
213 auto* cont ATLAS_THREAD_SAFE = const_cast<xAOD::IParticleContainer*>(target);
214 cont->lockDecoration(m_auxid);
215}
216
217
218// main algorithm
219TruthParentDecoratorAlg::TruthParentDecoratorAlg(const std::string& name, ISvcLocator* loc):
220 AthReentrantAlgorithm(name, loc)
221{
222 // these aren't user configurable
223 declare(m_target_pdgid_key);
224 declare(m_target_dr_truth_key);
225 declare(m_target_link_key);
226 declare(m_target_index_key);
227 declare(m_target_n_matched_key);
229 declare(m_match_pdgid_key);
230 declare(m_match_children_key);
231 declare(m_match_link_key);
232}
233
235 // initialize inputs
236 ATH_CHECK(m_parents_key.initialize());
237 ATH_CHECK(m_target_container_key.initialize());
238 ATH_CHECK(m_cascades_key.initialize());
239 // weird hack because Gaudi can't handle an infinite default
240 if (m_match_delta_r.value() <= 0) m_match_delta_r.value() = INFINITY;
241 // initialize outputs
242 std::string jc = m_target_container_key.key();
243 std::string pfx = jc + "." + m_prefix.value();
244 m_target_pdgid_key = pfx + "PdgId";
245 m_target_dr_truth_key = pfx + "DRTruthParticle";
246 m_target_link_key = pfx + "Link";
247 m_target_index_key = pfx + "Index";
248 m_target_n_matched_key = pfx + "NMatchedChildren";
249 m_target_match_mask_key = pfx + "ParentsMask";
250 m_match_pdgid_key = pfx + "MatchingParticlePdgId";
251 m_match_children_key = pfx + "MatchingParticleNChildren";
252 m_match_link_key = pfx + "MatchingParticleLink";
253 ATH_CHECK(m_target_pdgid_key.initialize());
254 ATH_CHECK(m_target_dr_truth_key.initialize());
255 ATH_CHECK(m_target_link_key.initialize());
256 ATH_CHECK(m_target_index_key.initialize());
257 ATH_CHECK(m_target_n_matched_key.initialize());
259 ATH_CHECK(m_match_pdgid_key.initialize());
260 ATH_CHECK(m_match_children_key.initialize());
261 ATH_CHECK(m_match_link_key.initialize());
262
263 for (auto& [key, pids]: m_counts_matching_cascade) {
264 m_cascade_count_writer_keys.emplace_back(jc + "." + key);
265 m_cascade_count_decorators.emplace_back(key, pids);
266 }
267 for (auto& key: m_cascade_count_writer_keys) declare(key);
269
270 // ATLASRECTS-8290: this should be removed eventually
272
273 return StatusCode::SUCCESS;
274}
275
276StatusCode TruthParentDecoratorAlg::execute(const EventContext& cxt) const
277{
278 ATH_MSG_DEBUG("Executing");
279
281 // part 1: read in the particles
284
285 using uc_t = unsigned char;
295
296 if (targets->empty()) return StatusCode::SUCCESS;
297
298 // read in and sort the parent collection
300 std::set<int> parentids(m_parent_pdgids.begin(), m_parent_pdgids.end());
301 std::vector<const xAOD::TruthParticle*> psort;
302 for (const xAOD::TruthParticle* p: *phandle) {
303 if (!parentids.contains(p->pdgId())) continue;
304 if (!isOriginal(p)) continue;
305 psort.push_back(p);
306 }
307 // for lack of a better idea, store truth parents sorted by mass
308 std::sort(psort.begin(), psort.end(),[](const auto* p1, const auto* p2) {return p1->m() > p2->m();});
309 // check to make sure we don't overflow the match mask
310 constexpr size_t max_idx = std::numeric_limits<parent_mask_t>::digits;
311 if (psort.size() > max_idx) {
313 "Found too many parent particles to store in parent match mask "
314 "truncating the parent collection [max: " << max_idx << ", "
315 "n: " << psort.size() << "]");
316 psort.resize(max_idx);
317 }
318
319
320 std::vector<SG::ReadHandle<TPC>> cascades_raw;
321 for (const auto& key: m_cascades_key) {
322 cascades_raw.emplace_back(key, cxt);
323 }
324 logInputs(msgStream(), targets, phandle, cascades_raw);
325
327 // part 2: build the barcodex
329 Barcodex barcodex;
330 IPMap ipmap;
331 addTruthContainer(barcodex, ipmap, *phandle);
332 for (auto& cascade: cascades_raw) {
333 addTruthContainer(barcodex, ipmap, *cascade);
334 }
335 logIPMap(msg(), ipmap);
336
337 ATH_MSG_DEBUG("merged cascade contains " << barcodex.size() << " particles");
338
340 // Part 3: build map from targets to parents
342 std::unordered_map<const J*, std::vector<MatchedParent>> labeled_targets;
343 unsigned int n_parents = 0;
344 for (const auto* p: psort) {
345 unsigned int parent_index = n_parents++;
346 // ATLASRECTS-8290: this should be replaced with ->uid()
347 ATH_MSG_VERBOSE("pdgid: " << p->pdgId() << ", barcode: " << m_uid(*p));
348 for (auto& [cbar, histbars]: findAllDescendants(m_uid(*p), barcodex)) {
349 IPMap::mapped_type& barkids = ipmap.at(cbar);
350 const xAOD::TruthParticle* child = selectChild(barkids);
351 std::vector<std::pair<float, const J*>> drs;
352 float drsMinDR=9999;
353 const J* drsMinMatch = 0;
354 for (const auto* j: *targets) {
355 if(j->p4().DeltaR(child->p4()) < drsMinDR) {
356 drsMinDR=j->p4().DeltaR(child->p4());
357 drsMinMatch=j;
358 }
359 }
360 if(drsMinMatch){
362 match.parent = p;
363 match.child = child;
364 match.deltaR = drsMinDR;
365 match.parent_index = parent_index;
366 match.cascade_pids.insert(child->pdgId());
367 for (auto& histbar: histbars) {
368 match.cascade_pids.insert(selectChild(ipmap.at(histbar))->pdgId());
369 }
370 if (match.deltaR < m_match_delta_r) {
371 labeled_targets[drsMinMatch].push_back(std::move(match));
372 }
373 }
374 }
375 }
376
378 // Part 4: decorate!
380
381 for (const J* j: *targets) {
382 if (labeled_targets.contains(j)) {
383 const std::vector<MatchedParent>& matches = labeled_targets.at(j);
384 auto min_dr = [](auto& p1, auto& p2) {
385 return p1.deltaR < p2.deltaR;
386 };
387 const MatchedParent& nearest = *std::min_element(
388 matches.begin(), matches.end(), min_dr);
389 const xAOD::TruthParticle* p = nearest.parent;
390 pdgid(*j) = p->pdgId();
391 deltaR(*j) = nearest.deltaR;
392 auto* container = dynamic_cast<const TPC*>(p->container());
393 link(*j) = JL(*container, p->index());
394 index(*j) = nearest.parent_index;
395 nMatched(*j) = matches.size();
396 mask(*j) = matchMask(matches);
397 const xAOD::TruthParticle* child = nearest.child;
398 matchPdgId(*j) = child->pdgId();
399 matchChildCount(*j) = child->nChildren();
400 auto* matchedContainer = dynamic_cast<const TPC*>(child->container());
401 matchLink(*j) = JL(*matchedContainer, child->index());
402 for (const auto& cascadeCount: m_cascade_count_decorators) {
403 cascadeCount.decorate(*j, matches);
404 }
405 } else {
406 pdgid(*j) = 0;
407 deltaR(*j) = NAN;
408 link(*j) = JL();
409 index(*j) = -1;
410 nMatched(*j) = -1;
411 mask(*j) = 0x0;
412 matchPdgId(*j) = 0;
413 matchChildCount(*j) = 0;
414 matchLink(*j) = JL();
415 for (const auto& cascadeCount: m_cascade_count_decorators) {
416 cascadeCount.decorateDefault(*j);
417 }
418 }
419 }
420
422 // Part 5: lock decorations
424
425 for (const auto& dec: m_cascade_count_decorators) {
426 dec.lock(targets.get());
427 }
428
429 return StatusCode::SUCCESS;
430}
431
433 if (!m_allow_missing_children_pdgids.empty()) {
434 float missing_fraction = double(m_missing_n_ignored) / m_total_children;
435 auto msg = std::format("ignored {} missing children out of {} ({:.2}%)",m_missing_n_ignored.load(),m_total_children.load(),missing_fraction * 100);
436 if (missing_fraction > m_missing_children_fraction_warning_threshold) {
438 } else {
440 }
441 }
442 if (!m_warn_missing_children_pdgids.empty()) {
443 auto msg = std::format("warned of {} missing children out of {}", m_missing_n_warned.load(), m_total_children.load());
444 if (m_missing_n_warned > 0) {
446 } else {
448 }
449 }
450 return StatusCode::SUCCESS;
451}
452
454
455 std::set<int> targid(m_cascade_pdgids.begin(), m_cascade_pdgids.end());
456 // we allow decays through any of the parent pdgids
457 targid.insert(m_parent_pdgids.begin(), m_parent_pdgids.end());
458
459 // this determines if a cascade vertex should be saved or not
460 auto cascadeWants = [
461 &targid,
462 &b=m_add_b,
463 &c=m_add_c,
466 ] (const xAOD::TruthParticle* p) {
467 if (int n_parents = p->nParents(); n_parents == 1) {
468 if (vsl && isSoftLepton(p)) return false;
469 if (vsc && isSoftCharm(p)) return false;
470 }
471 if (targid.contains(p->pdgId())) return true;
472 if (b && p->hasBottom()) return true;
473 if (c && p->hasCharm()) return true;
474 return false;
475 };
476
477 // insert a particle into the record, return the child set
478 // ATLASRECTS-8290: this should be replaced with ->uid()
479 auto insert = [this, &barcodex, &ipmap](const auto* p) -> auto& {
480 ipmap[m_uid(*p)].insert(p);
481 return barcodex[m_uid(*p)];
482 };
483
484 for (const xAOD::TruthParticle* p: container) {
485 if (cascadeWants(p)) {
486 auto& child_set = insert(p);
487 for (unsigned int child_n = 0; child_n < p->nChildren(); child_n++) {
488 const xAOD::TruthParticle* c = p->child(child_n);
489
490 // Unfortunately the truth record is often broken in various
491 // ways. There are a few configurable ways to deal with
492 // this. We keep track of the total number and how often we
493 // use these workarounds to make sure things don't go too
494 // crazy.
496 const auto& ok_missing = m_allow_missing_children_pdgids.value();
497 if (!c) {
498 if(ok_missing.contains(p->pdgId())) {
500 } else {
501 auto problem = std::format(
502 "null truth child [barcode={},pdg_id={},child={}of{}]",
503 // ATLASRECTS-8290: m_uid should be replaced with ->uid()
504 m_uid(*p), p->pdgId(), child_n, p->nChildren());
505 const auto& warn_missing = m_warn_missing_children_pdgids.value();
506 if (warn_missing.contains(p->pdgId())) {
508 ATH_MSG_WARNING(problem);
509 } else {
510 throw std::runtime_error(problem);
511 }
512 }
513 } else if (cascadeWants(c)) {
514 insert(c);
515 // ATLASRECTS-8290: m_uid should be replaced with ->uid()
516 child_set.insert(m_uid(*c));
517 }
518 };
519 }
520 }
521}
Scalar deltaR(const MatrixBase< Derived > &vec) const
#define endmsg
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_INFO(x)
#define ATH_MSG_VERBOSE(x)
#define ATH_MSG_WARNING(x)
#define ATH_MSG_DEBUG(x)
ATLAS-specific HepMC functions.
std::map< std::string, double > instance
Handle class for adding a decoration to an object.
std::string stringify(T obj)
#define ATLAS_THREAD_SAFE
An algorithm that can be simultaneously executed in multiple threads.
void decorate(const SG::AuxElement &target, const std::vector< MatchedParent > &parents) const
SG::AuxElement::Decorator< unsigned char > m_dec
CascadeCountDecorator(const std::string &name, const std::vector< int > &pids)
void decorateDefault(const SG::AuxElement &target) const
void lock(const xAOD::IParticleContainer *target) const
Base class for elements of a container that can have aux data.
Definition AuxElement.h:484
const SG::AuxVectorData * container() const
Return the container holding this element.
size_t index() const
Return the index of this element within its container.
Helper class to provide constant type-safe access to aux data.
const_pointer_type get() const
Dereference the pointer, but don't cache anything.
Handle class for adding a decoration to an object.
SG::WriteDecorHandleKeyArray< JC > m_cascade_count_writer_keys
void addTruthContainer(Barcodex &, IPMap &, const TPC &) const
Gaudi::Property< std::unordered_set< int > > m_allow_missing_children_pdgids
Gaudi::Property< bool > m_add_c
Gaudi::Property< bool > m_veto_soft_lepton
Gaudi::Property< bool > m_add_b
SG::WriteDecorHandleKey< JC > m_target_index_key
TruthParentDecoratorAlg(const std::string &name, ISvcLocator *loc)
std::vector< CascadeCountDecorator > m_cascade_count_decorators
SG::WriteDecorHandleKey< JC > m_target_n_matched_key
std::atomic< unsigned long long > m_total_children
Gaudi::Property< bool > m_use_barcode
SG::WriteDecorHandleKey< JC > m_match_children_key
Gaudi::Property< cascade_counter_property_t > m_counts_matching_cascade
SG::WriteDecorHandleKey< JC > m_target_pdgid_key
Gaudi::Property< std::vector< int > > m_cascade_pdgids
Gaudi::Property< std::string > m_prefix
std::map< int, std::set< const xAOD::TruthParticle * > > IPMap
Gaudi::Property< bool > m_veto_soft_charm
SG::ReadHandleKeyArray< TPC > m_cascades_key
SG::WriteDecorHandleKey< JC > m_match_link_key
virtual StatusCode initialize() override
Gaudi::Property< std::vector< int > > m_parent_pdgids
Gaudi::Property< float > m_missing_children_fraction_warning_threshold
SG::WriteDecorHandleKey< JC > m_target_match_mask_key
virtual StatusCode execute(const EventContext &) const override
std::map< int, std::set< int > > Barcodex
SG::WriteDecorHandleKey< JC > m_target_link_key
SG::WriteDecorHandleKey< JC > m_target_dr_truth_key
SG::ReadHandleKey< JC > m_target_container_key
SG::ConstAccessor< int > m_uid
std::atomic< unsigned long long > m_missing_n_warned
SG::WriteDecorHandleKey< JC > m_match_pdgid_key
xAOD::IParticleContainer JC
SG::ReadHandleKey< TPC > m_parents_key
virtual StatusCode finalize() override
Gaudi::Property< std::unordered_set< int > > m_warn_missing_children_pdgids
Gaudi::Property< float > m_match_delta_r
xAOD::TruthParticleContainer TPC
std::atomic< unsigned long long > m_missing_n_ignored
int pdgId() const
PDG ID code.
size_t nChildren() const
Number of children of this particle.
virtual FourMom_t p4() const override final
The full 4-momentum of the particle.
bool match(std::string s1, std::string s2)
match the individual directories of two strings
Definition hcg.cxx:357
int barcode(const T *p)
Definition Barcode.h:16
Forward declaration.
std::string join(const std::vector< std::string > &v, const char c=',')
Definition index.py:1
output
Definition merge.py:16
void sort(typename DataModel_detail::iterator< DVL > beg, typename DataModel_detail::iterator< DVL > end)
Specialization of sort for DataVector/List.
TruthParticle_v1 TruthParticle
Typedef to implementation.
TruthParticleContainer_v1 TruthParticleContainer
Declare the latest version of the truth particle container.
DataVector< IParticle > IParticleContainer
Simple convenience declaration of IParticleContainer.
const xAOD::TruthParticle * parent
std::set< int > cascade_pids
const xAOD::TruthParticle * child
MsgStream & msg
Definition testRead.cxx:32