Skip to main content

spacelab_estimation/
modifier.rs

1//! Measurement corrections as a composable layer: one correction is a decorator over an observable,
2//! and a decorated observable is itself an observable.
3//!
4//! [`measurement`](crate::measurement) computes geometry and nothing else — a range, an elevation,
5//! a line-of-sight angle. What an instrument reads is that geometry plus every correction the
6//! signal picked up on the way: tropospheric and ionospheric delay, the gravitational (Shapiro)
7//! delay, a station or transponder bias. Before this module each caller added those at its own call
8//! site, in its own order, and no two callers wrote it the same way.
9//!
10//! # Shape
11//!
12//! [`Observable`] is what an instrument reads, as a function of the six-element satellite state and
13//! `K` **estimated measurement parameters** — the biases and offsets the filter solves for
14//! alongside the orbit. [`Modifier`] is one correction, and it returns the *delta* it contributes
15//! rather than a rewritten value. [`Modified`] joins the two and is itself an [`Observable`], so
16//! corrections chain to any depth:
17//!
18//! ```text
19//! Modified::new(Range{station}, ShapiroDelay{..}).with(EstimatedBias::<1>::new(0)?)
20//!     = range(sat, station) + shapiro(sat, station) + parameters[0]
21//! ```
22//!
23//! Composition is **static** — `Modified<Modified<Range, ShapiroDelay>, EstimatedBias<1>>` is one
24//! monomorphised type — for the same reason the force models compose in tuples rather than in a
25//! `Vec<Box<dyn Acceleration>>`: a trait object cannot carry a generic method, and every value here
26//! is generic over [`Scalar`] so that the partials come from automatic differentiation rather than
27//! from a hand-written Jacobian that can fall out of step with the value.
28//!
29//! # What this is not
30//!
31//! An options struct on each measurement function — `range(sat, station, &RangeOptions { troposphere,
32//! ionosphere, bias, .. })` — was rejected. It puts every correction's parameters in every
33//! measurement's signature, so adding one correction is a breaking change to all six observables:
34//! the divergent-change smell, and precisely what the decorator avoids.
35//!
36//! # Where the atmospheric models are
37//!
38//! They are not here and they are not reachable from here. Saastamoinen, VMF1/VMF3, GPT3, Niell,
39//! Klobuchar and NeQuick-G live in `spacelab_gnss`, which this crate does not depend on, so
40//! [`AtmosphericDelay`] is generic over a caller-supplied [`SlantDelay`]: the caller owns the model
41//! and the dependency edge, this layer owns the composition. The trait is stated over [`Scalar`]
42//! rather than over `f64` on purpose — a delay evaluated at `f64` would enter the filter with a
43//! zero partial, and the tropospheric mapping function's own elevation derivative is metres per
44//! degree at low elevation, not a rounding term.
45
46use spacelab_autodiff::{Dual, Scalar, jacobian};
47
48use crate::light_time::SPEED_OF_LIGHT;
49use crate::measurement::{
50    Station, Topocentric, azimuth, declination, elevation, range, range_rate, right_ascension,
51};
52use crate::radiometric::{CoronaSeries, PlasmaSignature, RadiometricError, solar_corona_delay};
53
54/// Why a modifier could not be built.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum ModifierError {
57    /// An estimated parameter was addressed past the end of the parameter vector. Reported at
58    /// construction, so an assembled chain can only read a parameter that exists.
59    ParameterOutOfRange {
60        /// The index asked for.
61        index: usize,
62        /// The number of estimated measurement parameters the chain carries.
63        parameters: usize,
64    },
65}
66
67impl core::fmt::Display for ModifierError {
68    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
69        match self {
70            Self::ParameterOutOfRange { index, parameters } => write!(
71                f,
72                "estimated parameter {index} is past the {parameters} the measurement carries"
73            ),
74        }
75    }
76}
77
78impl core::error::Error for ModifierError {}
79
80/// What an instrument reads, as a function of the satellite state and the `K` estimated measurement
81/// parameters.
82///
83/// Written once over any [`Scalar`], so [`partials`] gets the value and every partial from the same
84/// source. `satellite` is the six-element state in the working frame, at the epoch the geometry
85/// belongs to — light time is a choice of *epoch*, settled before this is called by
86/// [`observed::reduce`](crate::observed::reduce), whose
87/// [`partials_at_emission`](crate::observed::partials_at_emission) also corrects the row this
88/// observable's partials produce for the state's own effect on the flight time.
89pub trait Observable<const K: usize> {
90    /// The observable's value at this state and these parameters.
91    fn value<S: Scalar>(&self, satellite: &[S; 6], parameters: &[S; K]) -> S;
92}
93
94/// One correction to an observable: the amount it adds, in the observable's own units.
95///
96/// A delta rather than a rewritten value, because every correction in this layer is additive in the
97/// observable — a delay adds metres to a range, a bias adds its own units to whatever it biases —
98/// and a delta can be compared directly against the model it came from, which is how the
99/// no-arithmetic-of-its-own property is tested.
100pub trait Modifier<const K: usize> {
101    /// The correction's contribution at this state and these parameters.
102    fn delta<S: Scalar>(&self, satellite: &[S; 6], parameters: &[S; K]) -> S;
103}
104
105/// An observable decorated with one correction — itself an observable, which is what makes the
106/// chain compose.
107///
108/// The sum is taken in application order. Floating-point addition is not associative, so the order
109/// a caller writes the chain in is the order it is summed in, and a chain reproduces a hand-written
110/// composition of the same terms in the same order to the bit.
111#[derive(Debug, Clone, Copy, PartialEq)]
112pub struct Modified<O, M> {
113    /// The decorated observable.
114    pub observable: O,
115    /// The correction applied to it.
116    pub modifier: M,
117}
118
119impl<O, M> Modified<O, M> {
120    /// Decorate `observable` with one correction.
121    #[must_use]
122    pub const fn new(observable: O, modifier: M) -> Self {
123        Self {
124            observable,
125            modifier,
126        }
127    }
128
129    /// Add one more correction to the chain, applied after the ones already in it.
130    ///
131    /// Chaining lives here rather than on [`Observable`] so that a chain can be built without
132    /// naming `K`: every observable and every modifier in this module is written for all `K`, so a
133    /// method on the trait would be ambiguous at the point it is called and would have to be
134    /// turbofished. Assembled this way, `K` is fixed once — where the chain meets the parameter
135    /// vector it is evaluated at.
136    #[must_use]
137    pub const fn with<N>(self, modifier: N) -> Modified<Self, N> {
138        Modified::new(self, modifier)
139    }
140}
141
142impl<const K: usize, O: Observable<K>, M: Modifier<K>> Observable<K> for Modified<O, M> {
143    fn value<S: Scalar>(&self, satellite: &[S; 6], parameters: &[S; K]) -> S {
144        self.observable.value(satellite, parameters) + self.modifier.delta(satellite, parameters)
145    }
146}
147
148/// Slant range to a station — [`measurement::range`](crate::measurement::range) lifted into the
149/// layer.
150#[derive(Debug, Clone, Copy, PartialEq)]
151pub struct Range {
152    /// The observing station.
153    pub station: Station,
154}
155
156impl<const K: usize> Observable<K> for Range {
157    fn value<S: Scalar>(&self, satellite: &[S; 6], _parameters: &[S; K]) -> S {
158        range(satellite, &self.station)
159    }
160}
161
162/// Range rate — [`measurement::range_rate`](crate::measurement::range_rate) lifted into the layer.
163#[derive(Debug, Clone, Copy, PartialEq)]
164pub struct RangeRate {
165    /// The observing station.
166    pub station: Station,
167}
168
169impl<const K: usize> Observable<K> for RangeRate {
170    fn value<S: Scalar>(&self, satellite: &[S; 6], _parameters: &[S; K]) -> S {
171        range_rate(satellite, &self.station)
172    }
173}
174
175/// Topocentric right ascension — [`measurement::right_ascension`](crate::measurement::right_ascension)
176/// lifted into the layer. Cyclic in `2π`; the residual still has to be wrapped by the caller.
177#[derive(Debug, Clone, Copy, PartialEq)]
178pub struct RightAscension {
179    /// The observing station.
180    pub station: Station,
181}
182
183impl<const K: usize> Observable<K> for RightAscension {
184    fn value<S: Scalar>(&self, satellite: &[S; 6], _parameters: &[S; K]) -> S {
185        right_ascension(satellite, &self.station)
186    }
187}
188
189/// Topocentric declination — [`measurement::declination`](crate::measurement::declination) lifted
190/// into the layer.
191#[derive(Debug, Clone, Copy, PartialEq)]
192pub struct Declination {
193    /// The observing station.
194    pub station: Station,
195}
196
197impl<const K: usize> Observable<K> for Declination {
198    fn value<S: Scalar>(&self, satellite: &[S; 6], _parameters: &[S; K]) -> S {
199        declination(satellite, &self.station)
200    }
201}
202
203/// Elevation above the local horizon — [`measurement::elevation`](crate::measurement::elevation)
204/// lifted into the layer.
205#[derive(Debug, Clone, Copy, PartialEq)]
206pub struct Elevation {
207    /// The station and its horizon frame.
208    pub topocentric: Topocentric,
209}
210
211impl<const K: usize> Observable<K> for Elevation {
212    fn value<S: Scalar>(&self, satellite: &[S; 6], _parameters: &[S; K]) -> S {
213        elevation(satellite, &self.topocentric)
214    }
215}
216
217/// Azimuth from local north — [`measurement::azimuth`](crate::measurement::azimuth) lifted into the
218/// layer. Cyclic in `2π`; the residual still has to be wrapped by the caller.
219#[derive(Debug, Clone, Copy, PartialEq)]
220pub struct Azimuth {
221    /// The station and its horizon frame.
222    pub topocentric: Topocentric,
223}
224
225impl<const K: usize> Observable<K> for Azimuth {
226    fn value<S: Scalar>(&self, satellite: &[S; 6], _parameters: &[S; K]) -> S {
227        azimuth(satellite, &self.topocentric)
228    }
229}
230
231/// Shapiro gravitational delay of one signal leg, metres — IERS Conventions (2010) §11.
232///
233/// `r_emitter` and `r_receiver` are the geocentric distances of the two endpoints and `path` the
234/// straight-line distance between them, all metres; `gm` is the central body's gravitational
235/// parameter, m³/s².
236///
237/// # Derivation
238///
239/// The delay is the coordinate-time excess `(2GM/c²)∫dl/r` along the leg. `derivations/shapiro_delay.mac`
240/// verifies in Maxima that the antiderivative `log(l + b + √(l² + 2bl + r₁²))` differentiates back
241/// to `1/r(l)` (residual exactly `0`) and that evaluating it between the endpoints reduces to
242/// `log((r₁ + r₂ + p)/(r₁ + r₂ − p))` (difference from the IERS form exactly `0`). The same script
243/// integrates the three-dimensional geometry numerically: quadrature minus closed form is `0.0 m`
244/// at a 500 km zenith pass, `1.1e-19 m` at 10° elevation and `-1.1e-18 m` at LAGEOS.
245///
246/// # Size, measured
247///
248/// One leg, from the same script: **0.669 mm** to a 500 km satellite at the zenith, **2.281 mm** at
249/// 10° elevation, **9.516 mm** to LAGEOS at 12 270 km, **12.66 mm** to GPS at 20 200 km. A two-way
250/// system doubles those in flight time, but a two-way range published as a one-way range —
251/// `c(τ_up + τ_down)/2`, which is how an ILRS normal point is formed — carries one leg. The
252/// commonly quoted "~2 cm two-way" belongs to GNSS altitude (25.3 mm), not to LEO, where the
253/// two-way delay is 1.34 mm at the zenith and 4.56 mm at 10°.
254#[must_use]
255pub fn shapiro_delay<S: Scalar>(r_emitter: S, r_receiver: S, path: S, gm: f64) -> S {
256    let sum = r_emitter + r_receiver;
257    S::from_f64(2.0 * gm / (SPEED_OF_LIGHT * SPEED_OF_LIGHT)) * ((sum + path) / (sum - path)).ln()
258}
259
260/// The Shapiro delay with the PPN parameter `γ` written out rather than assumed.
261///
262/// ```text
263/// Δρ = (1 + γ) GM/c² · ln((r_e + r_r + s)/(r_e + r_r − s))
264/// ```
265///
266/// [`shapiro_delay`] is this at `γ = 1`, which is general relativity and what every other use in
267/// this workspace wants. It is separate because `γ` is the one parameter of the measurement model
268/// that is *solved for* rather than adopted: it is the quantity Cassini measured at superior
269/// conjunction — `γ − 1 = (2.1 ± 2.3) × 10⁻⁵`, Bertotti, Iess & Tortora, *Nature* **425** (2003) —
270/// and that measurement is exactly `∂ρ/∂γ` over a tracking arc. A `γ` baked into the constant `2`
271/// has partial zero and cannot be estimated at all.
272///
273/// The two functions are one formula and the tests hold them to that: `shapiro_delay_ppn(.., 1.0)`
274/// is bit-identical to `shapiro_delay`, and the partial is the delay itself divided by `1 + γ`.
275#[must_use]
276pub fn shapiro_delay_ppn<S: Scalar>(r_emitter: S, r_receiver: S, path: S, gm: f64, gamma: S) -> S {
277    let sum = r_emitter + r_receiver;
278    (gamma + S::from_f64(1.0))
279        * S::from_f64(gm / (SPEED_OF_LIGHT * SPEED_OF_LIGHT))
280        * ((sum + path) / (sum - path)).ln()
281}
282
283/// The Shapiro delay as a modifier on a range: [`shapiro_delay`] over the leg between the station
284/// and the satellite.
285///
286/// The state and the station must be in the same **geocentric** frame; only the two geocentric
287/// distances and the straight-line path enter, so a rotating Earth-fixed frame and an inertial one
288/// give the same delay.
289///
290/// `spacelab_slr::shapiro_delay` is the same equation at `f64`, for the two-way SLR model. This one
291/// is generic over [`Scalar`] because it is differentiated: an `f64` delay would enter the filter
292/// with a zero partial. They are two implementations of one formula and can drift; what stops it is
293/// that `derivations/shapiro_delay.mac` pins this one to a bigfloat reference and computes the
294/// 9.516 mm LAGEOS leg the SLR side's own test brackets.
295#[derive(Debug, Clone, Copy, PartialEq)]
296pub struct ShapiroDelay {
297    /// Station position in the working frame, metres.
298    pub station: [f64; 3],
299    /// Gravitational parameter of the central body, m³/s².
300    pub gm: f64,
301}
302
303impl<const K: usize> Modifier<K> for ShapiroDelay {
304    fn delta<S: Scalar>(&self, satellite: &[S; 6], _parameters: &[S; K]) -> S {
305        let r_satellite = (satellite[0] * satellite[0]
306            + satellite[1] * satellite[1]
307            + satellite[2] * satellite[2])
308            .sqrt();
309        let r_station = S::from_f64(libm::sqrt(
310            self.station[0] * self.station[0]
311                + self.station[1] * self.station[1]
312                + self.station[2] * self.station[2],
313        ));
314        let path = range(satellite, &Station::fixed(self.station));
315        shapiro_delay(r_satellite, r_station, path, self.gm)
316    }
317}
318
319/// A bias of known size, applied rather than solved for.
320///
321/// This is the ILRS Data Handling File case — a station whose range bias the network publishes, in
322/// the observable's own units. Where the network instead flags a bias to be *estimated*, the
323/// modifier is [`EstimatedBias`].
324#[derive(Debug, Clone, Copy, PartialEq)]
325pub struct Bias {
326    /// The bias added to the observable, in its units.
327    pub value: f64,
328}
329
330impl<const K: usize> Modifier<K> for Bias {
331    fn delta<S: Scalar>(&self, _satellite: &[S; 6], _parameters: &[S; K]) -> S {
332        S::from_f64(self.value)
333    }
334}
335
336/// A bias the filter solves for: one of the `K` estimated measurement parameters, added to the
337/// observable.
338///
339/// The partial `∂observable/∂parameter` is then exactly `1`, from AD, and the parameter gets a
340/// column in the Jacobian row like any state direction. An estimator that can only subtract a fixed
341/// bias cannot detect one that changed; this is the difference between the two.
342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
343pub struct EstimatedBias<const K: usize> {
344    index: usize,
345}
346
347impl<const K: usize> EstimatedBias<K> {
348    /// The bias carried by estimated parameter `index`.
349    ///
350    /// # Errors
351    ///
352    /// [`ModifierError::ParameterOutOfRange`] if `index` is not one of the `K` parameters. Checked
353    /// once here so that evaluation cannot address a parameter that does not exist.
354    pub const fn new(index: usize) -> Result<Self, ModifierError> {
355        if index < K {
356            Ok(Self { index })
357        } else {
358            Err(ModifierError::ParameterOutOfRange {
359                index,
360                parameters: K,
361            })
362        }
363    }
364
365    /// Which estimated parameter this bias reads.
366    #[must_use]
367    pub const fn index(&self) -> usize {
368        self.index
369    }
370}
371
372impl<const K: usize> Modifier<K> for EstimatedBias<K> {
373    fn delta<S: Scalar>(&self, _satellite: &[S; 6], parameters: &[S; K]) -> S {
374        parameters[self.index]
375    }
376}
377
378/// The Shapiro delay with `γ` taken from an estimated parameter, so the arc measures it.
379///
380/// The geometry is [`ShapiroDelay`]'s; the only difference is where `γ` comes from, and that
381/// difference is the whole point — with `γ` in the parameter vector the Jacobian gains a column
382/// `∂ρ/∂γ = Δρ/(1 + γ)`, which at Cassini's 2002 conjunction geometry is **19.7 km** per unit `γ`
383/// on the one-way range, measured by this module's own test. That is what makes the parameter
384/// observable at all: Bertotti's `± 2.3 × 10⁻⁵` is 45 cm of range against it.
385///
386/// This is Tudat's `ppn_parameter_gamma`, and it is the only one of its ~80 estimable parameters
387/// that belongs in *this* layer: the rest — `ppn_parameter_beta`, the Love numbers, the free-core-
388/// nutation rate, the Yarkovsky coefficient, the gas–surface accommodation coefficients — enter
389/// through the force model or the Earth-orientation model, not through the measurement.
390#[derive(Debug, Clone, Copy, PartialEq)]
391pub struct EstimatedShapiroDelay<const K: usize> {
392    /// Station position in the working frame, metres.
393    pub station: [f64; 3],
394    /// Gravitational parameter of the central body, m³/s².
395    pub gm: f64,
396    index: usize,
397}
398
399impl<const K: usize> EstimatedShapiroDelay<K> {
400    /// The Shapiro delay whose `γ` is estimated parameter `index`.
401    ///
402    /// # Errors
403    ///
404    /// [`ModifierError::ParameterOutOfRange`] if `index` is not one of the `K` parameters.
405    pub const fn new(station: [f64; 3], gm: f64, index: usize) -> Result<Self, ModifierError> {
406        if index < K {
407            Ok(Self { station, gm, index })
408        } else {
409            Err(ModifierError::ParameterOutOfRange {
410                index,
411                parameters: K,
412            })
413        }
414    }
415
416    /// Which estimated parameter carries `γ`.
417    #[must_use]
418    pub const fn index(&self) -> usize {
419        self.index
420    }
421}
422
423impl<const K: usize> Modifier<K> for EstimatedShapiroDelay<K> {
424    fn delta<S: Scalar>(&self, satellite: &[S; 6], parameters: &[S; K]) -> S {
425        let r_satellite = (satellite[0] * satellite[0]
426            + satellite[1] * satellite[1]
427            + satellite[2] * satellite[2])
428            .sqrt();
429        let r_station = S::from_f64(libm::sqrt(
430            self.station[0] * self.station[0]
431                + self.station[1] * self.station[1]
432                + self.station[2] * self.station[2],
433        ));
434        let path = range(satellite, &Station::fixed(self.station));
435        shapiro_delay_ppn(
436            r_satellite,
437            r_station,
438            path,
439            self.gm,
440            parameters[self.index],
441        )
442    }
443}
444
445/// A clock offset that drifts across an arc: `bias + rate · Δt`, both estimated.
446///
447/// The arcwise counterpart of [`EstimatedBias`], and Tudat's arcwise clock/time-bias parameters.
448/// A station clock is not a constant over a pass — it is a polynomial, and the linear term is the
449/// one a single arc can separate from the orbit, because a bias that is constant over the arc is
450/// degenerate with the along-track state and a bias that ramps is not.
451///
452/// `elapsed` is a *constant of the observation*, like the meteorology [`AtmosphericDelay`] carries:
453/// the modifier is built per observation with the seconds since the arc's own reference epoch
454/// already in it, so that [`Observable::value`] keeps its signature and the layer keeps its rule
455/// that everything not a function of the state lives in the implementor.
456#[derive(Debug, Clone, Copy, PartialEq)]
457pub struct EstimatedDrift<const K: usize> {
458    /// Seconds from the arc's reference epoch to this observation.
459    pub elapsed: f64,
460    bias: usize,
461    rate: usize,
462}
463
464impl<const K: usize> EstimatedDrift<K> {
465    /// The drift carried by parameters `bias` and `rate`, evaluated `elapsed` seconds into the arc.
466    ///
467    /// # Errors
468    ///
469    /// [`ModifierError::ParameterOutOfRange`] naming whichever index is past the `K` parameters.
470    /// The two are checked in order, so a call with both wrong reports the first.
471    pub const fn new(elapsed: f64, bias: usize, rate: usize) -> Result<Self, ModifierError> {
472        if bias >= K {
473            return Err(ModifierError::ParameterOutOfRange {
474                index: bias,
475                parameters: K,
476            });
477        }
478        if rate >= K {
479            return Err(ModifierError::ParameterOutOfRange {
480                index: rate,
481                parameters: K,
482            });
483        }
484        Ok(Self {
485            elapsed,
486            bias,
487            rate,
488        })
489    }
490
491    /// Which estimated parameter carries the constant term.
492    #[must_use]
493    pub const fn bias_index(&self) -> usize {
494        self.bias
495    }
496
497    /// Which estimated parameter carries the rate.
498    #[must_use]
499    pub const fn rate_index(&self) -> usize {
500        self.rate
501    }
502}
503
504impl<const K: usize> Modifier<K> for EstimatedDrift<K> {
505    fn delta<S: Scalar>(&self, _satellite: &[S; 6], parameters: &[S; K]) -> S {
506        parameters[self.bias] + parameters[self.rate] * S::from_f64(self.elapsed)
507    }
508}
509
510/// The solar-corona range correction as a modifier — [`solar_corona_delay`] on the station-to-
511/// satellite leg, with both endpoints referred to the Sun.
512///
513/// [`crate::radiometric`] computes the path integral; this is what puts it in the chain beside the
514/// Shapiro delay and the troposphere, which is what #325 is for. The series and the frequency are
515/// validated once at construction, so evaluation carries no error the caller has to handle on every
516/// observation.
517///
518/// # Occultation
519///
520/// A line of sight whose closest approach to the Sun's centre is inside
521/// [`SOLAR_RADIUS`](crate::radiometric::SOLAR_RADIUS) is not a
522/// link, and the correction has no value there. [`Self::occulted`] answers that question directly
523/// and [`Modifier::delta`] returns NaN — the same "no answer" this workspace uses everywhere a
524/// total function has no total domain. Screen with `occulted` before scheduling the observation;
525/// a NaN reaching the residual is a scheduling bug, and it is visible rather than silent.
526#[derive(Debug, Clone, Copy, PartialEq)]
527pub struct SolarCoronaDelay<'a> {
528    /// The station, in the same geocentric frame as the state, metres.
529    pub station: [f64; 3],
530    /// The Sun, in that frame at this observation's epoch, metres.
531    pub sun: [f64; 3],
532    series: CoronaSeries<'a>,
533    frequency: f64,
534    signature: PlasmaSignature,
535}
536
537impl<'a> SolarCoronaDelay<'a> {
538    /// The corona correction for a link on `frequency` hertz through `series`.
539    ///
540    /// # Errors
541    ///
542    /// [`RadiometricError::NonPositiveFrequency`] if the frequency is not positive and finite. The
543    /// series validates itself, at [`CoronaSeries::new`].
544    pub const fn new(
545        station: [f64; 3],
546        sun: [f64; 3],
547        series: CoronaSeries<'a>,
548        frequency: f64,
549        signature: PlasmaSignature,
550    ) -> Result<Self, RadiometricError> {
551        if frequency <= 0.0 || !frequency.is_finite() {
552            return Err(RadiometricError::NonPositiveFrequency { hertz: frequency });
553        }
554        Ok(Self {
555            station,
556            sun,
557            series,
558            frequency,
559            signature,
560        })
561    }
562
563    /// Whether the Sun stands between the station and the satellite closely enough that there is no
564    /// link — the geometry [`solar_corona_delay`] refuses.
565    #[must_use]
566    pub fn occulted(&self, satellite: &[f64; 6]) -> bool {
567        let station = self.heliocentric(&[self.station[0], self.station[1], self.station[2]]);
568        let target = self.heliocentric(&[satellite[0], satellite[1], satellite[2]]);
569        solar_corona_delay(
570            &self.series,
571            &target,
572            &station,
573            self.frequency,
574            self.signature,
575        )
576        .is_err()
577    }
578
579    /// A geocentric position referred to the Sun.
580    fn heliocentric<S: Scalar>(&self, position: &[S; 3]) -> [S; 3] {
581        [
582            position[0] - S::from_f64(self.sun[0]),
583            position[1] - S::from_f64(self.sun[1]),
584            position[2] - S::from_f64(self.sun[2]),
585        ]
586    }
587}
588
589impl<const K: usize> Modifier<K> for SolarCoronaDelay<'_> {
590    fn delta<S: Scalar>(&self, satellite: &[S; 6], _parameters: &[S; K]) -> S {
591        let station = self.heliocentric(&[
592            S::from_f64(self.station[0]),
593            S::from_f64(self.station[1]),
594            S::from_f64(self.station[2]),
595        ]);
596        let target = self.heliocentric(&[satellite[0], satellite[1], satellite[2]]);
597        solar_corona_delay(
598            &self.series,
599            &target,
600            &station,
601            self.frequency,
602            self.signature,
603        )
604        .unwrap_or_else(|_| S::from_f64(f64::NAN))
605    }
606}
607
608/// A one-way path delay along the line of sight, metres — the interface the tropospheric and
609/// ionospheric models are attached through.
610///
611/// Generic over [`Scalar`] because the delay is a function of the *state*: elevation and azimuth
612/// both move with the orbit, and a mapping function's elevation derivative is the largest term in
613/// the correction's own Jacobian at low elevation. Everything that is a constant of the observation
614/// — the epoch, the meteorology, the station's coordinates, the mapping-function coefficients —
615/// belongs in the implementor, which the caller constructs per observation.
616pub trait SlantDelay {
617    /// Delay in metres for a line of sight at `elevation` above the horizon and `azimuth` from
618    /// north, both radians.
619    fn delay<S: Scalar>(&self, elevation: S, azimuth: S) -> S;
620}
621
622/// A [`SlantDelay`] attached to an observable, evaluated at the line of sight the state implies.
623#[derive(Debug, Clone, Copy, PartialEq)]
624pub struct AtmosphericDelay<D> {
625    /// The station and its horizon frame — the delay is a function of the local elevation.
626    pub topocentric: Topocentric,
627    /// The delay model.
628    pub model: D,
629}
630
631impl<const K: usize, D: SlantDelay> Modifier<K> for AtmosphericDelay<D> {
632    fn delta<S: Scalar>(&self, satellite: &[S; 6], _parameters: &[S; K]) -> S {
633        self.model.delay(
634            elevation(satellite, &self.topocentric),
635            azimuth(satellite, &self.topocentric),
636        )
637    }
638}
639
640/// One observation's value and its partials, from automatic differentiation.
641#[derive(Debug, Clone, Copy, PartialEq)]
642pub struct Partials<const K: usize> {
643    /// The modified observable's value.
644    pub value: f64,
645    /// `∂value/∂state(t)` — chain it through the state transition matrix to reach the epoch state.
646    pub state: [f64; 6],
647    /// `∂value/∂parameter` for each estimated measurement parameter. These do not go through the
648    /// STM: a bias is not propagated, so the column is the partial itself.
649    pub parameters: [f64; K],
650}
651
652/// Evaluate a modified observable and its partials at one observation.
653///
654/// Two AD passes, not one: the seeded dimension is a const generic, `6 + K` cannot be spelled on
655/// stable Rust, and a second evaluation of a measurement geometry is nothing against the force
656/// evaluation that produced the state it is given. Both passes read the same source, so the value
657/// they agree on is the value the partials belong to.
658#[must_use]
659pub fn partials<const K: usize, O: Observable<K>>(
660    observable: &O,
661    satellite: &[f64; 6],
662    parameters: &[f64; K],
663) -> Partials<K> {
664    let mut lifted_parameters = [Dual::<6>::constant(0.0); K];
665    for (slot, p) in lifted_parameters.iter_mut().zip(parameters) {
666        *slot = Dual::constant(*p);
667    }
668    let (value, state_jacobian) =
669        jacobian::<6, 1, _>(|s| [observable.value(s, &lifted_parameters)], satellite);
670
671    let mut lifted_state = [Dual::<K>::constant(0.0); 6];
672    for (slot, x) in lifted_state.iter_mut().zip(satellite) {
673        *slot = Dual::constant(*x);
674    }
675    let (_, parameter_jacobian) =
676        jacobian::<K, 1, _>(|p| [observable.value(&lifted_state, p)], parameters);
677
678    let mut state = [0.0; 6];
679    for (slot, row) in state.iter_mut().zip(&state_jacobian) {
680        *slot = row[0];
681    }
682    let mut columns = [0.0; K];
683    for (slot, row) in columns.iter_mut().zip(&parameter_jacobian) {
684        *slot = row[0];
685    }
686    Partials {
687        value: value[0],
688        state,
689        parameters: columns,
690    }
691}
692
693#[cfg(test)]
694mod tests {
695    // The Maxima reference below is written at the precision it was computed to, not at the
696    // shortest `f64` that round-trips: a truncated constant cannot be checked against the source.
697    #![allow(
698        clippy::excessive_precision,
699        clippy::expect_used,
700        clippy::unwrap_used,
701        clippy::many_single_char_names
702    )]
703
704    use spacelab_testkit::assert_within_ulps;
705
706    use super::*;
707    use crate::radiometric::{AKSIM_PAVLOV_2022, SOLAR_RADIUS};
708
709    /// IERS 2010 conventional GM, m³/s² — the value `derivations/shapiro_delay.mac` uses.
710    const EARTH_GM: f64 = 3.986_004_418e14;
711    const EARTH_RADIUS: f64 = 6_378_137.0;
712
713    fn station() -> Station {
714        Station::fixed([4_075_530.0, 931_781.0, 4_801_618.0])
715    }
716
717    fn topocentric() -> Topocentric {
718        Topocentric::from_geodetic([4_075_530.0, 931_781.0, 4_801_618.0], 0.8977, 0.2251)
719    }
720
721    fn satellite() -> [f64; 6] {
722        [
723            3_961_000.0,
724            2_614_000.0,
725            5_215_000.0,
726            -3_140.0,
727            6_190.0,
728            -0.7e3,
729        ]
730    }
731
732    /// Lifting an observable into the layer adds no arithmetic: every one of the six reproduces the
733    /// free function it wraps to the bit, at a state where no component is zero or shared.
734    #[test]
735    fn every_observable_reproduces_the_free_function_to_the_ulp() {
736        let (sat, st, tp) = (satellite(), station(), topocentric());
737        let none: [f64; 0] = [];
738        assert_within_ulps(
739            Range { station: st }.value(&sat, &none),
740            range(&sat, &st),
741            0,
742            "range",
743        );
744        assert_within_ulps(
745            RangeRate { station: st }.value(&sat, &none),
746            range_rate(&sat, &st),
747            0,
748            "range rate",
749        );
750        assert_within_ulps(
751            RightAscension { station: st }.value(&sat, &none),
752            right_ascension(&sat, &st),
753            0,
754            "right ascension",
755        );
756        assert_within_ulps(
757            Declination { station: st }.value(&sat, &none),
758            declination(&sat, &st),
759            0,
760            "declination",
761        );
762        assert_within_ulps(
763            Elevation { topocentric: tp }.value(&sat, &none),
764            elevation(&sat, &tp),
765            0,
766            "elevation",
767        );
768        assert_within_ulps(
769            Azimuth { topocentric: tp }.value(&sat, &none),
770            azimuth(&sat, &tp),
771            0,
772            "azimuth",
773        );
774    }
775
776    /// A chain is its terms summed in the order they were added, and nothing else. Written against
777    /// the hand-composed expression the layer exists to replace, at zero ulps: if the decorator
778    /// carried any arithmetic of its own — a reordering, a fused multiply, a second `sqrt` — this is
779    /// where it would show.
780    #[test]
781    fn a_chain_is_the_hand_written_composition_to_the_ulp() {
782        let (sat, st) = (satellite(), station());
783        let none: [f64; 0] = [];
784        let shapiro = ShapiroDelay {
785            station: st.position,
786            gm: EARTH_GM,
787        };
788        let bias = Bias { value: -0.012 };
789
790        let chained = Modified::new(Range { station: st }, shapiro)
791            .with(bias)
792            .value(&sat, &none);
793        let by_hand = range(&sat, &st) + shapiro.delta(&sat, &none) + bias.delta(&sat, &none);
794        assert_within_ulps(chained, by_hand, 0, "the chained composition");
795    }
796
797    /// The closed form against Maxima at 40 digits.
798    ///
799    /// `derivations/shapiro_delay.mac` proves the antiderivative and the reduction to the IERS form
800    /// symbolically (both residuals exactly 0) and then evaluates it as a bigfloat at
801    /// `(r₁, r₂, p) = (7000000, 7500000, 900000)` m with the same GM:
802    /// `1.102527717326717568931198e-3` m.
803    #[test]
804    fn the_shapiro_delay_matches_the_maxima_closed_form() {
805        let maxima = 1.102_527_717_326_717_568_931_198e-3;
806        assert_within_ulps(
807            shapiro_delay(7.0e6, 7.5e6, 9.0e5, EARTH_GM),
808            maxima,
809            1,
810            "the Shapiro delay against Maxima",
811        );
812    }
813
814    /// Coincident endpoints have no path and no delay — `log(1)`, exactly zero, not a small
815    /// residue that a cancellation happened to leave behind.
816    #[test]
817    fn the_shapiro_delay_vanishes_when_the_endpoints_coincide() {
818        assert_within_ulps(
819            shapiro_delay(EARTH_RADIUS, EARTH_RADIUS, 0.0, EARTH_GM),
820            0.0,
821            0,
822            "the delay over no path",
823        );
824    }
825
826    /// The modifier is the closed form evaluated at the leg's own geometry, to the bit: the two
827    /// geocentric distances and the straight-line path, and no fourth quantity.
828    #[test]
829    fn the_shapiro_modifier_is_the_closed_form_at_the_leg_geometry() {
830        let (sat, st) = (satellite(), station());
831        let none: [f64; 0] = [];
832        let modifier = ShapiroDelay {
833            station: st.position,
834            gm: EARTH_GM,
835        };
836        let r_sat = libm::sqrt(sat[0] * sat[0] + sat[1] * sat[1] + sat[2] * sat[2]);
837        let p = st.position;
838        let r_sta = libm::sqrt(p[0] * p[0] + p[1] * p[1] + p[2] * p[2]);
839        assert_within_ulps(
840            modifier.delta(&sat, &none),
841            shapiro_delay(r_sat, r_sta, range(&sat, &st), EARTH_GM),
842            0,
843            "the modifier against the closed form",
844        );
845    }
846
847    /// The correction is differentiated, not pasted on.
848    ///
849    /// `∂D/∂rᵢ = k[(∂s + ∂p)/(s + p) − (∂s − ∂p)/(s − p)]` with `s = r_sat + r_sta`,
850    /// `∂s/∂rᵢ = rᵢ/r_sat`, `∂p/∂rᵢ = (rᵢ − stationᵢ)/p` and `k = 2GM/c²`. The AD partial of the
851    /// delay agrees with it to **6.7e-16 relative** on a partial of size 1.9e-10 per metre.
852    ///
853    /// The chain's own partial is then checked to carry it, and *that* comparison has a floor the
854    /// correction has nothing to do with: the geometric partial is of order 1, the delay's is
855    /// 1e-10, and differencing two `f64`s ten decades apart leaves about `ε/2` of the larger —
856    /// 3.4e-17 was measured here, which is why the bound below is 1e-16 and not the 1e-15 relative
857    /// the AD itself reaches.
858    #[test]
859    fn the_shapiro_partials_are_the_closed_form_derivative() {
860        let (sat, st) = (satellite(), station());
861        let none: [f64; 0] = [];
862        let modifier = ShapiroDelay {
863            station: st.position,
864            gm: EARTH_GM,
865        };
866
867        let r_sat = libm::sqrt(sat[0] * sat[0] + sat[1] * sat[1] + sat[2] * sat[2]);
868        let q = st.position;
869        let r_sta = libm::sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2]);
870        let path = range(&sat, &st);
871        let s = r_sat + r_sta;
872        let k = 2.0 * EARTH_GM / (SPEED_OF_LIGHT * SPEED_OF_LIGHT);
873
874        let (_, delay_jacobian) = jacobian::<6, 1, _>(|z| [modifier.delta(z, &[])], &sat);
875        let bare = partials(&Range { station: st }, &sat, &none);
876        let decorated = partials(&Modified::new(Range { station: st }, modifier), &sat, &none);
877
878        for i in 0..3 {
879            let ds = sat[i] / r_sat;
880            let dp = (sat[i] - q[i]) / path;
881            let want = k * ((ds + dp) / (s + path) - (ds - dp) / (s - path));
882            assert!(
883                want.abs() > 1e-11,
884                "the delay partial {want} is too small to test"
885            );
886            assert!(
887                (delay_jacobian[i][0] - want).abs() <= 1e-14 * want.abs(),
888                "∂(Shapiro)/∂r[{i}] = {} against the closed form {want}",
889                delay_jacobian[i][0]
890            );
891            let carried = decorated.state[i] - bare.state[i];
892            assert!(
893                (carried - want).abs() < 1e-16,
894                "the chain carried {carried} of the delay partial {want}"
895            );
896        }
897        // A delay does not depend on velocity, so those partials are untouched.
898        for i in 3..6 {
899            assert_within_ulps(decorated.state[i], bare.state[i], 0, "a velocity partial");
900        }
901    }
902
903    /// An estimated bias is a unit column in the Jacobian and changes nothing else: the value moves
904    /// by the bias, the state partials do not move at all.
905    #[test]
906    fn an_estimated_bias_is_a_unit_column_and_leaves_the_state_partials_alone() {
907        let (sat, st) = (satellite(), station());
908        let bias = EstimatedBias::<2>::new(1).expect("index 1 of 2");
909        assert_eq!(bias.index(), 1);
910        let observable = Modified::new(Range { station: st }, bias);
911
912        let p = partials(&observable, &sat, &[0.0, 4.75]);
913        let bare = partials(&Range { station: st }, &sat, &[0.0, 4.75]);
914        assert_within_ulps(p.value, bare.value + 4.75, 0, "the biased value");
915        assert_within_ulps(p.parameters[1], 1.0, 0, "∂range/∂bias");
916        assert_within_ulps(p.parameters[0], 0.0, 0, "∂range/∂(unused parameter)");
917        for i in 0..6 {
918            assert_within_ulps(p.state[i], bare.state[i], 0, "a state partial");
919        }
920    }
921
922    /// A parameter index past the vector is refused at construction, so evaluation cannot read one
923    /// that does not exist.
924    #[test]
925    fn an_estimated_parameter_past_the_vector_is_refused() {
926        assert_eq!(
927            EstimatedBias::<2>::new(2),
928            Err(ModifierError::ParameterOutOfRange {
929                index: 2,
930                parameters: 2,
931            })
932        );
933        assert!(EstimatedBias::<2>::new(1).is_ok());
934        assert!(EstimatedBias::<0>::new(0).is_err());
935    }
936
937    /// The index a bias reports is the parameter it reads, at every index the vector has.
938    ///
939    /// Checked across the whole vector rather than at one index: a reader that answered with a fixed
940    /// index would agree with a single-index test and disagree with the parameter actually read.
941    #[test]
942    fn an_estimated_bias_reports_the_parameter_it_reads() {
943        let parameters = [-2.0, 3.5, 7.25];
944        for index in 0..parameters.len() {
945            let bias = EstimatedBias::<3>::new(index).expect("index within the vector");
946            assert_eq!(bias.index(), index);
947            assert_within_ulps(
948                bias.delta(&[0.0; 6], &parameters),
949                parameters[index],
950                0,
951                "the bias read from its own parameter",
952            );
953        }
954    }
955
956    /// The one refusal says which index was asked for and how many the chain carries — the two
957    /// numbers a caller needs to fix the call.
958    #[test]
959    fn the_out_of_range_refusal_names_both_numbers() {
960        let error = ModifierError::ParameterOutOfRange {
961            index: 3,
962            parameters: 2,
963        };
964        let expected = "estimated parameter 3 is past the 2 the measurement carries";
965        assert_eq!(format!("{error}"), expected);
966        let dynamic: &dyn core::error::Error = &error;
967        assert_eq!(format!("{dynamic}"), expected);
968    }
969
970    /// A zenith delay mapped by `1/sin(elevation)` with an azimuthal gradient — a stand-in for the
971    /// models in `spacelab_gnss`, which this crate cannot reach, exercising both arguments.
972    struct MappedDelay {
973        zenith: f64,
974        gradient: f64,
975    }
976
977    impl SlantDelay for MappedDelay {
978        fn delay<S: Scalar>(&self, elevation: S, azimuth: S) -> S {
979            (S::from_f64(self.zenith) + S::from_f64(self.gradient) * azimuth.cos())
980                * elevation.sin().recip()
981        }
982    }
983
984    /// A supplied delay model reaches the observable through the line of sight it implies, and its
985    /// elevation dependence survives into the partials.
986    ///
987    /// The value is checked to the bit against the model called directly. The partial is checked
988    /// against a central difference, which is an independent route with its own `√ε` floor: measured
989    /// **1.8e-10 relative**, on partials of order 1e-5 m/m and a delay of 8.23 m at the 16.3°
990    /// elevation of this geometry. The bound is left at 1e-7, the floor the difference itself has.
991    #[test]
992    fn a_supplied_delay_reaches_the_observable_through_the_line_of_sight() {
993        let (sat, tp) = (satellite(), topocentric());
994        let none: [f64; 0] = [];
995        let modifier = AtmosphericDelay {
996            topocentric: tp,
997            model: MappedDelay {
998                zenith: 2.31,
999                gradient: 0.04,
1000            },
1001        };
1002        assert_within_ulps(
1003            modifier.delta(&sat, &none),
1004            modifier
1005                .model
1006                .delay(elevation(&sat, &tp), azimuth(&sat, &tp)),
1007            0,
1008            "the delay at the line of sight",
1009        );
1010
1011        let observable = Modified::new(Elevation { topocentric: tp }, modifier);
1012        let p = partials(&observable, &sat, &none);
1013        let h = 1.0;
1014        for i in 0..3 {
1015            let (mut lo, mut hi) = (sat, sat);
1016            lo[i] -= h;
1017            hi[i] += h;
1018            let central = (observable.value(&hi, &none) - observable.value(&lo, &none)) / (2.0 * h);
1019            assert!(
1020                (p.state[i] - central).abs() <= 1e-7 * central.abs(),
1021                "∂/∂r[{i}] = {} against the central difference {central}",
1022                p.state[i]
1023            );
1024        }
1025    }
1026
1027    /// IAU 2015 Resolution B3 nominal solar mass parameter, m³/s² — an exact defining constant.
1028    const SUN_GM: f64 = 1.327_124_4e20;
1029    /// IAU 2012 Resolution B2 astronomical unit, metres — exact.
1030    const ASTRONOMICAL_UNIT: f64 = 1.495_978_707e11;
1031
1032    /// Earth and a deep-space probe at superior conjunction, both referred to the Sun at the origin,
1033    /// on a line of sight passing `impact` metres from the Sun's centre.
1034    ///
1035    /// The probe is at Cassini's heliocentric distance during the 2002 conjunction, 8.43 AU. The
1036    /// separation angle is solved for rather than assumed: `b = r_e r_p sin δ / p` with `p` the
1037    /// straight-line path, whose own dependence on `δ` the fixed point below removes. Every test
1038    /// that uses this reads the impact parameter back out of the geometry rather than trusting it.
1039    ///
1040    /// **The conjunction plane is deliberately not a coordinate plane.** Written on the axes — Earth
1041    /// on `x`, probe in `xy` — it is the same conjunction up to a rotation and gives the same delay,
1042    /// and it leaves `station[1] = station[2] = satellite[2] = 0` through every evaluation. Seven of
1043    /// `seal-estimation-325`'s nine survivors were that fixture: with a zero component, `y·y` and
1044    /// `z·z` are both `0`, so `*` → `+` and `+` → `-` in the two geocentric radii change nothing at
1045    /// all. `seal-radiometric` had found the identical gap one module over, in `angle_between`, and
1046    /// the remedy is the same one — build on two orthonormal directions with no zero component,
1047    /// `u = (2,3,6)/7` and `v = (3,6,−4)/√61`, which are exactly orthogonal (`6 + 18 − 24 = 0`).
1048    /// A rotation leaves every distance and the impact parameter invariant, so nothing else moves.
1049    fn conjunction(impact: f64) -> ([f64; 3], [f64; 6]) {
1050        const U: [f64; 3] = [2.0 / 7.0, 3.0 / 7.0, 6.0 / 7.0];
1051        let root61 = libm::sqrt(61.0);
1052        let v = [3.0 / root61, 6.0 / root61, -4.0 / root61];
1053
1054        let (r_earth, r_probe) = (ASTRONOMICAL_UNIT, 8.43 * ASTRONOMICAL_UNIT);
1055        let mut delta = libm::asin(impact * (r_earth + r_probe) / (r_earth * r_probe));
1056        for _ in 0..4 {
1057            let path = libm::sqrt(
1058                r_earth * r_earth + r_probe * r_probe + 2.0 * r_earth * r_probe * libm::cos(delta),
1059            );
1060            delta = libm::asin(impact * path / (r_earth * r_probe));
1061        }
1062        let (sin_delta, cos_delta) = (libm::sin(delta), libm::cos(delta));
1063
1064        let mut earth = [0.0_f64; 3];
1065        let mut probe = [0.0_f64; 6];
1066        for i in 0..3 {
1067            earth[i] = r_earth * U[i];
1068            probe[i] = r_probe * (v[i] * sin_delta - U[i] * cos_delta);
1069        }
1070        (earth, probe)
1071    }
1072
1073    /// The perpendicular distance from the origin to the line through two points.
1074    fn impact_parameter(a: &[f64; 3], b: &[f64; 3]) -> f64 {
1075        let cross = [
1076            a[1] * b[2] - a[2] * b[1],
1077            a[2] * b[0] - a[0] * b[2],
1078            a[0] * b[1] - a[1] * b[0],
1079        ];
1080        let separation = libm::sqrt(
1081            (a[0] - b[0]) * (a[0] - b[0])
1082                + (a[1] - b[1]) * (a[1] - b[1])
1083                + (a[2] - b[2]) * (a[2] - b[2]),
1084        );
1085        libm::sqrt(cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]) / separation
1086    }
1087
1088    /// Writing `γ` out changes nothing at `γ = 1`: general relativity is the one-parameter family's
1089    /// own member, to the bit, and not a value the second implementation happens to come close to.
1090    ///
1091    /// Checked over four decades of path geometry, because the two differ in *where* the factor two
1092    /// sits — `2GM/c²` against `(1 + γ) · GM/c²` — and a scaling that is exact at one magnitude and
1093    /// rounds at another would show as a one-ulp disagreement somewhere along this sweep.
1094    #[test]
1095    fn the_ppn_shapiro_delay_is_the_relativistic_one_at_unit_gamma() {
1096        for path in [9.0e5, 9.0e6, 6.0e7, 1.2e9] {
1097            let (r1, r2) = (7.0e6 + path, 7.5e6 + path);
1098            assert_within_ulps(
1099                shapiro_delay_ppn(r1, r2, path, EARTH_GM, 1.0),
1100                shapiro_delay(r1, r2, path, EARTH_GM),
1101                0,
1102                "the PPN form at γ = 1",
1103            );
1104        }
1105    }
1106
1107    /// `γ` scales the delay and nothing else: the value is linear in `1 + γ` and the partial is the
1108    /// slope of that line, `Δρ/(1 + γ)`, which is what makes a tracking arc a measurement of `γ`.
1109    ///
1110    /// The geometry is Cassini's 2002 superior conjunction — 1 AU to 8.43 AU with the ray passing
1111    /// 1.6 solar radii from the Sun's centre. The measured one-way delay there is **39 333.7 m**
1112    /// and the partial is half of it, **19 666.8 m per unit `γ`**. Two independent checks stand
1113    /// behind that. The closed form is compared against the near-conjunction asymptote
1114    /// `(1 + γ)(GM/c²) ln(4 r_e r_p / b²)`, which is a different expression of the same geometry
1115    /// and agrees to better than 1e-5 relative; and the AD partial is compared against
1116    /// `Δρ/(1 + γ)`, which is analytic and shares no code with the AD pass.
1117    ///
1118    /// Bertotti, Iess & Tortora, *Nature* **425**, 374 (2003) measured `γ − 1 = (2.1 ± 2.3) × 10⁻⁵`
1119    /// from this geometry; against a 19.7 km partial that uncertainty is 45 cm of range, which is
1120    /// the scale a Ka-band tracking system reaches and the reason the parameter is estimable at all.
1121    #[test]
1122    fn an_estimated_gamma_is_the_delay_divided_by_one_plus_gamma() {
1123        let (earth, probe) = conjunction(1.6 * SOLAR_RADIUS);
1124        let impact = impact_parameter(&earth, &[probe[0], probe[1], probe[2]]);
1125        assert!(
1126            (impact - 1.6 * SOLAR_RADIUS).abs() < 1e-6 * SOLAR_RADIUS,
1127            "the conjunction geometry was placed at {impact} m from the Sun"
1128        );
1129
1130        let gamma = 1.0;
1131        let modifier = EstimatedShapiroDelay::<1>::new(earth, SUN_GM, 0).expect("index 0 of 1");
1132        assert_eq!(modifier.index(), 0);
1133        let observable = Modified::new(
1134            Range {
1135                station: Station::fixed(earth),
1136            },
1137            modifier,
1138        );
1139        let p = partials(&observable, &probe, &[gamma]);
1140
1141        let delay = modifier.delta(&probe, &[gamma]);
1142        let r_probe = libm::sqrt(probe[0] * probe[0] + probe[1] * probe[1] + probe[2] * probe[2]);
1143        let r_earth = libm::sqrt(earth[0] * earth[0] + earth[1] * earth[1] + earth[2] * earth[2]);
1144        let asymptote = libm::log(4.0 * r_earth * r_probe / (impact * impact));
1145        let approximate = (1.0 + gamma) * SUN_GM / (SPEED_OF_LIGHT * SPEED_OF_LIGHT) * asymptote;
1146        assert!(
1147            (delay - approximate).abs() < 1e-5 * delay,
1148            "the closed form {delay} m against the near-conjunction asymptote {approximate} m"
1149        );
1150        assert!(
1151            (39_300.0..39_400.0).contains(&delay),
1152            "the conjunction delay is {delay} m, not the 39.33 km the doc comment claims"
1153        );
1154
1155        assert!(
1156            (p.parameters[0] - delay / (1.0 + gamma)).abs() < 1e-12 * delay,
1157            "∂ρ/∂γ = {} against Δρ/(1 + γ) = {}",
1158            p.parameters[0],
1159            delay / (1.0 + gamma)
1160        );
1161        assert!(
1162            (19_650.0..19_690.0).contains(&p.parameters[0]),
1163            "∂ρ/∂γ is {} m, not the 19.67 km the doc comment claims",
1164            p.parameters[0]
1165        );
1166        // The whole family, not one member: doubling `1 + γ` doubles the delay exactly.
1167        assert_within_ulps(
1168            modifier.delta(&probe, &[3.0]),
1169            2.0 * delay,
1170            0,
1171            "the delay at γ = 3",
1172        );
1173        assert_within_ulps(
1174            modifier.delta(&probe, &[-1.0]),
1175            0.0,
1176            0,
1177            "the delay at γ = −1",
1178        );
1179    }
1180
1181    /// An out-of-range `γ` index is refused at construction, like every other estimated parameter.
1182    #[test]
1183    fn an_estimated_gamma_past_the_vector_is_refused() {
1184        assert_eq!(
1185            EstimatedShapiroDelay::<2>::new([0.0, 0.0, 0.0], SUN_GM, 2),
1186            Err(ModifierError::ParameterOutOfRange {
1187                index: 2,
1188                parameters: 2,
1189            })
1190        );
1191        assert!(EstimatedShapiroDelay::<2>::new([0.0, 0.0, 0.0], SUN_GM, 1).is_ok());
1192    }
1193
1194    /// `γ` is read from the slot the chain was built with, at every slot the vector has.
1195    ///
1196    /// Checked across the whole vector rather than at one index, for the reason
1197    /// [`an_estimated_bias_reports_the_parameter_it_reads`] is: a reader answering with a fixed
1198    /// index agrees with a single-index test and disagrees with the parameter actually read. The
1199    /// delay assertion is the same fact from the other side — wherever `γ = 1` is placed the answer
1200    /// is general relativity's, and the two slots holding nonsense are not read.
1201    #[test]
1202    fn an_estimated_gamma_reports_and_reads_its_own_slot() {
1203        let (earth, probe) = conjunction(1.6 * SOLAR_RADIUS);
1204        let relativity = ShapiroDelay {
1205            station: earth,
1206            gm: SUN_GM,
1207        };
1208        let none: [f64; 0] = [];
1209        let expected: f64 = relativity.delta(&probe, &none);
1210
1211        for index in 0..3 {
1212            let modifier =
1213                EstimatedShapiroDelay::<3>::new(earth, SUN_GM, index).expect("within the vector");
1214            assert_eq!(modifier.index(), index);
1215            let mut parameters = [-7.5_f64; 3];
1216            parameters[index] = 1.0;
1217            assert_within_ulps(
1218                modifier.delta(&probe, &parameters),
1219                expected,
1220                0,
1221                "the delay at γ = 1 read from its own slot",
1222            );
1223        }
1224    }
1225
1226    /// A drifting clock is two unit-and-ramp columns: `∂/∂bias = 1` and `∂/∂rate = Δt`, exactly,
1227    /// with the state partials untouched — which is the whole difference from [`EstimatedBias`],
1228    /// whose second column does not exist.
1229    #[test]
1230    fn a_drifting_clock_contributes_a_unit_column_and_a_ramp_column() {
1231        let (sat, st) = (satellite(), station());
1232        let elapsed = 1_837.5;
1233        // Neither index is zero and neither is the other: an accessor answering with a fixed slot,
1234        // or with the wrong one of the two, agrees with no assertion below.
1235        let drift =
1236            EstimatedDrift::<3>::new(elapsed, 2, 1).expect("both indices within the vector");
1237        assert_eq!(drift.bias_index(), 2);
1238        assert_eq!(drift.rate_index(), 1);
1239
1240        let parameters = [0.0, 1.25e-3, -0.4];
1241        let observable = Modified::new(Range { station: st }, drift);
1242        let p = partials(&observable, &sat, &parameters);
1243        let bare = partials(&Range { station: st }, &sat, &parameters);
1244
1245        assert_within_ulps(
1246            p.value,
1247            bare.value + parameters[2] + parameters[1] * elapsed,
1248            0,
1249            "the drifted range",
1250        );
1251        assert_within_ulps(p.parameters[2], 1.0, 0, "∂range/∂bias");
1252        assert_within_ulps(p.parameters[1], elapsed, 0, "∂range/∂rate");
1253        assert_within_ulps(p.parameters[0], 0.0, 0, "∂range/∂(unused parameter)");
1254        for i in 0..6 {
1255            assert_within_ulps(p.state[i], bare.state[i], 0, "a state partial");
1256        }
1257        // Every pairing of the three slots, so that neither accessor can answer with a constant.
1258        for (bias, rate) in [(0, 1), (1, 2), (2, 0)] {
1259            let placed = EstimatedDrift::<3>::new(7.0, bias, rate).expect("within the vector");
1260            assert_eq!((placed.bias_index(), placed.rate_index()), (bias, rate));
1261        }
1262        // At the arc's own reference epoch the rate is unobservable and the bias is all there is.
1263        let at_epoch = EstimatedDrift::<3>::new(0.0, 2, 1).expect("both indices within the vector");
1264        assert_within_ulps(
1265            at_epoch.delta(&sat, &parameters),
1266            parameters[2],
1267            0,
1268            "the drift at Δt = 0",
1269        );
1270    }
1271
1272    /// Both indices are checked, and the refusal names whichever one is past the vector — a drift
1273    /// whose rate index is wrong is as unevaluable as one whose bias index is.
1274    #[test]
1275    fn a_drift_names_whichever_index_is_past_the_vector() {
1276        assert_eq!(
1277            EstimatedDrift::<2>::new(0.0, 2, 1),
1278            Err(ModifierError::ParameterOutOfRange {
1279                index: 2,
1280                parameters: 2,
1281            })
1282        );
1283        assert_eq!(
1284            EstimatedDrift::<2>::new(0.0, 1, 7),
1285            Err(ModifierError::ParameterOutOfRange {
1286                index: 7,
1287                parameters: 2,
1288            })
1289        );
1290        // Both wrong reports the first, which is the one the caller fixes first.
1291        assert_eq!(
1292            EstimatedDrift::<2>::new(0.0, 5, 7),
1293            Err(ModifierError::ParameterOutOfRange {
1294                index: 5,
1295                parameters: 2,
1296            })
1297        );
1298        assert!(EstimatedDrift::<2>::new(0.0, 1, 0).is_ok());
1299    }
1300
1301    /// The corona modifier is [`solar_corona_delay`] at the leg's own geometry, to the bit, and it
1302    /// refers both endpoints to the Sun rather than to the frame origin.
1303    ///
1304    /// The second half is the part a value comparison alone would miss: the delay is a function of
1305    /// the three positions *relative to the Sun*, so translating station, Sun and satellite together
1306    /// must leave it unchanged. A sign slip in the subtraction passes the first assertion at one
1307    /// frame origin and fails this one at any other.
1308    #[test]
1309    fn the_corona_modifier_is_the_path_integral_referred_to_the_sun() {
1310        let series = CoronaSeries::new(&AKSIM_PAVLOV_2022).expect("the published one-term series");
1311        let (earth_from_sun, probe_from_sun) = conjunction(4.0 * SOLAR_RADIUS);
1312        let sun = [1.0e10, -2.0e10, 3.0e10];
1313        let station = [
1314            sun[0] + earth_from_sun[0],
1315            sun[1] + earth_from_sun[1],
1316            sun[2] + earth_from_sun[2],
1317        ];
1318        let mut satellite = [0.0; 6];
1319        for i in 0..3 {
1320            satellite[i] = sun[i] + probe_from_sun[i];
1321        }
1322
1323        let frequency = 8.4e9;
1324        let none: [f64; 0] = [];
1325        let modifier =
1326            SolarCoronaDelay::new(station, sun, series, frequency, PlasmaSignature::GroupDelay)
1327                .expect("a positive X-band frequency");
1328        let direct = solar_corona_delay(
1329            &series,
1330            &[probe_from_sun[0], probe_from_sun[1], probe_from_sun[2]],
1331            &earth_from_sun,
1332            frequency,
1333            PlasmaSignature::GroupDelay,
1334        )
1335        .expect("a line of sight outside the Sun");
1336        assert_within_ulps(
1337            modifier.delta(&satellite, &none),
1338            direct,
1339            0,
1340            "the corona modifier against the path integral",
1341        );
1342
1343        let shifted_sun = [sun[0] - 7.0e11, sun[1] + 5.0e11, sun[2] - 1.0e11];
1344        let shifted_station = [
1345            station[0] - 7.0e11,
1346            station[1] + 5.0e11,
1347            station[2] - 1.0e11,
1348        ];
1349        let mut shifted_satellite = satellite;
1350        shifted_satellite[0] -= 7.0e11;
1351        shifted_satellite[1] += 5.0e11;
1352        shifted_satellite[2] -= 1.0e11;
1353        let shifted = SolarCoronaDelay::new(
1354            shifted_station,
1355            shifted_sun,
1356            series,
1357            frequency,
1358            PlasmaSignature::GroupDelay,
1359        )
1360        .expect("a positive X-band frequency");
1361        // Not zero ulps, and the reason is the translation and not the model: shifting a 1.5e11 m
1362        // coordinate by 7e11 m and subtracting it back rounds off three bits, which reaches the
1363        // impact parameter — a difference of two nearly-parallel vectors — as ~1e-14 relative.
1364        // Measured 6 ulps on a 112 m delay; the bound is 32, still five orders below any sign slip.
1365        assert_within_ulps(
1366            shifted.delta(&shifted_satellite, &none),
1367            direct,
1368            32,
1369            "the corona delay under a common translation",
1370        );
1371
1372        // A group delay is late and a phase advance is early, by the same column.
1373        let phase = SolarCoronaDelay::new(
1374            station,
1375            sun,
1376            series,
1377            frequency,
1378            PlasmaSignature::PhaseAdvance,
1379        )
1380        .expect("a positive X-band frequency");
1381        assert_within_ulps(
1382            phase.delta(&satellite, &none),
1383            -direct,
1384            0,
1385            "the phase-advance signature",
1386        );
1387        assert!(
1388            direct > 0.0 && direct.is_finite(),
1389            "the X-band corona delay at four solar radii is {direct} m"
1390        );
1391    }
1392
1393    /// [`SolarCoronaDelay::occulted`] answers the question [`Modifier::delta`]'s NaN encodes, and it
1394    /// answers it at the same geometries — checked by walking the line of sight across the limb from
1395    /// an eighth of a solar radius out to nearly four, rather than at a single point on either side.
1396    ///
1397    /// The sweep steps by 0.25 R☉ off a half-step offset, so it never lands on the limb. That is
1398    /// than convenient: [`conjunction`] places the ray by a fixed point that converges to about
1399    /// 1e-9 R☉, and `solar_corona_delay`'s test is the strict `impact < SOLAR_RADIUS`, so at
1400    /// exactly one solar radius the verdict is decided by the last bit of the placement and the
1401    /// assertion would be measuring the generator. Either side of it is a real question.
1402    #[test]
1403    fn occultation_is_exactly_where_the_corona_delay_has_no_value() {
1404        let series = CoronaSeries::new(&AKSIM_PAVLOV_2022).expect("the published one-term series");
1405        let none: [f64; 0] = [];
1406        let mut inside = 0;
1407        let mut outside = 0;
1408        for step in 0..16 {
1409            let radii = 0.25 * f64::from(step) + 0.125;
1410            let (earth_from_sun, probe) = conjunction(radii * SOLAR_RADIUS);
1411            let modifier = SolarCoronaDelay::new(
1412                earth_from_sun,
1413                [0.0, 0.0, 0.0],
1414                series,
1415                8.4e9,
1416                PlasmaSignature::GroupDelay,
1417            )
1418            .expect("a positive X-band frequency");
1419            let value: f64 = modifier.delta(&probe, &none);
1420            assert_eq!(
1421                modifier.occulted(&probe),
1422                value.is_nan(),
1423                "at {radii} solar radii the verdict and the value disagree ({value} m)"
1424            );
1425            if radii < 1.0 {
1426                assert!(modifier.occulted(&probe), "{radii} solar radii is inside");
1427                inside += 1;
1428            } else {
1429                assert!(
1430                    !modifier.occulted(&probe) && value > 0.0,
1431                    "{radii} solar radii is a link, and the delay is {value} m"
1432                );
1433                outside += 1;
1434            }
1435        }
1436        assert_eq!(
1437            (inside, outside),
1438            (4, 12),
1439            "the sweep crossed the limb once"
1440        );
1441    }
1442
1443    /// A frequency that is not positive and finite is refused once, at construction, so evaluation
1444    /// carries no error the caller has to handle on every observation.
1445    #[test]
1446    fn a_corona_link_without_a_frequency_is_refused_at_construction() {
1447        let series = CoronaSeries::new(&AKSIM_PAVLOV_2022).expect("the published one-term series");
1448        for frequency in [0.0, -8.4e9, f64::NAN, f64::INFINITY] {
1449            assert!(
1450                matches!(
1451                    SolarCoronaDelay::new(
1452                        [0.0, 0.0, 0.0],
1453                        [0.0, 0.0, 0.0],
1454                        series,
1455                        frequency,
1456                        PlasmaSignature::GroupDelay,
1457                    ),
1458                    Err(RadiometricError::NonPositiveFrequency { .. })
1459                ),
1460                "{frequency} Hz was accepted as a carrier"
1461            );
1462        }
1463        assert!(
1464            SolarCoronaDelay::new(
1465                [0.0, 0.0, 0.0],
1466                [0.0, 0.0, 0.0],
1467                series,
1468                8.4e9,
1469                PlasmaSignature::GroupDelay,
1470            )
1471            .is_ok()
1472        );
1473    }
1474
1475    /// `partials` is the same two quantities a caller would get from AD by hand, at zero ulps —
1476    /// it exists to keep the chain rule in one place, not to compute anything of its own.
1477    #[test]
1478    fn partials_agree_with_a_direct_ad_pass() {
1479        let (sat, st) = (satellite(), station());
1480        let observable = Modified::new(
1481            Range { station: st },
1482            ShapiroDelay {
1483                station: st.position,
1484                gm: EARTH_GM,
1485            },
1486        )
1487        .with(EstimatedBias::<1>::new(0).expect("index 0 of 1"));
1488        let parameters = [-0.031];
1489
1490        let p = partials(&observable, &sat, &parameters);
1491        let lifted = [Dual::<6>::constant(parameters[0]); 1];
1492        let (value, jac) = jacobian::<6, 1, _>(|s| [observable.value(s, &lifted)], &sat);
1493        assert_within_ulps(p.value, value[0], 0, "the value");
1494        for (i, row) in jac.iter().enumerate() {
1495            assert_within_ulps(p.state[i], row[0], 0, "a state partial");
1496        }
1497    }
1498}