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
/*
    Nyx, blazing fast astrodynamics
    Copyright (C) 2018-onwards Christopher Rabotin <christopher.rabotin@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

use anise::astro::PhysicsResult;
use anise::constants::frames::EARTH_J2000;
pub use anise::prelude::Orbit;

use nalgebra::Vector3;
use serde::{Deserialize, Serialize};
use snafu::ResultExt;
use typed_builder::TypedBuilder;

use super::{AstroPhysicsSnafu, BPlane, State};
use crate::dynamics::guidance::Thruster;
use crate::dynamics::DynamicsError;
use crate::errors::{StateAstroSnafu, StateError};
use crate::io::ConfigRepr;
use crate::linalg::{Const, DimName, OMatrix, OVector};
use crate::md::StateParameter;
use crate::time::Epoch;
use crate::utils::{cartesian_to_spherical, spherical_to_cartesian};

#[cfg(feature = "python")]
use pyo3::prelude::*;
use std::default::Default;
use std::fmt;
use std::ops::Add;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "python", pyclass)]
pub enum GuidanceMode {
    /// Guidance is turned off and Guidance Law may switch mode to Thrust for next call
    Coast,
    /// Guidance is turned on and Guidance Law may switch mode to Coast for next call
    Thrust,
    /// Guidance is turned off and Guidance Law may not change its mode (will need to be done externally to the guidance law).
    Inhibit,
}

impl Default for GuidanceMode {
    fn default() -> Self {
        Self::Coast
    }
}

impl From<f64> for GuidanceMode {
    fn from(value: f64) -> Self {
        if value >= 1.0 {
            Self::Thrust
        } else if value < 0.0 {
            Self::Inhibit
        } else {
            Self::Coast
        }
    }
}

impl From<GuidanceMode> for f64 {
    fn from(mode: GuidanceMode) -> f64 {
        match mode {
            GuidanceMode::Coast => 0.0,
            GuidanceMode::Thrust => 1.0,
            GuidanceMode::Inhibit => -1.0,
        }
    }
}

/// A spacecraft state, composed of its orbit, its dry and fuel (wet) masses (in kg), its SRP configuration, its drag configuration, its thruster configuration, and its guidance mode.
///
/// Optionally, the spacecraft state can also store the state transition matrix from the start of the propagation until the current time (i.e. trajectory STM, not step-size STM).
#[derive(Clone, Copy, Debug, Serialize, Deserialize, TypedBuilder)]
#[cfg_attr(feature = "python", pyclass)]
#[cfg_attr(feature = "python", pyo3(module = "nyx_space.cosmic"))]
pub struct Spacecraft {
    /// Initial orbit the vehicle is in
    pub orbit: Orbit,
    /// Dry mass, i.e. mass without fuel, in kg
    #[builder(default)]
    pub dry_mass_kg: f64,
    /// Fuel mass (if fuel mass is negative, thrusting will fail, unless configured to break laws of physics)
    #[builder(default)]
    pub fuel_mass_kg: f64,
    /// Solar Radiation Pressure configuration for this spacecraft
    #[builder(default)]
    #[serde(default)]
    pub srp: SrpConfig,

    #[builder(default)]
    #[serde(default)]
    pub drag: DragConfig,

    #[builder(default, setter(strip_option))]
    pub thruster: Option<Thruster>,
    /// Any extra information or extension that is needed for specific guidance laws
    #[builder(default)]
    #[serde(default)]
    pub mode: GuidanceMode,
    /// Optionally stores the state transition matrix from the start of the propagation until the current time (i.e. trajectory STM, not step-size STM)
    /// STM is contains position and velocity, Cr, Cd, fuel mass
    #[builder(default, setter(strip_option))]
    #[serde(skip)]
    pub stm: Option<OMatrix<f64, Const<9>, Const<9>>>,
}

impl Default for Spacecraft {
    fn default() -> Self {
        Self {
            orbit: Orbit::zero(EARTH_J2000),
            dry_mass_kg: 0.0,
            fuel_mass_kg: 0.0,
            srp: SrpConfig::default(),
            drag: DragConfig::default(),
            thruster: None,
            mode: GuidanceMode::default(),
            stm: None,
        }
    }
}

impl From<Orbit> for Spacecraft {
    fn from(orbit: Orbit) -> Self {
        Self::builder().orbit(orbit).build()
    }
}

#[cfg_attr(feature = "python", pyclass)]
#[cfg_attr(feature = "python", pyo3(module = "nyx_space.cosmic"))]
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)]
/// The Solar Radiation Pressure configuration for a spacecraft
pub struct SrpConfig {
    /// solar radiation pressure area
    pub area_m2: f64,
    /// coefficient of reflectivity, must be between 0.0 (translucent) and 2.0 (all radiation absorbed and twice the force is transmitted back), defaults to 1.8
    pub cr: f64,
}

impl SrpConfig {
    /// Initialize the SRP from the c_r default and the provided drag area
    pub fn from_area(area_m2: f64) -> Self {
        Self {
            area_m2,
            ..Default::default()
        }
    }
}

impl Default for SrpConfig {
    fn default() -> Self {
        Self {
            area_m2: 0.0,
            cr: 1.8,
        }
    }
}

#[cfg_attr(feature = "python", pyclass)]
#[cfg_attr(feature = "python", pyo3(module = "nyx_space.cosmic"))]
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)]
/// The drag configuration for a spacecraft
pub struct DragConfig {
    /// drag area
    pub area_m2: f64,
    /// coefficient of drag; (spheres are between 2.0 and 2.1, use 2.2 in Earth's atmosphere (default)).
    pub cd: f64,
}

impl DragConfig {
    /// Initialize the drag from the c_d default and the provided drag area
    pub fn from_area(area_m2: f64) -> Self {
        Self {
            area_m2,
            ..Default::default()
        }
    }
}

impl Default for DragConfig {
    fn default() -> Self {
        Self {
            area_m2: 0.0,
            cd: 2.2,
        }
    }
}

impl Spacecraft {
    /// Initialize a spacecraft state from all of its parameters
    pub fn new(
        orbit: Orbit,
        dry_mass_kg: f64,
        fuel_mass_kg: f64,
        srp_area_m2: f64,
        drag_area_m2: f64,
        cr: f64,
        cd: f64,
    ) -> Self {
        Self {
            orbit,
            dry_mass_kg,
            fuel_mass_kg,
            srp: SrpConfig {
                area_m2: srp_area_m2,
                cr,
            },
            drag: DragConfig {
                area_m2: drag_area_m2,
                cd,
            },
            ..Default::default()
        }
    }

    /// Initialize a spacecraft state from only a thruster and mass. Use this when designing guidance laws while ignoring drag and SRP.
    pub fn from_thruster(
        orbit: Orbit,
        dry_mass_kg: f64,
        fuel_mass_kg: f64,
        thruster: Thruster,
        mode: GuidanceMode,
    ) -> Self {
        Self {
            orbit,
            dry_mass_kg,
            fuel_mass_kg,
            thruster: Some(thruster),
            mode,
            ..Default::default()
        }
    }

    /// Initialize a spacecraft state from the SRP default 1.8 for coefficient of reflectivity (fuel mass and drag parameters nullified!)
    pub fn from_srp_defaults(orbit: Orbit, dry_mass_kg: f64, srp_area_m2: f64) -> Self {
        Self {
            orbit,
            dry_mass_kg,
            srp: SrpConfig::from_area(srp_area_m2),
            ..Default::default()
        }
    }

    /// Initialize a spacecraft state from the SRP default 1.8 for coefficient of drag (fuel mass and SRP parameters nullified!)
    pub fn from_drag_defaults(orbit: Orbit, dry_mass_kg: f64, drag_area_m2: f64) -> Self {
        Self {
            orbit,
            dry_mass_kg,
            drag: DragConfig::from_area(drag_area_m2),
            ..Default::default()
        }
    }

    pub fn with_dv_km_s(mut self, dv_km_s: Vector3<f64>) -> Self {
        self.orbit.apply_dv_km_s(dv_km_s);
        self
    }

    /// Returns a copy of the state with a new dry mass
    pub fn with_dry_mass(mut self, dry_mass_kg: f64) -> Self {
        self.dry_mass_kg = dry_mass_kg;
        self
    }

    /// Returns a copy of the state with a new fuel mass
    pub fn with_fuel_mass(mut self, fuel_mass_kg: f64) -> Self {
        self.fuel_mass_kg = fuel_mass_kg;
        self
    }

    /// Returns a copy of the state with a new SRP area and CR
    pub fn with_srp(mut self, srp_area_m2: f64, cr: f64) -> Self {
        self.srp = SrpConfig {
            area_m2: srp_area_m2,
            cr,
        };

        self
    }

    /// Returns a copy of the state with a new SRP area
    pub fn with_srp_area(mut self, srp_area_m2: f64) -> Self {
        self.srp.area_m2 = srp_area_m2;
        self
    }

    /// Returns a copy of the state with a new coefficient of reflectivity
    pub fn with_cr(mut self, cr: f64) -> Self {
        self.srp.cr = cr;
        self
    }

    /// Returns a copy of the state with a new drag area and CD
    pub fn with_drag(mut self, drag_area_m2: f64, cd: f64) -> Self {
        self.drag = DragConfig {
            area_m2: drag_area_m2,
            cd,
        };
        self
    }

    /// Returns a copy of the state with a new SRP area
    pub fn with_drag_area(mut self, drag_area_m2: f64) -> Self {
        self.drag.area_m2 = drag_area_m2;
        self
    }

    /// Returns a copy of the state with a new coefficient of drag
    pub fn with_cd(mut self, cd: f64) -> Self {
        self.drag.cd = cd;
        self
    }

    /// Returns a copy of the state with a new orbit
    pub fn with_orbit(mut self, orbit: Orbit) -> Self {
        self.orbit = orbit;
        self
    }

    /// Returns the root sum square error between this spacecraft and the other, in kilometers for the position, kilometers per second in velocity, and kilograms in fuel
    pub fn rss(&self, other: &Self) -> PhysicsResult<(f64, f64, f64)> {
        let rss_p_km = self.orbit.rss_radius_km(&other.orbit)?;
        let rss_v_km_s = self.orbit.rss_velocity_km_s(&other.orbit)?;
        let rss_fuel_kg = (self.fuel_mass_kg - other.fuel_mass_kg).powi(2).sqrt();

        Ok((rss_p_km, rss_v_km_s, rss_fuel_kg))
    }

    /// Sets the STM of this state of identity, which also enables computation of the STM for spacecraft navigation
    pub fn enable_stm(&mut self) {
        self.stm = Some(OMatrix::<f64, Const<9>, Const<9>>::identity());
    }

    /// Copies the current state but sets the STM to identity
    pub fn with_stm(mut self) -> Self {
        self.enable_stm();
        self
    }

    /// Returns the total mass in kilograms
    pub fn mass_kg(&self) -> f64 {
        self.dry_mass_kg + self.fuel_mass_kg
    }

    /// Returns a copy of the state with the provided guidance mode
    pub fn with_guidance_mode(mut self, mode: GuidanceMode) -> Self {
        self.mode = mode;
        self
    }

    pub fn mode(&self) -> GuidanceMode {
        self.mode
    }

    pub fn mut_mode(&mut self, mode: GuidanceMode) {
        self.mode = mode;
    }
}

impl PartialEq for Spacecraft {
    fn eq(&self, other: &Self) -> bool {
        let mass_tol = 1e-6; // milligram
        self.orbit.eq_within(&other.orbit, 1e-9, 1e-12)
            && (self.dry_mass_kg - other.dry_mass_kg).abs() < mass_tol
            && (self.fuel_mass_kg - other.fuel_mass_kg).abs() < mass_tol
            && self.srp == other.srp
            && self.drag == other.drag
    }
}

#[allow(clippy::format_in_format_args)]
impl fmt::Display for Spacecraft {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mass_prec = f.precision().unwrap_or(3);
        let orbit_prec = f.precision().unwrap_or(6);
        write!(
            f,
            "total mass = {} kg @  {}  {:?}",
            format!("{:.*}", mass_prec, self.dry_mass_kg + self.fuel_mass_kg),
            format!("{:.*}", orbit_prec, self.orbit),
            self.mode,
        )
    }
}

#[allow(clippy::format_in_format_args)]
impl fmt::LowerExp for Spacecraft {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mass_prec = f.precision().unwrap_or(3);
        let orbit_prec = f.precision().unwrap_or(6);
        write!(
            f,
            "total mass = {} kg @  {}  {:?}",
            format!("{:.*e}", mass_prec, self.dry_mass_kg + self.fuel_mass_kg),
            format!("{:.*e}", orbit_prec, self.orbit),
            self.mode,
        )
    }
}

#[allow(clippy::format_in_format_args)]
impl fmt::LowerHex for Spacecraft {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mass_prec = f.precision().unwrap_or(3);
        let orbit_prec = f.precision().unwrap_or(6);
        write!(
            f,
            "total mass = {} kg @  {}  {:?}",
            format!("{:.*}", mass_prec, self.dry_mass_kg + self.fuel_mass_kg),
            format!("{:.*x}", orbit_prec, self.orbit),
            self.mode,
        )
    }
}

#[allow(clippy::format_in_format_args)]
impl fmt::UpperHex for Spacecraft {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mass_prec = f.precision().unwrap_or(3);
        let orbit_prec = f.precision().unwrap_or(6);
        write!(
            f,
            "total mass = {} kg @  {}  {:?}",
            format!("{:.*e}", mass_prec, self.dry_mass_kg + self.fuel_mass_kg),
            format!("{:.*X}", orbit_prec, self.orbit),
            self.mode,
        )
    }
}

impl State for Spacecraft {
    type Size = Const<9>;
    type VecLength = Const<90>;

    fn reset_stm(&mut self) {
        self.stm = Some(OMatrix::<f64, Const<9>, Const<9>>::identity());
    }

    fn zeros() -> Self {
        Self::default()
    }

    /// The vector is organized as such:
    /// [X, Y, Z, Vx, Vy, Vz, Cr, Cd, Fuel mass, STM(9x9)]
    fn to_vector(&self) -> OVector<f64, Const<90>> {
        let mut vector = OVector::<f64, Const<90>>::zeros();
        // Set the orbit state info
        for (i, val) in self.orbit.radius_km.iter().enumerate() {
            // Place the orbit state first, then skip three (Cr, Cd, Fuel), then copy orbit STM
            vector[i] = *val;
        }
        for (i, val) in self.orbit.velocity_km_s.iter().enumerate() {
            // Place the orbit state first, then skip three (Cr, Cd, Fuel), then copy orbit STM
            vector[i + 3] = *val;
        }
        // Set the spacecraft parameters
        vector[6] = self.srp.cr;
        vector[7] = self.drag.cd;
        vector[8] = self.fuel_mass_kg;
        // Add the STM to the vector
        if let Some(stm) = self.stm {
            for (idx, stm_val) in stm.as_slice().iter().enumerate() {
                vector[idx + Self::Size::dim()] = *stm_val;
            }
        }
        vector
    }

    /// Vector is expected to be organized as such:
    /// [X, Y, Z, Vx, Vy, Vz, Cr, Cd, Fuel mass, STM(9x9)]
    fn set(&mut self, epoch: Epoch, vector: &OVector<f64, Const<90>>) {
        let sc_state =
            OVector::<f64, Self::Size>::from_column_slice(&vector.as_slice()[..Self::Size::dim()]);

        if self.stm.is_some() {
            let sc_full_stm = OMatrix::<f64, Self::Size, Self::Size>::from_column_slice(
                &vector.as_slice()[Self::Size::dim()..],
            );

            self.stm = Some(sc_full_stm);
        }

        let radius_km = sc_state.fixed_rows::<3>(0).into_owned();
        let vel_km_s = sc_state.fixed_rows::<3>(3).into_owned();
        self.orbit.epoch = epoch;
        self.orbit.radius_km = radius_km;
        self.orbit.velocity_km_s = vel_km_s;
        self.srp.cr = sc_state[6];
        self.drag.cd = sc_state[7];
        self.fuel_mass_kg = sc_state[8];
    }

    /// diag(STM) = [X,Y,Z,Vx,Vy,Vz,Cr,Cd,Fuel]
    /// WARNING: Currently the STM assumes that the fuel mass is constant at ALL TIMES!
    fn stm(&self) -> Result<OMatrix<f64, Self::Size, Self::Size>, DynamicsError> {
        match self.stm {
            Some(stm) => Ok(stm),
            None => Err(DynamicsError::StateTransitionMatrixUnset),
        }
    }

    fn epoch(&self) -> Epoch {
        self.orbit.epoch
    }

    fn set_epoch(&mut self, epoch: Epoch) {
        self.orbit.epoch = epoch
    }

    fn add(self, other: OVector<f64, Self::Size>) -> Self {
        self + other
    }

    fn value(&self, param: StateParameter) -> Result<f64, StateError> {
        match param {
            StateParameter::Cd => Ok(self.drag.cd),
            StateParameter::Cr => Ok(self.srp.cr),
            StateParameter::DryMass => Ok(self.dry_mass_kg),
            StateParameter::FuelMass => Ok(self.fuel_mass_kg),
            StateParameter::Isp => match self.thruster {
                Some(thruster) => Ok(thruster.isp_s),
                None => Err(StateError::NoThrusterAvail),
            },
            StateParameter::Thrust => match self.thruster {
                Some(thruster) => Ok(thruster.thrust_N),
                None => Err(StateError::NoThrusterAvail),
            },
            StateParameter::GuidanceMode => Ok(self.mode.into()),
            StateParameter::ApoapsisRadius => self
                .orbit
                .apoapsis_km()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::AoL => self
                .orbit
                .aol_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::AoP => self
                .orbit
                .aop_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::BdotR => Ok(BPlane::new(self.orbit)
                .context(StateAstroSnafu { param })?
                .b_r
                .real()),
            StateParameter::BdotT => Ok(BPlane::new(self.orbit)
                .context(StateAstroSnafu { param })?
                .b_t
                .real()),
            StateParameter::BLTOF => Ok(BPlane::new(self.orbit)
                .context(StateAstroSnafu { param })?
                .ltof_s
                .real()),
            StateParameter::C3 => self
                .orbit
                .c3_km2_s2()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::Declination => Ok(self.orbit.declination_deg()),
            StateParameter::EccentricAnomaly => self
                .orbit
                .ea_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::Eccentricity => self
                .orbit
                .ecc()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::Energy => self
                .orbit
                .energy_km2_s2()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::FlightPathAngle => self
                .orbit
                .fpa_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::Height => self
                .orbit
                .height_km()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::Latitude => self
                .orbit
                .latitude_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::Longitude => Ok(self.orbit.longitude_deg()),
            StateParameter::Hmag => self
                .orbit
                .hmag()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::HX => self
                .orbit
                .hx()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::HY => self
                .orbit
                .hy()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::HZ => self
                .orbit
                .hz()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::HyperbolicAnomaly => self
                .orbit
                .hyperbolic_anomaly_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::Inclination => self
                .orbit
                .inc_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::MeanAnomaly => self
                .orbit
                .ma_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::PeriapsisRadius => self
                .orbit
                .periapsis_km()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::Period => Ok(self
                .orbit
                .period()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param })?
                .to_seconds()),
            StateParameter::RightAscension => Ok(self.orbit.right_ascension_deg()),
            StateParameter::RAAN => self
                .orbit
                .raan_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::Rmag => Ok(self.orbit.rmag_km()),
            StateParameter::SemiMinorAxis => self
                .orbit
                .semi_minor_axis_km()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::SemiParameter => self
                .orbit
                .semi_parameter_km()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::SMA => self
                .orbit
                .sma_km()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::TrueAnomaly => self
                .orbit
                .ta_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::TrueLongitude => self
                .orbit
                .tlong_deg()
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param }),
            StateParameter::VelocityDeclination => Ok(self.orbit.velocity_declination_deg()),
            StateParameter::Vmag => Ok(self.orbit.vmag_km_s()),
            StateParameter::X => Ok(self.orbit.radius_km.x),
            StateParameter::Y => Ok(self.orbit.radius_km.y),
            StateParameter::Z => Ok(self.orbit.radius_km.z),
            StateParameter::VX => Ok(self.orbit.velocity_km_s.x),
            StateParameter::VY => Ok(self.orbit.velocity_km_s.y),
            StateParameter::VZ => Ok(self.orbit.velocity_km_s.z),
            _ => Err(StateError::Unavailable { param }),
        }
    }

    fn set_value(&mut self, param: StateParameter, val: f64) -> Result<(), StateError> {
        match param {
            StateParameter::Cd => self.drag.cd = val,
            StateParameter::Cr => self.srp.cr = val,
            StateParameter::FuelMass => self.fuel_mass_kg = val,
            StateParameter::Isp => match self.thruster {
                Some(ref mut thruster) => thruster.isp_s = val,
                None => return Err(StateError::NoThrusterAvail),
            },
            StateParameter::Thrust => match self.thruster {
                Some(ref mut thruster) => thruster.thrust_N = val,
                None => return Err(StateError::NoThrusterAvail),
            },
            StateParameter::AoP => self
                .orbit
                .set_aop_deg(val)
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param })?,
            StateParameter::Eccentricity => self
                .orbit
                .set_ecc(val)
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param })?,
            StateParameter::Inclination => self
                .orbit
                .set_inc_deg(val)
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param })?,
            StateParameter::RAAN => self
                .orbit
                .set_raan_deg(val)
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param })?,
            StateParameter::SMA => self
                .orbit
                .set_sma_km(val)
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param })?,
            StateParameter::TrueAnomaly => self
                .orbit
                .set_ta_deg(val)
                .context(AstroPhysicsSnafu)
                .context(StateAstroSnafu { param })?,
            StateParameter::X => self.orbit.radius_km.x = val,
            StateParameter::Y => self.orbit.radius_km.y = val,
            StateParameter::Z => self.orbit.radius_km.z = val,
            StateParameter::Rmag => {
                // Convert the position to spherical coordinates
                let (_, θ, φ) = cartesian_to_spherical(&self.orbit.radius_km);
                // Convert back to cartesian after setting the new range value
                self.orbit.radius_km = spherical_to_cartesian(val, θ, φ);
            }
            StateParameter::VX => self.orbit.velocity_km_s.x = val,
            StateParameter::VY => self.orbit.velocity_km_s.y = val,
            StateParameter::VZ => self.orbit.velocity_km_s.z = val,
            StateParameter::Vmag => {
                // Convert the velocity to spherical coordinates
                let (_, θ, φ) = cartesian_to_spherical(&self.orbit.velocity_km_s);
                // Convert back to cartesian after setting the new range value
                self.orbit.velocity_km_s = spherical_to_cartesian(val, θ, φ);
            }
            _ => return Err(StateError::ReadOnly { param }),
        }
        Ok(())
    }

    fn unset_stm(&mut self) {
        self.stm = None;
    }
}

impl Add<OVector<f64, Const<6>>> for Spacecraft {
    type Output = Self;

    /// Adds the provided state deviation to this orbit
    fn add(mut self, other: OVector<f64, Const<6>>) -> Self {
        let radius_km = other.fixed_rows::<3>(0).into_owned();
        let vel_km_s = other.fixed_rows::<3>(3).into_owned();

        self.orbit.radius_km += radius_km;
        self.orbit.velocity_km_s += vel_km_s;

        self
    }
}

impl Add<OVector<f64, Const<9>>> for Spacecraft {
    type Output = Self;

    /// Adds the provided state deviation to this orbit
    fn add(mut self, other: OVector<f64, Const<9>>) -> Self {
        let radius_km = other.fixed_rows::<3>(0).into_owned();
        let vel_km_s = other.fixed_rows::<3>(3).into_owned();

        self.orbit.radius_km += radius_km;
        self.orbit.velocity_km_s += vel_km_s;
        self.srp.cr += other[6];
        self.drag.cd += other[7];
        self.fuel_mass_kg += other[8];

        self
    }
}

impl ConfigRepr for Spacecraft {}

#[test]
fn test_serde() {
    use serde_yaml;
    use std::str::FromStr;

    use anise::constants::frames::EARTH_J2000;

    let orbit = Orbit::new(
        -9042.862234,
        18536.333069,
        6999.957069,
        -3.288789,
        -2.226285,
        1.646738,
        Epoch::from_str("2018-09-15T00:15:53.098 UTC").unwrap(),
        EARTH_J2000,
    );

    let sc = Spacecraft::new(orbit, 500.0, 159.0, 2.0, 2.0, 1.8, 2.2);

    let serialized_sc = serde_yaml::to_string(&sc).unwrap();
    println!("{}", serialized_sc);

    let deser_sc: Spacecraft = serde_yaml::from_str(&serialized_sc).unwrap();

    assert_eq!(sc, deser_sc);

    // Check that we can omit the thruster info entirely.
    let s = r#"
orbit:
    radius_km:
        - -9042.862234
        - 18536.333069
        - 6999.957069
    velocity_km_s:
        - -3.288789
        - -2.226285
        - 1.646738
    epoch: 2018-09-15T00:15:53.098000000 UTC
    frame:
      ephemeris_id: 399
      orientation_id: 1
      mu_km3_s2: null
      shape: null
dry_mass_kg: 500.0
fuel_mass_kg: 159.0
srp:
    area_m2: 2.0
    cr: 1.8
drag:
    area_m2: 2.0
    cd: 2.2
    "#;

    let deser_sc: Spacecraft = serde_yaml::from_str(s).unwrap();
    assert_eq!(sc, deser_sc);

    // Check that we can specify a thruster info entirely.
    let s = r#"
orbit:
    radius_km:
    - -9042.862234
    - 18536.333069
    - 6999.957069
    velocity_km_s:
    - -3.288789
    - -2.226285
    - 1.646738
    epoch: 2018-09-15T00:15:53.098000000 UTC
    frame:
        ephemeris_id: 399
        orientation_id: 1
        mu_km3_s2: null
        shape: null
dry_mass_kg: 500.0
fuel_mass_kg: 159.0
srp:
    area_m2: 2.0
    cr: 1.8
drag:
    area_m2: 2.0
    cd: 2.2
thruster:
    thrust_N: 1e-5
    isp_s: 300.5
    "#;

    let mut sc_thruster = sc;
    sc_thruster.thruster = Some(Thruster {
        isp_s: 300.5,
        thrust_N: 1e-5,
    });
    let deser_sc: Spacecraft = serde_yaml::from_str(s).unwrap();
    assert_eq!(sc_thruster, deser_sc);

    // Tests the minimum definition which will set all of the defaults too
    let s = r#"
orbit:
    radius_km:
    - -9042.862234
    - 18536.333069
    - 6999.957069
    velocity_km_s:
    - -3.288789
    - -2.226285
    - 1.646738
    epoch: 2018-09-15T00:15:53.098000000 UTC
    frame:
        ephemeris_id: 399
        orientation_id: 1
        mu_km3_s2: null
        shape: null
dry_mass_kg: 500.0
fuel_mass_kg: 159.0
"#;

    let deser_sc: Spacecraft = serde_yaml::from_str(s).unwrap();

    let sc = Spacecraft::new(orbit, 500.0, 159.0, 0.0, 0.0, 1.8, 2.2);
    assert_eq!(sc, deser_sc);
}