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
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
//! SGP4 satellite propagation with 0 ULP parity to the Vallado C++ reference
//! implementation (v2020-07-13).
//!
//! This module is a faithful pure-Rust port of Vallado's SGP4 verified bit-for-bit
//! against the canonical 33-satellite / 198-propagation-point Vallado verification
//! suite. TLEs are curve-fit parameters generated by Vallado's SGP4; using a
//! different propagator introduces errors. This module preserves the exact
//! floating-point computation order of the C++ reference so output matches
//! Python's `sgp4` C extension (which compiles the same source) bit-for-bit.
//!
//! ## Quick start
//!
//! ```
//! use sidereon_core::astro::sgp4::{Satellite, MinutesSinceEpoch};
//!
//! let line1 = "1 25544U 98067A   18184.80969102  .00001614  00000-0  31745-4 0  9993";
//! let line2 = "2 25544  51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106";
//!
//! let sat = Satellite::from_tle(line1, line2).unwrap();
//! let pred = sat.propagate(MinutesSinceEpoch(0.0)).unwrap();
//!
//! // position in km, velocity in km/s, TEME frame
//! let _ = pred.position;
//! let _ = pred.velocity;
//! ```

#[allow(
    dead_code,
    unused_variables,
    unused_assignments,
    unused_mut,
    non_snake_case,
    non_camel_case_types,
    clippy::approx_constant,
    clippy::excessive_precision,
    clippy::too_many_arguments,
    clippy::needless_return,
    clippy::assign_op_pattern,
    clippy::manual_range_contains,
    clippy::collapsible_if,
    clippy::collapsible_else_if,
    clippy::float_cmp,
    clippy::needless_late_init,
    clippy::field_reassign_with_default
)]
mod vallado;

use crate::astro::tle;
use crate::validate::{self, FieldError};
use thiserror::Error;

const MAX_VALLADO_SATNUM: u32 = 99_999;

// ── Error ────────────────────────────────────────────────────────────

/// Validation failure category for public SGP4 inputs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Sgp4InputErrorKind {
    /// A numeric input was NaN or infinite.
    NonFinite,
    /// A positive physical input was zero or negative.
    NotPositive,
    /// A non-negative physical input was negative.
    Negative,
    /// A numeric input was finite but outside the SGP4 domain.
    OutOfRange,
    /// A required input field was absent.
    Missing,
    /// A text field could not be parsed as a float.
    FloatParse,
    /// A text field could not be parsed as an integer.
    IntParse,
    /// A civil date field was out of range.
    InvalidCivilDate,
    /// A civil time field was out of range.
    InvalidCivilTime,
}

impl core::fmt::Display for Sgp4InputErrorKind {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let label = match self {
            Self::NonFinite => "not finite",
            Self::NotPositive => "not positive",
            Self::Negative => "negative",
            Self::OutOfRange => "out of range",
            Self::Missing => "missing",
            Self::FloatParse => "invalid float",
            Self::IntParse => "invalid integer",
            Self::InvalidCivilDate => "invalid civil date",
            Self::InvalidCivilTime => "invalid civil time",
        };
        f.write_str(label)
    }
}

impl From<&FieldError> for Sgp4InputErrorKind {
    fn from(error: &FieldError) -> Self {
        match error {
            FieldError::Missing { .. } => Self::Missing,
            FieldError::NonFinite { .. } => Self::NonFinite,
            FieldError::NotPositive { .. } => Self::NotPositive,
            FieldError::Negative { .. } => Self::Negative,
            FieldError::OutOfRange { .. } => Self::OutOfRange,
            FieldError::FloatParse { .. } => Self::FloatParse,
            FieldError::IntParse { .. } => Self::IntParse,
            FieldError::InvalidCivilDate { .. } => Self::InvalidCivilDate,
            FieldError::InvalidCivilTime { .. } => Self::InvalidCivilTime,
        }
    }
}

/// Error from SGP4 initialization or propagation.
#[derive(Error, Debug, Clone, PartialEq)]
pub enum Error {
    /// A public SGP4 input was malformed, non-finite, or outside the model
    /// domain. Boundary validation rejects this before the Vallado kernel runs.
    #[error("invalid SGP4 input {field}: {kind}")]
    InvalidInput {
        /// The invalid input field.
        field: &'static str,
        /// The validation failure category.
        kind: Sgp4InputErrorKind,
    },
    /// The Vallado step kernel returned a non-finite state vector.
    #[error("SGP4 returned non-finite {field}")]
    NonFiniteOutput {
        /// The output vector that was non-finite.
        field: &'static str,
    },
    /// TLE line has invalid format.
    #[error("invalid TLE: {0}")]
    InvalidTle(String),
    /// SGP4 returned a non-zero error code.
    ///
    /// Codes: 1 = mean elements, 2 = mean motion, 3 = perturbed elements,
    /// 4 = semi-latus rectum, 5 = epoch elements sub-orbital,
    /// 6 = satellite decayed.
    #[error("SGP4 error code {code}")]
    Sgp4 { code: i32 },
}

const MAX_MINUTES_SINCE_EPOCH: f64 = 10_000_000.0;

// ── Types ────────────────────────────────────────────────────────────

/// Minutes since the TLE epoch. Newtype to prevent mixing with raw `f64`.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MinutesSinceEpoch(pub f64);

/// Propagation result in the TEME (True Equator, Mean Equinox) frame.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Prediction {
    /// Position in km, TEME frame.
    pub position: [f64; 3],
    /// Velocity in km/s, TEME frame.
    pub velocity: [f64; 3],
}

/// Julian date split as `(whole, fraction)` for high-precision time input.
///
/// Skyfield convention: `whole = floor(JD)`, `fraction = remainder`.
/// For example, 2018-07-04 00:00:00 UTC = `JulianDate(2458303.0, 0.5)`.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct JulianDate(pub f64, pub f64);

pub(crate) fn sgp4_julian_date_from_calendar(
    year: i32,
    mon: i32,
    day: i32,
    hr: i32,
    minute: i32,
    sec: f64,
) -> JulianDate {
    let (jd, jdfrac) = vallado::jday_SGP4(year, mon, day, hr, minute, sec);
    JulianDate(jd, jdfrac)
}

pub(crate) fn sgp4_julian_date_from_day_of_year(year: i32, days: f64) -> JulianDate {
    let (mon, day, hr, minute, sec) = vallado::days2mdhms_SGP4(year, days);
    let JulianDate(jd, jdfrac_raw) =
        sgp4_julian_date_from_calendar(year, mon, day, hr, minute, sec);
    let jdfrac = (jdfrac_raw * 100_000_000.0).round() / 100_000_000.0;
    JulianDate(jd, jdfrac)
}

/// Vallado SGP4 operation mode. Controls which initialization branch
/// `sgp4init` follows. The two modes produce subtly different results;
/// the divergence grows with propagation time and can reach hundreds of
/// millimeters over a few orbits at LEO.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum OpsMode {
    /// Improved formulation (Vallado `'i'`). Default for new work and
    /// matches the default of Python's `sgp4` package. Recommended unless
    /// you specifically need AFSPC operational parity.
    #[default]
    Improved,
    /// AFSPC operational compatibility mode (Vallado `'a'`). Use this
    /// when reproducing outputs from operational AFSPC systems or matching
    /// reference values from older crates / catalogs that ran in AFSPC mode.
    Afspc,
}

impl OpsMode {
    fn as_char(self) -> char {
        match self {
            OpsMode::Improved => 'i',
            OpsMode::Afspc => 'a',
        }
    }
}

/// Pre-parsed Vallado SGP4 element set.
///
/// Use this when the TLE has already been parsed externally (e.g. from an
/// OMM message, JSON catalog, or another system) and you want to feed the
/// element values directly into the SGP4 initializer instead of going through
/// the TLE string parser.
///
/// Field units match the Vallado SGP4 reference inputs:
/// angles in **degrees**, mean motion in **revolutions per day**, drag term
/// in the dimensionless TLE convention.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ElementSet {
    /// Epoch as a split Julian date `(whole, fraction)`.
    ///
    /// This is format-agnostic and loss-free for the SGP4 initializer: TLE
    /// conversion stores the exact split JD produced by Vallado's
    /// `days2mdhms`/`jday` path with the legacy 8-decimal fraction rounding,
    /// while OMM conversion stores the split JD from its full calendar
    /// timestamp directly.
    pub epoch: JulianDate,
    /// SGP4 drag term (Vallado B\*). Dimensionless TLE convention.
    pub bstar: f64,
    /// First derivative of mean motion in rev/day². TLE "ndot".
    pub mean_motion_dot: f64,
    /// Second derivative of mean motion in rev/day³. TLE "nddot".
    pub mean_motion_double_dot: f64,
    /// Eccentricity, dimensionless, in [0, 1).
    pub eccentricity: f64,
    /// Argument of perigee, degrees.
    pub argument_of_perigee_deg: f64,
    /// Inclination, degrees.
    pub inclination_deg: f64,
    /// Mean anomaly, degrees.
    pub mean_anomaly_deg: f64,
    /// Mean motion, revolutions per day.
    pub mean_motion_rev_per_day: f64,
    /// Right ascension of ascending node (RAAN), degrees.
    pub right_ascension_deg: f64,
    /// Catalog (NORAD) number for this object. Used only for diagnostic
    /// reporting inside SGP4 - propagation results do not depend on it.
    /// Pass `0` if unknown.
    pub catalog_number: u32,
}

// ── Satellite ────────────────────────────────────────────────────────

/// A parsed TLE ready for propagation.
///
/// Holds the raw TLE lines plus the initialized SGP4 satellite record. The
/// TLE is parsed and `sgp4init` is run exactly once during `from_tle`, so
/// subsequent `propagate` calls just invoke the propagation kernel directly:
/// fast, and crucially, with no precision loss from JD round-tripping.
#[derive(Clone)]
pub struct Satellite {
    line1: String,
    line2: String,
    /// Source elements used to initialize the cached SGP4 record. Kept so
    /// element-built satellites can serialize without inventing TLE text.
    elements: ElementSet,
    opsmode: OpsMode,
    /// Pre-initialized satellite record. Boxed to keep `Satellite` small on
    /// the stack - `ElsetRec` has ~150 fields.
    satrec: Box<vallado::ElsetRec>,
}

impl std::fmt::Debug for Satellite {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Satellite")
            .field("line1", &self.line1)
            .field("line2", &self.line2)
            .field("elements", &self.elements)
            .field("opsmode", &self.opsmode)
            .finish_non_exhaustive()
    }
}

impl Satellite {
    /// Parse a two-line element set using the default `Improved` opsmode.
    ///
    /// Lines should be the standard 69-character TLE format. Leading and
    /// trailing whitespace is trimmed before length validation. Runs the full
    /// SGP4 initialization (`sgp4init`) once and caches the resulting state
    /// so propagation calls are pure step kernels.
    pub fn from_tle(line1: &str, line2: &str) -> Result<Self, Error> {
        Self::from_tle_with_opsmode(line1, line2, OpsMode::Improved)
    }

    /// Parse a two-line element set with an explicit `OpsMode`.
    ///
    /// Use `OpsMode::Afspc` to reproduce results from operational AFSPC
    /// systems or older crates that ran in AFSPC compatibility mode.
    ///
    /// The TLE flows through the canonical element-set IR: it is parsed by the
    /// forgiving [`crate::astro::tle`] grammar into [`crate::astro::tle::TleElements`],
    /// converted to an [`ElementSet`], and initialized through the single
    /// [`Satellite::from_elements`] path - the same path OMM and any other input
    /// format use. There is no separate TLE-direct initialization. The parse is
    /// lenient on cosmetics (trailing content past column 69, leading-dot and
    /// assumed-decimal field forms, an advisory checksum) but still rejects
    /// genuinely corrupt input (non-ASCII, wrong line structure, mismatched
    /// satellite numbers).
    pub fn from_tle_with_opsmode(
        line1: &str,
        line2: &str,
        opsmode: OpsMode,
    ) -> Result<Self, Error> {
        let l1 = line1.trim();
        let l2 = line2.trim();

        let parsed = tle::parse(l1, l2).map_err(|e| Error::InvalidTle(e.to_string()))?;
        let elements = parsed
            .elements
            .to_element_set()
            .map_err(map_tle_bridge_error)?;
        let satrec = init_satrec_from_elements(&elements, opsmode)?;

        Ok(Satellite {
            line1: l1.to_string(),
            line2: l2.to_string(),
            elements,
            opsmode,
            satrec: Box::new(satrec),
        })
    }

    /// Parse a satellite from a TLE block that may carry a leading name line.
    ///
    /// CelesTrak and Space-Track serve TLEs in the common "3-line" (TLE/3LE)
    /// form: an object-name line followed by the two element lines. This accepts
    /// that block, strips an optional leading name line, and parses the first
    /// `1 `/`2 ` element-line pair. A plain 2-line block (no name line) also
    /// parses. Uses the default `Improved` opsmode.
    pub fn from_3line(block: &str) -> Result<Self, Error> {
        Self::from_3line_with_opsmode(block, OpsMode::Improved)
    }

    /// Parse a name-line-prefixed TLE block with an explicit `OpsMode`. See
    /// [`Satellite::from_3line`].
    pub fn from_3line_with_opsmode(block: &str, opsmode: OpsMode) -> Result<Self, Error> {
        let mut l1 = None;
        let mut l2 = None;
        for line in block.lines() {
            let line = line.trim();
            if l1.is_none() && line.starts_with("1 ") {
                l1 = Some(line.to_string());
            } else if l2.is_none() && line.starts_with("2 ") {
                l2 = Some(line.to_string());
            }
        }
        let l1 = l1.ok_or_else(|| Error::InvalidTle("no line 1 in TLE block".into()))?;
        let l2 = l2.ok_or_else(|| Error::InvalidTle("no line 2 in TLE block".into()))?;
        Self::from_tle_with_opsmode(&l1, &l2, opsmode)
    }

    /// Construct a `Satellite` from pre-parsed Vallado SGP4 elements using
    /// the default `Improved` opsmode.
    ///
    /// Useful when TLE data has already been parsed externally (OMM, JSON
    /// catalog, another system) and you only need the element values to flow
    /// into SGP4 initialization. Equivalent to `from_tle` for propagation
    /// behavior, but bypasses the TLE string parser.
    ///
    /// Note: a `Satellite` constructed this way has empty `line1()` and
    /// `line2()` accessors since there is no source TLE to return.
    pub fn from_elements(elements: &ElementSet) -> Result<Self, Error> {
        Self::from_elements_with_opsmode(elements, OpsMode::Improved)
    }

    /// Construct a `Satellite` from pre-parsed elements with an explicit
    /// `OpsMode`. See `from_tle_with_opsmode` for the rationale.
    pub fn from_elements_with_opsmode(
        elements: &ElementSet,
        opsmode: OpsMode,
    ) -> Result<Self, Error> {
        let satrec = init_satrec_from_elements(elements, opsmode)?;
        Ok(Satellite {
            line1: String::new(),
            line2: String::new(),
            elements: elements.clone(),
            opsmode,
            satrec: Box::new(satrec),
        })
    }

    /// Propagate to a time given as minutes since the TLE epoch.
    ///
    /// Calls the SGP4 step kernel directly with the supplied tsince - no JD
    /// round-trip, no precision loss.
    pub fn propagate(&self, t: MinutesSinceEpoch) -> Result<Prediction, Error> {
        // Clone the satrec so propagation doesn't mutate the cached state
        // (sgp4 writes back into the satrec - error code, atime, etc.).
        propagate_satrec((*self.satrec).clone(), t)
    }

    /// Propagate to a Julian date, split as `(whole, fraction)`.
    ///
    /// Computes the tsince from the cached epoch via the same subtraction
    /// the C++ wrapper uses:
    ///
    /// ```text
    /// tsince = (jd - jdsatepoch) * 1440 + (fr - jdsatepochF) * 1440
    /// ```
    pub fn propagate_jd(&self, jd: JulianDate) -> Result<Prediction, Error> {
        validate::finite(jd.0, "julian_date.whole").map_err(map_input_error)?;
        validate::finite_in_range_exclusive_upper(jd.1, 0.0, 1.0, "julian_date.fraction")
            .map_err(map_input_error)?;
        let tsince =
            (jd.0 - self.satrec.jdsatepoch) * 1440.0 + (jd.1 - self.satrec.jdsatepochF) * 1440.0;
        validate::finite(tsince, "minutes_since_epoch").map_err(map_input_error)?;
        self.propagate(MinutesSinceEpoch(tsince))
    }

    pub(crate) fn mean_motion_rad_per_min(&self) -> f64 {
        self.satrec.no_kozai
    }

    pub(crate) fn eccentricity(&self) -> f64 {
        self.satrec.ecco
    }

    /// Raw TLE line 1. Returns an empty string when this `Satellite` was
    /// constructed via `from_elements` (no source TLE).
    pub fn line1(&self) -> &str {
        &self.line1
    }

    /// Raw TLE line 2. Returns an empty string when this `Satellite` was
    /// constructed via `from_elements` (no source TLE).
    pub fn line2(&self) -> &str {
        &self.line2
    }

    /// Cached TLE epoch as a split Julian date `(jdsatepoch, jdsatepochF)`.
    ///
    /// Useful for computing time offsets between two TLEs without losing
    /// precision through floating-point round-trips.
    pub fn epoch_jd(&self) -> JulianDate {
        JulianDate(self.satrec.jdsatepoch, self.satrec.jdsatepochF)
    }

    #[cfg(feature = "serde")]
    fn has_source_tle(&self) -> bool {
        !self.line1.is_empty() && !self.line2.is_empty()
    }
}

/// One-shot SGP4 propagation from pre-parsed elements using the default
/// `Improved` opsmode.
///
/// Equivalent to `Satellite::from_elements(&e)?.propagate(t)` but without
/// allocating a cached `Satellite`. Suitable for one-call use cases where
/// the satellite record is not reused (e.g. NIF entry points that get
/// elements + a single time per call).
pub fn propagate_elements(
    elements: &ElementSet,
    t: MinutesSinceEpoch,
) -> Result<Prediction, Error> {
    propagate_elements_with_opsmode(elements, t, OpsMode::Improved)
}

/// One-shot SGP4 propagation with an explicit `OpsMode`.
pub fn propagate_elements_with_opsmode(
    elements: &ElementSet,
    t: MinutesSinceEpoch,
    opsmode: OpsMode,
) -> Result<Prediction, Error> {
    let satrec = init_satrec_from_elements(elements, opsmode)?;
    propagate_satrec(satrec, t)
}

#[cfg(feature = "serde")]
impl serde::Serialize for Satellite {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = s.serialize_struct("Satellite", 2)?;
        if self.has_source_tle() {
            st.serialize_field("line1", &self.line1)?;
            st.serialize_field("line2", &self.line2)?;
        } else {
            st.serialize_field("elements", &self.elements)?;
            st.serialize_field("opsmode", &self.opsmode)?;
        }
        st.end()
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Satellite {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        #[derive(serde::Deserialize)]
        struct Wire {
            line1: Option<String>,
            line2: Option<String>,
            elements: Option<ElementSet>,
            opsmode: Option<OpsMode>,
        }
        let w = Wire::deserialize(d)?;
        let opsmode = w.opsmode.unwrap_or_default();
        let has_tle_line = w
            .line1
            .as_deref()
            .is_some_and(|line| !line.trim().is_empty())
            || w.line2
                .as_deref()
                .is_some_and(|line| !line.trim().is_empty());
        if let Some(elements) = w.elements {
            if has_tle_line {
                Err(serde::de::Error::custom(
                    "ambiguous Satellite wire format: use either TLE lines or elements",
                ))
            } else {
                Satellite::from_elements_with_opsmode(&elements, opsmode)
                    .map_err(serde::de::Error::custom)
            }
        } else if let (Some(line1), Some(line2)) = (w.line1, w.line2) {
            if line1.trim().is_empty() || line2.trim().is_empty() {
                Err(serde::de::Error::custom(
                    "Satellite wire format requires non-empty line1/line2 or elements",
                ))
            } else {
                Satellite::from_tle_with_opsmode(&line1, &line2, opsmode)
                    .map_err(serde::de::Error::custom)
            }
        } else {
            Err(serde::de::Error::custom(
                "Satellite wire format requires non-empty line1/line2 or elements",
            ))
        }
    }
}

// ── Internal helpers ─────────────────────────────────────────────────

fn propagate_satrec(
    mut satrec: vallado::ElsetRec,
    t: MinutesSinceEpoch,
) -> Result<Prediction, Error> {
    validate::finite(t.0, "minutes_since_epoch").map_err(map_input_error)?;
    if t.0.abs() > MAX_MINUTES_SINCE_EPOCH {
        return Err(invalid_domain("minutes_since_epoch"));
    }

    let mut r = [0.0_f64; 3];
    let mut v = [0.0_f64; 3];
    let ok = vallado::sgp4(&mut satrec, t.0, &mut r, &mut v);
    if !ok || satrec.error != 0 {
        return Err(Error::Sgp4 { code: satrec.error });
    }
    validate_prediction(r, v)?;
    Ok(Prediction {
        position: r,
        velocity: v,
    })
}

fn validate_prediction(position: [f64; 3], velocity: [f64; 3]) -> Result<(), Error> {
    validate::finite_vec3(position, "position_km").map_err(map_output_error)?;
    validate::finite_vec3(velocity, "velocity_km_s").map_err(map_output_error)?;
    Ok(())
}

/// Run `sgp4init` from a pre-parsed element set, returning the initialized
/// satellite record. Performs the same angle/units conversion as
/// `vallado::twoline2rv_propagate` so a `Satellite` constructed from
/// elements is equivalent to one constructed from the matching TLE.
fn init_satrec_from_elements(
    elements: &ElementSet,
    opsmode: OpsMode,
) -> Result<vallado::ElsetRec, Error> {
    validate_elements(elements)?;

    let deg2rad = std::f64::consts::PI / 180.0;
    let xpdotp = 1440.0 / (2.0 * std::f64::consts::PI);

    let inclo = elements.inclination_deg * deg2rad;
    let nodeo = elements.right_ascension_deg * deg2rad;
    let argpo = elements.argument_of_perigee_deg * deg2rad;
    let mo = elements.mean_anomaly_deg * deg2rad;
    let no_kozai = elements.mean_motion_rev_per_day / xpdotp;
    // ndot rev/day² → rad/min², nddot rev/day³ → rad/min³.
    // Matches the conversion in `vallado::twoline2rv_propagate`.
    let ndot = elements.mean_motion_dot / (xpdotp * 1440.0);
    let nddot = elements.mean_motion_double_dot / (xpdotp * 1440.0 * 1440.0);

    let JulianDate(jd, jdfrac) = elements.epoch;
    let epoch_sgp4 = jd + jdfrac - 2433281.5;

    let satnum_str = format!("{:>5}", elements.catalog_number);

    let mut satrec = vallado::ElsetRec {
        jdsatepoch: jd,
        jdsatepochF: jdfrac,
        ..vallado::ElsetRec::default()
    };

    vallado::sgp4init(
        vallado::GravConstType::Wgs72,
        opsmode.as_char(),
        &satnum_str,
        epoch_sgp4,
        elements.bstar,
        ndot,
        nddot,
        elements.eccentricity,
        argpo,
        inclo,
        mo,
        no_kozai,
        nodeo,
        &mut satrec,
    );

    // sgp4init may have rewritten jdsatepoch via initl - restore the split.
    satrec.jdsatepoch = jd;
    satrec.jdsatepochF = jdfrac;

    Ok(satrec)
}

fn validate_elements(elements: &ElementSet) -> Result<(), Error> {
    if elements.catalog_number > MAX_VALLADO_SATNUM {
        return Err(invalid_domain("element.catalog_number"));
    }
    validate_epoch(elements.epoch)?;
    validate::finite(elements.bstar, "element.bstar").map_err(map_input_error)?;
    validate::finite(elements.mean_motion_dot, "element.mean_motion_dot")
        .map_err(map_input_error)?;
    validate::finite(
        elements.mean_motion_double_dot,
        "element.mean_motion_double_dot",
    )
    .map_err(map_input_error)?;
    validate::finite_in_range_exclusive_upper(
        elements.eccentricity,
        0.0,
        1.0,
        "element.eccentricity",
    )
    .map_err(map_input_error)?;
    validate::finite(
        elements.argument_of_perigee_deg,
        "element.argument_of_perigee_deg",
    )
    .map_err(map_input_error)?;
    validate::finite(elements.inclination_deg, "element.inclination_deg")
        .map_err(map_input_error)?;
    validate::finite(elements.mean_anomaly_deg, "element.mean_anomaly_deg")
        .map_err(map_input_error)?;
    validate::finite_positive(
        elements.mean_motion_rev_per_day,
        "element.mean_motion_rev_per_day",
    )
    .map_err(map_input_error)?;
    validate::finite(elements.right_ascension_deg, "element.right_ascension_deg")
        .map_err(map_input_error)?;

    Ok(())
}

fn validate_epoch(epoch: JulianDate) -> Result<(), Error> {
    validate::finite(epoch.0, "element.epoch.whole").map_err(map_input_error)?;
    validate::finite(epoch.1, "element.epoch.fraction").map_err(map_input_error)?;

    let total = epoch.0 + epoch.1;
    validate::finite(total, "element.epoch").map_err(map_input_error)?;
    if !(0.0..=5_000_000.0).contains(&total) {
        return Err(invalid_domain("element.epoch"));
    }
    Ok(())
}

fn map_input_error(error: FieldError) -> Error {
    Error::InvalidInput {
        field: error.field(),
        kind: Sgp4InputErrorKind::from(&error),
    }
}

fn invalid_domain(field: &'static str) -> Error {
    Error::InvalidInput {
        field,
        kind: Sgp4InputErrorKind::OutOfRange,
    }
}

fn map_tle_bridge_error(error: tle::TleError) -> Error {
    match error {
        tle::TleError::InvalidField { field, reason } => Error::InvalidInput {
            field,
            kind: match reason {
                "not finite" => Sgp4InputErrorKind::NonFinite,
                "not positive" => Sgp4InputErrorKind::NotPositive,
                "negative" => Sgp4InputErrorKind::Negative,
                "out of range" => Sgp4InputErrorKind::OutOfRange,
                _ => Sgp4InputErrorKind::OutOfRange,
            },
        },
        other => Error::InvalidTle(other.to_string()),
    }
}

fn map_output_error(error: FieldError) -> Error {
    Error::NonFiniteOutput {
        field: error.field(),
    }
}

#[cfg(test)]
mod tests {
    use super::{
        propagate_elements, ElementSet, Error, JulianDate, MinutesSinceEpoch, Satellite,
        Sgp4InputErrorKind, MAX_MINUTES_SINCE_EPOCH,
    };

    /// A TLE carrying a multibyte character inside a fixed-width column must
    /// return a typed [`Error::InvalidTle`] rather than panicking. The field
    /// extractor slices by byte column (`l1[18..20]`, ...); a non-ASCII byte
    /// inside such a window used to panic on a non-char-boundary slice. The
    /// ASCII guard now rejects the line with a typed error; valid input parses.
    #[test]
    fn non_ascii_tle_returns_invalid_tle_not_panic() {
        let line1 = "1 25544U 98067A   18184.80969102  .00001614  00000-0  31745-4 0  9993";
        let line2 = "2 25544  51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106";
        assert!(
            Satellite::from_tle(line1, line2).is_ok(),
            "clean ASCII TLE must still parse"
        );

        // Drop a 3-byte character into the epoch-year column (bytes 18..20),
        // straddling byte 20 so the pre-guard `l1[18..20]` slice would panic.
        let mut bad1 = String::from(&line1[..18]);
        bad1.push('\u{20ac}');
        bad1.push_str(&line1[19..]);
        assert!(
            !bad1.is_char_boundary(20),
            "corruption must straddle byte 20"
        );

        let err = Satellite::from_tle(&bad1, line2).expect_err("non-ASCII TLE must not parse");
        assert!(
            matches!(err, Error::InvalidTle(_)),
            "expected a typed InvalidTle error, got: {err:?}"
        );
    }

    // ── Forgiving-inbound leniency (now that `from_tle` flows through the
    // canonical IR via the lenient `tle` parser) ───────────────────────────

    const ISS_L1: &str = "1 25544U 98067A   18184.80969102  .00001614  00000-0  31745-4 0  9993";
    const ISS_L2: &str = "2 25544  51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106";

    fn iss_elements() -> ElementSet {
        crate::astro::tle::parse(ISS_L1, ISS_L2)
            .unwrap()
            .elements
            .to_element_set()
            .expect("valid TLE bridge")
    }

    fn assert_invalid_input<T>(
        result: Result<T, Error>,
        field: &'static str,
        kind: Sgp4InputErrorKind,
    ) {
        match result {
            Err(Error::InvalidInput {
                field: actual_field,
                kind: actual_kind,
            }) => {
                assert_eq!(actual_field, field);
                assert_eq!(actual_kind, kind);
            }
            Err(err) => panic!("expected InvalidInput({field}, {kind}), got {err:?}"),
            Ok(_) => panic!("expected InvalidInput({field}, {kind}), got Ok"),
        }
    }

    /// Assert two satellites are bit-identical (same cached epoch and same
    /// propagated state at several offsets).
    fn assert_same(a: &Satellite, b: &Satellite) {
        let (ea, eb) = (a.epoch_jd(), b.epoch_jd());
        assert_eq!(
            (ea.0.to_bits(), ea.1.to_bits()),
            (eb.0.to_bits(), eb.1.to_bits()),
            "epoch JD differs"
        );
        for &t in &[0.0, 100.0, 1440.0] {
            let pa = a.propagate(MinutesSinceEpoch(t)).unwrap();
            let pb = b.propagate(MinutesSinceEpoch(t)).unwrap();
            for axis in 0..3 {
                assert_eq!(
                    pa.position[axis].to_bits(),
                    pb.position[axis].to_bits(),
                    "position[{axis}] differs at t={t}"
                );
                assert_eq!(
                    pa.velocity[axis].to_bits(),
                    pb.velocity[axis].to_bits(),
                    "velocity[{axis}] differs at t={t}"
                );
            }
        }
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_round_trips_tle_satellites() {
        let sat = Satellite::from_tle(ISS_L1, ISS_L2).unwrap();
        let encoded = serde_json::to_string(&sat).unwrap();
        assert!(encoded.contains("\"line1\""));
        assert!(encoded.contains("\"line2\""));
        assert!(!encoded.contains("\"elements\""));

        let decoded: Satellite = serde_json::from_str(&encoded).unwrap();
        assert_eq!(decoded.line1(), ISS_L1);
        assert_eq!(decoded.line2(), ISS_L2);
        assert_same(&sat, &decoded);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_round_trips_element_built_satellites() {
        let elements = iss_elements();
        let sat = Satellite::from_elements(&elements).unwrap();
        let encoded = serde_json::to_string(&sat).unwrap();
        assert!(encoded.contains("\"elements\""));
        assert!(encoded.contains("\"opsmode\""));
        assert!(!encoded.contains("\"line1\""));
        assert!(!encoded.contains("\"line2\""));

        let decoded: Satellite = serde_json::from_str(&encoded).unwrap();
        assert!(decoded.line1().is_empty());
        assert!(decoded.line2().is_empty());
        assert_same(&sat, &decoded);
    }

    #[test]
    fn from_elements_rejects_non_finite_fields_before_sgp4init() {
        let mut elements = iss_elements();
        elements.bstar = f64::NAN;

        assert_invalid_input(
            Satellite::from_elements(&elements),
            "element.bstar",
            Sgp4InputErrorKind::NonFinite,
        );
    }

    #[test]
    fn from_elements_rejects_sgp4_domain_before_sgp4init() {
        let mut elements = iss_elements();
        elements.mean_motion_rev_per_day = 0.0;
        assert_invalid_input(
            Satellite::from_elements(&elements),
            "element.mean_motion_rev_per_day",
            Sgp4InputErrorKind::NotPositive,
        );

        let mut elements = iss_elements();
        elements.eccentricity = -0.1;
        assert_invalid_input(
            Satellite::from_elements(&elements),
            "element.eccentricity",
            Sgp4InputErrorKind::OutOfRange,
        );

        let mut elements = iss_elements();
        elements.eccentricity = 1.0;
        assert_invalid_input(
            Satellite::from_elements(&elements),
            "element.eccentricity",
            Sgp4InputErrorKind::OutOfRange,
        );

        let mut elements = iss_elements();
        elements.catalog_number = 100_000;
        assert_invalid_input(
            Satellite::from_elements(&elements),
            "element.catalog_number",
            Sgp4InputErrorKind::OutOfRange,
        );
    }

    #[test]
    fn from_elements_rejects_invalid_epoch() {
        let mut elements = iss_elements();
        elements.epoch = JulianDate(f64::NAN, 0.0);
        assert_invalid_input(
            Satellite::from_elements(&elements),
            "element.epoch.whole",
            Sgp4InputErrorKind::NonFinite,
        );

        let mut elements = iss_elements();
        elements.epoch = JulianDate(9_000_000.0, 0.0);
        assert_invalid_input(
            Satellite::from_elements(&elements),
            "element.epoch",
            Sgp4InputErrorKind::OutOfRange,
        );
    }

    #[test]
    fn from_elements_accepts_full_julian_epoch() {
        let mut elements = iss_elements();
        elements.epoch = super::sgp4_julian_date_from_calendar(2057, 1, 1, 0, 0, 0.0);
        Satellite::from_elements(&elements).expect("full 2057 epoch is valid");
    }

    #[test]
    fn from_tle_accepts_epoch_after_parser_conversion_to_full_jd() {
        let mut line1 = ISS_L1.to_string();
        line1.replace_range(18..32, "19366.00000000");

        Satellite::from_tle(&line1, ISS_L2).expect("TLE epoch is converted to full JD");
    }

    #[test]
    fn propagation_rejects_non_finite_time_inputs() {
        let sat = Satellite::from_tle(ISS_L1, ISS_L2).unwrap();
        assert_invalid_input(
            sat.propagate(MinutesSinceEpoch(f64::NAN)),
            "minutes_since_epoch",
            Sgp4InputErrorKind::NonFinite,
        );
        assert_invalid_input(
            sat.propagate_jd(JulianDate(f64::INFINITY, 0.0)),
            "julian_date.whole",
            Sgp4InputErrorKind::NonFinite,
        );

        let elements = iss_elements();
        assert_invalid_input(
            propagate_elements(&elements, MinutesSinceEpoch(f64::INFINITY)),
            "minutes_since_epoch",
            Sgp4InputErrorKind::NonFinite,
        );
    }

    #[test]
    fn propagation_rejects_out_of_domain_time_inputs() {
        let sat = Satellite::from_tle(ISS_L1, ISS_L2).unwrap();
        assert_invalid_input(
            sat.propagate(MinutesSinceEpoch(MAX_MINUTES_SINCE_EPOCH.next_up())),
            "minutes_since_epoch",
            Sgp4InputErrorKind::OutOfRange,
        );
        assert_invalid_input(
            sat.propagate_jd(JulianDate(2_458_304.0, 1.0)),
            "julian_date.fraction",
            Sgp4InputErrorKind::OutOfRange,
        );
    }

    #[test]
    fn lenient_trailing_whitespace_and_content_past_col_69() {
        let clean = Satellite::from_tle(ISS_L1, ISS_L2).unwrap();

        // Trailing whitespace on both lines.
        let pad = Satellite::from_tle(&format!("{ISS_L1}   "), &format!("{ISS_L2}\t ")).unwrap();
        assert_same(&clean, &pad);

        // Extra content past the 69-column record (CelesTrak/Space-Track blobs
        // sometimes carry it); it is trimmed before parsing.
        let extra =
            Satellite::from_tle(&format!("{ISS_L1} EXTRA-JUNK"), &format!("{ISS_L2} 999999"))
                .unwrap();
        assert_same(&clean, &extra);
    }

    #[test]
    fn lenient_leading_dot_and_assumed_decimal_fields() {
        // The ISS TLE already carries a leading-dot first derivative
        // (` .00001614`), an assumed-decimal B\* (`31745-4`), and the implicit
        // `0.` eccentricity (`0003435`). A successful parse + finite LEO state
        // proves those normalizations run through the public entry point.
        let sat = Satellite::from_tle(ISS_L1, ISS_L2).unwrap();
        let p = sat.propagate(MinutesSinceEpoch(0.0)).unwrap();
        let r = (p.position[0].powi(2) + p.position[1].powi(2) + p.position[2].powi(2)).sqrt();
        assert!(
            (6500.0..=7200.0).contains(&r),
            "ISS radius {r} km outside LEO"
        );
    }

    #[test]
    fn lenient_missing_optional_bookkeeping_fields() {
        // Blank element-set number, ephemeris type, and revolution number are
        // cosmetic for propagation and must default rather than reject. Build
        // such a TLE by blanking those columns (cols 63, 65-68 on line 1 and
        // 64-68 on line 2) while leaving the orbital fields intact.
        let l1: String = ISS_L1
            .char_indices()
            .map(|(i, c)| {
                if i == 62 || (64..=67).contains(&i) {
                    ' '
                } else {
                    c
                }
            })
            .collect();
        let l2: String = ISS_L2
            .char_indices()
            .map(|(i, c)| if (63..=67).contains(&i) { ' ' } else { c })
            .collect();
        // Same orbital elements as the clean TLE → bit-identical propagation
        // (the blanked fields do not feed SGP4).
        let clean = Satellite::from_tle(ISS_L1, ISS_L2).unwrap();
        let blanked = Satellite::from_tle(&l1, &l2).unwrap();
        assert_same(&clean, &blanked);
    }

    #[test]
    fn three_line_form_strips_name_line() {
        let clean = Satellite::from_tle(ISS_L1, ISS_L2).unwrap();

        let block = format!("ISS (ZARYA)\n{ISS_L1}\n{ISS_L2}\n");
        let three = Satellite::from_3line(&block).unwrap();
        assert_same(&clean, &three);

        // A plain two-line block (no name line) also parses.
        let two = Satellite::from_3line(&format!("{ISS_L1}\n{ISS_L2}")).unwrap();
        assert_same(&clean, &two);
    }

    #[test]
    fn three_line_form_rejects_block_without_element_lines() {
        assert!(Satellite::from_3line("just a name\nand some text").is_err());
        assert!(Satellite::from_3line("").is_err());
    }

    #[test]
    fn rejects_genuine_corruption() {
        // Empty.
        assert!(Satellite::from_tle("", "").is_err());
        // Non-TLE text.
        assert!(Satellite::from_tle("hello world", "goodbye world").is_err());
        // Swapped lines (line 2 first).
        assert!(Satellite::from_tle(ISS_L2, ISS_L1).is_err());
        // Mismatched satellite numbers between line 1 and line 2.
        let l2_wrong = "2 25545  51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106";
        assert!(matches!(
            Satellite::from_tle(ISS_L1, l2_wrong),
            Err(Error::InvalidTle(_))
        ));
    }
}