siderust 0.7.0

High-precision astronomy and satellite mechanics in Rust.
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Vallés Puig, Ramon

//! # DE4xx Body-Chain Resolution
//!
//! ## Scientific scope
//!
//! The JPL DE ephemerides natively integrate the Sun, the Earth–Moon
//! Barycenter (EMB), and the Moon relative to the EMB.  This module
//! reconstructs the individual states of the Sun, Earth, and Moon in
//! every reference-center and unit combination required by the public
//! [`Ephemeris`](crate::calculus::ephemeris::Ephemeris) trait.
//!
//! Derived quantities:
//!
//! - **Earth barycentric** = EMB − Moon_offset × μ_Moon / (μ_Earth + μ_Moon)
//! - **Moon geocentric**   = Moon_offset × μ_Earth / (μ_Earth + μ_Moon)
//! - **Earth heliocentric**= Earth_bary − Sun_bary
//!
//! where μ_Moon / (μ_Earth + μ_Moon) ≈ 1/82.300560.
//!
//! ## Technical scope
//!
//! - All intermediate vectors carry frame
//!   ([`crate::coordinates::frames::ICRF`]) and unit ([`Kilometer`]
//!   or [`Per<Kilometer, Day>`]) in the type system; body-chain arithmetic
//!   is compile-time checked.
//! - Frame conversion (ICRF → EclipticMeanJ2000) and unit conversion
//!   (km → AU, km/day → AU/day) are applied explicitly after chain arithmetic.
//! - Time input: `JulianDate` (TT); TT → TDB conversion is performed
//!   internally via [`JulianDate::tt_to_tdb`].
//!
//! | Segment | DE NAIF IDs   | Meaning                                |
//! |---------|---------------|----------------------------------------|
//! | Sun     | 10 → 0 (SSB)  | Sun barycentric (ICRF, km)             |
//! | EMB     |  3 → 0 (SSB)  | Earth-Moon barycenter bary. (ICRF, km) |
//! | Moon    | 301 → 3 (EMB) | Moon offset from EMB (ICRF, km)        |
//!
//! ## References
//!
//! - Standish, E. M. (1998). "JPL Planetary and Lunar Ephemerides, DE405/LE405".
//!   *JPL Interoffice Memorandum* 312.F-98-048.
//! - Park, R. S., et al. (2021). "The JPL Planetary and Lunar Ephemerides
//!   DE440 and DE441". *The Astronomical Journal* 161, 105.
//!   <https://doi.org/10.3847/1538-3881/abd414>

use super::eval::{DynSegmentDescriptor, SegmentDescriptor};

use crate::calculus::ephemeris::EphemerisError;
use crate::coordinates::{
    cartesian::{Position, Velocity},
    centers::{Barycentric, Geocentric, Heliocentric},
    frames::EclipticMeanJ2000,
    transform::VectorAstroExt,
};
use crate::qtty::{AstronomicalUnit, Day, Kilometer, Per};
use crate::time::JulianDate;

// ── Physical constants (single source of truth: qtty + DE4xx headers) ────

/// Earth/Moon mass ratio embedded in DE4xx headers.
///
/// This value is consistent across DE440 and DE441.
const EARTH_MOON_RATIO: f64 = 81.300_569_074_190_62;

/// μ_Earth / (μ_Earth + μ_Moon) , Earth's mass fraction of the EM system.
const FRAC_EARTH: f64 = EARTH_MOON_RATIO / (EARTH_MOON_RATIO + 1.0);

/// μ_Moon / (μ_Earth + μ_Moon) , Moon's mass fraction of the EM system.
const FRAC_MOON: f64 = 1.0 / (EARTH_MOON_RATIO + 1.0);

// ── Velocity type alias ─────────────────────────────────────────────────

type AuPerDay = Per<AstronomicalUnit, Day>;

// ── Generic body-chain functions ─────────────────────────────────────────

/// Sun barycentric position in EclipticMeanJ2000 J2000 (AU).
///
/// Generic over any DE4xx data source providing a SUN segment.
#[inline]
pub fn try_sun_barycentric(
    jd: JulianDate,
    sun: &SegmentDescriptor,
) -> Result<Position<Barycentric, EclipticMeanJ2000, AstronomicalUnit>, EphemerisError> {
    let jd_tdb = JulianDate::tt_to_tdb(jd);
    let sun_icrf = sun.try_position(jd_tdb)?;
    let sun_ecl_au = sun_icrf
        .to_frame::<EclipticMeanJ2000>(&JulianDate::J2000)
        .to_unit::<AstronomicalUnit>();
    Ok(Position::new(
        sun_ecl_au.x(),
        sun_ecl_au.y(),
        sun_ecl_au.z(),
    ))
}

/// Sun barycentric position in EclipticMeanJ2000 J2000 (AU).
///
/// # Panics
///
/// Panics when `jd` is outside the underlying JPL segment coverage. Use
/// [`try_sun_barycentric`] for explicit error handling.
#[inline]
pub fn sun_barycentric(
    jd: JulianDate,
    sun: &SegmentDescriptor,
) -> Position<Barycentric, EclipticMeanJ2000, AstronomicalUnit> {
    try_sun_barycentric(jd, sun).expect("JPL Sun barycentric position unavailable")
}

/// Earth barycentric position in EclipticMeanJ2000 J2000 (AU).
///
/// `Earth_bary = EMB − Moon_offset × FRAC_MOON`
///
/// Generic over any DE4xx data source providing EMB and MOON segments.
#[inline]
pub fn try_earth_barycentric(
    jd: JulianDate,
    emb: &SegmentDescriptor,
    moon: &SegmentDescriptor,
) -> Result<Position<Barycentric, EclipticMeanJ2000, AstronomicalUnit>, EphemerisError> {
    let jd_tdb = JulianDate::tt_to_tdb(jd);
    let emb_pos = emb.try_position(jd_tdb)?;
    let moon_off = moon.try_position(jd_tdb)?;
    let earth_icrf = emb_pos - moon_off.scale(FRAC_MOON);
    let earth_ecl_au = earth_icrf
        .to_frame::<EclipticMeanJ2000>(&JulianDate::J2000)
        .to_unit::<AstronomicalUnit>();
    Ok(Position::new(
        earth_ecl_au.x(),
        earth_ecl_au.y(),
        earth_ecl_au.z(),
    ))
}

/// Earth barycentric position in EclipticMeanJ2000 J2000 (AU).
///
/// # Panics
///
/// Panics when `jd` is outside the underlying JPL segment coverage. Use
/// [`try_earth_barycentric`] for explicit error handling.
#[inline]
pub fn earth_barycentric(
    jd: JulianDate,
    emb: &SegmentDescriptor,
    moon: &SegmentDescriptor,
) -> Position<Barycentric, EclipticMeanJ2000, AstronomicalUnit> {
    try_earth_barycentric(jd, emb, moon).expect("JPL Earth barycentric position unavailable")
}

/// Earth heliocentric position in EclipticMeanJ2000 J2000 (AU).
///
/// `Earth_helio = Earth_bary − Sun_bary`
///
/// Generic over any DE4xx data source providing SUN, EMB, and MOON segments.
#[inline]
pub fn try_earth_heliocentric(
    jd: JulianDate,
    sun: &SegmentDescriptor,
    emb: &SegmentDescriptor,
    moon: &SegmentDescriptor,
) -> Result<Position<Heliocentric, EclipticMeanJ2000, AstronomicalUnit>, EphemerisError> {
    let jd_tdb = JulianDate::tt_to_tdb(jd);
    let emb_pos = emb.try_position(jd_tdb)?;
    let moon_off = moon.try_position(jd_tdb)?;
    let sun_pos = sun.try_position(jd_tdb)?;
    let earth_icrf = emb_pos - moon_off.scale(FRAC_MOON) - sun_pos;
    let earth_ecl_au = earth_icrf
        .to_frame::<EclipticMeanJ2000>(&JulianDate::J2000)
        .to_unit::<AstronomicalUnit>();
    Ok(Position::new(
        earth_ecl_au.x(),
        earth_ecl_au.y(),
        earth_ecl_au.z(),
    ))
}

/// Earth heliocentric position in EclipticMeanJ2000 J2000 (AU).
///
/// # Panics
///
/// Panics when `jd` is outside the underlying JPL segment coverage. Use
/// [`try_earth_heliocentric`] for explicit error handling.
#[inline]
pub fn earth_heliocentric(
    jd: JulianDate,
    sun: &SegmentDescriptor,
    emb: &SegmentDescriptor,
    moon: &SegmentDescriptor,
) -> Position<Heliocentric, EclipticMeanJ2000, AstronomicalUnit> {
    try_earth_heliocentric(jd, sun, emb, moon).expect("JPL Earth heliocentric position unavailable")
}

/// Earth barycentric velocity in EclipticMeanJ2000 J2000 (AU/day).
///
/// `v_Earth = v_EMB − v_Moon_offset × FRAC_MOON`
///
/// Generic over any DE4xx data source providing EMB and MOON segments.
#[inline]
pub fn try_earth_barycentric_velocity(
    jd: JulianDate,
    emb: &SegmentDescriptor,
    moon: &SegmentDescriptor,
) -> Result<Velocity<EclipticMeanJ2000, AuPerDay>, EphemerisError> {
    let jd_tdb = JulianDate::tt_to_tdb(jd);
    let v_emb = emb.try_velocity(jd_tdb)?;
    let v_moon_off = moon.try_velocity(jd_tdb)?;
    let v_earth_icrf = v_emb - v_moon_off.scale(FRAC_MOON);
    Ok(v_earth_icrf
        .to_frame::<EclipticMeanJ2000>(&JulianDate::J2000)
        .to_unit::<AuPerDay>())
}

/// Earth barycentric velocity in EclipticMeanJ2000 J2000 (AU/day).
///
/// # Panics
///
/// Panics when `jd` is outside the underlying JPL segment coverage. Use
/// [`try_earth_barycentric_velocity`] for explicit error handling.
#[inline]
pub fn earth_barycentric_velocity(
    jd: JulianDate,
    emb: &SegmentDescriptor,
    moon: &SegmentDescriptor,
) -> Velocity<EclipticMeanJ2000, AuPerDay> {
    try_earth_barycentric_velocity(jd, emb, moon)
        .expect("JPL Earth barycentric velocity unavailable")
}

/// Moon geocentric position in EclipticMeanJ2000 J2000 (km).
///
/// `Moon_geo = Moon_offset × FRAC_EARTH`
///
/// Generic over any DE4xx data source providing a MOON segment.
#[inline]
pub fn try_moon_geocentric(
    jd: JulianDate,
    moon: &SegmentDescriptor,
) -> Result<Position<Geocentric, EclipticMeanJ2000, Kilometer>, EphemerisError> {
    let jd_tdb = JulianDate::tt_to_tdb(jd);
    let moon_off = moon.try_position(jd_tdb)?;
    let moon_geo_icrf = moon_off.scale(FRAC_EARTH);
    let moon_geo_ecl = moon_geo_icrf.to_frame::<EclipticMeanJ2000>(&JulianDate::J2000);
    Ok(Position::new(
        moon_geo_ecl.x(),
        moon_geo_ecl.y(),
        moon_geo_ecl.z(),
    ))
}

/// Moon geocentric position in EclipticMeanJ2000 J2000 (km).
///
/// # Panics
///
/// Panics when `jd` is outside the underlying JPL segment coverage. Use
/// [`try_moon_geocentric`] for explicit error handling.
#[inline]
pub fn moon_geocentric(
    jd: JulianDate,
    moon: &SegmentDescriptor,
) -> Position<Geocentric, EclipticMeanJ2000, Kilometer> {
    try_moon_geocentric(jd, moon).expect("JPL Moon geocentric position unavailable")
}

// ═══════════════════════════════════════════════════════════════════════════
// DynSegmentDescriptor variants, runtime-loaded data
// ═══════════════════════════════════════════════════════════════════════════

/// Sun barycentric position (runtime data).
#[inline]
pub fn try_dyn_sun_barycentric(
    jd: JulianDate,
    sun: &DynSegmentDescriptor,
) -> Result<Position<Barycentric, EclipticMeanJ2000, AstronomicalUnit>, EphemerisError> {
    let jd_tdb = JulianDate::tt_to_tdb(jd);
    let sun_icrf = sun.try_position(jd_tdb)?;
    let sun_ecl_au = sun_icrf
        .to_frame::<EclipticMeanJ2000>(&JulianDate::J2000)
        .to_unit::<AstronomicalUnit>();
    Ok(Position::new(
        sun_ecl_au.x(),
        sun_ecl_au.y(),
        sun_ecl_au.z(),
    ))
}

/// Sun barycentric position (runtime data).
#[inline]
pub fn dyn_sun_barycentric(
    jd: JulianDate,
    sun: &DynSegmentDescriptor,
) -> Position<Barycentric, EclipticMeanJ2000, AstronomicalUnit> {
    try_dyn_sun_barycentric(jd, sun).expect("runtime JPL Sun barycentric position unavailable")
}

/// Earth barycentric position (runtime data).
#[inline]
pub fn try_dyn_earth_barycentric(
    jd: JulianDate,
    emb: &DynSegmentDescriptor,
    moon: &DynSegmentDescriptor,
) -> Result<Position<Barycentric, EclipticMeanJ2000, AstronomicalUnit>, EphemerisError> {
    let jd_tdb = JulianDate::tt_to_tdb(jd);
    let emb_pos = emb.try_position(jd_tdb)?;
    let moon_off = moon.try_position(jd_tdb)?;
    let earth_icrf = emb_pos - moon_off.scale(FRAC_MOON);
    let earth_ecl_au = earth_icrf
        .to_frame::<EclipticMeanJ2000>(&JulianDate::J2000)
        .to_unit::<AstronomicalUnit>();
    Ok(Position::new(
        earth_ecl_au.x(),
        earth_ecl_au.y(),
        earth_ecl_au.z(),
    ))
}

/// Earth barycentric position (runtime data).
#[inline]
pub fn dyn_earth_barycentric(
    jd: JulianDate,
    emb: &DynSegmentDescriptor,
    moon: &DynSegmentDescriptor,
) -> Position<Barycentric, EclipticMeanJ2000, AstronomicalUnit> {
    try_dyn_earth_barycentric(jd, emb, moon)
        .expect("runtime JPL Earth barycentric position unavailable")
}

/// Earth heliocentric position (runtime data).
#[inline]
pub fn try_dyn_earth_heliocentric(
    jd: JulianDate,
    sun: &DynSegmentDescriptor,
    emb: &DynSegmentDescriptor,
    moon: &DynSegmentDescriptor,
) -> Result<Position<Heliocentric, EclipticMeanJ2000, AstronomicalUnit>, EphemerisError> {
    let jd_tdb = JulianDate::tt_to_tdb(jd);
    let emb_pos = emb.try_position(jd_tdb)?;
    let moon_off = moon.try_position(jd_tdb)?;
    let sun_pos = sun.try_position(jd_tdb)?;
    let earth_icrf = emb_pos - moon_off.scale(FRAC_MOON) - sun_pos;
    let earth_ecl_au = earth_icrf
        .to_frame::<EclipticMeanJ2000>(&JulianDate::J2000)
        .to_unit::<AstronomicalUnit>();
    Ok(Position::new(
        earth_ecl_au.x(),
        earth_ecl_au.y(),
        earth_ecl_au.z(),
    ))
}

/// Earth heliocentric position (runtime data).
#[inline]
pub fn dyn_earth_heliocentric(
    jd: JulianDate,
    sun: &DynSegmentDescriptor,
    emb: &DynSegmentDescriptor,
    moon: &DynSegmentDescriptor,
) -> Position<Heliocentric, EclipticMeanJ2000, AstronomicalUnit> {
    try_dyn_earth_heliocentric(jd, sun, emb, moon)
        .expect("runtime JPL Earth heliocentric position unavailable")
}

/// Earth barycentric velocity (runtime data).
#[inline]
pub fn try_dyn_earth_barycentric_velocity(
    jd: JulianDate,
    emb: &DynSegmentDescriptor,
    moon: &DynSegmentDescriptor,
) -> Result<Velocity<EclipticMeanJ2000, AuPerDay>, EphemerisError> {
    let jd_tdb = JulianDate::tt_to_tdb(jd);
    let v_emb = emb.try_velocity(jd_tdb)?;
    let v_moon_off = moon.try_velocity(jd_tdb)?;
    let v_earth_icrf = v_emb - v_moon_off.scale(FRAC_MOON);
    Ok(v_earth_icrf
        .to_frame::<EclipticMeanJ2000>(&JulianDate::J2000)
        .to_unit::<AuPerDay>())
}

/// Earth barycentric velocity (runtime data).
#[inline]
pub fn dyn_earth_barycentric_velocity(
    jd: JulianDate,
    emb: &DynSegmentDescriptor,
    moon: &DynSegmentDescriptor,
) -> Velocity<EclipticMeanJ2000, AuPerDay> {
    try_dyn_earth_barycentric_velocity(jd, emb, moon)
        .expect("runtime JPL Earth barycentric velocity unavailable")
}

/// Moon geocentric position (runtime data).
#[inline]
pub fn try_dyn_moon_geocentric(
    jd: JulianDate,
    moon: &DynSegmentDescriptor,
) -> Result<Position<Geocentric, EclipticMeanJ2000, Kilometer>, EphemerisError> {
    let jd_tdb = JulianDate::tt_to_tdb(jd);
    let moon_off = moon.try_position(jd_tdb)?;
    let moon_geo_icrf = moon_off.scale(FRAC_EARTH);
    let moon_geo_ecl = moon_geo_icrf.to_frame::<EclipticMeanJ2000>(&JulianDate::J2000);
    Ok(Position::new(
        moon_geo_ecl.x(),
        moon_geo_ecl.y(),
        moon_geo_ecl.z(),
    ))
}

/// Moon geocentric position (runtime data).
#[inline]
pub fn dyn_moon_geocentric(
    jd: JulianDate,
    moon: &DynSegmentDescriptor,
) -> Position<Geocentric, EclipticMeanJ2000, Kilometer> {
    try_dyn_moon_geocentric(jd, moon).expect("runtime JPL Moon geocentric position unavailable")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::calculus::jpl::eval::{DynSegmentDescriptor, SegmentDescriptor};

    const SECONDS_PER_DAY: f64 = crate::qtty::time::SECONDS_PER_DAY;
    const JD_J2000: f64 = 2451545.0;

    // ── Shared test data for SegmentDescriptor (compile-time variant) ─────

    /// Static record for sun-like segment: position ~0.5 AU at tau=0.
    static SUN_RECORD: [f64; 8] = [
        500.0 * SECONDS_PER_DAY, // mid (seconds past J2000)
        500.0 * SECONDS_PER_DAY, // radius = half-interval
        7.5e7,
        0.0, // cx ~0.5 AU in km
        3.0e7,
        0.0, // cy
        1.0e7,
        0.0, // cz
    ];

    /// Static record for EMB-like segment: ~1 AU from SSB.
    static EMB_RECORD: [f64; 8] = [
        500.0 * SECONDS_PER_DAY,
        500.0 * SECONDS_PER_DAY,
        1.5e8,
        0.0, // ~1 AU
        0.0,
        0.0,
        0.0,
        0.0,
    ];

    /// Static record for Moon offset (~Earth-Moon distance).
    static MOON_RECORD: [f64; 8] = [
        500.0 * SECONDS_PER_DAY,
        500.0 * SECONDS_PER_DAY,
        3.84e5,
        0.0, // ~384400 km
        0.0,
        0.0,
        0.0,
        0.0,
    ];

    fn sun_record_fn(_: usize) -> &'static [f64] {
        &SUN_RECORD
    }
    fn emb_record_fn(_: usize) -> &'static [f64] {
        &EMB_RECORD
    }
    fn moon_record_fn(_: usize) -> &'static [f64] {
        &MOON_RECORD
    }

    fn make_static_seg(record_fn: fn(usize) -> &'static [f64]) -> SegmentDescriptor {
        use crate::qtty::Seconds;
        SegmentDescriptor {
            init: Seconds::new(0.0),
            intlen: Seconds::new(1000.0 * SECONDS_PER_DAY),
            ncoeff: 2,
            n_records: 1,
            record_fn,
        }
    }

    fn jd_test_static() -> JulianDate {
        JulianDate::new(JD_J2000 + 500.0)
    }

    // ── SegmentDescriptor (compile-time) tests ────────────────────────────

    #[test]
    fn sun_barycentric_is_finite() {
        let sun = make_static_seg(sun_record_fn);
        let pos = sun_barycentric(jd_test_static(), &sun);
        assert!(pos.x().is_finite());
        assert!(pos.y().is_finite());
        assert!(pos.z().is_finite());
    }

    #[test]
    fn earth_barycentric_is_finite() {
        let emb = make_static_seg(emb_record_fn);
        let moon = make_static_seg(moon_record_fn);
        let pos = earth_barycentric(jd_test_static(), &emb, &moon);
        assert!(pos.x().is_finite());
        assert!(pos.y().is_finite());
        assert!(pos.z().is_finite());
    }

    #[test]
    fn earth_heliocentric_is_finite() {
        let sun = make_static_seg(sun_record_fn);
        let emb = make_static_seg(emb_record_fn);
        let moon = make_static_seg(moon_record_fn);
        let pos = earth_heliocentric(jd_test_static(), &sun, &emb, &moon);
        assert!(pos.x().is_finite());
        assert!(pos.y().is_finite());
        assert!(pos.z().is_finite());
    }

    #[test]
    fn earth_barycentric_velocity_is_finite() {
        let emb = make_static_seg(emb_record_fn);
        let moon = make_static_seg(moon_record_fn);
        let vel = earth_barycentric_velocity(jd_test_static(), &emb, &moon);
        assert!(vel.x().is_finite());
        assert!(vel.y().is_finite());
        assert!(vel.z().is_finite());
    }

    #[test]
    fn moon_geocentric_is_finite() {
        let moon = make_static_seg(moon_record_fn);
        let pos = moon_geocentric(jd_test_static(), &moon);
        assert!(pos.x().is_finite());
        assert!(pos.y().is_finite());
        assert!(pos.z().is_finite());
    }

    #[test]
    fn moon_geocentric_magnitude_scaled_by_frac_earth() {
        let r_km = 384400.0;
        let moon = make_static_seg(moon_record_fn); // position = (r_km, 0, 0) at tau=0
        let pos = moon_geocentric(jd_test_static(), &moon);
        let mag =
            (pos.x().value().powi(2) + pos.y().value().powi(2) + pos.z().value().powi(2)).sqrt();
        let expected = r_km * FRAC_EARTH;
        assert!(
            (mag - expected).abs() / expected < 0.01,
            "mag={mag}, expected={expected}"
        );
    }

    // ── DynSegmentDescriptor tests ────────────────────────────────────────

    /// Create a synthetic DynSegmentDescriptor representing a constant position.
    ///
    /// The segment spans 1000 days from J2000. The position at tau=0 (J2000+500d)
    /// is (x_km, y_km, z_km) in ICRF km. The velocity is zero.
    fn make_seg(x_km: f64, y_km: f64, z_km: f64) -> DynSegmentDescriptor {
        use crate::qtty::Seconds;
        let ncoeff = 2usize;
        let rsize = 2 + 3 * ncoeff; // 8
        let intlen_secs = 1000.0 * SECONDS_PER_DAY;
        let mid = intlen_secs / 2.0;
        let radius = intlen_secs / 2.0;
        // Record: [mid, radius, cx0, cx1, cy0, cy1, cz0, cz1]
        let data = vec![mid, radius, x_km, 0.0, y_km, 0.0, z_km, 0.0];
        DynSegmentDescriptor {
            init: Seconds::new(0.0),
            intlen: Seconds::new(intlen_secs),
            ncoeff,
            rsize,
            n_records: 1,
            data,
        }
    }

    /// JD at J2000 + 500 days (midpoint of our test segment → tau = 0).
    fn jd_test() -> JulianDate {
        JulianDate::new(JD_J2000 + 500.0)
    }

    // ── FRAC constants ────────────────────────────────────────────────────

    #[test]
    fn frac_earth_plus_frac_moon_equals_one() {
        assert!((FRAC_EARTH + FRAC_MOON - 1.0).abs() < 1e-12);
    }

    #[test]
    fn frac_earth_is_dominant() {
        const {
            assert!(FRAC_EARTH > 0.98);
        }
        const {
            assert!(FRAC_MOON < 0.02);
        }
    }

    // ── dyn_sun_barycentric ───────────────────────────────────────────────

    #[test]
    fn dyn_sun_barycentric_is_finite() {
        let sun = make_seg(1.0e8, 2.0e7, 3.0e6); // ~1 AU-ish in km
        let pos = dyn_sun_barycentric(jd_test(), &sun);
        assert!(pos.x().is_finite());
        assert!(pos.y().is_finite());
        assert!(pos.z().is_finite());
    }

    // ── dyn_earth_barycentric ─────────────────────────────────────────────

    #[test]
    fn dyn_earth_barycentric_is_finite() {
        let emb = make_seg(1.5e8, 0.0, 0.0);
        let moon = make_seg(3.84e5, 0.0, 0.0);
        let pos = dyn_earth_barycentric(jd_test(), &emb, &moon);
        assert!(pos.x().is_finite());
        assert!(pos.y().is_finite());
        assert!(pos.z().is_finite());
    }

    // ── dyn_earth_heliocentric ─────────────────────────────────────────────

    #[test]
    fn dyn_earth_heliocentric_is_finite() {
        let sun = make_seg(1.0e8, 0.0, 0.0);
        let emb = make_seg(1.5e8, 0.0, 0.0);
        let moon = make_seg(3.84e5, 0.0, 0.0);
        let pos = dyn_earth_heliocentric(jd_test(), &sun, &emb, &moon);
        assert!(pos.x().is_finite());
        assert!(pos.y().is_finite());
        assert!(pos.z().is_finite());
    }

    // ── dyn_earth_barycentric_velocity ────────────────────────────────────

    #[test]
    fn dyn_earth_barycentric_velocity_is_finite() {
        let emb = make_seg(1.5e8, 0.0, 0.0);
        let moon = make_seg(3.84e5, 0.0, 0.0);
        let vel = dyn_earth_barycentric_velocity(jd_test(), &emb, &moon);
        assert!(vel.x().is_finite());
        assert!(vel.y().is_finite());
        assert!(vel.z().is_finite());
    }

    // ── dyn_moon_geocentric ───────────────────────────────────────────────

    #[test]
    fn dyn_moon_geocentric_is_finite() {
        let moon = make_seg(3.84e5, 1.0e4, 2.0e3);
        let pos = dyn_moon_geocentric(jd_test(), &moon);
        assert!(pos.x().is_finite());
        assert!(pos.y().is_finite());
        assert!(pos.z().is_finite());
    }

    #[test]
    fn dyn_moon_geocentric_scaled_by_frac_earth() {
        // With moon_off = (R, 0, 0) at tau=0, geocentric = moon_off * FRAC_EARTH
        // After frame transform, x should be close to R * FRAC_EARTH (ignoring rotation)
        let r_km = 384400.0;
        let moon = make_seg(r_km, 0.0, 0.0);
        let pos = dyn_moon_geocentric(jd_test(), &moon);
        // The frame rotation can change x/y/z but the magnitude should be ~r_km * FRAC_EARTH
        let magnitude =
            (pos.x().value().powi(2) + pos.y().value().powi(2) + pos.z().value().powi(2)).sqrt();
        let expected = r_km * FRAC_EARTH;
        assert!(
            (magnitude - expected).abs() / expected < 0.01,
            "magnitude={magnitude}, expected={expected}"
        );
    }

    // ── dyn_sun_barycentric with realistic values ─────────────────────────

    #[test]
    fn dyn_sun_barycentric_small_offset_from_origin() {
        // Sun barycentric should be close to origin (~few million km)
        // Use known-ish values: Sun is ~0.005 AU from SSB
        let sun = make_seg(5.0e5, 3.0e5, 1.0e5); // ~0.005 AU range
        let pos = dyn_sun_barycentric(jd_test(), &sun);
        let mag_au =
            (pos.x().value().powi(2) + pos.y().value().powi(2) + pos.z().value().powi(2)).sqrt();
        // ~0.005 AU is plausible for Sun-SSB offset
        assert!(mag_au < 0.1, "unexpected large Sun-SSB offset: {mag_au} AU");
    }
}