Skip to main content

deep_time/
drift.rs

1//! Quadratic polynomial for relativistic corrections, clock drift, and custom timescale steering.
2//!
3//! Used by spacecraft 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 spacecraft navigation pipelines, black-hole flyby simulations, cosmological trajectories, or 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    /// It is primarily useful for tests, legacy ephemeris data, or when
299    /// converting previously-computed α values into the form required by
300    /// [`TrajectorySample`].
301    #[inline]
302    pub const fn grav_potential_from_alpha(alpha: Real) -> Real {
303        let alpha_sq = alpha * alpha;
304        (alpha_sq - f!(1.0)) / f!(2.0) * C_SQUARED
305    }
306
307    /// Computes the total Newtonian gravitational potential Φ at a given position
308    /// from an arbitrary collection of point-mass bodies (Sun, Earth, Moon,
309    /// planets, asteroids, etc.).
310    ///
311    /// This is the standard method used by real mission planners (Apollo,
312    /// Artemis, Mars orbiters, lunar landers) and in open-source astrodynamics
313    /// libraries (SPICE/NAIF, Orekit, GMAT, poliastro). It evaluates
314    ///
315    /// \[
316    /// \Phi = -\sum_i \frac{GM_i}{r_i}
317    /// \]
318    ///
319    /// # Example (realistic cislunar trajectory)
320    /// ```rust
321    /// use deep_time::{Position, Spacetime};
322    ///
323    /// let bodies = [
324    ///     (Position::from_au(0.0, 0.0, 0.0), 1.3271244e20),     // Sun
325    ///     (Position::from_au(1.0, 0.0, 0.0), 3.9860044e14),     // Earth
326    ///     (Position::from_au(1.00257, 0.0, 0.0), 4.9048695e12), // Moon
327    /// ];
328    ///
329    /// let position = Position::from_au(1.001, 0.001, 0.0); // e.g. spacecraft, asteroid, etc.
330    ///
331    /// let phi = Spacetime::grav_potential_from_point_masses(
332    ///     position,
333    ///     bodies.iter().copied(),
334    /// );
335    /// ```
336    pub fn grav_potential_from_point_masses<I>(position: Position, bodies: I) -> Real
337    where
338        I: IntoIterator<Item = (Position, Real)>, // (body_position, GM in m³/s²)
339    {
340        let mut phi = 0.0;
341        for (body_pos, gm) in bodies {
342            let r = position.distance_to(body_pos);
343            if r > 0.0 {
344                phi -= gm / r;
345            }
346        }
347        phi
348    }
349}
350
351#[cfg(feature = "wire")]
352impl Spacetime {
353    /// Size of the canonical wire representation in bytes (24 bytes).
354    pub const WIRE_SIZE: usize = 24;
355
356    /// Serializes this `Spacetime` snapshot into a fixed 24-byte buffer.
357    ///
358    /// All fields are stored as little-endian IEEE 754 `f64`.
359    pub fn to_wire_bytes(&self) -> [u8; Self::WIRE_SIZE] {
360        let mut buf = [0u8; Self::WIRE_SIZE];
361        buf[0..8].copy_from_slice(&self.alpha.to_le_bytes());
362        buf[8..16].copy_from_slice(&self.beta.to_le_bytes());
363        buf[16..24].copy_from_slice(&self.kretschmann.to_le_bytes());
364        buf
365    }
366
367    /// Deserializes a `Spacetime` from exactly 24 bytes.
368    ///
369    /// ## Security
370    ///
371    /// Accepts any `f64` bit pattern (including `NaN`/`Inf`) to match the
372    /// type’s own invariants. Fixed size makes it immune to length-based
373    /// attacks. Safe for untrusted input.
374    pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self> {
375        if bytes.len() != Self::WIRE_SIZE {
376            return None;
377        }
378        let alpha = f64::from_le_bytes([
379            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
380        ]);
381        let beta = f64::from_le_bytes([
382            bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
383        ]);
384        let kretschmann = f64::from_le_bytes([
385            bytes[16], bytes[17], bytes[18], bytes[19], bytes[20], bytes[21], bytes[22], bytes[23],
386        ]);
387        Some(Self {
388            alpha,
389            beta,
390            kretschmann,
391        })
392    }
393}
394
395/// Quadratic polynomial that describes the accumulated difference between an
396/// observer’s proper time (the time measured by a real clock moving through
397/// spacetime) and a chosen coordinate time such as TT, TAI, or any other
398/// `Scale`.
399///
400/// The polynomial follows the classic form  
401/// Δt = constant + rate·Δt + accel·(Δt)²  
402/// where the three coefficients capture any fixed offset, constant drift, and
403/// quadratic acceleration of the clock. This structure is used throughout
404/// spacecraft navigation, GNSS systems, and relativistic timing pipelines to
405/// steer clocks, predict time offsets, and maintain synchronization over long
406/// durations.
407///
408/// All three coefficients are stored using the exact `Dt` type, which
409/// guarantees 36-digit precision with no floating-point rounding errors even
410/// over centuries of integration.
411#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
412#[cfg_attr(feature = "js", derive(tsify::Tsify))]
413#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
414pub struct Drift {
415    /// Constant term a₀ expressed in seconds.  
416    /// This represents any fixed time offset between the observer’s proper time
417    /// and the chosen coordinate time.
418    constant: Dt,
419
420    /// Linear drift rate a₁ expressed in seconds per second.  
421    /// This term captures a steady fractional rate difference (for example, a
422    /// clock that runs consistently fast or slow).
423    rate: Dt,
424
425    /// Quadratic acceleration term a₂ expressed in seconds per second squared.  
426    /// This term accounts for any changing drift rate, such as the gradual
427    /// acceleration caused by relativistic effects or hardware aging.
428    accel: Dt,
429}
430
431impl Drift {
432    /// Creates a new `Drift` polynomial from its three exact coefficients.
433    #[inline]
434    pub const fn new(constant: Dt, rate: Dt, accel: Dt) -> Self {
435        Self {
436            constant,
437            rate,
438            accel,
439        }
440    }
441
442    /// The zero polynomial representing no correction at all.  
443    /// Use this when the observer’s clock is already perfectly synchronized with
444    /// the chosen coordinate time.
445    pub const ZERO: Self = Self::new(Dt::ZERO, Dt::ZERO, Dt::ZERO);
446
447    /// Creates a `Drift` consisting of a pure constant offset.  
448    /// This is the most common constructor when only a fixed time bias is known
449    /// (for example, after a one-time clock synchronization or leap-second
450    /// adjustment).
451    #[inline]
452    pub const fn from_constant(c: Dt) -> Self {
453        Self::new(c, Dt::ZERO, Dt::ZERO)
454    }
455
456    /// Creates a `Drift` consisting of a constant offset together with a
457    /// constant linear drift rate.  
458    /// This form is very common for GNSS receivers and spacecraft clock steering,
459    /// where a steady fractional frequency offset must be corrected in addition
460    /// to any fixed bias.
461    #[inline]
462    pub const fn from_offset_and_rate(offset: Dt, rate: Dt) -> Self {
463        Self::new(offset, rate, Dt::ZERO)
464    }
465
466    #[inline]
467    pub const fn constant(&self) -> &Dt {
468        &self.constant
469    }
470
471    #[inline]
472    pub const fn rate(&self) -> &Dt {
473        &self.rate
474    }
475
476    #[inline]
477    pub const fn accel(&self) -> &Dt {
478        &self.accel
479    }
480
481    #[inline]
482    pub const fn set_constant(&mut self, constant: Dt) -> &mut Self {
483        self.constant = constant;
484        self
485        // constant never affects the pre-computed big fields
486    }
487
488    #[inline]
489    pub const fn set_rate(&mut self, rate: Dt) -> &mut Self {
490        self.rate = rate;
491        self
492    }
493
494    #[inline]
495    pub const fn set_accel(&mut self, accel: Dt) -> &mut Self {
496        self.accel = accel;
497        self
498    }
499
500    #[inline]
501    pub const fn with_constant(self, constant: Dt) -> Self {
502        Self::new(constant, self.rate, self.accel)
503    }
504
505    #[inline]
506    pub const fn with_rate(self, rate: Dt) -> Self {
507        Self::new(self.constant, rate, self.accel)
508    }
509
510    #[inline]
511    pub const fn with_accel(self, accel: Dt) -> Self {
512        Self::new(self.constant, self.rate, accel)
513    }
514
515    /// Returns the instantaneous proper-time rate `dτ/dt` (dimensionless).
516    ///
517    /// This value tells you how fast a real physical clock (such as a spacecraft
518    /// onboard clock) is advancing compared to coordinate time. A value of exactly
519    /// `1.0` means the clock runs at the normal rate. Values slightly below `1.0`
520    /// are typical when the clock is moving or sitting in a gravitational well.
521    ///
522    /// The rate includes special-relativistic velocity effects, gravitational
523    /// time dilation, and the library’s built-in Planck-scale saturation term.
524    #[inline]
525    pub const fn proper_time_rate(&self) -> Real {
526        f!(1.0) + self.rate.to_sec_f()
527    }
528
529    /// Evaluates the polynomial at the given elapsed coordinate time span.  
530    ///
531    /// Returns the exact accumulated time difference (in seconds) between proper
532    /// time and coordinate time after the interval span has passed. All
533    /// arithmetic is performed with full 36-digit precision, ensuring no loss of
534    /// accuracy even for multi-year integrations.
535    pub const fn time_diff_after(&self, span: &Dt) -> Dt {
536        let dt_attos = span.to_attos();
537        let mut total_attos = self.constant.to_attos();
538
539        if !self.rate.is_zero() || !self.accel.is_zero() {
540            // Linear term: rate * dt
541            let rate_attos = self.rate.to_attos();
542            let rate_term = rate_attos.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
543            total_attos = total_attos.wrapping_add(rate_term);
544
545            // Quadratic term: accel * dt²
546            let accel_attos = self.accel.to_attos();
547            let accel_dt = accel_attos.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
548            let accel_term = accel_dt.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
549            total_attos = total_attos.saturating_add(accel_term);
550        }
551
552        Dt::from_attos(total_attos, Scale::TAI)
553    }
554
555    /// Evaluates the deterministic relativistic/polynomial correction **and**
556    /// adds a user-supplied stochastic offset (in seconds).
557    ///
558    /// This is the single production method for realistic stochastic clock
559    /// modeling. In real mission pipelines the deterministic part (this
560    /// polynomial) is kept perfectly clean; stochastic noise (white phase noise,
561    /// random-walk frequency noise, Monte-Carlo realizations, Kalman process
562    /// noise, measured clock residuals, etc.) is added at evaluation time.
563    ///
564    /// Pass `0.0` (or simply call the original `time_diff_after`) when you
565    /// want purely deterministic behavior.
566    #[inline]
567    pub fn time_diff_after_with_noise(&self, span: &Dt, stochastic_offset_sec: Real) -> Dt {
568        self.time_diff_after(span)
569            .add(Dt::from_sec_f(stochastic_offset_sec))
570    }
571
572    /// Creates a `Drift` directly from an observer’s velocity and total
573    /// local gravitational potential using the library’s unified master-Lagrangian
574    /// proper-time rate.  
575    ///
576    /// This is the recommended high-level constructor for nearly all users. It
577    /// automatically computes the relativistic clock rate that includes both
578    /// special-relativistic velocity effects and gravitational time dilation,
579    /// then returns a `Drift` that can be evaluated at any future time.
580    ///
581    /// The `characteristic_length_scale` parameter controls whether the
582    /// weak-field or strong-field formulation is used:
583    ///
584    /// - In the weak-field regime (where |Φ|/c² ≪ 1), simply pass
585    ///   `characteristic_length_scale = 0.0`. This returns exactly the same
586    ///   relativistic clock rate used by JPL, ESA, GNSS systems, and all modern
587    ///   solar-system navigation pipelines.
588    /// - In strong-field conditions, supply a non-zero length scale (in meters)
589    ///   over which the gravitational potential changes at the observer’s
590    ///   location. This activates the library’s intrinsic Planck-scale saturation
591    ///   term when spacetime curvature becomes extreme.
592    pub const fn from_velocity_potential_and_scale(
593        velocity_m_s: Real,
594        grav_potential_m2_s2: Real,
595        characteristic_length_scale: Real,
596    ) -> Self {
597        let phi = grav_potential_m2_s2 / C_SQUARED;
598        let velocity = Velocity::from_speed(velocity_m_s);
599        let spacetime = Spacetime::from_potential_velocity_and_scale(
600            phi,
601            velocity,
602            characteristic_length_scale,
603        );
604        Self::from_spacetime(&spacetime)
605    }
606
607    /// Canonical low-level constructor that implements the exact intrinsic
608    /// expression from the master Lagrangian.  
609    ///
610    /// This function is the single source of truth for the proper-time rate
611    /// calculation used throughout the library. Most users will never call it
612    /// directly; the high-level constructors `from_velocity_potential_and_scale`
613    /// and `from_spacetime` are the intended entry points.
614    ///
615    /// The internal expression is  
616    /// K_eff = [δ(1 + x) + x(1−δ)²] / (1 + x)  
617    /// where δ = α²(1−β²) and x = ℓ_Pl⁴ 𝒦. The returned rate offset is then
618    /// applied as a linear term in the `Drift` polynomial.
619    pub const fn from_unified_proper_time_rate(u: Real, kretschmann: Real) -> Self {
620        let delta = u.max(f!(0.0));
621        let x = PLANCK_LENGTH_4 * kretschmann.max(f!(0.0));
622
623        let one_minus_delta = f!(1.0) - delta;
624        let num = delta * (f!(1.0) + x) + x * (one_minus_delta * one_minus_delta);
625        let k_eff = num / (f!(1.0) + x);
626
627        let rate_factor = sqrt(k_eff).max(f!(0.0));
628        let rate_offset = rate_factor - f!(1.0);
629
630        Self::from_offset_and_rate(Dt::ZERO, Dt::from_sec_f(rate_offset))
631    }
632
633    /// Creates a `Drift` from a fully resolved `Spacetime` snapshot.  
634    ///
635    /// This is the canonical high-level entry point when you already hold a
636    /// `Spacetime` object containing the gravitational lapse factor α, the
637    /// local velocity β, and the Kretschmann scalar. It internally computes the
638    /// unified proper-time rate and packages the result as a `Drift`
639    /// polynomial ready for evaluation at any future time.
640    #[inline]
641    pub const fn from_spacetime(spacetime: &Spacetime) -> Self {
642        let u = spacetime.alpha * spacetime.alpha * (f!(1.0) - spacetime.beta * spacetime.beta);
643        Self::from_unified_proper_time_rate(u, spacetime.kretschmann)
644    }
645}
646
647#[cfg(feature = "wire")]
648impl Drift {
649    /// Current wire format version.
650    pub const WIRE_VERSION: u8 = 1;
651
652    /// Size of the canonical wire representation in bytes.
653    pub const WIRE_SIZE: usize = 3 * Dt::WIRE_SIZE; // 3 × 17 = 51
654
655    /// Serializes this `Drift` polynomial into a fixed buffer.
656    ///
657    /// The layout is the concatenation of the three `Dt` fields.
658    pub fn to_wire_bytes(&self) -> [u8; Self::WIRE_SIZE] {
659        let mut buf = [0u8; Self::WIRE_SIZE];
660        let c = self.constant.to_wire_bytes();
661        let r = self.rate.to_wire_bytes();
662        let a = self.accel.to_wire_bytes();
663
664        buf[0..Dt::WIRE_SIZE].copy_from_slice(&c);
665        buf[Dt::WIRE_SIZE..2 * Dt::WIRE_SIZE].copy_from_slice(&r);
666        buf[2 * Dt::WIRE_SIZE..].copy_from_slice(&a);
667        buf
668    }
669
670    /// Deserializes a `Drift` from exactly `WIRE_SIZE` bytes of wire data.
671    ///
672    /// Returns `None` if any nested `Dt` fails validation or if the version
673    /// byte is unknown.
674    ///
675    /// ## Security
676    ///
677    /// Composes the safety guarantees of [`Dt::from_wire_bytes`].
678    /// Fixed size and layered validation make it safe for untrusted input.
679    pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self> {
680        if bytes.len() != Self::WIRE_SIZE {
681            return None;
682        }
683
684        if bytes[0] != Self::WIRE_VERSION {
685            return None;
686        }
687
688        let constant = Dt::from_wire_bytes(&bytes[0..Dt::WIRE_SIZE])?;
689        let rate = Dt::from_wire_bytes(&bytes[Dt::WIRE_SIZE..2 * Dt::WIRE_SIZE])?;
690        let accel = Dt::from_wire_bytes(&bytes[2 * Dt::WIRE_SIZE..])?;
691
692        Some(Self::new(constant, rate, accel))
693    }
694}
695
696impl Dt {
697    #[inline]
698    pub const fn to_drift_as_constant(self, rate: Dt, accel: Dt) -> Drift {
699        Drift::new(self, rate, accel)
700    }
701
702    #[inline]
703    pub const fn to_drift_as_rate(self, constant: Dt, accel: Dt) -> Drift {
704        Drift::new(constant, self, accel)
705    }
706
707    #[inline]
708    pub const fn to_drift_as_accel(self, constant: Dt, rate: Dt) -> Drift {
709        Drift::new(constant, rate, self)
710    }
711}