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