Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-18 09:56:25

0001 // This file is part of the ACTS project.
0002 //
0003 // Copyright (C) 2016 CERN for the benefit of the ACTS project
0004 //
0005 // This Source Code Form is subject to the terms of the Mozilla Public
0006 // License, v. 2.0. If a copy of the MPL was not distributed with this
0007 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
0008 
0009 #pragma once
0010 
0011 #include "Acts/Definitions/Common.hpp"
0012 #include "Acts/EventData/MultiTrajectory.hpp"
0013 #include "Acts/EventData/MultiTrajectoryHelpers.hpp"
0014 #include "Acts/EventData/TrackStatePropMask.hpp"
0015 #include "Acts/EventData/TransformationHelpers.hpp"
0016 #include "Acts/EventData/Types.hpp"
0017 #include "Acts/Geometry/GeometryContext.hpp"
0018 #include "Acts/MagneticField/MagneticFieldContext.hpp"
0019 #include "Acts/Propagator/ActorList.hpp"
0020 #include "Acts/Propagator/ConstrainedStep.hpp"
0021 #include "Acts/Propagator/PropagatorState.hpp"
0022 #include "Acts/Propagator/StandardAborters.hpp"
0023 #include "Acts/Propagator/StepperConcept.hpp"
0024 #include "Acts/Propagator/detail/LoopProtection.hpp"
0025 #include "Acts/Propagator/detail/PointwiseMaterialInteraction.hpp"
0026 #include "Acts/TrackFinding/CombinatorialKalmanFilterError.hpp"
0027 #include "Acts/TrackFinding/CombinatorialKalmanFilterExtensions.hpp"
0028 #include "Acts/TrackFitting/BetheHeitlerApprox.hpp"
0029 #include "Acts/TrackFitting/GsfOptions.hpp"
0030 #include "Acts/TrackFitting/detail/GsfComponentMerging.hpp"
0031 #include "Acts/TrackFitting/detail/GsfUtils.hpp"
0032 #include "Acts/Utilities/CalibrationContext.hpp"
0033 #include "Acts/Utilities/Logger.hpp"
0034 #include "Acts/Utilities/Result.hpp"
0035 
0036 #include <functional>
0037 #include <limits>
0038 #include <memory>
0039 #include <stdexcept>
0040 #include <type_traits>
0041 
0042 namespace Acts {
0043 
0044 /// @addtogroup track_finding
0045 /// @{
0046 
0047 /// Combined options for the combinatorial Kalman filter.
0048 ///
0049 /// @tparam source_link_iterator_t Type of the source link iterator
0050 /// @tparam track_container_t Type of the track container
0051 template <typename track_container_t>
0052 struct CombinatorialKalmanFilterOptions {
0053   /// Type alias for track state container backend
0054   using TrackStateContainerBackend =
0055       typename track_container_t::TrackStateContainerBackend;
0056   /// Type alias for track state proxy from the container
0057   using TrackStateProxy = typename track_container_t::TrackStateProxy;
0058 
0059   /// PropagatorOptions with context
0060   ///
0061   /// @param gctx The geometry context for this track finding/fitting
0062   /// @param mctx The magnetic context for this track finding/fitting
0063   /// @param cctx The calibration context for this track finding/fitting
0064   /// @param extensions_ The extension struct
0065   /// @param pOptions The plain propagator options
0066   /// @param mScattering Whether to include multiple scattering
0067   /// @param eLoss Whether to include energy loss
0068   CombinatorialKalmanFilterOptions(
0069       const GeometryContext& gctx, const MagneticFieldContext& mctx,
0070       std::reference_wrapper<const CalibrationContext> cctx,
0071       CombinatorialKalmanFilterExtensions<track_container_t> extensions_,
0072       const PropagatorPlainOptions& pOptions, bool mScattering = true,
0073       bool eLoss = true)
0074       : geoContext(gctx),
0075         magFieldContext(mctx),
0076         calibrationContext(cctx),
0077         extensions(extensions_),
0078         propagatorPlainOptions(pOptions),
0079         multipleScattering(mScattering),
0080         energyLoss(eLoss) {}
0081 
0082   /// Contexts are required and the options must not be default-constructible.
0083   CombinatorialKalmanFilterOptions() = delete;
0084 
0085   /// Context object for the geometry
0086   std::reference_wrapper<const GeometryContext> geoContext;
0087   /// Context object for the magnetic field
0088   std::reference_wrapper<const MagneticFieldContext> magFieldContext;
0089   /// context object for the calibration
0090   std::reference_wrapper<const CalibrationContext> calibrationContext;
0091 
0092   /// The filter extensions
0093   CombinatorialKalmanFilterExtensions<track_container_t> extensions;
0094 
0095   /// The trivial propagator options
0096   PropagatorPlainOptions propagatorPlainOptions;
0097 
0098   /// The target surface
0099   /// @note This is useful if the filtering should be terminated at a
0100   ///       certain surface
0101   const Surface* targetSurface = nullptr;
0102 
0103   /// Whether to consider multiple scattering.
0104   bool multipleScattering = true;
0105 
0106   /// Whether to consider energy loss.
0107   bool energyLoss = true;
0108 
0109   /// Skip the pre propagation call. This effectively skips the first surface
0110   /// @note This is useful if the first surface should not be considered in a second reverse pass
0111   bool skipPrePropagationUpdate = false;
0112 
0113   /// Whether to record track states on material-only (non-sensitive) surfaces.
0114   /// Material effects are applied either way, only the record is dropped.
0115   /// @note Keep enabled if the surfaces themselves are needed, e.g. for a refit
0116   ///       with the `DirectNavigator`. Must stay enabled with a
0117   ///       multi-component stepper.
0118   bool recordMaterialStates = true;
0119 };
0120 
0121 /// Options for the combinatorial Kalman filter with bremsstrahlung recovery.
0122 ///
0123 /// These extend the plain options with the parameters that are only meaningful
0124 /// when the filter runs with a multi-component (GSF-like) stepper. Keeping them
0125 /// in a dedicated type means the single-component configuration cannot even
0126 /// name them.
0127 ///
0128 /// @tparam track_container_t Type of the track container
0129 template <typename track_container_t>
0130 struct BremCombinatorialKalmanFilterOptions
0131     : public CombinatorialKalmanFilterOptions<track_container_t> {
0132   /// Reuse the base-class constructors.
0133   using CombinatorialKalmanFilterOptions<
0134       track_container_t>::CombinatorialKalmanFilterOptions;
0135 
0136   /// Maximum number of components which the GSF should handle
0137   std::size_t maxComponents = 12;
0138 
0139   /// When to discard components
0140   double weightCutoff = 1e-4;
0141 
0142   /// How to reduce the states that are stored in the multi trajectory
0143   ComponentMergeMethod mergeMethod = ComponentMergeMethod::eMaxWeight;
0144 
0145   /// The Bethe-Heitler approximation for bremsstrahlung energy loss
0146   std::shared_ptr<const BetheHeitlerApprox> betheHeitlerApprox;
0147 };
0148 
0149 /// Result container for the combinatorial Kalman filter actor.
0150 ///
0151 /// @tparam track_container_t Type of the track container storing results
0152 template <typename track_container_t>
0153 struct CombinatorialKalmanFilterResult {
0154   /// Track state container backend type
0155   using TrackStateContainerBackend =
0156       typename track_container_t::TrackStateContainerBackend;
0157   /// Track proxy type
0158   using TrackProxy = typename track_container_t::TrackProxy;
0159   /// Track state proxy type
0160   using TrackStateProxy = typename track_container_t::TrackStateProxy;
0161 
0162   /// The track container to store the found tracks
0163   track_container_t* tracks{nullptr};
0164 
0165   /// Fitted states that the actor has handled.
0166   TrackStateContainerBackend* trackStates{nullptr};
0167 
0168   /// Indices into `tracks` which mark active branches
0169   std::vector<TrackProxy> activeBranches;
0170 
0171   /// Indices into `tracks` which mark active branches
0172   std::vector<TrackProxy> collectedTracks;
0173 
0174   /// Track state candidates buffer which can be used by the track state creator
0175   std::vector<TrackStateProxy> trackStateCandidates;
0176 
0177   /// Transport jacobians of skipped material surfaces, folded into the next
0178   /// recorded track state to keep the jacobian chain intact
0179   BoundMatrix accumulatedJacobian = BoundMatrix::Identity();
0180 
0181   /// Indicator if track finding has been done
0182   bool finished = false;
0183 
0184   /// Path limit aborter
0185   PathLimitReached pathLimitReached;
0186 };
0187 
0188 /// Combinatorial Kalman filter to find tracks.
0189 ///
0190 /// @tparam propagator_t Type of the propagator
0191 ///
0192 /// The CombinatorialKalmanFilter contains an Actor and a Sequencer sub-class.
0193 /// The Sequencer has to be part of the Navigator of the Propagator in order to
0194 /// initialize and provide the measurement surfaces.
0195 ///
0196 /// The Actor is part of the Propagation call and does the Kalman update.
0197 /// Updater and Calibrator are given to the Actor for further use:
0198 /// - The Updater is the implemented kalman updater formalism, it
0199 ///   runs via a visitor pattern through the measurements.
0200 ///
0201 /// Measurements are not required to be ordered for the
0202 /// CombinatorialKalmanFilter, measurement ordering needs to be figured out by
0203 /// the navigation of the propagator.
0204 ///
0205 /// The void components are provided mainly for unit testing.
0206 ///
0207 template <typename propagator_t, typename track_container_t>
0208 class CombinatorialKalmanFilter {
0209  public:
0210   /// Constructor with propagator and logging level
0211   /// @param pPropagator The propagator used for the track finding
0212   /// @param _logger The logger for messages
0213   explicit CombinatorialKalmanFilter(propagator_t pPropagator,
0214                                      std::unique_ptr<const Logger> _logger =
0215                                          getDefaultLogger("CKF", Logging::INFO))
0216       : m_propagator(std::move(pPropagator)),
0217         m_logger(std::move(_logger)),
0218         m_actorLogger{m_logger->cloneWithSuffix("Actor")},
0219         m_updaterLogger{m_logger->cloneWithSuffix("Updater")} {}
0220 
0221  private:
0222   using BoundState = std::tuple<BoundTrackParameters, BoundMatrix, double>;
0223   using TrackStateContainerBackend =
0224       typename track_container_t::TrackStateContainerBackend;
0225   using TrackProxy = typename track_container_t::TrackProxy;
0226   using TrackStateProxy = typename track_container_t::TrackStateProxy;
0227 
0228   static constexpr bool IsMultiStepper =
0229       Concepts::MultiStepper<typename propagator_t::Stepper>;
0230   using TemporaryStates = detail::Gsf::TemporaryStates<VectorMultiTrajectory>;
0231 
0232   /// Single component bound state tuple containing parameters, Jacobian, and
0233   /// path length
0234   using SingleBoundState =
0235       std::tuple<BoundTrackParameters, BoundMatrix, double>;
0236 
0237   /// The propagator for the transport and material update
0238   propagator_t m_propagator;
0239 
0240   std::unique_ptr<const Logger> m_logger;
0241   std::shared_ptr<const Logger> m_actorLogger;
0242   std::shared_ptr<const Logger> m_updaterLogger;
0243 
0244   const Logger& logger() const { return *m_logger; }
0245 
0246   /// @brief Propagator Actor plugin for the CombinatorialKalmanFilter
0247   ///
0248   /// The CombinatorialKalmanFilter Actor does not rely on the measurements to
0249   /// be sorted along the track.
0250   class Actor {
0251    public:
0252     using BoundState = std::tuple<BoundTrackParameters, BoundMatrix, double>;
0253     /// Broadcast the result_type
0254     using result_type = CombinatorialKalmanFilterResult<track_container_t>;
0255 
0256     using BranchStopperResult = CombinatorialKalmanFilterBranchStopperResult;
0257 
0258     /// The target surface aborter
0259     SurfaceReached targetReached{std::numeric_limits<double>::lowest()};
0260 
0261     /// Whether to consider multiple scattering.
0262     bool multipleScattering = true;
0263 
0264     /// Whether to consider energy loss.
0265     bool energyLoss = true;
0266 
0267     /// Skip the pre propagation call. This effectively skips the first surface
0268     bool skipPrePropagationUpdate = false;
0269 
0270     /// @see CombinatorialKalmanFilterOptions::recordMaterialStates
0271     bool recordMaterialStates = true;
0272 
0273     /// Calibration context for the finding run
0274     const CalibrationContext* calibrationContextPtr{nullptr};
0275 
0276     CombinatorialKalmanFilterExtensions<track_container_t> extensions;
0277 
0278     /// End of world aborter
0279     EndOfWorldReached endOfWorldReached;
0280 
0281     /// Volume constraint aborter
0282     VolumeConstraintAborter volumeConstraintAborter;
0283 
0284     /// State that is only meaningful when the filter runs with a
0285     /// multi-component stepper (bremsstrahlung recovery).
0286     struct BremState {
0287       /// Maximum number of components which the GSF should handle
0288       std::size_t maxComponents = 12;
0289       /// When to discard components
0290       double weightCutoff = 1e-4;
0291       /// How to reduce the states that are stored in the multi trajectory
0292       ComponentMergeMethod mergeMethod = ComponentMergeMethod::eMaxWeight;
0293       /// The Bethe-Heitler approximation for bremsstrahlung energy loss
0294       const BetheHeitlerApprox* betheHeitlerApprox{nullptr};
0295 
0296       /// Scratch buffers reused across surfaces during the multi-component
0297       /// update. Owned by `findTracks` and wired in before propagation.
0298       TemporaryStates* temporaryStates{nullptr};
0299       /// Bethe-Heitler approximation components cache
0300       std::vector<BetheHeitlerApprox::Component>* betheHeitlerCache{nullptr};
0301       /// GsfComponent cache for the multi-component update
0302       std::vector<GsfComponent>* componentCache{nullptr};
0303     };
0304     /// Empty stand-in for the single-component stepper.
0305     struct NoBremState {};
0306 
0307     /// Bremsstrahlung-only state, gated on the stepper type so it adds no
0308     /// storage in the single-component case.
0309     [[no_unique_address]] std::conditional_t<IsMultiStepper, BremState,
0310                                              NoBremState> brem;
0311 
0312     /// Actor logger instance
0313     const Logger* actorLogger{nullptr};
0314     /// Updater logger instance
0315     const Logger* updaterLogger{nullptr};
0316 
0317     const Logger& logger() const { return *actorLogger; }
0318 
0319     /// @brief CombinatorialKalmanFilter actor operation
0320     ///
0321     /// @tparam propagator_state_t Type of the Propagator state
0322     /// @tparam stepper_t Type of the stepper
0323     ///
0324     /// @param state is the mutable propagator state object
0325     /// @param stepper is the stepper in use
0326     /// @param navigator is the navigator in use
0327     /// @param result is the mutable result state object
0328     template <typename propagator_state_t, typename stepper_t,
0329               typename navigator_t>
0330     Result<void> act(propagator_state_t& state, const stepper_t& stepper,
0331                      const navigator_t& navigator, result_type& result,
0332                      const Logger& /*logger*/) const {
0333       ACTS_VERBOSE("CKF Actor called");
0334 
0335       assert(result.trackStates && "No MultiTrajectory set");
0336 
0337       if (state.stage == PropagatorStage::prePropagation &&
0338           skipPrePropagationUpdate) {
0339         ACTS_VERBOSE("Skip pre-propagation update (first surface)");
0340         return Result<void>::success();
0341       }
0342       if (state.stage == PropagatorStage::postPropagation) {
0343         ACTS_VERBOSE("Skip post-propagation action");
0344         return Result<void>::success();
0345       }
0346 
0347       ACTS_VERBOSE("CombinatorialKalmanFilter step");
0348 
0349       assert(!result.activeBranches.empty() && "No active branches");
0350       assert(!result.finished && "Should never reach this when finished");
0351 
0352       // Initialize path limit reached aborter
0353       if (result.pathLimitReached.internalLimit ==
0354           std::numeric_limits<double>::max()) {
0355         detail::setupLoopProtection(state, stepper, result.pathLimitReached,
0356                                     true, logger());
0357       }
0358 
0359       // Update:
0360       // - Waiting for a current surface
0361       if (const Surface* surface = navigator.currentSurface(state.navigation);
0362           surface != nullptr) {
0363         // There are three scenarios:
0364         // 1) The surface is in the measurement map
0365         // -> Select source links
0366         // -> Perform the kalman update for selected non-outlier source links
0367         // -> Add track states in multitrajectory. Multiple states mean branch
0368         // splitting.
0369         // -> Call branch stopper to justify each branch
0370         // -> If there is non-outlier state, update stepper information
0371         // 2) The surface is not in the measurement map but with material or is
0372         // an active surface
0373         // -> Add a hole or passive material state in multitrajectory
0374         // -> Call branch stopper to justify the branch
0375         // 3) The surface is neither in the measurement map nor with material
0376         // -> Do nothing
0377         ACTS_VERBOSE("Perform filter step");
0378         auto res = filter(*surface, state, stepper, navigator, result);
0379         if (!res.ok()) {
0380           ACTS_DEBUG("Error in filter: " << res.error().message());
0381           return res.error();
0382         }
0383 
0384         if (result.finished) {
0385           ACTS_VERBOSE("CKF Actor returns after filter step");
0386           return Result<void>::success();
0387         }
0388       }
0389 
0390       assert(!result.activeBranches.empty() && "No active branches");
0391 
0392       const bool isEndOfWorldReached =
0393           endOfWorldReached.checkAbort(state, stepper, navigator, logger());
0394       const bool isVolumeConstraintReached = volumeConstraintAborter.checkAbort(
0395           state, stepper, navigator, logger());
0396       const bool isPathLimitReached = result.pathLimitReached.checkAbort(
0397           state, stepper, navigator, logger());
0398       const bool isTargetReached =
0399           targetReached.checkAbort(state, stepper, navigator, logger());
0400       if (isEndOfWorldReached || isVolumeConstraintReached ||
0401           isPathLimitReached || isTargetReached) {
0402         if (isEndOfWorldReached) {
0403           ACTS_VERBOSE("End of world reached");
0404         } else if (isVolumeConstraintReached) {
0405           ACTS_VERBOSE("Volume constraint reached");
0406         } else if (isPathLimitReached) {
0407           ACTS_VERBOSE("Path limit reached");
0408         } else if (isTargetReached) {
0409           ACTS_VERBOSE("Target surface reached");
0410 
0411           // Bind the parameter to the target surface
0412           auto res = stepper.boundState(state.stepping, *targetReached.surface);
0413           if (!res.ok()) {
0414             ACTS_DEBUG("Error while acquiring bound state for target surface: "
0415                        << res.error() << " " << res.error().message());
0416             return res.error();
0417           }
0418 
0419           const auto& [boundParams, jacobian, pathLength] = *res;
0420           auto currentBranch = result.activeBranches.back();
0421           // Assign the fitted parameters
0422           if constexpr (!IsMultiStepper) {
0423             currentBranch.parameters() = boundParams.parameters();
0424             currentBranch.covariance() = *boundParams.covariance();
0425           } else {
0426             const auto singleParams = boundParams.merge(brem.mergeMethod);
0427             currentBranch.parameters() = singleParams.parameters();
0428             currentBranch.covariance() = *singleParams.covariance();
0429           }
0430           currentBranch.setReferenceSurface(
0431               boundParams.referenceSurface().getSharedPtr());
0432 
0433           stepper.releaseStepSize(state.stepping,
0434                                   ConstrainedStep::Type::Navigator);
0435         }
0436 
0437         // Record the active branch and remove it from the list
0438         storeLastActiveBranch(result);
0439         result.activeBranches.pop_back();
0440 
0441         // Reset propagation state to track state at next active branch
0442         auto resetRes = reset(state, stepper, navigator, result);
0443         if (!resetRes.ok()) {
0444           return resetRes.error();
0445         }
0446       }
0447 
0448       return Result<void>::success();
0449     }
0450 
0451     template <typename propagator_state_t, typename stepper_t,
0452               typename navigator_t>
0453     bool checkAbort(propagator_state_t& /*state*/, const stepper_t& /*stepper*/,
0454                     const navigator_t& /*navigator*/, const result_type& result,
0455                     const Logger& /*logger*/) const {
0456       return result.finished;
0457     }
0458 
0459     /// @brief CombinatorialKalmanFilter actor operation: reset propagation
0460     ///
0461     /// @tparam propagator_state_t Type of Propagator state
0462     /// @tparam stepper_t Type of the stepper
0463     /// @tparam navigator_t Type of the navigator
0464     ///
0465     /// @param state is the mutable propagator state object
0466     /// @param stepper is the stepper in use
0467     /// @param navigator is the navigator in use
0468     /// @param result is the mutable result state object
0469     template <typename propagator_state_t, typename stepper_t,
0470               typename navigator_t>
0471     Result<void> reset(propagator_state_t& state, const stepper_t& stepper,
0472                        const navigator_t& navigator,
0473                        result_type& result) const {
0474       if (result.activeBranches.empty()) {
0475         ACTS_VERBOSE("Stop CKF with " << result.collectedTracks.size()
0476                                       << " found tracks");
0477         result.finished = true;
0478 
0479         return Result<void>::success();
0480       }
0481 
0482       auto currentBranch = result.activeBranches.back();
0483       auto currentState = currentBranch.outermostTrackState();
0484 
0485       ACTS_VERBOSE("Propagation jumps to branch with tip = "
0486                    << currentBranch.tipIndex());
0487 
0488       // Reset the stepping state
0489       if constexpr (!IsMultiStepper) {
0490         stepper.initialize(state.stepping, currentState.filtered(),
0491                            currentState.filteredCovariance(),
0492                            stepper.particleHypothesis(state.stepping),
0493                            currentState.referenceSurface());
0494       } else {
0495         const MultiComponentBoundTrackParameters multiBoundParameters(
0496             currentState.referenceSurface().getSharedPtr(),
0497             currentState.filtered(), currentState.filteredCovariance(),
0498             stepper.particleHypothesis(state.stepping));
0499 
0500         stepper.initialize(state.stepping, multiBoundParameters);
0501       }
0502 
0503       // `initialize` re-roots the jacobian chain at this branch
0504       result.accumulatedJacobian = BoundMatrix::Identity();
0505 
0506       // Reset the navigation state
0507       // Set targetSurface to nullptr for forward filtering
0508       state.navigation.options.startSurface = &currentState.referenceSurface();
0509       state.navigation.options.targetSurface = nullptr;
0510       auto navInitRes = navigator.initialize(
0511           state.navigation, stepper.position(state.stepping),
0512           stepper.direction(state.stepping), state.options.direction);
0513       if (!navInitRes.ok()) {
0514         ACTS_DEBUG("Navigation initialization failed: " << navInitRes.error());
0515         return navInitRes.error();
0516       }
0517 
0518       // No Kalman filtering for the starting surface, but still need
0519       // to consider the material effects here
0520       const Result<void> materialRes = performMaterialInteraction(
0521           state, stepper, currentState.referenceSurface(),
0522           detail::determineMaterialUpdateMode(state, navigator,
0523                                               MaterialUpdateMode::PostUpdate));
0524       if (!materialRes.ok()) {
0525         ACTS_DEBUG("Material interaction failed during reset: "
0526                    << materialRes.error().message());
0527         return materialRes.error();
0528       }
0529 
0530       // Set path limit based on loop protection
0531       detail::setupLoopProtection(state, stepper, result.pathLimitReached, true,
0532                                   logger());
0533 
0534       // Set path limit based on target surface
0535       targetReached.checkAbort(state, stepper, navigator, logger());
0536 
0537       return Result<void>::success();
0538     }
0539 
0540     /// @brief CombinatorialKalmanFilter actor operation:
0541     /// - filtering for all measurement(s) on surface
0542     /// - store selected track states in multiTrajectory
0543     /// - update propagator state to the (last) selected track state
0544     ///
0545     /// @tparam propagator_state_t Type of the Propagator state
0546     /// @tparam stepper_t Type of the stepper
0547     /// @tparam navigator_t Type of the navigator
0548     ///
0549     /// @param surface The surface where the update happens
0550     /// @param state The mutable propagator state object
0551     /// @param stepper The stepper in use
0552     /// @param navigator The navigator in use
0553     /// @param result The mutable result state object
0554     template <typename propagator_state_t, typename stepper_t,
0555               typename navigator_t>
0556     Result<void> filter(const Surface& surface, propagator_state_t& state,
0557                         const stepper_t& stepper, const navigator_t& navigator,
0558                         result_type& result) const {
0559       using PM = TrackStatePropMask;
0560 
0561       const bool isSensitive = surface.isSensitive();
0562       const bool hasMaterial = surface.hasMaterial();
0563       const bool isMaterialOnly = hasMaterial && !isSensitive;
0564       bool expectMeasurements = isSensitive;
0565 
0566       if (isSensitive) {
0567         ACTS_VERBOSE("Measurement surface " << surface.geometryId()
0568                                             << " detected.");
0569       } else if (isMaterialOnly) {
0570         ACTS_VERBOSE("Material surface " << surface.geometryId()
0571                                          << " detected.");
0572       } else {
0573         ACTS_VERBOSE("Passive surface " << surface.geometryId()
0574                                         << " detected.");
0575         return Result<void>::success();
0576       }
0577 
0578       // Transport the covariance to the surface
0579       if (isMaterialOnly) {
0580         stepper.transportCovarianceToCurvilinear(state.stepping);
0581       } else {
0582         stepper.transportCovarianceToBound(state.stepping, surface);
0583       }
0584 
0585       // Update state and stepper with pre material effects
0586       const Result<void> materialPreRes = performMaterialInteraction(
0587           state, stepper, surface,
0588           detail::determineMaterialUpdateMode(state, navigator,
0589                                               MaterialUpdateMode::PreUpdate));
0590       if (!materialPreRes.ok()) {
0591         ACTS_DEBUG("Material interaction failed during reset: "
0592                    << materialPreRes.error().message());
0593         return materialPreRes.error();
0594       }
0595 
0596       if constexpr (!IsMultiStepper) {
0597         if (isMaterialOnly && !recordMaterialStates) {
0598           ACTS_VERBOSE("Skip material track state on surface "
0599                        << surface.geometryId());
0600 
0601           // keep the jacobian segment the transport above just closed
0602           result.accumulatedJacobian =
0603               state.stepping.jacobian * result.accumulatedJacobian;
0604 
0605           // apply the post material effects and return early, skipping the
0606           // track state creation below
0607           const Result<void> materialPostRes = performMaterialInteraction(
0608               state, stepper, surface,
0609               detail::determineMaterialUpdateMode(
0610                   state, navigator, MaterialUpdateMode::PostUpdate));
0611           if (!materialPostRes.ok()) {
0612             ACTS_DEBUG("Material interaction failed during post-update: "
0613                        << materialPostRes.error().message());
0614           }
0615           return materialPostRes;
0616         }
0617       }
0618 
0619       // Bind the transported state to the current surface
0620       auto boundStateRes = [&]() -> Result<SingleBoundState> {
0621         if constexpr (!IsMultiStepper) {
0622           auto res = stepper.boundState(state.stepping, surface, false);
0623           if (!res.ok()) {
0624             return res.error();
0625           }
0626           auto& [boundParams, jacobian, pathLength] = *res;
0627           boundParams.covariance() = state.stepping.cov;
0628           return res;
0629         } else {
0630           // This triggers a second covariance transport which is wasteful in
0631           // terms of compute. But the multi stepper might filter bound
0632           // components and we cannot easily match stepper components to bound
0633           // parameter components right now to make use of the same track as
0634           // above.
0635           // TODO this should be revisited
0636           auto res = stepper.boundState(state.stepping, surface, true);
0637           if (!res.ok()) {
0638             return res.error();
0639           }
0640           auto [multiBoundParams, jacobian, pathLength] = *res;
0641           const auto singleParams = multiBoundParams.merge(brem.mergeMethod);
0642           return Result<SingleBoundState>::success(
0643               {singleParams, jacobian, pathLength});
0644         }
0645       }();
0646       if (!boundStateRes.ok()) {
0647         return boundStateRes.error();
0648       }
0649       auto& boundState = *boundStateRes;
0650 
0651       if constexpr (!IsMultiStepper) {
0652         if (!recordMaterialStates) {
0653           // prepend the jacobians of the surfaces skipped since the last state
0654           std::get<1>(boundState) =
0655               std::get<1>(boundState) * result.accumulatedJacobian;
0656           result.accumulatedJacobian = BoundMatrix::Identity();
0657         }
0658       }
0659 
0660       auto currentBranch = result.activeBranches.back();
0661       TrackIndexType prevTip = currentBranch.tipIndex();
0662 
0663       using TrackStatesResult = Result<CkfTypes::BranchVector<TrackIndexType>>;
0664       TrackStatesResult tsRes = TrackStatesResult::success({});
0665       if (isSensitive) {
0666         // extend trajectory with measurements associated to the current surface
0667         // which may create extra trajectory branches if more than one
0668         // measurement is selected.
0669         tsRes = extensions.createTrackStates(
0670             state.geoContext, *calibrationContextPtr, surface, boundState,
0671             prevTip, result.trackStateCandidates, *result.trackStates,
0672             logger());
0673       }
0674 
0675       if (tsRes.ok() && !(*tsRes).empty()) {
0676         const CkfTypes::BranchVector<TrackIndexType>& newTrackStateList =
0677             *tsRes;
0678         const Result<unsigned int> procRes =
0679             processNewTrackStates(state, stepper, newTrackStateList, result);
0680         if (!procRes.ok()) {
0681           ACTS_DEBUG("Processing of selected track states failed: "
0682                      << procRes.error().message());
0683           return procRes.error();
0684         }
0685         unsigned int nBranchesOnSurface = *procRes;
0686 
0687         if (nBranchesOnSurface == 0) {
0688           ACTS_VERBOSE("All branches on surface " << surface.geometryId()
0689                                                   << " have been stopped");
0690 
0691           Result<void> resetRes = reset(state, stepper, navigator, result);
0692           if (!resetRes.ok()) {
0693             return resetRes.error();
0694           }
0695 
0696           return Result<void>::success();
0697         }
0698 
0699         // `currentBranch` is invalidated after `processNewTrackStates`
0700         currentBranch = result.activeBranches.back();
0701         prevTip = currentBranch.tipIndex();
0702       } else {
0703         if (!tsRes.ok()) {
0704           if (static_cast<CombinatorialKalmanFilterError>(
0705                   tsRes.error().value()) ==
0706               CombinatorialKalmanFilterError::NoMeasurementExpected) {
0707             // recoverable error returned by track state creator
0708             expectMeasurements = false;
0709           } else {
0710             ACTS_DEBUG("Track state creation failed on surface "
0711                        << surface.geometryId() << ": " << tsRes.error());
0712             return tsRes.error();
0713           }
0714         }
0715 
0716         if (expectMeasurements) {
0717           ACTS_VERBOSE("Detected hole after measurement selection on surface "
0718                        << surface.geometryId());
0719         }
0720 
0721         const auto stateMask = PM::Predicted | PM::Jacobian;
0722 
0723         // Add a hole or material track state to the multitrajectory
0724         TrackIndexType currentTip =
0725             addNonSourcelinkState(stateMask, boundState, result, isSensitive,
0726                                   expectMeasurements, prevTip);
0727         currentBranch.tipIndex() = currentTip;
0728         auto currentState = currentBranch.outermostTrackState();
0729         if (expectMeasurements) {
0730           currentBranch.nHoles()++;
0731         }
0732 
0733         BranchStopperResult branchStopperResult =
0734             extensions.branchStopper(currentBranch, currentState);
0735 
0736         // Check the branch
0737         if (branchStopperResult == BranchStopperResult::Continue) {
0738           // Remembered the active branch and its state
0739         } else {
0740           // No branch on this surface
0741           if (branchStopperResult == BranchStopperResult::StopAndKeep) {
0742             storeLastActiveBranch(result);
0743           }
0744           // Remove the branch from list
0745           result.activeBranches.pop_back();
0746 
0747           // Branch on the surface has been stopped - reset
0748           ACTS_VERBOSE("Branch on surface " << surface.geometryId()
0749                                             << " has been stopped");
0750 
0751           Result<void> resetRes = reset(state, stepper, navigator, result);
0752           if (!resetRes.ok()) {
0753             return resetRes.error();
0754           }
0755 
0756           return Result<void>::success();
0757         }
0758       }
0759 
0760       auto currentState = currentBranch.outermostTrackState();
0761 
0762       if (currentState.typeFlags().isOutlier()) {
0763         // We don't need to update the stepper given an outlier state
0764         ACTS_VERBOSE("Outlier state detected on surface "
0765                      << surface.geometryId());
0766       } else if (currentState.typeFlags().isMeasurement()) {
0767         // If there are measurement track states on this surface
0768         // Update stepping state using filtered parameters of last track
0769         // state on this surface
0770         updateStepper(state, stepper, currentState);
0771         ACTS_VERBOSE("Stepping state is updated with filtered parameter:");
0772         ACTS_VERBOSE("-> " << currentState.filtered().transpose()
0773                            << " of track state with tip = "
0774                            << currentState.index());
0775       }
0776 
0777       // Update state and stepper with post material effects
0778       const Result<void> materialPostRes = performMaterialInteraction(
0779           state, stepper, surface,
0780           detail::determineMaterialUpdateMode(state, navigator,
0781                                               MaterialUpdateMode::PostUpdate));
0782       if (!materialPostRes.ok()) {
0783         ACTS_DEBUG("Material interaction failed during post-update: "
0784                    << materialPostRes.error().message());
0785         return materialPostRes.error();
0786       }
0787 
0788       return Result<void>::success();
0789     }
0790 
0791     /// Process new, incompomplete track states and set the filtered state
0792     ///
0793     /// @note will process the given list of new states, run the updater
0794     ///     or share the predicted state for states flagged as outliers
0795     ///     and add them to the list of active branches
0796     ///
0797     /// @tparam propagator_state_t Type of the Propagator state
0798     /// @tparam stepper_t Type of the stepper
0799     /// @param state The mutable propagator state object
0800     /// @param stepper The stepper in use
0801     /// @param newTrackStateList index list of new track states
0802     /// @param result which contains among others the new states, and the list of active branches
0803     /// @return the number of newly added branches or an error
0804     template <typename propagator_state_t, typename stepper_t>
0805     Result<unsigned int> processNewTrackStates(
0806         propagator_state_t& state, const stepper_t& stepper,
0807         const CkfTypes::BranchVector<TrackIndexType>& newTrackStateList,
0808         result_type& result) const {
0809       using PM = TrackStatePropMask;
0810 
0811       unsigned int nBranchesOnSurface = 0;
0812 
0813       auto rootBranch = result.activeBranches.back();
0814 
0815       // Build the new branches by forking the root branch. Reverse the order
0816       // to process the best candidate first
0817       CkfTypes::BranchVector<TrackProxy> newBranches;
0818       for (auto it = newTrackStateList.rbegin(); it != newTrackStateList.rend();
0819            ++it) {
0820         // Keep the root branch as the first branch, make a copy for the
0821         // others
0822         auto shallowCopy = [&] {
0823           auto sc = rootBranch.container().makeTrack();
0824           sc.copyFromShallow(rootBranch);
0825           return sc;
0826         };
0827         auto newBranch =
0828             (it == newTrackStateList.rbegin()) ? rootBranch : shallowCopy();
0829         newBranch.tipIndex() = *it;
0830         newBranches.push_back(newBranch);
0831       }
0832 
0833       // Remove the root branch
0834       result.activeBranches.pop_back();
0835 
0836       // Update and select from the new branches
0837       for (TrackProxy newBranch : newBranches) {
0838         auto trackState = newBranch.outermostTrackState();
0839         TrackStateTypeMap typeFlags = trackState.typeFlags();
0840 
0841         if (typeFlags.isOutlier()) {
0842           // No Kalman update for outlier
0843           // Set the filtered parameter index to be the same with predicted
0844           // parameter
0845           trackState.shareFrom(PM::Predicted, PM::Filtered);
0846           // Increment number of outliers
0847           newBranch.nOutliers()++;
0848         } else if (typeFlags.isMeasurement()) {
0849           // Allocate the filtered parameters right before they are written
0850           trackState.addComponents(PM::Filtered);
0851           // Kalman update
0852           const auto updateRes = kalmanUpdate(state, stepper, trackState);
0853           if (!updateRes.ok()) {
0854             ACTS_DEBUG("Update step failed: " << updateRes.error().message());
0855             return updateRes.error();
0856           }
0857           ACTS_VERBOSE("Appended measurement track state with tip = "
0858                        << newBranch.tipIndex());
0859           // Increment number of measurements
0860           newBranch.nMeasurements()++;
0861           newBranch.nDoF() += trackState.calibratedSize();
0862           newBranch.chi2() += trackState.chi2();
0863         } else {
0864           ACTS_WARNING("Cannot handle this track state flags");
0865           continue;
0866         }
0867 
0868         result.activeBranches.push_back(newBranch);
0869 
0870         BranchStopperResult branchStopperResult =
0871             extensions.branchStopper(newBranch, trackState);
0872 
0873         // Check if need to stop this branch
0874         if (branchStopperResult == BranchStopperResult::Continue) {
0875           // Record the number of branches on surface
0876           nBranchesOnSurface++;
0877         } else {
0878           // Record the number of stopped branches
0879           if (branchStopperResult == BranchStopperResult::StopAndKeep) {
0880             storeLastActiveBranch(result);
0881           }
0882           // Remove the branch from list
0883           result.activeBranches.pop_back();
0884         }
0885       }
0886 
0887       return nBranchesOnSurface;
0888     }
0889 
0890     /// @brief CombinatorialKalmanFilter actor operation: add a hole or material track state
0891     ///
0892     /// @param stateMask The bitmask that instructs which components to allocate
0893     /// @param boundState The bound state on current surface
0894     /// @param result is the mutable result state object and which to leave invalid
0895     /// @param isSensitive The surface is sensitive or passive
0896     /// @param expectMeasurements True if measurements where expected for this surface
0897     /// @param prevTip The index of the previous state
0898     ///
0899     /// @return The tip of added state
0900     TrackIndexType addNonSourcelinkState(TrackStatePropMask stateMask,
0901                                          const BoundState& boundState,
0902                                          result_type& result, bool isSensitive,
0903                                          bool expectMeasurements,
0904                                          TrackIndexType prevTip) const {
0905       using PM = TrackStatePropMask;
0906 
0907       // Add a track state
0908       auto trackStateProxy =
0909           result.trackStates->makeTrackState(stateMask, prevTip);
0910       ACTS_VERBOSE("Create "
0911                    << (isSensitive
0912                            ? (expectMeasurements ? "Hole"
0913                                                  : "noMeasurementExpected")
0914                            : "Material")
0915                    << " output track state #" << trackStateProxy.index()
0916                    << " with mask: " << stateMask);
0917 
0918       const auto& [boundParams, jacobian, pathLength] = boundState;
0919       // Fill the track state
0920       trackStateProxy.predicted() = boundParams.parameters();
0921       trackStateProxy.predictedCovariance() = boundParams.covariance().value();
0922       trackStateProxy.jacobian() = jacobian;
0923       trackStateProxy.pathLength() = pathLength;
0924       // Set the surface
0925       trackStateProxy.setReferenceSurface(
0926           boundParams.referenceSurface().getSharedPtr());
0927 
0928       // Set the track state flags
0929       auto typeFlags = trackStateProxy.typeFlags();
0930       if (trackStateProxy.referenceSurface().hasMaterial()) {
0931         typeFlags.setHasMaterial();
0932       }
0933       typeFlags.setHasParameters();
0934       if (isSensitive) {
0935         if (expectMeasurements) {
0936           typeFlags.setIsHole();
0937         } else {
0938           typeFlags.setHasNoExpectedHit();
0939         }
0940       }
0941 
0942       // Set the filtered parameter index to be the same with predicted
0943       // parameter
0944       trackStateProxy.shareFrom(PM::Predicted, PM::Filtered);
0945 
0946       return trackStateProxy.index();
0947     }
0948 
0949     void storeLastActiveBranch(result_type& result) const {
0950       auto currentBranch = result.activeBranches.back();
0951       TrackIndexType currentTip = currentBranch.tipIndex();
0952 
0953       ACTS_VERBOSE("Storing track "
0954                    << currentBranch.index() << " with tip index " << currentTip
0955                    << ". nMeasurements = " << currentBranch.nMeasurements()
0956                    << ", nOutliers = " << currentBranch.nOutliers()
0957                    << ", nHoles = " << currentBranch.nHoles());
0958 
0959       result.collectedTracks.push_back(currentBranch);
0960     }
0961 
0962     template <typename propagator_state_t, typename stepper_t>
0963     Result<void> performMaterialInteraction(
0964         propagator_state_t& state, const stepper_t& stepper,
0965         const Surface& surface, MaterialUpdateMode updateMode) const {
0966       if (!surface.hasMaterial()) {
0967         return Result<void>::success();
0968       }
0969 
0970       if constexpr (!IsMultiStepper) {
0971         const Result<detail::PointwiseMaterialEffects> materialInteractionRes =
0972             detail::performMaterialInteraction(
0973                 state, stepper, surface, updateMode, NoiseUpdateMode::addNoise,
0974                 multipleScattering, energyLoss, logger());
0975         if (!materialInteractionRes.ok()) {
0976           ACTS_DEBUG("Material interaction failed during reset: "
0977                      << materialInteractionRes.error().message());
0978           return materialInteractionRes.error();
0979         }
0980 
0981         return Result<void>::success();
0982       } else {
0983         if (ACTS_CHECK_BIT(updateMode, MaterialUpdateMode::PostUpdate)) {
0984           brem.betheHeitlerCache->clear();
0985           brem.componentCache->clear();
0986           std::size_t nInvalidBetheHeitler = 0;
0987           double maxPathXOverX0 = 0;
0988 
0989           for (auto cmp : stepper.componentIterable(state.stepping)) {
0990             const auto boundParamsRes = transformFreeToBoundParameters(
0991                 cmp.state().pars, surface, state.options.geoContext);
0992             if (!boundParamsRes.ok()) {
0993               ACTS_DEBUG(
0994                   "Failed to transform free to bound parameters for "
0995                   "Bethe-Heitler approximation: "
0996                   << boundParamsRes.error());
0997               continue;
0998             }
0999 
1000             const BoundTrackParameters bound(
1001                 surface.getSharedPtr(), *boundParamsRes, cmp.state().cov,
1002                 stepper.particleHypothesis(state.stepping));
1003 
1004             detail::Gsf::applyBetheHeitler(
1005                 state.options.geoContext, surface, state.options.direction,
1006                 bound, cmp.weight(), *brem.betheHeitlerApprox,
1007                 *brem.betheHeitlerCache, brem.weightCutoff,
1008                 *brem.componentCache, nInvalidBetheHeitler, maxPathXOverX0,
1009                 logger());
1010           }
1011 
1012           if (brem.componentCache->empty()) {
1013             ACTS_WARNING(
1014                 "No components left after applying energy loss. "
1015                 "Is the weight cutoff "
1016                 << brem.weightCutoff << " too high?");
1017             ACTS_WARNING("Return to propagator without applying energy loss");
1018             return Result<void>::success();
1019           }
1020 
1021           // reduce component number
1022           const auto finalCmpNumber =
1023               std::min(static_cast<std::size_t>(stepper.maxComponents),
1024                        brem.maxComponents);
1025           extensions.mixtureReducer(*brem.componentCache, finalCmpNumber,
1026                                     surface);
1027 
1028           detail::Gsf::removeLowWeightComponents(*brem.componentCache,
1029                                                  brem.weightCutoff);
1030 
1031           detail::Gsf::updateStepper(state, stepper, surface,
1032                                      *brem.componentCache);
1033         }
1034 
1035         detail::Gsf::applyMultipleScattering(state, stepper, surface,
1036                                              updateMode, logger());
1037 
1038         return Result<void>::success();
1039       }
1040     }
1041 
1042     template <typename propagator_state_t, typename stepper_t>
1043     Result<void> kalmanUpdate(propagator_state_t& state,
1044                               const stepper_t& stepper,
1045                               TrackStateProxy& trackState) const {
1046       if constexpr (!IsMultiStepper) {
1047         return extensions.updater(state.geoContext, trackState, *updaterLogger);
1048       } else {
1049         using PrtProjector = detail::Gsf::MultiTrajectoryProjector<
1050             detail::Gsf::StatesType::ePredicted, TrackStateContainerBackend>;
1051         using FltProjector = detail::Gsf::MultiTrajectoryProjector<
1052             detail::Gsf::StatesType::eFiltered, TrackStateContainerBackend>;
1053 
1054         const auto& surface = trackState.referenceSurface();
1055 
1056         auto& temporaryStates = *brem.temporaryStates;
1057         temporaryStates.clear();
1058 
1059         for (auto cmp : stepper.componentIterable(state.stepping)) {
1060           auto& singleState = cmp.singleState(state).stepping;
1061           const auto& singleStepper = cmp.singleStepper(stepper);
1062 
1063           TrackStatePropMask mask = TrackStatePropMask::Predicted |
1064                                     TrackStatePropMask::Jacobian |
1065                                     TrackStatePropMask::Calibrated;
1066           TrackStateProxy trackStateProxy =
1067               temporaryStates.traj.makeTrackState(mask, kTrackIndexInvalid);
1068 
1069           // TODO call calibrator again?
1070 
1071           trackStateProxy.setReferenceSurface(surface.getSharedPtr());
1072           // Bind the transported state to the current surface
1073           auto res = singleStepper.boundState(singleState, surface);
1074           if (!res.ok()) {
1075             ACTS_ERROR("Propagate to surface " << surface.geometryId()
1076                                                << " failed: " << res.error());
1077             return res.error();
1078           }
1079           const auto& [boundParams, jacobian, pathLength] = *res;
1080 
1081           // Fill the track state
1082           trackStateProxy.predicted() = boundParams.parameters();
1083           trackStateProxy.predictedCovariance() = *boundParams.covariance();
1084           trackStateProxy.allocateCalibrated(trackState.calibratedSize());
1085           trackStateProxy.setProjectorSubspaceIndices(
1086               trackState.projectorSubspaceIndices());
1087           trackStateProxy.effectiveCalibrated() =
1088               trackState.effectiveCalibrated();
1089           trackStateProxy.effectiveCalibratedCovariance() =
1090               trackState.effectiveCalibratedCovariance();
1091 
1092           // Allocate the filtered parameters right before they are written
1093           trackStateProxy.addComponents(TrackStatePropMask::Filtered);
1094 
1095           const auto updateRes = extensions.updater(
1096               state.geoContext, trackStateProxy, *updaterLogger);
1097           if (!updateRes.ok()) {
1098             return updateRes.error();
1099           }
1100 
1101           temporaryStates.tips.push_back(trackStateProxy.index());
1102           temporaryStates.weights[trackStateProxy.index()] = cmp.weight();
1103         }
1104 
1105         detail::Gsf::computePosteriorWeights(temporaryStates.traj,
1106                                              temporaryStates.tips,
1107                                              temporaryStates.weights);
1108 
1109         detail::Gsf::normalizeWeights(temporaryStates.tips,
1110                                       [&](auto idx) -> double& {
1111                                         return temporaryStates.weights.at(idx);
1112                                       });
1113 
1114         const auto [prtMean, prtCov] = detail::Gsf::mergeGaussianMixture(
1115             temporaryStates.tips,
1116             PrtProjector{temporaryStates.traj, temporaryStates.weights},
1117             surface, brem.mergeMethod);
1118         trackState.predicted() = prtMean;
1119         trackState.predictedCovariance() = prtCov;
1120 
1121         const auto [fltMean, fltCov] = detail::Gsf::mergeGaussianMixture(
1122             temporaryStates.tips,
1123             FltProjector{temporaryStates.traj, temporaryStates.weights},
1124             surface, brem.mergeMethod);
1125         trackState.filtered() = fltMean;
1126         trackState.filteredCovariance() = fltCov;
1127 
1128         return Result<void>::success();
1129       }
1130     }
1131 
1132     template <typename propagator_state_t, typename stepper_t>
1133     void updateStepper(propagator_state_t& state, const stepper_t& stepper,
1134                        const TrackStateProxy& currentState) const {
1135       if constexpr (!IsMultiStepper) {
1136         stepper.update(state.stepping,
1137                        MultiTrajectoryHelpers::freeFiltered(
1138                            state.options.geoContext, currentState),
1139                        currentState.filtered(),
1140                        currentState.filteredCovariance(),
1141                        currentState.referenceSurface());
1142       } else {
1143         // Conincidentially the temporaryStates correspond to the currentState
1144         // but it seems fragile to rely on that. It would be better to store the
1145         // multi bound parameters on the track state and recover them here. This
1146         // would also behave better in case of branching.
1147         // TODO revisit this
1148         detail::Gsf::updateStepper(state, stepper, *brem.temporaryStates,
1149                                    brem.weightCutoff);
1150       }
1151     }
1152   };
1153 
1154   /// Void path limit reached aborter to replace the default since the path
1155   /// limit is handled in the CKF actor internally.
1156   struct StubPathLimitReached {
1157     double internalLimit{};
1158 
1159     template <typename propagator_state_t, typename stepper_t,
1160               typename navigator_t>
1161     bool checkAbort(propagator_state_t& /*state*/, const stepper_t& /*stepper*/,
1162                     const navigator_t& /*navigator*/,
1163                     const Logger& /*logger*/) const {
1164       return false;
1165     }
1166   };
1167 
1168  public:
1169   /// Options for this filter instantiation, selected by the stepper: the plain
1170   /// @ref CombinatorialKalmanFilterOptions for a single-component stepper, and
1171   /// @ref BremCombinatorialKalmanFilterOptions (bremsstrahlung recovery) for a
1172   /// multi-component stepper.
1173   using Options = std::conditional_t<
1174       IsMultiStepper, BremCombinatorialKalmanFilterOptions<track_container_t>,
1175       CombinatorialKalmanFilterOptions<track_container_t>>;
1176 
1177   /// Combinatorial Kalman Filter implementation, calls the Kalman filter
1178   ///
1179   /// @param initialParameters The initial track parameters
1180   /// @param tfOptions CombinatorialKalmanFilterOptions steering the track
1181   ///                  finding
1182   /// @param trackContainer Track container in which to store the results
1183   /// @param rootBranch The track to be used as the root branch
1184   ///
1185   /// @note The input measurements are given in the form of @c SourceLinks.
1186   ///       It's @c calibrator_t's job to turn them into calibrated measurements
1187   ///       used in the track finding.
1188   ///
1189   /// @return a container of track finding result for all the initial track
1190   /// parameters
1191   Result<std::vector<TrackProxy>> findTracks(
1192       const BoundTrackParameters& initialParameters, const Options& tfOptions,
1193       track_container_t& trackContainer, TrackProxy rootBranch) const {
1194     // Create the ActorList
1195     using CombinatorialKalmanFilterActor = Actor;
1196     using Actors = ActorList<CombinatorialKalmanFilterActor>;
1197 
1198     // Create relevant options for the propagation options
1199     using PropagatorOptions = typename propagator_t::template Options<Actors>;
1200     PropagatorOptions propOptions(tfOptions.geoContext,
1201                                   tfOptions.magFieldContext);
1202 
1203     // Set the trivial propagator options
1204     propOptions.setPlainOptions(tfOptions.propagatorPlainOptions);
1205 
1206     // Catch the actor
1207     auto& combKalmanActor =
1208         propOptions.actorList.template get<CombinatorialKalmanFilterActor>();
1209     combKalmanActor.targetReached.surface = tfOptions.targetSurface;
1210     combKalmanActor.multipleScattering = tfOptions.multipleScattering;
1211     combKalmanActor.energyLoss = tfOptions.energyLoss;
1212     combKalmanActor.skipPrePropagationUpdate =
1213         tfOptions.skipPrePropagationUpdate;
1214     if constexpr (IsMultiStepper) {
1215       // there is no single transport jacobian to fold into the next state
1216       if (!tfOptions.recordMaterialStates) {
1217         throw std::invalid_argument(
1218             "recordMaterialStates cannot be disabled with a multi-component "
1219             "stepper");
1220       }
1221     } else {
1222       combKalmanActor.recordMaterialStates = tfOptions.recordMaterialStates;
1223     }
1224     combKalmanActor.actorLogger = m_actorLogger.get();
1225     combKalmanActor.updaterLogger = m_updaterLogger.get();
1226     combKalmanActor.calibrationContextPtr = &tfOptions.calibrationContext.get();
1227 
1228     // copy delegates to calibrator, updater, branch stopper
1229     combKalmanActor.extensions = tfOptions.extensions;
1230 
1231     // Scratch buffers for the multi-component (bremsstrahlung) path. They must
1232     // outlive the propagation below; they are left untouched by a
1233     // single-component stepper.
1234     TemporaryStates temporaryStates;
1235     std::vector<BetheHeitlerApprox::Component> betheHeitlerCache;
1236     std::vector<GsfComponent> componentCache;
1237 
1238     // The bremsstrahlung parameters only exist on the multi-component options.
1239     if constexpr (IsMultiStepper) {
1240       combKalmanActor.brem.maxComponents = tfOptions.maxComponents;
1241       combKalmanActor.brem.weightCutoff = tfOptions.weightCutoff;
1242       combKalmanActor.brem.mergeMethod = tfOptions.mergeMethod;
1243       combKalmanActor.brem.betheHeitlerApprox =
1244           tfOptions.betheHeitlerApprox.get();
1245 
1246       combKalmanActor.brem.temporaryStates = &temporaryStates;
1247       combKalmanActor.brem.betheHeitlerCache = &betheHeitlerCache;
1248       combKalmanActor.brem.componentCache = &componentCache;
1249     }
1250 
1251     auto propState =
1252         m_propagator
1253             .template makeState<PropagatorOptions, StubPathLimitReached>(
1254                 propOptions);
1255 
1256     if constexpr (!IsMultiStepper) {
1257       const auto initResult =
1258           m_propagator
1259               .template initialize<decltype(propState), StubPathLimitReached>(
1260                   propState, initialParameters);
1261       if (!initResult.ok()) {
1262         ACTS_DEBUG("Propagation initialization failed: " << initResult.error());
1263         return initResult.error();
1264       }
1265     } else {
1266       const MultiComponentBoundTrackParameters multiBoundInitialParameters(
1267           initialParameters.referenceSurface().getSharedPtr(),
1268           initialParameters.parameters(), initialParameters.covariance(),
1269           initialParameters.particleHypothesis());
1270 
1271       const auto initResult =
1272           m_propagator
1273               .template initialize<decltype(propState), StubPathLimitReached>(
1274                   propState, multiBoundInitialParameters);
1275       if (!initResult.ok()) {
1276         ACTS_DEBUG("Propagation initialization failed: " << initResult.error());
1277         return initResult.error();
1278       }
1279     }
1280 
1281     auto& r =
1282         propState
1283             .template get<CombinatorialKalmanFilterResult<track_container_t>>();
1284     r.tracks = &trackContainer;
1285     r.trackStates = &trackContainer.trackStateContainer();
1286 
1287     // make sure the right particle hypothesis is set on the root branch
1288     rootBranch.setParticleHypothesis(initialParameters.particleHypothesis());
1289 
1290     r.activeBranches.push_back(rootBranch);
1291 
1292     auto propagationResult = m_propagator.propagate(propState);
1293 
1294     auto result = m_propagator.makeResult(
1295         std::move(propState), propagationResult, propOptions, false);
1296 
1297     if (!result.ok()) {
1298       ACTS_DEBUG("Propagation failed: " << result.error() << " "
1299                                         << result.error().message()
1300                                         << " with the initial parameters: \n"
1301                                         << initialParameters.parameters());
1302       return result.error();
1303     }
1304 
1305     auto& propRes = *result;
1306 
1307     // Get the result of the CombinatorialKalmanFilter
1308     auto combKalmanResult =
1309         std::move(propRes.template get<
1310                   CombinatorialKalmanFilterResult<track_container_t>>());
1311 
1312     // Check if track finding finished properly
1313     if (!combKalmanResult.finished) {
1314       ACTS_DEBUG("CombinatorialKalmanFilter failed: "
1315                  << "Propagation reached max steps "
1316                  << "with the initial parameters: "
1317                  << initialParameters.parameters().transpose());
1318       return CombinatorialKalmanFilterError::PropagationReachesMaxSteps;
1319     }
1320 
1321     return std::move(combKalmanResult.collectedTracks);
1322   }
1323 
1324   /// Combinatorial Kalman Filter implementation, calls the Kalman filter
1325   ///
1326   /// @param initialParameters The initial track parameters
1327   /// @param tfOptions CombinatorialKalmanFilterOptions steering the track
1328   ///                  finding
1329   /// @param trackContainer Track container in which to store the results
1330   /// @note The input measurements are given in the form of @c SourceLinks.
1331   ///       It's @c calibrator_t's job to turn them into calibrated measurements
1332   ///       used in the track finding.
1333   ///
1334   /// @return a container of track finding result for all the initial track
1335   /// parameters
1336   Result<std::vector<TrackProxy>> findTracks(
1337       const BoundTrackParameters& initialParameters, const Options& tfOptions,
1338       track_container_t& trackContainer) const {
1339     auto rootBranch = trackContainer.makeTrack();
1340     return findTracks(initialParameters, tfOptions, trackContainer, rootBranch);
1341   }
1342 };
1343 
1344 /// @}
1345 
1346 }  // namespace Acts