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
65pub mod sequence;
66
67/// The `Dynamics` trait handles and stores any equation of motion *and* the state is integrated.
68///
69/// Its design is such that several of the provided dynamics can be combined fairly easily. However,
70/// when combining the dynamics (e.g. integrating both the attitude of a spaceraft and its orbital
71/// parameters), it is up to the implementor to handle time and state organization correctly.
72/// For time management, I highly recommend using `hifitime` which is thoroughly validated.
73#[allow(clippy::type_complexity)]
74pub trait Dynamics: Clone + Sync + Send
75where
76 DefaultAllocator: Allocator<<Self::StateType as State>::Size>
77 + Allocator<<Self::StateType as State>::VecLength>
78 + Allocator<<Self::StateType as State>::Size, <Self::StateType as State>::Size>,
79{
80 /// The state of the associated hyperdual state, almost always StateType + U1
81 type HyperdualSize: DimName;
82 type StateType: State;
83
84 /// Defines the equations of motion for these dynamics, or a combination of provided dynamics.
85 /// The time delta_t is in **seconds** PAST the context epoch. The state vector is the state which
86 /// changes for every intermediate step of the integration. The state context is the state of
87 /// what is being propagated, it should allow rebuilding a new state context from the
88 /// provided state vector.
89 fn eom(
90 &self,
91 delta_t: f64,
92 state_vec: &OVector<f64, <Self::StateType as State>::VecLength>,
93 state_ctx: &Self::StateType,
94 almanac: Arc<Almanac>,
95 ) -> Result<OVector<f64, <Self::StateType as State>::VecLength>, DynamicsError>
96 where
97 DefaultAllocator: Allocator<<Self::StateType as State>::VecLength>;
98
99 /// Defines the equations of motion for Dual numbers for these dynamics.
100 /// _All_ dynamics need to allow for automatic differentiation. However, if differentiation is not supported,
101 /// then the dynamics should prevent initialization with a context which has an STM defined.
102 fn dual_eom(
103 &self,
104 _delta_t: f64,
105 _osculating_state: &Self::StateType,
106 _almanac: Arc<Almanac>,
107 ) -> Result<
108 (
109 OVector<f64, <Self::StateType as State>::Size>,
110 OMatrix<f64, <Self::StateType as State>::Size, <Self::StateType as State>::Size>,
111 ),
112 DynamicsError,
113 >
114 where
115 DefaultAllocator: Allocator<Self::HyperdualSize>
116 + Allocator<<Self::StateType as State>::Size>
117 + Allocator<<Self::StateType as State>::Size, <Self::StateType as State>::Size>,
118 Owned<f64, Self::HyperdualSize>: Copy,
119 {
120 Err(DynamicsError::StateTransitionMatrixUnset)
121 }
122
123 /// Optionally performs some final changes after each successful integration of the equations of motion.
124 /// For example, this can be used to update the Guidance mode.
125 /// NOTE: This function is also called just prior to very first integration step in order to update the initial state if needed.
126 fn finally(
127 &self,
128 next_state: Self::StateType,
129 _almanac: Arc<Almanac>,
130 ) -> Result<Self::StateType, DynamicsError> {
131 Ok(next_state)
132 }
133}
134
135/// 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).
136///
137/// Examples include Solar Radiation Pressure, drag, etc., i.e. forces which do not need to save the current state, only act on it.
138pub trait ForceModel: Send + Sync + fmt::Display {
139 /// 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
140 fn estimation_index(&self) -> Option<usize>;
141
142 /// Defines the equations of motion for this force model from the provided osculating state.
143 fn eom(&self, ctx: &Spacecraft, almanac: Arc<Almanac>) -> Result<Vector3<f64>, DynamicsError>;
144
145 /// Force models must implement their partials, although those will only be called if the propagation requires the
146 /// computation of the STM. The `osc_ctx` is the osculating context, i.e. it changes for each sub-step of the integrator.
147 /// 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.
148 fn dual_eom(
149 &self,
150 osc_ctx: &Spacecraft,
151 almanac: Arc<Almanac>,
152 ) -> Result<(Vector3<f64>, Matrix4x3<f64>), DynamicsError>;
153}
154
155/// The `AccelModel` trait handles immutable dynamics which return an acceleration. Those can be added directly to Orbital Dynamics for example.
156///
157/// Examples include spherical harmonics, i.e. accelerations which do not need to save the current state, only act on it.
158pub trait AccelModel: Send + Sync + fmt::Display {
159 /// Defines the equations of motion for this force model from the provided osculating state in the integration frame.
160 fn eom(&self, osc: &Orbit, almanac: Arc<Almanac>) -> Result<Vector3<f64>, DynamicsError>;
161
162 /// Acceleration models must implement their partials, although those will only be called if the propagation requires the
163 /// computation of the STM.
164 fn dual_eom(
165 &self,
166 osc_ctx: &Orbit,
167 almanac: Arc<Almanac>,
168 ) -> Result<(Vector3<f64>, Matrix3<f64>), DynamicsError>;
169}
170
171/// Stores dynamical model errors
172#[derive(Debug, PartialEq, Snafu)]
173#[snafu(visibility(pub(crate)))]
174pub enum DynamicsError {
175 /// Fuel exhausted at the provided spacecraft state
176 #[snafu(display("fuel exhausted at {sc}"))]
177 FuelExhausted { sc: Box<Spacecraft> },
178 #[snafu(display("expected STM to be set"))]
179 StateTransitionMatrixUnset,
180 #[snafu(display("dynamical model encountered an astro error: {source}"))]
181 DynamicsAstro { source: AstroError },
182 #[snafu(display("dynamical model encountered an issue with the guidance: {source}"))]
183 DynamicsGuidance { source: GuidanceError },
184 #[snafu(display("dynamical model issue due to Almanac: {action} {source}"))]
185 DynamicsAlmanacError {
186 action: &'static str,
187 #[snafu(source(from(AlmanacError, Box::new)))]
188 source: Box<AlmanacError>,
189 },
190 #[snafu(display("dynamical model issue due to planetary data: {action} {source}"))]
191 DynamicsPlanetaryError {
192 action: &'static str,
193 source: PlanetaryDataError,
194 },
195}