Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-02 09:15:02

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2024 - 2025 Whitney Armstrong, Wouter Deconinck, Dmitry Romanov, Shujie Li, Dmitry Kalinkin
0003 
0004 #include <Acts/Definitions/Algebra.hpp>
0005 #include <Acts/Definitions/TrackParametrization.hpp>
0006 #include <Acts/Definitions/Units.hpp>
0007 #include <Acts/EventData/MultiTrajectoryHelpers.hpp>
0008 #include <Acts/EventData/ParticleHypothesis.hpp>
0009 #include <Acts/EventData/ProxyAccessor.hpp>
0010 #include <Acts/EventData/SourceLink.hpp>
0011 #include <Acts/EventData/TrackProxy.hpp>
0012 #include <Acts/EventData/VectorMultiTrajectory.hpp>
0013 #include <Acts/Geometry/GeometryContext.hpp>
0014 #include <Acts/Geometry/GeometryIdentifier.hpp>
0015 #include <Acts/Surfaces/Surface.hpp>
0016 #include <Acts/Utilities/UnitVectors.hpp>
0017 #include <ActsExamples/EventData/IndexSourceLink.hpp>
0018 #include <ActsExamples/EventData/Track.hpp>
0019 #include <Eigen/Core>
0020 #include <edm4eic/Cov6f.h>
0021 #include <edm4eic/RawTrackerHit.h>
0022 #include <edm4eic/TrackerHit.h>
0023 #include <edm4hep/MCParticleCollection.h>
0024 #include <edm4hep/SimTrackerHit.h>
0025 #include <edm4hep/Vector2f.h>
0026 #include <edm4hep/Vector3f.h>
0027 #include <edm4hep/utils/vector_utils.h>
0028 #include <podio/ObjectID.h>
0029 #include <podio/RelationRange.h>
0030 #include <podio/detail/Link.h>
0031 #include <podio/detail/LinkCollectionImpl.h>
0032 #include <any>
0033 #include <array>
0034 #include <cmath>
0035 #include <cstddef>
0036 #include <map>
0037 #include <memory>
0038 #include <numeric>
0039 #include <tuple>
0040 #include <utility>
0041 #include <vector>
0042 
0043 #include "ActsToTracks.h"
0044 #include "extensions/edm4eic/EDM4eicToActs.h"
0045 
0046 namespace eicrecon {
0047 
0048 // Custom comparator for MCParticle that uses deterministic ObjectID-based comparison
0049 // instead of podio's default memory-address-based comparison
0050 namespace {
0051   struct MCParticleCompare {
0052     bool operator()(const edm4hep::MCParticle& p_a, const edm4hep::MCParticle& p_b) const {
0053       // Compare particles by ObjectID for deterministic ordering
0054       auto id_a = p_a.getObjectID();
0055       auto id_b = p_b.getObjectID();
0056       if (id_a.collectionID != id_b.collectionID) {
0057         return id_a.collectionID < id_b.collectionID;
0058       }
0059       return id_a.index < id_b.index;
0060     }
0061   };
0062 
0063   // Bound covariance -> [x,y,z,px,py,pz], via the surface's bound-to-free Jacobian (rank 5)
0064   // Note: this covariance is a linear approximation (J C J^T) with rank 5 (perigee condition);
0065   // use a pseudo-inverse to invert it. For forward tracks (|eta| > 2.5) it is non-linear in the
0066   // momentum part (see EICrecon#3024 and tracking/vertexing WG meeting 11/05/2026); for fits, prefer the perigee TrackParameters.
0067   edm4eic::Cov6f cartesianCovariance(const Acts::BoundVector& par, const Acts::BoundMatrix& cov,
0068                                      const Acts::BoundToFreeMatrix& boundToFree) {
0069     const Acts::Vector3 direction =
0070         Acts::makeDirectionFromPhiTheta(par[Acts::eBoundPhi], par[Acts::eBoundTheta]);
0071     const double qOverP = par[Acts::eBoundQOverP];
0072     const double p      = std::abs(1.0 / qOverP);
0073     Eigen::Matrix<double, 6, Acts::eFreeSize> freeToCart =
0074         Eigen::Matrix<double, 6, Acts::eFreeSize>::Zero();
0075     freeToCart.block<3, 3>(0, Acts::eFreePos0)         = Eigen::Matrix3d::Identity();
0076     freeToCart.block<3, 3>(3, Acts::eFreeDir0)         = p * Eigen::Matrix3d::Identity();
0077     freeToCart.block<3, 1>(3, Acts::eFreeQOverP)       = -p / qOverP * direction;
0078     const Eigen::Matrix<double, 6, Acts::eBoundSize> J = freeToCart * boundToFree;
0079     const Eigen::Matrix<double, 6, 6> C                = J * cov * J.transpose();
0080 
0081     const std::array<double, 6> unit{Acts::UnitConstants::mm,  Acts::UnitConstants::mm,
0082                                      Acts::UnitConstants::mm,  Acts::UnitConstants::GeV,
0083                                      Acts::UnitConstants::GeV, Acts::UnitConstants::GeV};
0084     edm4eic::Cov6f out;
0085     for (unsigned int i = 0; i < 6; ++i) {
0086       for (unsigned int j = i; j < 6; ++j) {
0087         out(i, j) = static_cast<float>(C(i, j) / unit.at(i) / unit.at(j));
0088       }
0089     }
0090     return out;
0091   }
0092 } // namespace
0093 
0094 void ActsToTracks::init() {}
0095 
0096 void ActsToTracks::process(const Input& input, const Output& output) const {
0097   const auto [meas2Ds, track_seeds, acts_track_states, acts_tracks, raw_hit_assocs] = input;
0098   auto [trajectories, track_parameters, tracks, tracks_links, tracks_assoc]         = output;
0099 
0100   // Create accessor for seed number dynamic column
0101   Acts::ConstProxyAccessor<unsigned int> seedNumber("seed");
0102 
0103   // Construct ActsExamples::ConstTrackContainer from underlying containers
0104   auto trackStateContainer = std::make_shared<Acts::ConstVectorMultiTrajectory>(*acts_track_states);
0105   auto trackContainer      = std::make_shared<Acts::ConstVectorTrackContainer>(*acts_tracks);
0106   ActsExamples::ConstTrackContainer acts_track_container(trackContainer, trackStateContainer);
0107 
0108   // Loop over tracks
0109   for (const auto& track : acts_track_container) {
0110     // Collect the trajectory summary info
0111     auto trajectoryState = Acts::MultiTrajectoryHelpers::trajectoryState(
0112         acts_track_container.trackStateContainer(), track.tipIndex());
0113 
0114     // Create trajectory
0115     auto trajectory = trajectories->create();
0116     trajectory.setNMeasurements(trajectoryState.nMeasurements);
0117     trajectory.setNStates(trajectoryState.nStates);
0118     trajectory.setNOutliers(trajectoryState.nOutliers);
0119     trajectory.setNHoles(trajectoryState.nHoles);
0120     trajectory.setNSharedHits(trajectoryState.nSharedHits);
0121 
0122     // Set the seed that was used to obtain this track
0123     unsigned int iseed = seedNumber(track);
0124     if (iseed < track_seeds->size()) {
0125       trajectory.setSeed((*track_seeds)[iseed]);
0126     } else {
0127       warning("ActsToTracks: seed index {} is out of bounds (track_seeds size = {}), seed will not "
0128               "be set for this trajectory",
0129               iseed, track_seeds->size());
0130     }
0131 
0132     debug("trajectory state, measurement, outlier, hole: {} {} {} {}", trajectoryState.nStates,
0133           trajectoryState.nMeasurements, trajectoryState.nOutliers, trajectoryState.nHoles);
0134 
0135     for (const auto& measurementChi2 : trajectoryState.measurementChi2) {
0136       trajectory.addToMeasurementChi2(measurementChi2);
0137     }
0138 
0139     for (const auto& outlierChi2 : trajectoryState.outlierChi2) {
0140       trajectory.addToOutlierChi2(outlierChi2);
0141     }
0142 
0143     // Get the fitted track parameter
0144     const auto& parameter  = track.parameters();
0145     const auto& covariance = track.covariance();
0146 
0147     auto pars = track_parameters->create();
0148     pars.setType(0); // type: track head --> 0
0149     pars.setLoc({static_cast<float>(parameter[Acts::eBoundLoc0] / Acts::UnitConstants::mm),
0150                  static_cast<float>(parameter[Acts::eBoundLoc1] / Acts::UnitConstants::mm)});
0151     pars.setTheta(static_cast<float>(parameter[Acts::eBoundTheta] / Acts::UnitConstants::rad));
0152     pars.setPhi(static_cast<float>(parameter[Acts::eBoundPhi] / Acts::UnitConstants::rad));
0153     pars.setQOverP(static_cast<float>(parameter[Acts::eBoundQOverP] * Acts::UnitConstants::GeV));
0154     pars.setTime(static_cast<float>(parameter[Acts::eBoundTime] / Acts::UnitConstants::ns));
0155     edm4eic::Cov6f cov;
0156     for (std::size_t i = 0; const auto& [a, x] : edm4eic_indexed_units) {
0157       for (std::size_t j = 0; const auto& [b, y] : edm4eic_indexed_units) {
0158         // FIXME why not pars.getCovariance()(i,j) = covariance(a,b) / x / y;
0159         cov(i, j) = covariance(a, b) / x / y;
0160         ++j;
0161       }
0162       ++i;
0163     }
0164     pars.setCovariance(cov);
0165 
0166     trajectory.addToTrackParameters(pars);
0167 
0168     // Fill tracks
0169     auto track_out = tracks->create();
0170     track_out.setType( // Flag that defines the type of track
0171         pars.getType());
0172 
0173     // Compute 3D position from perigee local coordinates via localToGlobal.
0174     // A default GeometryContext is sufficient here: the perigee surface is
0175     // defined purely by its center point and carries no alignment data.
0176     const auto gctx = Acts::GeometryContext::dangerouslyDefaultConstruct();
0177     const Acts::Vector2 localPos{parameter[Acts::eBoundLoc0], parameter[Acts::eBoundLoc1]};
0178     const Acts::Vector3 direction =
0179         Acts::makeDirectionFromPhiTheta(parameter[Acts::eBoundPhi], parameter[Acts::eBoundTheta]);
0180     const Acts::Vector3 globalPos =
0181         track.referenceSurface().localToGlobal(gctx, localPos, direction);
0182     track_out.setPosition( // Track 3-position at the perigee [mm]
0183         edm4hep::Vector3f{static_cast<float>(globalPos.x()), static_cast<float>(globalPos.y()),
0184                           static_cast<float>(globalPos.z())});
0185 
0186     // Compute Cartesian momentum from spherical parameters.
0187     const double qOverP = parameter[Acts::eBoundQOverP];
0188     double p_abs        = 0.0;
0189     if (std::isfinite(qOverP) && qOverP != 0.0) {
0190       p_abs = std::abs(1.0 / qOverP);
0191     } else {
0192       warning("ActsToTracks: track has qOverP={}, which yields non-finite momentum; setting "
0193               "momentum to zero",
0194               qOverP);
0195     }
0196     const double p = p_abs;
0197     track_out.setMomentum( // Track 3-momentum at the perigee [GeV]
0198         edm4hep::utils::sphericalToVector(p, parameter[Acts::eBoundTheta],
0199                                           parameter[Acts::eBoundPhi]));
0200 
0201     if (p_abs > 0.0) { // Covariance matrix in basis [x,y,z,px,py,pz]
0202       track_out.setPositionMomentumCovariance(cartesianCovariance(
0203           parameter, covariance,
0204           track.referenceSurface().boundToFreeJacobian(gctx, globalPos, direction)));
0205     }
0206     track_out.setTime( // Track time at the perigee [ns]
0207         static_cast<float>(parameter[Acts::eBoundTime] / Acts::UnitConstants::ns));
0208     track_out.setTimeError( // Error on the track perigee time
0209         static_cast<float>(sqrt(covariance(Acts::eBoundTime, Acts::eBoundTime))) /
0210         Acts::UnitConstants::ns);
0211     const double charge = // Particle charge (0 if qOverP is invalid or zero)
0212         (std::isfinite(qOverP) && qOverP != 0.0) ? std::copysign(1.0, qOverP) : 0.0;
0213     track_out.setCharge(charge);
0214     track_out.setChi2(trajectoryState.chi2Sum); // Total chi2
0215     track_out.setNdf(trajectoryState.NDF);      // Number of degrees of freedom
0216     track_out.setPdg(                           // PDG particle ID hypothesis
0217         track.particleHypothesis().absolutePdg());
0218     track_out.setTrajectory(trajectory); // Trajectory of this track
0219 
0220     // Determine track association with MCParticle, weighted by number of used measurements
0221     std::map<edm4hep::MCParticle, double, MCParticleCompare> mcparticle_weight_by_hit_count;
0222 
0223     // save measurement2d to good measurements or outliers according to srclink index
0224     // fix me: ideally, this should be integrated into multitrajectoryhelper
0225     // fix me: should say "OutlierMeasurements" instead of "OutlierHits" etc
0226     for (const auto& state : track.trackStatesReversed()) {
0227       auto geoID     = state.referenceSurface().geometryId().value();
0228       auto typeFlags = state.typeFlags();
0229 
0230       // find the associated hit (2D measurement) with state sourcelink index
0231       // fix me: calibrated or not?
0232       if (state.hasUncalibratedSourceLink()) {
0233 
0234         std::size_t srclink_index =
0235             state.getUncalibratedSourceLink().template get<ActsExamples::IndexSourceLink>().index();
0236 
0237         // no hit on this state/surface, skip
0238         if (typeFlags.isHole()) {
0239           debug("No hit found on geo id={}", geoID);
0240 
0241         } else {
0242           auto meas2D = (*meas2Ds)[srclink_index];
0243           if (typeFlags.isOutlier()) {
0244             trajectory.addToOutliers_deprecated(meas2D);
0245             debug("Outlier on geo id={}, index={}, loc={},{}", geoID, srclink_index,
0246                   meas2D.getLoc().a, meas2D.getLoc().b);
0247           } else if (typeFlags.isMeasurement()) {
0248             track_out.addToMeasurements(meas2D);
0249             trajectory.addToMeasurements_deprecated(meas2D);
0250             debug("Measurement on geo id={}, index={}, loc={},{}", geoID, srclink_index,
0251                   meas2D.getLoc().a, meas2D.getLoc().b);
0252 
0253             // Determine track associations if hit associations provided
0254             if (raw_hit_assocs != nullptr) {
0255               for (const auto& hit : meas2D.getHits()) {
0256                 auto raw_hit = hit.getRawHit();
0257                 for (const auto raw_hit_assoc : *raw_hit_assocs) {
0258                   if (raw_hit_assoc.getRawHit() == raw_hit) {
0259                     auto sim_hit     = raw_hit_assoc.getSimHit();
0260                     auto mc_particle = sim_hit.getParticle();
0261                     mcparticle_weight_by_hit_count[mc_particle]++;
0262                   }
0263                 }
0264               }
0265             }
0266           }
0267         }
0268       }
0269     }
0270 
0271     // Store track associations if hit associations provided
0272     // FIXME: not able to check whether optional inputs were provided
0273     //if (raw_hit_assocs->has_value()) {
0274     double total_weight = std::accumulate(
0275         mcparticle_weight_by_hit_count.begin(), mcparticle_weight_by_hit_count.end(), 0,
0276         [](const double sum, const auto& i) { return sum + i.second; });
0277     for (const auto& [mcparticle, weight] : mcparticle_weight_by_hit_count) {
0278       double normalized_weight = weight / total_weight;
0279       auto track_link          = tracks_links->create();
0280       track_link.setFrom(track_out);
0281       track_link.setTo(mcparticle);
0282       track_link.setWeight(normalized_weight);
0283       auto track_assoc = tracks_assoc->create();
0284       track_assoc.setRec(track_out);
0285       track_assoc.setSim(mcparticle);
0286       track_assoc.setWeight(normalized_weight);
0287       debug("track {}: mcparticle {} weight {}", track_out.id().index, mcparticle.id().index,
0288             normalized_weight);
0289     }
0290     //}
0291   }
0292 }
0293 
0294 } // namespace eicrecon