Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-05 09:51:56

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/Algebra.hpp"
0012 #include "Acts/Definitions/Common.hpp"
0013 #include "Acts/Definitions/TrackParametrization.hpp"
0014 #include "Acts/Definitions/Units.hpp"
0015 #include "Acts/EventData/BoundTrackParameters.hpp"
0016 #include "Acts/EventData/TransformationHelpers.hpp"
0017 #include "Acts/EventData/detail/CorrectedTransformationFreeToBound.hpp"
0018 #include "Acts/Geometry/GeometryContext.hpp"
0019 #include "Acts/MagneticField/MagneticFieldProvider.hpp"
0020 #include "Acts/Propagator/ConstrainedStep.hpp"
0021 #include "Acts/Propagator/EigenStepperError.hpp"
0022 #include "Acts/Propagator/NavigationTarget.hpp"
0023 #include "Acts/Propagator/StepperOptions.hpp"
0024 #include "Acts/Propagator/StepperStatistics.hpp"
0025 #include "Acts/Propagator/detail/SteppingHelper.hpp"
0026 #include "Acts/Surfaces/BoundaryTolerance.hpp"
0027 #include "Acts/Surfaces/CurvilinearSurface.hpp"
0028 #include "Acts/Surfaces/Surface.hpp"
0029 #include "Acts/Surfaces/SurfaceError.hpp"
0030 #include "Acts/Utilities/Intersection.hpp"
0031 #include "Acts/Utilities/MathHelpers.hpp"
0032 #include "Acts/Utilities/Result.hpp"
0033 
0034 #include <algorithm>
0035 #include <array>
0036 #include <cmath>
0037 #include <cstdint>
0038 #include <memory>
0039 #include <optional>
0040 #include <stdexcept>
0041 #include <string>
0042 #include <utility>
0043 
0044 namespace Acts {
0045 
0046 class IVolumeMaterial;
0047 
0048 /// @brief Historical ATLAS Runge-Kutta-Nystroem stepper for performance studies.
0049 /// @ingroup propagation
0050 ///
0051 /// @warning This implementation prioritizes speed and is not intended for
0052 /// production use. Use SympyStepper or EigenStepper for production tracking.
0053 ///
0054 /// Adapted from the ATLAS RungeKuttaPropagator in Athena, with ACTS-specific
0055 /// time propagation and error control. The integration kernel uses
0056 /// hand-expanded scalar expressions and approximate direction normalization.
0057 /// Covariance transport neglects magnetic-field gradients. Volume material and
0058 /// the non-linear free-to-bound correction are not supported.
0059 ///
0060 /// This historical port is maintained independently of Athena.
0061 class AtlasStepper {
0062  public:
0063   /// Type alias for bound track parameters
0064   using BoundParameters = BoundTrackParameters;
0065   /// Type alias for Jacobian matrix
0066   using Jacobian = BoundMatrix;
0067   /// Type alias for covariance matrix
0068   using Covariance = BoundMatrix;
0069 
0070   /// Configuration for constructing an AtlasStepper.
0071   struct Config {
0072     /// Magnetic field provider
0073     std::shared_ptr<const MagneticFieldProvider> bField;
0074   };
0075 
0076   /// Stepper options extending plain stepper settings.
0077   struct Options : public StepperPlainOptions {
0078     /// Constructor from context objects
0079     /// @param gctx Geometry context
0080     /// @param mctx Magnetic field context
0081     Options(const GeometryContext& gctx, const MagneticFieldContext& mctx)
0082         : StepperPlainOptions(gctx, mctx) {}
0083 
0084     /// Set plain options
0085     /// @param options Plain stepper options to set
0086     void setPlainOptions(const StepperPlainOptions& options) {
0087       static_cast<StepperPlainOptions&>(*this) = options;
0088     }
0089   };
0090 
0091   /// @brief Nested State struct for the local caching
0092   struct State {
0093     /// Constructor
0094     ///
0095     /// @param [in] optionsIn The options for the stepper
0096     /// @param [in] fieldCacheIn The magnetic field cache
0097     State(const Options& optionsIn, MagneticFieldProvider::Cache fieldCacheIn)
0098         : options(optionsIn), fieldCache(std::move(fieldCacheIn)) {}
0099 
0100     /// Stepper options for this propagation
0101     Options options;
0102 
0103     /// Particle mass and charge used for curvature and time of flight
0104     ParticleHypothesis particleHypothesis = ParticleHypothesis::pion();
0105 
0106     /// Flag indicating new magnetic field evaluation needed
0107     bool newField = true;
0108     /// Last accepted step's final field sample (an endpoint approximation)
0109     Vector3 field = Vector3::Zero();
0110     /// Storage pattern of pVector
0111     /// @verbatim
0112     ///                   /dL0    /dL1    /dPhi   /the   /dCM   /dT
0113     /// X  ->P[0]  dX /   P[ 8]   P[16]   P[24]   P[32]   P[40]  P[48]
0114     /// Y  ->P[1]  dY /   P[ 9]   P[17]   P[25]   P[33]   P[41]  P[49]
0115     /// Z  ->P[2]  dZ /   P[10]   P[18]   P[26]   P[34]   P[42]  P[50]
0116     /// T  ->P[3]  dT/    P[11]   P[19]   P[27]   P[35]   P[43]  P[51]
0117     /// Ax ->P[4]  dAx/   P[12]   P[20]   P[28]   P[36]   P[44]  P[52]
0118     /// Ay ->P[5]  dAy/   P[13]   P[21]   P[29]   P[37]   P[45]  P[53]
0119     /// Az ->P[6]  dAz/   P[14]   P[22]   P[30]   P[38]   P[46]  P[54]
0120     /// CM ->P[7]  dCM/   P[15]   P[23]   P[31]   P[39]   P[47]  P[55]
0121     /// @endverbatim
0122     /// Here A is the unit direction and CM is q/p.
0123     /// The position and direction entries in the q/p column are scaled by q/p;
0124     /// the time and q/p entries are unscaled. Transport removes this scaling.
0125     /// P[56..58] cache d(direction)/ds; P[59] caches dt/ds.
0126     std::array<double, 60> pVector{};
0127 
0128     /// Whether the cached path derivatives describe the current parameters
0129     bool derivativeReady = false;
0130 
0131     /// Covariance at the anchor, i.e. the frame of the last initialization,
0132     /// transport or update, set if the covariance is transported
0133     std::optional<Covariance> cov;
0134 
0135     /// Accumulated path length during propagation
0136     double pathAccumulated = 0.;
0137 
0138     /// Total number of performed steps
0139     std::size_t nSteps = 0;
0140 
0141     /// Constrained step size for adaptive integration
0142     ConstrainedStep stepSize;
0143 
0144     /// Previous step size for overstep estimation
0145     double previousStepSize = 0.;
0146 
0147     /// It caches the current magnetic field cell and stays (and interpolates)
0148     ///  within as long as this is valid. See step() code for details.
0149     MagneticFieldProvider::Cache fieldCache;
0150 
0151     /// The statistics of the stepper
0152     StepperStatistics statistics;
0153   };
0154 
0155   /// Construct AtlasStepper with magnetic field provider
0156   /// @param bField Shared pointer to magnetic field provider
0157   explicit AtlasStepper(std::shared_ptr<const MagneticFieldProvider> bField)
0158       : m_bField(std::move(bField)) {}
0159 
0160   /// Construct AtlasStepper with configuration
0161   /// @param config Configuration containing magnetic field provider and other settings
0162   explicit AtlasStepper(const Config& config) : m_bField(config.bField) {}
0163 
0164   /// Create stepper state with given options
0165   /// @param options Stepper options including magnetic field context
0166   /// @return Stepper state initialized with options and magnetic field cache
0167   State makeState(const Options& options) const {
0168     State state{options, m_bField->makeCache(options.magFieldContext)};
0169     return state;
0170   }
0171 
0172   /// Initialize stepper state from bound track parameters
0173   /// @param state Stepper state to initialize
0174   /// @param par Bound track parameters containing initial conditions
0175   void initialize(State& state, const BoundParameters& par) const {
0176     initialize(state, par.parameters(), par.covariance(),
0177                par.particleHypothesis(), par.referenceSurface());
0178   }
0179 
0180   /// Initialize stepper state from individual parameters
0181   /// @param state Stepper state to initialize
0182   /// @param boundParams Bound track parameter vector
0183   /// @param cov Optional covariance matrix
0184   /// @param particleHypothesis Particle hypothesis (mass, charge)
0185   /// @param surface Reference surface for bound parameters
0186   void initialize(State& state, const BoundVector& boundParams,
0187                   const std::optional<BoundMatrix>& cov,
0188                   ParticleHypothesis particleHypothesis,
0189                   const Surface& surface) const {
0190     state.particleHypothesis = particleHypothesis;
0191 
0192     state.pathAccumulated = 0;
0193     state.nSteps = 0;
0194     state.stepSize = ConstrainedStep();
0195     state.stepSize.setAccuracy(state.options.initialStepSize);
0196     state.stepSize.setUser(state.options.maxStepSize);
0197     state.previousStepSize = 0;
0198     state.statistics = StepperStatistics();
0199 
0200     const FreeVector freeParams = transformBoundToFreeParameters(
0201         surface, state.options.geoContext, boundParams);
0202     update(state, freeParams.segment<3>(eFreePos0),
0203            freeParams.segment<3>(eFreeDir0), freeParams[eFreeQOverP],
0204            freeParams[eFreeTime]);
0205     state.cov = cov;
0206     resetJacobian(state, surface);
0207   }
0208 
0209   /// Get the field for the stepping
0210   /// It checks first if the access is still within the Cell,
0211   /// and updates the cell if necessary, then it takes the field
0212   /// from the cell
0213   /// @param [in,out] state is the stepper state associated with the track
0214   ///                 the magnetic field cell is used (and potentially updated)
0215   /// @param [in] pos is the field position
0216   /// @return Magnetic field vector at the given position or error
0217   Result<Vector3> getField(State& state, const Vector3& pos) const {
0218     return m_bField->getField(pos, state.fieldCache);
0219   }
0220 
0221   /// Current global geometric curvature d(direction)/ds in inverse length.
0222   /// Unchanged under propagation reversal; reflects current momentum and field.
0223   /// @param state Stepping state; the field cache may be updated
0224   /// @return Curvature vector, or a field lookup error
0225   Result<Vector3> curvature(State& state) const {
0226     return detail::magneticCurvature(*this, state);
0227   }
0228 
0229   /// Get particle position from stepper state
0230   /// @param state Stepper state containing track information
0231   /// @return 3D position vector
0232   Vector3 position(const State& state) const {
0233     return Vector3(state.pVector[0], state.pVector[1], state.pVector[2]);
0234   }
0235 
0236   /// Get particle direction from stepper state
0237   /// @param state Stepper state containing track information
0238   /// @return 3D unit direction vector
0239   Vector3 direction(const State& state) const {
0240     return Vector3(state.pVector[4], state.pVector[5], state.pVector[6]);
0241   }
0242 
0243   /// Get charge over momentum from stepper state
0244   /// @param state Stepper state containing track information
0245   /// @return Charge over momentum (q/p)
0246   double qOverP(const State& state) const { return state.pVector[7]; }
0247 
0248   /// Absolute momentum accessor
0249   ///
0250   /// @param state [in] The stepping state (thread-local cache)
0251   /// @return Absolute momentum magnitude
0252   double absoluteMomentum(const State& state) const {
0253     return particleHypothesis(state).extractMomentum(qOverP(state));
0254   }
0255 
0256   /// Get 3D momentum vector from stepper state
0257   /// @param state Stepper state containing track information
0258   /// @return 3D momentum vector
0259   Vector3 momentum(const State& state) const {
0260     return absoluteMomentum(state) * direction(state);
0261   }
0262 
0263   /// Charge access
0264   ///
0265   /// @param state [in] The stepping state (thread-local cache)
0266   /// @return Electric charge of the particle
0267   double charge(const State& state) const {
0268     return particleHypothesis(state).extractCharge(qOverP(state));
0269   }
0270 
0271   /// Particle hypothesis
0272   ///
0273   /// @param state [in] The stepping state (thread-local cache)
0274   /// @return Reference to the particle hypothesis used
0275   const ParticleHypothesis& particleHypothesis(const State& state) const {
0276     return state.particleHypothesis;
0277   }
0278 
0279   /// Overstep limit
0280   /// @return Overstep limit for this stepper (negative value)
0281   double overstepLimit(const State& /*state*/) const {
0282     return -m_overstepLimit;
0283   }
0284 
0285   /// Time access
0286   /// @param state The stepping state to get time from
0287   /// @return Current time coordinate
0288   double time(const State& state) const { return state.pVector[3]; }
0289 
0290   /// Update surface status
0291   ///
0292   /// This method intersect the provided surface and update the navigation
0293   /// step estimation accordingly (hence it changes the state). It also
0294   /// returns the status of the intersection to trigger onSurface in case
0295   /// the surface is reached.
0296   ///
0297   /// @param [in,out] state The stepping state (thread-local cache)
0298   /// @param [in] surface The surface provided
0299   /// @param [in] index The surface intersection index
0300   /// @param [in] navDir The navigation direction
0301   /// @param [in] boundaryTolerance The boundary check for this status update
0302   /// @param [in] surfaceTolerance Surface tolerance used for intersection
0303   /// @param [in] stype The step size type to be set
0304   /// @param [in] logger Logger instance to use
0305   /// @param curvature Global geometric curvature for the crossing estimate
0306   /// @return IntersectionStatus indicating how the surface was encountered
0307   IntersectionStatus updateSurfaceStatus(
0308       State& state, const Surface& surface, std::uint8_t index,
0309       Direction navDir, const BoundaryTolerance& boundaryTolerance,
0310       double surfaceTolerance, ConstrainedStep::Type stype,
0311       const Logger& logger = getDummyLogger(),
0312       const Vector3& curvature = Vector3::Zero()) const {
0313     return detail::updateSingleSurfaceStatus<AtlasStepper>(
0314         *this, state, surface, index, navDir, boundaryTolerance,
0315         surfaceTolerance, stype, logger, curvature);
0316   }
0317 
0318   /// Update step size
0319   ///
0320   /// It checks the status to the reference surface & updates
0321   /// the step size accordingly
0322   ///
0323   /// @param state [in,out] The stepping state (thread-local cache)
0324   /// @param target [in] The NavigationTarget
0325   /// @param direction [in] The propagation direction
0326   /// @param stype [in] The step size type to be set
0327   void updateStepSize(State& state, const NavigationTarget& target,
0328                       Direction direction, ConstrainedStep::Type stype) const {
0329     static_cast<void>(direction);
0330     double stepSize = target.pathLength();
0331     updateStepSize(state, stepSize, stype);
0332   }
0333 
0334   /// Update step size - explicitly with a double
0335   ///
0336   /// @param [in,out] state The stepping state (thread-local cache)
0337   /// @param [in] stepSize The step size value
0338   /// @param [in] stype The step size type to be set
0339   void updateStepSize(State& state, double stepSize,
0340                       ConstrainedStep::Type stype) const {
0341     state.previousStepSize = state.stepSize.value();
0342     state.stepSize.update(stepSize, stype);
0343   }
0344 
0345   /// Release the Step size
0346   ///
0347   /// @param [in,out] state The stepping state (thread-local cache)
0348   /// @param [in] stype The step size type to be released
0349   void releaseStepSize(State& state, ConstrainedStep::Type stype) const {
0350     state.stepSize.release(stype);
0351   }
0352 
0353   /// Get the step size
0354   ///
0355   /// @param state [in] The stepping state (thread-local cache)
0356   /// @param stype [in] The step size type to be returned
0357   /// @return Current step size for the specified constraint type
0358   double getStepSize(const State& state, ConstrainedStep::Type stype) const {
0359     return state.stepSize.value(stype);
0360   }
0361 
0362   /// Output the Step Size - single component
0363   ///
0364   /// @param [in,out] state The stepping state (thread-local cache)
0365   /// @return String representation of the current step size
0366   std::string outputStepSize(const State& state) const {
0367     return state.stepSize.toString();
0368   }
0369 
0370   /// Get the step size constraints
0371   ///
0372   /// @param state [in] The stepping state (thread-local cache)
0373   /// @return The step size constraints
0374   const ConstrainedStep& stepSize(const State& state) const {
0375     return state.stepSize;
0376   }
0377 
0378   /// Get the stepper statistics
0379   ///
0380   /// @param state [in] The stepping state (thread-local cache)
0381   /// @return The statistics since the last initialization
0382   const StepperStatistics& statistics(const State& state) const {
0383     return state.statistics;
0384   }
0385 
0386   /// Get the path length
0387   ///
0388   /// @param state [in] The stepping state (thread-local cache)
0389   /// @return The path length since the last initialization
0390   double pathLength(const State& state) const { return state.pathAccumulated; }
0391 
0392   /// Check if the state carries a covariance
0393   ///
0394   /// @param state [in] The stepping state (thread-local cache)
0395   /// @return True if the covariance is transported
0396   bool hasCovariance(const State& state) const { return state.cov.has_value(); }
0397 
0398   /// Get the covariance at the anchor
0399   ///
0400   /// The anchor is the frame of the last initialization, transport or update.
0401   ///
0402   /// @param state [in] The stepping state (thread-local cache)
0403   /// @return The covariance at the anchor, or no value if the state does not
0404   ///         carry a covariance
0405   const std::optional<Covariance>& covariance(const State& state) const {
0406     return state.cov;
0407   }
0408 
0409   /// Set the covariance at the anchor
0410   ///
0411   /// The state must already carry a covariance, because the stepper only
0412   /// transports the Jacobian while it has one.
0413   ///
0414   /// @param [in,out] state The stepping state (thread-local cache)
0415   /// @param [in] covariance The new covariance at the anchor
0416   /// @throws std::logic_error if the state does not carry a covariance
0417   void setCovariance(State& state, const Covariance& covariance) const {
0418     if (!state.cov.has_value()) {
0419       throw std::logic_error(
0420           "Cannot set the covariance of a state without a covariance");
0421     }
0422     state.cov = covariance;
0423   }
0424 
0425   /// Get the bound parameters at the current position
0426   ///
0427   /// The parameters carry the covariance at the anchor if the state has one.
0428   ///
0429   /// @param [in] state The stepping state (thread-local cache)
0430   /// @param [in] surface The surface of the parameters
0431   /// @return The bound parameters, or a failure if the position cannot be
0432   ///         expressed on @p surface
0433   Result<BoundParameters> boundParameters(const State& state,
0434                                           const Surface& surface) const {
0435     Vector4 pos4(state.pVector[0], state.pVector[1], state.pVector[2],
0436                  state.pVector[3]);
0437     return BoundTrackParameters::create(
0438         state.options.geoContext, surface.getSharedPtr(), pos4,
0439         direction(state), qOverP(state), state.cov, state.particleHypothesis);
0440   }
0441 
0442   /// @brief If necessary fill additional members needed for
0443   /// transportToCurvilinear
0444   ///
0445   /// Compute path length derivatives in case they have not been computed
0446   /// yet, which is the case if no step has been executed yet.
0447   ///
0448   /// @param [in, out] state The stepping state (thread-local cache)
0449   /// @return true if nothing is missing after this call, false otherwise.
0450   bool prepareCurvilinearState(State& state) const {
0451     return prepareDerivatives(state).ok();
0452   }
0453 
0454   /// Get the curvilinear parameters at the current position
0455   ///
0456   /// The parameters carry the covariance at the anchor if the state has one.
0457   ///
0458   /// @param [in] state The stepping state (thread-local cache)
0459   /// @return The curvilinear parameters
0460   BoundParameters curvilinearParameters(const State& state) const {
0461     Vector4 pos4(state.pVector[0], state.pVector[1], state.pVector[2],
0462                  state.pVector[3]);
0463     return BoundTrackParameters::createCurvilinear(pos4, direction(state),
0464                                                    qOverP(state), state.cov,
0465                                                    state.particleHypothesis);
0466   }
0467 
0468   /// The state update method
0469   ///
0470   /// @param [in,out] state The stepper state for
0471   /// @param [in] parameters The new free track parameters at start
0472   /// @param [in] boundParams Corresponding bound parameters
0473   /// @param [in] covariance The updated covariance matrix
0474   /// @param [in] surface The surface used to update the pVector
0475   void update(State& state, const FreeVector& parameters,
0476               const BoundVector& boundParams, const Covariance& covariance,
0477               const Surface& surface) const {
0478     static_cast<void>(boundParams);
0479     update(state, parameters.segment<3>(eFreePos0),
0480            parameters.segment<3>(eFreeDir0).normalized(),
0481            parameters[eFreeQOverP], parameters[eFreeTime]);
0482     state.cov = covariance;
0483     resetJacobian(state, surface);
0484   }
0485 
0486   /// Method to update momentum, direction and p
0487   ///
0488   /// @param state The state object
0489   /// @param uposition the updated position
0490   /// @param udirection the updated direction
0491   /// @param qop the updated momentum value
0492   /// @param time the update time
0493   void update(State& state, const Vector3& uposition, const Vector3& udirection,
0494               double qop, double time) const {
0495     // update the vector
0496     state.pVector[0] = uposition[0];
0497     state.pVector[1] = uposition[1];
0498     state.pVector[2] = uposition[2];
0499     state.pVector[3] = time;
0500     state.pVector[4] = udirection[0];
0501     state.pVector[5] = udirection[1];
0502     state.pVector[6] = udirection[2];
0503     // The scaled q/p Jacobian column requires a nonzero divisor on transport.
0504     constexpr double minQOverP = 1e-15;
0505     state.pVector[7] =
0506         state.particleHypothesis.absoluteCharge() == 0.
0507             ? qop
0508             : std::copysign(std::max(std::abs(qop), minQOverP), qop);
0509     state.newField = true;
0510     state.derivativeReady = false;
0511   }
0512 
0513   /// Transport the covariance to the curvilinear frame at the current position
0514   ///
0515   /// This anchors the state on the curvilinear frame. Without a covariance
0516   /// the state does not change.
0517   ///
0518   /// @param [in,out] state State of the stepper
0519   /// @return The jacobian from the previous anchor to the curvilinear frame
0520   Jacobian transportToCurvilinear(State& state) const {
0521     if (!state.cov.has_value()) {
0522       return Jacobian::Identity();
0523     }
0524 
0525     const auto surface =
0526         CurvilinearSurface(position(state), direction(state)).surface();
0527     return transportToBound(state, *surface).value();
0528   }
0529 
0530   /// Transport the covariance to a surface at the current position
0531   ///
0532   /// This anchors the state on @p surface. Without a covariance the state
0533   /// does not change. The state must be on @p surface, and it stays unchanged
0534   /// if it is not.
0535   ///
0536   /// @param [in,out] state State of the stepper
0537   /// @param [in] surface The surface to transport the covariance to
0538   /// @return The jacobian from the previous anchor to @p surface, or a failure
0539   ///         if the state is not on @p surface
0540   Result<Jacobian> transportToBound(
0541       State& state, const Surface& surface,
0542       const FreeToBoundCorrection& /*freeToBoundCorrection*/ =
0543           FreeToBoundCorrection(false)) const {
0544     if (!surface.isOnSurface(state.options.geoContext, position(state),
0545                              direction(state), BoundaryTolerance::Infinite())) {
0546       return Result<Jacobian>::failure(
0547           SurfaceError::GlobalPositionNotOnSurface);
0548     }
0549 
0550     if (!state.cov.has_value()) {
0551       return Result<Jacobian>::success(Jacobian::Identity());
0552     }
0553 
0554     auto prepared = prepareDerivatives(state);
0555     if (!prepared.ok()) {
0556       return Result<Jacobian>::failure(prepared.error());
0557     }
0558 
0559     const Vector3 pos = position(state);
0560     const Vector3 dir = direction(state);
0561     BoundToFreeMatrix transportJacobian =
0562         Eigen::Map<const BoundToFreeMatrix>(state.pVector.data() + eFreeSize);
0563     // Undo the kernel's q/p scaling of the position and direction derivatives.
0564     const double inverseQOverP = qOverP(state) == 0. ? 0. : 1. / qOverP(state);
0565     transportJacobian.block<3, 1>(eFreePos0, eBoundQOverP) *= inverseQOverP;
0566     transportJacobian.block<3, 1>(eFreeDir0, eBoundQOverP) *= inverseQOverP;
0567 
0568     FreeVector pathDerivative = FreeVector::Zero();
0569     pathDerivative.segment<3>(eFreePos0) = dir;
0570     pathDerivative[eFreeTime] = state.pVector[59];
0571     pathDerivative.segment<3>(eFreeDir0) =
0572         Eigen::Map<const Vector3>(state.pVector.data() + 56);
0573     const FreeToPathMatrix freeToPath =
0574         surface.freeToPathDerivative(state.options.geoContext, pos, dir);
0575     const FreeToBoundMatrix freeToBound =
0576         surface.freeToBoundJacobian(state.options.geoContext, pos, dir);
0577     const Jacobian jac =
0578         freeToBound *
0579         (transportJacobian + pathDerivative * (freeToPath * transportJacobian));
0580     *state.cov = jac * *state.cov * jac.transpose();
0581 
0582     resetJacobian(state, surface);
0583 
0584     return Result<Jacobian>::success(jac);
0585   }
0586 
0587   /// Perform the actual step on the state
0588   ///
0589   /// @param [in,out] state State of the stepper
0590   /// @param propDir is the direction of propagation
0591   /// @param material is the optional volume material we are stepping through.
0592   ///         Ignored; this stepper only integrates motion in a magnetic field.
0593   /// @return the result of the step
0594   ///
0595   /// @note The state contains the desired step size. It can be negative during
0596   ///       backwards track propagation, and since we're using an adaptive
0597   ///       algorithm, it can be modified by the stepper class during
0598   ///       propagation.
0599   Result<double> step(State& state, Direction propDir,
0600                       const IVolumeMaterial* material) const {
0601     static_cast<void>(material);
0602 
0603     // Keep the scalar notation of the original ATLAS kernel.
0604     auto h = state.stepSize.value() * propDir;
0605     const bool withJacobian = state.cov.has_value();
0606     if (!std::isfinite(h)) {
0607       return EigenStepperError::StepInvalid;
0608     }
0609     // Skip a zero step: it is the identity, and h = 0 raises an FPE in the
0610     // 2 / h below
0611     if (h == 0.) {
0612       return 0.;
0613     }
0614 
0615     double* R = &(state.pVector[0]);  // Coordinates
0616     double* A = &(state.pVector[4]);  // Directions
0617     double* sA = &(state.pVector[56]);
0618     // A neutral particle must not bend in a magnetic field.
0619     const double halfQOverP = charge(state) == 0. ? 0. : 0.5 * qOverP(state);
0620     Vector3 f0, f;
0621 
0622     // if new field is required get it
0623     if (state.newField) {
0624       const Vector3 pos(R[0], R[1], R[2]);
0625       // This is sd.B_first in EigenStepper
0626       auto fRes = getField(state, pos);
0627       if (!fRes.ok()) {
0628         return fRes.error();
0629       }
0630       f0 = *fRes;
0631     } else {
0632       f0 = state.field;
0633     }
0634 
0635     const auto calcStepSizeScaling = [&](const double errorEstimate) -> double {
0636       // For details about these values see ATL-SOFT-PUB-2009-001
0637       constexpr double lower = 0.25;
0638       constexpr double upper = 4.0;
0639       if (errorEstimate == 0.) {
0640         return upper;
0641       }
0642       // Fourth-order controller; two square roots avoid a general pow call.
0643       double x =
0644           std::sqrt(std::sqrt(state.options.stepTolerance / errorEstimate));
0645 
0646       return std::clamp(x, lower, upper);
0647     };
0648 
0649     const auto isErrorTolerable = [&](const double errorEstimate) {
0650       // For details about these values see ATL-SOFT-PUB-2009-001
0651       constexpr double marginFactor = 4.0;
0652 
0653       return errorEstimate <= marginFactor * state.options.stepTolerance;
0654     };
0655 
0656     double errorEstimate = 0;
0657     double initialStepSize = h;
0658 
0659     std::uint32_t nStepTrials = 0;
0660     while (true) {
0661       ++state.statistics.nAttemptedSteps;
0662 
0663       // PS2 is h/(2*momentum) in EigenStepper
0664       double S3 = (1. / 3.) * h, S4 = .25 * h, PS2 = halfQOverP * h;
0665 
0666       // First point
0667       //
0668       // H0 is (h/(2*momentum) * sd.B_first) in EigenStepper
0669       double H0[3] = {f0[0] * PS2, f0[1] * PS2, f0[2] * PS2};
0670       // { A0, B0, C0 } is (h/2 * sd.k1) in EigenStepper
0671       double A0 = A[1] * H0[2] - A[2] * H0[1];
0672       double B0 = A[2] * H0[0] - A[0] * H0[2];
0673       double C0 = A[0] * H0[1] - A[1] * H0[0];
0674       // { A2, B2, C2 } is (h/2 * sd.k1 + direction) in EigenStepper
0675       double A2 = A0 + A[0];
0676       double B2 = B0 + A[1];
0677       double C2 = C0 + A[2];
0678       // { A1, B1, C1 } is (h/2 * sd.k1 + 2*direction) in EigenStepper
0679       double A1 = A2 + A[0];
0680       double B1 = B2 + A[1];
0681       double C1 = C2 + A[2];
0682 
0683       // Second point
0684       const Vector3 middlePosition(R[0] + A1 * S4, R[1] + B1 * S4,
0685                                    R[2] + C1 * S4);
0686       // This is sd.B_middle in EigenStepper
0687       auto middleFieldResult = getField(state, middlePosition);
0688       if (!middleFieldResult.ok()) {
0689         return middleFieldResult.error();
0690       }
0691       f = *middleFieldResult;
0692 
0693       // H1 is (h/(2*momentum) * sd.B_middle) in EigenStepper
0694       double H1[3] = {f[0] * PS2, f[1] * PS2, f[2] * PS2};
0695       // { A3, B3, C3 } is (direction + h/2 * sd.k2) in EigenStepper
0696       double A3 = (A[0] + B2 * H1[2]) - C2 * H1[1];
0697       double B3 = (A[1] + C2 * H1[0]) - A2 * H1[2];
0698       double C3 = (A[2] + A2 * H1[1]) - B2 * H1[0];
0699       // { A4, B4, C4 } is (direction + h/2 * sd.k3) in EigenStepper
0700       double A4 = (A[0] + B3 * H1[2]) - C3 * H1[1];
0701       double B4 = (A[1] + C3 * H1[0]) - A3 * H1[2];
0702       double C4 = (A[2] + A3 * H1[1]) - B3 * H1[0];
0703       // { A5, B5, C5 } is (direction + h * sd.k3) in EigenStepper
0704       double A5 = 2. * A4 - A[0];
0705       double B5 = 2. * B4 - A[1];
0706       double C5 = 2. * C4 - A[2];
0707 
0708       // Last point
0709       const Vector3 endPosition(R[0] + h * A4, R[1] + h * B4, R[2] + h * C4);
0710       // This is sd.B_last in Eigen stepper
0711       auto endFieldResult = getField(state, endPosition);
0712       if (!endFieldResult.ok()) {
0713         return endFieldResult.error();
0714       }
0715       f = *endFieldResult;
0716 
0717       // H2 is (h/(2*momentum) * sd.B_last) in EigenStepper
0718       double H2[3] = {f[0] * PS2, f[1] * PS2, f[2] * PS2};
0719       // { A6, B6, C6 } is (h/2 * sd.k4) in EigenStepper
0720       double A6 = B5 * H2[2] - C5 * H2[1];
0721       double B6 = C5 * H2[0] - A5 * H2[2];
0722       double C6 = A5 * H2[1] - B5 * H2[0];
0723 
0724       // Test approximation quality on give step and possible step reduction
0725       //
0726       // This is (h2 * (sd.k1 - sd.k2 - sd.k3 + sd.k4).template lpNorm<1>())
0727       // in EigenStepper
0728       errorEstimate =
0729           2. * std::abs(h) *
0730           (std::abs((A1 + A6) - (A3 + A4)) + std::abs((B1 + B6) - (B3 + B4)) +
0731            std::abs((C1 + C6) - (C3 + C4)));
0732       if (!std::isfinite(errorEstimate)) {
0733         return EigenStepperError::StepInvalid;
0734       }
0735       if (!isErrorTolerable(errorEstimate)) {
0736         ++state.statistics.nRejectedSteps;
0737         const double stepSizeScaling = calcStepSizeScaling(errorEstimate);
0738         h *= stepSizeScaling;
0739         // neutralize the sign of h again
0740         state.stepSize.setAccuracy(h * propDir);
0741         if (h == 0. || std::abs(h) < std::abs(state.options.stepSizeCutOff)) {
0742           return EigenStepperError::StepSizeStalled;
0743         }
0744         if (++nStepTrials > state.options.maxRungeKuttaStepTrials) {
0745           return EigenStepperError::StepSizeAdjustmentFailed;
0746         }
0747         continue;
0748       }
0749 
0750       // Parameters calculation
0751       //
0752       double A00 = A[0], A11 = A[1], A22 = A[2];
0753 
0754       A[0] = 2. * A3 + (A0 + A5 + A6);
0755       A[1] = 2. * B3 + (B0 + B5 + B6);
0756       A[2] = 2. * C3 + (C0 + C5 + C6);
0757 
0758       double D = (A[0] * A[0] + A[1] * A[1]) + (A[2] * A[2] - 9.);
0759       double Sl = 2. / h;
0760       D = (1. / 3.) - ((1. / 648.) * D) * (12. - D);
0761 
0762       R[0] += (A2 + A3 + A4) * S3;
0763       R[1] += (B2 + B3 + B4) * S3;
0764       R[2] += (C2 + C3 + C4) * S3;
0765       A[0] *= D;
0766       A[1] *= D;
0767       A[2] *= D;
0768       sA[0] = A6 * Sl;
0769       sA[1] = B6 * Sl;
0770       sA[2] = C6 * Sl;
0771 
0772       double mass = particleHypothesis(state).mass();
0773       double momentum = absoluteMomentum(state);
0774 
0775       // Evaluate the time propagation
0776       const double mOverP = mass / momentum;
0777       double dtds = fastHypot(1., mOverP);
0778       state.pVector[3] += h * dtds;
0779       state.pVector[59] = dtds;
0780       state.field = f;
0781       state.newField = false;
0782       state.derivativeReady = true;
0783 
0784       if (withJacobian) {
0785         // d(t)/d(q/p) = h m^2 (q/p) / (q^2 dt/ds), with the q^2 folded into p
0786         // via p = |q| / |q/p|.
0787         double dtdl = particleHypothesis(state).hasMomentumHypothesis()
0788                           ? 0.
0789                           : h * mOverP * mOverP / (qOverP(state) * dtds);
0790         state.pVector[43] += dtdl;
0791 
0792         // Jacobian calculation
0793         //
0794         double* d2A = &state.pVector[28];
0795         double* d3A = &state.pVector[36];
0796         double* d4A = &state.pVector[44];
0797         double d2A0 = H0[2] * d2A[1] - H0[1] * d2A[2];
0798         double d2B0 = H0[0] * d2A[2] - H0[2] * d2A[0];
0799         double d2C0 = H0[1] * d2A[0] - H0[0] * d2A[1];
0800         double d3A0 = H0[2] * d3A[1] - H0[1] * d3A[2];
0801         double d3B0 = H0[0] * d3A[2] - H0[2] * d3A[0];
0802         double d3C0 = H0[1] * d3A[0] - H0[0] * d3A[1];
0803         double d4A0 = (A0 + H0[2] * d4A[1]) - H0[1] * d4A[2];
0804         double d4B0 = (B0 + H0[0] * d4A[2]) - H0[2] * d4A[0];
0805         double d4C0 = (C0 + H0[1] * d4A[0]) - H0[0] * d4A[1];
0806         double d2A2 = d2A0 + d2A[0];
0807         double d2B2 = d2B0 + d2A[1];
0808         double d2C2 = d2C0 + d2A[2];
0809         double d3A2 = d3A0 + d3A[0];
0810         double d3B2 = d3B0 + d3A[1];
0811         double d3C2 = d3C0 + d3A[2];
0812         double d4A2 = d4A0 + d4A[0];
0813         double d4B2 = d4B0 + d4A[1];
0814         double d4C2 = d4C0 + d4A[2];
0815         double d0 = d4A[0] - A00;
0816         double d1 = d4A[1] - A11;
0817         double d2 = d4A[2] - A22;
0818         double d2A3 = (d2A[0] + d2B2 * H1[2]) - d2C2 * H1[1];
0819         double d2B3 = (d2A[1] + d2C2 * H1[0]) - d2A2 * H1[2];
0820         double d2C3 = (d2A[2] + d2A2 * H1[1]) - d2B2 * H1[0];
0821         double d3A3 = (d3A[0] + d3B2 * H1[2]) - d3C2 * H1[1];
0822         double d3B3 = (d3A[1] + d3C2 * H1[0]) - d3A2 * H1[2];
0823         double d3C3 = (d3A[2] + d3A2 * H1[1]) - d3B2 * H1[0];
0824         double d4A3 = ((A3 + d0) + d4B2 * H1[2]) - d4C2 * H1[1];
0825         double d4B3 = ((B3 + d1) + d4C2 * H1[0]) - d4A2 * H1[2];
0826         double d4C3 = ((C3 + d2) + d4A2 * H1[1]) - d4B2 * H1[0];
0827         double d2A4 = (d2A[0] + d2B3 * H1[2]) - d2C3 * H1[1];
0828         double d2B4 = (d2A[1] + d2C3 * H1[0]) - d2A3 * H1[2];
0829         double d2C4 = (d2A[2] + d2A3 * H1[1]) - d2B3 * H1[0];
0830         double d3A4 = (d3A[0] + d3B3 * H1[2]) - d3C3 * H1[1];
0831         double d3B4 = (d3A[1] + d3C3 * H1[0]) - d3A3 * H1[2];
0832         double d3C4 = (d3A[2] + d3A3 * H1[1]) - d3B3 * H1[0];
0833         double d4A4 = ((A4 + d0) + d4B3 * H1[2]) - d4C3 * H1[1];
0834         double d4B4 = ((B4 + d1) + d4C3 * H1[0]) - d4A3 * H1[2];
0835         double d4C4 = ((C4 + d2) + d4A3 * H1[1]) - d4B3 * H1[0];
0836         double d2A5 = 2. * d2A4 - d2A[0];
0837         double d2B5 = 2. * d2B4 - d2A[1];
0838         double d2C5 = 2. * d2C4 - d2A[2];
0839         double d3A5 = 2. * d3A4 - d3A[0];
0840         double d3B5 = 2. * d3B4 - d3A[1];
0841         double d3C5 = 2. * d3C4 - d3A[2];
0842         double d4A5 = 2. * d4A4 - d4A[0];
0843         double d4B5 = 2. * d4B4 - d4A[1];
0844         double d4C5 = 2. * d4C4 - d4A[2];
0845         double d2A6 = d2B5 * H2[2] - d2C5 * H2[1];
0846         double d2B6 = d2C5 * H2[0] - d2A5 * H2[2];
0847         double d2C6 = d2A5 * H2[1] - d2B5 * H2[0];
0848         double d3A6 = d3B5 * H2[2] - d3C5 * H2[1];
0849         double d3B6 = d3C5 * H2[0] - d3A5 * H2[2];
0850         double d3C6 = d3A5 * H2[1] - d3B5 * H2[0];
0851         double d4A6 = d4B5 * H2[2] - d4C5 * H2[1];
0852         double d4B6 = d4C5 * H2[0] - d4A5 * H2[2];
0853         double d4C6 = d4A5 * H2[1] - d4B5 * H2[0];
0854 
0855         double* dR = &state.pVector[24];
0856         dR[0] += (d2A2 + d2A3 + d2A4) * S3;
0857         dR[1] += (d2B2 + d2B3 + d2B4) * S3;
0858         dR[2] += (d2C2 + d2C3 + d2C4) * S3;
0859         d2A[0] = ((d2A0 + 2. * d2A3) + (d2A5 + d2A6)) * (1. / 3.);
0860         d2A[1] = ((d2B0 + 2. * d2B3) + (d2B5 + d2B6)) * (1. / 3.);
0861         d2A[2] = ((d2C0 + 2. * d2C3) + (d2C5 + d2C6)) * (1. / 3.);
0862 
0863         dR = &state.pVector[32];
0864         dR[0] += (d3A2 + d3A3 + d3A4) * S3;
0865         dR[1] += (d3B2 + d3B3 + d3B4) * S3;
0866         dR[2] += (d3C2 + d3C3 + d3C4) * S3;
0867         d3A[0] = ((d3A0 + 2. * d3A3) + (d3A5 + d3A6)) * (1. / 3.);
0868         d3A[1] = ((d3B0 + 2. * d3B3) + (d3B5 + d3B6)) * (1. / 3.);
0869         d3A[2] = ((d3C0 + 2. * d3C3) + (d3C5 + d3C6)) * (1. / 3.);
0870 
0871         dR = &state.pVector[40];
0872         dR[0] += (d4A2 + d4A3 + d4A4) * S3;
0873         dR[1] += (d4B2 + d4B3 + d4B4) * S3;
0874         dR[2] += (d4C2 + d4C3 + d4C4) * S3;
0875         d4A[0] = ((d4A0 + 2. * d4A3) + (d4A5 + d4A6 + A6)) * (1. / 3.);
0876         d4A[1] = ((d4B0 + 2. * d4B3) + (d4B5 + d4B6 + B6)) * (1. / 3.);
0877         d4A[2] = ((d4C0 + 2. * d4C3) + (d4C5 + d4C6 + C6)) * (1. / 3.);
0878       }
0879 
0880       break;
0881     }
0882 
0883     state.pathAccumulated += h;
0884     ++state.nSteps;
0885 
0886     ++state.statistics.nSuccessfulSteps;
0887     if (propDir != Direction::fromScalarZeroAsPositive(initialStepSize)) {
0888       ++state.statistics.nReverseSteps;
0889     }
0890     state.statistics.pathLength += h;
0891     state.statistics.absolutePathLength += std::abs(h);
0892 
0893     const double stepSizeScaling = calcStepSizeScaling(errorEstimate);
0894     const double nextAccuracy = std::abs(h * stepSizeScaling);
0895     const double previousAccuracy = std::abs(state.stepSize.accuracy());
0896     const double initialStepLength = std::abs(initialStepSize);
0897     if (nextAccuracy < initialStepLength || nextAccuracy > previousAccuracy) {
0898       state.stepSize.setAccuracy(nextAccuracy);
0899     }
0900 
0901     return h;
0902   }
0903 
0904  private:
0905   /// Initialize the bound-to-free Jacobian at a new covariance anchor.
0906   void resetJacobian(State& state, const Surface& surface) const {
0907     std::ranges::fill(state.pVector.begin() + eFreeSize, state.pVector.end(),
0908                       0.);
0909     if (state.cov.has_value()) {
0910       Eigen::Map<BoundToFreeMatrix>(state.pVector.data() + eFreeSize) =
0911           surface.boundToFreeJacobian(state.options.geoContext, position(state),
0912                                       direction(state));
0913     }
0914     state.derivativeReady = false;
0915   }
0916 
0917   /// Prepare path corrections also before the first step or after an update.
0918   Result<void> prepareDerivatives(State& state) const {
0919     if (state.derivativeReady) {
0920       return Result<void>::success();
0921     }
0922     auto field = getField(state, position(state));
0923     if (!field.ok()) {
0924       return field.error();
0925     }
0926     const double curvature = charge(state) == 0. ? 0. : qOverP(state);
0927     Eigen::Map<Vector3>(state.pVector.data() + 56) =
0928         curvature * direction(state).cross(*field);
0929     const double mOverP =
0930         particleHypothesis(state).mass() / absoluteMomentum(state);
0931     state.pVector[59] = fastHypot(1., mOverP);
0932     state.derivativeReady = true;
0933     return Result<void>::success();
0934   }
0935 
0936   std::shared_ptr<const MagneticFieldProvider> m_bField;
0937 
0938   /// Overstep limit: could/should be dynamic
0939   double m_overstepLimit = 100 * UnitConstants::um;
0940 };
0941 
0942 }  // namespace Acts