Skip to main content

deep_time/physics/
drift.rs

1//! Quadratic polynomial for relativistic corrections, clock drift, and custom timescale steering.
2//!
3//! Used to model the accumulated difference between Proper time (τ)
4//! and a coordinate time such as TT (or any other `Scale`).
5//!
6//! Information on the underlying physical model (the master Lagrangian, different
7//! regimes of behavior, and its relationship to general relativity) can be found
8//! [here](https://github.com/ragardner/deep-time/blob/main/docs/relativity.md).
9
10use crate::{
11    ATTOS_PER_SEC_I128, C_SQUARED, Dt, PLANCK_LENGTH_4, Real, Scale, Spacetime, Velocity, sqrt,
12};
13
14/// Quadratic polynomial that describes the accumulated difference between an
15/// observer’s proper time (the time measured by a real clock moving through
16/// spacetime) and a chosen coordinate time such as TT, TAI, or any other
17/// `Scale`.
18///
19/// The polynomial follows the classic form  
20/// Δt = constant + rate·Δt + accel·(Δt)²  
21/// where the three coefficients capture any fixed offset, constant drift, and
22/// quadratic acceleration of the clock. This structure is used throughout
23/// spacecraft navigation, GNSS systems, and relativistic timing pipelines to
24/// steer clocks, predict time offsets, and maintain synchronization over long
25/// durations.
26///
27/// All three coefficients are stored using [`Dt`].
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29#[cfg_attr(feature = "tsify", derive(tsify::Tsify))]
30#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct Drift {
32    /// Constant term a₀ expressed in seconds.  
33    /// This represents any fixed time offset between the observer’s proper time
34    /// and the chosen coordinate time.
35    pub constant: Dt,
36
37    /// Linear drift rate a₁ expressed in seconds per second.  
38    /// This term captures a steady fractional rate difference (for example, a
39    /// clock that runs consistently fast or slow).
40    pub rate: Dt,
41
42    /// Quadratic acceleration term a₂ expressed in seconds per second squared.  
43    /// This term accounts for any changing drift rate, such as the gradual
44    /// acceleration caused by relativistic effects or hardware aging.
45    pub accel: Dt,
46}
47
48impl Drift {
49    /// Creates a new `Drift` polynomial from its three coefficients.
50    #[inline]
51    pub const fn new(constant: Dt, rate: Dt, accel: Dt) -> Drift {
52        Self {
53            constant,
54            rate,
55            accel,
56        }
57    }
58
59    /// The zero polynomial representing no correction at all.
60    ///
61    /// Use this when the observer’s clock is already perfectly synchronized with
62    /// the chosen coordinate time.
63    pub const ZERO: Self = Self::new(Dt::ZERO, Dt::ZERO, Dt::ZERO);
64
65    /// Creates a [`Drift`] consisting of a pure constant offset.
66    ///
67    /// This is the most common constructor when only a fixed time bias is known
68    /// (for example, after a one-time clock synchronization or leap-second
69    /// adjustment).
70    #[inline]
71    pub const fn from_constant(c: Dt) -> Drift {
72        Self::new(c, Dt::ZERO, Dt::ZERO)
73    }
74
75    /// Creates a [`Drift`] consisting of a constant offset together with a
76    /// constant linear drift rate.  
77    ///
78    /// This form is very common for GNSS receivers and spacecraft clock steering,
79    /// where a steady fractional frequency offset must be corrected in addition
80    /// to any fixed bias.
81    #[inline]
82    pub const fn from_offset_and_rate(offset: Dt, rate: Dt) -> Drift {
83        Self::new(offset, rate, Dt::ZERO)
84    }
85
86    /// Returns the instantaneous proper-time rate `dτ/dt` (dimensionless).
87    ///
88    /// This value tells you how fast a real physical clock (such as a spacecraft
89    /// onboard clock) is advancing compared to coordinate time. A value of
90    /// `1.0` means the clock runs at the normal rate. Values slightly below `1.0`
91    /// are typical when the clock is moving or sitting in a gravitational well.
92    ///
93    /// The rate includes special-relativistic velocity effects, gravitational
94    /// time dilation, and the library’s built-in Planck-scale saturation term.
95    #[inline]
96    pub const fn proper_time_rate(&self) -> Real {
97        f!(1.0) + self.rate.to_sec_f()
98    }
99
100    /// Evaluates the polynomial at the given elapsed coordinate time span.  
101    ///
102    /// Returns the accumulated time difference (in seconds) between proper
103    /// time and coordinate time after the interval span has passed.
104    pub const fn time_diff_after(&self, span: &Dt) -> Dt {
105        let dt_attos = span.to_attos();
106        let mut total_attos = self.constant.to_attos();
107
108        if !self.rate.is_zero() || !self.accel.is_zero() {
109            // Linear term: rate * dt
110            let rate_attos: i128 = self.rate.to_attos();
111            let rate_term = rate_attos.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
112            total_attos = total_attos.wrapping_add(rate_term);
113
114            // Quadratic term: accel * dt²
115            let accel_attos: i128 = self.accel.to_attos();
116            let accel_dt = accel_attos.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
117            let accel_term = accel_dt.wrapping_mul(dt_attos) / ATTOS_PER_SEC_I128;
118            total_attos = total_attos.saturating_add(accel_term);
119        }
120
121        crate::dt!(total_attos)
122    }
123
124    /// Evaluates the deterministic relativistic/polynomial correction **and**
125    /// adds a user-supplied stochastic offset (in seconds).
126    ///
127    /// This is the single production method for realistic stochastic clock
128    /// modeling. In real mission pipelines the deterministic part (this
129    /// polynomial) is kept perfectly clean; stochastic noise (white phase noise,
130    /// random-walk frequency noise, Monte-Carlo realizations, Kalman process
131    /// noise, measured clock residuals, etc.) is added at evaluation time.
132    ///
133    /// Pass `0.0` (or simply call the original `time_diff_after`) when you
134    /// want purely deterministic behavior.
135    #[inline]
136    pub fn time_diff_after_with_noise(&self, span: &Dt, stochastic_offset_sec: Real) -> Dt {
137        self.time_diff_after(span).add(Dt::from_sec_f(
138            stochastic_offset_sec,
139            Scale::TAI,
140            Scale::TAI,
141        ))
142    }
143
144    /// Creates a `Drift` directly from an observer’s velocity and total
145    /// local gravitational potential using the library’s unified master-Lagrangian
146    /// proper-time rate.  
147    ///
148    /// It automatically computes the relativistic clock rate that includes both
149    /// special-relativistic velocity effects and gravitational time dilation,
150    /// then returns a [`Drift`] that can be evaluated at any future time.
151    ///
152    /// The `characteristic_length_scale` parameter controls whether the
153    /// weak-field or strong-field formulation is used:
154    ///
155    /// - In the weak-field regime (where |Φ|/c² ≪ 1), simply pass
156    ///   `characteristic_length_scale = 0.0`. This returns the same
157    ///   relativistic clock rate used by JPL, ESA, GNSS systems, and all modern
158    ///   solar-system navigation pipelines.
159    /// - In strong-field conditions, supply a non-zero length scale (in meters)
160    ///   over which the gravitational potential changes at the observer’s
161    ///   location. This activates the library’s intrinsic Planck-scale saturation
162    ///   term when spacetime curvature becomes extreme.
163    pub const fn from_velocity_potential_and_scale(
164        velocity_m_s: Real,
165        grav_potential_m2_s2: Real,
166        characteristic_length_scale: Real,
167    ) -> Drift {
168        let phi = grav_potential_m2_s2 / C_SQUARED;
169        let velocity = Velocity::from_speed(velocity_m_s);
170        let spacetime = Spacetime::from_potential_velocity_and_scale(
171            phi,
172            velocity,
173            characteristic_length_scale,
174        );
175        Self::from_spacetime(&spacetime)
176    }
177
178    /// Canonical low-level constructor that implements the library's general
179    /// relativity formula.
180    ///
181    /// This function is the single source of truth for the proper-time rate
182    /// calculation used throughout the library. Most users will never call it
183    /// directly; the high-level constructors `from_velocity_potential_and_scale`
184    /// and `from_spacetime` are the intended entry points.
185    ///
186    /// The internal expression is  
187    /// K_eff = [δ(1 + x) + x(1−δ)²] / (1 + x)  
188    /// where δ = α²(1−β²) and x = ℓ_Pl⁴ 𝒦.
189    ///
190    /// The returned rate offset is then applied as a linear term in the `Drift`
191    /// polynomial.
192    pub const fn from_unified_proper_time_rate(u: Real, kretschmann: Real) -> Drift {
193        let delta = u.max(f!(0.0));
194        let x = PLANCK_LENGTH_4 * kretschmann.max(f!(0.0));
195
196        let one_minus_delta = f!(1.0) - delta;
197        let num = delta * (f!(1.0) + x) + x * (one_minus_delta * one_minus_delta);
198        let k_eff = num / (f!(1.0) + x);
199
200        let rate_factor = sqrt(k_eff).max(f!(0.0));
201        let rate_offset = rate_factor - f!(1.0);
202
203        Self::from_offset_and_rate(
204            Dt::ZERO,
205            Dt::from_sec_f(rate_offset, Scale::TAI, Scale::TAI),
206        )
207    }
208
209    /// Creates a `Drift` from a fully resolved `Spacetime` snapshot.  
210    ///
211    /// This is the canonical high-level entry point when you already hold a
212    /// `Spacetime` object containing the gravitational lapse factor α, the
213    /// local velocity β, and the Kretschmann scalar. It internally computes the
214    /// unified proper-time rate and packages the result as a `Drift`
215    /// polynomial ready for evaluation at any future time.
216    #[inline]
217    pub const fn from_spacetime(spacetime: &Spacetime) -> Drift {
218        let u = spacetime.alpha * spacetime.alpha * (f!(1.0) - spacetime.beta * spacetime.beta);
219        Self::from_unified_proper_time_rate(u, spacetime.kretschmann)
220    }
221}
222
223impl Dt {
224    /// Builds a clock-drift model in which this [`Dt`] is treated as the
225    /// initial fixed time difference between the observer’s proper time and
226    /// the chosen coordinate time.
227    ///
228    /// In practice you often compute or measure a one-time offset (for example
229    /// after a clock synchronization or a leap-second jump) and then want to
230    /// combine it with a steady rate difference and any quadratic change.
231    /// This method lets you do that directly from a [`Dt`] without having to
232    /// call the more verbose [`Drift::new`].
233    ///
234    /// The other two arguments describe how the difference between the two
235    /// clocks will evolve:
236    /// - `rate` — the constant fractional speed difference (how much faster or
237    ///   slower one clock runs compared with the other).
238    /// - `accel` — how quickly that speed difference itself is changing (for
239    ///   example because the spacecraft is moving through a varying gravitational
240    ///   field).
241    ///
242    /// See [`Drift`] and [`Drift::from_offset_and_rate`] for more background on
243    /// why these three numbers are used to model real clocks.
244    #[inline]
245    pub const fn to_drift_as_constant(self, rate: Dt, accel: Dt) -> Drift {
246        Drift::new(self, rate, accel)
247    }
248
249    /// Builds a clock-drift model in which this [`Dt`] supplies the constant
250    /// fractional rate difference between the observer’s proper time and the
251    /// chosen coordinate time.
252    ///
253    /// If you have already calculated (or measured) a steady rate offset as a
254    /// [`Dt`], you can use this method to attach an initial time offset and a
255    /// quadratic term and obtain a complete [`Drift`] polynomial.
256    ///
257    /// Physically, the rate term captures the fact that two clocks that are
258    /// moving at different velocities or sitting at different gravitational
259    /// potentials will accumulate a steadily growing time difference. The
260    /// other two parameters let you also describe any starting bias and any
261    /// change in that rate over time.
262    ///
263    /// See the documentation on [`Drift`] for the meaning of the three
264    /// coefficients in a relativistic timing context.
265    #[inline]
266    pub const fn to_drift_as_rate(self, constant: Dt, accel: Dt) -> Drift {
267        Drift::new(constant, self, accel)
268    }
269
270    /// Builds a clock-drift model in which this [`Dt`] supplies the quadratic
271    /// term that describes how the rate difference itself is changing.
272    ///
273    /// Some situations (a spacecraft on a highly elliptical orbit, a clock
274    /// whose frequency is aging, or a trajectory that takes it through regions
275    /// of changing gravitational potential) cause the *rate* at which two
276    /// clocks diverge to change over time. If you have computed that changing
277    /// rate as a [`Dt`], this method lets you combine it with an initial offset
278    /// and a base rate to form a full [`Drift`].
279    ///
280    /// The other two arguments are:
281    /// - `constant` — any fixed time bias present at the start.
282    /// - `rate` — the base fractional rate difference that will itself be
283    ///   modified by the quadratic term supplied by `self`.
284    ///
285    /// See [`Drift`] for more explanation of why a quadratic model is used for
286    /// relativistic clock predictions.
287    #[inline]
288    pub const fn to_drift_as_accel(self, constant: Dt, rate: Dt) -> Drift {
289        Drift::new(constant, rate, self)
290    }
291
292    /// Advances this `Dt` by the given elapsed duration while applying the relativistic proper-time correction
293    /// derived from the supplied `Spacetime` model.
294    ///
295    /// - This method is intended for simulation of remote clocks (e.g., Earth time as observed from a spacecraft).
296    /// - For a local hardware proper-time clock, use the plain `add` methods instead.
297    #[inline]
298    pub const fn adjusted_advance(&mut self, elapsed: &Dt, spacetime: &Spacetime) {
299        let dtau = elapsed.add(Drift::from_spacetime(spacetime).time_diff_after(elapsed));
300        *self = self.add(dtau);
301    }
302
303    /// Advances this `Dt` by the given elapsed duration while applying the relativistic proper-time correction
304    /// from a pre-computed `Drift` value.
305    ///
306    /// - This is an optimized variant of [`Dt::adjusted_advance`](../struct.Dt.html#method.adjusted_advance)
307    ///   for callers that already hold a [`Drift`] instance.
308    /// - This method is intended for simulation of remote clocks (e.g., Earth time as observed from a spacecraft).
309    /// - For a local hardware proper-time clock, use the plain `add` methods instead.
310    #[inline]
311    pub const fn adjusted_advance_using_drift(&mut self, elapsed: &Dt, drift: &Drift) {
312        let dtau = elapsed.add(drift.time_diff_after(elapsed));
313        *self = self.add(dtau);
314    }
315
316    /// Converts this instant to any other [`Scale`] while applying an exact quadratic relativistic
317    /// or clock-drift correction defined by a [`Drift`] model relative to a reference instant.
318    pub const fn convert_using_drift(self, reference: Dt, drift: &Drift) -> Dt {
319        let span = self.to_diff_raw(reference);
320        let correction = drift.time_diff_after(&span);
321        self.add(correction)
322    }
323
324    /// Performs the inverse conversion of [`Dt::convert_using_drift`], recovering the original proper
325    /// time on the source clock scale.
326    ///
327    /// A fixed-point iteration (at most 16 steps) is used to solve the implicit equation. For the common
328    /// case of a pure constant offset the function returns immediately without iteration.
329    pub const fn convert_back_using_drift(self, reference: Dt, drift: &Drift) -> Dt {
330        if drift.rate.is_zero() && drift.accel.is_zero() {
331            return self.sub(drift.constant);
332        }
333        let mut guess = self;
334        let mut i = 0u32;
335        while i < 16 {
336            let span = guess.to_diff_raw(reference);
337            let correction = drift.time_diff_after(&span);
338            guess = self.sub(correction);
339            i += 1;
340        }
341        guess
342    }
343}
344
345#[cfg(feature = "wire")]
346impl Drift {
347    /// Current wire format version.
348    pub const WIRE_VERSION: u8 = 1;
349
350    /// Size of the canonical wire representation in bytes.
351    pub const WIRE_SIZE: usize = 3 * Dt::WIRE_SIZE;
352
353    /// Serializes this [`Drift`] polynomial into a fixed buffer.
354    ///
355    /// The layout is the concatenation of the three `Dt` fields.
356    pub fn to_wire_bytes(&self) -> [u8; Self::WIRE_SIZE] {
357        let mut buf = [0u8; Self::WIRE_SIZE];
358        let c = self.constant.to_wire_bytes();
359        let r = self.rate.to_wire_bytes();
360        let a = self.accel.to_wire_bytes();
361
362        buf[0..Dt::WIRE_SIZE].copy_from_slice(&c);
363        buf[Dt::WIRE_SIZE..2 * Dt::WIRE_SIZE].copy_from_slice(&r);
364        buf[2 * Dt::WIRE_SIZE..].copy_from_slice(&a);
365        buf
366    }
367
368    /// Deserializes a [`Drift`] from exactly `WIRE_SIZE` bytes of wire data.
369    ///
370    /// Returns `None` if any nested `Dt` fails validation or if the version
371    /// byte is unknown.
372    ///
373    /// ## Security
374    ///
375    /// Composes the safety guarantees of
376    /// [`from_wire_bytes`](docs.rs/deep-time/latest/deep_time/struct.Dt.html#method.from_wire_bytes).
377    ///
378    /// Fixed size and layered validation make it safe for untrusted input.
379    pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self> {
380        if bytes.len() != Self::WIRE_SIZE {
381            return None;
382        }
383
384        if bytes[0] != Self::WIRE_VERSION {
385            return None;
386        }
387
388        let constant = Dt::from_wire_bytes(&bytes[0..Dt::WIRE_SIZE])?;
389        let rate = Dt::from_wire_bytes(&bytes[Dt::WIRE_SIZE..2 * Dt::WIRE_SIZE])?;
390        let accel = Dt::from_wire_bytes(&bytes[2 * Dt::WIRE_SIZE..])?;
391
392        Some(Self::new(constant, rate, accel))
393    }
394}