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::SpacecraftDynamics;
26use crate::dynamics::{GravityField, OrbitalDynamics};
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        // Build the spacecraft dynamics
117        let mut sc_dyn = SpacecraftDynamics::new(orbital_dyn);
118
119        if let Some(srp) = &self.force_models.solar_pressure {
120            sc_dyn.force_models.push(Arc::new(srp.clone()));
121        }
122
123        if let Some(drag) = &self.force_models.drag {
124            sc_dyn.force_models.push(Arc::new(*drag));
125        }
126
127        // And set it all up!
128        Ok(sc_dyn)
129    }
130}
131
132/// Propagator config includes the method, options, and all dynamics
133#[derive(Clone, Debug, Serialize, Deserialize, StaticType)]
134#[cfg_attr(feature = "python", pyclass(from_py_object))]
135pub struct PropagatorConfig {
136    pub dynamics: Dynamics,
137    pub method: IntegratorMethod,
138    pub options: IntegratorOptions,
139}
140
141impl PropagatorConfig {
142    pub fn build(&self, almanac: Arc<Almanac>) -> Result<Propagator<SpacecraftDynamics>, String> {
143        Ok(Propagator::new(
144            self.dynamics.build(almanac)?,
145            self.method,
146            self.options,
147        ))
148    }
149}
150
151/// Acceleration models alter the orbital dynamics
152#[derive(Clone, Default, Serialize, Deserialize, Debug)]
153#[cfg_attr(feature = "python", pyclass(from_py_object, get_all, set_all))]
154pub struct AccelModels {
155    pub point_masses: Option<PointMasses>,
156    pub gravity_field: Option<GravityFieldConfig>,
157}
158
159/// Force models alter the spacecraft dynamics (they need a mass).
160#[derive(Clone, Default, Serialize, Deserialize, Debug)]
161#[cfg_attr(feature = "python", pyclass(from_py_object, get_all, set_all))]
162pub struct ForceModels {
163    pub solar_pressure: Option<SolarPressure>,
164    pub drag: Option<Drag>,
165}
166
167#[derive(Clone, Debug, Serialize, Deserialize, StaticType)]
168pub struct GuidanceConfig {
169    pub thruster_model: String,
170    pub disable_prop_mass: bool,
171    pub law: SteeringLaw,
172}
173
174// NOTE: Steering laws are not yet available in Python =(
175#[derive(Clone, Debug, Serialize, Deserialize, StaticType)]
176pub enum SteeringLaw {
177    FiniteBurn(Maneuver),
178    Kluever {
179        /// Stores the objectives, and their associated weights (set to zero to disable).
180        objectives: Vec<ObjectiveWeight>,
181        /// If defined, coast until vehicle is out of the provided eclipse state.
182        max_eclipse_prct: Option<f64>,
183    },
184    Ruggiero {
185        /// Stores the objectives, and their associated efficiency threshold (set to zero if not minimum efficiency).
186        objectives: Vec<ObjectiveEfficiency>,
187        /// If defined, coast until vehicle is out of the provided eclipse state.
188        max_eclipse_prct: Option<f64>,
189    },
190}
191
192impl StaticType for AccelModels {
193    fn static_type() -> serde_dhall::SimpleType {
194        let mut fields = HashMap::new();
195
196        fields.insert(
197            "point_masses".to_string(),
198            SimpleType::Optional(Box::new(PointMasses::static_type())),
199        );
200
201        #[allow(dead_code)]
202        #[derive(StaticType)]
203        struct GravityFieldDhall(GravityFieldConfig, FrameUid);
204
205        fields.insert(
206            "gravity_field".to_string(),
207            SimpleType::Optional(Box::new(GravityFieldDhall::static_type())),
208        );
209
210        SimpleType::Record(fields)
211    }
212}
213
214impl StaticType for ForceModels {
215    fn static_type() -> serde_dhall::SimpleType {
216        let mut fields = HashMap::new();
217
218        fields.insert(
219            "solar_pressure".to_string(),
220            SimpleType::Optional(Box::new(SolarPressure::static_type())),
221        );
222
223        fields.insert(
224            "drag".to_string(),
225            SimpleType::Optional(Box::new(Drag::static_type())),
226        );
227
228        SimpleType::Record(fields)
229    }
230}