Skip to main content

sidereon_core/
observables.rs

1//! Forward GNSS observable prediction.
2//!
3//! This module owns the language-independent geometry behind Sidereon'
4//! `Observables.predict`: transmit-time iteration, Sagnac rotation, line of
5//! sight, range rate, Doppler, and topocentric azimuth/elevation. Ephemeris
6//! parsing and interpolation stay with their existing SP3/broadcast products.
7
8use crate::astro::frames::transforms::itrs_to_geodetic_compute;
9use std::f64::consts::PI;
10
11use crate::astro::time::civil;
12use crate::constants::{
13    AZIMUTH_ZENITH_EPS, C_M_S, DEGREES_PER_CIRCLE, DEGREES_PER_SEMICIRCLE, F_L1_HZ, KM_TO_M,
14    MICROSECONDS_PER_SECOND, OBSERVABLE_TRANSMIT_TIME_ITERATIONS, OMEGA_E_DOT_RAD_S,
15};
16use crate::ephemeris::BroadcastEphemeris;
17use crate::estimation::recipe::SagnacRecipe;
18use crate::id::GnssSatelliteId;
19use crate::sp3::Sp3;
20use crate::spp::EphemerisSource;
21use crate::validate;
22use crate::Error;
23use rayon::prelude::*;
24
25const FD_HALF_S: f64 = 0.5;
26
27/// Satellite state required by the observable predictor.
28#[derive(Debug, Clone, Copy, PartialEq)]
29pub struct ObservableState {
30    /// Satellite ECEF position in meters at the query epoch.
31    pub position_ecef_m: [f64; 3],
32    /// Satellite clock offset in seconds. SP3 clocks can be absent.
33    pub clock_s: Option<f64>,
34}
35
36/// An ephemeris product usable by [`predict`].
37pub trait ObservableEphemerisSource {
38    /// ECEF position and optional satellite clock at seconds since J2000.
39    fn observable_state_at_j2000_s(
40        &self,
41        sat: GnssSatelliteId,
42        t_j2000_s: f64,
43    ) -> Result<ObservableState, ObservablesError>;
44}
45
46impl ObservableEphemerisSource for Sp3 {
47    fn observable_state_at_j2000_s(
48        &self,
49        sat: GnssSatelliteId,
50        t_j2000_s: f64,
51    ) -> Result<ObservableState, ObservablesError> {
52        let state = self
53            .position_at_j2000_seconds(sat, t_j2000_s)
54            .map_err(ObservablesError::Ephemeris)?;
55        Ok(ObservableState {
56            position_ecef_m: state.position.as_array(),
57            clock_s: state.clock_s,
58        })
59    }
60}
61
62impl ObservableEphemerisSource for BroadcastEphemeris {
63    fn observable_state_at_j2000_s(
64        &self,
65        sat: GnssSatelliteId,
66        t_j2000_s: f64,
67    ) -> Result<ObservableState, ObservablesError> {
68        let Some((position_ecef_m, clock_s)) =
69            EphemerisSource::position_clock_at_j2000_s(self, sat, t_j2000_s)
70        else {
71            return Err(ObservablesError::NoEphemeris);
72        };
73        Ok(ObservableState {
74            position_ecef_m,
75            clock_s: Some(clock_s),
76        })
77    }
78}
79
80/// Input-validation failure category for observable prediction.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum ObservablesInputErrorKind {
83    /// A floating-point input was NaN or infinite.
84    NonFinite,
85    /// A positive physical input was zero or negative.
86    NotPositive,
87    /// A non-negative physical input was negative.
88    Negative,
89    /// A finite numeric input was outside its accepted range.
90    OutOfRange,
91    /// A required input field was absent.
92    Missing,
93    /// A text field could not be parsed as a float.
94    FloatParse,
95    /// A text field could not be parsed as an integer.
96    IntParse,
97    /// A civil date field was out of range.
98    InvalidCivilDate,
99    /// A civil time field was out of range.
100    InvalidCivilTime,
101}
102
103impl core::fmt::Display for ObservablesInputErrorKind {
104    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
105        let label = match self {
106            Self::NonFinite => "not finite",
107            Self::NotPositive => "not positive",
108            Self::Negative => "negative",
109            Self::OutOfRange => "out of range",
110            Self::Missing => "missing",
111            Self::FloatParse => "invalid float",
112            Self::IntParse => "invalid integer",
113            Self::InvalidCivilDate => "invalid civil date",
114            Self::InvalidCivilTime => "invalid civil time",
115        };
116        f.write_str(label)
117    }
118}
119
120impl From<&validate::FieldError> for ObservablesInputErrorKind {
121    fn from(error: &validate::FieldError) -> Self {
122        match error {
123            validate::FieldError::Missing { .. } => Self::Missing,
124            validate::FieldError::NonFinite { .. } => Self::NonFinite,
125            validate::FieldError::NotPositive { .. } => Self::NotPositive,
126            validate::FieldError::Negative { .. } => Self::Negative,
127            validate::FieldError::OutOfRange { .. } => Self::OutOfRange,
128            validate::FieldError::FloatParse { .. } => Self::FloatParse,
129            validate::FieldError::IntParse { .. } => Self::IntParse,
130            validate::FieldError::InvalidCivilDate { .. } => Self::InvalidCivilDate,
131            validate::FieldError::InvalidCivilTime { .. } => Self::InvalidCivilTime,
132        }
133    }
134}
135
136/// Error returned by the observable predictor.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub enum ObservablesError {
139    /// A public predictor input or ephemeris-source state was malformed,
140    /// non-finite, or outside its physical domain.
141    InvalidInput {
142        /// The invalid input field.
143        field: &'static str,
144        /// The validation failure category.
145        kind: ObservablesInputErrorKind,
146    },
147    /// The ephemeris product has no usable record for the satellite/epoch.
148    NoEphemeris,
149    /// The underlying ephemeris product returned a structured crate error.
150    Ephemeris(Error),
151}
152
153impl core::fmt::Display for ObservablesError {
154    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
155        match self {
156            Self::InvalidInput { field, kind } => {
157                write!(f, "invalid observable input {field}: {kind}")
158            }
159            Self::NoEphemeris => write!(f, "no ephemeris"),
160            Self::Ephemeris(err) => write!(f, "{err}"),
161        }
162    }
163}
164
165impl std::error::Error for ObservablesError {}
166
167/// Options controlling observable prediction.
168#[derive(Debug, Clone, Copy, PartialEq)]
169pub struct PredictOptions {
170    /// Carrier frequency used to scale Doppler, hertz.
171    pub carrier_hz: f64,
172    /// Apply fixed-point light-time / transmit-time correction.
173    pub light_time: bool,
174    /// Apply Earth-rotation Sagnac correction.
175    pub sagnac: bool,
176}
177
178/// Options controlling transmit-time satellite-state evaluation.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub struct TransmitTimeOptions {
181    /// Apply fixed-point light-time / transmit-time correction.
182    pub light_time: bool,
183    /// Apply Earth-rotation Sagnac correction to the returned position/velocity.
184    pub sagnac: bool,
185}
186
187impl Default for TransmitTimeOptions {
188    fn default() -> Self {
189        Self {
190            light_time: true,
191            sagnac: true,
192        }
193    }
194}
195
196impl Default for PredictOptions {
197    fn default() -> Self {
198        Self {
199            carrier_hz: F_L1_HZ,
200            light_time: true,
201            sagnac: true,
202        }
203    }
204}
205
206/// Satellite state at its signal transmit time for one receive epoch.
207///
208/// `transmit_position_ecef_m` is the ephemeris position evaluated at
209/// `transmit_time_j2000_s`. `position_ecef_m` is that position transported into
210/// the receive-time ECEF frame when [`TransmitTimeOptions::sagnac`] is enabled.
211/// `velocity_m_s` is the finite-difference ECEF velocity at transmit time with
212/// the same transport applied.
213#[derive(Debug, Clone, Copy, PartialEq)]
214pub struct TransmitTimeSatelliteState {
215    /// Signal flight time, seconds.
216    pub signal_flight_time_s: f64,
217    /// Transmit-time offset from receive time, rounded to microseconds.
218    pub transmit_offset_us: i64,
219    /// Transmit time as seconds since J2000.
220    pub transmit_time_j2000_s: f64,
221    /// Satellite clock offset at transmit time, seconds.
222    pub clock_s: Option<f64>,
223    /// Ephemeris ECEF satellite position at transmit time, metres.
224    pub transmit_position_ecef_m: [f64; 3],
225    /// Sagnac-transported ECEF satellite position, metres.
226    pub position_ecef_m: [f64; 3],
227    /// Sagnac-transported ECEF satellite velocity, metres per second.
228    pub velocity_m_s: [f64; 3],
229    /// Geometric range after optional Sagnac transport, metres.
230    pub geometric_range_m: f64,
231    /// Receiver-to-satellite line-of-sight unit vector in ECEF.
232    pub los_unit: [f64; 3],
233}
234
235/// Predicted GNSS observables at one receive epoch.
236#[derive(Debug, Clone, Copy, PartialEq)]
237pub struct PredictedObservables {
238    /// Geometric range after optional Sagnac rotation, meters.
239    pub geometric_range_m: f64,
240    /// Range-rate LOS projection, meters per second.
241    pub range_rate_m_s: f64,
242    /// Doppler shift at `PredictOptions::carrier_hz`, hertz.
243    pub doppler_hz: f64,
244    /// Satellite clock offset at transmit time, seconds.
245    pub sat_clock_s: Option<f64>,
246    /// Topocentric elevation, degrees.
247    pub elevation_deg: f64,
248    /// Topocentric azimuth in `[0, 360)`, degrees.
249    ///
250    /// At (and arbitrarily near) the receiver's zenith the azimuth is
251    /// geometrically undefined; it is defined here to be exactly `0.0` once the
252    /// horizontal line-of-sight projection falls below
253    /// [`crate::constants::AZIMUTH_ZENITH_EPS`], rather than returning rounding
254    /// noise or erroring.
255    pub azimuth_deg: f64,
256    /// Transmit-time offset from receive time, rounded to microseconds.
257    pub transmit_offset_us: i64,
258    /// Transmit time as seconds since J2000.
259    pub transmit_time_j2000_s: f64,
260    /// Receiver-to-satellite line-of-sight unit vector in ECEF.
261    pub los_unit: [f64; 3],
262    /// Sagnac-rotated satellite ECEF position in meters.
263    pub sat_pos_ecef_m: [f64; 3],
264    /// Sagnac-rotated satellite ECEF velocity in meters per second.
265    pub sat_velocity_m_s: [f64; 3],
266}
267
268/// Convert split Julian date to seconds since J2000.
269pub fn j2000_seconds_from_split(jd_whole: f64, jd_fraction: f64) -> Result<f64, ObservablesError> {
270    validate::finite(jd_whole, "jd_whole").map_err(map_input_error)?;
271    validate::finite(jd_fraction, "jd_fraction").map_err(map_input_error)?;
272    validate::finite(
273        civil::j2000_seconds_from_split(jd_whole, jd_fraction),
274        "j2000_seconds",
275    )
276    .map_err(map_input_error)
277}
278
279/// Evaluate a satellite's transmit-time ECEF state for one static receiver.
280///
281/// This is the per-satellite primitive underneath observable prediction: it
282/// iterates light time, evaluates the ephemeris at the satellite's transmit
283/// epoch, applies the Sagnac/Earth-rotation transport if requested, and returns
284/// the transported position, velocity, clock, range, and line of sight without
285/// constructing Doppler or topocentric observables.
286pub fn transmit_time_satellite_state(
287    source: &dyn ObservableEphemerisSource,
288    sat: GnssSatelliteId,
289    receiver_ecef_m: [f64; 3],
290    t_rx_j2000_s: f64,
291    options: TransmitTimeOptions,
292) -> Result<TransmitTimeSatelliteState, ObservablesError> {
293    validate_transmit_time_inputs(receiver_ecef_m, t_rx_j2000_s)?;
294    let predict_options = PredictOptions {
295        carrier_hz: F_L1_HZ,
296        light_time: options.light_time,
297        sagnac: options.sagnac,
298    };
299    let solved = solve_transmit_time(source, sat, receiver_ecef_m, t_rx_j2000_s, predict_options)?;
300
301    let dx = solved.sat_rot_ecef_m[0] - receiver_ecef_m[0];
302    let dy = solved.sat_rot_ecef_m[1] - receiver_ecef_m[1];
303    let dz = solved.sat_rot_ecef_m[2] - receiver_ecef_m[2];
304    let range = geometric_range_m([dx, dy, dz])?;
305    let los = [dx / range, dy / range, dz / range];
306
307    let velocity = satellite_velocity(source, sat, solved.transmit_time_j2000_s)?;
308    let velocity_rot = sagnac_rotate(velocity, solved.tau_s, options.sagnac);
309    validate::finite_vec3(velocity_rot, "satellite velocity_m_s").map_err(map_input_error)?;
310
311    Ok(TransmitTimeSatelliteState {
312        signal_flight_time_s: solved.tau_s,
313        transmit_offset_us: solved.transmit_offset_us,
314        transmit_time_j2000_s: solved.transmit_time_j2000_s,
315        clock_s: solved.state.clock_s,
316        transmit_position_ecef_m: solved.state.position_ecef_m,
317        position_ecef_m: solved.sat_rot_ecef_m,
318        velocity_m_s: velocity_rot,
319        geometric_range_m: range,
320        los_unit: los,
321    })
322}
323
324/// Predict observables for `sat` from a static ECEF receiver.
325pub fn predict(
326    source: &dyn ObservableEphemerisSource,
327    sat: GnssSatelliteId,
328    receiver_ecef_m: [f64; 3],
329    t_rx_j2000_s: f64,
330    options: PredictOptions,
331) -> Result<PredictedObservables, ObservablesError> {
332    validate_predict_inputs(receiver_ecef_m, t_rx_j2000_s, options)?;
333    let solved = solve_transmit_time(source, sat, receiver_ecef_m, t_rx_j2000_s, options)?;
334
335    let dx = solved.sat_rot_ecef_m[0] - receiver_ecef_m[0];
336    let dy = solved.sat_rot_ecef_m[1] - receiver_ecef_m[1];
337    let dz = solved.sat_rot_ecef_m[2] - receiver_ecef_m[2];
338    let range = geometric_range_m([dx, dy, dz])?;
339    let los = [dx / range, dy / range, dz / range];
340
341    let velocity = satellite_velocity(source, sat, solved.transmit_time_j2000_s)?;
342    let velocity_rot = sagnac_rotate(velocity, solved.tau_s, options.sagnac);
343    validate::finite_vec3(velocity_rot, "satellite velocity_m_s").map_err(map_input_error)?;
344    let range_rate = los[0] * velocity_rot[0] + los[1] * velocity_rot[1] + los[2] * velocity_rot[2];
345    validate::finite(range_rate, "range_rate_m_s").map_err(map_input_error)?;
346    let doppler_hz = -range_rate * options.carrier_hz / C_M_S;
347    validate::finite(doppler_hz, "doppler_hz").map_err(map_input_error)?;
348    let (elevation_deg, azimuth_deg) = topocentric(receiver_ecef_m, [dx, dy, dz], range)?;
349
350    Ok(PredictedObservables {
351        geometric_range_m: range,
352        range_rate_m_s: range_rate,
353        doppler_hz,
354        sat_clock_s: solved.state.clock_s,
355        elevation_deg,
356        azimuth_deg,
357        transmit_offset_us: solved.transmit_offset_us,
358        transmit_time_j2000_s: solved.transmit_time_j2000_s,
359        los_unit: los,
360        sat_pos_ecef_m: solved.sat_rot_ecef_m,
361        sat_velocity_m_s: velocity_rot,
362    })
363}
364
365/// One batch prediction request: the satellite to observe, the static receiver
366/// ECEF position in meters, and the receive epoch in seconds since J2000.
367///
368/// Each entry is fully independent of the others; the receiver position and
369/// epoch are per-request, so a single batch can mix many satellites, many
370/// receivers, and many epochs in any combination.
371pub type PredictRequest = (GnssSatelliteId, [f64; 3], f64);
372
373/// Predict observables for many `(satellite, receiver, epoch)` requests, serially.
374///
375/// Element `i` of the result is exactly what [`predict`] returns for
376/// `requests[i]` (including its `Err`), evaluated with the shared `options`.
377/// This is the single-threaded reference that [`predict_batch_parallel`] is
378/// proven bit-identical against; it lets a caller predict a whole fleet/arc in
379/// one call instead of paying per-call dispatch overhead in a host-language loop.
380pub fn predict_batch(
381    source: &dyn ObservableEphemerisSource,
382    requests: &[PredictRequest],
383    options: PredictOptions,
384) -> Vec<Result<PredictedObservables, ObservablesError>> {
385    requests
386        .iter()
387        .map(|&(sat, receiver_ecef_m, t_rx_j2000_s)| {
388            predict(source, sat, receiver_ecef_m, t_rx_j2000_s, options)
389        })
390        .collect()
391}
392
393/// Predict observables for many `(satellite, receiver, epoch)` requests, fanning
394/// the independent requests across a rayon thread pool.
395///
396/// Each request is evaluated by the same scalar [`predict`] kernel and the
397/// indexed parallel collect preserves input order, so element `i` is
398/// byte-for-byte identical to element `i` of [`predict_batch`]: the requests
399/// share no mutable state and a single `predict` is internally sequential, so
400/// throughput scales with cores while every value stays bit-exact. The
401/// `source` must be `Sync` because it is read concurrently from every worker.
402pub fn predict_batch_parallel(
403    source: &(dyn ObservableEphemerisSource + Sync),
404    requests: &[PredictRequest],
405    options: PredictOptions,
406) -> Vec<Result<PredictedObservables, ObservablesError>> {
407    requests
408        .par_iter()
409        .map(|&(sat, receiver_ecef_m, t_rx_j2000_s)| {
410            predict(source, sat, receiver_ecef_m, t_rx_j2000_s, options)
411        })
412        .collect()
413}
414
415#[derive(Debug, Clone, Copy)]
416struct SolvedTransmitTime {
417    tau_s: f64,
418    transmit_offset_us: i64,
419    transmit_time_j2000_s: f64,
420    state: ObservableState,
421    sat_rot_ecef_m: [f64; 3],
422}
423
424fn solve_transmit_time(
425    source: &dyn ObservableEphemerisSource,
426    sat: GnssSatelliteId,
427    receiver_ecef_m: [f64; 3],
428    t_rx_j2000_s: f64,
429    options: PredictOptions,
430) -> Result<SolvedTransmitTime, ObservablesError> {
431    if !options.light_time {
432        let state = validated_state_at_j2000_s(source, sat, t_rx_j2000_s)?;
433        let sat_rot = sagnac_rotate(state.position_ecef_m, 0.0, options.sagnac);
434        validate::finite_vec3(sat_rot, "satellite position_ecef_m").map_err(map_input_error)?;
435        return Ok(SolvedTransmitTime {
436            tau_s: 0.0,
437            transmit_offset_us: 0,
438            transmit_time_j2000_s: t_rx_j2000_s,
439            state,
440            sat_rot_ecef_m: sat_rot,
441        });
442    }
443
444    let mut tau = 0.0;
445    for iter in 0..OBSERVABLE_TRANSMIT_TIME_ITERATIONS {
446        let transmit_offset_us = microseconds_from_tau(tau);
447        let t_tx = t_rx_j2000_s - transmit_offset_us as f64 / MICROSECONDS_PER_SECOND;
448        let state = validated_state_at_j2000_s(source, sat, t_tx)?;
449        let sat_rot = sagnac_rotate(state.position_ecef_m, tau, options.sagnac);
450        validate::finite_vec3(sat_rot, "satellite position_ecef_m").map_err(map_input_error)?;
451        let dx = sat_rot[0] - receiver_ecef_m[0];
452        let dy = sat_rot[1] - receiver_ecef_m[1];
453        let dz = sat_rot[2] - receiver_ecef_m[2];
454        let range = geometric_range_m([dx, dy, dz])?;
455        let new_tau = range / C_M_S;
456
457        if iter + 1 == OBSERVABLE_TRANSMIT_TIME_ITERATIONS {
458            return finalize_transmit_time(source, sat, t_rx_j2000_s, new_tau, options.sagnac);
459        }
460
461        tau = new_tau;
462    }
463
464    unreachable!("fixed transmit-time loop always returns on its last iteration")
465}
466
467fn finalize_transmit_time(
468    source: &dyn ObservableEphemerisSource,
469    sat: GnssSatelliteId,
470    t_rx_j2000_s: f64,
471    tau: f64,
472    sagnac: bool,
473) -> Result<SolvedTransmitTime, ObservablesError> {
474    let transmit_offset_us = microseconds_from_tau(tau);
475    let t_tx = t_rx_j2000_s - transmit_offset_us as f64 / MICROSECONDS_PER_SECOND;
476    validate::finite(t_tx, "transmit_time_j2000_s").map_err(map_input_error)?;
477    let state = validated_state_at_j2000_s(source, sat, t_tx)?;
478    let sat_rot = sagnac_rotate(state.position_ecef_m, tau, sagnac);
479    validate::finite_vec3(sat_rot, "satellite position_ecef_m").map_err(map_input_error)?;
480    Ok(SolvedTransmitTime {
481        tau_s: tau,
482        transmit_offset_us,
483        transmit_time_j2000_s: t_tx,
484        state,
485        sat_rot_ecef_m: sat_rot,
486    })
487}
488
489fn microseconds_from_tau(tau_s: f64) -> i64 {
490    (tau_s * MICROSECONDS_PER_SECOND).round() as i64
491}
492
493fn satellite_velocity(
494    source: &dyn ObservableEphemerisSource,
495    sat: GnssSatelliteId,
496    t_tx_j2000_s: f64,
497) -> Result<[f64; 3], ObservablesError> {
498    let plus = validated_state_at_j2000_s(source, sat, t_tx_j2000_s + FD_HALF_S)?;
499    let minus = validated_state_at_j2000_s(source, sat, t_tx_j2000_s - FD_HALF_S)?;
500    let denom = 2.0 * FD_HALF_S;
501    let velocity = [
502        (plus.position_ecef_m[0] - minus.position_ecef_m[0]) / denom,
503        (plus.position_ecef_m[1] - minus.position_ecef_m[1]) / denom,
504        (plus.position_ecef_m[2] - minus.position_ecef_m[2]) / denom,
505    ];
506    validate::finite_vec3(velocity, "satellite velocity_m_s").map_err(map_input_error)
507}
508
509fn validate_predict_inputs(
510    receiver_ecef_m: [f64; 3],
511    t_rx_j2000_s: f64,
512    options: PredictOptions,
513) -> Result<(), ObservablesError> {
514    validate::finite_vec3(receiver_ecef_m, "receiver_ecef_m").map_err(map_input_error)?;
515    validate::finite(t_rx_j2000_s, "t_rx_j2000_s").map_err(map_input_error)?;
516    validate::finite_positive(options.carrier_hz, "options.carrier_hz").map_err(map_input_error)?;
517    Ok(())
518}
519
520fn validate_transmit_time_inputs(
521    receiver_ecef_m: [f64; 3],
522    t_rx_j2000_s: f64,
523) -> Result<(), ObservablesError> {
524    validate::finite_vec3(receiver_ecef_m, "receiver_ecef_m").map_err(map_input_error)?;
525    validate::finite(t_rx_j2000_s, "t_rx_j2000_s").map_err(map_input_error)?;
526    Ok(())
527}
528
529fn validated_state_at_j2000_s(
530    source: &dyn ObservableEphemerisSource,
531    sat: GnssSatelliteId,
532    t_j2000_s: f64,
533) -> Result<ObservableState, ObservablesError> {
534    let state = source.observable_state_at_j2000_s(sat, t_j2000_s)?;
535    validate_observable_state(&state)?;
536    Ok(state)
537}
538
539fn validate_observable_state(state: &ObservableState) -> Result<(), ObservablesError> {
540    validate::finite_vec3(state.position_ecef_m, "observable state position_ecef_m")
541        .map_err(map_input_error)?;
542    if let Some(clock_s) = state.clock_s {
543        validate::finite(clock_s, "observable state clock_s").map_err(map_input_error)?;
544    }
545    Ok(())
546}
547
548fn geometric_range_m(delta_ecef_m: [f64; 3]) -> Result<f64, ObservablesError> {
549    let range = (delta_ecef_m[0] * delta_ecef_m[0]
550        + delta_ecef_m[1] * delta_ecef_m[1]
551        + delta_ecef_m[2] * delta_ecef_m[2])
552        .sqrt();
553    validate::finite_positive(range, "geometric_range_m").map_err(map_input_error)
554}
555
556fn map_input_error(error: validate::FieldError) -> ObservablesError {
557    ObservablesError::InvalidInput {
558        field: error.field(),
559        kind: ObservablesInputErrorKind::from(&error),
560    }
561}
562
563fn sagnac_rotate(pos: [f64; 3], tau_s: f64, apply: bool) -> [f64; 3] {
564    let sagnac = if apply {
565        SagnacRecipe::ClosedFormZRotation
566    } else {
567        SagnacRecipe::Off
568    };
569    crate::estimation::substrate::range::rotate_transmit_satellite(
570        sagnac,
571        pos,
572        tau_s,
573        OMEGA_E_DOT_RAD_S,
574    )
575}
576
577fn topocentric(
578    receiver_ecef_m: [f64; 3],
579    delta_ecef_m: [f64; 3],
580    range_m: f64,
581) -> Result<(f64, f64), ObservablesError> {
582    let (lat_deg, lon_deg, _height_km) = itrs_to_geodetic_compute(
583        receiver_ecef_m[0] / KM_TO_M,
584        receiver_ecef_m[1] / KM_TO_M,
585        receiver_ecef_m[2] / KM_TO_M,
586    )
587    .map_err(|_| ObservablesError::InvalidInput {
588        field: "receiver_ecef_m",
589        kind: ObservablesInputErrorKind::OutOfRange,
590    })?;
591    // Sidereon' application oracle pins this multiply-then-divide order.
592    let lat = lat_deg * PI / DEGREES_PER_SEMICIRCLE;
593    let lon = lon_deg * PI / DEGREES_PER_SEMICIRCLE;
594
595    let sl = lat.sin();
596    let cl = lat.cos();
597    let so = lon.sin();
598    let co = lon.cos();
599
600    let dx = delta_ecef_m[0];
601    let dy = delta_ecef_m[1];
602    let dz = delta_ecef_m[2];
603
604    let e = -so * dx + co * dy;
605    let n = -sl * co * dx - sl * so * dy + cl * dz;
606    let u = cl * co * dx + cl * so * dy + sl * dz;
607
608    // Near the zenith the horizontal projection (e, n) is pure rounding noise,
609    // so azimuth is degenerate and defined to be 0.0 (RTKLIB satazel semantics).
610    // Outside that threshold the multiply-then-divide order is pinned by the
611    // application oracle.
612    let horiz_sq = e * e + n * n;
613    let mut azimuth_deg = if horiz_sq < AZIMUTH_ZENITH_EPS * range_m * range_m {
614        0.0
615    } else {
616        e.atan2(n) * DEGREES_PER_SEMICIRCLE / PI
617    };
618    if azimuth_deg < 0.0 {
619        azimuth_deg += DEGREES_PER_CIRCLE;
620    }
621    // range_m is an ECEF norm, so at an exact zenith u/range_m can round just
622    // past 1.0 and make asin return NaN. Clamp to the valid asin domain; this
623    // only touches the previously-NaN boundary and leaves in-range values bit
624    // identical.
625    let sin_elevation = (u / range_m).clamp(-1.0, 1.0);
626    let elevation_deg = sin_elevation.asin() * DEGREES_PER_SEMICIRCLE / PI;
627
628    validate::finite(elevation_deg, "elevation_deg").map_err(map_input_error)?;
629    validate::finite(azimuth_deg, "azimuth_deg").map_err(map_input_error)?;
630    Ok((elevation_deg, azimuth_deg))
631}
632
633#[cfg(test)]
634mod public_api_tests {
635    use super::*;
636    use crate::{GnssSatelliteId, GnssSystem};
637
638    #[derive(Debug, Clone, Copy)]
639    struct StaticSource {
640        state: ObservableState,
641    }
642
643    impl ObservableEphemerisSource for StaticSource {
644        fn observable_state_at_j2000_s(
645            &self,
646            _sat: GnssSatelliteId,
647            _t_j2000_s: f64,
648        ) -> Result<ObservableState, ObservablesError> {
649            Ok(self.state)
650        }
651    }
652
653    #[test]
654    fn topocentric_elevation_is_ninety_at_non_equatorial_zenith() {
655        // A ~45 deg receiver (non-equatorial) with the satellite placed exactly
656        // along the receiver's recovered geodetic up, so the east/north
657        // projection is zero and the asin argument u/range lands on the domain
658        // boundary. For this receiver the rounding pushes u/range to just past
659        // 1.0 (1.0000000000000002): without the clamp asin returns NaN and the
660        // finite check turns it into an InvalidInput error. The clamp must yield
661        // a finite ~90 deg elevation instead. This exact receiver was found by
662        // scanning ECEF positions for the >1.0 rounding case.
663        let rx = [
664            4_509_179.095_483_66,
665            275_556.225_682_215_9,
666            4_487_348.408_865_919,
667        ];
668        let (lat_deg, lon_deg, _h) =
669            itrs_to_geodetic_compute(rx[0] / KM_TO_M, rx[1] / KM_TO_M, rx[2] / KM_TO_M)
670                .expect("receiver geodetic conversion");
671        assert!(lat_deg.abs() > 40.0, "receiver must be non-equatorial");
672
673        // Reconstruct the up unit vector exactly as `topocentric` does, then put
674        // the satellite straight overhead along it.
675        let lat = lat_deg * PI / DEGREES_PER_SEMICIRCLE;
676        let lon = lon_deg * PI / DEGREES_PER_SEMICIRCLE;
677        let (sl, cl) = lat.sin_cos();
678        let (so, co) = lon.sin_cos();
679        let up = [cl * co, cl * so, sl];
680
681        let d = 20_000_000.0_f64;
682        let delta = [up[0] * d, up[1] * d, up[2] * d];
683        let range = (delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2]).sqrt();
684        // Guard the regression premise: this geometry really does overshoot the
685        // asin domain (the bug this test pins).
686        let u = cl * co * delta[0] + cl * so * delta[1] + sl * delta[2];
687        assert!(
688            u / range > 1.0,
689            "test geometry must overshoot the asin domain"
690        );
691
692        let (elevation_deg, _azimuth_deg) =
693            topocentric(rx, delta, range).expect("non-equatorial zenith must not error");
694        assert!(elevation_deg.is_finite());
695        assert!((elevation_deg - 90.0).abs() < 1e-9);
696    }
697
698    #[test]
699    fn transmit_time_state_matches_predict_substrate_with_no_light_time() {
700        let source = StaticSource {
701            state: ObservableState {
702                position_ecef_m: [20_200_000.0, 14_000_000.0, 21_700_000.0],
703                clock_s: Some(1.25e-6),
704            },
705        };
706        let sat = GnssSatelliteId::new(GnssSystem::Gps, 21).expect("valid satellite id");
707        let rx = [4_027_894.0, 307_046.0, 4_919_474.0];
708        let state = transmit_time_satellite_state(
709            &source,
710            sat,
711            rx,
712            646_272_000.0,
713            TransmitTimeOptions {
714                light_time: false,
715                sagnac: true,
716            },
717        )
718        .expect("state");
719        let prediction = predict(
720            &source,
721            sat,
722            rx,
723            646_272_000.0,
724            PredictOptions {
725                carrier_hz: F_L1_HZ,
726                light_time: false,
727                sagnac: true,
728            },
729        )
730        .expect("prediction");
731
732        assert_eq!(state.signal_flight_time_s.to_bits(), 0.0f64.to_bits());
733        assert_eq!(state.transmit_offset_us, 0);
734        assert_eq!(
735            state.transmit_time_j2000_s.to_bits(),
736            646_272_000.0f64.to_bits()
737        );
738        assert_eq!(state.clock_s.unwrap().to_bits(), 1.25e-6f64.to_bits());
739        assert_eq!(
740            state.transmit_position_ecef_m.map(f64::to_bits),
741            source.state.position_ecef_m.map(f64::to_bits)
742        );
743        assert_eq!(
744            state.position_ecef_m.map(f64::to_bits),
745            prediction.sat_pos_ecef_m.map(f64::to_bits)
746        );
747        assert_eq!(
748            state.velocity_m_s.map(f64::to_bits),
749            prediction.sat_velocity_m_s.map(f64::to_bits)
750        );
751        assert_eq!(
752            state.geometric_range_m.to_bits(),
753            prediction.geometric_range_m.to_bits()
754        );
755        assert_eq!(
756            state.los_unit.map(f64::to_bits),
757            prediction.los_unit.map(f64::to_bits)
758        );
759    }
760}
761
762#[cfg(all(test, sidereon_repo_tests))]
763mod tests {
764    use super::*;
765    use crate::{GnssSatelliteId, GnssSystem};
766
767    #[derive(Debug, Clone, Copy)]
768    struct StaticSource {
769        state: ObservableState,
770    }
771
772    impl ObservableEphemerisSource for StaticSource {
773        fn observable_state_at_j2000_s(
774            &self,
775            _sat: GnssSatelliteId,
776            _t_j2000_s: f64,
777        ) -> Result<ObservableState, ObservablesError> {
778            Ok(self.state)
779        }
780    }
781
782    fn sp3_fixture() -> Sp3 {
783        let path = concat!(
784            env!("CARGO_MANIFEST_DIR"),
785            "/tests/fixtures/sp3/GRG0MGXFIN_20201760000_01D_15M_ORB.SP3"
786        );
787        let bytes = std::fs::read(path).unwrap_or_else(|e| panic!("read SP3 fixture {path}: {e}"));
788        Sp3::parse(&bytes).expect("parse SP3 fixture")
789    }
790
791    fn static_source(position_ecef_m: [f64; 3]) -> StaticSource {
792        StaticSource {
793            state: ObservableState {
794                position_ecef_m,
795                clock_s: Some(0.0),
796            },
797        }
798    }
799
800    fn no_light_time_options() -> PredictOptions {
801        PredictOptions {
802            carrier_hz: F_L1_HZ,
803            light_time: false,
804            sagnac: true,
805        }
806    }
807
808    fn assert_invalid_observables_input(
809        err: ObservablesError,
810        field: &'static str,
811        kind: ObservablesInputErrorKind,
812    ) {
813        match err {
814            ObservablesError::InvalidInput {
815                field: got_field,
816                kind: got_kind,
817            } => {
818                assert_eq!(got_field, field);
819                assert_eq!(got_kind, kind);
820            }
821            other => panic!("expected InvalidInput({field}, {kind:?}), got {other:?}"),
822        }
823    }
824
825    #[test]
826    fn split_julian_to_j2000_seconds_matches_orbis_time() {
827        let t = j2000_seconds_from_split(2_459_024.5, 0.5).expect("valid split Julian date");
828        assert_eq!(t, 646_272_000.0);
829    }
830
831    #[test]
832    fn split_julian_to_j2000_seconds_rejects_non_finite_parts() {
833        for (jd_whole, jd_fraction, field) in [
834            (f64::NAN, 0.5, "jd_whole"),
835            (f64::INFINITY, 0.5, "jd_whole"),
836            (2_459_024.5, f64::NAN, "jd_fraction"),
837            (2_459_024.5, f64::NEG_INFINITY, "jd_fraction"),
838        ] {
839            let err = j2000_seconds_from_split(jd_whole, jd_fraction)
840                .expect_err("non-finite split Julian date part must fail");
841            assert_invalid_observables_input(err, field, ObservablesInputErrorKind::NonFinite);
842        }
843    }
844
845    #[test]
846    fn sp3_predict_reference_case() {
847        let sp3 = sp3_fixture();
848        let sat = GnssSatelliteId::new(GnssSystem::Gps, 21).expect("valid satellite id");
849        let rx = [3_512_900.0, 780_500.0, 5_248_700.0];
850        let obs = predict(&sp3, sat, rx, 646_272_000.0, PredictOptions::default())
851            .expect("predict observables");
852
853        assert_eq!(obs.geometric_range_m.to_bits(), 0x4173cf438ba57358);
854        assert_eq!(obs.range_rate_m_s.to_bits(), 0x402d7dd36f6b8980);
855        assert_eq!(obs.doppler_hz.to_bits(), 0xc0535f534ba7c77d);
856        assert_eq!(obs.sat_clock_s.unwrap().to_bits(), 0x3ef04d2d8279460c);
857        assert_eq!(obs.elevation_deg.to_bits(), 0x4054590eed870f52);
858        assert_eq!(obs.azimuth_deg.to_bits(), 0x40645ff5a090a131);
859        assert_eq!(obs.transmit_offset_us, 69_288);
860        assert_eq!(obs.transmit_time_j2000_s.to_bits(), 0x41c342a9fff72192);
861        assert_eq!(
862            obs.los_unit.map(f64::to_bits),
863            [0x3fe4c70da9fa70dd, 0x3fc834429adb2bae, 0x3fe792a4f57fdcb1,]
864        );
865        assert_eq!(
866            obs.sat_pos_ecef_m.map(f64::to_bits),
867            [0x41703667d8c0eb8f, 0x4151f601b1d775f3, 0x4173992c0ec03dcd,]
868        );
869        assert_eq!(
870            obs.sat_velocity_m_s.map(f64::to_bits),
871            [0xc09c17d81e540ab6, 0x409a192982abbeb7, 0x40926013f2ae8000,]
872        );
873    }
874
875    #[test]
876    fn predict_rejects_invalid_entry_inputs() {
877        let source = static_source([20_200_000.0, 14_000_000.0, 21_700_000.0]);
878        let sat = GnssSatelliteId::new(GnssSystem::Gps, 21).expect("valid satellite id");
879
880        let err = predict(
881            &source,
882            sat,
883            [f64::NAN, 0.0, 0.0],
884            646_272_000.0,
885            no_light_time_options(),
886        )
887        .expect_err("non-finite receiver position must fail");
888        assert_invalid_observables_input(
889            err,
890            "receiver_ecef_m",
891            ObservablesInputErrorKind::NonFinite,
892        );
893
894        let err = predict(
895            &source,
896            sat,
897            [0.0, 0.0, 0.0],
898            f64::INFINITY,
899            no_light_time_options(),
900        )
901        .expect_err("non-finite receive time must fail");
902        assert_invalid_observables_input(err, "t_rx_j2000_s", ObservablesInputErrorKind::NonFinite);
903
904        let mut options = no_light_time_options();
905        options.carrier_hz = 0.0;
906        let err = predict(&source, sat, [0.0, 0.0, 0.0], 646_272_000.0, options)
907            .expect_err("non-positive carrier must fail");
908        assert_invalid_observables_input(
909            err,
910            "options.carrier_hz",
911            ObservablesInputErrorKind::NotPositive,
912        );
913    }
914
915    #[test]
916    fn predict_rejects_invalid_source_state_and_zero_range() {
917        let sat = GnssSatelliteId::new(GnssSystem::Gps, 21).expect("valid satellite id");
918
919        let source = static_source([f64::NAN, 14_000_000.0, 21_700_000.0]);
920        let err = predict(
921            &source,
922            sat,
923            [0.0, 0.0, 0.0],
924            646_272_000.0,
925            no_light_time_options(),
926        )
927        .expect_err("non-finite ephemeris position must fail");
928        assert_invalid_observables_input(
929            err,
930            "observable state position_ecef_m",
931            ObservablesInputErrorKind::NonFinite,
932        );
933
934        let source = static_source([1_000.0, 2_000.0, 3_000.0]);
935        let err = predict(
936            &source,
937            sat,
938            [1_000.0, 2_000.0, 3_000.0],
939            646_272_000.0,
940            no_light_time_options(),
941        )
942        .expect_err("zero geometric range must fail");
943        assert_invalid_observables_input(
944            err,
945            "geometric_range_m",
946            ObservablesInputErrorKind::NotPositive,
947        );
948    }
949
950    #[test]
951    fn topocentric_rejects_invalid_receiver_geodetic_conversion() {
952        let err = topocentric([f64::MAX, 0.0, 0.0], [1.0, 0.0, 0.0], 1.0)
953            .expect_err("invalid receiver geodetic conversion must fail");
954
955        assert_invalid_observables_input(
956            err,
957            "receiver_ecef_m",
958            ObservablesInputErrorKind::OutOfRange,
959        );
960    }
961
962    // WGS84 equatorial radius; a receiver here sits at lat=0, lon=0, height~=0,
963    // so the geodetic up direction is +X and a satellite displaced along +X is
964    // exactly overhead (degenerate azimuth geometry).
965    const EQUATORIAL_RX_X_M: f64 = 6_378_137.0;
966
967    #[test]
968    fn topocentric_azimuth_is_zero_at_exact_zenith() {
969        // Satellite displaced purely radially (+X) above an equatorial receiver:
970        // east == north == 0, so azimuth is degenerate.
971        let (elevation_deg, azimuth_deg) = topocentric(
972            [EQUATORIAL_RX_X_M, 0.0, 0.0],
973            [20_000_000.0, 0.0, 0.0],
974            20_000_000.0,
975        )
976        .expect("zenith topocentric must not error");
977        assert_eq!(azimuth_deg, 0.0);
978        assert!(azimuth_deg.is_finite());
979        assert!((elevation_deg - 90.0).abs() < 1e-9);
980    }
981
982    #[test]
983    fn topocentric_azimuth_is_zero_just_off_zenith() {
984        // A ~1e-9 m horizontal nudge is pure rounding-scale noise at a 20,000 km
985        // range, so azimuth stays pinned to 0.0 (RTKLIB satazel semantics).
986        let (_, azimuth_deg) = topocentric(
987            [EQUATORIAL_RX_X_M, 0.0, 0.0],
988            [20_000_000.0, 1.0e-9, 1.0e-9],
989            20_000_000.0,
990        )
991        .expect("near-zenith topocentric must not error");
992        assert_eq!(azimuth_deg, 0.0);
993        assert!(azimuth_deg.is_finite());
994    }
995
996    #[test]
997    fn predict_azimuth_is_zero_at_exact_zenith() {
998        let source = StaticSource {
999            state: ObservableState {
1000                position_ecef_m: [EQUATORIAL_RX_X_M + 20_000_000.0, 0.0, 0.0],
1001                clock_s: None,
1002            },
1003        };
1004        let sat = GnssSatelliteId::new(GnssSystem::Gps, 1).expect("valid satellite id");
1005        let obs = predict(
1006            &source,
1007            sat,
1008            [EQUATORIAL_RX_X_M, 0.0, 0.0],
1009            0.0,
1010            PredictOptions {
1011                carrier_hz: F_L1_HZ,
1012                light_time: false,
1013                sagnac: false,
1014            },
1015        )
1016        .expect("zenith predict must not error");
1017        assert_eq!(obs.azimuth_deg, 0.0);
1018        assert!(obs.azimuth_deg.is_finite());
1019        assert!((obs.elevation_deg - 90.0).abs() < 1e-9);
1020    }
1021
1022    fn batch_test_requests() -> Vec<PredictRequest> {
1023        let sat1 = GnssSatelliteId::new(GnssSystem::Gps, 21).expect("valid satellite id");
1024        let sat2 = GnssSatelliteId::new(GnssSystem::Gps, 7).expect("valid satellite id");
1025        vec![
1026            (sat1, [4_027_894.0, 307_046.0, 4_919_474.0], 646_272_000.0),
1027            (sat2, [4_027_900.0, 307_050.0, 4_919_480.0], 646_272_030.0),
1028            (
1029                sat1,
1030                [1_130_000.0, -4_830_000.0, 3_994_000.0],
1031                646_272_060.0,
1032            ),
1033            (
1034                sat2,
1035                [-2_700_000.0, -4_290_000.0, 3_855_000.0],
1036                646_272_090.0,
1037            ),
1038        ]
1039    }
1040
1041    fn assert_observables_bits_eq(a: &PredictedObservables, b: &PredictedObservables) {
1042        assert_eq!(a.geometric_range_m.to_bits(), b.geometric_range_m.to_bits());
1043        assert_eq!(a.range_rate_m_s.to_bits(), b.range_rate_m_s.to_bits());
1044        assert_eq!(a.doppler_hz.to_bits(), b.doppler_hz.to_bits());
1045        assert_eq!(a.elevation_deg.to_bits(), b.elevation_deg.to_bits());
1046        assert_eq!(a.azimuth_deg.to_bits(), b.azimuth_deg.to_bits());
1047        assert_eq!(a.transmit_offset_us, b.transmit_offset_us);
1048        assert_eq!(
1049            a.transmit_time_j2000_s.to_bits(),
1050            b.transmit_time_j2000_s.to_bits()
1051        );
1052        for k in 0..3 {
1053            assert_eq!(a.los_unit[k].to_bits(), b.los_unit[k].to_bits());
1054            assert_eq!(a.sat_pos_ecef_m[k].to_bits(), b.sat_pos_ecef_m[k].to_bits());
1055            assert_eq!(
1056                a.sat_velocity_m_s[k].to_bits(),
1057                b.sat_velocity_m_s[k].to_bits()
1058            );
1059        }
1060    }
1061
1062    #[test]
1063    fn predict_batch_matches_scalar_loop_bitwise() {
1064        let source = StaticSource {
1065            state: ObservableState {
1066                position_ecef_m: [20_200_000.0, 14_000_000.0, 21_700_000.0],
1067                clock_s: Some(1.25e-6),
1068            },
1069        };
1070        let options = PredictOptions {
1071            carrier_hz: F_L1_HZ,
1072            light_time: true,
1073            sagnac: true,
1074        };
1075        let requests = batch_test_requests();
1076        let batch = predict_batch(&source, &requests, options);
1077        assert_eq!(batch.len(), requests.len());
1078        for (entry, &(sat, rx, t)) in batch.iter().zip(requests.iter()) {
1079            let scalar = predict(&source, sat, rx, t, options);
1080            match (entry, &scalar) {
1081                (Ok(b), Ok(s)) => assert_observables_bits_eq(b, s),
1082                (Err(_), Err(_)) => {}
1083                _ => panic!("batch and scalar predict disagree on Ok/Err"),
1084            }
1085        }
1086    }
1087
1088    #[test]
1089    fn predict_batch_parallel_matches_serial_bitwise() {
1090        let source = StaticSource {
1091            state: ObservableState {
1092                position_ecef_m: [20_200_000.0, 14_000_000.0, 21_700_000.0],
1093                clock_s: Some(1.25e-6),
1094            },
1095        };
1096        let options = PredictOptions {
1097            carrier_hz: F_L1_HZ,
1098            light_time: true,
1099            sagnac: true,
1100        };
1101        let requests = batch_test_requests();
1102        let serial = predict_batch(&source, &requests, options);
1103        let parallel = predict_batch_parallel(&source, &requests, options);
1104        assert_eq!(serial.len(), parallel.len());
1105        for (s, p) in serial.iter().zip(parallel.iter()) {
1106            match (s, p) {
1107                (Ok(a), Ok(b)) => assert_observables_bits_eq(a, b),
1108                (Err(_), Err(_)) => {}
1109                _ => panic!("serial and parallel batch disagree on Ok/Err"),
1110            }
1111        }
1112    }
1113}