nyx_space/dynamics/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 crate::cosmic::{AstroError, Orbit};
20use crate::linalg::allocator::Allocator;
21use crate::linalg::{DefaultAllocator, DimName, Matrix3, Matrix4x3, OMatrix, OVector, Vector3};
22use crate::State;
23use anise::almanac::planetary::PlanetaryDataError;
24use anise::almanac::Almanac;
25use anise::errors::AlmanacError;
26use hyperdual::Owned;
27use snafu::Snafu;
28
29use std::fmt;
30use std::sync::Arc;
31
32pub use crate::errors::NyxError;
33
34/// The orbital module handles all Cartesian based orbital dynamics.
35///
36/// It is up to the engineer to ensure that the coordinate frames of the different dynamics borrowed
37/// from this module match, or perform the appropriate coordinate transformations.
38pub mod orbital;
39use self::guidance::GuidanceError;
40pub use self::orbital::*;
41
42/// The spacecraft module allows for simulation of spacecraft dynamics in general, including propulsion/maneuvers.
43pub mod spacecraft;
44pub use self::spacecraft::*;
45
46/// Defines a few examples of guidance laws.
47pub mod guidance;
48
49/// Defines some velocity change controllers.
50pub mod deltavctrl;
51
52/// Defines solar radiation pressure models
53pub mod solarpressure;
54pub use self::solarpressure::*;
55
56/// The drag module handles drag in a very basic fashion. Do not use for high fidelity dynamics.
57pub mod drag;
58pub use self::drag::*;
59
60/// Define the spherical harmonic models.
61/// This module allows loading gravity models from [PDS](http://pds-geosciences.wustl.edu/), [EGM2008](http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm2008/) and GMAT's own COF files.
62pub mod sph_harmonics;
63pub use self::sph_harmonics::*;
64
65/// The `Dynamics` trait handles and stores any equation of motion *and* the state is integrated.
66///
67/// Its design is such that several of the provided dynamics can be combined fairly easily. However,
68/// when combining the dynamics (e.g. integrating both the attitude of a spaceraft and its orbital
69/// parameters), it is up to the implementor to handle time and state organization correctly.
70/// For time management, I highly recommend using `hifitime` which is thoroughly validated.
71#[allow(clippy::type_complexity)]
72pub trait Dynamics: Clone + Sync + Send
73where
74 DefaultAllocator: Allocator<<Self::StateType as State>::Size>
75 + Allocator<<Self::StateType as State>::VecLength>
76 + Allocator<<Self::StateType as State>::Size, <Self::StateType as State>::Size>,
77{
78 /// The state of the associated hyperdual state, almost always StateType + U1
79 type HyperdualSize: DimName;
80 type StateType: State;
81
82 /// Defines the equations of motion for these dynamics, or a combination of provided dynamics.
83 /// The time delta_t is in **seconds** PAST the context epoch. The state vector is the state which
84 /// changes for every intermediate step of the integration. The state context is the state of
85 /// what is being propagated, it should allow rebuilding a new state context from the
86 /// provided state vector.
87 fn eom(
88 &self,
89 delta_t: f64,
90 state_vec: &OVector<f64, <Self::StateType as State>::VecLength>,
91 state_ctx: &Self::StateType,
92 almanac: Arc<Almanac>,
93 ) -> Result<OVector<f64, <Self::StateType as State>::VecLength>, DynamicsError>
94 where
95 DefaultAllocator: Allocator<<Self::StateType as State>::VecLength>;
96
97 /// Defines the equations of motion for Dual numbers for these dynamics.
98 /// _All_ dynamics need to allow for automatic differentiation. However, if differentiation is not supported,
99 /// then the dynamics should prevent initialization with a context which has an STM defined.
100 fn dual_eom(
101 &self,
102 _delta_t: f64,
103 _osculating_state: &Self::StateType,
104 _almanac: Arc<Almanac>,
105 ) -> Result<
106 (
107 OVector<f64, <Self::StateType as State>::Size>,
108 OMatrix<f64, <Self::StateType as State>::Size, <Self::StateType as State>::Size>,
109 ),
110 DynamicsError,
111 >
112 where
113 DefaultAllocator: Allocator<Self::HyperdualSize>
114 + Allocator<<Self::StateType as State>::Size>
115 + Allocator<<Self::StateType as State>::Size, <Self::StateType as State>::Size>,
116 Owned<f64, Self::HyperdualSize>: Copy,
117 {
118 Err(DynamicsError::StateTransitionMatrixUnset)
119 }
120
121 /// Optionally performs some final changes after each successful integration of the equations of motion.
122 /// For example, this can be used to update the Guidance mode.
123 /// NOTE: This function is also called just prior to very first integration step in order to update the initial state if needed.
124 fn finally(
125 &self,
126 next_state: Self::StateType,
127 _almanac: Arc<Almanac>,
128 ) -> Result<Self::StateType, DynamicsError> {
129 Ok(next_state)
130 }
131}
132
133/// The `ForceModel` trait handles immutable dynamics which return a force. Those will be divided by the mass of the spacecraft to compute the acceleration (F = ma).
134///
135/// Examples include Solar Radiation Pressure, drag, etc., i.e. forces which do not need to save the current state, only act on it.
136pub trait ForceModel: Send + Sync + fmt::Display {
137 /// If a parameter of this force model is stored in the spacecraft state, then this function should return the index where this parameter is being affected
138 fn estimation_index(&self) -> Option<usize>;
139
140 /// Defines the equations of motion for this force model from the provided osculating state.
141 fn eom(&self, ctx: &Spacecraft, almanac: Arc<Almanac>) -> Result<Vector3<f64>, DynamicsError>;
142
143 /// Force models must implement their partials, although those will only be called if the propagation requires the
144 /// computation of the STM. The `osc_ctx` is the osculating context, i.e. it changes for each sub-step of the integrator.
145 /// The last row corresponds to the partials of the parameter of this force model wrt the position, i.e. this only applies to conservative forces.
146 fn dual_eom(
147 &self,
148 osc_ctx: &Spacecraft,
149 almanac: Arc<Almanac>,
150 ) -> Result<(Vector3<f64>, Matrix4x3<f64>), DynamicsError>;
151}
152
153/// The `AccelModel` trait handles immutable dynamics which return an acceleration. Those can be added directly to Orbital Dynamics for example.
154///
155/// Examples include spherical harmonics, i.e. accelerations which do not need to save the current state, only act on it.
156pub trait AccelModel: Send + Sync + fmt::Display {
157 /// Defines the equations of motion for this force model from the provided osculating state in the integration frame.
158 fn eom(&self, osc: &Orbit, almanac: Arc<Almanac>) -> Result<Vector3<f64>, DynamicsError>;
159
160 /// Acceleration models must implement their partials, although those will only be called if the propagation requires the
161 /// computation of the STM.
162 fn dual_eom(
163 &self,
164 osc_ctx: &Orbit,
165 almanac: Arc<Almanac>,
166 ) -> Result<(Vector3<f64>, Matrix3<f64>), DynamicsError>;
167}
168
169/// Stores dynamical model errors
170#[derive(Debug, PartialEq, Snafu)]
171#[snafu(visibility(pub(crate)))]
172pub enum DynamicsError {
173 /// Fuel exhausted at the provided spacecraft state
174 #[snafu(display("fuel exhausted at {sc}"))]
175 FuelExhausted { sc: Box<Spacecraft> },
176 #[snafu(display("expected STM to be set"))]
177 StateTransitionMatrixUnset,
178 #[snafu(display("dynamical model encountered an astro error: {source}"))]
179 DynamicsAstro { source: AstroError },
180 #[snafu(display("dynamical model encountered an issue with the guidance: {source}"))]
181 DynamicsGuidance { source: GuidanceError },
182 #[snafu(display("dynamical model issue due to Almanac: {action} {source}"))]
183 DynamicsAlmanacError {
184 action: &'static str,
185 #[snafu(source(from(AlmanacError, Box::new)))]
186 source: Box<AlmanacError>,
187 },
188 #[snafu(display("dynamical model issue due to planetary data: {action} {source}"))]
189 DynamicsPlanetaryError {
190 action: &'static str,
191 source: PlanetaryDataError,
192 },
193}