deep_time/clock_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 **LocalSpacetime** 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 LocalSpacetime.
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(\TSpan\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 (LocalSpacetime 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```python
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::{ATTOS_PER_SEC_I128, C_SQUARED, PLANCK_LENGTH_4, Real, TSpan, Velocity, sqrt};
100
101/// The three local spacetime quantities that fully determine how fast an observer’s
102/// proper time advances relative to coordinate time.
103///
104/// This structure holds the gravitational lapse factor, the observer’s local velocity,
105/// and the curvature information needed for the library’s unified proper-time model.
106/// It is the low-level input that `ClockDrift` uses internally.
107#[derive(Copy, Clone, Debug, PartialEq)]
108#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
109#[cfg_attr(feature = "js", derive(tsify::Tsify))]
110pub struct LocalSpacetime {
111 /// Gravitational lapse (redshift) factor α.
112 /// This is the factor by which clocks run slower in a gravitational potential.
113 pub alpha: Real,
114
115 /// Local three-velocity β = v/c measured in the coordinate rest frame.
116 pub beta: Real,
117
118 /// Kretschmann scalar (a scalar measure of spacetime curvature).
119 /// In the weak-field regime — where |Φ|/c² ≪ 1 and the gravitational field varies
120 /// over macroscopic distances — this value is effectively zero and can safely be
121 /// left at its default. It only becomes numerically relevant in strong-field
122 /// environments such as:
123 ///
124 /// - the surface or immediate vicinity of neutron stars (where |Φ|/c² ≈ 0.15–0.25);
125 /// - regions near a black-hole event horizon (e.g. the photon rings imaged by the
126 /// Event Horizon Telescope around M87* or Sgr A*);
127 /// - the final inspiral and merger phases of binary neutron-star or black-hole
128 /// systems (as observed by LIGO/Virgo in events such as GW170817 or GW150914).
129 ///
130 /// In these regimes a realistic non-zero value (estimated from the local potential
131 /// and a characteristic length scale) activates the library’s intrinsic Planck-scale
132 /// saturation term.
133 pub kretschmann: Real,
134}
135
136impl LocalSpacetime {
137 #[inline]
138 pub const fn new(alpha: Real, beta: Real, kretschmann: Real) -> Self {
139 Self {
140 alpha,
141 beta,
142 kretschmann,
143 }
144 }
145
146 /// Returns the instantaneous proper-time rate `dτ/dt` from this snapshot.
147 ///
148 /// Convenience method that internally uses the same unified calculation as
149 /// `ClockDrift::proper_time_rate`.
150 #[inline]
151 pub const fn proper_time_rate(self) -> Real {
152 ClockDrift::from_local_spacetime(&self).proper_time_rate()
153 }
154
155 /// Convenience for direct gravimeter / sensor paths.
156 #[inline]
157 pub const fn from_gravitic_and_velocity(
158 alpha: Real,
159 velocity: Velocity,
160 kretschmann: Real,
161 ) -> Self {
162 Self::new(alpha, velocity.beta(), kretschmann)
163 }
164
165 /// Converts the Newtonian gravitational potential Φ/c² (where Φ < 0 for bound orbits)
166 /// into the relativistic lapse factor α = √(1 + 2Φ/c²).
167 ///
168 /// This function implements the standard weak-field approximation used in general
169 /// relativity. It is valid when the dimensionless gravitational potential satisfies
170 /// |Φ|/c² ≪ 1. In this regime spacetime is nearly flat, gravitational time dilation
171 /// is a small perturbation, and higher-order curvature effects can safely be neglected.
172 /// The resulting α gives the factor by which clocks tick more slowly in a gravitational
173 /// well relative to a distant reference clock.
174 ///
175 /// This approximation is excellent for solar-system navigation, GNSS satellites,
176 /// most spacecraft operations, and any environment where |Φ|/c² remains much smaller
177 /// than ~0.01. It is exported from `deep_time::alpha_from_weak_field_potential`
178 /// and is the recommended way to obtain the lapse factor when you have the local
179 /// Newtonian potential.
180 ///
181 /// The weak-field regime breaks down in strong-gravity environments where
182 /// |Φ|/c² approaches or exceeds ~0.1. Such conditions occur near:
183 ///
184 /// - the surface or immediate vicinity of neutron stars (where |Φ|/c² ≈ 0.15–0.25);
185 /// - regions near a black-hole event horizon (e.g. the photon rings imaged by the
186 /// Event Horizon Telescope around M87* or Sgr A*);
187 /// - the final inspiral and merger phases of binary neutron-star or black-hole
188 /// systems (as observed by LIGO/Virgo in events such as GW170817 or GW150914).
189 ///
190 /// In those extreme regimes this function alone is no longer sufficient; a full
191 /// strong-field treatment (including curvature information passed to `LocalSpacetime`)
192 /// is required.
193 #[inline]
194 pub const fn alpha_from_weak_field_potential(grav_potential_over_c2: Real) -> Real {
195 // gravitational_potential_over_c2 = Φ/c² < 0 → α < 1 (clocks run slower)
196 sqrt((f!(1.0) + f!(2.0) * grav_potential_over_c2).max(f!(0.0)))
197 }
198
199 /// Kretschmann scalar from total relativity
200 /// Computes the Kretschmann scalar \(\mathcal{K}\) from the total gravitational
201 /// relativity experienced by a local observer at the observer’s spacetime point.
202 ///
203 /// This is the canonical, physics-true convenience function for the master Lagrangian.
204 /// It uses:
205 /// - `phi` = Φ/c² — the total local gravitational potential (redshift/gravity effect)
206 /// felt by the observer from all masses.
207 /// - `characteristic_length_scale` — the typical length scale (in meters) over which
208 /// the gravitational field varies at the observer’s location.
209 ///
210 /// **For existing weak-field users** (Earth orbit, GNSS, solar-system navigation):
211 /// Supply your existing `phi` value and set `characteristic_length_scale = 0.0`.
212 /// The function safely returns 0.0 (the correct value in double precision).
213 ///
214 /// **For strong-field / future users** (black-hole flybys, neutron stars, direct
215 /// gravimeters, or full metric evaluation):
216 /// Supply the measured or computed \(\phi\) and the real local length scale (or
217 /// the value from your metric). The function returns a physically accurate non-zero
218 /// curvature.
219 pub const fn kretschmann_from_potential_and_scale(
220 grav_potential_over_c2: Real,
221 characteristic_length_scale: Real,
222 ) -> Real {
223 if characteristic_length_scale <= f!(0.0) || grav_potential_over_c2 <= f!(0.0) {
224 return f!(0.0);
225 }
226 // Exact weak-field limit: K ≈ 48 φ² / L⁴
227 let curvature_scale = f!(2.0) * grav_potential_over_c2
228 / (characteristic_length_scale * characteristic_length_scale);
229 f!(12.0) * (curvature_scale * curvature_scale)
230 }
231
232 /// Recommended constructor for most users.
233 ///
234 /// Computes both the gravitational lapse factor `α` and an estimate of the
235 /// Kretschmann scalar from the dimensionless gravitational potential Φ/c²
236 /// and a characteristic length scale.
237 ///
238 /// The lapse factor α is computed using `alpha_from_weak_field_potential`,
239 /// which is the standard weak-field expression α = √(1 + 2Φ/c²). It is valid
240 /// when the dimensionless gravitational potential satisfies |Φ|/c² ≪ 1. In
241 /// this regime spacetime is nearly flat, gravitational time dilation is a
242 /// small perturbation, and higher-order curvature effects can safely be
243 /// neglected. The resulting α gives the factor by which clocks tick more
244 /// slowly in a gravitational well relative to a distant reference clock.
245 ///
246 /// This approximation is excellent for solar-system navigation, GNSS
247 /// satellites, most spacecraft operations, and any environment where
248 /// |Φ|/c² remains much smaller than ~0.01. It is exported from
249 /// `deep_time::alpha_from_weak_field_potential` and is the recommended
250 /// way to obtain the lapse factor when you have the local Newtonian potential.
251 ///
252 /// The weak-field regime breaks down in strong-gravity environments where
253 /// |Φ|/c² approaches or exceeds ~0.1. Such conditions occur near:
254 ///
255 /// - the surface or immediate vicinity of neutron stars (where |Φ|/c² ≈ 0.15–0.25);
256 /// - regions near a black-hole event horizon (e.g. the photon rings imaged by the
257 /// Event Horizon Telescope around M87* or Sgr A*);
258 /// - the final inspiral and merger phases of binary neutron-star or black-hole
259 /// systems (as observed by LIGO/Virgo in events such as GW170817 or GW150914).
260 ///
261 /// In those extreme regimes this function alone is no longer sufficient; a full
262 /// strong-field treatment (including curvature information passed to `LocalSpacetime`)
263 /// is required.
264 ///
265 /// For the `characteristic_length_scale` parameter:
266 /// - In weak-field conditions, pass `0.0`. This returns exactly the same clock
267 /// rate as the classic relativistic formulation and sets the Kretschmann scalar
268 /// to zero (its default value for all ordinary navigation, GNSS, or solar-system
269 /// work).
270 /// - In strong-field conditions, supply the typical length scale (in meters) over
271 /// which the gravitational field varies significantly at the observer’s location.
272 /// This allows the library to estimate the Kretschmann scalar and activate the
273 /// intrinsic Planck-scale saturation term when curvature becomes extreme.
274 pub const fn from_potential_velocity_and_scale(
275 grav_potential_over_c2: Real, // Φ/c² (total local potential)
276 velocity: Velocity,
277 characteristic_length_scale: Real,
278 ) -> Self {
279 let alpha: Real = Self::alpha_from_weak_field_potential(grav_potential_over_c2);
280 let kretschmann: Real = Self::kretschmann_from_potential_and_scale(
281 grav_potential_over_c2,
282 characteristic_length_scale,
283 );
284 Self::from_gravitic_and_velocity(alpha, velocity, kretschmann)
285 }
286}
287
288#[cfg(feature = "wire")]
289impl LocalSpacetime {
290 /// Size of the canonical wire representation in bytes (24 bytes).
291 pub const WIRE_SIZE: usize = 24;
292
293 /// Serializes this `LocalSpacetime` snapshot into a fixed 24-byte buffer.
294 ///
295 /// All fields are stored as little-endian IEEE 754 `f64`.
296 pub fn to_wire_bytes(&self) -> [u8; Self::WIRE_SIZE] {
297 let mut buf = [0u8; Self::WIRE_SIZE];
298 buf[0..8].copy_from_slice(&self.alpha.to_le_bytes());
299 buf[8..16].copy_from_slice(&self.beta.to_le_bytes());
300 buf[16..24].copy_from_slice(&self.kretschmann.to_le_bytes());
301 buf
302 }
303
304 /// Deserializes a `LocalSpacetime` from exactly 24 bytes.
305 ///
306 /// ## Security
307 ///
308 /// Accepts any `f64` bit pattern (including `NaN`/`Inf`) to match the
309 /// type’s own invariants. Fixed size makes it immune to length-based
310 /// attacks. Safe for untrusted input.
311 pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self> {
312 if bytes.len() != Self::WIRE_SIZE {
313 return None;
314 }
315 let alpha = f64::from_le_bytes([
316 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
317 ]);
318 let beta = f64::from_le_bytes([
319 bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
320 ]);
321 let kretschmann = f64::from_le_bytes([
322 bytes[16], bytes[17], bytes[18], bytes[19], bytes[20], bytes[21], bytes[22], bytes[23],
323 ]);
324 Some(Self {
325 alpha,
326 beta,
327 kretschmann,
328 })
329 }
330}
331
332/// Quadratic polynomial that describes the accumulated difference between an
333/// observer’s proper time (the time measured by a real clock moving through
334/// spacetime) and a chosen coordinate time such as TT, TAI, or any other
335/// `Scale`.
336///
337/// The polynomial follows the classic form
338/// Δt = constant + rate·Δt + accel·(Δt)²
339/// where the three coefficients capture any fixed offset, constant drift, and
340/// quadratic acceleration of the clock. This structure is used throughout
341/// spacecraft navigation, GNSS systems, and relativistic timing pipelines to
342/// steer clocks, predict time offsets, and maintain synchronization over long
343/// durations.
344///
345/// All three coefficients are stored using the exact `TSpan` type, which
346/// guarantees 36-digit precision with no floating-point rounding errors even
347/// over centuries of integration.
348#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
349#[cfg_attr(feature = "js", derive(tsify::Tsify))]
350#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
351pub struct ClockDrift {
352 /// Constant term a₀ expressed in seconds.
353 /// This represents any fixed time offset between the observer’s proper time
354 /// and the chosen coordinate time.
355 constant: TSpan,
356
357 /// Linear drift rate a₁ expressed in seconds per second.
358 /// This term captures a steady fractional rate difference (for example, a
359 /// clock that runs consistently fast or slow).
360 rate: TSpan,
361
362 /// Quadratic acceleration term a₂ expressed in seconds per second squared.
363 /// This term accounts for any changing drift rate, such as the gradual
364 /// acceleration caused by relativistic effects or hardware aging.
365 accel: TSpan,
366}
367
368impl ClockDrift {
369 /// Creates a new `ClockDrift` polynomial from its three exact coefficients.
370 #[inline]
371 pub const fn new(constant: TSpan, rate: TSpan, accel: TSpan) -> Self {
372 Self {
373 constant,
374 rate,
375 accel,
376 }
377 }
378
379 /// The zero polynomial representing no correction at all.
380 /// Use this when the observer’s clock is already perfectly synchronized with
381 /// the chosen coordinate time.
382 pub const ZERO: Self = Self::new(TSpan::ZERO, TSpan::ZERO, TSpan::ZERO);
383
384 /// Creates a `ClockDrift` consisting of a pure constant offset.
385 /// This is the most common constructor when only a fixed time bias is known
386 /// (for example, after a one-time clock synchronization or leap-second
387 /// adjustment).
388 #[inline]
389 pub const fn from_constant(c: TSpan) -> Self {
390 Self::new(c, TSpan::ZERO, TSpan::ZERO)
391 }
392
393 /// Creates a `ClockDrift` consisting of a constant offset together with a
394 /// constant linear drift rate.
395 /// This form is very common for GNSS receivers and spacecraft clock steering,
396 /// where a steady fractional frequency offset must be corrected in addition
397 /// to any fixed bias.
398 #[inline]
399 pub const fn from_offset_and_rate(offset: TSpan, rate: TSpan) -> Self {
400 Self::new(offset, rate, TSpan::ZERO)
401 }
402
403 #[inline]
404 pub const fn constant(&self) -> &TSpan {
405 &self.constant
406 }
407
408 #[inline]
409 pub const fn rate(&self) -> &TSpan {
410 &self.rate
411 }
412
413 #[inline]
414 pub const fn accel(&self) -> &TSpan {
415 &self.accel
416 }
417
418 #[inline]
419 pub const fn set_constant(&mut self, constant: TSpan) -> &mut Self {
420 self.constant = constant;
421 self
422 // constant never affects the pre-computed big fields
423 }
424
425 #[inline]
426 pub const fn set_rate(&mut self, rate: TSpan) -> &mut Self {
427 self.rate = rate;
428 self
429 }
430
431 #[inline]
432 pub const fn set_accel(&mut self, accel: TSpan) -> &mut Self {
433 self.accel = accel;
434 self
435 }
436
437 #[inline]
438 pub const fn with_constant(self, constant: TSpan) -> Self {
439 Self::new(constant, self.rate, self.accel)
440 }
441
442 #[inline]
443 pub const fn with_rate(self, rate: TSpan) -> Self {
444 Self::new(self.constant, rate, self.accel)
445 }
446
447 #[inline]
448 pub const fn with_accel(self, accel: TSpan) -> Self {
449 Self::new(self.constant, self.rate, accel)
450 }
451
452 /// Returns the instantaneous proper-time rate `dτ/dt` (dimensionless).
453 ///
454 /// This value tells you how fast a real physical clock (such as a spacecraft
455 /// onboard clock) is advancing compared to coordinate time. A value of exactly
456 /// `1.0` means the clock runs at the normal rate. Values slightly below `1.0`
457 /// are typical when the clock is moving or sitting in a gravitational well.
458 ///
459 /// The rate includes special-relativistic velocity effects, gravitational
460 /// time dilation, and the library’s built-in Planck-scale saturation term.
461 #[inline]
462 pub const fn proper_time_rate(&self) -> Real {
463 f!(1.0) + self.rate.to_sec_f()
464 }
465
466 /// Evaluates the polynomial at the given elapsed coordinate time span.
467 ///
468 /// Returns the exact accumulated time difference (in seconds) between proper
469 /// time and coordinate time after the interval span has passed. All
470 /// arithmetic is performed with full 36-digit precision, ensuring no loss of
471 /// accuracy even for multi-year integrations.
472 pub const fn time_diff_after(&self, span: &TSpan) -> TSpan {
473 let dt_attos = span.to_attos();
474 let mut total_attos = self.constant.to_attos();
475
476 if !self.rate.is_zero() || !self.accel.is_zero() {
477 // Linear term: rate * dt
478 let rate_attos = self.rate.to_attos();
479 let rate_term = rate_attos.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
480 total_attos = total_attos.wrapping_add(rate_term);
481
482 // Quadratic term: accel * dt²
483 let accel_attos = self.accel.to_attos();
484 let accel_dt = accel_attos.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
485 let accel_term = accel_dt.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
486 total_attos = total_attos.saturating_add(accel_term);
487 }
488
489 TSpan::from_attos(total_attos)
490 }
491
492 /// Creates a `ClockDrift` directly from an observer’s velocity and total
493 /// local gravitational potential using the library’s unified master-Lagrangian
494 /// proper-time rate.
495 ///
496 /// This is the recommended high-level constructor for nearly all users. It
497 /// automatically computes the relativistic clock rate that includes both
498 /// special-relativistic velocity effects and gravitational time dilation,
499 /// then returns a `ClockDrift` that can be evaluated at any future time.
500 ///
501 /// The `characteristic_length_scale` parameter controls whether the
502 /// weak-field or strong-field formulation is used:
503 ///
504 /// - In the weak-field regime (where |Φ|/c² ≪ 1), simply pass
505 /// `characteristic_length_scale = 0.0`. This returns exactly the same
506 /// relativistic clock rate used by JPL, ESA, GNSS systems, and all modern
507 /// solar-system navigation pipelines.
508 /// - In strong-field conditions, supply a non-zero length scale (in meters)
509 /// over which the gravitational potential changes at the observer’s
510 /// location. This activates the library’s intrinsic Planck-scale saturation
511 /// term when spacetime curvature becomes extreme.
512 pub const fn from_velocity_potential_and_scale(
513 velocity_m_s: Real,
514 grav_potential_m2_s2: Real,
515 characteristic_length_scale: Real,
516 ) -> Self {
517 let phi = grav_potential_m2_s2 / C_SQUARED;
518 let velocity = Velocity::from_speed(velocity_m_s);
519 let spacetime = LocalSpacetime::from_potential_velocity_and_scale(
520 phi,
521 velocity,
522 characteristic_length_scale,
523 );
524 Self::from_local_spacetime(&spacetime)
525 }
526
527 /// Canonical low-level constructor that implements the exact intrinsic
528 /// expression from the master Lagrangian.
529 ///
530 /// This function is the single source of truth for the proper-time rate
531 /// calculation used throughout the library. Most users will never call it
532 /// directly; the high-level constructors `from_velocity_potential_and_scale`
533 /// and `from_local_spacetime` are the intended entry points.
534 ///
535 /// The internal expression is
536 /// K_eff = [δ(1 + x) + x(1−δ)²] / (1 + x)
537 /// where δ = α²(1−β²) and x = ℓ_Pl⁴ 𝒦. The returned rate offset is then
538 /// applied as a linear term in the `ClockDrift` polynomial.
539 pub const fn from_unified_proper_time_rate(u: Real, kretschmann: Real) -> Self {
540 let delta = u.max(f!(0.0));
541 let x = PLANCK_LENGTH_4 * kretschmann.max(f!(0.0));
542
543 let one_minus_delta = f!(1.0) - delta;
544 let num = delta * (f!(1.0) + x) + x * (one_minus_delta * one_minus_delta);
545 let k_eff = num / (f!(1.0) + x);
546
547 let rate_factor = sqrt(k_eff).max(f!(0.0));
548 let rate_offset = rate_factor - f!(1.0);
549
550 Self::from_offset_and_rate(TSpan::ZERO, TSpan::from_sec_f(rate_offset))
551 }
552
553 /// Creates a `ClockDrift` from a fully resolved `LocalSpacetime` snapshot.
554 ///
555 /// This is the canonical high-level entry point when you already hold a
556 /// `LocalSpacetime` object containing the gravitational lapse factor α, the
557 /// local velocity β, and the Kretschmann scalar. It internally computes the
558 /// unified proper-time rate and packages the result as a `ClockDrift`
559 /// polynomial ready for evaluation at any future time.
560 #[inline]
561 pub const fn from_local_spacetime(spacetime: &LocalSpacetime) -> Self {
562 let u = spacetime.alpha * spacetime.alpha * (f!(1.0) - spacetime.beta * spacetime.beta);
563 Self::from_unified_proper_time_rate(u, spacetime.kretschmann)
564 }
565}
566
567#[cfg(feature = "wire")]
568impl ClockDrift {
569 /// Current wire format version.
570 pub const WIRE_VERSION: u8 = 1;
571
572 /// Size of the canonical wire representation in bytes.
573 pub const WIRE_SIZE: usize = 3 * TSpan::WIRE_SIZE; // 3 × 17 = 51
574
575 /// Serializes this `ClockDrift` polynomial into a fixed buffer.
576 ///
577 /// The layout is the concatenation of the three `TSpan` fields.
578 pub fn to_wire_bytes(&self) -> [u8; Self::WIRE_SIZE] {
579 let mut buf = [0u8; Self::WIRE_SIZE];
580 let c = self.constant.to_wire_bytes();
581 let r = self.rate.to_wire_bytes();
582 let a = self.accel.to_wire_bytes();
583
584 buf[0..TSpan::WIRE_SIZE].copy_from_slice(&c);
585 buf[TSpan::WIRE_SIZE..2 * TSpan::WIRE_SIZE].copy_from_slice(&r);
586 buf[2 * TSpan::WIRE_SIZE..].copy_from_slice(&a);
587 buf
588 }
589
590 /// Deserializes a `ClockDrift` from exactly `WIRE_SIZE` bytes of wire data.
591 ///
592 /// Returns `None` if any nested `TSpan` fails validation or if the version
593 /// byte is unknown.
594 ///
595 /// ## Security
596 ///
597 /// Composes the safety guarantees of [`TSpan::from_wire_bytes`].
598 /// Fixed size and layered validation make it safe for untrusted input.
599 pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self> {
600 if bytes.len() != Self::WIRE_SIZE {
601 return None;
602 }
603
604 if bytes[0] != Self::WIRE_VERSION {
605 return None;
606 }
607
608 let constant = TSpan::from_wire_bytes(&bytes[0..TSpan::WIRE_SIZE])?;
609 let rate = TSpan::from_wire_bytes(&bytes[TSpan::WIRE_SIZE..2 * TSpan::WIRE_SIZE])?;
610 let accel = TSpan::from_wire_bytes(&bytes[2 * TSpan::WIRE_SIZE..])?;
611
612 Some(Self::new(constant, rate, accel))
613 }
614}