Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-09-04 08:27:51

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2022 - 2024, Sylvester Joosten, Wouter Deconinck, Dmitry Romanov, Christopher Dilks, Dmitry Kalinkin
0003 
0004 #include "MatchToRICHPID.h"
0005 
0006 #include <edm4eic/TrackPoint.h>
0007 #include <edm4eic/TrackSegmentCollection.h>
0008 #include <edm4hep/MCParticle.h>
0009 #include <edm4hep/Vector3f.h>
0010 #include <edm4hep/utils/vector_utils.h>
0011 #include <podio/LinkNavigator.h>
0012 #include <podio/ObjectID.h>
0013 #include <podio/RelationRange.h>
0014 #include <podio/detail/Link.h>
0015 #include <podio/detail/LinkCollectionImpl.h>
0016 #include <algorithm>
0017 #include <cmath>
0018 #include <cstddef>
0019 #include <memory>
0020 #include <tuple>
0021 #include <utility>
0022 #include <vector>
0023 
0024 #include "algorithms/interfaces/LinkTruthUtils.h"
0025 #include "algorithms/pid/ConvertParticleID.h"
0026 #include "algorithms/pid/MatchToRICHPIDConfig.h"
0027 
0028 namespace eicrecon {
0029 
0030 void MatchToRICHPID::init() {}
0031 
0032 void MatchToRICHPID::process(const MatchToRICHPID::Input& input,
0033                              const MatchToRICHPID::Output& output) const {
0034   const auto [parts_in, links_in, drich_cherenkov_pid] = input;
0035   auto [parts_out, links_out, assocs_out, pids]        = output;
0036   const truth::EventLinkNavigator<edm4eic::MCRecoParticleLinkCollection> link_nav(links_in);
0037 
0038   for (auto part_in : *parts_in) {
0039     auto part_out = part_in.clone();
0040 
0041     // link Cherenkov PID objects
0042     auto success = linkCherenkovPID(part_out, *drich_cherenkov_pid, *pids);
0043     if (success) {
0044       trace("Previous PDG vs. CherenkovPID PDG: {:>10} vs. {:<10}", part_in.getPDG(),
0045             part_out.getParticleIDUsed().isAvailable() ? part_out.getParticleIDUsed().getPDG() : 0);
0046     }
0047 
0048     for (const auto& [sim_particle, weight] : link_nav.linked(part_in)) {
0049       auto link_out = links_out->create();
0050       link_out.setFrom(part_out);
0051       link_out.setTo(sim_particle);
0052       link_out.setWeight(weight);
0053       auto assoc_out = assocs_out->create();
0054       assoc_out.setRec(part_out);
0055       assoc_out.setSim(sim_particle);
0056       assoc_out.setWeight(weight);
0057     }
0058 
0059     parts_out->push_back(part_out);
0060   }
0061 }
0062 
0063 /* link PID objects to input particle
0064      * - finds `CherenkovParticleID` object in `in_pids` associated to particle `in_part`
0065      *   by proximity matching to the associated track
0066      * - converts this `CherenkovParticleID` object's PID hypotheses to `ParticleID` objects,
0067      *   relates them to `in_part`, and adds them to the collection `out_pids` for persistency
0068      * - returns `true` iff PID objects were found and linked
0069      */
0070 bool MatchToRICHPID::linkCherenkovPID(edm4eic::MutableReconstructedParticle& in_part,
0071                                       const edm4eic::CherenkovParticleIDCollection& in_pids,
0072                                       edm4hep::ParticleIDCollection& out_pids) const {
0073 
0074   // skip this particle, if neutral
0075   if (std::abs(in_part.getCharge()) < 0.001) {
0076     return false;
0077   }
0078 
0079   // structure to store list of candidate matches
0080   struct ProxMatch {
0081     double match_dist;
0082     std::size_t pid_idx;
0083   };
0084   std::vector<ProxMatch> prox_match_list;
0085 
0086   // get input reconstructed particle momentum angles
0087   auto in_part_p   = in_part.getMomentum();
0088   auto in_part_eta = edm4hep::utils::eta(in_part_p);
0089   auto in_part_phi = edm4hep::utils::angleAzimuthal(in_part_p);
0090   trace("Input particle: (eta,phi) = ( {:>5.4}, {:>5.4} deg )", in_part_eta,
0091         in_part_phi * 180.0 / M_PI);
0092 
0093   // loop over input CherenkovParticleID objects
0094   for (std::size_t in_pid_idx = 0; in_pid_idx < in_pids.size(); in_pid_idx++) {
0095     auto in_pid = in_pids.at(in_pid_idx);
0096 
0097     // get charged particle track associated to this CherenkovParticleID object
0098     auto in_track = in_pid.getChargedParticle();
0099     if (!in_track.isAvailable()) {
0100       error("found CherenkovParticleID object with no chargedParticle");
0101       return false;
0102     }
0103     if (in_track.points_size() == 0) {
0104       error("found chargedParticle for CherenkovParticleID, but it has no TrackPoints");
0105       return false;
0106     }
0107 
0108     // get average momentum direction of the track's TrackPoints
0109     decltype(edm4eic::TrackPoint::momentum) in_track_p{0.0, 0.0, 0.0};
0110     for (const auto& in_track_point : in_track.getPoints()) {
0111       in_track_p = in_track_p + (in_track_point.momentum / in_track.points_size());
0112     }
0113     auto in_track_eta = edm4hep::utils::eta(in_track_p);
0114     auto in_track_phi = edm4hep::utils::angleAzimuthal(in_track_p);
0115 
0116     // calculate dist(eta,phi)
0117     auto match_dist = std::hypot(in_part_eta - in_track_eta, in_part_phi - in_track_phi);
0118 
0119     // check if the match is close enough: within user-specified tolerances
0120     auto match_is_close = std::abs(in_part_eta - in_track_eta) < m_cfg.etaTolerance &&
0121                           std::abs(in_part_phi - in_track_phi) < m_cfg.phiTolerance;
0122     if (match_is_close) {
0123       prox_match_list.push_back(ProxMatch{.match_dist = match_dist, .pid_idx = in_pid_idx});
0124     }
0125 
0126     // logging
0127     trace("  - (eta,phi) = ( {:>5.4}, {:>5.4} deg ),  match_dist = {:<5.4}{}", in_track_eta,
0128           in_track_phi * 180.0 / M_PI, match_dist, match_is_close ? " => CLOSE!" : "");
0129 
0130   } // end loop over input CherenkovParticleID objects
0131 
0132   // check if at least one match was found
0133   if (prox_match_list.empty()) {
0134     trace("  => no matching CherenkovParticleID found for this particle");
0135     return false;
0136   }
0137 
0138   // choose the closest matching CherenkovParticleID object corresponding to this input reconstructed particle
0139   auto closest_prox_match = *std::ranges::min_element(
0140       prox_match_list, [](ProxMatch a, ProxMatch b) { return a.match_dist < b.match_dist; });
0141   auto in_pid_matched = in_pids.at(closest_prox_match.pid_idx);
0142   trace("  => best match: match_dist = {:<5.4} at idx = {}", closest_prox_match.match_dist,
0143         closest_prox_match.pid_idx);
0144 
0145   // convert `CherenkovParticleID` object's hypotheses => set of `ParticleID` objects
0146   auto out_pid_index_map = ConvertParticleID::ConvertToParticleIDs(in_pid_matched, out_pids, true);
0147   if (out_pid_index_map.empty()) {
0148     error("found CherenkovParticleID object with no hypotheses");
0149     return false;
0150   }
0151 
0152   // relate matched ParticleID objects to output particle
0153   for (const auto& [out_pids_index, out_pids_id] : out_pid_index_map) {
0154     const auto& out_pid = out_pids.at(out_pids_index);
0155     if (out_pid.getObjectID().index != static_cast<int>(out_pids_id)) { // sanity check
0156       error("indexing error in `edm4eic::ParticleID` collection");
0157       return false;
0158     }
0159     in_part.addToParticleIDs(out_pid);
0160   }
0161   in_part.setParticleIDUsed(in_part.getParticleIDs().at(0)); // highest likelihood is the first
0162   in_part.setGoodnessOfPID(1); // FIXME: not used yet, aside from 0=noPID vs 1=hasPID
0163 
0164   // trace logging
0165   trace("    {:.^50}", " PID results ");
0166   trace("      Hypotheses (sorted):");
0167   for (auto hyp : in_part.getParticleIDs()) {
0168     float npe =
0169         hyp.parameters_size() > 0 ? hyp.getParameters(0) : -1; // assume NPE is the first parameter
0170     trace("{:{}}{:>6}  {:>10.8}  {:>10.8}", "", 8, hyp.getPDG(), hyp.getLikelihood(), npe);
0171   }
0172   trace("    {:'^50}", "");
0173 
0174   return true;
0175 }
0176 } // namespace eicrecon