Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-08 07:51:22

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