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