deep_time/physics/light_time.rs
1use crate::{
2 C, C_SQUARED, Drift, Dt, Position, Real, Scale, Spacetime, TWO_GM_SUN_OVER_C3, Velocity, log,
3};
4
5impl Dt {
6 /// Shapiro gravitational time scale for the Sun (`2 G M_☉ / c³`).
7 ///
8 /// Recommended value for the Sun when building the `bodies` slice passed to
9 /// [`Observer::shapiro_delay`], [`Observer::shapiro_delay`],
10 /// and related methods.
11 pub const SHAPIRO_SOLAR: Self = Self::from_sec_f(TWO_GM_SUN_OVER_C3, Scale::TAI);
12
13 /// Creates the Shapiro delay scale for an arbitrary central body
14 /// from its standard gravitational parameter `GM` (μ) in m³ s⁻².
15 ///
16 /// This produces the coefficient used in the Shapiro gravitational time delay
17 /// formula. It is the recommended way to create a custom Shapiro scale for
18 /// planets, stars, or other massive bodies.
19 ///
20 /// The returned value is intended to be used for the `bodies` parameter
21 /// when calling [`Observer::shapiro_delay`] or
22 /// [`Observer::shapiro_delay`].
23 #[inline]
24 pub const fn shapiro_from_grav_param(gm: Real) -> Dt {
25 let secs = 2.0 * gm / (C * C_SQUARED);
26 Self::from_sec_f(secs, Scale::TAI)
27 }
28
29 /// Creates an [`Observer`] using this time value along with the
30 /// provided position, velocity, and gravitational information.
31 ///
32 /// An [`Observer`] represents a complete snapshot of an observer
33 /// (spacecraft, ground station, planet, person, etc.) at a
34 /// specific moment.
35 ///
36 /// It bundles together the time, position, velocity, and local
37 /// gravitational environment so that relativistic calculations
38 /// (light time, clock rates, Shapiro delay, etc.) can be performed.
39 ///
40 /// This method is a convenience constructor. It is useful when you
41 /// already have a [`Dt`] (a time value) and want to build an
42 /// [`Observer`] directly from it.
43 ///
44 /// ## Parameters
45 ///
46 /// - `position`: The observer’s position in meters (typically expressed
47 /// in a barycentric or heliocentric frame).
48 /// - `velocity`: The observer’s velocity in meters per second.
49 /// - `grav_potential_m2_s2`: The total Newtonian gravitational potential
50 /// (Φ) at the observer’s location, in m²/s². This is usually negative
51 /// for bound orbits and is the sum of contributions from the Sun and
52 /// planets.
53 /// - `characteristic_length_scale`: A length scale (in meters) over which
54 /// gravity varies significantly at this location. Use `0.0` for normal
55 /// solar-system and weak-field cases. Only provide a non-zero value when
56 /// working in strong gravitational fields.
57 ///
58 /// ## Examples
59 ///
60 /// ```
61 /// use deep_time::{Dt, Position, Spacetime, Velocity};
62 ///
63 /// let bodies = [
64 /// (Position::from_au(0.0, 0.0, 0.0), 1.3271244e20), // Sun
65 /// (Position::from_au(1.0, 0.0, 0.0), 3.9860044e14), // Earth
66 /// (Position::from_au(1.00257, 0.0, 0.0), 4.9048695e12), // Moon
67 /// ];
68 ///
69 /// let position = Position::from_au(1.001, 0.001, 0.0); // e.g. spacecraft, asteroid, etc.
70 ///
71 /// let grav_potential = Spacetime::grav_potential_from_point_masses(
72 /// position,
73 /// bodies.iter().copied(),
74 /// );
75 ///
76 /// let t = Dt::span_f(1234.5);
77 ///
78 /// let state = t.to_observer(
79 /// Position::ZERO,
80 /// Velocity::ZERO,
81 /// grav_potential,
82 /// 0.0, // normal solar-system use
83 /// );
84 /// ```
85 #[inline]
86 pub const fn to_observer(
87 self,
88 position: Position,
89 velocity: Velocity,
90 grav_potential_m2_s2: Real,
91 characteristic_length_scale: Real,
92 ) -> Observer {
93 Observer {
94 time: self,
95 position,
96 velocity,
97 grav_potential_m2_s2,
98 characteristic_length_scale,
99 }
100 }
101}
102
103/// An observer at a specific instant.
104///
105/// Combines time, position, velocity, and local gravitational
106/// information. It is the main input type used by relativistic light-time
107/// methods in this library.
108#[derive(Clone, Copy, Debug, PartialEq)]
109#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
110#[cfg_attr(feature = "tsify", derive(tsify::Tsify))]
111pub struct Observer {
112 /// The time of this observer.
113 ///
114 /// Any [`Scale`] is accepted. This time is treated as coordinate time.
115 pub time: Dt,
116
117 /// Position of the observer in meters.
118 ///
119 /// Typically expressed in a barycentric (solar-system barycenter) or
120 /// heliocentric frame, depending on the application.
121 pub position: Position,
122
123 /// Velocity of the observer in meters per second.
124 pub velocity: Velocity,
125
126 /// Newtonian gravitational potential Φ at the observer’s location
127 /// (in m² s⁻²).
128 ///
129 /// This value is usually negative for bound orbits. It should normally
130 /// include contributions from the Sun and all relevant planets.
131 pub grav_potential_m2_s2: Real,
132
133 /// Characteristic length scale (in meters) over which the gravitational
134 /// field varies significantly at this location.
135 ///
136 /// - Use `0.0` (the default) for all solar-system, GNSS, and weak-field
137 /// applications.
138 /// - Provide a non-zero value only when working in strong gravitational
139 /// fields (e.g. near neutron stars or black holes), where the library’s
140 /// higher-order curvature terms become relevant.
141 pub characteristic_length_scale: Real,
142}
143
144impl Observer {
145 /// Creates a new `Observer` for typical solar-system, GNSS,
146 /// or weak-field use.
147 ///
148 /// This is the recommended constructor for most applications.
149 /// It sets the `characteristic_length_scale` to `0.0`, which disables
150 /// higher-order curvature terms in the proper-time model.
151 ///
152 /// ## Parameters
153 ///
154 /// - `time`: The time of the observer.
155 /// - `position`: Position in meters (usually barycentric or heliocentric).
156 /// - `velocity`: Velocity in m/s.
157 /// - `grav_potential_m2_s2`: Newtonian gravitational potential Φ
158 /// at the location (in m²/s²).
159 #[inline]
160 pub const fn new(
161 time: Dt,
162 position: Position,
163 velocity: Velocity,
164 grav_potential_m2_s2: Real,
165 ) -> Observer {
166 Self {
167 time,
168 position,
169 velocity,
170 grav_potential_m2_s2,
171 characteristic_length_scale: 0.0,
172 }
173 }
174
175 /// Returns the instantaneous proper-time rate `dτ/dt` for this observer.
176 ///
177 /// This value indicates how fast a physical clock located at this observer
178 /// would advance relative to the time used by this `Observer`.
179 /// A returned value of `1.0` means the clock advances at the same rate
180 /// as the observer's time coordinate. Values are typically slightly different
181 /// from `1.0` due to the effects of velocity and gravitational potential.
182 ///
183 /// This rate is computed using the library’s unified proper-time model.
184 /// It is used internally for light-time corrections and Doppler calculations.
185 #[inline]
186 pub const fn proper_time_rate(&self) -> Real {
187 Spacetime::from_potential_velocity_and_scale(
188 self.grav_potential_m2_s2 / C_SQUARED,
189 self.velocity,
190 self.characteristic_length_scale,
191 )
192 .proper_time_rate()
193 }
194
195 /// Returns the ratio of proper time rates between the receiver and transmitter
196 /// for a one-way signal.
197 ///
198 /// This method computes:
199 ///
200 /// ```text
201 /// ratio = rx.proper_time_rate() / self.proper_time_rate()
202 /// ```
203 ///
204 /// ### Interpretation
205 ///
206 /// - A value of `1.0` indicates that both clocks run at the same rate.
207 /// - A value **less than `1.0`** means the receiver’s clock runs slower than
208 /// the transmitter’s clock. The receiver will observe a lower frequency
209 /// than was emitted.
210 /// - A value **greater than `1.0`** means the receiver’s clock runs faster
211 /// than the transmitter’s clock. The receiver will observe a higher frequency
212 /// than was emitted.
213 ///
214 /// The ratio captures the combined effect of special-relativistic time dilation
215 /// (due to velocity) and general-relativistic gravitational time dilation.
216 ///
217 /// ### Typical Usage (One-Way)
218 ///
219 /// This ratio is often combined with the classical kinematic Doppler term
220 /// to estimate the total one-way frequency shift:
221 ///
222 /// ```text
223 /// approximate_frequency_shift ≈ ratio * (1 - v_radial / C)
224 /// ```
225 ///
226 /// where `v_radial` is the radial velocity (positive when the receiver is
227 /// receding).
228 ///
229 /// ### Two-Way Usage
230 ///
231 /// For round-trip (two-way) measurements, square the one-way ratio:
232 ///
233 /// ```rust
234 /// use deep_time::{Dt, Observer, Position, Spacetime, Velocity};
235 ///
236 /// let bodies = [
237 /// (Position::from_au(0.0, 0.0, 0.0), 1.3271244e20), // Sun
238 /// (Position::from_au(1.0, 0.0, 0.0), 3.9860044e14), // Earth
239 /// ];
240 ///
241 /// let tx_pos = Position::from_au(1.0, 0.0, 0.0);
242 /// let rx_pos = Position::from_au(1.00257, 0.0, 0.0);
243 ///
244 /// let grav_potential_tx = Spacetime::grav_potential_from_point_masses(tx_pos, bodies.iter().copied());
245 /// let grav_potential_rx = Spacetime::grav_potential_from_point_masses(rx_pos, bodies.iter().copied());
246 ///
247 /// let transmitter = Observer::new(
248 /// Dt::span_f(0.0),
249 /// tx_pos,
250 /// Velocity::ZERO,
251 /// grav_potential_tx,
252 /// );
253 ///
254 /// let receiver = Observer::new(
255 /// Dt::span_f(0.0),
256 /// rx_pos,
257 /// Velocity::from_speed(800.0),
258 /// grav_potential_rx,
259 /// );
260 ///
261 /// let one_way_ratio = transmitter.relativistic_clock_rate_ratio(receiver);
262 /// let two_way_ratio = one_way_ratio * one_way_ratio;
263 /// ```
264 ///
265 /// **Note:** Squaring the one-way ratio is a common first-order approximation.
266 /// For higher precision (especially during flybys or when uplink and downlink
267 /// geometries differ significantly), consider using
268 /// [`round_trip_light_time_correction`](Self::round_trip_light_time_correction)
269 /// instead.
270 ///
271 /// This pattern is commonly used when correcting two-way Doppler (range-rate)
272 /// data for relativistic clock effects.
273 ///
274 /// ### Limitations
275 ///
276 /// - This method only accounts for the **difference in clock rates** between
277 /// the two ends.
278 /// - It does **not** include Shapiro delay or higher-order relativistic effects
279 /// on signal propagation.
280 /// - The combination with classical Doppler shown above is a first-order
281 /// approximation.
282 ///
283 /// ## Parameters
284 ///
285 /// - `self` — Transmitter state at the time of transmission.
286 /// - `rx` — Receiver state at the approximate time of reception.
287 ///
288 /// ## Examples
289 ///
290 /// ```rust
291 /// use deep_time::{Dt, Observer, Position, Spacetime, Velocity, constants::C};
292 ///
293 /// let bodies = [
294 /// (Position::from_au(0.0, 0.0, 0.0), 1.3271244e20), // Sun
295 /// (Position::from_au(1.0, 0.0, 0.0), 3.9860044e14), // Earth
296 /// ];
297 ///
298 /// let tx_pos = Position::from_au(1.0, 0.0, 0.0);
299 /// let rx_pos = Position::from_au(1.002, 0.0, 0.0);
300 ///
301 /// let grav_potential_tx = Spacetime::grav_potential_from_point_masses(tx_pos, bodies.iter().copied());
302 /// let grav_potential_rx = Spacetime::grav_potential_from_point_masses(rx_pos, bodies.iter().copied());
303 ///
304 /// let transmitter = Observer::new(
305 /// Dt::span_f(0.0),
306 /// tx_pos,
307 /// Velocity::ZERO,
308 /// grav_potential_tx,
309 /// );
310 ///
311 /// // Receiver receding at ~1.2 km/s (example spacecraft)
312 /// let receiver = Observer::new(
313 /// Dt::span_f(0.0),
314 /// rx_pos,
315 /// Velocity::from_speed(1200.0),
316 /// grav_potential_rx,
317 /// );
318 ///
319 /// let ratio = transmitter.relativistic_clock_rate_ratio(receiver);
320 ///
321 /// let v_radial = 1200.0; // m/s, positive if receding
322 /// let classical_doppler = 1.0 - v_radial / C;
323 ///
324 /// let approx_frequency_shift = ratio * classical_doppler;
325 /// ```
326 #[inline]
327 pub const fn relativistic_clock_rate_ratio(&self, rx: Observer) -> Real {
328 rx.proper_time_rate() / self.proper_time_rate()
329 }
330
331 /// Computes the combined one-way relativistic correction for a signal
332 /// traveling from this observer (the transmitter) to a receiver.
333 ///
334 /// This value is the **total extra time** you should add to the Newtonian
335 /// geometric light travel time (`distance / speed of light`). It includes
336 /// **two** separate relativistic effects:
337 ///
338 /// 1. The gravitational propagation delay (Shapiro delay) caused by the
339 /// Sun and other bodies slowing the signal.
340 /// 2. The differential clock-rate correction caused by the transmitter
341 /// and receiver having slightly different proper-time rates (due to
342 /// their velocities and gravitational potentials).
343 ///
344 /// In other words, this method gives you **propagation delay + clock-rate
345 /// correction** in one convenient call.
346 ///
347 /// **Important:** This is a convenience method. It is provided so you can
348 /// get the full one-way relativistic correction quickly. If you need
349 /// strict separation of the two effects (for example, to apply them at
350 /// different stages of your calculation), call
351 /// [`Self::shapiro_delay`] and [`Self::compute_differential_clock_correction`]
352 /// individually and add the results yourself.
353 ///
354 /// ## When to use this method
355 ///
356 /// Use this when you need the complete relativistic correction for
357 /// one-way light time in a single step — for example when:
358 /// - Computing high-precision one-way range or Doppler observables
359 /// - Building simplified navigation or orbit determination models
360 /// - You want the total effect without manually combining the pieces
361 ///
362 /// ## The `bodies` parameter – which masses to include
363 ///
364 /// Pass a slice of `(shapiro_coefficient, body_position)` pairs:
365 ///
366 /// - `shapiro_coefficient`: How strong the delay from this body should be.
367 /// It equals `2GM / c³`. Use [`Dt::SHAPIRO_SOLAR`] for the Sun, or
368 /// [`Dt::shapiro_from_grav_param(gm)`] for any other body.
369 /// - `body_position`: Where the center of that body is located at the
370 /// relevant time.
371 ///
372 /// **Important: All positions must be measured the same way**
373 ///
374 /// The transmitter position (`self.position`), the receiver position
375 /// (`rx.position`), and every `body_position` you provide must all be
376 /// measured from the **same point in space**, and they must all use
377 /// the **same directions** for their X, Y, and Z axes.
378 ///
379 /// For example, if your transmitter position is measured from the center
380 /// of the solar system, then the receiver and body positions must also
381 /// be measured from the center of the solar system using the same
382 /// pointing directions for the coordinate axes.
383 ///
384 /// In most solar-system work, people use positions from JPL ephemerides
385 /// (which are measured from the center of the solar system).
386 ///
387 /// Pass an empty slice (`&[]`) to turn off the Shapiro (gravitational)
388 /// part of the correction.
389 ///
390 /// ## Parameters
391 ///
392 /// * `rx` — Receiver state at the approximate time the signal arrives.
393 /// * `bodies` — List of bodies that should contribute to the gravitational
394 /// propagation delay.
395 ///
396 /// ## Returns
397 ///
398 /// The total one-way relativistic correction (Shapiro propagation delay
399 /// plus differential clock-rate correction), expressed as a `Dt` in the
400 /// same time scale as `self.time`.
401 ///
402 /// This value should normally be **added** to the Newtonian geometric
403 /// light time.
404 pub const fn one_way_relativistic_delay(&self, rx: Observer, bodies: &[(Dt, Position)]) -> Dt {
405 let prop = self.shapiro_delay(rx, bodies);
406 let drift = self.compute_differential_clock_correction(rx);
407 prop.add(drift)
408 }
409
410 /// Iteratively solves the one-way light-time equation in coordinate time,
411 /// including relativistic propagation corrections, until convergence.
412 ///
413 /// This solver computes the receive epoch `t_rx` such that:
414 ///
415 /// ```text
416 /// t_rx = t_tx + |r_rx(t_rx) − r_tx(t_tx)| / c + Δt_shapiro(t_tx, t_rx)
417 /// ```
418 ///
419 /// It performs fixed-point iteration using the propagation delay returned by
420 /// [`Self::shapiro_delay`]. Clock-rate and proper-time effects
421 /// are **not** included in the iteration; they should be applied separately
422 /// when converting between coordinate time and proper time or when forming
423 /// observables.
424 ///
425 /// The solver is suitable for high-precision one-way light-time calculations
426 /// and works with any ephemeris source via the provided closure.
427 ///
428 /// ## Parameters
429 ///
430 /// * `rx_provider` — Closure returning the full [`Observer`] of the
431 /// receiver at a given coordinate time.
432 /// * `bodies` — Slice of `(shapiro_coefficient, body_position)` pairs
433 /// controlling the Shapiro contribution. Use `&[(Dt::SHAPIRO_SOLAR, sun_pos)]`
434 /// for solar-system work; include additional bodies for higher precision.
435 /// Pass `&[]` to disable Shapiro.
436 /// * `tolerance` — Maximum allowed change in receive time per iteration
437 /// before declaring convergence (e.g. `Dt::from_ns(1, Scale::TAI)`).
438 /// * `max_iter` — Maximum number of iterations. Typical values are 12–20
439 /// for solar-system geometries.
440 ///
441 /// ## Returns
442 ///
443 /// A tuple `(prop_correction, rx_time, final_state)` where:
444 /// - `prop_correction` is the converged Shapiro propagation delay,
445 /// - `rx_time` is the converged receive time (same scale as `self.time`),
446 /// - `final_state` is the receiver state at `rx_time`.
447 pub fn iterative_one_way_light_time_to<F>(
448 &self,
449 rx_provider: &mut F,
450 bodies: &[(Dt, Position)],
451 tolerance: Dt,
452 max_iter: usize,
453 ) -> (Dt, Dt, Observer)
454 where
455 F: FnMut(Dt) -> Observer,
456 {
457 // Initial geometric guess
458 let initial_rx = rx_provider(self.time);
459 let initial_r_sep = self.position.distance_to(initial_rx.position);
460 let initial_geometric = Dt::from_sec_f(initial_r_sep / C, Scale::TAI);
461
462 let mut rx_time = self.time.add(initial_geometric);
463 let mut prop_correction = Dt::ZERO;
464
465 for _ in 0..max_iter {
466 let rx = rx_provider(rx_time);
467
468 prop_correction = self.shapiro_delay(rx, bodies);
469
470 let r_sep = self.position.distance_to(rx.position);
471 let geometric = Dt::from_sec_f(r_sep / C, Scale::TAI);
472 let full_delay = geometric.add(prop_correction);
473
474 let new_rx_time = self.time.add(full_delay);
475 let change = new_rx_time.to_diff_raw(rx_time);
476
477 rx_time = new_rx_time;
478
479 if change.abs() < tolerance {
480 return (prop_correction, rx_time, rx);
481 }
482 }
483
484 // Fallback after max iterations
485 let final_rx = rx_provider(rx_time);
486 (prop_correction, rx_time, final_rx)
487 }
488
489 /// Computes the total Shapiro (gravitational propagation) delay for a
490 /// complete round-trip (two-way) signal.
491 ///
492 /// This method solves the uplink and downlink legs *separately and
493 /// independently* using the iterative light-time solver. This approach
494 /// is more accurate than older combined round-trip formulas when the
495 /// two ends have significantly different velocities or are in different
496 /// gravitational environments.
497 ///
498 /// The returned value is the **sum of the uplink and downlink Shapiro
499 /// delays only**. It does **not** include clock-rate or proper-time
500 /// corrections.
501 ///
502 /// ## When to use this method
503 ///
504 /// Use this when you need the total gravitational propagation correction
505 /// for two-way (round-trip) measurements, for example:
506 /// - Two-way range or range-rate (Doppler) data
507 /// - Transponded signals from spacecraft
508 /// - Any high-precision two-way light-time calculation
509 ///
510 /// For one-way signals, use [`Self::shapiro_delay`] or
511 /// [`Self::one_way_relativistic_delay`] instead.
512 ///
513 /// ## How the calculation works
514 ///
515 /// 1. Solves the uplink leg (from `self` to the remote receiver) using
516 /// the `rx_provider` closure.
517 /// 2. Obtains the accurate receiver state at the uplink arrival time.
518 /// 3. Solves the downlink leg (from the receiver back to the local
519 /// transmitter) using the `tx_provider` closure.
520 ///
521 /// ## The `bodies` parameter – which masses to include
522 ///
523 /// Pass a slice of `(shapiro_coefficient, body_position)` pairs (the
524 /// same slice is used for both legs). See [`Self::shapiro_delay`] for
525 /// details on how to build this slice.
526 ///
527 /// **Important: All states returned by the providers must be consistent**
528 /// with the same reference frame (same origin and same coordinate axes).
529 ///
530 /// ## Parameters
531 ///
532 /// * `rx_provider` — Closure that returns the full [`Observer`] of
533 /// the remote receiver (planet, spacecraft, etc.) at any given
534 /// coordinate time.
535 /// * `tx_provider` — Closure that returns the full [`Observer`] of
536 /// the local transmitter at any given coordinate time (used only for
537 /// the downlink leg).
538 /// * `bodies` — Slice of `(shapiro_coefficient, body_position)` pairs
539 /// describing the gravitating bodies.
540 /// * `tolerance` — Convergence tolerance for each leg’s iterative solver
541 /// (e.g. `Dt::from_ns(1, Scale::TAI)`).
542 /// * `max_iter` — Maximum number of iterations allowed per leg
543 /// (typical values are 12–20).
544 ///
545 /// ## Returns
546 ///
547 /// The total round-trip Shapiro propagation delay (uplink + downlink)
548 /// as a `Dt`, in the same time scale as `self.time`.
549 ///
550 /// This value should normally be **added** to the Newtonian geometric
551 /// round-trip light time. Clock-rate corrections must still be applied
552 /// separately (e.g. by squaring the one-way clock-rate ratio).
553 pub fn round_trip_light_time_correction<RxF, TxF>(
554 &self,
555 mut rx_provider: RxF, // remote body (planet, spacecraft, etc.)
556 mut tx_provider: TxF, // local transmitter for the return leg (can move)
557 bodies: &[(Dt, Position)],
558 tolerance: Dt,
559 max_iter: usize,
560 ) -> Dt
561 where
562 RxF: FnMut(Dt) -> Observer,
563 TxF: FnMut(Dt) -> Observer,
564 {
565 // Uplink leg: transmitter → receiver
566 let (uplink_prop, rx_time, _rx_state) =
567 self.iterative_one_way_light_time_to(&mut rx_provider, bodies, tolerance, max_iter);
568
569 // Downlink leg: receiver → transmitter
570 let return_tx = rx_provider(rx_time); // accurate state at uplink arrival
571
572 let (downlink_prop, _return_rx_time, _return_rx_state) = return_tx
573 .iterative_one_way_light_time_to(&mut tx_provider, bodies, tolerance, max_iter);
574
575 uplink_prop.add(downlink_prop)
576 }
577
578 /// Computes the one-way gravitational propagation delay (Shapiro delay)
579 /// caused by massive bodies between this observer (the transmitter) and
580 /// a receiver.
581 ///
582 /// This value is the **extra time** a radio signal takes to travel because
583 /// gravity from the Sun and planets slightly slows it down. You normally
584 /// add this delay to the ordinary geometric light travel time
585 /// (`distance / speed of light`) to get a more accurate total one-way
586 /// signal travel time.
587 ///
588 /// **Important:** This method returns **only** the gravitational
589 /// propagation delay. It does **not** include clock-rate differences
590 /// between the transmitter and receiver caused by velocity or gravity.
591 /// Those effects are available separately through
592 /// [`Self::compute_differential_clock_correction`],
593 /// [`Self::proper_time_rate`], and [`Self::relativistic_clock_rate_ratio`].
594 ///
595 /// ## When to use this method
596 ///
597 /// Use this when you need the gravitational (Shapiro) contribution to
598 /// one-way light time — for example when building high-precision range,
599 /// Doppler, or orbit determination models.
600 ///
601 /// ## The `bodies` parameter – which masses to include
602 ///
603 /// Pass a slice of `(shapiro_coefficient, body_position)` pairs:
604 ///
605 /// - `shapiro_coefficient`: How strong the delay from this body should be.
606 /// It equals `2GM / c³`. Use [`Dt::SHAPIRO_SOLAR`] for the Sun, or
607 /// [`Dt::shapiro_from_grav_param(gm)`] for any other body.
608 /// - `body_position`: Where the center of that body is located at the
609 /// relevant time.
610 ///
611 /// **Important: All positions must be measured the same way**
612 ///
613 /// The transmitter position (`self.position`), the receiver position
614 /// (`rx.position`), and every `body_position` you provide must all be
615 /// measured from the **same point in space**, and they must all use
616 /// the **same directions** for their X, Y, and Z axes.
617 ///
618 /// For example, if the transmitter position is measured from the center
619 /// of the solar system, then the receiver and body positions must also
620 /// be measured from the center of the solar system, using the same
621 /// pointing directions for the coordinate axes.
622 ///
623 /// If the positions come from different measurement systems, the
624 /// calculated delay will be wrong.
625 ///
626 /// In most solar-system work, people use positions from JPL ephemerides
627 /// (which are measured from the center of the solar system).
628 ///
629 /// Pass an empty slice (`&[]`) to turn off Shapiro delay entirely.
630 ///
631 /// ## Parameters
632 ///
633 /// * `rx` — Receiver state at the approximate time the signal arrives.
634 /// * `bodies` — List of bodies that should contribute to the delay.
635 ///
636 /// ## Returns
637 ///
638 /// The total one-way Shapiro gravitational propagation delay, in the
639 /// same time scale as `self.time`. This value should normally be
640 /// **added** to the Newtonian geometric light time.
641 pub const fn shapiro_delay(&self, rx: Observer, bodies: &[(Dt, Position)]) -> Dt {
642 let mut total = Dt::ZERO;
643 let mut i = 0;
644
645 while i < bodies.len() {
646 let (shapiro_coeff, body_pos) = bodies[i];
647 total = total.add(Self::shapiro_one_way_delay(
648 shapiro_coeff,
649 self.position,
650 rx.position,
651 body_pos,
652 ));
653 i += 1;
654 }
655
656 total
657 }
658
659 /// Computes the first-order one-way Shapiro gravitational time delay
660 /// due to a single central body using a numerically stable formulation.
661 ///
662 /// This is the **core low-level implementation** (pub(crate) const fn).
663 /// It replaces the classic radial formula with an algebraically equivalent
664 /// but cancellation-free form that is robust even for small impact parameters
665 /// (near-grazing / conjunction geometries).
666 ///
667 /// The algorithm uses the identity:
668 ///
669 ///
670 /// ln((r_tx + r_rx + r_sep) / (r_tx + r_rx - r_sep))
671 /// ≡ 2·ln(num) − ln(denom_term)
672 ///
673 ///
674 /// where denom_term is computed from the dot-product identity
675 /// (r_tx + r_rx)² − r_sep² = 2(r_tx·r_rx + p_tx · p_rx).
676 /// This avoids the dangerous subtraction that loses precision when
677 /// the signal path passes close to the body.
678 ///
679 /// The result is equivalent (within floating-point) to the
680 /// classic Moyer/DSN-style formula while being far more stable.
681 /// Contributions from multiple bodies are summed at a higher level.
682 ///
683 /// ## Safety / Guards
684 ///
685 /// - Returns [`Dt::ZERO`](../struct.Dt.html#associatedconstant.ZERO)
686 /// for any non-positive distance or zero Shapiro coefficient.
687 /// - Protects against invalid logarithm argument (`arg <= 1.0`).
688 /// - Designed for weak-field solar-system / cislunar use (monopole, straight-line approx).
689 pub(crate) const fn shapiro_one_way_delay(
690 shapiro: Dt,
691 tx_pos: Position,
692 rx_pos: Position,
693 body_pos: Position,
694 ) -> Dt {
695 let shapiro_sec = shapiro.to_sec_f();
696
697 // Distances relative to *this specific gravitating body*
698 let r_tx = tx_pos.distance_to(body_pos);
699 let r_rx = rx_pos.distance_to(body_pos);
700 let r_sep = tx_pos.distance_to(rx_pos);
701
702 if r_tx <= f!(0.0) || r_rx <= f!(0.0) || r_sep <= f!(0.0) || shapiro_sec == f!(0.0) {
703 return Dt::ZERO;
704 }
705
706 let s = r_tx + r_rx;
707 let num = s + r_sep; // (r_tx + r_rx + r_sep)
708
709 if num <= f!(0.0) {
710 return Dt::ZERO;
711 }
712
713 // Stable computation of (r_tx + r_rx)^2 − r_sep^2
714 // = 2 × (r_tx r_rx + \vec{p_tx} · \vec{p_rx})
715 let dot_term = (r_tx * r_tx + r_rx * r_rx - r_sep * r_sep) / f!(2.0);
716 let denom_term = f!(2.0) * (r_tx * r_rx + dot_term);
717
718 if denom_term <= f!(0.0) {
719 return Dt::ZERO;
720 }
721
722 let arg = (num * num) / denom_term;
723
724 if arg <= f!(1.0) {
725 return Dt::ZERO;
726 }
727
728 let delay_sec = shapiro_sec * log(arg);
729 Dt::from_sec_f(delay_sec, Scale::TAI)
730 }
731
732 /// Computes the differential proper-time correction between `self`
733 /// (transmitter) and `rx` (receiver) over the interval between their
734 /// time tags.
735 ///
736 /// This returns the difference in proper time advance between the two
737 /// observers. It does **not** include Shapiro propagation delay.
738 ///
739 /// The result can be added to the output of [`Self::shapiro_delay`]
740 /// or [`Self::iterative_one_way_light_time_to`] when a combined
741 /// relativistic correction (propagation + clock rate) is required.
742 ///
743 /// ## Parameters
744 ///
745 /// * `rx` — Receiver state at the approximate time of reception.
746 ///
747 /// ## Returns
748 ///
749 /// The differential clock-rate correction (`rx_proper_advance − tx_proper_advance`).
750 pub const fn compute_differential_clock_correction(&self, rx: Observer) -> Dt {
751 let span = rx.time.to_diff_raw(self.time);
752
753 let tx_drift = Drift::from_velocity_potential_and_scale(
754 self.velocity.speed(),
755 self.grav_potential_m2_s2,
756 self.characteristic_length_scale,
757 );
758 let rx_drift = Drift::from_velocity_potential_and_scale(
759 rx.velocity.speed(),
760 rx.grav_potential_m2_s2,
761 rx.characteristic_length_scale,
762 );
763
764 rx_drift
765 .time_diff_after(&span)
766 .sub(tx_drift.time_diff_after(&span))
767 }
768}