Skip to main content

hpr_motor/
motor.rs

1//! The solid motor model: thrust, propellant consumption, and the motor's mass, center of mass and
2//! inertia at any time in the burn.
3//!
4//! **Consumption by impulse fraction.** With a constant effective exhaust velocity `c = F/ṁ`
5//! (NASA SP-8039, glossary p. 95), the propellant burned by time `t` is in proportion to the
6//! impulse delivered:
7//!
8//! ```text
9//! c = I_total / m_p0,   ṁ(t) = F(t) / c,   m_p(t) = m_p0 (1 − I(t)/I_total)
10//! ```
11//!
12//! This is RocketPy's `SolidMotor` consumption (`rocketpy/motors/solid_motor.py:401-418`,
13//! `motor.py:483-524`), and the mass column of ThrustCurve.org's `.rse` files follows it
14//! (`docs/format/rse.md`). It is an approximation: the real `c` drifts as the nozzle erodes
15//! (SP-8039 p. 14), and its efficiency differs with chamber pressure between motors (SP-8039
16//! Fig. 18, p. 40). All propellant is gone when the thrust curve ends.
17//!
18//! **Where the propellant is.** A [`Propellant::Column`] keeps its shape and loses density as it
19//! burns, so its center stays put and its inertia scales with its mass (the model of RocketPy's
20//! `GenericMotor`). [`Propellant::Grains`] regress as BATES grains ([`crate::grains`]).
21//!
22//! **The whole motor** combines the propellant with the dry mass (case, closures, nozzle, liner)
23//! about the instantaneous center of mass ([`MassElement::combine`]).
24//!
25//! **Ambient pressure.** A curve measured at reference pressure `p_ref` gives, at ambient `p_a`,
26//! `F = F_ref + (p_ref − p_a) A_e` (from SP-8039 eq. 2, `F = ṁ u_e + (p_e − p_a) A_e`, with the
27//! flow unchanged; RocketPy's `Motor.pressure_thrust`, `motor.py:1173-1191`). It holds while the
28//! nozzle flows full (this project's inference from SP-8039 pp. 32–34). See `docs/physics/motor.md`.
29
30use std::f64::consts::PI;
31
32use serde::{Deserialize, Serialize};
33
34use crate::curve::ThrustCurve;
35use crate::error::MotorError;
36use crate::grains::BatesGrains;
37use crate::mass::MassElement;
38
39/// What a motor whose figures imply an impossible exhaust velocity should check: the hint that
40/// ends that refusal's message, so a program can show it apart from the fact (`hpr` writes it as
41/// a `help:` line).
42pub const UNITS_HINT: &str = "check the units of the masses and the curve";
43
44/// Standard sea-level pressure (US Standard Atmosphere 1976), Pa.
45///
46/// A thrust curve's reference pressure is the ambient pressure where the motor was static-tested,
47/// which motor files and catalogs don't record; this value is only a stand-in when the test site's
48/// pressure is unknown.
49pub const STANDARD_SEA_LEVEL_PRESSURE_PA: f64 = 101_325.0;
50
51/// A propellant charge of fixed shape whose density falls as it burns.
52#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
53#[serde(deny_unknown_fields)]
54pub struct PropellantColumn {
55    /// Initial propellant mass, kg.
56    pub mass_kg: f64,
57    /// Center of the column along the motor axis, m from the nozzle exit.
58    pub center_m: f64,
59    /// Outer radius, m.
60    pub outer_radius_m: f64,
61    /// Inner (bore) radius, m; zero for a solid column.
62    pub inner_radius_m: f64,
63    /// Length, m.
64    pub length_m: f64,
65}
66
67/// How the propellant is laid out and how its shape evolves. Serialized with a `model` tag
68/// (`"column"`, `"grains"`).
69///
70/// Not `Copy`, so that a later model can hold tabulated data.
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
72#[serde(tag = "model", rename_all = "snake_case")]
73#[non_exhaustive]
74pub enum Propellant {
75    /// A fixed-shape column: the default when only a motor's envelope is known.
76    Column(PropellantColumn),
77    /// BATES grains that regress on their bores and ends.
78    Grains(BatesGrains),
79}
80
81/// A nozzle, for the ambient-pressure correction of thrust.
82#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
83#[serde(deny_unknown_fields)]
84pub struct Nozzle {
85    /// Exit radius, m.
86    pub exit_radius_m: f64,
87    /// Throat radius, m, when known (informational: the thrust curve already carries its effect).
88    pub throat_radius_m: Option<f64>,
89    /// The ambient pressure the thrust curve was measured at, Pa: the static test site's. The
90    /// thrust is then corrected to the ambient pressure in flight.
91    ///
92    /// `None` flies the curve as it is at every ambient pressure, with no correction. That is
93    /// RocketPy's default (`Motor(reference_pressure=None)`, whose `pressure_thrust` is then zero,
94    /// `motor.py:1188-1189`), so a RocketPy input transcribed into HPR Sim says `None`.
95    ///
96    /// Which to give: motor files don't record where the curve was measured. For a motor tested
97    /// near sea level, [`STANDARD_SEA_LEVEL_PRESSURE_PA`] adds the thrust a higher site gains
98    /// (16 kPa × `A_e` at 1,400 m); `None` leaves it out. A design must say which: the field is
99    /// required, as `null` for `None`, so leaving it out is an error rather than a silent choice.
100    /// Motors read from `.eng` or `.rse` files, or from the catalog, carry no nozzle and so no
101    /// correction.
102    #[serde(deserialize_with = "Option::deserialize")]
103    // Required, and `null` allowed: `required` alone would drop the `null`.
104    #[schemars(required, extend("type" = ["number", "null"]))]
105    pub reference_pressure_pa: Option<f64>,
106}
107
108impl Nozzle {
109    /// The exit area `A_e = π r_e²`, m².
110    pub fn exit_area_m2(&self) -> f64 {
111        PI * self.exit_radius_m * self.exit_radius_m
112    }
113}
114
115/// A solid rocket motor.
116///
117/// Nothing here can tell a hybrid's thrust curve from a solid's, so the checks are at the edges:
118/// [`crate::catalog::CatalogMotor::motor`] refuses hybrids and the `.rse` reader warns about them
119/// (`.eng` files don't say).
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
121#[serde(try_from = "MotorData", into = "MotorData")]
122pub struct SolidMotor {
123    curve: ThrustCurve,
124    propellant: Propellant,
125    dry: MassElement,
126    nozzle: Option<Nozzle>,
127    /// `m_p0`, kg.
128    propellant_mass_kg: f64,
129}
130
131/// The serialized form of a [`SolidMotor`].
132#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
133#[serde(deny_unknown_fields)]
134struct MotorData {
135    curve: ThrustCurve,
136    propellant: Propellant,
137    dry: MassElement,
138    nozzle: Option<Nozzle>,
139}
140
141impl TryFrom<MotorData> for SolidMotor {
142    type Error = MotorError;
143
144    fn try_from(data: MotorData) -> Result<Self, Self::Error> {
145        Self::new(data.curve, data.propellant, data.dry, data.nozzle)
146    }
147}
148
149impl From<SolidMotor> for MotorData {
150    fn from(motor: SolidMotor) -> Self {
151        Self {
152            curve: motor.curve,
153            propellant: motor.propellant,
154            dry: motor.dry,
155            nozzle: motor.nozzle,
156        }
157    }
158}
159
160/// A motor's thrust and mass properties at one time.
161#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
162pub struct MotorState {
163    /// Time since ignition, s.
164    pub time_s: f64,
165    /// Thrust from the curve (at its reference pressure), N.
166    pub thrust_n: f64,
167    /// Propellant consumption rate `ṁ = F/c`, kg/s (non-negative; the motor's mass falls at this
168    /// rate).
169    pub mass_flow_kg_s: f64,
170    /// The propellant left, about its own center of mass.
171    pub propellant: MassElement,
172    /// The whole motor (dry mass plus propellant), about the motor's center of mass.
173    pub total: MassElement,
174}
175
176/// The effective exhaust velocity `c = I/m_p` a solid motor's curve and propellant mass have to
177/// imply, m/s.
178///
179/// Measured over the 1,708 ThrustCurve.org simulator files with both a parsed impulse and a
180/// propellant mass in their motor's ThrustCurve.org record, `c` runs 236 to 3,031 m/s, with a
181/// median of 1,866 and 90% of them between 928 and 2,210 (the full table is in
182/// `docs/research/exhaust-velocity-guard.md`). The record's mass is not the one the bundled
183/// catalog flies: since issue #295 each motor's index masses are its default file's header, and
184/// the record's is kept only for comparison ([`crate::CatalogMotor::stated`]). The bulk is APCP;
185/// most of the tail below about 900 m/s is black powder (64 of its 83 files).
186///
187/// **The bound rejects none of those 1,708.** It is not a filter on propellant: it is there to
188/// catch a mass-unit slip, grams given as kilograms, which moves `c` by a factor of 1,000: the
189/// worked example in [`SolidMotor::from_envelope`]'s test lands at 1.8 m/s. `c` doesn't depend on
190/// the motor's size, so sizes given in millimeters pass it. The headroom is real but not great at
191/// either end. Over the record-mass survey both ends are data errors: the lowest, 1.18x above
192/// the floor, is a Cesaroni E75 record giving 104 g of propellant for a 52 g motor, and the
193/// highest, 1.65x below the ceiling, a misfiled curve. The lowest entry NAR's list backs, the
194/// Quest B4, is 1.85x above the floor. On the header masses the catalog flies, the highest is the
195/// Ellis J228 at 4,128.18 m/s, 1.21x below the ceiling. A small motor whose recorded propellant
196/// mass is too large for its impulse could fall through the floor; issue #11 records the
197/// fallback, which is to apply the bound only above a couple of grams.
198pub const EXHAUST_VELOCITY_RANGE_M_S: std::ops::RangeInclusive<f64> = 200.0..=5000.0;
199
200impl SolidMotor {
201    /// Builds a motor from its thrust curve, propellant, dry mass (about its own center) and
202    /// optional nozzle.
203    ///
204    /// # Errors
205    ///
206    /// - [`MotorError::Domain`] for a non-positive or non-finite dry mass (the motor at burnout,
207    ///   whose center of mass needs some mass), a negative or non-finite dry inertia, a non-finite
208    ///   position, a column with non-positive mass, radius or length, a nozzle with a non-positive
209    ///   exit radius, a throat radius outside `(0, exit radius]`, or a negative or non-finite
210    ///   reference pressure.
211    /// - [`MotorError::Inconsistent`] for a column bore at least as wide as the column, bad grain
212    ///   geometry ([`BatesGrains::validate`]), or a curve and propellant mass whose effective
213    ///   exhaust velocity `I/m_p` is outside [`EXHAUST_VELOCITY_RANGE_M_S`], which is what a
214    ///   propellant mass in the wrong unit looks like. Sizes can't be checked this way.
215    pub fn new(
216        curve: ThrustCurve,
217        propellant: Propellant,
218        dry: MassElement,
219        nozzle: Option<Nozzle>,
220    ) -> Result<Self, MotorError> {
221        dry.validate([
222            "dry mass (kg)",
223            "dry center of mass (m)",
224            "dry axial inertia (kg·m²)",
225            "dry transverse inertia (kg·m²)",
226        ])?;
227        if dry.mass_kg <= 0.0 {
228            return Err(MotorError::Domain {
229                what: "dry mass (kg), which must be positive",
230                value: dry.mass_kg,
231            });
232        }
233        let propellant_mass_kg = match &propellant {
234            Propellant::Column(column) => {
235                for (value, what) in [
236                    (column.mass_kg, "propellant mass (kg)"),
237                    (column.outer_radius_m, "propellant outer radius (m)"),
238                    (column.length_m, "propellant length (m)"),
239                ] {
240                    if !(value.is_finite() && value > 0.0) {
241                        return Err(MotorError::Domain { what, value });
242                    }
243                }
244                if !column.center_m.is_finite() {
245                    return Err(MotorError::Domain {
246                        what: "propellant center (m)",
247                        value: column.center_m,
248                    });
249                }
250                if !(column.inner_radius_m.is_finite() && column.inner_radius_m >= 0.0) {
251                    return Err(MotorError::Domain {
252                        what: "propellant bore radius (m)",
253                        value: column.inner_radius_m,
254                    });
255                }
256                if column.inner_radius_m >= column.outer_radius_m {
257                    return Err(MotorError::Inconsistent(format!(
258                        "propellant bore radius {} m is not inside the outer radius {} m",
259                        column.inner_radius_m, column.outer_radius_m
260                    )));
261                }
262                column.mass_kg
263            }
264            Propellant::Grains(grains) => {
265                grains.validate()?;
266                grains.initial_mass_kg()
267            }
268        };
269        if let Some(nozzle) = &nozzle {
270            if !(nozzle.exit_radius_m.is_finite() && nozzle.exit_radius_m > 0.0) {
271                return Err(MotorError::Domain {
272                    what: "nozzle exit radius (m)",
273                    value: nozzle.exit_radius_m,
274                });
275            }
276            if let Some(throat) = nozzle.throat_radius_m
277                && !(throat.is_finite() && throat > 0.0 && throat <= nozzle.exit_radius_m)
278            {
279                return Err(MotorError::Domain {
280                    what: "nozzle throat radius (m), which must be in (0, exit radius]",
281                    value: throat,
282                });
283            }
284            if let Some(reference) = nozzle.reference_pressure_pa
285                && !(reference.is_finite() && reference >= 0.0)
286            {
287                return Err(MotorError::Domain {
288                    what: "thrust-curve reference pressure (Pa)",
289                    value: reference,
290                });
291            }
292        }
293        // A mass-unit slip is the failure this catches: the 411I175 built from grams read as
294        // kilograms is accepted by every check above, and flies with an effective exhaust velocity
295        // of 1.8 m/s. Its sizes in millimeters don't change `c`, so nothing here can catch them.
296        let exhaust_velocity_m_s = curve.total_impulse_ns() / propellant_mass_kg;
297        if !EXHAUST_VELOCITY_RANGE_M_S.contains(&exhaust_velocity_m_s) {
298            return Err(MotorError::Inconsistent(format!(
299                "a total impulse of {} N·s from {propellant_mass_kg} kg of propellant is an \
300                 effective exhaust velocity of {exhaust_velocity_m_s} m/s. A solid motor can have \
301                 only {} to {} m/s; {UNITS_HINT}",
302                curve.total_impulse_ns(),
303                EXHAUST_VELOCITY_RANGE_M_S.start(),
304                EXHAUST_VELOCITY_RANGE_M_S.end()
305            )));
306        }
307        Ok(Self {
308            curve,
309            propellant,
310            dry,
311            nozzle,
312            propellant_mass_kg,
313        })
314    }
315
316    /// A motor known only by its envelope, as in a motor file or catalog: diameter `D`, length `L`,
317    /// propellant mass and loaded mass.
318    ///
319    /// The assumptions are crude, and a motor with measured data should be built with
320    /// [`SolidMotor::new`] instead:
321    ///
322    /// - the propellant is a solid column of radius `D/2` filling the length, centered at `L/2`;
323    /// - the dry mass (loaded minus propellant) is a thin tube of radius `D/2` and length `L`,
324    ///   centered at `L/2`;
325    /// - no nozzle is known, so thrust gets no ambient-pressure correction.
326    ///
327    /// # Errors
328    ///
329    /// [`MotorError::Domain`] for a non-positive or non-finite dimension or propellant mass, and
330    /// [`MotorError::Inconsistent`] when the propellant mass is not below the loaded mass (the
331    /// motor would weigh nothing at burnout), or when the curve and the propellant mass imply an
332    /// effective exhaust velocity outside [`EXHAUST_VELOCITY_RANGE_M_S`], which is what masses
333    /// given in grams look like. Sizes given in millimeters don't change it, so this check can't
334    /// catch them.
335    pub fn from_envelope(
336        curve: ThrustCurve,
337        diameter_m: f64,
338        length_m: f64,
339        propellant_mass_kg: f64,
340        loaded_mass_kg: f64,
341    ) -> Result<Self, MotorError> {
342        for (value, what) in [
343            (propellant_mass_kg, "propellant mass (kg)"),
344            (loaded_mass_kg, "loaded motor mass (kg)"),
345            (diameter_m, "motor diameter (m)"),
346            (length_m, "motor length (m)"),
347        ] {
348            if !(value.is_finite() && value > 0.0) {
349                return Err(MotorError::Domain { what, value });
350            }
351        }
352        if propellant_mass_kg >= loaded_mass_kg {
353            return Err(MotorError::Inconsistent(format!(
354                "propellant mass {propellant_mass_kg} kg is not below the loaded mass \
355                 {loaded_mass_kg} kg"
356            )));
357        }
358        let radius = 0.5 * diameter_m;
359        let center = 0.5 * length_m;
360        let column = PropellantColumn {
361            mass_kg: propellant_mass_kg,
362            center_m: center,
363            outer_radius_m: radius,
364            inner_radius_m: 0.0,
365            length_m,
366        };
367        let dry = MassElement::thin_tube(
368            loaded_mass_kg - propellant_mass_kg,
369            center,
370            radius,
371            length_m,
372        );
373        Self::new(curve, Propellant::Column(column), dry, None)
374    }
375
376    /// The same motor with more dry mass, such as a reload's case and closures (when the loaded
377    /// mass excludes them) or a motor retainer, combined about the new dry center of mass.
378    ///
379    /// # Errors
380    ///
381    /// [`MotorError::Domain`] for a negative or non-finite mass or inertia, or a non-finite
382    /// position.
383    pub fn with_added_dry_mass(mut self, hardware: MassElement) -> Result<Self, MotorError> {
384        hardware.validate([
385            "added dry mass (kg)",
386            "added dry mass center (m)",
387            "added dry axial inertia (kg·m²)",
388            "added dry transverse inertia (kg·m²)",
389        ])?;
390        self.dry = MassElement::combine([&self.dry, &hardware]);
391        Ok(self)
392    }
393
394    /// The thrust curve.
395    pub fn curve(&self) -> &ThrustCurve {
396        &self.curve
397    }
398
399    /// The propellant model.
400    pub fn propellant(&self) -> &Propellant {
401        &self.propellant
402    }
403
404    /// The dry mass, about its own center of mass.
405    pub fn dry(&self) -> MassElement {
406        self.dry
407    }
408
409    /// The nozzle, when known.
410    pub fn nozzle(&self) -> Option<Nozzle> {
411        self.nozzle
412    }
413
414    /// The propellant mass at ignition `m_p0`, kg.
415    pub fn propellant_initial_mass_kg(&self) -> f64 {
416        self.propellant_mass_kg
417    }
418
419    /// The effective exhaust velocity `c = I_total / m_p0`, m/s.
420    pub fn exhaust_velocity_m_s(&self) -> f64 {
421        self.curve.total_impulse_ns() / self.propellant_mass_kg
422    }
423
424    /// The time the thrust curve ends and the propellant is gone, s.
425    pub fn burnout_time_s(&self) -> f64 {
426        self.curve.end_time_s()
427    }
428
429    /// The propellant left at time `t`, `m_p0 (1 − I(t)/I_total)`, kg. A NaN time gives NaN.
430    pub fn propellant_mass_kg(&self, t: f64) -> f64 {
431        if t.is_nan() {
432            return f64::NAN;
433        }
434        let fraction = self.curve.impulse_ns(t) / self.curve.total_impulse_ns();
435        (self.propellant_mass_kg * (1.0 - fraction)).max(0.0)
436    }
437
438    /// The mass flow at `t`, kg/s: the `mass_flow_kg_s` of [`SolidMotor::state`], `F(t) / v_e`,
439    /// without the grains' shape and the mass elements that call also builds.
440    pub fn mass_flow_kg_s(&self, t: f64) -> f64 {
441        self.curve.thrust_n(t) / self.exhaust_velocity_m_s()
442    }
443
444    /// The thrust and mass properties at `t` seconds after ignition. Before ignition the motor is
445    /// loaded and after burnout it is empty.
446    pub fn state(&self, t: f64) -> MotorState {
447        let thrust_n = self.curve.thrust_n(t);
448        let mass = self.propellant_mass_kg(t);
449        let propellant = match &self.propellant {
450            Propellant::Column(column) => MassElement::hollow_cylinder(
451                mass,
452                column.center_m,
453                column.outer_radius_m,
454                column.inner_radius_m,
455                column.length_m,
456            ),
457            Propellant::Grains(grains) => grains.mass_element(mass),
458        };
459        MotorState {
460            time_s: t,
461            thrust_n,
462            mass_flow_kg_s: thrust_n / self.exhaust_velocity_m_s(),
463            propellant,
464            total: MassElement::combine([&self.dry, &propellant]),
465        }
466    }
467
468    /// The thrust at `t` with ambient pressure `ambient_pa`, N: `F + (p_ref − p_a) A_e`, with the
469    /// nozzle's [`Nozzle::reference_pressure_pa`], strictly inside the burn (`0 < t < t_end`, as
470    /// RocketPy's flight applies it) where the curve's thrust is positive, never below zero; the
471    /// curve's thrust elsewhere, without a nozzle, and with a nozzle that gives no reference
472    /// pressure. A NaN time gives NaN, and so does a NaN ambient pressure where the term applies.
473    ///
474    /// The term is the full-flow value throughout, so the thrust steps by it just after ignition
475    /// and again at `t_end` (both events for an integrator), and in the ignition transient and the
476    /// tail-off, where a real nozzle's exit pressure is far from its full-flow value, it misstates
477    /// the thrust (`docs/physics/motor.md`).
478    pub fn thrust_at_pressure_n(&self, t: f64, ambient_pa: f64) -> f64 {
479        let thrust = self.curve.thrust_n(t);
480        match self.nozzle {
481            Some(
482                nozzle @ Nozzle {
483                    reference_pressure_pa: Some(reference_pa),
484                    ..
485                },
486            ) if t > 0.0 && t < self.curve.end_time_s() && (thrust > 0.0 || thrust.is_nan()) => {
487                let corrected = thrust + (reference_pa - ambient_pa) * nozzle.exit_area_m2();
488                if corrected.is_nan() {
489                    corrected
490                } else {
491                    corrected.max(0.0)
492                }
493            }
494            _ => thrust,
495        }
496    }
497}
498
499#[cfg(test)]
500mod tests {
501    use super::*;
502
503    fn curve() -> ThrustCurve {
504        ThrustCurve::new(vec![0.0, 0.1, 1.0, 1.2], vec![0.0, 500.0, 400.0, 0.0]).unwrap()
505    }
506
507    #[test]
508    fn column_mass_follows_the_impulse_fraction() {
509        let motor = SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.3, 0.6).unwrap();
510        let total = motor.curve().total_impulse_ns();
511        assert!((total - (25.0 + 405.0 + 40.0)).abs() < 1e-12);
512        assert!((motor.exhaust_velocity_m_s() - total / 0.3).abs() < 1e-9);
513        for t in [-1.0, 0.0, 0.05, 0.5, 1.1, 1.2, 5.0] {
514            let state = motor.state(t);
515            let expected = 0.3 * (1.0 - motor.curve().impulse_ns(t) / total);
516            assert!((state.propellant.mass_kg - expected).abs() < 1e-15, "{t}");
517            assert!((state.total.mass_kg - (0.3 + expected)).abs() < 1e-15);
518            assert!(
519                (state.mass_flow_kg_s * motor.exhaust_velocity_m_s() - state.thrust_n).abs() < 1e-9
520            );
521        }
522        assert_eq!(motor.state(0.0).propellant.mass_kg, 0.3);
523        assert_eq!(motor.state(1.2).propellant.mass_kg, 0.0);
524        // The ṁ integral is the propellant burned: trapezoids on a fine grid.
525        let n = 12_000;
526        let dt = 1.2 / f64::from(n);
527        let burned: f64 = (0..n)
528            .map(|i| {
529                let (a, b) = (f64::from(i) * dt, f64::from(i + 1) * dt);
530                0.5 * (motor.state(a).mass_flow_kg_s + motor.state(b).mass_flow_kg_s) * dt
531            })
532            .sum();
533        assert!((burned - 0.3).abs() < 1e-6, "{burned}");
534    }
535
536    #[test]
537    fn the_mass_flow_alone_is_the_states_to_the_bit() {
538        // The flight reads `mass_flow_kg_s` instead of the state's for speed; the two must stay
539        // one expression, or a flight's numbers change with the shortcut.
540        let motor = SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.3, 0.6).unwrap();
541        // The burn on a fine grid, so that even a last-bit change in the expression shows, and
542        // the times before ignition and after burnout.
543        let grid = (0..=1_200).map(|i| f64::from(i) * 1e-3);
544        for t in [-1.0, 5.0].into_iter().chain(grid) {
545            assert_eq!(
546                motor.mass_flow_kg_s(t).to_bits(),
547                motor.state(t).mass_flow_kg_s.to_bits(),
548                "{t}"
549            );
550        }
551    }
552
553    #[test]
554    fn a_units_slip_is_refused_by_its_exhaust_velocity() {
555        // The worked example from the issue: the 411I175's envelope in millimeters and grams,
556        // read as meters and kilograms. Every dimension is positive and finite, the propellant is
557        // below the loaded mass, and the motor is nonsense: 437.5 kg of motor, and 411 N·s from
558        // 228.9 kg of propellant is an exhaust velocity of 1.8 m/s.
559        let i175 = ThrustCurve::new(vec![0.0, 0.1, 2.3, 2.4], vec![0.0, 220.0, 150.0, 0.0])
560            .expect("a plausible I-class curve");
561        // 425.5 N·s: an I by the NFPA classes, which is what the designation says.
562        let impulse = i175.total_impulse_ns();
563        assert!((impulse - 425.5).abs() < 0.1, "{impulse}");
564        let slipped = SolidMotor::from_envelope(i175.clone(), 38.0, 245.0, 228.9, 437.5)
565            .expect_err("millimeters and grams read as meters and kilograms");
566        assert!(
567            matches!(&slipped, MotorError::Inconsistent(message)
568                if message.contains("exhaust velocity") && message.contains("check the units")),
569            "{slipped}"
570        );
571        // The same motor in SI is accepted: 38 mm by 245 mm, 228.9 g of propellant, 437.5 g
572        // loaded, c = 1,859 m/s, which is within 0.5% of the median, 1,866 m/s, of the 1,708
573        // surveyed files.
574        let motor = SolidMotor::from_envelope(i175.clone(), 0.038, 0.245, 0.2289, 0.4375)
575            .expect("the same motor in meters and kilograms");
576        let c = motor.curve().total_impulse_ns() / motor.propellant_mass_kg(0.0);
577        assert!((1700.0..1900.0).contains(&c), "{c}");
578
579        // The bound is on the physics, not on which constructor was used.
580        let dry = MassElement::thin_tube(0.2086, 0.1225, 0.019, 0.245);
581        let column = PropellantColumn {
582            mass_kg: 2.289,
583            center_m: 0.1225,
584            outer_radius_m: 0.017,
585            inner_radius_m: 0.005,
586            length_m: 0.2,
587        };
588        let ten_times = SolidMotor::new(i175, Propellant::Column(column), dry, None)
589            .expect_err("ten times the propellant for the same impulse");
590        assert!(
591            // 425.5 N·s over 2.289 kg is 185.9 m/s, just under the floor.
592            matches!(&ten_times, MotorError::Inconsistent(message) if message.contains("185.8")),
593            "{ten_times}"
594        );
595
596        assert!(!EXHAUST_VELOCITY_RANGE_M_S.contains(&1.8));
597    }
598
599    #[test]
600    fn every_bundled_motor_is_inside_the_range() {
601        // The check's other half: a bound real motors fall outside is a bug, not a check. This
602        // builds every bundled motor with a file that reads rather than asserting a remembered pair
603        // of numbers: the doc's figures
604        // came out of the catalog's stored impulse once, which is not what the check divides.
605        let catalog = crate::Catalog::bundled().expect("the bundled catalog parses");
606        let mut lowest = f64::INFINITY;
607        let mut highest: f64 = 0.0;
608        let (mut low_name, mut high_name) = (String::new(), String::new());
609        for entry in catalog.motors.iter().filter(|m| !m.curves.is_empty()) {
610            let motor = entry
611                .bundled_motor()
612                .unwrap_or_else(|error| panic!("{}: {error}", entry.designation));
613            let c = motor.curve().total_impulse_ns() / motor.propellant_mass_kg(0.0);
614            assert!(
615                EXHAUST_VELOCITY_RANGE_M_S.contains(&c),
616                "{}: c = {c} m/s",
617                entry.designation
618            );
619            if c < lowest {
620                lowest = c;
621                low_name = entry.common_name.clone();
622            }
623            if c > highest {
624                highest = c;
625                high_name = entry.common_name.clone();
626            }
627        }
628        // `docs/physics/motor.md` quotes these; they are measured here so the doc cannot drift.
629        assert!((lowest - 296.83).abs() < 0.01, "{low_name} at {lowest}");
630        assert!((highest - 4128.18).abs() < 0.01, "{high_name} at {highest}");
631    }
632
633    #[test]
634    fn a_curve_ending_above_zero_is_empty_and_silent_at_its_end() {
635        let cut = ThrustCurve::new(vec![0.0, 1.0], vec![20.0, 20.0]).unwrap();
636        // 20 N·s from 10 g is c = 2,000 m/s, which is what APCP does; the 200 g this used to burn
637        // was 100 m/s, and `EXHAUST_VELOCITY_RANGE_M_S` now refuses it.
638        let motor = SolidMotor::from_envelope(cut, 0.038, 0.25, 0.01, 0.5).unwrap();
639        let before = motor.state(1.0 - 1e-9);
640        assert_eq!(before.thrust_n, 20.0);
641        assert!(before.mass_flow_kg_s > 0.0 && before.propellant.mass_kg > 0.0);
642        let end = motor.state(motor.burnout_time_s());
643        assert_eq!(
644            (end.thrust_n, end.mass_flow_kg_s, end.propellant.mass_kg),
645            (0.0, 0.0, 0.0)
646        );
647        assert_eq!(end.total.mass_kg, 0.49);
648    }
649
650    #[test]
651    fn envelope_defaults_are_centered_tubes_and_columns() {
652        let motor = SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.3, 0.6).unwrap();
653        let loaded = motor.state(0.0);
654        assert_eq!(loaded.total.cg_m, 0.125);
655        let r2 = 0.019f64 * 0.019;
656        let dry_axial = 0.3 * r2;
657        let prop_axial = 0.5 * 0.3 * r2;
658        assert!((loaded.total.axial_inertia_kg_m2 - (dry_axial + prop_axial)).abs() < 1e-15);
659        let dry_t = 0.3 * (r2 / 2.0 + 0.25f64.powi(2) / 12.0);
660        let prop_t = 0.3 * (r2 / 4.0 + 0.25f64.powi(2) / 12.0);
661        assert!((loaded.total.transverse_inertia_kg_m2 - (dry_t + prop_t)).abs() < 1e-15);
662        assert!(motor.nozzle().is_none());
663        assert_eq!(
664            motor.thrust_at_pressure_n(0.5, 0.0),
665            motor.curve().thrust_n(0.5)
666        );
667    }
668
669    #[test]
670    fn pressure_correction_uses_the_exit_area() {
671        let dry = MassElement::thin_tube(0.3, 0.125, 0.019, 0.25);
672        let column = PropellantColumn {
673            mass_kg: 0.3,
674            center_m: 0.15,
675            outer_radius_m: 0.017,
676            inner_radius_m: 0.005,
677            length_m: 0.2,
678        };
679        let nozzle = Nozzle {
680            exit_radius_m: 0.01,
681            throat_radius_m: Some(0.004),
682            reference_pressure_pa: Some(STANDARD_SEA_LEVEL_PRESSURE_PA),
683        };
684        let motor =
685            SolidMotor::new(curve(), Propellant::Column(column), dry, Some(nozzle)).unwrap();
686        let area = PI * 1e-4;
687        let f = motor.curve().thrust_n(0.5);
688        let vacuum = motor.thrust_at_pressure_n(0.5, 0.0);
689        assert!((vacuum - (f + 101_325.0 * area)).abs() < 1e-9);
690        assert_eq!(motor.thrust_at_pressure_n(0.5, 101_325.0), f);
691        assert_eq!(motor.thrust_at_pressure_n(2.0, 0.0), 0.0);
692        assert_eq!(motor.thrust_at_pressure_n(0.001, 1e9), 0.0);
693        // The curve's own reference pressure is used: tested at altitude, it gains less in vacuum.
694        let high = SolidMotor::new(
695            curve(),
696            Propellant::Column(column),
697            dry,
698            Some(Nozzle {
699                reference_pressure_pa: Some(80_000.0),
700                ..nozzle
701            }),
702        )
703        .unwrap();
704        assert!((high.thrust_at_pressure_n(0.5, 0.0) - (f + 80_000.0 * area)).abs() < 1e-9);
705        assert!((high.thrust_at_pressure_n(0.5, 101_325.0) - (f - 21_325.0 * area)).abs() < 1e-9);
706        // With no reference pressure, as RocketPy's `Motor(reference_pressure=None)`, the curve is
707        // flown as it is at every pressure: its `pressure_thrust` is zero (`motor.py:1188-1189`).
708        let uncorrected = SolidMotor::new(
709            curve(),
710            Propellant::Column(column),
711            dry,
712            Some(Nozzle {
713                reference_pressure_pa: None,
714                ..nozzle
715            }),
716        )
717        .unwrap();
718        for pressure in [0.0, 50_000.0, 101_325.0, 1e9] {
719            assert_eq!(uncorrected.thrust_at_pressure_n(0.5, pressure), f);
720        }
721        // A design says which it means: `null` is no correction, and leaving the key out is an
722        // error, not a quiet `None`.
723        let read = |text: &str| serde_json::from_str::<Nozzle>(text);
724        assert_eq!(
725            read(
726                r#"{"exit_radius_m": 0.01, "throat_radius_m": null, "reference_pressure_pa": null}"#
727            )
728            .unwrap()
729            .reference_pressure_pa,
730            None
731        );
732        assert!(read(r#"{"exit_radius_m": 0.01, "throat_radius_m": null}"#).is_err());
733        // Only strictly inside the burn: nothing is added at ignition or at the last sample.
734        assert_eq!(motor.thrust_at_pressure_n(0.0, 0.0), 0.0);
735        assert_eq!(motor.thrust_at_pressure_n(1.2, 0.0), 0.0);
736        assert!(motor.thrust_at_pressure_n(0.5, f64::NAN).is_nan());
737        assert!(motor.thrust_at_pressure_n(f64::NAN, 0.0).is_nan());
738        // A NaN time gives NaN mass properties, for columns and grains alike.
739        let state = motor.state(f64::NAN);
740        assert!(state.total.mass_kg.is_nan() && state.propellant.mass_kg.is_nan());
741        assert!(state.total.cg_m.is_nan());
742        // No flow, no pressure term: a zero-thrust gap inside the burn gets none. The thrusts are
743        // 400 N rather than the 10 N this used to use, so that 0.3 kg of propellant implies
744        // c = 1,990 m/s instead of 50 m/s, which `EXHAUST_VELOCITY_RANGE_M_S` refuses.
745        let gap = ThrustCurve::new(
746            vec![0.0, 1.0, 1.0, 2.0, 2.0, 3.0],
747            vec![400.0, 400.0, 0.0, 0.0, 400.0, 0.0],
748        )
749        .unwrap();
750        let gapped = SolidMotor::new(gap, Propellant::Column(column), dry, Some(nozzle)).unwrap();
751        assert_eq!(gapped.thrust_at_pressure_n(1.5, 0.0), 0.0);
752        assert!(gapped.thrust_at_pressure_n(2.5, 0.0) > gapped.curve().thrust_n(2.5));
753    }
754
755    #[test]
756    fn rejects_bad_inputs() {
757        let dry = MassElement::thin_tube(0.3, 0.125, 0.019, 0.25);
758        let column = PropellantColumn {
759            mass_kg: 0.3,
760            center_m: 0.15,
761            outer_radius_m: 0.017,
762            inner_radius_m: 0.005,
763            length_m: 0.2,
764        };
765        let build = |column: PropellantColumn, dry: MassElement, nozzle: Option<Nozzle>| {
766            SolidMotor::new(curve(), Propellant::Column(column), dry, nozzle)
767        };
768        assert!(build(column, dry, None).is_ok());
769        assert!(
770            build(
771                PropellantColumn {
772                    mass_kg: 0.0,
773                    ..column
774                },
775                dry,
776                None
777            )
778            .is_err()
779        );
780        assert!(
781            build(
782                PropellantColumn {
783                    inner_radius_m: 0.017,
784                    ..column
785                },
786                dry,
787                None
788            )
789            .is_err()
790        );
791        assert!(
792            build(
793                PropellantColumn {
794                    center_m: f64::NAN,
795                    ..column
796                },
797                dry,
798                None
799            )
800            .is_err()
801        );
802        assert!(
803            build(
804                column,
805                MassElement {
806                    mass_kg: -0.1,
807                    ..dry
808                },
809                None
810            )
811            .is_err()
812        );
813        // No dry mass: nothing would be left at burnout to have a center of mass.
814        assert!(
815            build(
816                column,
817                MassElement {
818                    mass_kg: 0.0,
819                    ..dry
820                },
821                None
822            )
823            .is_err()
824        );
825        let nozzle = |exit, throat, reference| {
826            Some(Nozzle {
827                exit_radius_m: exit,
828                throat_radius_m: throat,
829                reference_pressure_pa: Some(reference),
830            })
831        };
832        assert!(build(column, dry, nozzle(0.01, Some(0.004), 101_325.0)).is_ok());
833        assert!(build(column, dry, nozzle(0.0, None, 101_325.0)).is_err());
834        assert!(build(column, dry, nozzle(0.01, Some(0.02), 101_325.0)).is_err());
835        assert!(build(column, dry, nozzle(0.01, None, -1.0)).is_err());
836        assert!(build(column, dry, nozzle(0.01, None, f64::NAN)).is_err());
837        assert!(SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.7, 0.6).is_err());
838        assert!(SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.6, 0.6).is_err());
839        assert!(matches!(
840            SolidMotor::from_envelope(curve(), 0.038, 0.25, f64::NAN, 0.6),
841            Err(MotorError::Domain {
842                what: "propellant mass (kg)",
843                ..
844            })
845        ));
846        assert!(SolidMotor::from_envelope(curve(), 0.0, 0.25, 0.3, 0.6).is_err());
847    }
848
849    #[test]
850    fn added_hardware_joins_the_dry_mass() {
851        let motor = SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.3, 0.6).unwrap();
852        let retainer = MassElement::thin_tube(0.05, -0.01, 0.022, 0.02);
853        let with = motor.clone().with_added_dry_mass(retainer).unwrap();
854        let burnout = with.state(with.burnout_time_s()).total;
855        let expected = MassElement::combine([&motor.dry(), &retainer]);
856        assert_eq!(
857            burnout,
858            MassElement::combine([
859                &expected,
860                &MassElement {
861                    cg_m: 0.125,
862                    ..MassElement::ZERO
863                }
864            ])
865        );
866        assert!((burnout.mass_kg - 0.35).abs() < 1e-15);
867        assert!(burnout.cg_m < 0.125);
868        assert!(
869            motor
870                .with_added_dry_mass(MassElement {
871                    mass_kg: f64::NAN,
872                    ..retainer
873                })
874                .is_err()
875        );
876    }
877
878    #[derive(Debug, serde::Deserialize)]
879    struct Oracle {
880        oracle: String,
881        cases: Vec<OracleCase>,
882    }
883
884    #[derive(Debug, serde::Deserialize)]
885    struct OracleCase {
886        name: String,
887        inputs: OracleInputs,
888        scalars: OracleScalars,
889        series: OracleSeries,
890    }
891
892    #[derive(Debug, serde::Deserialize)]
893    struct OracleInputs {
894        thrust_file: String,
895        thrust_file_sha256: String,
896        dry_mass: f64,
897        dry_inertia: [f64; 3],
898        center_of_dry_mass_position: f64,
899        nozzle_position: f64,
900        nozzle_radius: f64,
901        throat_radius: f64,
902        grain_number: u32,
903        grain_density: f64,
904        grain_outer_radius: f64,
905        grain_initial_inner_radius: f64,
906        grain_initial_height: f64,
907        grain_separation: f64,
908        grains_center_of_mass_position: f64,
909        coordinate_system_orientation: String,
910        only_radial_burn: bool,
911        interpolation_method: String,
912        burn_time: Option<f64>,
913    }
914
915    #[derive(Debug, serde::Deserialize)]
916    struct OracleScalars {
917        total_impulse_ns: f64,
918        burn_out_time_s: f64,
919        exhaust_velocity_mps: f64,
920        propellant_initial_mass_kg: f64,
921    }
922
923    #[derive(Debug, serde::Deserialize)]
924    struct OracleSeries {
925        time_s: Vec<f64>,
926        thrust: Vec<f64>,
927        mass_flow_rate: Vec<f64>,
928        propellant_mass: Vec<f64>,
929        total_mass: Vec<f64>,
930        center_of_propellant_mass: Vec<f64>,
931        center_of_mass: Vec<f64>,
932        grain_inner_radius: Vec<f64>,
933        grain_height: Vec<f64>,
934        #[serde(rename = "propellant_I_11")]
935        propellant_i_11: Vec<f64>,
936        #[serde(rename = "propellant_I_33")]
937        propellant_i_33: Vec<f64>,
938        #[serde(rename = "I_11")]
939        i_11: Vec<f64>,
940        #[serde(rename = "I_33")]
941        i_33: Vec<f64>,
942    }
943
944    /// M1.3's done-when: mass and inertia evolution matches RocketPy's `SolidMotor` for three
945    /// motors within 1%. The fixture comes from `validation/oracles/rocketpy/solid_motor.py`,
946    /// which runs RocketPy 1.13.0 on three bundled curves with BATES grain loads.
947    ///
948    /// Each quantity's error is relative to RocketPy's value, except where the value itself goes
949    /// to zero (thrust, flow, and the propellant's mass and inertias): there it is relative to the
950    /// peak or ignition value, and a grain height that burns away is relative to its initial
951    /// height. Positions are compared in hpr's motor frame (meters forward of the nozzle exit),
952    /// relative to the motor's length.
953    ///
954    /// Measured: every error is below 1e-4. At RocketPy's own ODE knots hpr's exact web matches
955    /// RocketPy's bore and height to about 1e-9, so the residual is RocketPy's linear interpolation
956    /// between knots. The test holds 0.1%, ten times tighter than the done-when, so a regression
957    /// shows long before 1%. It also pins the two figures the motor page quotes: the largest
958    /// propellant-mass gap relative to RocketPy's own value before burnout, and the largest
959    /// center-of-mass gap. Because inputs and outputs share the frame mapping, loaded and
960    /// burned-out centers are also checked against values worked by hand from the cases' layouts.
961    #[test]
962    fn matches_rocketpy_solid_motor_for_three_bundled_motors() {
963        let oracle: Oracle = serde_json::from_str(include_str!(
964            "../../../validation/fixtures/motor/rocketpy-solid-motor.json"
965        ))
966        .unwrap();
967        assert_eq!(oracle.oracle, "rocketpy 1.13.0");
968        assert_eq!(oracle.cases.len(), 3);
969        let catalog = crate::catalog::Catalog::bundled().unwrap();
970        // The largest propellant-mass gap relative to RocketPy's own value, its case and
971        // RocketPy's mass there; and the largest center-of-mass gap over the motor's length.
972        let mut own_gap = (0.0, String::new(), 0.0);
973        let mut center_gap: f64 = 0.0;
974        for case in &oracle.cases {
975            let inputs = &case.inputs;
976            let (entry, curve) = catalog
977                .motors
978                .iter()
979                .find_map(|m| {
980                    m.curves
981                        .iter()
982                        .find(|c| c.file == inputs.thrust_file)
983                        .map(|c| (m, c))
984                })
985                .unwrap();
986            // The oracle read the same bytes the crate bundles.
987            assert_eq!(curve.sha256, inputs.thrust_file_sha256, "{}", case.name);
988            let text = crate::catalog::bundled_curve_text(&curve.file).unwrap();
989            let thrust = entry.thrust_curve(curve, text).unwrap();
990
991            // RocketPy positions are along its own axis from its own origin; hpr's run forward
992            // from the nozzle exit.
993            let sign = match inputs.coordinate_system_orientation.as_str() {
994                "nozzle_to_combustion_chamber" => 1.0,
995                "combustion_chamber_to_nozzle" => -1.0,
996                other => panic!("unknown orientation {other}"),
997            };
998            let to_hpr = |z: f64| sign * (z - inputs.nozzle_position);
999            let grains = BatesGrains {
1000                count: inputs.grain_number,
1001                density_kg_m3: inputs.grain_density,
1002                outer_radius_m: inputs.grain_outer_radius,
1003                initial_inner_radius_m: inputs.grain_initial_inner_radius,
1004                initial_height_m: inputs.grain_initial_height,
1005                separation_m: inputs.grain_separation,
1006                center_m: to_hpr(inputs.grains_center_of_mass_position),
1007                inhibited_ends: inputs.only_radial_burn,
1008            };
1009            let dry = MassElement {
1010                mass_kg: inputs.dry_mass,
1011                cg_m: to_hpr(inputs.center_of_dry_mass_position),
1012                axial_inertia_kg_m2: inputs.dry_inertia[2],
1013                transverse_inertia_kg_m2: inputs.dry_inertia[0],
1014            };
1015            let nozzle = Nozzle {
1016                exit_radius_m: inputs.nozzle_radius,
1017                throat_radius_m: Some(inputs.throat_radius),
1018                reference_pressure_pa: Some(STANDARD_SEA_LEVEL_PRESSURE_PA),
1019            };
1020            let motor =
1021                SolidMotor::new(thrust, Propellant::Grains(grains), dry, Some(nozzle)).unwrap();
1022            // The fixture must describe the model compared: linear thrust, the whole curve.
1023            assert_eq!(inputs.interpolation_method, "linear");
1024            assert_eq!(inputs.burn_time, None);
1025            // Centers in hpr's frame, worked by hand from each case's layout (meters forward of
1026            // the nozzle exit): the dry mass and grains at loaded, the dry mass at burnout.
1027            let hand = match case.name.as_str() {
1028                // Nozzle exit at 0: dry 0.2086 kg at 0.11, grains 0.2289391 kg at 0.13.
1029                "cti-411i175-38mm-radial-burnout" => (0.2086, 0.11, 0.13),
1030                // Axis from the forward closure to the nozzle exit at 0.404: dry at 0.25 and grains
1031                // at 0.19 from the closure are 0.154 and 0.214 forward of the exit.
1032                "cti-1633k940-54mm-axial-burnout-chamber-to-nozzle" => (0.5985, 0.154, 0.214),
1033                // Nozzle exit at 0: dry 1.731 kg at 0.50, grains at 0.56.
1034                "loki-m1378lr-54mm-inhibited-ends" => (1.731, 0.50, 0.56),
1035                other => panic!("no hand values for {other}"),
1036            };
1037            let (dry_kg, dry_z, grains_z) = hand;
1038            let m_p = case.scalars.propellant_initial_mass_kg;
1039            let loaded_cg = (dry_kg * dry_z + m_p * grains_z) / (dry_kg + m_p);
1040            assert!(
1041                (motor.state(0.0).total.cg_m - loaded_cg).abs() < 1e-12,
1042                "{}",
1043                case.name
1044            );
1045            assert!(
1046                (motor.state(motor.burnout_time_s()).total.cg_m - dry_z).abs() < 1e-12,
1047                "{}",
1048                case.name
1049            );
1050
1051            let scalars = &case.scalars;
1052            let close = |a: f64, b: f64| (a - b).abs() <= 1e-9 * b.abs();
1053            assert!(
1054                close(motor.curve().total_impulse_ns(), scalars.total_impulse_ns),
1055                "{}",
1056                case.name
1057            );
1058            assert!(
1059                close(motor.burnout_time_s(), scalars.burn_out_time_s),
1060                "{}",
1061                case.name
1062            );
1063            assert!(close(
1064                motor.propellant_initial_mass_kg(),
1065                scalars.propellant_initial_mass_kg
1066            ));
1067            assert!(close(
1068                motor.exhaust_velocity_m_s(),
1069                scalars.exhaust_velocity_mps
1070            ));
1071
1072            let series = &case.series;
1073            let length = entry.length_mm * 1e-3;
1074            let mut worst: Vec<(&str, f64)> = Vec::new();
1075            let mut record = |what: &'static str, error: f64| match worst
1076                .iter_mut()
1077                .find(|(name, _)| *name == what)
1078            {
1079                Some((_, max)) => *max = max.max(error),
1080                None => worst.push((what, error)),
1081            };
1082            let loaded = motor.state(0.0);
1083            let peak_flow = motor.curve().peak_thrust_n() / motor.exhaust_velocity_m_s();
1084            for (i, &t) in series.time_s.iter().enumerate() {
1085                let state = motor.state(t);
1086                let shape = grains.shape(state.propellant.mass_kg);
1087                let relative = |ours: f64, theirs: f64| (ours - theirs).abs() / theirs.abs();
1088                let scaled = |ours: f64, theirs: f64, scale: f64| (ours - theirs).abs() / scale;
1089                record(
1090                    "thrust",
1091                    scaled(
1092                        state.thrust_n,
1093                        series.thrust[i],
1094                        motor.curve().peak_thrust_n(),
1095                    ),
1096                );
1097                record(
1098                    "mass flow",
1099                    scaled(state.mass_flow_kg_s, -series.mass_flow_rate[i], peak_flow),
1100                );
1101                record(
1102                    "propellant mass",
1103                    scaled(
1104                        state.propellant.mass_kg,
1105                        series.propellant_mass[i],
1106                        scalars.propellant_initial_mass_kg,
1107                    ),
1108                );
1109                // Before burnout, also relative to RocketPy's own propellant mass. After it,
1110                // RocketPy keeps a residue under 1e-10 kg where hpr's is zero.
1111                if t < scalars.burn_out_time_s {
1112                    let gap = relative(state.propellant.mass_kg, series.propellant_mass[i]);
1113                    assert!(gap.is_finite(), "{} at {t} s", case.name);
1114                    if gap > own_gap.0 {
1115                        own_gap = (gap, case.name.clone(), series.propellant_mass[i]);
1116                    }
1117                }
1118                record(
1119                    "total mass",
1120                    relative(state.total.mass_kg, series.total_mass[i]),
1121                );
1122                record(
1123                    "propellant center",
1124                    scaled(
1125                        state.propellant.cg_m,
1126                        to_hpr(series.center_of_propellant_mass[i]),
1127                        length,
1128                    ),
1129                );
1130                let center = scaled(state.total.cg_m, to_hpr(series.center_of_mass[i]), length);
1131                assert!(center.is_finite(), "{} at {t} s", case.name);
1132                center_gap = center_gap.max(center);
1133                record("center of mass", center);
1134                record(
1135                    "grain bore radius",
1136                    relative(shape.inner_radius_m, series.grain_inner_radius[i]),
1137                );
1138                record(
1139                    "grain height",
1140                    scaled(
1141                        shape.height_m,
1142                        series.grain_height[i],
1143                        inputs.grain_initial_height,
1144                    ),
1145                );
1146                record(
1147                    "propellant I_11",
1148                    scaled(
1149                        state.propellant.transverse_inertia_kg_m2,
1150                        series.propellant_i_11[i],
1151                        loaded.propellant.transverse_inertia_kg_m2,
1152                    ),
1153                );
1154                record(
1155                    "propellant I_33",
1156                    scaled(
1157                        state.propellant.axial_inertia_kg_m2,
1158                        series.propellant_i_33[i],
1159                        loaded.propellant.axial_inertia_kg_m2,
1160                    ),
1161                );
1162                record(
1163                    "motor I_11",
1164                    relative(state.total.transverse_inertia_kg_m2, series.i_11[i]),
1165                );
1166                record(
1167                    "motor I_33",
1168                    relative(state.total.axial_inertia_kg_m2, series.i_33[i]),
1169                );
1170            }
1171            eprintln!("{}: largest errors against RocketPy", case.name);
1172            for (what, error) in &worst {
1173                eprintln!("  {what:<18} {:.3e}", error);
1174                assert!(
1175                    *error <= 1e-3,
1176                    "{}: {what} differs from RocketPy by {:.4}%",
1177                    case.name,
1178                    100.0 * error
1179                );
1180            }
1181        }
1182        // The figures docs/physics/motor.md quotes. In the last milligrams of the 38 mm I case
1183        // the masses differ by 69% of RocketPy's value, from its interpolation between the
1184        // points its solver stored; on the fixed scale above that is about 2e-5.
1185        let (gap, gap_case, gap_theirs_kg) = own_gap;
1186        eprintln!("propellant, own: {gap:.4e} in {gap_case} at {gap_theirs_kg:.3e} kg");
1187        eprintln!("center of mass: {center_gap:.4e} of the motor length");
1188        assert!((0.688..0.689).contains(&gap), "{gap}");
1189        assert_eq!(gap_case, "cti-411i175-38mm-radial-burnout");
1190        assert!((6.9e-6..7.0e-6).contains(&gap_theirs_kg), "{gap_theirs_kg}");
1191        assert!((5.8e-6..5.9e-6).contains(&center_gap), "{center_gap}");
1192    }
1193
1194    #[test]
1195    fn serde_round_trips_and_rechecks() {
1196        let motor = SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.3, 0.6).unwrap();
1197        let json = serde_json::to_string(&motor).unwrap();
1198        assert_eq!(serde_json::from_str::<SolidMotor>(&json).unwrap(), motor);
1199        let broken = json.replace(
1200            "\"mass_kg\":0.3,\"center_m\"",
1201            "\"mass_kg\":-0.3,\"center_m\"",
1202        );
1203        assert_ne!(broken, json);
1204        assert!(serde_json::from_str::<SolidMotor>(&broken).is_err());
1205    }
1206}