Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-16 10:10:23

0001 //------------------------------- -*- C++ -*- -------------------------------//
0002 // Copyright Celeritas contributors: see top-level COPYRIGHT file for details
0003 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
0004 //---------------------------------------------------------------------------//
0005 //! \file celeritas/field/FieldPropagator.hh
0006 //---------------------------------------------------------------------------//
0007 #pragma once
0008 
0009 #include "corecel/Macros.hh"
0010 #include "corecel/Types.hh"
0011 #include "corecel/math/Algorithms.hh"
0012 #include "corecel/math/ArrayOperators.hh"
0013 #include "corecel/math/NumericLimits.hh"
0014 #include "geocel/Types.hh"
0015 #include "celeritas/geo/CoreGeoTrackView.hh"
0016 #include "celeritas/phys/ParticleTrackView.hh"
0017 
0018 #include "Types.hh"
0019 
0020 #include "detail/FieldUtils.hh"
0021 
0022 namespace celeritas
0023 {
0024 //---------------------------------------------------------------------------//
0025 /*!
0026  * Propagate a charged particle in a field.
0027  *
0028  * For a given initial state (position, momentum), it propagates a charged
0029  * particle along a curved trajectory up to an interaction length proposed by
0030  * a chosen physics process for the step, possibly integrating sub-steps by
0031  * an adaptive step control with a required accuracy of tracking in a
0032  * field. It updates the final state (position, momentum, boundary) along with
0033  * the step actually taken.  If the final position is outside the current
0034  * volume, it returns a geometry limited step and the state at the
0035  * intersection between the curve trajectory and the first volume boundary
0036  * using an iterative step control method within a tolerance error imposed on
0037  * the closest distance between two positions by the field stepper and the
0038  * linear projection to the volume boundary.
0039  *
0040  * \note This follows similar methods to Geant4's G4PropagatorInField class.
0041  */
0042 template<class SubstepperT, class GTV>
0043 class FieldPropagator
0044 {
0045   public:
0046     //!@{
0047     //! \name Type aliases
0048     using result_type = Propagation;
0049     //!@}
0050 
0051   public:
0052     // Construct with shared parameters and the field driver
0053     inline CELER_FUNCTION FieldPropagator(
0054         SubstepperT&& advance, ParticleTrackView const& particle, GTV&& geo);
0055 
0056     // Move track up to a user-provided distance, or to the next boundary
0057     inline CELER_FUNCTION result_type operator()(real_type dist);
0058 
0059   private:
0060     //! Limit on substeps
0061     inline CELER_FUNCTION short int max_substeps() const;
0062 
0063     // Intersection tolerance
0064     inline CELER_FUNCTION real_type delta_intersection() const;
0065 
0066     // Distance to bump or to consider a "zero" movement
0067     inline CELER_FUNCTION real_type bump_distance() const;
0068 
0069     // Smallest allowable inner loop distance to take
0070     inline CELER_FUNCTION real_type minimum_substep() const;
0071 
0072   private:
0073     //// DATA ////
0074 
0075     SubstepperT advance_;
0076     GTV geo_;
0077     OdeState state_;
0078 };
0079 
0080 //---------------------------------------------------------------------------//
0081 // DEDUCTION GUIDES
0082 //---------------------------------------------------------------------------//
0083 template<class SubstepperT, class GTV>
0084 CELER_CTAD_FUNCTION FieldPropagator(
0085     SubstepperT&&, ParticleTrackView const&, GTV&&)
0086     -> FieldPropagator<SubstepperT, GTV>;
0087 
0088 //---------------------------------------------------------------------------//
0089 // INLINE DEFINITIONS
0090 //---------------------------------------------------------------------------//
0091 /*!
0092  * Construct with shared field parameters and the field driver.
0093  */
0094 template<class SubstepperT, class GTV>
0095 CELER_FUNCTION FieldPropagator<SubstepperT, GTV>::FieldPropagator(
0096     SubstepperT&& advance, ParticleTrackView const& particle, GTV&& geo)
0097     : advance_(::celeritas::forward<SubstepperT>(advance))
0098     , geo_(::celeritas::forward<GTV>(geo))
0099 {
0100     using MomentumUnits = OdeState::MomentumUnits;
0101 
0102     state_.pos = geo_.pos();
0103     state_.mom = value_as<MomentumUnits>(particle.momentum()) * geo_.dir();
0104 }
0105 
0106 //---------------------------------------------------------------------------//
0107 /*!
0108  * Propagate a charged particle in a field.
0109  *
0110  * It utilises a field driver (based on an adaptive step control to limit the
0111  * length traveled based on the magnetic field behavior and geometric
0112  * tolerances) to track a charged particle along a curved trajectory for a
0113  * given step length within a required accuracy or intersects
0114  * with a new volume (geometry limited step).
0115  *
0116  * The position of the internal OdeState `state_` should be consistent with the
0117  * geometry `geo_`'s position, but the geometry's direction will be a series
0118  * of "trial" directions that are the chords between the start and end points
0119  * of a curved substep through the field. At the end of the propagation step,
0120  * the geometry state's direction is updated based on the actual value of the
0121  * calculated momentum.
0122  *
0123  * Caveats:
0124  * - The physical (geometry track state) position may deviate from the exact
0125  *   curved propagation position up to a driver-based tolerance at every
0126  *   boundary crossing. The momentum will always be conserved, though.
0127  * - In some unusual cases (e.g. a very small caller-requested step, or an
0128  *   unusual accumulation in the driver's substeps) the distance returned may
0129  *   be slightly higher (again, up to a driver-based tolerance) than the
0130  *   physical distance travelled.
0131  */
0132 template<class SubstepperT, class GTV>
0133 CELER_FUNCTION auto FieldPropagator<SubstepperT, GTV>::operator()(
0134     real_type step) -> result_type
0135 {
0136     CELER_EXPECT(step > 0);
0137     result_type result;
0138     result.boundary = geo_.is_on_boundary();
0139     result.distance = 0;
0140 
0141     // Break the curved steps into substeps as determined by the driver *and*
0142     // by the proximity of geometry boundaries. Test for intersection with the
0143     // geometry boundary in each substep. This loop is guaranteed to converge
0144     // since the trial step always decreases *or* the actual position advances.
0145     real_type remaining = step;
0146     auto remaining_substeps = this->max_substeps();
0147     do
0148     {
0149         CELER_ASSERT(soft_zero(distance(state_.pos, geo_.pos())));
0150         CELER_ASSERT(result.boundary == geo_.is_on_boundary());
0151 
0152         // Advance up to (but probably less than) the remaining step length
0153         Substep substep = advance_(remaining, state_);
0154         CELER_ASSERT(substep.length > 0 && substep.length <= remaining);
0155 
0156         // Check whether the chord for this sub-step intersects a boundary
0157         auto chord = detail::make_chord(state_.pos, substep.state.pos);
0158 
0159         // Do a detailed boundary check from the start position toward
0160         // the substep end point.
0161         // Travel to the end of the chord, plus a little extra.
0162         if (chord.length >= this->minimum_substep())
0163         {
0164             // Only update the direction if the chord length is nontrivial.
0165             // This is usually the case but might be skipped in two cases:
0166             // - if the initial step is very small compared to the
0167             //   magnitude of the position (which can result in a zero length
0168             //   for the chord and NaNs for the direction)
0169             // - in a high-curvature track where the remaining distance is just
0170             //   barely above the remaining minimum step (in which case our
0171             //   boundary test does lose some accuracy)
0172             geo_.set_dir(chord.dir);
0173         }
0174         auto linear_step
0175             = geo_.find_next_step(chord.length + this->delta_intersection());
0176 
0177         // Scale the effective substep length to travel by the fraction along
0178         // the chord to the boundary. This value can be slightly larger than 1
0179         // because we search up a little past the endpoint (thanks to the delta
0180         // intersection).
0181         real_type const update_length = substep.length * linear_step.distance
0182                                         / chord.length;
0183 
0184         if (!linear_step.boundary)
0185         {
0186             // No boundary intersection along the chord: accept substep
0187             // movement inside the current volume and reset the remaining
0188             // distance so we can continue toward the next boundary or end of
0189             // caller-requested step. Reset the boundary flag to "false" only
0190             // in the unlikely case that we successfully shortened the substep
0191             // on a reentrant boundary crossing below.
0192             state_ = substep.state;
0193             result.boundary = false;
0194             result.distance += substep.length;
0195             remaining = step - result.distance;
0196             geo_.move_internal(state_.pos);
0197             --remaining_substeps;
0198         }
0199         else if (CELER_UNLIKELY(
0200                      result.boundary
0201                      && ((linear_step.distance) < this->bump_distance())))
0202         {
0203             // Likely heading back into the old volume when starting on a
0204             // surface (this can happen when tracking through a volume at a
0205             // near tangent). Reduce substep size and try again.
0206             // TODO: this condition is triggered in ORANGE when on a reentrant
0207             // boundary
0208             remaining = substep.length / 2;
0209         }
0210         else if (update_length <= this->minimum_substep()
0211                  || detail::is_intercept_close(state_.pos,
0212                                                chord.dir,
0213                                                linear_step.distance,
0214                                                substep.state.pos,
0215                                                this->delta_intersection())
0216                  || chord.length == 0)
0217         {
0218             // We're close enough to the boundary that the next trial step
0219             // would be less than the driver's minimum step.
0220             // *OR*
0221             // The straight-line intersection point is a distance less than
0222             // `delta_intersection` from the substep's end position.
0223             // Commit the proposed state's momentum, use the
0224             // post-boundary-crossing track position for consistency, and
0225             // conservatively reduce the *reported* traveled distance to avoid
0226             // coincident boundary crossings.
0227 
0228             // Only cross the boundary if the intersect point is less
0229             // than or exactly on the boundary, or if the crossing
0230             // doesn't put us past the end of the step
0231             result.boundary = (linear_step.distance <= chord.length
0232                                || result.distance + update_length <= step
0233                                || chord.length == 0);
0234 
0235             if (!result.boundary)
0236             {
0237                 // Don't move to the boundary, but instead move to the end of
0238                 // the substep. This should result in basically the same effect
0239                 // as "!linear_step.boundary" above.
0240                 state_.pos = substep.state.pos;
0241                 geo_.move_internal(substep.state.pos);
0242             }
0243 
0244             // The update length can be slightly greater than the substep due
0245             // to the extra delta_intersection boost when searching. The
0246             // substep itself can be more than the requested step.
0247             result.distance += celeritas::min(update_length, substep.length);
0248             state_.mom = substep.state.mom;
0249             remaining = 0;
0250         }
0251         else
0252         {
0253             // The straight-line intercept is too far from substep's end state.
0254             // Decrease the allowed substep (curved path distance) by the
0255             // fraction along the chord, and retry the driver step.
0256             remaining = update_length;
0257         }
0258     } while (remaining > this->minimum_substep() && remaining_substeps > 0);
0259 
0260     if (remaining_substeps == 0 && result.distance < step)
0261     {
0262         // Flag track as looping if the max number of substeps was reached
0263         // without hitting a boundary or moving the full step length
0264         result.looping = true;
0265     }
0266     else if (result.distance > 0)
0267     {
0268         if (result.boundary)
0269         {
0270             // We moved to a new boundary. Update the position to reflect the
0271             // geometry's state (and possibly "bump" the ODE state's position
0272             // because of the tolerance in the intercept checks above).
0273             geo_.move_to_boundary();
0274             state_.pos = geo_.pos();
0275         }
0276         else if (CELER_UNLIKELY(result.distance < step))
0277         {
0278             // Even though the track traveled the full step length, the
0279             // distance might be slightly less than the step due to roundoff
0280             // error. Reset the distance so the track's action isn't
0281             // erroneously set as propagation-limited.
0282             CELER_ASSERT(soft_equal(result.distance, step));
0283             result.distance = step;
0284         }
0285     }
0286 
0287     // Even though the along-substep movement was through chord lengths,
0288     // conserve momentum through the field change by updating the final
0289     // *direction* based on the state's momentum.
0290     Real3 dir = make_unit_vector(state_.mom);
0291     geo_.set_dir(dir);
0292 
0293     if (CELER_UNLIKELY(result.distance == 0))
0294     {
0295         // We failed to move at all, which means we hit a boundary no matter
0296         // what step length we took, which means we're stuck.
0297         // Using the just-reapplied direction, hope that we're pointing deeper
0298         // into the current volume and bump the particle.
0299         // TODO: move this into a higher-level failure/bump mechanic
0300         result.distance = celeritas::min(this->bump_distance(), step);
0301         result.boundary = false;
0302         axpy(result.distance, dir, &state_.pos);
0303         geo_.move_internal(state_.pos);
0304     }
0305     else
0306     {
0307         CELER_ENSURE(result.boundary == geo_.is_on_boundary());
0308     }
0309 
0310     // Due to accumulation errors from multiple substeps or chord-finding
0311     // within the driver, the distance may be very slightly beyond the
0312     // requested step.
0313     CELER_ENSURE(
0314         (result.distance > 0 || geo_.failed())
0315         && (result.distance <= step || soft_equal(result.distance, step)));
0316     return result;
0317 }
0318 
0319 //---------------------------------------------------------------------------//
0320 /*!
0321  * Distance close enough to a boundary to mark as being on the boundary.
0322  *
0323  * TODO: change delta intersection from property in FieldDriverOptions to
0324  * another FieldPropagatorOptions
0325  */
0326 template<class SubstepperT, class GTV>
0327 CELER_FUNCTION real_type
0328 FieldPropagator<SubstepperT, GTV>::delta_intersection() const
0329 {
0330     return advance_.delta_intersection();
0331 }
0332 
0333 //---------------------------------------------------------------------------//
0334 /*!
0335  * Maximum number of substeps.
0336  */
0337 template<class SubstepperT, class GTV>
0338 CELER_FUNCTION short int FieldPropagator<SubstepperT, GTV>::max_substeps() const
0339 {
0340     return advance_.max_substeps();
0341 }
0342 
0343 //---------------------------------------------------------------------------//
0344 /*!
0345  * Distance to bump or to consider a "zero" movement.
0346  */
0347 template<class SubstepperT, class GTV>
0348 CELER_FUNCTION real_type
0349 FieldPropagator<SubstepperT, GTV>::minimum_substep() const
0350 {
0351     return advance_.minimum_step();
0352 }
0353 
0354 //---------------------------------------------------------------------------//
0355 /*!
0356  * Distance to bump or to consider a "zero" movement.
0357  */
0358 template<class SubstepperT, class GTV>
0359 CELER_FUNCTION real_type FieldPropagator<SubstepperT, GTV>::bump_distance() const
0360 {
0361     using namespace celeritas::literals;
0362 
0363     return this->delta_intersection() * 0.1_r;
0364 }
0365 
0366 //---------------------------------------------------------------------------//
0367 }  // namespace celeritas