Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-07-24 08:25:33

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2022 - 2025 Whitney Armstrong, Wouter Deconinck, Dmitry Romanov, Shujie Li, Dmitry Kalinkin
0003 
0004 #include "CKFTracking.h"
0005 
0006 #include <Acts/Definitions/Algebra.hpp>
0007 #include <Acts/Definitions/TrackParametrization.hpp>
0008 #include <Acts/Definitions/Units.hpp>
0009 #if Acts_VERSION_MAJOR >= 46
0010 #include <Acts/EventData/BoundTrackParameters.hpp>
0011 #else
0012 #include <Acts/EventData/GenericBoundTrackParameters.hpp>
0013 #endif
0014 #include <Acts/EventData/MeasurementHelpers.hpp>
0015 #include <Acts/EventData/TrackStatePropMask.hpp>
0016 #include <Acts/Geometry/GeometryContext.hpp>
0017 #include <Acts/Geometry/GeometryHierarchyMap.hpp>
0018 #include <Acts/TrackFinding/CombinatorialKalmanFilterExtensions.hpp>
0019 #include <Acts/Utilities/CalibrationContext.hpp>
0020 #include <spdlog/common.h>
0021 #include <algorithm>
0022 #include <any>
0023 #include <array>
0024 #include <cstddef>
0025 #include <cstdint>
0026 #include <functional>
0027 #include <string>
0028 #include <system_error>
0029 #include <tuple>
0030 #include <utility>
0031 #include <Acts/EventData/ParticleHypothesis.hpp>
0032 #include <Acts/EventData/ProxyAccessor.hpp>
0033 #include <Acts/EventData/SourceLink.hpp>
0034 #include <Acts/EventData/TrackContainer.hpp>
0035 #include <Acts/EventData/TrackProxy.hpp>
0036 #include <Acts/EventData/VectorMultiTrajectory.hpp>
0037 #include <Acts/EventData/VectorTrackContainer.hpp>
0038 #include <Acts/Geometry/GeometryIdentifier.hpp>
0039 #include <Acts/Propagator/ActorList.hpp>
0040 #include <Acts/Propagator/EigenStepper.hpp>
0041 #include <Acts/Propagator/MaterialInteractor.hpp>
0042 #include <Acts/Propagator/Navigator.hpp>
0043 #include <Acts/Propagator/Propagator.hpp>
0044 #include <Acts/Propagator/PropagatorOptions.hpp>
0045 #include <Acts/Propagator/StandardAborters.hpp>
0046 #include <Acts/Surfaces/PerigeeSurface.hpp>
0047 #include <Acts/Surfaces/Surface.hpp>
0048 #include <Acts/TrackFinding/TrackStateCreator.hpp>
0049 #include <Acts/TrackFitting/GainMatrixUpdater.hpp>
0050 #include <Acts/Utilities/Logger.hpp>
0051 #include <Acts/Utilities/TrackHelpers.hpp>
0052 #include <ActsExamples/EventData/GeometryContainers.hpp>
0053 #include <ActsExamples/EventData/IndexSourceLink.hpp>
0054 #include <ActsExamples/EventData/Track.hpp>
0055 #include <boost/container/vector.hpp>
0056 #include <edm4eic/Cov3f.h>
0057 #include <edm4eic/Cov6f.h>
0058 #include <edm4eic/Measurement2DCollection.h>
0059 #include <edm4eic/TrackParametersCollection.h>
0060 #include <edm4eic/TrackSeedCollection.h>
0061 #include <edm4eic/unit_system.h>
0062 #include <edm4hep/Vector2f.h>
0063 #include <Eigen/Core>
0064 #include <Eigen/Geometry>
0065 #include <Eigen/LU> // IWYU pragma: keep
0066 // IWYU pragma: no_include <Acts/Utilities/detail/ContextType.hpp>
0067 // IWYU pragma: no_include <Acts/Utilities/detail/ContainerIterator.hpp>
0068 
0069 #include "ActsGeometryProvider.h"
0070 #include "extensions/edm4eic/EDM4eicToActs.h"
0071 #include "extensions/spdlog/SpdlogFormatters.h" // IWYU pragma: keep
0072 #include "extensions/spdlog/SpdlogToActs.h"
0073 
0074 namespace {
0075 
0076 /// Calibrator that reads directly from edm4eic::Measurement2DCollection.
0077 /// Also owns the geometry-ordered IndexSourceLink multiset built from the same collection.
0078 class EDM4eicMeasurementSourceLinkCalibrator {
0079 public:
0080   explicit EDM4eicMeasurementSourceLinkCalibrator(const edm4eic::Measurement2DCollection* meas2Ds)
0081       : m_meas2Ds(meas2Ds) {
0082     for (std::size_t index = 0; index < meas2Ds->size(); ++index) {
0083       m_orderedSourceLinks.emplace(Acts::GeometryIdentifier{(*meas2Ds)[index].getSurface()}, index);
0084     }
0085   }
0086 
0087   const ActsExamples::GeometryIdMultiset<ActsExamples::IndexSourceLink>&
0088   orderedSourceLinks() const {
0089     return m_orderedSourceLinks;
0090   }
0091 
0092   void calibrate(const Acts::GeometryContext& /*gctx*/, const Acts::CalibrationContext& /*cctx*/,
0093                  const Acts::SourceLink& sourceLink,
0094                  Acts::VectorMultiTrajectory::TrackStateProxy trackState) const {
0095     trackState.setUncalibratedSourceLink(Acts::SourceLink{sourceLink});
0096     const auto& idxSourceLink = sourceLink.get<ActsExamples::IndexSourceLink>();
0097     const auto& meas2D        = (*m_meas2Ds)[idxSourceLink.index()];
0098 
0099 #if Acts_VERSION_MAJOR > 45 || (Acts_VERSION_MAJOR == 45 && Acts_VERSION_MINOR >= 2)
0100     Acts::Vector<2> loc       = Acts::Vector2::Zero();
0101     Acts::SquareMatrix<2> cov = Acts::SquareMatrix<2>::Zero();
0102 #else
0103     Acts::ActsVector<2> loc       = Acts::Vector2::Zero();
0104     Acts::ActsSquareMatrix<2> cov = Acts::ActsSquareMatrix<2>::Zero();
0105 #endif
0106     constexpr auto mm                       = Acts::UnitConstants::mm / edm4eic::unit::mm;
0107     constexpr auto mm2                      = mm * mm;
0108     loc[Acts::eBoundLoc0]                   = meas2D.getLoc().a * mm;
0109     loc[Acts::eBoundLoc1]                   = meas2D.getLoc().b * mm;
0110     cov(Acts::eBoundLoc0, Acts::eBoundLoc0) = meas2D.getCovariance().xx * mm2;
0111     cov(Acts::eBoundLoc1, Acts::eBoundLoc1) = meas2D.getCovariance().yy * mm2;
0112     cov(Acts::eBoundLoc0, Acts::eBoundLoc1) = meas2D.getCovariance().xy * mm2;
0113     cov(Acts::eBoundLoc1, Acts::eBoundLoc0) = meas2D.getCovariance().xy * mm2;
0114 
0115     trackState.allocateCalibrated(loc, cov);
0116     std::array<uint8_t, 2> indices{static_cast<uint8_t>(Acts::eBoundLoc0),
0117                                    static_cast<uint8_t>(Acts::eBoundLoc1)};
0118     trackState.setProjectorSubspaceIndices(indices);
0119   }
0120 
0121 private:
0122   const edm4eic::Measurement2DCollection* m_meas2Ds;
0123   ActsExamples::GeometryIdMultiset<ActsExamples::IndexSourceLink> m_orderedSourceLinks;
0124 };
0125 
0126 } // anonymous namespace
0127 
0128 namespace eicrecon {
0129 
0130 using namespace Acts::UnitLiterals;
0131 
0132 void CKFTracking::init() {
0133   m_acts_logger = Acts::getDefaultLogger(
0134       "CKF", eicrecon::SpdlogToActsLevel(static_cast<spdlog::level::level_enum>(this->level())));
0135 
0136   // eta bins, chi2 and #sourclinks per surface cutoffs
0137   m_sourcelinkSelectorCfg = {
0138       {Acts::GeometryIdentifier(),
0139        {.etaBins               = m_cfg.etaBins,
0140         .chi2CutOff            = m_cfg.chi2CutOff,
0141         .numMeasurementsCutOff = {m_cfg.numMeasurementsCutOff.begin(),
0142                                   m_cfg.numMeasurementsCutOff.end()}}},
0143   };
0144   m_trackFinderFunc = CKFTracking::makeCKFTrackingFunction(
0145       m_geoSvc->trackingGeometry(), m_geoSvc->getFieldProvider(), acts_logger());
0146 }
0147 
0148 void CKFTracking::process(const Input& input, const Output& output) const {
0149   const auto [init_trk_seeds, meas2Ds]      = input;
0150   auto [output_track_states, output_tracks] = output;
0151 
0152   // If measurements or initial track parameters are empty, create empty output containers
0153   if (meas2Ds->empty() || init_trk_seeds->empty()) {
0154     debug("No seeds or measurements, creating empty output containers");
0155     *output_track_states = new Acts::ConstVectorMultiTrajectory();
0156     *output_tracks       = new Acts::ConstVectorTrackContainer();
0157     return;
0158   }
0159 
0160   ActsExamples::TrackParametersContainer acts_init_trk_params;
0161   for (const auto& track_seed : *init_trk_seeds) {
0162 
0163     const auto& track_parameter = track_seed.getParams();
0164 
0165     Acts::BoundVector params;
0166     params(Acts::eBoundLoc0) =
0167         track_parameter.getLoc().a * Acts::UnitConstants::mm; // cylinder radius
0168     params(Acts::eBoundLoc1) =
0169         track_parameter.getLoc().b * Acts::UnitConstants::mm; // cylinder length
0170     params(Acts::eBoundPhi)    = track_parameter.getPhi();
0171     params(Acts::eBoundTheta)  = track_parameter.getTheta();
0172     params(Acts::eBoundQOverP) = track_parameter.getQOverP() / Acts::UnitConstants::GeV;
0173     params(Acts::eBoundTime)   = track_parameter.getTime() * Acts::UnitConstants::ns;
0174 
0175 #if Acts_VERSION_MAJOR > 45 || (Acts_VERSION_MAJOR == 45 && Acts_VERSION_MINOR >= 1)
0176     Acts::BoundMatrix cov = Acts::BoundMatrix::Zero();
0177 #else
0178     Acts::BoundSquareMatrix cov = Acts::BoundSquareMatrix::Zero();
0179 #endif
0180     for (std::size_t i = 0; const auto& [a, x] : edm4eic_indexed_units) {
0181       for (std::size_t j = 0; const auto& [b, y] : edm4eic_indexed_units) {
0182         cov(a, b) = track_parameter.getCovariance()(i, j) * x * y;
0183         ++j;
0184       }
0185       ++i;
0186     }
0187 
0188     // Construct a perigee surface as the target surface
0189     auto pSurface = Acts::Surface::makeShared<const Acts::PerigeeSurface>(Acts::Vector3(0, 0, 0));
0190 
0191     // Create parameters
0192     acts_init_trk_params.emplace_back(pSurface, params, cov, Acts::ParticleHypothesis::pion());
0193   }
0194 
0195   //// Construct a perigee surface as the target surface
0196   auto pSurface = Acts::Surface::makeShared<Acts::PerigeeSurface>(Acts::Vector3{0., 0., 0.});
0197 
0198   // Convert algorithm log level to Acts log level for local logger
0199   const auto spdlog_level = static_cast<spdlog::level::level_enum>(this->level());
0200   const auto acts_level   = eicrecon::SpdlogToActsLevel(spdlog_level);
0201   ACTS_LOCAL_LOGGER(Acts::getDefaultLogger("CKF", acts_level));
0202 
0203   // Get run-scoped contexts from service
0204   const auto& gctx = m_geoSvc->getActsGeometryContext();
0205   const auto& mctx = m_geoSvc->getActsMagneticFieldContext();
0206   const auto& cctx = m_geoSvc->getActsCalibrationContext();
0207 
0208   Acts::PropagatorPlainOptions pOptions(gctx, mctx);
0209   pOptions.maxSteps = 10000;
0210 
0211   EDM4eicMeasurementSourceLinkCalibrator calibratorImpl{meas2Ds};
0212   Acts::GainMatrixUpdater kfUpdater;
0213   Acts::MeasurementSelector measSel{m_sourcelinkSelectorCfg};
0214 
0215   Acts::CombinatorialKalmanFilterExtensions<ActsExamples::TrackContainer> extensions;
0216   extensions.updater.connect<&Acts::GainMatrixUpdater::operator()<
0217       typename ActsExamples::TrackContainer::TrackStateContainerBackend>>(&kfUpdater);
0218 
0219   ActsExamples::IndexSourceLinkAccessor slAccessor;
0220   slAccessor.container = &calibratorImpl.orderedSourceLinks();
0221   using TrackStateCreatorType =
0222       Acts::TrackStateCreator<ActsExamples::IndexSourceLinkAccessor::Iterator,
0223                               ActsExamples::TrackContainer>;
0224   TrackStateCreatorType trackStateCreator;
0225   trackStateCreator.sourceLinkAccessor
0226       .template connect<&ActsExamples::IndexSourceLinkAccessor::range>(&slAccessor);
0227   trackStateCreator.calibrator.template connect<&EDM4eicMeasurementSourceLinkCalibrator::calibrate>(
0228       &calibratorImpl);
0229   trackStateCreator.measurementSelector
0230       .template connect<&Acts::MeasurementSelector::select<Acts::VectorMultiTrajectory>>(&measSel);
0231 
0232   extensions.createTrackStates.template connect<&TrackStateCreatorType::createTrackStates>(
0233       &trackStateCreator);
0234 
0235   // Set the CombinatorialKalmanFilter options
0236   CKFTracking::TrackFinderOptions options(gctx, mctx, cctx, extensions, pOptions);
0237 
0238   using Extrapolator        = Acts::Propagator<Acts::EigenStepper<>, Acts::Navigator>;
0239   using ExtrapolatorOptions = Extrapolator::template Options<
0240       Acts::ActorList<Acts::MaterialInteractor, Acts::EndOfWorldReached>>;
0241   Extrapolator extrapolator(Acts::EigenStepper<>(m_BField),
0242                             Acts::Navigator({.trackingGeometry = m_geoSvc->trackingGeometry()},
0243                                             acts_logger().cloneWithSuffix("Navigator")),
0244                             acts_logger().cloneWithSuffix("Propagator"));
0245   ExtrapolatorOptions extrapolationOptions(gctx, mctx);
0246 
0247   // Create track container
0248   auto trackContainer      = std::make_shared<Acts::VectorTrackContainer>();
0249   auto trackStateContainer = std::make_shared<Acts::VectorMultiTrajectory>();
0250   ActsExamples::TrackContainer acts_tracks(trackContainer, trackStateContainer);
0251 
0252   // Create temporary track container
0253   auto trackContainerTemp      = std::make_shared<Acts::VectorTrackContainer>();
0254   auto trackStateContainerTemp = std::make_shared<Acts::VectorMultiTrajectory>();
0255   ActsExamples::TrackContainer acts_tracks_temp(trackContainerTemp, trackStateContainerTemp);
0256 
0257   // Add seed number column
0258   acts_tracks.addColumn<unsigned int>("seed");
0259   acts_tracks_temp.addColumn<unsigned int>("seed");
0260   Acts::ProxyAccessor<unsigned int> seedNumber("seed");
0261 
0262   // Loop over seeds
0263   for (std::size_t iseed = 0; iseed < acts_init_trk_params.size(); ++iseed) {
0264 
0265     // Clear trackContainerTemp and trackStateContainerTemp
0266     acts_tracks_temp.clear();
0267 
0268     // Run track finding for this seed
0269     auto result = (*m_trackFinderFunc)(acts_init_trk_params.at(iseed), options, acts_tracks_temp);
0270 
0271     if (!result.ok()) {
0272       debug("Track finding failed for seed {} with error {}", iseed, result.error().message());
0273       continue;
0274     }
0275 
0276     // Set seed number for all found tracks
0277     auto& tracksForSeed = result.value();
0278     for (auto& track : tracksForSeed) {
0279       // Check if track has at least one valid (non-outlier) measurement
0280       // (this check avoids errors inside smoothing and extrapolation)
0281       auto lastMeasurement = Acts::findLastMeasurementState(track);
0282       if (!lastMeasurement.ok()) {
0283         debug("Track {} for seed {} has no valid measurements, skipping", track.index(), iseed);
0284         continue;
0285       }
0286 
0287       if (track.nMeasurements() < m_cfg.numMeasurementsMin) {
0288         trace("Track {} for seed {} has fewer measurements than minimum of {}, skipping",
0289               track.index(), iseed, m_cfg.numMeasurementsMin);
0290         continue;
0291       }
0292 
0293       auto smoothingResult = Acts::smoothTrack(gctx, track, acts_logger());
0294       if (!smoothingResult.ok()) {
0295         debug("Smoothing for seed {} and track {} failed with error {}", iseed, track.index(),
0296               smoothingResult.error().message());
0297         continue;
0298       }
0299 
0300       auto extrapolationResult = Acts::extrapolateTrackToReferenceSurface(
0301           track, *pSurface, extrapolator, extrapolationOptions,
0302           Acts::TrackExtrapolationStrategy::firstOrLast, acts_logger());
0303 
0304       if (!extrapolationResult.ok()) {
0305         debug("Extrapolation for seed {} and track {} failed with error {}", iseed, track.index(),
0306               extrapolationResult.error().message());
0307         continue;
0308       }
0309 
0310       seedNumber(track) = iseed;
0311 
0312       // Copy accepted track into main track container
0313       auto acts_tracks_proxy = acts_tracks.makeTrack();
0314       acts_tracks_proxy.copyFrom(track);
0315     }
0316   }
0317 
0318   // Allocate new const containers and assign pointers to outputs
0319   *output_track_states = new Acts::ConstVectorMultiTrajectory(std::move(*trackStateContainer));
0320   *output_tracks       = new Acts::ConstVectorTrackContainer(std::move(*trackContainer));
0321 }
0322 
0323 } // namespace eicrecon