30 using parent_mask_t =
unsigned long long;
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) +
"]");
42 mask |= (parent_mask_t{1} <<
match.parent_index);
48 std::string
join(
const std::vector<std::string>& v,
const std::string& sep =
", ") {
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);
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));
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()));
69 if (
output.empty())
return "none";
70 return "[" +
join(output) +
"]";
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();
83 "n_targets: " << targets->size() <<
", "
84 "n_parents: " << truth->size() <<
", "
85 "n_cascade_candidates: " << n_cascade_candidates <<
88 void logIPMap(MsgStream&
msg,
const IPMap& ipmap,
const MSG::Level level = MSG::VERBOSE)
90 if (
msg.level() > level)
return;
91 for (
const auto& [barcode, children]: ipmap) {
102 std::map<int, std::set<int>> findAllDescendants(
int parent,
const Barcodex& barcodex, std::set<int> history = {})
104 using return_t = std::map<int,std::set<int>>;
105 auto itr = barcodex.find(parent);
106 if (itr == barcodex.end()) {
108 throw std::runtime_error(
109 "can't find barcode " + std::to_string(parent) +
" history:"
110 " {" +
join(hist) +
"}");
112 const std::set<int>&
children = itr->second;
114 if (!history.insert(parent).second) {
116 throw std::runtime_error(
"found cycle, tried to add " + std::to_string(parent) +
" to {" +
join(hist) +
"}");
118 return_t all_children;
119 for (
int child: children) {
123 for (
auto& [dec, dh]: findAllDescendants(child, barcodex, history)) {
124 all_children[dec].merge(dh);
134 if (barkids.size() > 1) {
135 std::set<int> pdg_ids;
136 TLorentzVector sum_p4;
139 sum_p4 += dupkid->p4();
140 pdg_ids.insert(dupkid->pdgId());
141 if (dupkid->nChildren() > child->
nChildren()) child = dupkid;
143 if (pdg_ids.size() != 1) {
144 throw std::runtime_error(
"same barcode, different pdgid: [" +
join(
stringify(pdg_ids)) +
"]");
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()) +
"}"
156 for (
unsigned int parent_n = 0; parent_n <
p->nParents(); parent_n++) {
158 if (!parent)
throw std::runtime_error(
"broken truth record");
159 if (
parent->pdgId() ==
p->pdgId())
return false;
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) +
"]");
175 return (
parent->hasCharm() ||
parent->hasBottom()) &&
p->isChLepton();
179 return parent->hasBottom() &&
p->hasCharm();
187 m_pids(pids.begin(), pids.end()),
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++;
201 m_dec(target) = n_match;
243 std::string pfx = jc +
"." +
m_prefix.value();
273 return StatusCode::SUCCESS;
285 using uc_t =
unsigned char;
296 if (targets->empty())
return StatusCode::SUCCESS;
301 std::vector<const xAOD::TruthParticle*> psort;
303 if (!parentids.contains(p->pdgId()))
continue;
304 if (!isOriginal(p))
continue;
308 std::sort(psort.begin(), psort.end(),[](
const auto* p1,
const auto* p2) {return p1->m() > p2->m();});
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);
320 std::vector<SG::ReadHandle<TPC>> cascades_raw;
322 cascades_raw.emplace_back(key, cxt);
324 logInputs(msgStream(), targets, phandle, cascades_raw);
332 for (
auto& cascade: cascades_raw) {
335 logIPMap(
msg(), ipmap);
337 ATH_MSG_DEBUG(
"merged cascade contains " << barcodex.size() <<
" particles");
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++;
348 for (
auto& [cbar, histbars]: findAllDescendants(
m_uid(*p), barcodex)) {
349 IPMap::mapped_type& barkids = ipmap.at(cbar);
351 std::vector<std::pair<float, const J*>> drs;
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());
364 match.deltaR = drsMinDR;
365 match.parent_index = parent_index;
367 for (
auto& histbar: histbars) {
368 match.cascade_pids.insert(selectChild(ipmap.at(histbar))->pdgId());
371 labeled_targets[drsMinMatch].push_back(std::move(
match));
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;
388 matches.begin(), matches.end(), min_dr);
390 pdgid(*j) = p->pdgId();
392 auto* container =
dynamic_cast<const TPC*
>(p->container());
393 link(*j) =
JL(*container, p->index());
395 nMatched(*j) = matches.size();
396 mask(*j) = matchMask(matches);
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());
403 cascadeCount.decorate(*j, matches);
413 matchChildCount(*j) = 0;
414 matchLink(*j) =
JL();
416 cascadeCount.decorateDefault(*j);
426 dec.lock(targets.
get());
429 return StatusCode::SUCCESS;
450 return StatusCode::SUCCESS;
460 auto cascadeWants = [
467 if (
int n_parents = p->nParents(); n_parents == 1) {
468 if (vsl && isSoftLepton(p))
return false;
469 if (vsc && isSoftCharm(p))
return false;
471 if (targid.contains(p->pdgId()))
return true;
472 if (b && p->hasBottom())
return true;
473 if (c && p->hasCharm())
return true;
479 auto insert = [
this, &barcodex, &ipmap](
const auto* p) ->
auto& {
480 ipmap[
m_uid(*p)].insert(p);
481 return barcodex[
m_uid(*p)];
485 if (cascadeWants(p)) {
486 auto& child_set = insert(p);
487 for (
unsigned int child_n = 0; child_n < p->nChildren(); child_n++) {
498 if(ok_missing.contains(p->pdgId())) {
501 auto problem = std::format(
502 "null truth child [barcode={},pdg_id={},child={}of{}]",
504 m_uid(*p), p->pdgId(), child_n, p->nChildren());
506 if (warn_missing.contains(p->pdgId())) {
510 throw std::runtime_error(problem);
513 }
else if (cascadeWants(c)) {
516 child_set.insert(
m_uid(*c));
Scalar deltaR(const MatrixBase< Derived > &vec) const
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_VERBOSE(x)
#define ATH_MSG_WARNING(x)
ATLAS-specific HepMC functions.
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
std::vector< int > m_pids
Base class for elements of a container that can have aux data.
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
std::string join(const std::vector< std::string > &v, const char c=',')
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
unsigned int parent_index