Skip to main content

hpr_validate/
correction.rs

1//! A correction of the bias the simulators share, flown on a public flight:
2//! every motor's impulse scaled by one number and the drag by another, the rest of the flight as
3//! its report flies it.
4//!
5//! The motors are scaled through `hpr_analysis::montecarlo::dispersed_motor` at the rated burn
6//! time, which multiplies the thrust and the propellant's mass by the impulse scale, and the drag
7//! through `Simulation::with_drag_scale`: the same functions the fit's model of a boost uses
8//! (`hpr_forensics::fit`), so a scale carried from the fits means here what it meant there. Every
9//! motor of the rocket is scaled, in every configuration: one lit after a boost's cut, an upper
10//! stage's or a cluster's, is scaled too, since a correction in a flight's output wouldn't know
11//! which motors a log measured.
12
13use hpr_analysis::AnalysisError;
14use hpr_analysis::montecarlo::dispersed_motor;
15use hpr_atmos::ConstantWind;
16use hpr_design::Rocket;
17use hpr_sim::{Environment, SimError, Simulation};
18use serde::{Deserialize, Serialize};
19
20/// The two scales of a correction.
21#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
22pub struct Correction {
23    /// Every motor's total impulse over its rated impulse, at the rated burn time.
24    pub impulse_scale: f64,
25    /// The drag over the model's.
26    pub drag_scale: f64,
27}
28
29impl Correction {
30    /// No correction: both scales 1. Flown, it must be the flight its report flies.
31    pub const NONE: Self = Self {
32        impulse_scale: 1.0,
33        drag_scale: 1.0,
34    };
35
36    /// `rocket` with every motor of every configuration scaled by the impulse scale.
37    ///
38    /// # Errors
39    ///
40    /// A scale that isn't a positive number, or a motor whose propellant can't be scaled.
41    pub fn rocket(&self, rocket: &Rocket) -> Result<Rocket, AnalysisError> {
42        let mut rocket = rocket.clone();
43        for configuration in &mut rocket.configurations {
44            for mounted in &mut configuration.motors {
45                mounted.motor = dispersed_motor(&mounted.motor, self.impulse_scale, 1.0)?;
46            }
47        }
48        Ok(rocket)
49    }
50
51    /// `simulation` with its drag scaled by the drag scale.
52    ///
53    /// # Errors
54    ///
55    /// A drag scale that isn't a positive number.
56    pub fn simulation(&self, simulation: Simulation) -> Result<Simulation, SimError> {
57        simulation.with_drag_scale(self.drag_scale)
58    }
59}
60
61/// A public flight flown beside its report's flight: with or without a [`Correction`], with or
62/// without the tip-off phase (`Simulation::with_tip_off`; [what it moves on the real
63/// flights](https://hpr.fusionspace.co/physics/flight.html#the-tip-off-phase-on-the-real-flights)),
64/// and in its report's wind or in still air. Everything else is as the flight's report flies
65/// it: still air keeps the report's air (its pressure, temperature and density) and takes out
66/// only the wind. With no correction, no phase and the report's wind it is that report's flight
67/// itself.
68#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
69#[non_exhaustive]
70pub struct Variant {
71    /// The correction flown, or none: the motors and the drag as the report flies them.
72    pub correction: Option<Correction>,
73    /// Whether the flight flies the tip-off phase.
74    pub tip_off: bool,
75    /// Whether the wind is taken out: what the phase moves in still air is gravity's part alone.
76    pub still_air: bool,
77}
78
79impl Variant {
80    /// The report's own flight: no correction, no tip-off phase.
81    pub const GUIDED: Self = Self {
82        correction: None,
83        tip_off: false,
84        still_air: false,
85    };
86
87    /// The report's flight with the tip-off phase and no correction.
88    pub const TIP_OFF: Self = Self {
89        correction: None,
90        tip_off: true,
91        still_air: false,
92    };
93
94    /// [`Variant::GUIDED`] in still air.
95    pub const STILL_GUIDED: Self = Self {
96        still_air: true,
97        ..Self::GUIDED
98    };
99
100    /// [`Variant::TIP_OFF`] in still air.
101    pub const STILL_TIP_OFF: Self = Self {
102        still_air: true,
103        ..Self::TIP_OFF
104    };
105
106    /// `correction` flown, without the tip-off phase.
107    #[must_use]
108    pub fn corrected(correction: Correction) -> Self {
109        Self {
110            correction: Some(correction),
111            ..Self::GUIDED
112        }
113    }
114
115    /// `environment` with its wind taken out if the variant asks for still air.
116    #[must_use]
117    pub fn environment(&self, environment: Environment) -> Environment {
118        if self.still_air {
119            environment.with_wind(ConstantWind::calm())
120        } else {
121            environment
122        }
123    }
124
125    /// `rocket` as [`Correction::rocket`] scales it, or `None` with no correction: the rocket as
126    /// given.
127    ///
128    /// # Errors
129    ///
130    /// As [`Correction::rocket`].
131    pub fn rocket(&self, rocket: &Rocket) -> Result<Option<Rocket>, AnalysisError> {
132        self.correction.map(|c| c.rocket(rocket)).transpose()
133    }
134
135    /// `simulation` with the correction's drag scale, if any, and the tip-off phase if asked.
136    ///
137    /// # Errors
138    ///
139    /// As [`Correction::simulation`].
140    pub fn simulation(&self, simulation: Simulation) -> Result<Simulation, SimError> {
141        let simulation = match self.correction {
142            Some(correction) => correction.simulation(simulation)?,
143            None => simulation,
144        };
145        Ok(if self.tip_off {
146            simulation.with_tip_off()
147        } else {
148            simulation
149        })
150    }
151}
152
153#[cfg(test)]
154#[allow(
155    clippy::unwrap_used,
156    clippy::expect_used,
157    reason = "a test stops at the failure (clippy.toml)"
158)]
159mod tests {
160    use super::*;
161
162    /// A committed design with a motor, read from the repository.
163    fn bella_lui() -> Rocket {
164        let path = concat!(
165            env!("CARGO_MANIFEST_DIR"),
166            "/../../validation/designs/rocketpy-bella-lui.json"
167        );
168        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
169    }
170
171    fn impulses(rocket: &Rocket) -> Vec<f64> {
172        rocket
173            .configurations
174            .iter()
175            .flat_map(|c| c.motors.iter())
176            .map(|m| m.motor.curve().total_impulse_ns())
177            .collect()
178    }
179
180    #[test]
181    fn every_motor_is_scaled_by_the_impulse_scale() {
182        let rocket = bella_lui();
183        let rated = impulses(&rocket);
184        assert!(!rated.is_empty());
185        let scaled = Correction {
186            impulse_scale: 0.94,
187            drag_scale: 1.0,
188        }
189        .rocket(&rocket)
190        .unwrap();
191        for (rated, scaled) in rated.iter().zip(impulses(&scaled)) {
192            assert!((scaled / rated - 0.94).abs() < 1e-12, "{scaled} of {rated}");
193        }
194        // No correction leaves every motor's impulse as it was.
195        let same = Correction::NONE.rocket(&rocket).unwrap();
196        assert_eq!(impulses(&same), rated);
197    }
198
199    #[test]
200    fn a_scale_that_is_not_positive_is_refused() {
201        let rocket = bella_lui();
202        for impulse_scale in [0.0, -1.0, f64::NAN] {
203            let correction = Correction {
204                impulse_scale,
205                drag_scale: 1.0,
206            };
207            assert!(correction.rocket(&rocket).is_err(), "{impulse_scale}");
208        }
209    }
210
211    #[test]
212    fn a_variant_changes_only_what_it_names() {
213        use hpr_sim::{FlightSettings, Rail};
214        let rocket = bella_lui();
215        let site = hpr_core::geodesy::Geodetic {
216            latitude_rad: 0.8,
217            longitude_rad: 0.1,
218            height_m: 400.0,
219        };
220        let windy = Environment::standard(site)
221            .unwrap()
222            .with_wind(ConstantWind::new(6.0, 1.0).unwrap());
223        // Still air takes out the wind and keeps the air.
224        let still = Variant::STILL_GUIDED.environment(windy.clone());
225        assert_eq!(
226            still.wind.wind(500.0).unwrap().velocity_enu_m_s.length(),
227            0.0
228        );
229        assert!(windy.wind.wind(500.0).unwrap().velocity_enu_m_s.length() > 5.9);
230        assert_eq!(
231            still.atmosphere.air(500.0).unwrap(),
232            windy.atmosphere.air(500.0).unwrap()
233        );
234        // The report's wind is left as it is.
235        let kept = Variant::TIP_OFF.environment(windy.clone());
236        assert_eq!(
237            kept.wind.wind(500.0).unwrap(),
238            windy.wind.wind(500.0).unwrap()
239        );
240        // Only the tip-off variants ask for the phase, and only a correction scales the rocket.
241        let simulation = || {
242            Simulation::new(
243                &rocket,
244                "example",
245                windy.clone(),
246                Rail::vertical(5.0),
247                FlightSettings::default(),
248            )
249            .unwrap()
250        };
251        for (variant, phase) in [
252            (Variant::GUIDED, false),
253            (Variant::TIP_OFF, true),
254            (Variant::STILL_GUIDED, false),
255            (Variant::STILL_TIP_OFF, true),
256            (Variant::corrected(Correction::NONE), false),
257        ] {
258            assert_eq!(variant.simulation(simulation()).unwrap().tip_off(), phase);
259        }
260        assert!(Variant::TIP_OFF.rocket(&rocket).unwrap().is_none());
261        assert!(
262            Variant::corrected(Correction::NONE)
263                .rocket(&rocket)
264                .unwrap()
265                .is_some()
266        );
267    }
268}