lox-analysis 0.1.0-alpha.13

Mission analysis tools for the Lox ecosystem
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
// SPDX-FileCopyrightText: 2025 Helge Eichhorn <git@helgeeichhorn.de>
//
// SPDX-License-Identifier: MPL-2.0

use std::collections::HashMap;
use std::fmt;

use lox_bodies::{DynOrigin, Origin};
use lox_core::units::AngularRate;

#[cfg(feature = "imaging")]
use crate::imaging::OpticalPayload;
#[cfg(feature = "imaging")]
use crate::imaging::SarPayload;
#[cfg(feature = "imaging")]
use crate::imaging::analysis::PayloadAccessor;
use lox_frames::rotations::TryRotation;
use lox_frames::{DynFrame, ReferenceFrame};
use lox_time::Time;
use lox_time::intervals::TimeInterval;
use lox_time::time_scales::{DynTimeScale, Tai};
use rayon::prelude::*;

#[cfg(feature = "comms")]
use lox_comms::system::CommunicationSystem;

use crate::visibility::ElevationMask;
use lox_orbits::constellations::{ConstellationPropagator, DynConstellation};
use lox_orbits::ground::DynGroundLocation;
use lox_orbits::orbits::{Ensemble, KeplerianOrbit};
use lox_orbits::propagators::j2::DynJ2Propagator;
use lox_orbits::propagators::j4::DynJ4Propagator;
use lox_orbits::propagators::numerical::DynNumericalPropagator;
use lox_orbits::propagators::semi_analytical::DynVallado;
use lox_orbits::propagators::{OrbitSource, PropagateError};

/// Unique identifier for a ground station or spacecraft.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AssetId(String);

impl AssetId {
    /// Creates a new asset identifier.
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Returns the identifier as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for AssetId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Unique identifier for a satellite constellation.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ConstellationId(String);

impl ConstellationId {
    /// Creates a new constellation identifier.
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Returns the identifier as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ConstellationId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Unique identifier for a ground station network.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NetworkId(String);

impl NetworkId {
    /// Creates a new network identifier.
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Returns the identifier as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for NetworkId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A ground station with location, elevation mask, and optional network membership.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GroundStation {
    id: AssetId,
    location: DynGroundLocation,
    mask: ElevationMask,
    body_fixed_frame: DynFrame,
    network: Option<NetworkId>,
    #[cfg(feature = "comms")]
    communication_systems: Vec<CommunicationSystem>,
}

impl GroundStation {
    /// Creates a new ground station with the given location and elevation mask.
    pub fn new(id: impl Into<String>, location: DynGroundLocation, mask: ElevationMask) -> Self {
        let body_fixed_frame = DynFrame::Iau(location.origin());
        Self {
            id: AssetId::new(id),
            location,
            mask,
            body_fixed_frame,
            network: None,
            #[cfg(feature = "comms")]
            communication_systems: Vec::new(),
        }
    }

    /// Overrides the body-fixed frame (defaults to IAU frame of the location's origin).
    pub fn with_body_fixed_frame(mut self, frame: impl Into<DynFrame>) -> Self {
        self.body_fixed_frame = frame.into();
        self
    }

    /// Assigns this ground station to a network.
    pub fn with_network_id(mut self, id: impl Into<String>) -> Self {
        self.network = Some(NetworkId(id.into()));
        self
    }

    /// Adds a communication system to this ground station.
    #[cfg(feature = "comms")]
    pub fn with_communication_system(mut self, system: CommunicationSystem) -> Self {
        self.communication_systems.push(system);
        self
    }

    /// Returns the asset identifier.
    pub fn id(&self) -> &AssetId {
        &self.id
    }

    /// Returns the ground location.
    pub fn location(&self) -> &DynGroundLocation {
        &self.location
    }

    /// Returns the elevation mask.
    pub fn mask(&self) -> &ElevationMask {
        &self.mask
    }

    /// Returns the network identifier, if assigned.
    pub fn network_id(&self) -> Option<&NetworkId> {
        self.network.as_ref()
    }

    /// Returns the body-fixed reference frame.
    pub fn body_fixed_frame(&self) -> DynFrame {
        self.body_fixed_frame
    }

    /// Returns the communication systems attached to this ground station.
    #[cfg(feature = "comms")]
    pub fn communication_systems(&self) -> &[CommunicationSystem] {
        &self.communication_systems
    }
}

/// A spacecraft with an orbit source, optional slew rate, and constellation membership.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Spacecraft {
    id: AssetId,
    orbit: OrbitSource,
    max_slew_rate: Option<AngularRate>,
    constellation: Option<ConstellationId>,
    #[cfg(feature = "imaging")]
    optical_payload: Option<OpticalPayload>,
    #[cfg(feature = "imaging")]
    sar_payload: Option<SarPayload>,
    #[cfg(feature = "comms")]
    communication_systems: Vec<CommunicationSystem>,
}

impl Spacecraft {
    /// Creates a new spacecraft with the given orbit source.
    pub fn new(id: impl Into<String>, orbit: OrbitSource) -> Self {
        Self {
            id: AssetId::new(id),
            orbit,
            max_slew_rate: None,
            constellation: None,
            #[cfg(feature = "imaging")]
            optical_payload: None,
            #[cfg(feature = "imaging")]
            sar_payload: None,
            #[cfg(feature = "comms")]
            communication_systems: Vec::new(),
        }
    }

    /// Sets the maximum slew rate for the spacecraft.
    pub fn with_max_slew_rate(mut self, rate: AngularRate) -> Self {
        self.max_slew_rate = Some(rate);
        self
    }

    /// Assigns this spacecraft to a constellation.
    pub fn with_constellation_id(mut self, id: impl Into<String>) -> Self {
        self.constellation = Some(ConstellationId(id.into()));
        self
    }

    /// Sets the optical payload for this spacecraft.
    #[cfg(feature = "imaging")]
    pub fn with_optical_payload(mut self, payload: OpticalPayload) -> Self {
        self.optical_payload = Some(payload);
        self
    }

    /// Sets the SAR payload for this spacecraft.
    #[cfg(feature = "imaging")]
    pub fn with_sar_payload(mut self, payload: SarPayload) -> Self {
        self.sar_payload = Some(payload);
        self
    }

    /// Adds a communication system to this spacecraft.
    #[cfg(feature = "comms")]
    pub fn with_communication_system(mut self, system: CommunicationSystem) -> Self {
        self.communication_systems.push(system);
        self
    }

    /// Returns the asset identifier.
    pub fn id(&self) -> &AssetId {
        &self.id
    }

    /// Returns the orbit source.
    pub fn orbit(&self) -> &OrbitSource {
        &self.orbit
    }

    /// Returns the constellation identifier, if assigned.
    pub fn constellation_id(&self) -> Option<&ConstellationId> {
        self.constellation.as_ref()
    }

    /// Returns the maximum slew rate, if set.
    pub fn max_slew_rate(&self) -> Option<AngularRate> {
        self.max_slew_rate
    }

    /// Returns the optical payload, if set.
    #[cfg(feature = "imaging")]
    pub fn optical_payload(&self) -> Option<OpticalPayload> {
        self.optical_payload
    }

    /// Returns the SAR payload, if set.
    #[cfg(feature = "imaging")]
    pub fn sar_payload(&self) -> Option<SarPayload> {
        self.sar_payload
    }

    /// Returns the communication systems attached to this spacecraft.
    #[cfg(feature = "comms")]
    pub fn communication_systems(&self) -> &[CommunicationSystem] {
        &self.communication_systems
    }
}

/// A scenario declaring the analysis origin, reference frame, time interval,
/// and the assets (ground stations and spacecraft) involved.
///
/// The type parameters `O` and `R` specify the "native" origin body and
/// reference frame. For dynamic dispatch (e.g. via Python), use `DynScenario`.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Scenario<O: Origin, R: ReferenceFrame> {
    interval: TimeInterval<Tai>,
    origin: O,
    frame: R,
    ground_stations: Vec<GroundStation>,
    spacecraft: Vec<Spacecraft>,
    constellations: Vec<DynConstellation>,
}

/// Dynamic scenario — preserves backward compatibility and serves the Python API.
pub type DynScenario = Scenario<DynOrigin, DynFrame>;

/// Errors from converting a constellation into individual [`Spacecraft`].
#[derive(Debug, thiserror::Error)]
pub enum ConstellationConvertError {
    /// Failed to create a Keplerian orbit from satellite elements.
    #[error("failed to create Keplerian orbit: {0}")]
    KeplerianOrbit(String),
    /// Failed to convert Keplerian orbit to Cartesian state.
    #[error("failed to convert to Cartesian orbit: {0}")]
    CartesianConversion(String),
    /// Failed to create an orbit propagator.
    #[error("failed to create propagator: {0}")]
    Propagator(String),
}

/// Errors from propagating spacecraft trajectories within a scenario.
#[derive(Debug, thiserror::Error)]
pub enum ScenarioPropagateError {
    /// Orbit propagation failed for the named spacecraft.
    #[error("propagation failed for spacecraft \"{0}\": {1}")]
    Propagate(AssetId, PropagateError),
    /// Frame transformation failed for the named spacecraft.
    #[error("frame transformation failed for spacecraft \"{0}\": {1}")]
    FrameTransformation(AssetId, String),
}

impl<O: Origin + Copy + Send + Sync, R: ReferenceFrame + Copy + Send + Sync> Scenario<O, R> {
    /// Creates a new scenario from start/end times, origin, and frame.
    pub fn new(start_time: Time<Tai>, end_time: Time<Tai>, origin: O, frame: R) -> Self {
        let interval = TimeInterval::new(start_time, end_time);
        Self::with_interval(interval, origin, frame)
    }

    /// Creates a new scenario from a time interval, origin, and frame.
    pub fn with_interval(interval: TimeInterval<Tai>, origin: O, frame: R) -> Self {
        Self {
            interval,
            origin,
            frame,
            ground_stations: Vec::new(),
            spacecraft: Vec::new(),
            constellations: Vec::new(),
        }
    }

    /// Sets the spacecraft for this scenario.
    pub fn with_spacecraft(mut self, spacecraft: &[Spacecraft]) -> Self {
        self.spacecraft = spacecraft.into();
        self
    }

    /// Sets the ground stations for this scenario.
    pub fn with_ground_stations(mut self, ground_stations: &[GroundStation]) -> Self {
        self.ground_stations = ground_stations.into();
        self
    }

    /// Returns the scenario time interval.
    pub fn interval(&self) -> &TimeInterval<Tai> {
        &self.interval
    }

    /// Returns the central body origin.
    pub fn origin(&self) -> O {
        self.origin
    }

    /// Returns the reference frame.
    pub fn frame(&self) -> R {
        self.frame
    }

    /// Add a constellation to the scenario, converting each satellite into a
    /// [`Spacecraft`] using the constellation's selected propagator.
    pub fn with_constellation(
        mut self,
        constellation: DynConstellation,
    ) -> Result<Self, ConstellationConvertError> {
        let epoch = constellation.epoch();
        let origin = constellation.origin();
        let frame = constellation.frame();
        let propagator_kind = constellation.propagator();
        let name = constellation.name().to_string();

        for sat in constellation.satellites() {
            let keplerian_orbit =
                KeplerianOrbit::try_from_keplerian(sat.elements, epoch, origin, frame)
                    .map_err(|e| ConstellationConvertError::KeplerianOrbit(e.to_string()))?;
            let cartesian_orbit = keplerian_orbit
                .try_to_cartesian()
                .map_err(|e| ConstellationConvertError::CartesianConversion(e.to_string()))?;

            let orbit_source = match propagator_kind {
                ConstellationPropagator::Vallado => {
                    let v = DynVallado::try_new(cartesian_orbit)
                        .map_err(|e| ConstellationConvertError::Propagator(e.to_string()))?;
                    OrbitSource::Vallado(v)
                }
                ConstellationPropagator::Numerical => {
                    let n = DynNumericalPropagator::try_new(cartesian_orbit)
                        .map_err(|e| ConstellationConvertError::Propagator(e.to_string()))?;
                    OrbitSource::Numerical(n)
                }
                ConstellationPropagator::J2 => {
                    let p = DynJ2Propagator::try_new(cartesian_orbit)
                        .map_err(|e| ConstellationConvertError::Propagator(e.to_string()))?;
                    OrbitSource::J2(p)
                }
                ConstellationPropagator::J2Osc => {
                    let p = DynJ2Propagator::try_new(cartesian_orbit)
                        .map(|p| p.with_osculating(true))
                        .map_err(|e| ConstellationConvertError::Propagator(e.to_string()))?;
                    OrbitSource::J2(p)
                }
                ConstellationPropagator::J4 => {
                    let p = DynJ4Propagator::try_new(cartesian_orbit)
                        .map_err(|e| ConstellationConvertError::Propagator(e.to_string()))?;
                    OrbitSource::J4(p)
                }
                ConstellationPropagator::J4Osc => {
                    let p = DynJ4Propagator::try_new(cartesian_orbit)
                        .map(|p| p.with_osculating(true))
                        .map_err(|e| ConstellationConvertError::Propagator(e.to_string()))?;
                    OrbitSource::J4(p)
                }
            };

            let sc_id = format!("{} P{} S{}", name, sat.plane + 1, sat.index_in_plane + 1);
            let sc = Spacecraft::new(sc_id, orbit_source).with_constellation_id(&name);
            self.spacecraft.push(sc);
        }

        self.constellations.push(constellation);
        Ok(self)
    }

    /// Returns the constellations in this scenario.
    pub fn constellations(&self) -> &[DynConstellation] {
        &self.constellations
    }

    /// Returns the ground stations in this scenario.
    pub fn ground_stations(&self) -> &[GroundStation] {
        &self.ground_stations
    }

    /// Returns the spacecraft in this scenario.
    pub fn spacecraft(&self) -> &[Spacecraft] {
        &self.spacecraft
    }

    /// Propagate all spacecraft over the scenario interval, transforming
    /// trajectories to the scenario's frame using the provided rotation
    /// `provider`.
    ///
    /// Internally, each spacecraft's `OrbitSource` produces a `DynTrajectory`
    /// which is then rotated into the concrete frame `R` via the mixed
    /// `TryRotation<DynFrame, R, T>` impls, and finally re-tagged to
    /// `Trajectory<Tai, O, R>`.
    pub fn propagate<P>(
        &self,
        provider: &P,
    ) -> Result<Ensemble<AssetId, Tai, O, R>, ScenarioPropagateError>
    where
        R: Into<DynFrame>,
        P: TryRotation<DynFrame, R, DynTimeScale> + Send + Sync,
        P::Error: std::fmt::Display,
    {
        let dyn_interval = TimeInterval::new(
            self.interval.start().into_dyn(),
            self.interval.end().into_dyn(),
        );
        let origin = self.origin;
        let frame = self.frame;
        let entries: Result<HashMap<_, _>, _> = self
            .spacecraft
            .par_iter()
            .map(|sc| {
                let traj = sc
                    .orbit
                    .propagate(dyn_interval)
                    .map_err(|e| ScenarioPropagateError::Propagate(sc.id.clone(), e))?;
                // Rotate DynTrajectory directly into concrete frame R
                // (uses mixed TryRotation<DynFrame, R, DynTimeScale>).
                let rotated = traj.into_frame(frame, provider).map_err(|e| {
                    ScenarioPropagateError::FrameTransformation(sc.id.clone(), e.to_string())
                })?;
                // Re-tag origin and time scale (data unchanged, just type markers).
                let (epoch, _origin, frame, data) = rotated.into_parts();
                let typed = lox_orbits::orbits::Trajectory::from_parts(
                    epoch.with_scale(Tai),
                    origin,
                    frame,
                    data,
                );
                Ok((sc.id.clone(), typed))
            })
            .collect();
        Ok(Ensemble::new(entries?))
    }

    /// Returns a new scenario containing only spacecraft belonging to the given constellations.
    pub fn filter_by_constellations(&self, constellations: &[ConstellationId]) -> Self {
        let spacecraft = self
            .spacecraft
            .clone()
            .into_iter()
            .filter(|s| s.constellation.is_some())
            .filter(|s| constellations.contains(s.constellation.as_ref().unwrap()))
            .collect();
        Scenario {
            spacecraft,
            ..self.clone()
        }
    }

    /// Returns a new scenario containing only ground stations belonging to the given networks.
    pub fn filter_by_networks(&self, networks: &[NetworkId]) -> Self {
        let ground_stations = self
            .ground_stations
            .clone()
            .into_iter()
            .filter(|s| s.network.is_some())
            .filter(|s| networks.contains(s.network.as_ref().unwrap()))
            .collect();
        Scenario {
            ground_stations,
            ..self.clone()
        }
    }
}

#[cfg(feature = "imaging")]
impl PayloadAccessor<OpticalPayload> for Spacecraft {
    fn extract(&self) -> Option<OpticalPayload> {
        self.optical_payload
    }
}

#[cfg(feature = "imaging")]
impl PayloadAccessor<SarPayload> for Spacecraft {
    fn extract(&self) -> Option<SarPayload> {
        self.sar_payload
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use lox_core::coords::LonLatAlt;
    use lox_frames::DynFrame;
    use lox_orbits::ground::GroundLocation;
    use lox_time::deltas::TimeDelta;

    fn dummy_location() -> DynGroundLocation {
        let coords = LonLatAlt::from_degrees(-4.3676, 40.4527, 0.0).unwrap();
        GroundLocation::try_new(coords, DynOrigin::Earth).unwrap()
    }

    fn dummy_mask() -> ElevationMask {
        ElevationMask::with_fixed_elevation(0.0)
    }

    // --- ID types ---

    #[test]
    fn test_asset_id() {
        let id = AssetId::new("station-1");
        assert_eq!(id.as_str(), "station-1");
        assert_eq!(format!("{id}"), "station-1");
        assert_eq!(id, AssetId::new("station-1"));
        assert_ne!(id, AssetId::new("station-2"));
    }

    #[test]
    fn test_constellation_id() {
        let id = ConstellationId::new("oneweb");
        assert_eq!(id.as_str(), "oneweb");
        assert_eq!(format!("{id}"), "oneweb");
    }

    #[test]
    fn test_network_id() {
        let id = NetworkId::new("estrack");
        assert_eq!(id.as_str(), "estrack");
        assert_eq!(format!("{id}"), "estrack");
    }

    // --- GroundStation ---

    #[test]
    fn test_ground_station_new() {
        let loc = dummy_location();
        let mask = dummy_mask();
        let gs = GroundStation::new("gs1", loc, mask);
        assert_eq!(gs.id().as_str(), "gs1");
        assert_eq!(gs.body_fixed_frame(), DynFrame::Iau(DynOrigin::Earth));
    }

    #[test]
    fn test_ground_station_with_body_fixed_frame() {
        let gs = GroundStation::new("gs1", dummy_location(), dummy_mask())
            .with_body_fixed_frame(DynFrame::Itrf);
        assert_eq!(gs.body_fixed_frame(), DynFrame::Itrf);
    }

    #[test]
    fn test_ground_station_network_id_none_by_default() {
        let gs = GroundStation::new("gs1", dummy_location(), dummy_mask());
        assert!(gs.network_id().is_none());
    }

    #[test]
    fn test_ground_station_with_network_id() {
        let gs =
            GroundStation::new("gs1", dummy_location(), dummy_mask()).with_network_id("estrack");
        assert_eq!(gs.network_id(), Some(&NetworkId::new("estrack")));
        // Verify network via filter_by_networks round-trip.
        let start = Time::j2000(Tai);
        let end = start + TimeDelta::from_seconds(86400);
        let scenario = DynScenario::new(start, end, DynOrigin::Earth, DynFrame::Icrf)
            .with_ground_stations(&[gs]);
        let filtered = scenario.filter_by_networks(&[NetworkId::new("estrack")]);
        assert_eq!(filtered.ground_stations().len(), 1);
    }

    #[test]
    fn test_ground_station_location_getter() {
        let loc = dummy_location();
        let gs = GroundStation::new("gs1", loc.clone(), dummy_mask());
        let _ = gs.location(); // verify it compiles and returns
    }

    #[test]
    fn test_ground_station_mask_getter() {
        let mask = ElevationMask::with_fixed_elevation(0.1);
        let gs = GroundStation::new("gs1", dummy_location(), mask.clone());
        assert_eq!(gs.mask().min_elevation(0.0), 0.1);
    }

    // --- Spacecraft ---

    #[test]
    fn test_spacecraft_new() {
        let traj = lox_orbits::orbits::DynTrajectory::from_csv_dyn(
            &lox_test_utils::read_data_file("trajectory_lunar.csv"),
            DynOrigin::Earth,
            DynFrame::Icrf,
        )
        .unwrap();
        let sc = Spacecraft::new("sc1", OrbitSource::Trajectory(traj));
        assert_eq!(sc.id().as_str(), "sc1");
        assert!(sc.max_slew_rate().is_none());
        assert!(sc.constellation_id().is_none());
    }

    #[test]
    fn test_spacecraft_with_max_slew_rate() {
        let traj = lox_orbits::orbits::DynTrajectory::from_csv_dyn(
            &lox_test_utils::read_data_file("trajectory_lunar.csv"),
            DynOrigin::Earth,
            DynFrame::Icrf,
        )
        .unwrap();
        let rate = AngularRate::degrees_per_second(5.0);
        let sc = Spacecraft::new("sc1", OrbitSource::Trajectory(traj)).with_max_slew_rate(rate);
        assert!(sc.max_slew_rate().is_some());
    }

    #[test]
    fn test_spacecraft_with_constellation_id() {
        let traj = lox_orbits::orbits::DynTrajectory::from_csv_dyn(
            &lox_test_utils::read_data_file("trajectory_lunar.csv"),
            DynOrigin::Earth,
            DynFrame::Icrf,
        )
        .unwrap();
        let sc =
            Spacecraft::new("sc1", OrbitSource::Trajectory(traj)).with_constellation_id("oneweb");
        assert_eq!(sc.constellation_id(), Some(&ConstellationId::new("oneweb")));
    }

    #[test]
    fn test_spacecraft_orbit_getter() {
        let traj = lox_orbits::orbits::DynTrajectory::from_csv_dyn(
            &lox_test_utils::read_data_file("trajectory_lunar.csv"),
            DynOrigin::Earth,
            DynFrame::Icrf,
        )
        .unwrap();
        let sc = Spacecraft::new("sc1", OrbitSource::Trajectory(traj));
        assert!(matches!(sc.orbit(), OrbitSource::Trajectory(_)));
    }

    // --- Scenario ---

    #[test]
    fn test_scenario_construction() {
        let start = Time::j2000(Tai);
        let end = start + TimeDelta::from_seconds(86400);
        let scenario = DynScenario::new(start, end, DynOrigin::Earth, DynFrame::Icrf);
        assert_eq!(scenario.origin(), DynOrigin::Earth);
        assert_eq!(scenario.frame(), DynFrame::Icrf);
        assert!(scenario.spacecraft().is_empty());
        assert!(scenario.ground_stations().is_empty());
    }

    #[test]
    fn test_scenario_with_assets() {
        let start = Time::j2000(Tai);
        let end = start + TimeDelta::from_seconds(86400);
        let gs = GroundStation::new("gs1", dummy_location(), dummy_mask());
        let traj = lox_orbits::orbits::DynTrajectory::from_csv_dyn(
            &lox_test_utils::read_data_file("trajectory_lunar.csv"),
            DynOrigin::Earth,
            DynFrame::Icrf,
        )
        .unwrap();
        let sc = Spacecraft::new("sc1", OrbitSource::Trajectory(traj));
        let scenario = DynScenario::new(start, end, DynOrigin::Earth, DynFrame::Icrf)
            .with_ground_stations(&[gs])
            .with_spacecraft(&[sc]);
        assert_eq!(scenario.ground_stations().len(), 1);
        assert_eq!(scenario.spacecraft().len(), 1);
    }

    #[test]
    fn test_scenario_filter_by_constellations() {
        let start = Time::j2000(Tai);
        let end = start + TimeDelta::from_seconds(86400);
        let traj = lox_orbits::orbits::DynTrajectory::from_csv_dyn(
            &lox_test_utils::read_data_file("trajectory_lunar.csv"),
            DynOrigin::Earth,
            DynFrame::Icrf,
        )
        .unwrap();
        let sc1 = Spacecraft::new("sc1", OrbitSource::Trajectory(traj.clone()))
            .with_constellation_id("oneweb");
        let sc2 = Spacecraft::new("sc2", OrbitSource::Trajectory(traj));
        let scenario = DynScenario::new(start, end, DynOrigin::Earth, DynFrame::Icrf)
            .with_spacecraft(&[sc1, sc2]);
        let filtered = scenario.filter_by_constellations(&[ConstellationId::new("oneweb")]);
        assert_eq!(filtered.spacecraft().len(), 1);
        assert_eq!(filtered.spacecraft()[0].id().as_str(), "sc1");
    }

    #[test]
    fn test_scenario_filter_by_networks() {
        let start = Time::j2000(Tai);
        let end = start + TimeDelta::from_seconds(86400);
        let gs1 =
            GroundStation::new("gs1", dummy_location(), dummy_mask()).with_network_id("estrack");
        let gs2 = GroundStation::new("gs2", dummy_location(), dummy_mask());
        let scenario = DynScenario::new(start, end, DynOrigin::Earth, DynFrame::Icrf)
            .with_ground_stations(&[gs1, gs2]);
        let filtered = scenario.filter_by_networks(&[NetworkId::new("estrack")]);
        assert_eq!(filtered.ground_stations().len(), 1);
        assert_eq!(filtered.ground_stations()[0].id().as_str(), "gs1");
    }

    #[test]
    fn test_scenario_with_constellation() {
        use lox_core::units::{AngleUnits, DistanceUnits};
        use lox_orbits::constellations::WalkerDeltaBuilder;

        let start = Time::j2000(Tai);
        let end = start + TimeDelta::from_seconds(86400);
        let scenario = DynScenario::new(start, end, DynOrigin::Earth, DynFrame::Icrf);

        let constellation = WalkerDeltaBuilder::new(6, 3)
            .with_semi_major_axis(7000.0_f64.km(), 0.0)
            .with_inclination(53.0_f64.deg())
            .build_constellation("test", start, DynOrigin::Earth, DynFrame::Icrf)
            .unwrap()
            .into_dyn();

        let scenario = scenario.with_constellation(constellation).unwrap();
        assert_eq!(scenario.spacecraft().len(), 6);
        assert_eq!(scenario.constellations().len(), 1);
        assert_eq!(scenario.constellations()[0].name(), "test");
        // Verify spacecraft IDs contain constellation name
        assert!(scenario.spacecraft()[0].id().as_str().contains("test"));
    }

    #[test]
    fn test_scenario_interval() {
        let start = Time::j2000(Tai);
        let end = start + TimeDelta::from_seconds(86400);
        let scenario = DynScenario::new(start, end, DynOrigin::Earth, DynFrame::Icrf);
        assert_eq!(scenario.interval().start(), start);
        assert_eq!(scenario.interval().end(), end);
    }

    #[test]
    fn test_scenario_propagate() {
        let traj = lox_orbits::orbits::DynTrajectory::from_csv_dyn(
            &lox_test_utils::read_data_file("trajectory_lunar.csv"),
            DynOrigin::Earth,
            DynFrame::Icrf,
        )
        .unwrap();
        let start = traj.start_time().to_scale(Tai);
        let end = traj.end_time().to_scale(Tai);
        let sc = Spacecraft::new("sc1", OrbitSource::Trajectory(traj));
        let scenario =
            DynScenario::new(start, end, DynOrigin::Earth, DynFrame::Icrf).with_spacecraft(&[sc]);
        let ensemble = scenario
            .propagate(&lox_frames::providers::DefaultRotationProvider)
            .unwrap();
        assert_eq!(ensemble.len(), 1);
        assert!(ensemble.get(&AssetId::new("sc1")).is_some());
    }
}