nyx_space/cosmic/
mod.rs

1/*
2    Nyx, blazing fast astrodynamics
3    Copyright (C) 2018-onwards Christopher Rabotin <christopher.rabotin@gmail.com>
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU Affero General Public License as published
7    by the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU Affero General Public License for more details.
14
15    You should have received a copy of the GNU Affero General Public License
16    along with this program.  If not, see <https://www.gnu.org/licenses/>.
17*/
18
19use anise::errors::{AlmanacError, PhysicsError};
20pub use anise::prelude::*;
21
22pub use crate::cosmic::{DragData, GuidanceMode, Mass, SRPData, Spacecraft};
23use crate::dynamics::DynamicsError;
24pub use crate::errors::NyxError;
25use crate::errors::StateError;
26use crate::linalg::allocator::Allocator;
27use crate::linalg::{DefaultAllocator, DimName, OMatrix, OVector};
28use crate::md::StateParameter;
29use snafu::Snafu;
30use std::fmt;
31
32/// A trait allowing for something to have an epoch
33pub trait TimeTagged {
34    /// Retrieve the Epoch
35    fn epoch(&self) -> Epoch;
36    /// Set the Epoch
37    fn set_epoch(&mut self, epoch: Epoch);
38}
39
40/// A trait for generate propagation and estimation state.
41/// The first parameter is the size of the state, the second is the size of the propagated state including STM and extra items.
42pub trait State: Default + Copy + PartialEq + fmt::Display + fmt::LowerExp + Send + Sync
43where
44    Self: Sized,
45    DefaultAllocator:
46        Allocator<Self::Size> + Allocator<Self::Size, Self::Size> + Allocator<Self::VecLength>,
47{
48    /// Size of the state and its STM
49    type Size: DimName;
50    type VecLength: DimName;
51
52    /// Initialize an empty state
53    /// By default, this is not implemented. This function must be implemented when filtering on this state.
54    fn zeros() -> Self {
55        unimplemented!()
56    }
57
58    /// Return this state as a vector for the propagation/estimation
59    fn to_vector(&self) -> OVector<f64, Self::VecLength>;
60
61    /// Returns strictly the state vector without any STM, if set.
62    fn to_state_vector(&self) -> OVector<f64, Self::Size> {
63        OVector::<f64, Self::Size>::from_iterator(
64            self.to_vector().iter().copied().take(Self::Size::USIZE),
65        )
66    }
67
68    /// Return the state's _step_ state transition matrix.
69    /// By default, this is not implemented. This function must be implemented when filtering on this state.
70    fn stm(&self) -> Result<OMatrix<f64, Self::Size, Self::Size>, DynamicsError> {
71        Err(DynamicsError::StateTransitionMatrixUnset)
72    }
73
74    /// Copies the current state but sets the STM to identity
75    fn with_stm(self) -> Self;
76
77    /// Resets the STM, unimplemented by default.
78    fn reset_stm(&mut self) {
79        unimplemented!()
80    }
81
82    /// Unsets the STM for this state
83    fn unset_stm(&mut self);
84
85    /// Set this state
86    fn set(&mut self, epoch: Epoch, vector: &OVector<f64, Self::VecLength>);
87
88    /// Reconstruct a new State from the provided delta time in seconds compared to the current state
89    /// and with the provided vector.
90    fn set_with_delta_seconds(
91        mut self,
92        delta_t_s: f64,
93        vector: &OVector<f64, Self::VecLength>,
94    ) -> Self
95    where
96        DefaultAllocator: Allocator<Self::VecLength>,
97    {
98        self.set(self.epoch() + delta_t_s, vector);
99        self
100    }
101
102    /// Retrieve the Epoch
103    fn epoch(&self) -> Epoch;
104
105    /// Set the Epoch
106    fn set_epoch(&mut self, epoch: Epoch);
107
108    /// By default, this is not implemented. This function must be implemented when filtering on this state.
109    fn add(self, _other: OVector<f64, Self::Size>) -> Self {
110        unimplemented!()
111    }
112
113    /// Return the value of the parameter, returns an error by default
114    fn value(&self, param: StateParameter) -> Result<f64, StateError> {
115        Err(StateError::Unavailable { param })
116    }
117
118    /// Allows setting the value of the given parameter.
119    /// NOTE: Most parameters where the `value` is available CANNOT be also set for that parameter (it's a much harder problem!)
120    fn set_value(&mut self, param: StateParameter, _val: f64) -> Result<(), StateError> {
121        Err(StateError::Unavailable { param })
122    }
123
124    /// Returns a copy of the orbit
125    fn orbit(&self) -> Orbit;
126
127    /// Modifies this state's orbit
128    fn set_orbit(&mut self, _orbit: Orbit) {}
129}
130
131pub fn assert_orbit_eq_or_abs(left: &Orbit, right: &Orbit, epsilon: f64, msg: &str) {
132    if !left.eq_within(right, epsilon, epsilon) {
133        panic!(
134            r#"assertion failed: {}
135  left: `{:?}`,
136 right: `{:?}`"#,
137            msg, left, right
138        )
139    }
140}
141
142#[derive(Debug, PartialEq, Snafu)]
143#[snafu(visibility(pub(crate)))]
144pub enum AstroError {
145    #[snafu(display("B Plane jacobian invariant must be either VX, VY or VZ"))]
146    BPlaneInvariant,
147    #[snafu(display("operation requires a local frame"))]
148    NotLocalFrame,
149    #[snafu(display("partial derivatives not defined for this parameter"))]
150    PartialsUndefined,
151    #[snafu(display("Orbit is not hyperbolic so there is no hyperbolic anomaly."))]
152    NotHyperbolic,
153    #[snafu(display("physics error occured during astro computation: {source}"))]
154    AstroPhysics { source: PhysicsError },
155    #[snafu(display("ANISE Almanac error occured during astro computation: {source}"))]
156    AstroAlmanac {
157        #[snafu(source(from(AlmanacError, Box::new)))]
158        source: Box<AlmanacError>,
159    },
160}
161
162// Re-Export OrbitDual
163mod orbitdual;
164pub use self::orbitdual::*;
165
166// Re-Export B Plane
167mod bplane;
168pub use self::bplane::*;
169
170// Re-Export spacecraft
171mod spacecraft;
172pub use self::spacecraft::*;
173
174/// The eclipse module allows finding eclipses and (conversely) visibility between a state and another one (e.g. a planet or the Sun).
175pub mod eclipse;
176
177/// Speed of light in meters per second
178pub const SPEED_OF_LIGHT_M_S: f64 = SPEED_OF_LIGHT_KM_S * 1e3;
179pub use anise::constants::SPEED_OF_LIGHT_KM_S;
180
181/// Astronomical unit, in kilometers, according to the [IAU](https://www.iau.org/public/themes/measuring/).
182pub const AU: f64 = 149_597_870.700;
183
184/// From NIST special publication 330, 2008 edition, in meters per second squared
185pub const STD_GRAVITY: f64 = 9.80665;