sidereon-core 0.8.0

The complete Sidereon engine: numerical astrodynamics propagation core plus the GNSS domain layer (SP3, broadcast ephemeris, multi-GNSS positioning, RTK/PPP, ionosphere/troposphere, DOP) behind a default-on gnss feature
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! 0-ULP parity tests for the Saastamoinen + Niell tropospheric delay recipe.
//!
//! These assert the Rust port reproduces the canonical reference recipe
//! `parity/generator/troposphere.py` bit-for-bit, using the committed golden
//! fixture `parity/fixtures/troposphere_golden.json`. Values are serialised as
//! hex-float (Python `float.hex()`) so there is no decimal-parse ambiguity, and
//! parity is measured as ULP distance via the integer reinterpretation of the
//! IEEE-754 bit pattern, per the `skyfield_parity_test.exs` discipline.
//!
//! Every intermediate quantity (the water-vapour partial pressure, both zenith
//! delays, both mapping factors, the height correction, the seasonal phase) and
//! the final slant delay is checked per component, so a divergence is localised
//! to a single algorithm step rather than only seen at the output. The cases
//! span the full branch matrix: elevations from zenith down past the Niell low
//! range and the at/below-horizon gate; equator / mid / high / polar / southern
//! latitudes exercising the latitude-interpolation nodes, clamps, and the
//! southern seasonal-phase offset; day-of-year at the cosine-phase extremes and
//! a fractional mid-year value; sea level, high altitude, below sea level, the
//! Met-path height-gate edges; and humidity, temperature, and pressure extremes.
//! A separate standard-atmosphere family covers the pressure/temperature
//! synthesis and its height clamp.

use std::path::PathBuf;

use crate::astro::time::model::{Instant, JulianDateSplit, TimeScale};
use serde_json::Value;

use super::saastamoinen::{slant_components, standard_atmosphere};

/// Parse a C99 / Python `float.hex()` hex-float string into the exact `f64`.
///
/// Every hex frac digit is 4 mantissa bits and f64 has 52, so the reconstruction
/// of a 13-digit fraction is exact (no rounding).
fn parse_hex_float(s: &str) -> f64 {
    let s = s.trim();
    let (neg, rest) = match s.strip_prefix('-') {
        Some(r) => (true, r),
        None => (false, s),
    };
    let rest = rest
        .strip_prefix("0x")
        .or_else(|| rest.strip_prefix("0X"))
        .unwrap_or_else(|| panic!("not a hex float (missing 0x): {s:?}"));

    let (mantissa, exp_str) = rest
        .split_once(['p', 'P'])
        .unwrap_or_else(|| panic!("not a hex float (missing p exponent): {s:?}"));
    let exp2: i32 = exp_str
        .parse()
        .unwrap_or_else(|_| panic!("bad binary exponent in {s:?}"));

    let (int_part, frac_part) = match mantissa.split_once('.') {
        Some((i, f)) => (i, f),
        None => (mantissa, ""),
    };

    let int_val: f64 = i64::from_str_radix(int_part, 16)
        .unwrap_or_else(|_| panic!("bad integer hex digits in {s:?}"))
        as f64;

    let mut frac_val = 0.0f64;
    let mut scale = 1.0f64 / 16.0;
    for c in frac_part.chars() {
        let d = c
            .to_digit(16)
            .unwrap_or_else(|| panic!("bad hex frac digit {c:?} in {s:?}"));
        frac_val += (d as f64) * scale;
        scale /= 16.0;
    }

    let significand = int_val + frac_val;
    let val = significand * 2.0f64.powi(exp2);
    if neg {
        -val
    } else {
        val
    }
}

/// ULP distance between two `f64`, using the monotone signed-integer mapping of
/// the IEEE-754 bit pattern. Returns `u64::MAX` for any NaN so a NaN never
/// silently reads as 0 ULP.
fn ulp_distance(a: f64, b: f64) -> u64 {
    if a.is_nan() || b.is_nan() {
        return u64::MAX;
    }
    ordered_i64(a).abs_diff(ordered_i64(b))
}

/// Map an `f64` to a sign-magnitude-ordered `i64` so adjacent floats differ by 1.
fn ordered_i64(x: f64) -> i64 {
    let bits = x.to_bits() as i64;
    if bits < 0 {
        i64::MIN - bits
    } else {
        bits
    }
}

/// Render an `f64` as a Python-`float.hex()`-style string for diagnostics.
fn float_hex(x: f64) -> String {
    if x == 0.0 {
        return if x.is_sign_negative() {
            "-0x0.0p+0".into()
        } else {
            "0x0.0p+0".into()
        };
    }
    let bits = x.to_bits();
    let sign = if (bits >> 63) & 1 == 1 { "-" } else { "" };
    let exp = ((bits >> 52) & 0x7ff) as i64;
    let mantissa = bits & 0x000f_ffff_ffff_ffff;
    let unbiased = exp - 1023;
    if unbiased >= 0 {
        format!("{sign}0x1.{mantissa:013x}p+{unbiased}")
    } else {
        format!("{sign}0x1.{mantissa:013x}p{unbiased}")
    }
}

fn fixture_path() -> PathBuf {
    let crate_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    crate_dir
        .join("tests/fixtures/troposphere_golden.json")
        .canonicalize()
        .unwrap_or_else(|e| {
            panic!(
                "cannot locate tests/fixtures/troposphere_golden.json from {}: {e}",
                crate_dir.display()
            )
        })
}

fn hexf(v: &Value, key: &str) -> f64 {
    parse_hex_float(
        v[key]
            .as_str()
            .unwrap_or_else(|| panic!("missing/non-string {key}")),
    )
}

#[test]
fn troposphere_zero_ulp_full_branch_matrix() {
    let raw = std::fs::read_to_string(fixture_path()).expect("read troposphere_golden.json");
    let doc: Value = serde_json::from_str(&raw).expect("parse troposphere_golden.json");

    // Self-check the hex-float parser/serialiser round-trips a known bit pattern,
    // so a parser bug can never masquerade as parity.
    let probe = "0x1.921fb54442d18p+1"; // math.pi
    assert_eq!(
        float_hex(parse_hex_float(probe)),
        probe,
        "hex-float parser/serialiser round-trip is broken"
    );

    let mut failures: Vec<String> = Vec::new();
    let mut checks = 0usize;

    // --- Slant cases (zenith + mapping + composed delay). ---
    let slant_cases = doc["slant_cases"].as_array().expect("slant_cases array");
    assert!(
        slant_cases.len() >= 22,
        "expected the full slant branch matrix (>= 22 cases), found {}",
        slant_cases.len()
    );

    let slant_components_keys: &[&str] = &[
        "e", "zhd_m", "zwd_m", "mh", "mw", "dm", "cosy", "y", "slant_m",
    ];

    for case in slant_cases {
        let name = case["name"].as_str().unwrap_or("<unnamed>");
        let inp = &case["inputs"];
        let exp = &case["expect"];

        // Radian angles and the fractional day-of-year are taken straight from
        // the fixture, exactly as the reference recipe consumes them.
        let got = slant_components(
            hexf(inp, "el_rad"),
            crate::frame::Wgs84Geodetic::new(
                hexf(inp, "lat_rad"),
                hexf(inp, "lon_rad"),
                hexf(inp, "height_m"),
            )
            .expect("valid WGS84 geodetic position"),
            hexf(inp, "pressure_hpa"),
            hexf(inp, "temperature_k"),
            hexf(inp, "relative_humidity"),
            hexf(inp, "doy"),
        );

        let actual = |c: &str| -> f64 {
            match c {
                "e" => got.e,
                "zhd_m" => got.zhd_m,
                "zwd_m" => got.zwd_m,
                "mh" => got.mh,
                "mw" => got.mw,
                "dm" => got.dm,
                "cosy" => got.cosy,
                "y" => got.y,
                "slant_m" => got.slant_m,
                other => panic!("unknown component {other}"),
            }
        };

        for &c in slant_components_keys {
            let want = parse_hex_float(
                exp[c]
                    .as_str()
                    .unwrap_or_else(|| panic!("case {name}: missing expected component {c}")),
            );
            let a = actual(c);
            let ulp = ulp_distance(a, want);
            checks += 1;
            if ulp != 0 {
                failures.push(format!(
                    "slant {name}.{c}: {ulp} ULP (rust={} ref={})",
                    float_hex(a),
                    exp[c].as_str().unwrap()
                ));
            }
        }
    }

    // --- Standard-atmosphere helper family (P/T synthesis + height clamp). ---
    let std_cases = doc["standard_atmosphere_cases"]
        .as_array()
        .expect("standard_atmosphere_cases array");
    assert!(
        std_cases.len() >= 4,
        "expected the standard-atmosphere family (>= 4 cases), found {}",
        std_cases.len()
    );

    let std_keys: &[&str] = &["pressure_hpa", "temperature_k", "relative_humidity"];

    for case in std_cases {
        let name = case["name"].as_str().unwrap_or("<unnamed>");
        let inp = &case["inputs"];
        let exp = &case["expect"];

        let got = standard_atmosphere(hexf(inp, "height_m"), hexf(inp, "relative_humidity"));

        let actual = |c: &str| -> f64 {
            match c {
                "pressure_hpa" => got.pressure_hpa,
                "temperature_k" => got.temperature_k,
                "relative_humidity" => got.relative_humidity,
                other => panic!("unknown component {other}"),
            }
        };

        for &c in std_keys {
            let want = parse_hex_float(
                exp[c]
                    .as_str()
                    .unwrap_or_else(|| panic!("case {name}: missing expected component {c}")),
            );
            let a = actual(c);
            let ulp = ulp_distance(a, want);
            checks += 1;
            if ulp != 0 {
                failures.push(format!(
                    "std {name}.{c}: {ulp} ULP (rust={} ref={})",
                    float_hex(a),
                    exp[c].as_str().unwrap()
                ));
            }
        }
    }

    assert!(checks > 0, "no components were checked - fixture empty?");
    assert!(
        failures.is_empty(),
        "Troposphere Rust port diverged from the reference recipe on {} of {checks} components:\n  {}",
        failures.len(),
        failures.join("\n  ")
    );
}

/// Coverage for the PUBLIC `tropo_slant(epoch, ...)` wrapper, which the kernel
/// test above does not exercise (it feeds `doy` straight into
/// `slant_components`). The wrapper derives the day-of-year from `epoch`. Unlike
/// the ionosphere path there is no angle conversion (latitude stays in radians),
/// so when the epoch reconstructs the day-of-year exactly the public path is
/// bit-for-bit identical to the kernel/golden. This drives the `zenith_midlat`
/// case (day-of-year 28 -> 2000-01-28 00:00, reconstructed exactly) through the
/// public API and asserts 0 ULP against the golden, closing the coverage gap.
#[test]
fn tropo_public_wrapper_is_0_ulp_when_epoch_reconstructs_doy() {
    use crate::astro::time::model::{Instant, JulianDateSplit, TimeScale};

    let raw = std::fs::read_to_string(fixture_path()).expect("read troposphere_golden.json");
    let doc: Value = serde_json::from_str(&raw).expect("parse troposphere_golden.json");
    let cases = doc["slant_cases"].as_array().expect("slant_cases array");

    let case = cases
        .iter()
        .find(|c| c["name"].as_str() == Some("zenith_midlat"))
        .expect("zenith_midlat case present");
    let inp = &case["inputs"];

    // This reconstruction is only exact for an integer day-of-year at midnight;
    // assert that precondition so a fixture change can't silently invalidate it.
    assert_eq!(
        hexf(inp, "doy"),
        28.0,
        "test assumes zenith_midlat is day-of-year 28"
    );

    // 2000-01-28 00:00:00: JDN(noon) = 2451572, midnight boundary = 2451571.5.
    // fractional_day_of_year() maps this to exactly 28.0.
    let epoch = Instant::from_julian_date(
        TimeScale::Gpst,
        JulianDateSplit::new(2_451_571.5, 0.0).expect("valid split Julian date"),
    );

    let receiver = crate::frame::Wgs84Geodetic::new(
        hexf(inp, "lat_rad"),
        hexf(inp, "lon_rad"),
        hexf(inp, "height_m"),
    )
    .expect("valid WGS84 geodetic position");
    let met = super::Met::new(
        hexf(inp, "pressure_hpa"),
        hexf(inp, "temperature_k"),
        hexf(inp, "relative_humidity"),
    )
    .expect("valid troposphere met");

    let got = super::tropo_slant(hexf(inp, "el_rad"), receiver, met, epoch)
        .expect("valid public troposphere inputs");
    let want = parse_hex_float(case["expect"]["slant_m"].as_str().unwrap());

    assert_eq!(
        got.to_bits(),
        want.to_bits(),
        "public tropo_slant not 0-ULP: got={} want={}",
        float_hex(got),
        case["expect"]["slant_m"].as_str().unwrap()
    );
}

fn valid_tropo_receiver() -> crate::frame::Wgs84Geodetic {
    crate::frame::Wgs84Geodetic::new(45.0_f64.to_radians(), 8.0_f64.to_radians(), 400.0)
        .expect("valid WGS84 geodetic position")
}

fn valid_tropo_epoch() -> Instant {
    Instant::from_julian_date(
        TimeScale::Gpst,
        JulianDateSplit::new(2_451_571.5, 0.0).expect("valid split Julian date"),
    )
}

fn valid_tropo_met() -> super::Met {
    super::Met::new(1013.25, 288.15, 0.5).expect("valid troposphere met")
}

fn assert_invalid_input<T: core::fmt::Debug>(result: crate::Result<T>) {
    let err = result.expect_err("invalid troposphere input must be rejected");
    assert!(
        matches!(err, crate::error::Error::InvalidInput(_)),
        "expected InvalidInput, got {err:?}"
    );
}

#[test]
fn tropo_public_helpers_reject_invalid_domains() {
    let receiver = valid_tropo_receiver();
    let met = valid_tropo_met();
    let epoch = valid_tropo_epoch();
    let elevation = 30.0_f64.to_radians();

    assert_invalid_input(super::Met::new(f64::NAN, 288.15, 0.5));
    assert_invalid_input(super::Met::new(1013.25, 0.0, 0.5));
    assert_invalid_input(super::Met::new(1013.25, 288.15, 1.5));
    assert_invalid_input(super::Met::standard(f64::INFINITY, 0.5));
    assert_invalid_input(super::Met::standard(100.0, f64::NAN));
    assert_invalid_input(super::Met::standard(100_000.0, 0.5));

    assert_invalid_input(super::tropo_slant(f64::NAN, receiver, met, epoch));
    assert_invalid_input(super::tropo_slant(-1.0e-6, receiver, met, epoch));
    assert_invalid_input(super::tropo_mapping(
        super::MappingModel::Niell,
        0.0,
        receiver,
        epoch,
    ));

    let bad_receiver = crate::frame::Wgs84Geodetic {
        lat_rad: f64::NAN,
        lon_rad: receiver.lon_rad,
        height_m: receiver.height_m,
    };
    assert_invalid_input(super::tropo_slant(elevation, bad_receiver, met, epoch));

    let west_antimeridian = crate::frame::Wgs84Geodetic {
        lat_rad: receiver.lat_rad,
        lon_rad: -core::f64::consts::PI,
        height_m: receiver.height_m,
    };
    super::tropo_slant(elevation, west_antimeridian, met, epoch)
        .expect("west antimeridian receiver is valid");

    let bad_lon_receiver = crate::frame::Wgs84Geodetic {
        lat_rad: receiver.lat_rad,
        lon_rad: -core::f64::consts::PI - 1.0e-12,
        height_m: receiver.height_m,
    };
    assert_invalid_input(super::tropo_slant(elevation, bad_lon_receiver, met, epoch));

    let high_receiver = crate::frame::Wgs84Geodetic {
        lat_rad: receiver.lat_rad,
        lon_rad: receiver.lon_rad,
        height_m: 20_000.0,
    };
    assert_invalid_input(super::tropo_mapping(
        super::MappingModel::Niell,
        elevation,
        high_receiver,
        epoch,
    ));

    let bad_met = super::Met::new_unchecked(1013.25, f64::INFINITY, 0.5);
    assert_invalid_input(super::tropo_zenith(
        super::TropoModel::Saastamoinen,
        receiver,
        bad_met,
    ));

    let bad_epoch = Instant {
        scale: TimeScale::Gpst,
        repr: crate::astro::time::model::InstantRepr::JulianDate(JulianDateSplit {
            jd_whole: f64::NAN,
            fraction: 0.0,
        }),
    };
    assert_invalid_input(super::tropo_mapping(
        super::MappingModel::Niell,
        elevation,
        receiver,
        bad_epoch,
    ));

    let huge_epoch = Instant {
        scale: TimeScale::Gpst,
        repr: crate::astro::time::model::InstantRepr::JulianDate(JulianDateSplit {
            jd_whole: 1.0e20,
            fraction: 0.0,
        }),
    };
    assert_invalid_input(super::tropo_mapping(
        super::MappingModel::Niell,
        elevation,
        receiver,
        huge_epoch,
    ));

    let ancient_epoch = Instant {
        scale: TimeScale::Gpst,
        repr: crate::astro::time::model::InstantRepr::JulianDate(JulianDateSplit {
            jd_whole: 213.0,
            fraction: 0.0,
        }),
    };
    assert_invalid_input(super::tropo_mapping(
        super::MappingModel::Niell,
        elevation,
        receiver,
        ancient_epoch,
    ));
}

fn fixture_path_named(parts: &[&str]) -> PathBuf {
    let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    path.push("tests");
    path.push("fixtures");
    for part in parts {
        path.push(part);
    }
    path
}

fn bits_value(v: &Value) -> f64 {
    crate::test_parity::f64_from_hex(v.as_str().expect("hex-bit string")).expect("valid f64 bits")
}

fn bits_array3(v: &Value) -> [f64; 3] {
    let values: Vec<f64> = v
        .as_array()
        .expect("hex-bit array")
        .iter()
        .map(bits_value)
        .collect();
    [values[0], values[1], values[2]]
}

#[test]
fn zwd_xyz_variant_matches_generated_fixture_bits() {
    let raw = std::fs::read_to_string(fixture_path_named(&["tropo_zwd", "tropo_zwd.json"]))
        .expect("read tropo_zwd fixture");
    let doc: Value = serde_json::from_str(&raw).expect("parse tropo_zwd fixture");
    assert_eq!(doc["schema"], "gnss-tropo-zwd-v1");
    assert_eq!(doc["pyproj_version"], "3.6.1");

    let mut checked = 0usize;
    for case in doc["cases"].as_array().expect("cases") {
        let name = case["name"].as_str().expect("name");
        let day = case["day_of_year"].as_u64().expect("day") as u16;
        let sat = bits_array3(&case["sat_xyz_bits"]);
        let rx = bits_array3(&case["receiver_xyz_bits"]);
        let receiver_lonlatalt = bits_array3(&case["receiver_lonlatalt_bits"]);
        let options = super::ZwdSlantOptions::new(
            super::ZwdEpoch::new(0, day).expect("valid ZWD epoch"),
            super::ZwdProfile::default(),
        )
        .expect("valid ZWD options");
        let got = super::tropo_zwd_delay_xyz(options, &sat, &rx, |_| receiver_lonlatalt)
            .expect("valid ZWD XYZ inputs");
        let want = bits_value(&case["delay_bits"]);
        assert_eq!(
            got.to_bits(),
            want.to_bits(),
            "{name} ZWD delay bits: got=0x{:016x} want=0x{:016x}",
            got.to_bits(),
            want.to_bits()
        );
        checked += 1;
    }
    assert!(checked > 0, "empty tropo_zwd fixture");
}

#[test]
fn zwd_public_helpers_reject_invalid_inputs() {
    assert_invalid_input(super::ZwdEpoch::new(0, 0));
    assert_invalid_input(super::ZwdEpoch::new(0, 367));

    let profile = super::ZwdProfile::default();
    assert_invalid_input(super::ZwdSlantOptions::new(
        super::ZwdEpoch {
            unix_nanos: 0,
            day_of_year: 120,
        },
        super::ZwdProfile {
            wet_scale_height_m: f64::NAN,
            ..profile
        },
    ));
    assert_invalid_input(super::zwd_zenith_wet_delay(
        super::ZwdProfile {
            altitude_clamp: super::AltitudeClamp {
                min_m: 10.0,
                max_m: -10.0,
            },
            ..profile
        },
        100.0,
    ));
    assert_invalid_input(super::zwd_zenith_wet_delay(profile, f64::INFINITY));

    assert_invalid_input(super::zwd::niell_mapping_function(
        30.0_f64.to_radians(),
        91.0,
        120,
        100.0,
    ));

    let options = super::ZwdSlantOptions::new(
        super::ZwdEpoch::new(0, 120).expect("valid ZWD epoch"),
        profile,
    )
    .expect("valid ZWD options");
    let sat = [20_000_000.0, 1_000_000.0, 2_000_000.0];
    let rx = [6_300_000.0, 0.0, 0.0];
    assert_invalid_input(super::tropo_zwd_delay_xyz(
        options,
        &[f64::NAN, sat[1], sat[2]],
        &rx,
        |_| [0.0, 0.0, 0.0],
    ));
    assert_invalid_input(super::tropo_zwd_delay_xyz(options, &rx, &rx, |_| {
        [0.0, 0.0, 0.0]
    }));
    assert_invalid_input(super::tropo_zwd_delay_xyz(options, &sat, &rx, |_| {
        [0.0, f64::NAN, 0.0]
    }));
}