Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-28 09:20:49

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 #include <Acts/Utilities/MathHelpers.hpp>
0010 #include <edm4hep/Vector3f.h>
0011 #if Acts_VERSION_MAJOR >= 46
0012 #else
0013 #include <Acts/EventData/GenericBoundTrackParameters.hpp>
0014 #endif
0015 #include <Acts/EventData/MeasurementHelpers.hpp>
0016 #include <Acts/EventData/ParticleHypothesis.hpp>
0017 #include <Acts/EventData/ProxyAccessor.hpp>
0018 #include <Acts/EventData/SourceLink.hpp>
0019 #include <Acts/EventData/TrackContainer.hpp>
0020 #include <Acts/EventData/TrackProxy.hpp>
0021 #include <Acts/EventData/TrackStatePropMask.hpp>
0022 #include <Acts/EventData/VectorMultiTrajectory.hpp>
0023 #include <Acts/EventData/VectorTrackContainer.hpp>
0024 #include <Acts/Geometry/GeometryContext.hpp>
0025 #include <Acts/Geometry/GeometryIdentifier.hpp>
0026 #include <Acts/Propagator/ActorList.hpp>
0027 #if __has_include(<Acts/Propagator/DefaultActor.hpp>)
0028 #include <Acts/Propagator/DefaultActor.hpp>
0029 #endif
0030 #include <Acts/Propagator/EigenStepper.hpp>
0031 #include <Acts/Propagator/MaterialInteractor.hpp>
0032 #include <Acts/Propagator/Navigator.hpp>
0033 #include <Acts/Propagator/Propagator.hpp>
0034 #include <Acts/Propagator/PropagatorOptions.hpp>
0035 #if !__has_include(<Acts/Propagator/DefaultActor.hpp>)
0036 #include <Acts/Propagator/StandardAborters.hpp>
0037 #endif
0038 #include <Acts/Surfaces/PerigeeSurface.hpp>
0039 #include <Acts/Surfaces/Surface.hpp>
0040 #include <Acts/TrackFinding/CombinatorialKalmanFilterExtensions.hpp>
0041 #include <Acts/TrackFinding/TrackStateCreator.hpp>
0042 #include <Acts/TrackFitting/GainMatrixUpdater.hpp>
0043 #include <Acts/Utilities/CalibrationContext.hpp>
0044 #include <Acts/Utilities/Logger.hpp>
0045 #include <Acts/Utilities/TrackHelpers.hpp>
0046 #include <ActsExamples/EventData/GeometryContainers.hpp>
0047 #include <ActsExamples/EventData/IndexSourceLink.hpp>
0048 #include <ActsExamples/EventData/Track.hpp>
0049 #include <DD4hep/DetElement.h>
0050 #include <DD4hep/Detector.h>
0051 #include <boost/container/vector.hpp>
0052 #include <edm4eic/Cov3f.h>
0053 #include <edm4eic/Cov6f.h>
0054 #include <edm4eic/Measurement2DCollection.h>
0055 #include <edm4eic/TrackParametersCollection.h>
0056 #include <edm4eic/TrackSeedCollection.h>
0057 #include <edm4eic/unit_system.h>
0058 #include <edm4hep/Vector2f.h>
0059 #include <fmt/ranges.h>
0060 #include <spdlog/common.h>
0061 #include <Eigen/Core>
0062 #include <Eigen/Geometry>
0063 #include <Eigen/LU> // IWYU pragma: keep
0064 #include <algorithm>
0065 #include <any>
0066 #include <array>
0067 #include <cmath>
0068 #include <cstddef>
0069 #include <cstdint>
0070 #include <format>
0071 #include <functional>
0072 #include <map>
0073 #include <optional>
0074 #include <set>
0075 #include <stdexcept>
0076 #include <string>
0077 #include <system_error>
0078 #include <tuple>
0079 #include <utility>
0080 #include <vector>
0081 // IWYU pragma: no_include <Acts/Utilities/detail/ContextType.hpp>
0082 // IWYU pragma: no_include <Acts/Utilities/detail/ContainerIterator.hpp>
0083 
0084 #include "ActsGeometryProvider.h"
0085 #include "extensions/edm4eic/EDM4eicToActs.h"
0086 #include "extensions/spdlog/SpdlogFormatters.h" // IWYU pragma: keep
0087 #include "extensions/spdlog/SpdlogToActs.h"
0088 
0089 namespace {
0090 
0091 /// Whether a measurement is calibrated with time, based on the DD4hep system ID stored in the
0092 /// extra field of the geometry identifier of its surface
0093 bool usesTime(const edm4eic::Measurement2D& meas2D, const std::set<std::uint8_t>& timeSystemIDs) {
0094   return timeSystemIDs.contains(Acts::GeometryIdentifier{meas2D.getSurface()}.extra());
0095 }
0096 
0097 /// Calibrator that reads directly from edm4eic::Measurement2DCollection.
0098 /// Also owns the geometry-ordered IndexSourceLink multiset built from the same collection.
0099 class EDM4eicMeasurementSourceLinkCalibrator {
0100 public:
0101   EDM4eicMeasurementSourceLinkCalibrator(const edm4eic::Measurement2DCollection* meas2Ds,
0102                                          const std::set<std::uint8_t>& timeSystemIDs)
0103       : m_meas2Ds(meas2Ds), m_timeSystemIDs(&timeSystemIDs) {
0104     for (std::size_t index = 0; index < meas2Ds->size(); ++index) {
0105       m_orderedSourceLinks.emplace(Acts::GeometryIdentifier{(*meas2Ds)[index].getSurface()}, index);
0106     }
0107   }
0108 
0109   const ActsExamples::GeometryIdMultiset<ActsExamples::IndexSourceLink>&
0110   orderedSourceLinks() const {
0111     return m_orderedSourceLinks;
0112   }
0113 
0114   void calibrate(const Acts::GeometryContext& /*gctx*/, const Acts::CalibrationContext& /*cctx*/,
0115                  const Acts::SourceLink& sourceLink,
0116                  Acts::VectorMultiTrajectory::TrackStateProxy trackState) const {
0117     trackState.setUncalibratedSourceLink(Acts::SourceLink{sourceLink});
0118     const auto& idxSourceLink = sourceLink.get<ActsExamples::IndexSourceLink>();
0119     const auto& meas2D        = (*m_meas2Ds)[idxSourceLink.index()];
0120 
0121     if (usesTime(meas2D, *m_timeSystemIDs)) {
0122       calibrateImpl<3>(meas2D, trackState);
0123     } else {
0124       calibrateImpl<2>(meas2D, trackState);
0125     }
0126   }
0127 
0128 private:
0129   /// Fill the calibrated measurement with loc0, loc1 (N = 2) and additionally time (N = 3)
0130   template <std::size_t N>
0131   static void calibrateImpl(const edm4eic::Measurement2D& meas2D,
0132                             Acts::VectorMultiTrajectory::TrackStateProxy& trackState) {
0133     Acts::Vector<N> loc       = Acts::Vector<N>::Zero();
0134     Acts::SquareMatrix<N> cov = Acts::SquareMatrix<N>::Zero();
0135     // Bound parameters that make up the calibrated measurement, in storage order
0136     constexpr auto indices = []() {
0137       std::array<uint8_t, N> idx{static_cast<uint8_t>(Acts::eBoundLoc0),
0138                                  static_cast<uint8_t>(Acts::eBoundLoc1)};
0139       if constexpr (N == 3) {
0140         idx[2] = static_cast<uint8_t>(Acts::eBoundTime);
0141       }
0142       return idx;
0143     }();
0144     // Position of a bound parameter within the compact calibrated vector
0145     constexpr auto position = [indices](Acts::BoundIndices bound) {
0146       return static_cast<std::size_t>(std::find(indices.begin(), indices.end(), bound) -
0147                                       indices.begin());
0148     };
0149     constexpr std::size_t iLoc0 = position(Acts::eBoundLoc0);
0150     constexpr std::size_t iLoc1 = position(Acts::eBoundLoc1);
0151 
0152     constexpr auto mm  = Acts::UnitConstants::mm / edm4eic::unit::mm;
0153     constexpr auto mm2 = mm * mm;
0154     loc[iLoc0]         = meas2D.getLoc().a * mm;
0155     loc[iLoc1]         = meas2D.getLoc().b * mm;
0156     cov(iLoc0, iLoc0)  = meas2D.getCovariance().xx * mm2;
0157     cov(iLoc1, iLoc1)  = meas2D.getCovariance().yy * mm2;
0158     cov(iLoc0, iLoc1)  = meas2D.getCovariance().xy * mm2;
0159     cov(iLoc1, iLoc0)  = meas2D.getCovariance().xy * mm2;
0160 
0161     if constexpr (N == 3) {
0162       constexpr std::size_t iTime = position(Acts::eBoundTime);
0163       constexpr auto ns           = Acts::UnitConstants::ns / edm4eic::unit::ns;
0164       constexpr auto ns2          = ns * ns;
0165       // The time variance is stored in the zz component of the measurement covariance
0166       loc[iTime]        = meas2D.getTime() * ns;
0167       cov(iTime, iTime) = meas2D.getCovariance().zz * ns2;
0168       cov(iLoc0, iTime) = meas2D.getCovariance().xz * mm * ns;
0169       cov(iTime, iLoc0) = cov(iLoc0, iTime);
0170       cov(iLoc1, iTime) = meas2D.getCovariance().yz * mm * ns;
0171       cov(iTime, iLoc1) = cov(iLoc1, iTime);
0172     }
0173 
0174     trackState.allocateCalibrated(loc, cov);
0175     trackState.setProjectorSubspaceIndices(indices);
0176   }
0177 
0178   const edm4eic::Measurement2DCollection* m_meas2Ds;
0179   const std::set<std::uint8_t>* m_timeSystemIDs;
0180   ActsExamples::GeometryIdMultiset<ActsExamples::IndexSourceLink> m_orderedSourceLinks;
0181 };
0182 
0183 /// Per-branch stopper for the CombinatorialKalmanFilter.
0184 ///
0185 /// ACTS's default branch stopper never stops a branch, so a diverging branch is
0186 /// never abandoned. Once a fit goes bad the covariance inflates, the Kalman
0187 /// gain on q/p becomes ill-conditioned, and each further update throws q/p
0188 /// further off. The covariance eventually overflows double precision and the
0189 /// chi2 becomes NaN, which crashes the MeasurementSelector (seen in the
0190 /// far-forward B0 tracker).
0191 ///
0192 /// The divergence is visible in the filtered variance of q/p long before it
0193 /// becomes fatal: a well-behaved fit never exceeds the variance asserted by the
0194 /// seed, while a diverging one exceeds it by many orders of magnitude, and
0195 /// ultimately turns negative or non-finite as positive-definiteness is lost.
0196 /// Testing that variance therefore catches the divergence at the first bad
0197 /// update, while the chi2 still looks harmless, and costs a single matrix
0198 /// element with no history to inspect.
0199 class CKFBranchStopper {
0200 public:
0201   using TrackProxy      = ActsExamples::TrackContainer::TrackProxy;
0202   using TrackStateProxy = ActsExamples::TrackContainer::TrackStateProxy;
0203   using Result          = Acts::CombinatorialKalmanFilterBranchStopperResult;
0204   using LogFunc         = std::function<void(const std::string&)>;
0205 
0206   CKFBranchStopper(const eicrecon::CKFTrackingConfig& cfg, LogFunc log)
0207       : m_cfg(cfg), m_log(std::move(log)) {}
0208 
0209   Result operator()(const TrackProxy& track, const TrackStateProxy& trackState) const {
0210     if (!trackState.typeFlags().hasMeasurement() || !trackState.hasFiltered()) {
0211       return Result::Continue;
0212     }
0213 
0214     const double varQOverP =
0215         trackState.filteredCovariance()(Acts::eBoundQOverP, Acts::eBoundQOverP);
0216     // Catches an inflated variance, and also a negative or NaN one, which mean
0217     // the covariance has lost positive-definiteness altogether.
0218     if (!(varQOverP > 0.) || varQOverP > m_cfg.maxQOverPVariance) {
0219       if (m_log) {
0220         m_log(std::format("Dropping diverged CKF branch with {} measurement(s): "
0221                           "filtered var(q/p) = {:g}, limit {:g}",
0222                           track.nMeasurements(), varQOverP, m_cfg.maxQOverPVariance));
0223       }
0224       return Result::StopAndDrop;
0225     }
0226     return Result::Continue;
0227   }
0228 
0229 private:
0230   const eicrecon::CKFTrackingConfig& m_cfg;
0231   LogFunc m_log;
0232 };
0233 
0234 } // anonymous namespace
0235 
0236 namespace eicrecon {
0237 
0238 using namespace Acts::UnitLiterals;
0239 
0240 void CKFTracking::init() {
0241   m_acts_logger = Acts::getDefaultLogger(
0242       "CKF", eicrecon::SpdlogToActsLevel(static_cast<spdlog::level::level_enum>(this->level())));
0243 
0244   // Per-detector cuts. The hierarchy map masks out the extra field which holds the DD4hep
0245   // system ID, so detectors are resolved to the (volume, layer) identifiers of their surfaces.
0246   std::vector<const SurfaceCuts*> surface_cuts;
0247   std::vector<std::uint8_t> surface_cuts_system_ids;
0248   const auto& dd4hep_detectors = m_geoSvc->dd4hepDetector()->detectors();
0249   for (const auto& cuts : m_cfg.surfaceCuts) {
0250     const auto detector = dd4hep_detectors.find(cuts.detector);
0251     if (detector == dd4hep_detectors.end()) {
0252       warning("Detector '{}' for CKF surface cuts not in geometry, ignoring", cuts.detector);
0253       continue;
0254     }
0255     surface_cuts_system_ids.push_back(
0256         ActsGeometryProvider::geometryIdExtra(dd4hep::DetElement(detector->second).id()));
0257     surface_cuts.push_back(&cuts);
0258   }
0259 
0260   std::map<Acts::GeometryIdentifier, std::size_t> layer_cuts_index;
0261   std::vector<std::size_t> num_layers(surface_cuts.size(), 0);
0262   m_geoSvc->trackingGeometry()->visitSurfaces([&](const Acts::Surface* surface) {
0263     const auto geo_id = surface->geometryId();
0264     for (std::size_t i = 0; i < surface_cuts.size(); ++i) {
0265       if (geo_id.extra() != surface_cuts_system_ids[i] ||
0266           (surface_cuts[i]->layer != 0 && geo_id.layer() != surface_cuts[i]->layer)) {
0267         continue;
0268       }
0269       const auto layer_id =
0270           Acts::GeometryIdentifier().withVolume(geo_id.volume()).withLayer(geo_id.layer());
0271       const auto [it, inserted] = layer_cuts_index.emplace(layer_id, i);
0272       if (inserted) {
0273         ++num_layers[i];
0274       } else if (it->second != i) {
0275         throw std::runtime_error(
0276             std::format("CKF surface cuts for '{}' and '{}' both apply to volume {} layer {}",
0277                         surface_cuts[it->second]->detector, surface_cuts[i]->detector,
0278                         geo_id.volume(), geo_id.layer()));
0279       }
0280     }
0281   });
0282 
0283   for (std::size_t i = 0; i < surface_cuts.size(); ++i) {
0284     if (num_layers[i] == 0) {
0285       warning("CKF surface cuts for detector '{}' match no tracking surfaces",
0286               surface_cuts[i]->detector);
0287     }
0288   }
0289 
0290   const auto to_acts_cuts = [](const MeasurementSelectorCuts& cuts) {
0291 #if !(Acts_VERSION_MAJOR > 48 || (Acts_VERSION_MAJOR == 48 && Acts_VERSION_MINOR >= 5))
0292     if (cuts.chi2CutPerDimension) {
0293       throw std::runtime_error("CKF chi2CutPerDimension requires Acts >= 48.5");
0294     }
0295 #endif
0296     return Acts::MeasurementSelectorCuts{
0297         .etaBins               = cuts.etaBins,
0298         .chi2CutOff            = cuts.chi2CutOff,
0299         .numMeasurementsCutOff = {cuts.numMeasurementsCutOff.begin(),
0300                                   cuts.numMeasurementsCutOff.end()},
0301 #if Acts_VERSION_MAJOR > 48 || (Acts_VERSION_MAJOR == 48 && Acts_VERSION_MINOR >= 5)
0302         .chi2CutPerDimension = cuts.chi2CutPerDimension,
0303 #endif
0304     };
0305   };
0306   std::vector<Acts::MeasurementSelector::Config::InputElement> selector_cuts;
0307   selector_cuts.emplace_back(Acts::GeometryIdentifier(), to_acts_cuts(m_cfg.defaultCuts));
0308   for (const auto& [layer_id, i] : layer_cuts_index) {
0309     const auto& cuts = surface_cuts[i]->cuts;
0310     debug("CKF cuts for volume {} layer {} ({}): etaBins=[{}], chi2CutOff=[{}], "
0311           "chi2CutPerDimension={}, numMeasurementsCutOff=[{}]",
0312           layer_id.volume(), layer_id.layer(), surface_cuts[i]->detector,
0313           fmt::join(cuts.etaBins, ","), fmt::join(cuts.chi2CutOff, ","), cuts.chi2CutPerDimension,
0314           fmt::join(cuts.numMeasurementsCutOff, ","));
0315     selector_cuts.emplace_back(layer_id, to_acts_cuts(cuts));
0316   }
0317   m_measurementSelector.emplace(Acts::MeasurementSelector::Config(selector_cuts));
0318 
0319   m_trackFinderFunc = CKFTracking::makeCKFTrackingFunction(
0320       m_geoSvc->trackingGeometry(), m_geoSvc->getFieldProvider(), acts_logger());
0321 
0322   // Detectors whose measurements include time
0323   m_timeSystemIDs = m_geoSvc->geometryIdExtrasForReadouts(m_cfg.timeReadouts);
0324   if (!m_cfg.timeReadouts.empty()) {
0325     info("Including time for readouts {} (system IDs {})", fmt::join(m_cfg.timeReadouts, ", "),
0326          fmt::join(m_timeSystemIDs, ", "));
0327   }
0328 }
0329 
0330 void CKFTracking::process(const Input& input, const Output& output) const {
0331   const auto [init_trk_seeds, meas2Ds]      = input;
0332   auto [output_track_states, output_tracks] = output;
0333 
0334   // If measurements or initial track parameters are empty, create empty output containers
0335   if (meas2Ds->empty() || init_trk_seeds->empty()) {
0336     debug("No seeds or measurements, creating empty output containers");
0337     *output_track_states = new Acts::ConstVectorMultiTrajectory();
0338     *output_tracks       = new Acts::ConstVectorTrackContainer();
0339     return;
0340   }
0341 
0342   // Time-enabled calibration requires a valid time uncertainty on every measurement that uses it
0343   if (!m_timeSystemIDs.empty()) {
0344     bool invalid = false;
0345     for (const auto& meas2D : *meas2Ds) {
0346       if (!usesTime(meas2D, m_timeSystemIDs)) {
0347         continue;
0348       }
0349       const float var_t = meas2D.getCovariance().zz;
0350       if (!std::isfinite(var_t) || var_t <= 0) {
0351         error("Time is enabled but measurement on surface {} has invalid time variance {}; "
0352               "skipping tracking for this event",
0353               meas2D.getSurface(), var_t);
0354         invalid = true;
0355         break;
0356       }
0357     }
0358     if (invalid) {
0359       *output_track_states = new Acts::ConstVectorMultiTrajectory();
0360       *output_tracks       = new Acts::ConstVectorTrackContainer();
0361       return;
0362     }
0363   }
0364 
0365   ActsExamples::TrackParametersContainer acts_init_trk_params;
0366   for (const auto& track_seed : *init_trk_seeds) {
0367 
0368     const auto& track_parameter = track_seed.getParams();
0369 
0370     Acts::BoundVector params;
0371     params(Acts::eBoundLoc0) =
0372         track_parameter.getLoc().a * Acts::UnitConstants::mm; // cylinder radius
0373     params(Acts::eBoundLoc1) =
0374         track_parameter.getLoc().b * Acts::UnitConstants::mm; // cylinder length
0375     params(Acts::eBoundPhi)    = track_parameter.getPhi();
0376     params(Acts::eBoundTheta)  = track_parameter.getTheta();
0377     params(Acts::eBoundQOverP) = track_parameter.getQOverP() / Acts::UnitConstants::GeV;
0378     params(Acts::eBoundTime)   = track_parameter.getTime() * Acts::UnitConstants::ns;
0379 
0380     Acts::BoundMatrix cov = Acts::BoundMatrix::Zero();
0381     for (std::size_t i = 0; const auto& [a, x] : edm4eic_indexed_units) {
0382       for (std::size_t j = 0; const auto& [b, y] : edm4eic_indexed_units) {
0383         cov(a, b) = track_parameter.getCovariance()(i, j) * x * y;
0384         ++j;
0385       }
0386       ++i;
0387     }
0388 
0389     // Construct the perigee surface at the seed's reference point.
0390     // For IP-originating tracks this is (0,0,0); for displaced seeds (e.g. from
0391     // Lambda decay daughters) the seed carries the actual decay-vertex position
0392     // so the CKF propagates from there instead of from the IP.
0393     const auto& perigee_pos = track_seed.getPerigee();
0394     auto pSurface           = Acts::Surface::makeShared<const Acts::PerigeeSurface>(Acts::Vector3(
0395         perigee_pos.x * Acts::UnitConstants::mm, perigee_pos.y * Acts::UnitConstants::mm,
0396         perigee_pos.z * Acts::UnitConstants::mm));
0397 
0398     // Create parameters
0399     acts_init_trk_params.emplace_back(pSurface, params, cov, Acts::ParticleHypothesis::pion());
0400   }
0401 
0402   //// Construct a perigee surface as the target surface
0403   auto pSurface = Acts::Surface::makeShared<Acts::PerigeeSurface>(Acts::Vector3{0., 0., 0.});
0404 
0405   // Convert algorithm log level to Acts log level for local logger
0406   const auto spdlog_level = static_cast<spdlog::level::level_enum>(this->level());
0407   const auto acts_level   = eicrecon::SpdlogToActsLevel(spdlog_level);
0408   ACTS_LOCAL_LOGGER(Acts::getDefaultLogger("CKF", acts_level));
0409 
0410   // Get run-scoped contexts from service
0411   const auto& gctx = m_geoSvc->getActsGeometryContext();
0412   const auto& mctx = m_geoSvc->getActsMagneticFieldContext();
0413   const auto& cctx = m_geoSvc->getActsCalibrationContext();
0414 
0415   Acts::PropagatorPlainOptions pOptions(gctx, mctx);
0416   pOptions.maxSteps = 10000;
0417 
0418   EDM4eicMeasurementSourceLinkCalibrator calibratorImpl{meas2Ds, m_timeSystemIDs};
0419   Acts::GainMatrixUpdater kfUpdater;
0420 
0421   Acts::CombinatorialKalmanFilterExtensions<ActsExamples::TrackContainer> extensions;
0422   extensions.updater.connect<&Acts::GainMatrixUpdater::operator()<
0423       typename ActsExamples::TrackContainer::TrackStateContainerBackend>>(&kfUpdater);
0424 
0425   ActsExamples::IndexSourceLinkAccessor slAccessor;
0426   slAccessor.container = &calibratorImpl.orderedSourceLinks();
0427   using TrackStateCreatorType =
0428       Acts::TrackStateCreator<ActsExamples::IndexSourceLinkAccessor::Iterator,
0429                               ActsExamples::TrackContainer>;
0430   TrackStateCreatorType trackStateCreator;
0431   trackStateCreator.sourceLinkAccessor
0432       .template connect<&ActsExamples::IndexSourceLinkAccessor::range>(&slAccessor);
0433   trackStateCreator.calibrator.template connect<&EDM4eicMeasurementSourceLinkCalibrator::calibrate>(
0434       &calibratorImpl);
0435   trackStateCreator.measurementSelector
0436       .template connect<&Acts::MeasurementSelector::select<Acts::VectorMultiTrajectory>>(
0437           &*m_measurementSelector);
0438 
0439   extensions.createTrackStates.template connect<&TrackStateCreatorType::createTrackStates>(
0440       &trackStateCreator);
0441 
0442   // Per-branch stopping (ACTS default never stops a branch).
0443   CKFBranchStopper branchStopper{m_cfg, [this](const std::string& msg) { debug("{}", msg); }};
0444   extensions.branchStopper.connect<&CKFBranchStopper::operator()>(&branchStopper);
0445 
0446   // Set the CombinatorialKalmanFilter options
0447   CKFTracking::TrackFinderOptions options(gctx, mctx, cctx, extensions, pOptions);
0448 
0449   using Extrapolator = Acts::Propagator<Acts::EigenStepper<>, Acts::Navigator>;
0450 #if __has_include(<Acts/Propagator/DefaultActor.hpp>)
0451   // Acts >= PR #6410: a single actor per propagation; DefaultActor provides
0452   // the target surface, path limit and (optional) end-of-world abort conditions
0453   using ExtrapolatorOptions =
0454       Extrapolator::template Options<Acts::ActorList<Acts::DefaultActor, Acts::MaterialInteractor>>;
0455 #else
0456   using ExtrapolatorOptions = Extrapolator::template Options<
0457       Acts::ActorList<Acts::MaterialInteractor, Acts::EndOfWorldReached>>;
0458 #endif
0459   Extrapolator extrapolator(Acts::EigenStepper<>(m_BField),
0460                             Acts::Navigator({.trackingGeometry = m_geoSvc->trackingGeometry()},
0461                                             acts_logger().cloneWithSuffix("Navigator")),
0462                             acts_logger().cloneWithSuffix("Propagator"));
0463   ExtrapolatorOptions extrapolationOptions(gctx, mctx);
0464 #if __has_include(<Acts/Propagator/DefaultActor.hpp>)
0465   extrapolationOptions.stopAtEndOfWorld = true;
0466 #endif
0467 
0468   // Create track container
0469   auto trackContainer      = std::make_shared<Acts::VectorTrackContainer>();
0470   auto trackStateContainer = std::make_shared<Acts::VectorMultiTrajectory>();
0471   ActsExamples::TrackContainer acts_tracks(trackContainer, trackStateContainer);
0472 
0473   // Create temporary track container
0474   auto trackContainerTemp      = std::make_shared<Acts::VectorTrackContainer>();
0475   auto trackStateContainerTemp = std::make_shared<Acts::VectorMultiTrajectory>();
0476   ActsExamples::TrackContainer acts_tracks_temp(trackContainerTemp, trackStateContainerTemp);
0477 
0478   // Add seed number column
0479   acts_tracks.addColumn<unsigned int>("seed");
0480   acts_tracks_temp.addColumn<unsigned int>("seed");
0481   Acts::ProxyAccessor<unsigned int> seedNumber("seed");
0482 
0483   // Loop over seeds
0484   for (std::size_t iseed = 0; iseed < acts_init_trk_params.size(); ++iseed) {
0485 
0486     // Clear trackContainerTemp and trackStateContainerTemp
0487     acts_tracks_temp.clear();
0488 
0489     // Run track finding for this seed
0490     auto result = (*m_trackFinderFunc)(acts_init_trk_params.at(iseed), options, acts_tracks_temp);
0491 
0492     if (!result.ok()) {
0493       debug("Track finding failed for seed {} with error {}", iseed, result.error().message());
0494       continue;
0495     }
0496 
0497     // Set seed number for all found tracks
0498     auto& tracksForSeed = result.value();
0499     for (auto& track : tracksForSeed) {
0500       // Check if track has at least one valid (non-outlier) measurement
0501       // (this check avoids errors inside smoothing and extrapolation)
0502       auto lastMeasurement = Acts::findLastMeasurementState(track);
0503       if (!lastMeasurement.ok()) {
0504         debug("Track {} for seed {} has no valid measurements, skipping", track.index(), iseed);
0505         continue;
0506       }
0507 
0508       if (track.nMeasurements() < m_cfg.numMeasurementsMin) {
0509         trace("Track {} for seed {} has fewer measurements than minimum of {}, skipping",
0510               track.index(), iseed, m_cfg.numMeasurementsMin);
0511         continue;
0512       }
0513 
0514       auto smoothingResult = Acts::smoothTrack(gctx, track, acts_logger());
0515       if (!smoothingResult.ok()) {
0516         debug("Smoothing for seed {} and track {} failed with error {}", iseed, track.index(),
0517               smoothingResult.error().message());
0518         continue;
0519       }
0520 
0521       auto extrapolationResult = Acts::extrapolateTrackToReferenceSurface(
0522           track, *pSurface, extrapolator, extrapolationOptions,
0523           Acts::TrackExtrapolationStrategy::firstOrLast, acts_logger());
0524 
0525       if (!extrapolationResult.ok()) {
0526         debug("Extrapolation for seed {} and track {} failed with error {}", iseed, track.index(),
0527               extrapolationResult.error().message());
0528         continue;
0529       }
0530 
0531       seedNumber(track) = iseed;
0532 
0533       // Copy accepted track into main track container
0534       auto acts_tracks_proxy = acts_tracks.makeTrack();
0535       acts_tracks_proxy.copyFrom(track);
0536     }
0537   }
0538 
0539   // Allocate new const containers and assign pointers to outputs
0540   *output_track_states = new Acts::ConstVectorMultiTrajectory(std::move(*trackStateContainer));
0541   *output_tracks       = new Acts::ConstVectorTrackContainer(std::move(*trackContainer));
0542 }
0543 
0544 } // namespace eicrecon