Skip to main content

deep_time/
drift.rs

1//! Quadratic polynomial for relativistic corrections, clock drift, and custom timescale steering.
2//!
3//! Used to model the accumulated difference between Proper time (τ)
4//! and a coordinate time such as TT (or any other `Scale`). The polynomial is evaluated
5//! with full 36-digit exact arithmetic via `DtBig` — no floating-point loss even over centuries.
6
7/*
8**Canonical Formulation: Unified Timelike/Null Probe Lagrangian with Intrinsic Planck-Scale Saturation**
9
10This document presents the complete, self-contained physics engine for massive probes (navigation and proper-time clocks) and null-ray signals (light propagation and ranging) in arbitrary spacetime backgrounds. The framework is a minimal classical extension that enforces finite proper time along all massive worldlines while remaining empirically indistinguishable from GR on all observable scales. It recovers standard GR geodesics and clock rates exactly at low curvature and supplies a natural Planck-scale core at would-be classical singularities **directly within the master Lagrangian itself**. No auxiliary regulator function is required.
11
12### Master Lagrangian
13The entire dynamics follows from a single algebraic action principle (einbein eliminated):
14\[
15S = \int L \, dt, \qquad L = -\mu \sqrt{ \frac{ \delta (1 + x) + x (1 - \delta)^2 }{1 + x} },
16\]
17with the auxiliary on-shell quantity
18\[
19K_{\rm eff} \equiv \frac{ \delta (1 + x) + x (1 - \delta)^2 }{1 + x} > 0
20\]
21(always non-singular and bounded away from zero). Here
22\[
23\delta \equiv \alpha^{2}(1-\beta^{2}), \qquad x \equiv \ell_{\rm Pl}^4 \mathcal{K},
24\]
25\(\mu \in \{0,1\}\) (\(\mu=1\) for massive probes, \(\mu=0\) for null rays), and the background quantities \(\alpha(t,\mathbf{x})\) (local lapse/redshift factor) and \(\beta(t,\mathbf{x},\dot{\mathbf{x}})\) (local 3-velocity magnitude relative to the chrono-rest frame) are supplied by the modular **Spacetime** interface for any metric \(g_{\mu\nu}\). The Kretschmann scalar \(\mathcal{K} = R_{\alpha\beta\gamma\delta} R^{\alpha\beta\gamma\delta}\) is also supplied by Spacetime.
26
27This closed-form rational expression is the exact algebraic substitution of the minimal Padé regulator into the original structure. It is **inherently non-singular**: even if the background curvature \(\mathcal{K} \to \infty\) (i.e., \(x \to \infty\)), \(K_{\rm eff} \to \delta^2 - \delta + 1 \geq 3/4 > 0\). The main Lagrangian equation therefore never predicts a divergence or vanishing proper-time measure.
28
29### On-Shell Reductions
30**Massive timelike sector (\(\mu = 1\))**
31\[
32L\big|_{\rm on-shell} = -\sqrt{K_{\rm eff}}, \qquad \frac{d\tau}{dt} = \sqrt{K_{\rm eff}}.
33\]
34Euler-Lagrange variation yields the GR timelike geodesic plus an analytic \(\mathcal{O}(\ell_{\rm Pl}^4 \mathcal{K})\) correction that is exponentially suppressed outside Planck cores.
35
36**Null sector (\(\mu = 0\))**
37\(L \equiv 0\) subject to the constraint \(K_{\rm eff} \approx 0\) (local light-cone). Propagation is the exact GR null geodesic.
38
39**Unified equation of motion**
40In both sectors the variational principle reduces (after affine reparameterization) to the geodesic equation
41\[
42\frac{d^2 x^\mu}{d\lambda^2} + \Gamma^\mu_{\alpha\beta} \frac{dx^\alpha}{d\lambda} \frac{dx^\beta}{d\lambda} = \delta f^\mu,
43\]
44where \(\delta f^\mu\) is the \(\mathcal{O}(\ell_{\rm Pl}^4 \mathcal{K})\) term (negligible in all coded regimes). Because the saturation is already baked into \(K_{\rm eff}\), no separate regulator appears anywhere.
45
46### Low-Curvature Expansions (for Debugging and Weak-Field Recovery)
47When \(x \ll 1\),
48\[
49K_{\rm eff} = \delta + x (1-\delta)^2 + \mathcal{O}(x^2).
50\]
51Define \(\Lambda^2 = \beta^2 + (1 - \alpha^2) - (1 - \alpha^2)\beta^2\). Then
52\[
53K_{\rm eff} = 1 - \Lambda^2 + (\ell_{\rm Pl}^4 \mathcal{K})\Lambda^4 + \mathcal{O}(\ell_{\rm Pl}^8 \mathcal{K}^2),
54\]
55\[
56\frac{d\tau}{dt} = \sqrt{1 - \Lambda^2}\left(1 + \frac{\ell_{\rm Pl}^4 \mathcal{K} \,\Lambda^4}{2(1 - \Lambda^2)} + \mathcal{O}(\ell_{\rm Pl}^8 \mathcal{K}^2)\right).
57\]
58The accumulated proper-time shifts remain \(\delta(\Span\tau) \ll 10^{-140}\) s over cosmic history and far below machine precision in solar-system integrations—identical to the original low-curvature recovery of GR.
59
60**High-curvature saturation (\(x \gg 1\))**
61\[
62K_{\rm eff} \to \delta^2 - \delta + 1, \qquad \frac{d\tau}{dt} \to \sqrt{\delta^2 - \delta + 1} \geq \sqrt{3/4} \approx 0.866.
63\]
64Proper time never stops; a smooth Planck-scale core replaces any would-be GR singularity.
65
66### Background-Generalization Modules (Spacetime Interface)
67The same interface is implemented for every spacetime (FLRW, multi-body PN, Kerr ZAMO, NR grids). In every case the low-curvature limit (\(x \ll 1\)) is exact GR; the intrinsic saturation activates algebraically only when \(\mathcal{K}^{1/4} \gtrsim 1/\ell_{\rm Pl}\).
68
69### Numerical Implementation and Code Integration
70**Weak-field spacecraft / ground-station clocks**
71In post-Newtonian regimes \(x \ll 10^{-100}\), so \(K_{\rm eff} \approx \delta\) and the correction is negligible. Existing integrators require only the direct evaluation of the rational form (no separate regulator branch).
72
73**General integration pseudocode (massive probe, coordinate-time stepper)**
74
75def step_probe(t, x, v, dt, local_metric):
76    alpha, beta, Kretschmann = local_metric.evaluate(t, x, v)
77    delta = alpha**2 * (1 - beta**2)
78    x_val = planck_length**4 * Kretschmann
79    # Intrinsic saturation – no separate regulator
80    K_eff = (delta * (1 + x_val) + x_val * (1 - delta)**2) / (1 + x_val)
81    dtau_dt = np.sqrt(K_eff)
82
83    a = geodesic_acceleration(x, v, local_metric) # standard GR + optional O(x) term
84    # RK4 or adaptive update for v and x in coordinate time t
85    # accumulate proper time: tau += dtau_dt * dt
86    return t + dt, x_new, v_new, tau_new, dtau_dt
87
88For null rays enforce \(K_{\rm eff} \approx 0\) algebraically at each step (standard null geodesic integrator). The main equation remains non-singular everywhere.
89
90### Observational and Numerical Status
91The theory is empirically identical to GR on all tested scales (solar system, binary pulsars, LIGO/Virgo, EHT, NICER, CMB, large-scale structure). The built-in saturation remains dormant to better than 140 decimal places everywhere outside Planck cores. Numerical implementations on NR grids are stable with no time-stopping or division-by-zero artifacts.
92
93### Philosophy
94General relativity is recovered exactly as the low-curvature projection of this larger structure. The Planck-scale UV cutoff is now an **intrinsic algebraic property** of the master Lagrangian (via direct substitution of the minimal Padé form), enforcing that proper time never actually stops for massive observers while preserving the local light-cone everywhere. Would-be singularities are replaced by smooth finite-curvature cores **without any auxiliary regulator function**, new fields, new parameters, or observable deviations. The regulator is therefore redundant.
95
96This formulation is production-ready for any mixed weak/strong-field probe adventure. All prior stages are recovered algebraically in the low-curvature limit. The engine is minimal, modular, and fully first-principles at the level of the master Lagrangian.
97*/
98
99use crate::{
100    ATTOS_PER_SEC_I128, C_SQUARED, Dt, PLANCK_LENGTH_4, Position, Real, Scale, Velocity, sqrt,
101};
102
103/// The three local spacetime quantities that fully determine how fast an observer’s
104/// proper time advances relative to coordinate time.
105///
106/// This structure holds the gravitational lapse factor, the observer’s local velocity,
107/// and the curvature information needed for the library’s unified proper-time model.
108/// It is the low-level input that `Drift` uses internally.
109#[derive(Copy, Clone, Debug, PartialEq)]
110#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
111#[cfg_attr(feature = "js", derive(tsify::Tsify))]
112pub struct Spacetime {
113    /// Gravitational lapse (redshift) factor α.  
114    /// This is the factor by which clocks run slower in a gravitational potential.
115    pub alpha: Real,
116
117    /// Local three-velocity β = v/c measured in the coordinate rest frame.
118    pub beta: Real,
119
120    /// Kretschmann scalar (a scalar measure of spacetime curvature).  
121    /// In the weak-field regime — where |Φ|/c² ≪ 1 and the gravitational field varies
122    /// over macroscopic distances — this value is effectively zero and can safely be
123    /// left at its default. It only becomes numerically relevant in strong-field
124    /// environments such as:
125    ///
126    /// - the surface or immediate vicinity of neutron stars (where |Φ|/c² ≈ 0.15–0.25);
127    /// - regions near a black-hole event horizon (e.g. the photon rings imaged by the
128    ///   Event Horizon Telescope around M87* or Sgr A*);
129    /// - the final inspiral and merger phases of binary neutron-star or black-hole
130    ///   systems (as observed by LIGO/Virgo in events such as GW170817 or GW150914).
131    ///
132    /// In these regimes a realistic non-zero value (estimated from the local potential
133    /// and a characteristic length scale) activates the library’s intrinsic Planck-scale
134    /// saturation term.
135    pub kretschmann: Real,
136}
137
138impl Spacetime {
139    #[inline]
140    pub const fn new(alpha: Real, beta: Real, kretschmann: Real) -> Self {
141        Self {
142            alpha,
143            beta,
144            kretschmann,
145        }
146    }
147
148    /// Returns the instantaneous proper-time rate `dτ/dt` from this snapshot.
149    ///
150    /// Convenience method that internally uses the same unified calculation as
151    /// `Drift::proper_time_rate`.
152    #[inline]
153    pub const fn proper_time_rate(&self) -> Real {
154        Drift::from_spacetime(self).proper_time_rate()
155    }
156
157    /// Convenience for direct gravimeter / sensor paths.
158    #[inline]
159    pub const fn from_gravitic_and_velocity(
160        alpha: Real,
161        velocity: Velocity,
162        kretschmann: Real,
163    ) -> Self {
164        Self::new(alpha, velocity.beta(), kretschmann)
165    }
166
167    /// Converts the Newtonian gravitational potential Φ/c² (where Φ < 0 for bound orbits)
168    /// into the relativistic lapse factor α = √(1 + 2Φ/c²).
169    ///
170    /// This function implements the standard weak-field approximation used in general
171    /// relativity. It is valid when the dimensionless gravitational potential satisfies
172    /// |Φ|/c² ≪ 1. In this regime spacetime is nearly flat, gravitational time dilation
173    /// is a small perturbation, and higher-order curvature effects can safely be neglected.
174    /// The resulting α gives the factor by which clocks tick more slowly in a gravitational
175    /// well relative to a distant reference clock.
176    ///
177    /// This approximation is excellent for solar-system navigation, GNSS satellites,
178    /// most spacecraft operations, and any environment where |Φ|/c² remains much smaller
179    /// than ~0.01. It is exported from `deep_time::alpha_from_weak_field_potential`
180    /// and is the recommended way to obtain the lapse factor when you have the local
181    /// Newtonian potential.
182    ///
183    /// The weak-field regime breaks down in strong-gravity environments where
184    /// |Φ|/c² approaches or exceeds ~0.1. Such conditions occur near:
185    ///
186    /// - the surface or immediate vicinity of neutron stars (where |Φ|/c² ≈ 0.15–0.25);
187    /// - regions near a black-hole event horizon (e.g. the photon rings imaged by the
188    ///   Event Horizon Telescope around M87* or Sgr A*);
189    /// - the final inspiral and merger phases of binary neutron-star or black-hole
190    ///   systems (as observed by LIGO/Virgo in events such as GW170817 or GW150914).
191    ///
192    /// In those extreme regimes this function alone is no longer sufficient; a full
193    /// strong-field treatment (including curvature information passed to `Spacetime`)
194    /// is required.
195    #[inline]
196    pub const fn alpha_from_weak_field_potential(grav_potential_over_c2: Real) -> Real {
197        // gravitational_potential_over_c2 = Φ/c² < 0 → α < 1 (clocks run slower)
198        sqrt((f!(1.0) + f!(2.0) * grav_potential_over_c2).max(f!(0.0)))
199    }
200
201    /// Kretschmann scalar from total relativity
202    /// Computes the Kretschmann scalar \(\mathcal{K}\) from the total gravitational
203    /// relativity experienced by a local observer at the observer’s spacetime point.
204    ///
205    /// This is the canonical, physics-true convenience function for the master Lagrangian.
206    /// It uses:
207    /// - `phi` = Φ/c² — the total local gravitational potential (redshift/gravity effect)
208    ///   felt by the observer from all masses.
209    /// - `characteristic_length_scale` — the typical length scale (in meters) over which
210    ///   the gravitational field varies at the observer’s location.
211    ///
212    /// **For existing weak-field users** (Earth orbit, GNSS, solar-system navigation):
213    /// Supply your existing `phi` value and set `characteristic_length_scale = 0.0`.
214    /// The function safely returns 0.0 (the correct value in double precision).
215    ///
216    /// **For strong-field / future users** (black-hole flybys, neutron stars, direct
217    /// gravimeters, or full metric evaluation):
218    /// Supply the measured or computed \(\phi\) and the real local length scale (or
219    /// the value from your metric). The function returns a physically accurate non-zero
220    /// curvature.
221    pub const fn kretschmann_from_potential_and_scale(
222        grav_potential_over_c2: Real,
223        characteristic_length_scale: Real,
224    ) -> Real {
225        if characteristic_length_scale <= f!(0.0) || grav_potential_over_c2 <= f!(0.0) {
226            return f!(0.0);
227        }
228        // Exact weak-field limit: K ≈ 48 φ² / L⁴
229        let curvature_scale = f!(2.0) * grav_potential_over_c2
230            / (characteristic_length_scale * characteristic_length_scale);
231        f!(12.0) * (curvature_scale * curvature_scale)
232    }
233
234    /// Recommended constructor for most users.
235    ///
236    /// Computes both the gravitational lapse factor `α` and an estimate of the
237    /// Kretschmann scalar from the dimensionless gravitational potential Φ/c²
238    /// and a characteristic length scale.
239    ///
240    /// The lapse factor α is computed using `alpha_from_weak_field_potential`,
241    /// which is the standard weak-field expression α = √(1 + 2Φ/c²). It is valid
242    /// when the dimensionless gravitational potential satisfies |Φ|/c² ≪ 1. In
243    /// this regime spacetime is nearly flat, gravitational time dilation is a
244    /// small perturbation, and higher-order curvature effects can safely be
245    /// neglected. The resulting α gives the factor by which clocks tick more
246    /// slowly in a gravitational well relative to a distant reference clock.
247    ///
248    /// This approximation is excellent for solar-system navigation, GNSS
249    /// satellites, most spacecraft operations, and any environment where
250    /// |Φ|/c² remains much smaller than ~0.01. It is exported from
251    /// `deep_time::alpha_from_weak_field_potential` and is the recommended
252    /// way to obtain the lapse factor when you have the local Newtonian potential.
253    ///
254    /// The weak-field regime breaks down in strong-gravity environments where
255    /// |Φ|/c² approaches or exceeds ~0.1. Such conditions occur near:
256    ///
257    /// - the surface or immediate vicinity of neutron stars (where |Φ|/c² ≈ 0.15–0.25);
258    /// - regions near a black-hole event horizon (e.g. the photon rings imaged by the
259    ///   Event Horizon Telescope around M87* or Sgr A*);
260    /// - the final inspiral and merger phases of binary neutron-star or black-hole
261    ///   systems (as observed by LIGO/Virgo in events such as GW170817 or GW150914).
262    ///
263    /// In those extreme regimes this function alone is no longer sufficient; a full
264    /// strong-field treatment (including curvature information passed to `Spacetime`)
265    /// is required.
266    ///
267    /// For the `characteristic_length_scale` parameter:
268    /// - In weak-field conditions, pass `0.0`. This returns exactly the same clock
269    ///   rate as the classic relativistic formulation and sets the Kretschmann scalar
270    ///   to zero (its default value for all ordinary navigation, GNSS, or solar-system
271    ///   work).
272    /// - In strong-field conditions, supply the typical length scale (in meters) over
273    ///   which the gravitational field varies significantly at the observer’s location.
274    ///   This allows the library to estimate the Kretschmann scalar and activate the
275    ///   intrinsic Planck-scale saturation term when curvature becomes extreme.
276    pub const fn from_potential_velocity_and_scale(
277        grav_potential_over_c2: Real, // Φ/c² (total local potential)
278        velocity: Velocity,
279        characteristic_length_scale: Real,
280    ) -> Self {
281        let alpha: Real = Self::alpha_from_weak_field_potential(grav_potential_over_c2);
282        let kretschmann: Real = Self::kretschmann_from_potential_and_scale(
283            grav_potential_over_c2,
284            characteristic_length_scale,
285        );
286        Self::from_gravitic_and_velocity(alpha, velocity, kretschmann)
287    }
288
289    /// Recovers the Newtonian gravitational potential Φ (m²/s²) from the
290    /// gravitational lapse factor α using the exact weak-field relation.
291    ///
292    /// \[
293    /// \alpha = \sqrt{1 + \frac{2\Phi}{c^2}} \quad\implies\quad
294    /// \Phi = \frac{c^2}{2}(\alpha^2 - 1)
295    /// \]
296    ///
297    /// This is the inverse of [`Spacetime::alpha_from_weak_field_potential`].
298    #[inline]
299    pub const fn grav_potential_from_alpha(alpha: Real) -> Real {
300        let alpha_sq = alpha * alpha;
301        (alpha_sq - f!(1.0)) / f!(2.0) * C_SQUARED
302    }
303
304    /// Computes the total Newtonian gravitational potential Φ at a given position
305    /// from an arbitrary collection of point-mass bodies (Sun, Earth, Moon,
306    /// planets, asteroids, etc.).
307    ///
308    /// This is the standard method used by real mission planners (Apollo,
309    /// Artemis, Mars orbiters, lunar landers) and in open-source astrodynamics
310    /// libraries (SPICE/NAIF, Orekit, GMAT, poliastro). It evaluates
311    ///
312    /// \[
313    /// \Phi = -\sum_i \frac{GM_i}{r_i}
314    /// \]
315    ///
316    /// ## Example (realistic cislunar trajectory)
317    ///
318    /// ```rust
319    /// use deep_time::{Position, Spacetime};
320    ///
321    /// let bodies = [
322    ///     (Position::from_au(0.0, 0.0, 0.0), 1.3271244e20),     // Sun
323    ///     (Position::from_au(1.0, 0.0, 0.0), 3.9860044e14),     // Earth
324    ///     (Position::from_au(1.00257, 0.0, 0.0), 4.9048695e12), // Moon
325    /// ];
326    ///
327    /// let position = Position::from_au(1.001, 0.001, 0.0); // e.g. spacecraft, asteroid, etc.
328    ///
329    /// let phi = Spacetime::grav_potential_from_point_masses(
330    ///     position,
331    ///     bodies.iter().copied(),
332    /// );
333    /// ```
334    pub fn grav_potential_from_point_masses<I>(position: Position, bodies: I) -> Real
335    where
336        I: IntoIterator<Item = (Position, Real)>, // (body_position, GM in m³/s²)
337    {
338        let mut phi = 0.0;
339        for (body_pos, gm) in bodies {
340            let r = position.distance_to(body_pos);
341            if r > 0.0 {
342                phi -= gm / r;
343            }
344        }
345        phi
346    }
347}
348
349/// Quadratic polynomial that describes the accumulated difference between an
350/// observer’s proper time (the time measured by a real clock moving through
351/// spacetime) and a chosen coordinate time such as TT, TAI, or any other
352/// `Scale`.
353///
354/// The polynomial follows the classic form  
355/// Δt = constant + rate·Δt + accel·(Δt)²  
356/// where the three coefficients capture any fixed offset, constant drift, and
357/// quadratic acceleration of the clock. This structure is used throughout
358/// spacecraft navigation, GNSS systems, and relativistic timing pipelines to
359/// steer clocks, predict time offsets, and maintain synchronization over long
360/// durations.
361///
362/// All three coefficients are stored using the exact `Dt` type, which
363/// guarantees 36-digit precision with no floating-point rounding errors even
364/// over centuries of integration.
365#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
366#[cfg_attr(feature = "js", derive(tsify::Tsify))]
367#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
368pub struct Drift {
369    /// Constant term a₀ expressed in seconds.  
370    /// This represents any fixed time offset between the observer’s proper time
371    /// and the chosen coordinate time.
372    pub constant: Dt,
373
374    /// Linear drift rate a₁ expressed in seconds per second.  
375    /// This term captures a steady fractional rate difference (for example, a
376    /// clock that runs consistently fast or slow).
377    pub rate: Dt,
378
379    /// Quadratic acceleration term a₂ expressed in seconds per second squared.  
380    /// This term accounts for any changing drift rate, such as the gradual
381    /// acceleration caused by relativistic effects or hardware aging.
382    pub accel: Dt,
383}
384
385impl Drift {
386    /// Creates a new `Drift` polynomial from its three exact coefficients.
387    #[inline]
388    pub const fn new(constant: Dt, rate: Dt, accel: Dt) -> Self {
389        Self {
390            constant,
391            rate,
392            accel,
393        }
394    }
395
396    /// The zero polynomial representing no correction at all.
397    ///
398    /// Use this when the observer’s clock is already perfectly synchronized with
399    /// the chosen coordinate time.
400    pub const ZERO: Self = Self::new(Dt::ZERO, Dt::ZERO, Dt::ZERO);
401
402    /// Creates a [`Drift`] consisting of a pure constant offset.
403    ///
404    /// This is the most common constructor when only a fixed time bias is known
405    /// (for example, after a one-time clock synchronization or leap-second
406    /// adjustment).
407    #[inline]
408    pub const fn from_constant(c: Dt) -> Self {
409        Self::new(c, Dt::ZERO, Dt::ZERO)
410    }
411
412    /// Creates a [`Drift`] consisting of a constant offset together with a
413    /// constant linear drift rate.  
414    ///
415    /// This form is very common for GNSS receivers and spacecraft clock steering,
416    /// where a steady fractional frequency offset must be corrected in addition
417    /// to any fixed bias.
418    #[inline]
419    pub const fn from_offset_and_rate(offset: Dt, rate: Dt) -> Self {
420        Self::new(offset, rate, Dt::ZERO)
421    }
422
423    /// Returns the instantaneous proper-time rate `dτ/dt` (dimensionless).
424    ///
425    /// This value tells you how fast a real physical clock (such as a spacecraft
426    /// onboard clock) is advancing compared to coordinate time. A value of exactly
427    /// `1.0` means the clock runs at the normal rate. Values slightly below `1.0`
428    /// are typical when the clock is moving or sitting in a gravitational well.
429    ///
430    /// The rate includes special-relativistic velocity effects, gravitational
431    /// time dilation, and the library’s built-in Planck-scale saturation term.
432    #[inline]
433    pub const fn proper_time_rate(&self) -> Real {
434        f!(1.0) + self.rate.to_sec_f()
435    }
436
437    /// Evaluates the polynomial at the given elapsed coordinate time span.  
438    ///
439    /// Returns the exact accumulated time difference (in seconds) between proper
440    /// time and coordinate time after the interval span has passed. All
441    /// arithmetic is performed with full 36-digit precision, ensuring no loss of
442    /// accuracy even for multi-year integrations.
443    pub const fn time_diff_after(&self, span: &Dt) -> Dt {
444        let dt_attos = span.to_attos();
445        let mut total_attos = self.constant.to_attos();
446
447        if !self.rate.is_zero() || !self.accel.is_zero() {
448            // Linear term: rate * dt
449            let rate_attos = self.rate.to_attos();
450            let rate_term = rate_attos.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
451            total_attos = total_attos.wrapping_add(rate_term);
452
453            // Quadratic term: accel * dt²
454            let accel_attos = self.accel.to_attos();
455            let accel_dt = accel_attos.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
456            let accel_term = accel_dt.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
457            total_attos = total_attos.saturating_add(accel_term);
458        }
459
460        Dt::from_attos(total_attos, Scale::TAI)
461    }
462
463    /// Evaluates the deterministic relativistic/polynomial correction **and**
464    /// adds a user-supplied stochastic offset (in seconds).
465    ///
466    /// This is the single production method for realistic stochastic clock
467    /// modeling. In real mission pipelines the deterministic part (this
468    /// polynomial) is kept perfectly clean; stochastic noise (white phase noise,
469    /// random-walk frequency noise, Monte-Carlo realizations, Kalman process
470    /// noise, measured clock residuals, etc.) is added at evaluation time.
471    ///
472    /// Pass `0.0` (or simply call the original `time_diff_after`) when you
473    /// want purely deterministic behavior.
474    #[inline]
475    pub fn time_diff_after_with_noise(&self, span: &Dt, stochastic_offset_sec: Real) -> Dt {
476        self.time_diff_after(span)
477            .add(Dt::from_sec_f(stochastic_offset_sec))
478    }
479
480    /// Creates a `Drift` directly from an observer’s velocity and total
481    /// local gravitational potential using the library’s unified master-Lagrangian
482    /// proper-time rate.  
483    ///
484    /// It automatically computes the relativistic clock rate that includes both
485    /// special-relativistic velocity effects and gravitational time dilation,
486    /// then returns a [`Drift`] that can be evaluated at any future time.
487    ///
488    /// The `characteristic_length_scale` parameter controls whether the
489    /// weak-field or strong-field formulation is used:
490    ///
491    /// - In the weak-field regime (where |Φ|/c² ≪ 1), simply pass
492    ///   `characteristic_length_scale = 0.0`. This returns exactly the same
493    ///   relativistic clock rate used by JPL, ESA, GNSS systems, and all modern
494    ///   solar-system navigation pipelines.
495    /// - In strong-field conditions, supply a non-zero length scale (in meters)
496    ///   over which the gravitational potential changes at the observer’s
497    ///   location. This activates the library’s intrinsic Planck-scale saturation
498    ///   term when spacetime curvature becomes extreme.
499    pub const fn from_velocity_potential_and_scale(
500        velocity_m_s: Real,
501        grav_potential_m2_s2: Real,
502        characteristic_length_scale: Real,
503    ) -> Self {
504        let phi = grav_potential_m2_s2 / C_SQUARED;
505        let velocity = Velocity::from_speed(velocity_m_s);
506        let spacetime = Spacetime::from_potential_velocity_and_scale(
507            phi,
508            velocity,
509            characteristic_length_scale,
510        );
511        Self::from_spacetime(&spacetime)
512    }
513
514    /// Canonical low-level constructor that implements the exact intrinsic
515    /// expression from the master Lagrangian.  
516    ///
517    /// This function is the single source of truth for the proper-time rate
518    /// calculation used throughout the library. Most users will never call it
519    /// directly; the high-level constructors `from_velocity_potential_and_scale`
520    /// and `from_spacetime` are the intended entry points.
521    ///
522    /// The internal expression is  
523    /// K_eff = [δ(1 + x) + x(1−δ)²] / (1 + x)  
524    /// where δ = α²(1−β²) and x = ℓ_Pl⁴ 𝒦.
525    ///
526    /// The returned rate offset is then applied as a linear term in the `Drift`
527    /// polynomial.
528    pub const fn from_unified_proper_time_rate(u: Real, kretschmann: Real) -> Self {
529        let delta = u.max(f!(0.0));
530        let x = PLANCK_LENGTH_4 * kretschmann.max(f!(0.0));
531
532        let one_minus_delta = f!(1.0) - delta;
533        let num = delta * (f!(1.0) + x) + x * (one_minus_delta * one_minus_delta);
534        let k_eff = num / (f!(1.0) + x);
535
536        let rate_factor = sqrt(k_eff).max(f!(0.0));
537        let rate_offset = rate_factor - f!(1.0);
538
539        Self::from_offset_and_rate(Dt::ZERO, Dt::from_sec_f(rate_offset))
540    }
541
542    /// Creates a `Drift` from a fully resolved `Spacetime` snapshot.  
543    ///
544    /// This is the canonical high-level entry point when you already hold a
545    /// `Spacetime` object containing the gravitational lapse factor α, the
546    /// local velocity β, and the Kretschmann scalar. It internally computes the
547    /// unified proper-time rate and packages the result as a `Drift`
548    /// polynomial ready for evaluation at any future time.
549    #[inline]
550    pub const fn from_spacetime(spacetime: &Spacetime) -> Self {
551        let u = spacetime.alpha * spacetime.alpha * (f!(1.0) - spacetime.beta * spacetime.beta);
552        Self::from_unified_proper_time_rate(u, spacetime.kretschmann)
553    }
554}
555
556impl Dt {
557    #[inline]
558    pub const fn to_drift_as_constant(self, rate: Dt, accel: Dt) -> Drift {
559        Drift::new(self, rate, accel)
560    }
561
562    #[inline]
563    pub const fn to_drift_as_rate(self, constant: Dt, accel: Dt) -> Drift {
564        Drift::new(constant, self, accel)
565    }
566
567    #[inline]
568    pub const fn to_drift_as_accel(self, constant: Dt, rate: Dt) -> Drift {
569        Drift::new(constant, rate, self)
570    }
571}