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