Skip to main content

hpr_sim/
histories.rs

1//! Thrust, and mass with the center of mass, against flight time, given from outside in place of
2//! the flight's own: for sizing the difference between two codes, not a model
3//! ([M2.3c11][m2-3c11], the increment that added them; [ADR-349][adr-349]).
4//!
5//! The gap between HPR Sim's apogee and another tool's is split into parts by swapping one input
6//! at a time for the other tool's ([ADR-226][adr-226]). A drag table swaps the drag
7//! ([`crate::Simulation::with_drag_table`]); these swap the thrust ([`ThrustHistory`]) and the
8//! mass and center of mass ([`MassHistory`]), each a list of samples at the other tool's own
9//! times.
10//!
11//! **Interpolation.** Between two samples `(t_i, y_i)` and `(t_{i+1}, y_{i+1})` a history is the
12//! straight line
13//!
14//! ```text
15//! y(t) = y_i + (y_{i+1} − y_i) (t − t_i) / (t_{i+1} − t_i)
16//! ```
17//!
18//! and before the first sample or after the last it holds that sample's value. So its rate is
19//! the slope of the piece it is on, finite everywhere, and its second derivative is zero inside
20//! a piece. The flight stops its integration steps at every sample where the slope changes, so
21//! no step and no difference stencil of the mass properties straddles a corner: inside a step
22//! the rates are the piece's slopes exactly.
23//!
24//! **Thrust.** The history's value is the thrust as flown, N, along the rocket's axis `+z_B`: it
25//! takes the place of the sum of the motors' thrusts with HPR Sim's correction for the air's
26//! pressure, which is not applied to it again. It acts at the mean of the nozzle exits of the
27//! motors lit by a known time, so a symmetric cluster's thrust has no moment, as HPR Sim's own
28//! has none, and an asymmetric cluster's moment is left out. HPR Sim's motors still set when a
29//! motor burns: its burnout event, the burning motors' cross-section taken off the base drag,
30//! and the mass flow behind jet damping and the nozzle's terms of the equations of motion
31//! (`docs/physics/flight.md`).
32//!
33//! **Mass.** The history gives the whole rocket's mass `m(t)` and its center of mass `x(t)`, m
34//! aft of the nose tip along the axis, the body origin `O`: in body axes the center of mass is
35//! `r = (r_x, r_y, −x)`, its lateral offsets HPR Sim's own. The mass rate `ṁ`, the center of
36//! mass's rate `r′` and its acceleration `r″` are the history's slopes and zero. The inertia
37//! about the center of mass `I_c` stays HPR Sim's, and the inertia about `O` is taken from it by
38//! the parallel-axis theorem with the history's mass and center:
39//!
40//! ```text
41//! I_O = I_c + m (|r|² E − r rᵀ)
42//! ```
43//!
44//! so the inertia's difference from the other tool's stays in the split's remainder.
45//!
46//! **Time.** A history's time is the flight's clock: 0 at launch.
47//!
48//! **What refuses a history.** A sample list that is empty, lists of different lengths, times
49//! that don't rise, a value that isn't finite, a negative thrust, a mass that isn't positive, a first sample after
50//! launch, or a thrust that doesn't end at zero (the history would stop while the motor still
51//! pushed); a thrust history on a flight with no motor lit by a known time; and either history
52//! on a flight that splits, by a separation or an ejection, or moves or releases a part, since a
53//! history is the whole stack's mass and thrust and gives no part's own. A history read from
54//! JSON (`{"times_s": [...], "thrust_n": [...]}`, or `mass_kg` and `cg_aft_of_nose_m` beside the
55//! times) passes the same checks as one built by its constructor.
56//!
57//! [adr-226]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0226-the-2026-10-10-review-the-gap-to-openrocket-by-cause.md
58//! [adr-349]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0349-m2-3c6-in-four-the-public-nose-probe-first.md
59//! [m2-3c11]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions-and-roadmap.md#m2-3c11
60
61use serde::{Deserialize, Serialize};
62
63use crate::error::SimError;
64
65/// One quantity against time: samples at rising times, read by straight lines between them.
66#[derive(Debug, Clone, PartialEq)]
67struct Samples {
68    times_s: Vec<f64>,
69    values: Vec<f64>,
70}
71
72impl Samples {
73    /// The samples, checked: as many values as times, at least one, every number finite, the
74    /// times rising, the first at or before launch.
75    fn new(history: &'static str, times_s: Vec<f64>, values: Vec<f64>) -> Result<Self, SimError> {
76        let refuse = |why: &'static str| SimError::History { history, why };
77        if times_s.len() != values.len() {
78            return Err(refuse("it holds another number of values than of times"));
79        }
80        let (Some(&first), Some(_)) = (times_s.first(), values.first()) else {
81            return Err(refuse("it holds no sample"));
82        };
83        if !times_s.iter().chain(&values).all(|x| x.is_finite()) {
84            return Err(refuse("a time or a value is not a finite number"));
85        }
86        if times_s.windows(2).any(|pair| pair[1] <= pair[0]) {
87            return Err(refuse("its times don't rise from each sample to the next"));
88        }
89        if first > 0.0 {
90            return Err(refuse(
91                "its first sample comes after launch, so it doesn't cover the flight's start",
92            ));
93        }
94        Ok(Self { times_s, values })
95    }
96
97    /// The value at `t_s`: the line through the samples either side, or the first or last
98    /// sample's value outside them; not a number at a time that isn't one.
99    fn at(&self, t_s: f64) -> f64 {
100        if t_s.is_nan() {
101            return f64::NAN;
102        }
103        let times = &self.times_s;
104        let after = times.partition_point(|&t| t <= t_s);
105        if after == 0 {
106            return self.values[0];
107        }
108        if after == times.len() {
109            return self.values[times.len() - 1];
110        }
111        let (t0, t1) = (times[after - 1], times[after]);
112        let (y0, y1) = (self.values[after - 1], self.values[after]);
113        // `a + w (b − a)` keeps the samples' own values at the ends of a piece.
114        y0 + (y1 - y0) * ((t_s - t0) / (t1 - t0))
115    }
116
117    /// Whether the slope changes at sample `index`: an end, or a corner between two pieces.
118    fn corner(&self, index: usize) -> bool {
119        if index == 0 || index + 1 >= self.times_s.len() {
120            return true;
121        }
122        let slope = |i: usize| {
123            (self.values[i + 1] - self.values[i]) / (self.times_s[i + 1] - self.times_s[i])
124        };
125        slope(index - 1) != slope(index)
126    }
127
128    /// The times of the corners, the ends among them.
129    fn corners_s(&self) -> impl Iterator<Item = f64> + '_ {
130        (0..self.times_s.len())
131            .filter(|&index| self.corner(index))
132            .map(|index| self.times_s[index])
133    }
134
135    /// Whether the value changes anywhere inside `(a, b)`.
136    fn varies_within(&self, (a, b): (f64, f64)) -> bool {
137        let times = &self.times_s;
138        // The pieces that overlap `(a, b)`: from the one holding `a` to the one holding `b`.
139        let first = times.partition_point(|&t| t <= a).saturating_sub(1);
140        let last = times.partition_point(|&t| t < b).min(times.len() - 1);
141        (first..last).any(|i| self.values[i + 1] != self.values[i])
142    }
143}
144
145/// A thrust against flight time, N, flown in place of the motors' (the [module][self] says what
146/// stays HPR Sim's). It serializes as its `times_s` and `thrust_n` and is checked again when
147/// read.
148#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
149#[serde(try_from = "ThrustHistoryData", into = "ThrustHistoryData")]
150pub struct ThrustHistory {
151    thrust: Samples,
152}
153
154impl ThrustHistory {
155    /// The thrust `thrust_n[i]` at flight time `times_s[i]`.
156    ///
157    /// # Errors
158    ///
159    /// [`SimError::History`] if the lists differ in length or are empty, a number isn't finite,
160    /// the times don't rise, the first comes after launch (`0`), a thrust is negative, or the
161    /// last isn't zero.
162    pub fn new(times_s: Vec<f64>, thrust_n: Vec<f64>) -> Result<Self, SimError> {
163        let thrust = Samples::new("thrust", times_s, thrust_n)?;
164        let refuse = |why: &'static str| SimError::History {
165            history: "thrust",
166            why,
167        };
168        if thrust.values.iter().any(|&f| f < 0.0) {
169            return Err(refuse("a thrust is negative"));
170        }
171        if thrust.values.last().is_some_and(|&f| f != 0.0) {
172            return Err(refuse(
173                "its last thrust isn't zero, so it would stop while the motor still pushed",
174            ));
175        }
176        Ok(Self { thrust })
177    }
178
179    /// The thrust at flight time `t_s`, N.
180    #[must_use]
181    pub fn thrust_n(&self, t_s: f64) -> f64 {
182        self.thrust.at(t_s)
183    }
184
185    /// The sample times, s.
186    #[must_use]
187    pub fn times_s(&self) -> &[f64] {
188        &self.thrust.times_s
189    }
190}
191
192/// A mass and center of mass against flight time, flown in place of the design's (the
193/// [module][self] says what stays HPR Sim's). It serializes as its `times_s`, `mass_kg` and
194/// `cg_aft_of_nose_m` and is checked again when read.
195#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
196#[serde(try_from = "MassHistoryData", into = "MassHistoryData")]
197pub struct MassHistory {
198    mass: Samples,
199    cg: Samples,
200}
201
202impl MassHistory {
203    /// The mass `mass_kg[i]` and center of mass `cg_aft_of_nose_m[i]`, m aft of the nose tip, at
204    /// flight time `times_s[i]`.
205    ///
206    /// # Errors
207    ///
208    /// [`SimError::History`] if the lists differ in length or are empty, a number isn't finite,
209    /// the times don't rise, the first comes after launch (`0`), or a mass isn't positive.
210    pub fn new(
211        times_s: Vec<f64>,
212        mass_kg: Vec<f64>,
213        cg_aft_of_nose_m: Vec<f64>,
214    ) -> Result<Self, SimError> {
215        let mass = Samples::new("mass", times_s.clone(), mass_kg)?;
216        let cg = Samples::new("mass", times_s, cg_aft_of_nose_m)?;
217        if mass.values.iter().any(|&m| m <= 0.0) {
218            return Err(SimError::History {
219                history: "mass",
220                why: "a mass isn't positive",
221            });
222        }
223        Ok(Self { mass, cg })
224    }
225
226    /// The mass at flight time `t_s`, kg.
227    #[must_use]
228    pub fn mass_kg(&self, t_s: f64) -> f64 {
229        self.mass.at(t_s)
230    }
231
232    /// The center of mass at flight time `t_s`, m aft of the nose tip.
233    #[must_use]
234    pub fn cg_aft_of_nose_m(&self, t_s: f64) -> f64 {
235        self.cg.at(t_s)
236    }
237
238    /// The sample times, s.
239    #[must_use]
240    pub fn times_s(&self) -> &[f64] {
241        &self.mass.times_s
242    }
243
244    /// Whether the mass or the center of mass changes inside `window`.
245    pub(crate) fn varies_within(&self, window: (f64, f64)) -> bool {
246        self.mass.varies_within(window) || self.cg.varies_within(window)
247    }
248}
249
250/// The serialized form of a [`ThrustHistory`].
251#[derive(Serialize, Deserialize)]
252#[serde(deny_unknown_fields)]
253struct ThrustHistoryData {
254    times_s: Vec<f64>,
255    thrust_n: Vec<f64>,
256}
257
258impl TryFrom<ThrustHistoryData> for ThrustHistory {
259    type Error = SimError;
260
261    fn try_from(data: ThrustHistoryData) -> Result<Self, SimError> {
262        Self::new(data.times_s, data.thrust_n)
263    }
264}
265
266impl From<ThrustHistory> for ThrustHistoryData {
267    fn from(history: ThrustHistory) -> Self {
268        Self {
269            times_s: history.thrust.times_s,
270            thrust_n: history.thrust.values,
271        }
272    }
273}
274
275/// The serialized form of a [`MassHistory`]: one list of times for both quantities.
276#[derive(Serialize, Deserialize)]
277#[serde(deny_unknown_fields)]
278struct MassHistoryData {
279    times_s: Vec<f64>,
280    mass_kg: Vec<f64>,
281    cg_aft_of_nose_m: Vec<f64>,
282}
283
284impl TryFrom<MassHistoryData> for MassHistory {
285    type Error = SimError;
286
287    fn try_from(data: MassHistoryData) -> Result<Self, SimError> {
288        Self::new(data.times_s, data.mass_kg, data.cg_aft_of_nose_m)
289    }
290}
291
292impl From<MassHistory> for MassHistoryData {
293    fn from(history: MassHistory) -> Self {
294        Self {
295            times_s: history.mass.times_s,
296            mass_kg: history.mass.values,
297            cg_aft_of_nose_m: history.cg.values,
298        }
299    }
300}
301
302/// The histories a flight takes in place of its own, and where a thrust history acts.
303#[derive(Debug, Clone, Default, PartialEq)]
304pub(crate) struct Histories {
305    pub(crate) thrust: Option<ThrustHistory>,
306    /// The mean of the lit motors' nozzle exits in body axes, m: where the thrust acts.
307    pub(crate) nozzle_m: hpr_core::DVec3,
308    pub(crate) mass: Option<MassHistory>,
309}
310
311impl Histories {
312    /// The times the integration stops at: every corner of either history, sorted, after `0`.
313    pub(crate) fn corners_s(&self) -> Vec<f64> {
314        let mut times: Vec<f64> = self
315            .thrust
316            .iter()
317            .flat_map(|h| h.thrust.corners_s())
318            .chain(
319                self.mass
320                    .iter()
321                    .flat_map(|h| h.mass.corners_s().chain(h.cg.corners_s())),
322            )
323            .filter(|t| *t > 0.0)
324            .collect();
325        times.sort_by(f64::total_cmp);
326        times.dedup();
327        times
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    fn refusal(error: SimError) -> (&'static str, &'static str) {
336        match error {
337            SimError::History { history, why } => (history, why),
338            other => panic!("not a history's refusal: {other}"),
339        }
340    }
341
342    #[test]
343    fn a_history_reads_the_line_between_samples_and_holds_its_ends() {
344        let h = ThrustHistory::new(vec![0.0, 0.5, 2.0], vec![10.0, 40.0, 0.0]).unwrap();
345        assert_eq!(h.thrust_n(-1.0), 10.0);
346        assert_eq!(h.thrust_n(0.0), 10.0);
347        assert_eq!(h.thrust_n(0.5), 40.0);
348        assert_eq!(h.thrust_n(2.0), 0.0);
349        assert_eq!(h.thrust_n(9.0), 0.0);
350        // 10 + 30 × 0.25 / 0.5, and 40 − 40 × 0.75 / 1.5.
351        assert!((h.thrust_n(0.25) - 25.0).abs() < 1e-12);
352        assert!((h.thrust_n(1.25) - 20.0).abs() < 1e-12);
353        assert!(h.thrust_n(f64::NAN).is_nan());
354    }
355
356    #[test]
357    fn a_history_read_from_json_round_trips_and_is_checked_as_built() {
358        let thrust = ThrustHistory::new(vec![0.0, 0.5, 2.0], vec![10.0, 40.0, 0.0]).unwrap();
359        let text = serde_json::to_string(&thrust).unwrap();
360        assert_eq!(
361            text,
362            r#"{"times_s":[0.0,0.5,2.0],"thrust_n":[10.0,40.0,0.0]}"#
363        );
364        assert_eq!(
365            serde_json::from_str::<ThrustHistory>(&text).unwrap(),
366            thrust
367        );
368        let mass = MassHistory::new(vec![0.0, 1.0], vec![2.0, 1.5], vec![0.5, 0.45]).unwrap();
369        let text = serde_json::to_string(&mass).unwrap();
370        assert_eq!(
371            text,
372            r#"{"times_s":[0.0,1.0],"mass_kg":[2.0,1.5],"cg_aft_of_nose_m":[0.5,0.45]}"#
373        );
374        assert_eq!(serde_json::from_str::<MassHistory>(&text).unwrap(), mass);
375
376        // Each refusal of the constructors holds for a history read from JSON.
377        let refused = |text: &str| {
378            serde_json::from_str::<ThrustHistory>(text)
379                .unwrap_err()
380                .to_string()
381        };
382        for (text, why) in [
383            (r#"{"times_s":[],"thrust_n":[]}"#, "it holds no sample"),
384            (
385                r#"{"times_s":[1.0,0.5],"thrust_n":[3.0,0.0]}"#,
386                "its times don't rise from each sample to the next",
387            ),
388            (
389                r#"{"times_s":[0.0,1.0],"thrust_n":[-5.0,0.0]}"#,
390                "a thrust is negative",
391            ),
392            (
393                r#"{"times_s":[0.0,1.0],"thrust_n":[5.0,3.0]}"#,
394                "its last thrust isn't zero",
395            ),
396        ] {
397            let message = refused(text);
398            assert!(message.contains(why), "{text}: {message}");
399        }
400        let mass_refused = serde_json::from_str::<MassHistory>(
401            r#"{"times_s":[0.0],"mass_kg":[1.0,1.0,1.0],"cg_aft_of_nose_m":[0.5]}"#,
402        )
403        .unwrap_err()
404        .to_string();
405        assert!(
406            mass_refused.contains("it holds another number of values than of times"),
407            "{mass_refused}"
408        );
409        // A field the history doesn't have is refused, not dropped.
410        assert!(
411            serde_json::from_str::<ThrustHistory>(r#"{"times_s":[0.0],"thrust_n":[0.0],"cg":[]}"#)
412                .is_err()
413        );
414    }
415
416    #[test]
417    fn corners_leave_out_samples_on_a_straight_line() {
418        let h = ThrustHistory::new(
419            vec![-0.1, 0.0, 1.0, 2.0, 3.0, 4.0],
420            vec![0.0, 0.0, 5.0, 10.0, 0.0, 0.0],
421        )
422        .unwrap();
423        // 1.0 lies on the line from 0 to 2, and the ends always count; -0.1 is before launch.
424        let histories = Histories {
425            thrust: Some(h),
426            ..Histories::default()
427        };
428        assert_eq!(histories.corners_s(), vec![2.0, 3.0, 4.0]);
429    }
430
431    #[test]
432    fn a_mass_history_varies_only_where_its_samples_change() {
433        let h = MassHistory::new(
434            vec![0.0, 1.0, 2.0, 3.0],
435            vec![2.0, 1.5, 1.5, 1.5],
436            vec![0.5, 0.45, 0.45, 0.45],
437        )
438        .unwrap();
439        assert!(h.varies_within((0.2, 0.3)));
440        assert!(h.varies_within((0.9, 1.1)));
441        assert!(!h.varies_within((1.0, 2.5)));
442        assert!(!h.varies_within((2.5, 9.0)));
443        assert!((h.mass_kg(0.5) - 1.75).abs() < 1e-15);
444        assert!((h.cg_aft_of_nose_m(0.5) - 0.475).abs() < 1e-15);
445    }
446
447    #[test]
448    fn bad_samples_are_refused_with_why() {
449        let thrust = |t: Vec<f64>, f: Vec<f64>| refusal(ThrustHistory::new(t, f).unwrap_err());
450        assert_eq!(
451            thrust(vec![0.0, 1.0], vec![1.0]).1,
452            "it holds another number of values than of times"
453        );
454        assert_eq!(thrust(vec![], vec![]).1, "it holds no sample");
455        assert_eq!(
456            thrust(vec![0.0, f64::NAN], vec![1.0, 0.0]).1,
457            "a time or a value is not a finite number"
458        );
459        assert_eq!(
460            thrust(vec![0.0, 1.0, 1.0], vec![1.0, 1.0, 0.0]).1,
461            "its times don't rise from each sample to the next"
462        );
463        assert_eq!(
464            thrust(vec![0.1, 1.0], vec![1.0, 0.0]).1,
465            "its first sample comes after launch, so it doesn't cover the flight's start"
466        );
467        assert_eq!(
468            thrust(vec![0.0, 1.0], vec![-1.0, 0.0]).1,
469            "a thrust is negative"
470        );
471        assert_eq!(
472            thrust(vec![0.0, 1.0], vec![1.0, 0.5]),
473            (
474                "thrust",
475                "its last thrust isn't zero, so it would stop while the motor still pushed"
476            )
477        );
478        let mass =
479            refusal(MassHistory::new(vec![0.0, 1.0], vec![1.0, 0.0], vec![0.5, 0.5]).unwrap_err());
480        assert_eq!(mass, ("mass", "a mass isn't positive"));
481    }
482}