Skip to main content

nyx_space/dynamics/sequence/
config.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*/
18use anise::frames::FrameUid;
19use anise::prelude::Almanac;
20use serde::{Deserialize, Serialize};
21use serde_dhall::{SimpleType, StaticType};
22use std::collections::HashMap;
23use std::sync::Arc;
24
25use crate::dynamics::{GravityField, OrbitalDynamics};
26use crate::dynamics::{SolidTides, SpacecraftDynamics};
27use crate::io::gravity::GravityFieldData;
28use crate::propagators::Propagator;
29use crate::{
30    dynamics::{
31        Drag, PointMasses, SolarPressure,
32        guidance::{Maneuver, ObjectiveEfficiency, ObjectiveWeight},
33    },
34    io::gravity::GravityFieldConfig,
35    propagators::{IntegratorMethod, IntegratorOptions},
36};
37
38use crate::dynamics::sequence::discrete_event::DiscreteEvent;
39
40#[cfg(feature = "python")]
41use pyo3::prelude::*;
42
43#[derive(Clone, Debug, Serialize, Deserialize)]
44pub enum Phase {
45    Terminate,
46    Activity {
47        name: String,
48        propagator: String,
49        guidance: Option<Box<GuidanceConfig>>,
50        /// The discrete event will be applied ONCE before the equation of motions are integrated.
51        on_entry: Option<Box<DiscreteEvent>>,
52        /// Allows disabling a phase without removing it
53        disabled: bool,
54    },
55}
56
57impl StaticType for Phase {
58    fn static_type() -> SimpleType {
59        let mut variants = HashMap::new();
60
61        // Handle the Vector(Vector3<f64>) variant
62        // Most math crates serialize Vector3 as a list of 3 doubles
63        variants.insert("Terminate".to_string(), None);
64
65        //  Activity variant (Record variant)
66        let mut activity_fields = HashMap::new();
67
68        activity_fields.insert("name".to_string(), String::static_type());
69        activity_fields.insert("propagator".to_string(), String::static_type());
70
71        // Use the StaticType impl of the boxed inner types
72        activity_fields.insert(
73            "guidance".to_string(),
74            <Option<GuidanceConfig> as StaticType>::static_type(),
75        );
76
77        activity_fields.insert(
78            "on_entry".to_string(),
79            <Option<DiscreteEvent> as StaticType>::static_type(),
80        );
81
82        activity_fields.insert("disabled".to_string(), bool::static_type());
83
84        variants.insert(
85            "Activity".to_string(),
86            Some(SimpleType::Record(activity_fields)),
87        );
88
89        SimpleType::Union(variants)
90    }
91}
92
93/// Dynamics defines the dynamical environment with a set of acceleration and force models
94#[derive(Clone, Debug, Serialize, Deserialize, StaticType)]
95#[cfg_attr(feature = "python", pyclass(from_py_object))]
96pub struct Dynamics {
97    pub accel_models: AccelModels,
98    pub force_models: ForceModels,
99}
100
101impl Dynamics {
102    pub fn build(&self, almanac: Arc<Almanac>) -> Result<SpacecraftDynamics, String> {
103        // Build the orbital dynamics
104        let mut orbital_dyn = OrbitalDynamics::two_body();
105        if let Some(point_masses) = &self.accel_models.point_masses {
106            orbital_dyn
107                .accel_models
108                .push(Arc::new(point_masses.clone()));
109        }
110        if let Some(gravity_cfg) = &self.accel_models.gravity_field {
111            let grav_data = GravityFieldData::from_config(gravity_cfg.clone(), &almanac)
112                .map_err(|e| e.to_string())?;
113            let gravity_field = GravityField::new(grav_data);
114            orbital_dyn.accel_models.push(gravity_field);
115        }
116        if let Some(solid_tides) = &self.accel_models.solid_tides {
117            orbital_dyn.accel_models.push(Arc::new(solid_tides.clone()));
118        }
119        // Build the spacecraft dynamics
120        let mut sc_dyn = SpacecraftDynamics::new(orbital_dyn);
121
122        if let Some(srp) = &self.force_models.solar_pressure {
123            sc_dyn.force_models.push(Arc::new(srp.clone()));
124        }
125
126        if let Some(drag) = &self.force_models.drag {
127            sc_dyn.force_models.push(Arc::new(*drag));
128        }
129
130        // And set it all up!
131        Ok(sc_dyn)
132    }
133}
134
135/// Propagator config includes the method, options, and all dynamics
136#[derive(Clone, Debug, Serialize, Deserialize, StaticType)]
137#[cfg_attr(feature = "python", pyclass(from_py_object))]
138pub struct PropagatorConfig {
139    pub dynamics: Dynamics,
140    pub method: IntegratorMethod,
141    pub options: IntegratorOptions,
142}
143
144impl PropagatorConfig {
145    pub fn build(&self, almanac: Arc<Almanac>) -> Result<Propagator<SpacecraftDynamics>, String> {
146        Ok(Propagator::new(
147            self.dynamics.build(almanac)?,
148            self.method,
149            self.options,
150        ))
151    }
152}
153
154/// Acceleration models alter the orbital dynamics
155#[derive(Clone, Default, Serialize, Deserialize, Debug)]
156#[cfg_attr(feature = "python", pyclass(from_py_object, get_all, set_all))]
157pub struct AccelModels {
158    pub point_masses: Option<PointMasses>,
159    pub gravity_field: Option<GravityFieldConfig>,
160    pub solid_tides: Option<SolidTides>,
161}
162
163/// Force models alter the spacecraft dynamics (they need a mass).
164#[derive(Clone, Default, Serialize, Deserialize, Debug)]
165#[cfg_attr(feature = "python", pyclass(from_py_object, get_all, set_all))]
166pub struct ForceModels {
167    pub solar_pressure: Option<SolarPressure>,
168    pub drag: Option<Drag>,
169}
170
171#[derive(Clone, Debug, Serialize, Deserialize, StaticType)]
172pub struct GuidanceConfig {
173    pub thruster_model: String,
174    pub disable_prop_mass: bool,
175    pub law: SteeringLaw,
176}
177
178// NOTE: Steering laws are not yet available in Python =(
179#[derive(Clone, Debug, Serialize, Deserialize, StaticType)]
180pub enum SteeringLaw {
181    FiniteBurn(Maneuver),
182    Kluever {
183        /// Stores the objectives, and their associated weights (set to zero to disable).
184        objectives: Vec<ObjectiveWeight>,
185        /// If defined, coast until vehicle is out of the provided eclipse state.
186        max_eclipse_prct: Option<f64>,
187    },
188    Ruggiero {
189        /// Stores the objectives, and their associated efficiency threshold (set to zero if not minimum efficiency).
190        objectives: Vec<ObjectiveEfficiency>,
191        /// If defined, coast until vehicle is out of the provided eclipse state.
192        max_eclipse_prct: Option<f64>,
193    },
194}
195
196impl StaticType for AccelModels {
197    fn static_type() -> serde_dhall::SimpleType {
198        let mut fields = HashMap::new();
199
200        fields.insert(
201            "point_masses".to_string(),
202            SimpleType::Optional(Box::new(PointMasses::static_type())),
203        );
204
205        #[allow(dead_code)]
206        #[derive(StaticType)]
207        struct GravityFieldDhall(GravityFieldConfig, FrameUid);
208
209        fields.insert(
210            "gravity_field".to_string(),
211            SimpleType::Optional(Box::new(GravityFieldDhall::static_type())),
212        );
213
214        fields.insert(
215            "solid_tides".to_string(),
216            SimpleType::Optional(Box::new(SolidTides::static_type())),
217        );
218
219        SimpleType::Record(fields)
220    }
221}
222
223impl StaticType for ForceModels {
224    fn static_type() -> serde_dhall::SimpleType {
225        let mut fields = HashMap::new();
226
227        fields.insert(
228            "solar_pressure".to_string(),
229            SimpleType::Optional(Box::new(SolarPressure::static_type())),
230        );
231
232        fields.insert(
233            "drag".to_string(),
234            SimpleType::Optional(Box::new(Drag::static_type())),
235        );
236
237        SimpleType::Record(fields)
238    }
239}