Skip to main content

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::analysis::AnalysisError;
20use anise::errors::{AlmanacError, PhysicsError};
21pub use anise::prelude::*;
22
23pub use crate::cosmic::{DragData, GuidanceMode, Mass, SRPData, Spacecraft};
24use crate::dynamics::DynamicsError;
25pub use crate::errors::NyxError;
26use crate::errors::StateError;
27use crate::linalg::allocator::Allocator;
28use crate::linalg::{DefaultAllocator, DimName, OMatrix, OVector};
29use crate::md::StateParameter;
30use snafu::Snafu;
31use std::fmt;
32
33/// A trait allowing for something to have an epoch
34pub trait TimeTagged {
35    /// Retrieve the Epoch
36    fn epoch(&self) -> Epoch;
37    /// Set the Epoch
38    fn set_epoch(&mut self, epoch: Epoch);
39}
40
41/// A trait for generate propagation and estimation state.
42/// The first parameter is the size of the state, the second is the size of the propagated state including STM and extra items.
43pub trait State: Default + Copy + PartialEq + fmt::Display + fmt::LowerExp + Send + Sync
44where
45    Self: Sized,
46    DefaultAllocator:
47        Allocator<Self::Size> + Allocator<Self::Size, Self::Size> + Allocator<Self::VecLength>,
48{
49    /// Size of the state and its STM
50    type Size: DimName;
51    type VecLength: DimName;
52
53    /// Initialize an empty state
54    /// By default, this is not implemented. This function must be implemented when filtering on this state.
55    fn zeros() -> Self {
56        unimplemented!()
57    }
58
59    /// Return this state as a vector for the propagation/estimation
60    fn to_vector(&self) -> OVector<f64, Self::VecLength>;
61
62    /// Returns strictly the state vector without any STM, if set.
63    fn to_state_vector(&self) -> OVector<f64, Self::Size> {
64        OVector::<f64, Self::Size>::from_iterator(
65            self.to_vector().iter().copied().take(Self::Size::DIM),
66        )
67    }
68
69    /// Return the state's _step_ state transition matrix.
70    /// By default, this is not implemented. This function must be implemented when filtering on this state.
71    fn stm(&self) -> Result<OMatrix<f64, Self::Size, Self::Size>, DynamicsError> {
72        Err(DynamicsError::StateTransitionMatrixUnset)
73    }
74
75    /// Copies the current state but sets the STM to identity
76    fn with_stm(self) -> Self;
77
78    /// Resets the STM, unimplemented by default.
79    fn reset_stm(&mut self) {
80        unimplemented!()
81    }
82
83    /// Unsets the STM for this state
84    fn unset_stm(&mut self);
85
86    /// Set this state
87    fn set(&mut self, epoch: Epoch, vector: &OVector<f64, Self::VecLength>);
88
89    /// Reconstruct a new State from the provided delta time in seconds compared to the current state
90    /// and with the provided vector.
91    fn set_with_delta_seconds(
92        mut self,
93        delta_t_s: f64,
94        vector: &OVector<f64, Self::VecLength>,
95    ) -> Self
96    where
97        DefaultAllocator: Allocator<Self::VecLength>,
98    {
99        self.set(self.epoch() + delta_t_s, vector);
100        self
101    }
102
103    /// Retrieve the Epoch
104    fn epoch(&self) -> Epoch;
105
106    /// Set the Epoch
107    fn set_epoch(&mut self, epoch: Epoch);
108
109    /// By default, this is not implemented. This function must be implemented when filtering on this state.
110    fn add(self, _other: OVector<f64, Self::Size>) -> Self {
111        unimplemented!()
112    }
113
114    /// Return the value of the parameter, returns an error by default
115    fn value(&self, param: StateParameter) -> Result<f64, StateError> {
116        Err(StateError::Unavailable { param })
117    }
118
119    /// Allows setting the value of the given parameter.
120    /// NOTE: Most parameters where the `value` is available CANNOT be also set for that parameter (it's a much harder problem!)
121    fn set_value(&mut self, param: StateParameter, _val: f64) -> Result<(), StateError> {
122        Err(StateError::Unavailable { param })
123    }
124
125    /// Returns a copy of the orbit
126    fn orbit(&self) -> Orbit;
127
128    /// Modifies this state's orbit
129    fn set_orbit(&mut self, _orbit: Orbit) {}
130}
131
132pub fn assert_orbit_eq_or_abs(left: &Orbit, right: &Orbit, epsilon: f64, msg: &str) {
133    if !left.eq_within(right, epsilon, epsilon) {
134        panic!(
135            r#"assertion failed: {msg}
136  left: `{left:?}`,
137 right: `{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("analysis error occured during astro computation: {source}"))]
156    AstroAnalysis { source: AnalysisError },
157    #[snafu(display("ANISE Almanac error occured during astro computation: {source}"))]
158    AstroAlmanac {
159        #[snafu(source(from(AlmanacError, Box::new)))]
160        source: Box<AlmanacError>,
161    },
162}
163
164// Re-Export B Plane
165mod bplane;
166pub use self::bplane::*;
167
168// Re-Export spacecraft
169mod spacecraft;
170pub use self::spacecraft::*;
171
172/// The eclipse module allows finding eclipses and (conversely) visibility between a state and another one (e.g. a planet or the Sun).
173pub mod eclipse;
174
175/// Speed of light in meters per second
176pub const SPEED_OF_LIGHT_M_S: f64 = SPEED_OF_LIGHT_KM_S * 1e3;
177pub use anise::constants::SPEED_OF_LIGHT_KM_S;
178
179/// Astronomical unit, in kilometers, according to the [IAU](https://www.iau.org/public/themes/measuring/).
180pub const AU: f64 = 149_597_870.700;
181
182/// From NIST special publication 330, 2008 edition, in meters per second squared
183pub const STD_GRAVITY: f64 = 9.80665;