Skip to main content

hpr_sim/
metrics.rs

1//! What a flight comes to: its peaks, its apogee, its stability margins, the ejection delay that
2//! would fire at apogee, and where each body landed ([the flight-metrics milestone][m1-10a] and
3//! [its decision record][adr-077]; the guide's [Flight metrics][page] page).
4//!
5//! - [`FlightMetrics`] is an [`Observer`]: fly a [`Simulation`] with it, then ask it for a
6//!   [`FlightSummary`]. It finds each peak on the integrator's dense output, not in a recorded
7//!   table, so a peak between two rows is not missed ([Loft lesson L34][l34]).
8//! - [`stability`] gives the static margin and the margin at the flight's Mach number at one
9//!   instant, and [`margin`] the margin of any flow. A margin that would be a ratio of nearly cancelling
10//!   slopes is `None`, with the pitch-moment slope beside it ([L33][l33]).
11//! - [`optimum_delays`] flies the rocket with its charges held and gives, for each motor, the delay
12//!   from its burnout to that apogee, so it doesn't depend on the delay flown ([L94][l94]).
13//! - Anything that did not happen is `None`, never a zero, and every height names its datum
14//!   ([L35][l35]).
15//!
16//! **Heights.** A height here is the center of mass's ellipsoidal height above the launch site's,
17//! [`Sample::height_above_ground_m`]. The center of mass starts above the site (the rocket stands
18//! on the rail), at [`FlightSummary::launch_height_m`]; [`Apogee::gain_m`] counts from there, as
19//! OpenRocket's altitude does.
20//!
21//! [l33]: https://hpr.fusionspace.co/decisions-and-roadmap.html#l33
22//! [l34]: https://hpr.fusionspace.co/decisions-and-roadmap.html#l34
23//! [l35]: https://hpr.fusionspace.co/decisions-and-roadmap.html#l35
24//! [l94]: https://hpr.fusionspace.co/decisions-and-roadmap.html#l94
25//! [m1-10a]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-10a
26//! [adr-077]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-077-flight-metrics-peaks-on-the-dense-output-margins-only-where-they-mean-something-and-none-for-what-didnt-happen-2026-09-26
27//! [page]: https://hpr.fusionspace.co/physics/metrics.html
28
29use std::collections::BTreeMap;
30
31use hpr_aero::{AeroModel, Flow};
32use serde::{Deserialize, Serialize};
33
34use crate::dynamics::Phase;
35use crate::envelope::{self, EnvelopeFlag, HIGH_ANGLE_GRACE_S, HIGH_ANGLE_OF_ATTACK_RAD};
36use crate::environment::Environment;
37use crate::error::SimError;
38use crate::flight::{EventKind, FlightEvent, FlightResult, Simulation, Termination};
39use crate::recorder::{BodyStep, FlightStep, Observer, Sample};
40use crate::recovery::BodySample;
41
42/// The largest ratio `κ = Σ |C_Nα,i| / C_Nα` at which a margin is given: `√10`.
43///
44/// The center of pressure is `x_cp = Σ C_Nα,i x_i / C_Nα`, over the parts the model adds up, with
45/// each part's station `x_i` on the rocket, in `[0, L]`. Since `x_cp − x_j = Σ C_Nα,i (x_i − x_j) / C_Nα`, it lies within `κ L` of every
46/// station. An error `ε C_Nα,j` in one component's slope moves it by
47/// `ε C_Nα,j (x_j − x_cp) / C_Nα`, so by at most `ε κ² L`. A rocket whose slopes all push the same
48/// way has `κ = 1`, and a 1% error in one slope moves its center of pressure by at most 1% of its
49/// length. As the net slope goes to zero, `κ` runs away: the loads become a pure couple with no
50/// line of action, and the quotient is noise (Loft published ±12 to 15 calibers so,
51/// [lesson L33][l33]). At `κ = √10` a 1% error in one slope can move the center of pressure by a
52/// tenth of the rocket's length; past it HPR Sim gives no margin, only the pitch-moment slope, which
53/// stays finite. The limit is a chosen bound on that sensitivity, not a measurement. The bound
54/// holds for parts that each carry a force at a station: a part that is a pure couple (a step and
55/// a flare of equal slopes) has none, and `κ` doesn't count it.
56///
57/// [l33]: https://hpr.fusionspace.co/decisions-and-roadmap.html#l33
58pub const MARGIN_CONDITION_LIMIT: f64 = 3.162_277_660_168_379_5;
59
60/// The Mach number of the static margin: the air at rest, as RocketPy's `static_margin` takes it.
61pub const STATIC_MARGIN_MACH: f64 = 0.0;
62
63/// A peak over the flight, with where and when it came.
64#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
65pub struct Peak {
66    /// The peak value, in the quantity's own unit.
67    pub value: f64,
68    /// When it came, s after launch.
69    pub time_s: f64,
70    /// The center of mass's height above the launch site then, m.
71    pub height_above_ground_m: f64,
72}
73
74/// A peak over one separated body's own flight, with where and when it came.
75#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
76pub struct BodyPeak {
77    /// Which body, numbered as [`crate::BodyFlight::body`] is: 0 keeps the nose.
78    pub body: usize,
79    /// The peak value, in the quantity's own unit.
80    pub value: f64,
81    /// When it came, s after launch.
82    pub time_s: f64,
83    /// That body's height above the launch site then, m.
84    pub height_above_ground_m: f64,
85}
86
87/// The stability margin of one flow.
88#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
89pub struct Margin {
90    /// The Mach number.
91    pub mach: f64,
92    /// The total angle of attack, rad.
93    pub angle_of_attack_rad: f64,
94    /// The direction the air crosses the rocket, rad from `x_B` toward `y_B`
95    /// ([`hpr_aero::Flow::roll_rad`]): for [`weakest_margin`], its weakest plane's.
96    #[serde(default)]
97    pub roll_rad: f64,
98    /// The rocket's normal-force slope `C_Nα` on the reference area, per radian (at an angle of
99    /// attack, the secant `C_N/α`, [`hpr_aero::NormalForce::slope_per_rad`]).
100    pub normal_force_slope_per_rad: f64,
101    /// `Σ |C_Nα,i|` over the components, per radian: the scale against which the net slope is
102    /// judged ([`MARGIN_CONDITION_LIMIT`]). With a normal-force table it is the table's own slope's
103    /// magnitude.
104    pub slope_magnitude_sum_per_rad: f64,
105    /// The pitch-moment slope about the center of mass on the reference area and diameter, per
106    /// radian: `C_mα = −(Σ C_Nα,i x_i − C_Nα x_cg) / d`, stations `x` aft of the nose tip, from
107    /// [`hpr_aero::NormalForce::moment_slope_m`]. Negative restores. It is finite when the margin
108    /// is not, and with a margin it is `−C_Nα · margin`.
109    pub pitch_moment_slope_per_rad: f64,
110    /// The center of pressure, m aft of the nose tip; `None` when the margin is.
111    pub cp_station_m: Option<f64>,
112    /// The margin `(x_cp − x_cg) / d`, calibers: positive with the center of pressure aft of the
113    /// center of mass. `None` when the net slope is not positive or is below
114    /// `Σ |C_Nα,i| / MARGIN_CONDITION_LIMIT`, where the quotient would be noise.
115    pub margin_cal: Option<f64>,
116}
117
118/// The rocket's stability at one instant.
119#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
120pub struct Stability {
121    /// When, s after launch.
122    pub time_s: f64,
123    /// The center of mass's height above the launch site then, m.
124    pub height_above_ground_m: f64,
125    /// The dynamic pressure then, Pa: how hard the air presses on the margin's moment.
126    pub dynamic_pressure_pa: f64,
127    /// The center of mass, m aft of the nose tip.
128    pub cg_station_m: f64,
129    /// The reference diameter `d` the margins are counted in, m (the sustainer's after a powered
130    /// separation).
131    pub reference_diameter_m: f64,
132    /// The static margin: the air along the axis at [`STATIC_MARGIN_MACH`], with the center of
133    /// mass of this instant (RocketPy's `static_margin`), in the rocket's weakest plane
134    /// ([`weakest_margin`]).
135    pub static_margin: Margin,
136    /// The flight margin: the air along the axis at the flight's Mach number, with the center of
137    /// mass of this instant (RocketPy's `stability_margin`), in the rocket's weakest plane
138    /// ([`weakest_margin`]). The angle of attack is left out: near
139    /// apogee it swings toward 90° as the rocket slows and tips over, and a least margin that
140    /// followed it would land wherever large angles stopped being counted.
141    pub flight_margin: Margin,
142}
143
144/// The margin of `aero` in `flow` with the center of mass at `cg_station_m` (m aft of the nose
145/// tip). See [`Margin`] and [`MARGIN_CONDITION_LIMIT`] for when it is `None`.
146///
147/// # Errors
148///
149/// The aerodynamic model's, for a flow outside its range.
150pub fn margin(aero: &AeroModel, flow: &Flow, cg_station_m: f64) -> Result<Margin, SimError> {
151    let normal = aero.normal_force(flow)?;
152    let d = aero.reference_diameter_m();
153    let slope = normal.slope_per_rad;
154    let scale = if aero.normal_force_table().is_some() {
155        // The table gives one force at one station.
156        slope.abs()
157    } else {
158        aero.components(flow)?
159            .iter()
160            .map(|c| c.normal_force.slope_per_rad.abs())
161            .sum()
162    };
163    let conditioned = slope > 0.0 && slope * MARGIN_CONDITION_LIMIT >= scale;
164    let cp_station_m = normal.cp_station_m.filter(|_| conditioned);
165    Ok(Margin {
166        mach: flow.mach,
167        angle_of_attack_rad: flow.alpha_rad,
168        roll_rad: flow.roll_rad,
169        normal_force_slope_per_rad: slope,
170        slope_magnitude_sum_per_rad: scale,
171        pitch_moment_slope_per_rad: -(normal.moment_slope_m - slope * cg_station_m) / d,
172        cp_station_m,
173        margin_cal: cp_station_m.map(|cp| (cp - cg_station_m) / d),
174    })
175}
176
177/// The least margin of `aero` at Mach `mach`, the air along the axis, over the direction it
178/// crosses the rocket, with the center of mass at `cg_station_m`: [`margin`] in the weakest plane,
179/// whose direction it gives ([`Margin::roll_rad`]); or a plane where no margin can be given, if
180/// there is one (#329).
181///
182/// A fin set of one or two fins carries `Σ sin²(φ − θ_k)` of its force in the plane at `φ`
183/// (Niskanen 2009 eq. 3.51, [`hpr_aero::roll_sum`]), so a rocket with one ([`AeroModel::rolls`])
184/// has a margin in each plane. Each of its terms is then `a + b cos 2φ + c sin 2φ`, and so are the
185/// net slope `S(φ)`, its moment `M(φ) = Σ C_Nα,i x_i`, and the sum of the slopes' magnitudes
186/// `Σ(φ)` while each fin's slope is positive: three planes, `φ = 0, π/3, 2π/3`, give each sum's
187/// `a`, `b` and `c`. A quotient `N/D` of two such sums is stationary where
188/// `P sin 2φ + Q cos 2φ + R = 0`, with `P = n₀d₁ − n₁d₀`, `Q = n₂d₀ − n₀d₂` and
189/// `R = n₂d₁ − n₁d₂` (its derivative's numerator, `N′D − ND′`, expanded). The center of pressure
190/// `M/S` is foremost at one of its two roots, and the margin's conditioning `S/Σ`
191/// ([`MARGIN_CONDITION_LIMIT`]) worst at one of its. Each root, and the axial plane, is evaluated
192/// through the model: a plane with no margin wins, else the least margin. A rocket whose fin sets
193/// are each of three or more fins, or that flies a normal-force table, has one margin, the axial
194/// plane's, returned bit for bit.
195///
196/// # Errors
197///
198/// As [`margin`].
199pub fn weakest_margin(aero: &AeroModel, mach: f64, cg_station_m: f64) -> Result<Margin, SimError> {
200    let axial = margin(aero, &Flow::axial(mach), cg_station_m)?;
201    if !aero.rolls() {
202        return Ok(axial);
203    }
204    // Each sum's `[a, b, c]` in `a + b cos u + c sin u`, `u = 2φ`, from `u = 0, 2π/3, 4π/3`.
205    let mut samples = [[0.0; 3]; 3];
206    for (k, column) in [0.0, 1.0, 2.0].into_iter().enumerate() {
207        let flow = Flow::new(mach, 0.0, column * std::f64::consts::FRAC_PI_3);
208        let normal = aero.normal_force(&flow)?;
209        let scale: f64 = aero
210            .components(&flow)?
211            .iter()
212            .map(|c| c.normal_force.slope_per_rad.abs())
213            .sum();
214        samples[0][k] = normal.slope_per_rad;
215        samples[1][k] = normal.moment_slope_m;
216        samples[2][k] = scale;
217    }
218    let fit = |[f0, f1, f2]: [f64; 3]| {
219        [
220            (f0 + f1 + f2) / 3.0,
221            (2.0 * f0 - f1 - f2) / 3.0,
222            (f1 - f2) / 3.0_f64.sqrt(),
223        ]
224    };
225    let [slope, moment, scale] = samples.map(fit);
226    let mut least = axial;
227    for numerator_denominator in [(moment, slope), (slope, scale)] {
228        for u in stationary_angles(numerator_denominator) {
229            let candidate = margin(aero, &Flow::new(mach, 0.0, 0.5 * u), cg_station_m)?;
230            least = match (least.margin_cal, candidate.margin_cal) {
231                (None, _) => least,
232                (Some(_), None) => candidate,
233                (Some(a), Some(b)) if b < a => candidate,
234                _ => least,
235            };
236        }
237    }
238    Ok(least)
239}
240
241/// The angles `u` in `[0, 2π)` where `N(u)/D(u)` is stationary, `N = n₀ + n₁ cos u + n₂ sin u`
242/// and `D` alike: the roots of `P sin u + Q cos u + R = 0` ([`weakest_margin`]). `P sin u + Q cos u`
243/// is `A sin(u + ψ)` with `A = √(P² + Q²)` and `ψ = atan2(Q, P)`. None when the quotient is
244/// constant (`A` is zero); a root just past `|R| = A` by rounding is taken at the touch point.
245fn stationary_angles(([n0, n1, n2], [d0, d1, d2]): ([f64; 3], [f64; 3])) -> Vec<f64> {
246    let (p, q, r) = (n0 * d1 - n1 * d0, n2 * d0 - n0 * d2, n2 * d1 - n1 * d2);
247    let a = p.hypot(q);
248    if a.is_nan() || a <= 0.0 {
249        return Vec::new();
250    }
251    let ratio = -r / a;
252    if ratio.is_nan() || ratio.abs() > 1.0 + 1e-9 {
253        return Vec::new();
254    }
255    let (root, psi) = (ratio.clamp(-1.0, 1.0).asin(), q.atan2(p));
256    [root - psi, std::f64::consts::PI - root - psi]
257        .into_iter()
258        .map(|u| u.rem_euclid(std::f64::consts::TAU))
259        .collect()
260}
261
262/// The static margin and the flight margin of `aero` at `time_s`, with the center of mass
263/// `height_above_ground_m` above the launch site and at `cg_station_m` on the airframe, and the
264/// flight's air at Mach `mach` pressing with `dynamic_pressure_pa`.
265///
266/// # Errors
267///
268/// As [`margin`].
269pub fn stability(
270    aero: &AeroModel,
271    time_s: f64,
272    height_above_ground_m: f64,
273    dynamic_pressure_pa: f64,
274    cg_station_m: f64,
275    mach: f64,
276) -> Result<Stability, SimError> {
277    Ok(Stability {
278        time_s,
279        height_above_ground_m,
280        dynamic_pressure_pa,
281        cg_station_m,
282        reference_diameter_m: aero.reference_diameter_m(),
283        static_margin: weakest_margin(aero, STATIC_MARGIN_MACH, cg_station_m)?,
284        flight_margin: weakest_margin(aero, mach, cg_station_m)?,
285    })
286}
287
288/// The apogee of the flight's center of mass.
289#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
290pub struct Apogee {
291    /// When, s after launch.
292    pub time_s: f64,
293    /// The center of mass's ellipsoidal height above the launch site, m.
294    pub height_above_ground_m: f64,
295    /// The rise of the center of mass from where it stood at launch, m: the height above the site
296    /// less [`FlightSummary::launch_height_m`], as OpenRocket's altitude counts. `None` for a
297    /// flight started in the air ([`Simulation::run_free`]).
298    pub gain_m: Option<f64>,
299}
300
301/// Where something landed: the center of mass as it reached the launch site's ellipsoidal
302/// height.
303#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
304pub struct Landing {
305    /// Which separated body ([`crate::BodyFlight::body`]), or `None` for the flight itself: the
306    /// stack, or after a powered separation the sustainer.
307    pub body: Option<usize>,
308    /// When, s after launch.
309    pub time_s: f64,
310    /// Geodetic latitude, degrees north (WGS 84).
311    pub latitude_deg: f64,
312    /// Longitude, degrees east (WGS 84).
313    pub longitude_deg: f64,
314    /// East of the launch site in its local frame, m.
315    pub east_m: f64,
316    /// North of the launch site, m.
317    pub north_m: f64,
318    /// The horizontal distance from the launch site, m.
319    pub distance_m: f64,
320    /// The speed of the center of mass at the ground hit, relative to the ground, m/s.
321    pub ground_hit_speed_m_s: f64,
322    /// Its downward speed then, m/s.
323    pub descent_rate_m_s: f64,
324}
325
326impl Landing {
327    /// The landing at `sample`, for `body`, located on `environment`'s ellipsoid.
328    ///
329    /// # Errors
330    ///
331    /// [`SimError::Core`] if the position has no geodetic coordinates.
332    pub fn at(
333        body: Option<usize>,
334        sample: &BodySample,
335        environment: &Environment,
336    ) -> Result<Self, SimError> {
337        let place = environment
338            .earth
339            .frame()
340            .geodetic_from_enu(sample.cg_enu_m)?;
341        let (east_m, north_m) = (sample.cg_enu_m.x, sample.cg_enu_m.y);
342        Ok(Self {
343            body,
344            time_s: sample.time_s,
345            latitude_deg: place.latitude_rad.to_degrees(),
346            longitude_deg: place.longitude_rad.to_degrees(),
347            east_m,
348            north_m,
349            distance_m: east_m.hypot(north_m),
350            ground_hit_speed_m_s: sample.cg_velocity_enu_m_s.length(),
351            descent_rate_m_s: -sample.vertical_speed_m_s,
352        })
353    }
354}
355
356/// The metrics of one flight. Every field that may not have happened is an `Option`.
357#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
358pub struct FlightSummary {
359    /// Why the flight ended.
360    pub termination: Termination,
361    /// The center of mass's height above the launch site as the rocket stood at launch, m. `None`
362    /// for a flight started in the air ([`Simulation::run_free`]).
363    pub launch_height_m: Option<f64>,
364    /// The speed as the last rail guide left the rail, m/s, with its time and height.
365    pub rail_exit_speed_m_s: Option<Peak>,
366    /// The apogee of the center of mass. A stack that comes apart at a separation before its
367    /// apogee ([`Termination::Separated`]) has the apogee of the part that keeps the nose, body 0,
368    /// when that part reaches it whole. There is none when an ejection ([`crate::Ejection`]) parts
369    /// the stack before its apogee, or parts body 0 after the split and before body 0's apogee:
370    /// from the charge on, body 0 is only what the charge leaves at the nose (the piece ahead of
371    /// the parted joint, often the nose cone alone, or the airframe without a payload it let out),
372    /// and its apogee is not the rocket's. An ejection at an apogee or after it keeps that apogee.
373    pub apogee: Option<Apogee>,
374    /// The largest speed of the center of mass relative to the ground after liftoff, m/s.
375    pub max_speed_m_s: Option<Peak>,
376    /// The largest Mach number after liftoff.
377    pub max_mach: Option<Peak>,
378    /// The largest dynamic pressure after liftoff ("max q"), Pa.
379    pub max_dynamic_pressure_pa: Option<Peak>,
380    /// The largest acceleration of the nose tip (the body origin) relative to the launch frame
381    /// from liftoff until a recovery device opens, m/s²: the boost and the coast, from the
382    /// equations of motion.
383    pub max_acceleration_m_s2: Option<Peak>,
384    /// The largest specific force under the recovery devices, m/s²: the opening shock, the
385    /// opening load over the mass, `(drag + thrust)/m` ([`Sample::specific_force_enu_m_s2`]),
386    /// which follows the inflation model, kept apart from the boost's. Gravity is not in it: with
387    /// no motor burning, the mass times this is the opening force. Once a canopy reaches its
388    /// steady fall it reads about 1 g, so it is at least that unless the flight reaches the
389    /// ground first or comes apart at an ejection ([`crate::Ejection`]). When the stack comes
390    /// apart at a separation with nothing left to burn ([`Termination::Separated`]), the part
391    /// that keeps the nose, body 0, flies on as a point mass, and the drag of its own devices
392    /// over its mass counts too ([`BodyStep::specific_force_enu_m_s2`]), whether they open
393    /// before the split or after, until an ejection parts it. No other body's load counts:
394    /// never the part dropped aft at a separation, and no piece from an ejection of the stack
395    /// or of body 0 on, where body 0 is the ejection's lead piece (a nose cone pushed off is
396    /// the nose cone alone). Each of those has its own in
397    /// [`Self::body_max_descent_acceleration_m_s2`].
398    pub max_descent_acceleration_m_s2: Option<Peak>,
399    /// Each separated body's own opening shock, m/s², in body order: the largest specific force
400    /// under that body's own devices over its whole flight as a point mass. That is the drag of
401    /// its open devices over its mass, `½ ρ v² (C_D S) / m` (`ρ` the air's density, `v` the
402    /// body's airspeed, `C_D S` its open devices' drag area, `m` its mass;
403    /// [`BodyStep::specific_force_enu_m_s2`]), found inside its steps as the flight's is.
404    ///
405    /// The mass is the body's at that instant. A body that lets a piece go at an ejection keeps
406    /// its number ([`crate::BodyFlight::body`]), so its figure is the largest from before the
407    /// piece left or after, each over the mass it then had. Body 0's can therefore be larger
408    /// than the flight's ([`Self::max_descent_acceleration_m_s2`]), which stops counting body 0
409    /// at such an ejection.
410    ///
411    /// A tumble ([`crate::DeviceDrag::tumbling_stages`]) is a device like any other. A part that
412    /// tumbles from a fast split has the tumble's drag there, which can be above its canopy's
413    /// opening later; that drag is far outside the tumble's fit, so it is no bound either way.
414    /// A canopy that opens after such a tumble likely reads low: the tumble slows the part more
415    /// than a real booster slows (`docs/physics/recovery.md`).
416    ///
417    /// A body that never had a device of its own open has no entry, and what a body's devices
418    /// did while it was still part of the stack is the flight's, not here. Empty when nothing
419    /// came apart, and in a summary written before this field was.
420    #[serde(default)]
421    pub body_max_descent_acceleration_m_s2: Vec<BodyPeak>,
422    /// The largest airspeed at which a recovery device opened, m/s, with when and where: the
423    /// speed the opening load follows, as `q = ½ρv²`. When the stack comes apart with nothing
424    /// left to burn, the devices the part that keeps the nose opens in its own flight count too.
425    /// Over the ground the speed can be more or less by the wind's.
426    pub max_deployment_airspeed_m_s: Option<Peak>,
427    /// The smallest static margin from the rail exit to apogee or the first deployment,
428    /// calibers, where it is defined, found inside steps as a peak is. After a powered separation
429    /// the sustainer's margins count its own diameter.
430    pub min_static_margin_cal: Option<Peak>,
431    /// The smallest flight margin over the same span, calibers, found the same way. RocketPy's
432    /// `min_stability_margin` takes its least over the whole flight, so it can differ.
433    pub min_flight_margin_cal: Option<Peak>,
434    /// The smallest static margin over the same span while a motor burns, calibers, found the
435    /// same way: below zero, the rocket is unstable under power
436    /// ([`EnvelopeFlag::UnstableUnderPower`]; [#335][i335]). A step counts when the thrust at its
437    /// middle is positive. Every ignition, thrust-curve knot and burnout ends a step, so a motor's
438    /// thrust then holds through the step, and a step that ends at a burnout counts up to that
439    /// instant. A NaN margin at a step's start, middle or end while a motor burns is kept, and
440    /// then nothing replaces it, so it can't hide the flag; a NaN thrust counts as burning. `None`
441    /// when no motor burns in the span, the margin is nowhere defined while one does, and in a
442    /// summary written before this field was.
443    ///
444    /// [i335]: https://github.com/nrdptel/fusionspace-eridanus/issues/335
445    #[serde(default)]
446    pub min_powered_static_margin_cal: Option<Peak>,
447    /// The largest static pitch-moment slope `C_mα` per radian
448    /// ([`Margin::pitch_moment_slope_per_rad`], `C_mα = −(Σ C_Nα,i x_i − C_Nα x_cg) / d`) over the
449    /// same span while a motor burns, taken only at instants where the static margin is
450    /// undefined: above zero, the air turns the rocket away from its path, so it is unstable under
451    /// power although HPR Sim can give no margin ([`EnvelopeFlag::UnstableWithoutMargin`]). The
452    /// margin is undefined where the net normal-force slope is not positive, or is too small
453    /// against `Σ |C_Nα,i|` for the quotient to mean anything ([`MARGIN_CONDITION_LIMIT`]); the
454    /// moment slope stays finite there and still says which way the air turns the rocket.
455    /// Taken at the start, middle and end of each step where a motor burns, counted as for
456    /// [`min_powered_static_margin_cal`](Self::min_powered_static_margin_cal), not searched
457    /// between. A NaN slope is kept, and then nothing replaces it. `None` when the margin is
458    /// defined at every such instant, no motor burns in the span, and in a summary written
459    /// before this field was.
460    #[serde(default)]
461    pub max_powered_moment_slope_per_rad: Option<Peak>,
462    /// The stability as the last rail guide left the rail.
463    pub rail_exit_stability: Option<Stability>,
464    /// The largest angle of attack more than [`HIGH_ANGLE_GRACE_S`] after the rail exit (or the
465    /// start of a flight begun in the air), until apogee or the first deployment, rad. Only
466    /// instants where a 15° angle would give a normal force of at least
467    /// [`HIGH_ANGLE_MIN_FORCE_SHARE`](envelope::HIGH_ANGLE_MIN_FORCE_SHARE) of the rocket's weight count: as the path turns over near
468    /// apogee the angle swings past 15° on an ordinary flight, with too little air to move it ([the envelope flags' decision
469    /// record][adr-179]). Taken at each step's start, middle and end, not searched between.
470    /// `None` when no instant counted, and in a summary written before this field was.
471    ///
472    /// [adr-179]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0179-the-envelope-flags.md
473    #[serde(default)]
474    pub max_angle_of_attack_rad: Option<Peak>,
475    /// Where the flight itself landed: the stack, or after a powered separation the sustainer.
476    pub landing: Option<Landing>,
477    /// Where each separated body landed, in body order; a body that didn't land is left out.
478    pub body_landings: Vec<Landing>,
479}
480
481impl FlightSummary {
482    /// The operating envelope's flags this flight raises, in [`EnvelopeFlag`]'s order.
483    #[must_use]
484    pub fn envelope_flags(&self) -> Vec<EnvelopeFlag> {
485        crate::envelope::flags(
486            self.max_mach,
487            self.max_angle_of_attack_rad,
488            self.min_powered_static_margin_cal,
489            self.max_powered_moment_slope_per_rad,
490        )
491    }
492
493    /// The flight's own ground-hit speed, m/s, if it landed.
494    #[must_use]
495    pub fn ground_hit_speed_m_s(&self) -> Option<f64> {
496        self.landing.map(|landing| landing.ground_hit_speed_m_s)
497    }
498
499    /// Where the part that keeps the nose landed, as [`Self::apogee`] is its apogee: the
500    /// flight's own landing ([`Self::landing`]), or, after the stack comes apart with nothing
501    /// left to burn ([`Termination::Separated`], which leaves [`Self::landing`] empty), part 0's
502    /// from [`Self::body_landings`].
503    #[must_use]
504    pub fn nose_landing(&self) -> Option<&Landing> {
505        self.landing
506            .as_ref()
507            .or_else(|| self.body_landings.iter().find(|l| l.body == Some(0)))
508    }
509}
510
511/// Watches a flight and keeps its peaks, and its stability from the rail exit to apogee or the
512/// first deployment.
513///
514/// Each step is sampled at its start, middle and end. When the parabola through the three has its
515/// top inside the step, a golden-section search on the dense output finds the peak there; the
516/// largest of what it finds and the three samples is kept. The least margins are found the same
517/// way, with the parabola turned over. Thrust-curve knots and events end steps, so a thrust
518/// spike's peak is a step's end. Nothing is kept on the pad.
519///
520/// A watcher keeps one flight: [`FlightMetrics::clear`] it before watching another, and
521/// [`FlightMetrics::summary`] refuses a flight whose steps it didn't all see, once each, its
522/// separated bodies' steps included. An observer that wraps one must hand it every call,
523/// [`Observer::body_step`] too. Like
524/// [`crate::Recorder`], it serializes what it holds for inspection and is built with
525/// [`FlightMetrics::new`], not deserialized.
526#[derive(Debug, Clone, Default, PartialEq, Serialize)]
527pub struct FlightMetrics {
528    launch_height_m: Option<f64>,
529    max_speed: Option<Peak>,
530    max_mach: Option<Peak>,
531    max_q: Option<Peak>,
532    max_acceleration: Option<Peak>,
533    max_descent_acceleration: Option<Peak>,
534    /// The running maximum of the specific force on body 0, a separated body flown as a point
535    /// mass, under a device of its own: a step's largest, with the step's start, s, each time it
536    /// beats the last one kept. The summary takes the largest of those that start before an
537    /// ejection parts body 0, and only when the stack came apart at a separation with no
538    /// ejection: until then body 0 is the part that keeps the nose.
539    nose_descent_peaks: Vec<(f64, Peak)>,
540    /// Each separated body's largest specific force under its own devices, by body number.
541    body_descent_peaks: BTreeMap<usize, Peak>,
542    /// How many steps it saw of each separated body: that body's accepted steps, one each.
543    body_steps: BTreeMap<usize, u64>,
544    max_deployment_airspeed: Option<Peak>,
545    /// Whether any step was seen, and the last one's end.
546    last_end_s: Option<f64>,
547    /// How many steps it saw: a flight's accepted steps, one each.
548    steps: u64,
549    on_rail: bool,
550    past_apogee: bool,
551    /// Whether a separation came since the last step: the next starts on another rocket.
552    separated: bool,
553    /// The top Mach number of each vehicle the flight flew, as [`Self::max_mach_by_vehicle`].
554    vehicle_max_mach: Vec<Option<Peak>>,
555    rail_exit: Option<Stability>,
556    stability: Vec<Stability>,
557    min_static_margin: Option<Peak>,
558    min_flight_margin: Option<Peak>,
559    /// The least static margin over the steps where a motor burns.
560    min_powered_static_margin: Option<Peak>,
561    /// The largest static pitch-moment slope over the steps where a motor burns, at instants
562    /// without a static margin.
563    max_powered_moment_slope: Option<Peak>,
564    /// When the free flight began (the rail exit, or the start of a flight begun in the air), s:
565    /// where the angle of attack's window opens.
566    free_start_s: Option<f64>,
567    max_angle_of_attack: Option<Peak>,
568}
569
570/// What a peak is of.
571#[derive(Debug, Clone, Copy)]
572enum Quantity {
573    Speed,
574    Mach,
575    DynamicPressure,
576    Acceleration,
577}
578
579impl Quantity {
580    const ALL: [Quantity; 4] = [
581        Quantity::Speed,
582        Quantity::Mach,
583        Quantity::DynamicPressure,
584        Quantity::Acceleration,
585    ];
586
587    /// The quantity at `sample`. Under the recovery devices the acceleration is the specific
588    /// force, `(drag + thrust)/m`, the opening load over the mass: the motion's acceleration there
589    /// has gravity in it, and after apogee, with the drag up and gravity down, would read the
590    /// shock low by up to g (#1258).
591    fn of(self, sample: &Sample) -> f64 {
592        match self {
593            Quantity::Speed => sample.cg_velocity_enu_m_s.length(),
594            Quantity::Mach => sample.mach,
595            Quantity::DynamicPressure => sample.dynamic_pressure_pa,
596            Quantity::Acceleration if sample.phase == Phase::Descent => {
597                sample.specific_force_enu_m_s2.length()
598            }
599            Quantity::Acceleration => sample.acceleration_enu_m_s2.length(),
600        }
601    }
602}
603
604impl FlightMetrics {
605    /// A watcher with nothing seen.
606    #[must_use]
607    pub fn new() -> Self {
608        Self::default()
609    }
610
611    /// Forgets what it saw, ready for another flight.
612    pub fn clear(&mut self) {
613        *self = Self::default();
614    }
615
616    /// How many of body 0's step peaks are kept for the summary.
617    #[cfg(test)]
618    pub(crate) fn nose_peaks_kept(&self) -> usize {
619        self.nose_descent_peaks.len()
620    }
621
622    /// The stability from the rail exit (or the start of a flight begun in the air) to apogee or
623    /// the first deployment, whichever comes first: at the rail exit and at every step's end, in
624    /// time order. A powered separation adds the sustainer's own entry at the split, after the
625    /// stack's and at the same time, so the watcher needs the flight's events as well as its
626    /// steps.
627    #[must_use]
628    pub fn stability(&self) -> &[Stability] {
629        &self.stability
630    }
631
632    /// The top Mach number of each vehicle the flight flew in six degrees of freedom, as the
633    /// flight's own is found ([`FlightSummary::max_mach`]) but over that vehicle's steps alone:
634    /// the launch stack's first, then after each separation the vehicle that flew on (the
635    /// sustainer after a powered one, [`crate::Simulation::flown_vehicles`]). A separation that
636    /// ended the flight leaves a last entry of `None`, as does a vehicle that took no step off
637    /// the pad; a flight that took no step has none. The bodies that fall as points after a
638    /// separation aren't among them, as they aren't in the flight's.
639    #[must_use]
640    pub fn max_mach_by_vehicle(&self) -> &[Option<Peak>] {
641        &self.vehicle_max_mach
642    }
643
644    /// The summary of `result`, the flight this watched, flown in `environment`.
645    ///
646    /// # Errors
647    ///
648    /// [`SimError::Domain`] if it didn't see each of `result`'s accepted steps once, or its last
649    /// step ended after `result` did (it watched another flight, or wasn't cleared between two),
650    /// or it didn't see each accepted step of each of `result`'s separated bodies once, or saw
651    /// a body `result` doesn't have;
652    /// [`SimError::Core`] if a landing has no geodetic coordinates.
653    pub fn summary(
654        &self,
655        result: &FlightResult,
656        environment: &Environment,
657    ) -> Result<FlightSummary, SimError> {
658        // A flight can end without a step (before its first, or on a stop a few ulps ahead that
659        // the clock just moves to), so the steps are counted rather than its end matched.
660        if self.steps != result.stats.accepted_steps
661            || self
662                .last_end_s
663                .is_some_and(|end| end > result.final_sample.time_s)
664        {
665            return Err(SimError::Domain {
666                what: "steps this watcher saw (it must watch each step of the flight it sums up, \
667                       and be cleared before another)",
668                value: self.steps as f64,
669            });
670        }
671        // The same for each separated body, whose opening shock is read from its own steps: a
672        // body this watcher saw that the flight doesn't have, or a body's steps not all seen
673        // once, is another flight's.
674        let seen = |body: usize| self.body_steps.get(&body).copied().unwrap_or(0);
675        let stray = self
676            .body_steps
677            .keys()
678            .find(|body| !result.bodies.iter().any(|flown| flown.body == **body));
679        let miscounted = result
680            .bodies
681            .iter()
682            .find(|flown| seen(flown.body) != flown.stats.accepted_steps);
683        if let Some(body) = stray.copied().or(miscounted.map(|flown| flown.body)) {
684            return Err(SimError::Domain {
685                what: "steps this watcher saw of a separated body (it must watch each step of \
686                       every body of the flight it sums up, and be cleared before another)",
687                value: seen(body) as f64,
688            });
689        }
690        // A stack that came apart at a separation on its way up has the apogee of the part that
691        // keeps the nose, body 0, which flies on as a point mass ([`Termination::Separated`]).
692        // An ejection's body 0 is its lead piece, often the nose cone alone, so a stack that
693        // came apart at one on its way up has none; nor has a flight whose body 0 lets a piece
694        // go after the split and before its own apogee, since the apogee body 0 then reaches is
695        // that of what the charge left of it (#1531). An apogee reached whole, the charge at it
696        // or after, stays.
697        let ejection = |event: &EventKind| matches!(event, EventKind::Ejection(_));
698        let stack = result
699            .event(EventKind::Apogee)
700            .map(|event| (event.sample.time_s, event.sample.height_above_ground_m));
701        let nose = || {
702            result
703                .bodies
704                .iter()
705                .find(|body| body.body == 0)
706                .and_then(|body| {
707                    body.events
708                        .iter()
709                        .take_while(|event| !ejection(&event.kind))
710                        .find(|event| event.kind == EventKind::Apogee)
711                })
712                .map(|event| (event.sample.time_s, event.sample.height_above_ground_m))
713        };
714        let apogee = stack
715            .or_else(|| {
716                let separated = result.termination == Termination::Separated
717                    && result.event(EventKind::Separation).is_some()
718                    && !result.events.iter().any(|event| ejection(&event.kind));
719                separated.then(nose).flatten()
720            })
721            .map(|(time_s, height)| Apogee {
722                time_s,
723                height_above_ground_m: height,
724                gain_m: self.launch_height_m.map(|start| height - start),
725            });
726        let rail_exit = result.event(EventKind::RailExit).map(|event| event.sample);
727        // When the stack came apart with nothing left to burn, the part that keeps the nose, part
728        // 0, flies on as a point and opens its own devices; the top airspeed counts those too, as
729        // the event list does, so a main that opens later and faster is not left out.
730        let mut max_deployment_airspeed = self.max_deployment_airspeed;
731        if result.termination == Termination::Separated {
732            let nose = result.bodies.iter().filter(|body| body.body == 0);
733            for event in nose.flat_map(|body| &body.events) {
734                let sample = &event.sample;
735                if matches!(event.kind, EventKind::Deployment(_))
736                    && max_deployment_airspeed.is_none_or(|peak| sample.airspeed_m_s > peak.value)
737                {
738                    max_deployment_airspeed = Some(Peak {
739                        value: sample.airspeed_m_s,
740                        time_s: sample.time_s,
741                        height_above_ground_m: sample.height_above_ground_m,
742                    });
743                }
744            }
745        }
746        // Body 0's opening shock counts while it is the part that keeps the nose: after a
747        // separation with no ejection, and until an ejection of its own parts it. From an
748        // ejection on, body 0 is that ejection's lead piece (a nose cone pushed off is the nose
749        // cone alone), whose load is left out.
750        let mut max_descent_acceleration = self.max_descent_acceleration;
751        if result.termination == Termination::Separated
752            && result.event(EventKind::Separation).is_some()
753            && !result.events.iter().any(|event| ejection(&event.kind))
754        {
755            let parted_s = result
756                .bodies
757                .iter()
758                .filter(|body| body.body == 0)
759                .flat_map(|body| &body.events)
760                .find(|event| ejection(&event.kind))
761                .map_or(f64::INFINITY, |event| event.sample.time_s);
762            for (start_s, nose) in &self.nose_descent_peaks {
763                if *start_s < parted_s
764                    && max_descent_acceleration.is_none_or(|peak| nose.value > peak.value)
765                {
766                    max_descent_acceleration = Some(*nose);
767                }
768            }
769        }
770        let landing = if result.termination == Termination::GroundHit {
771            let s = &result.final_sample;
772            Some(Landing::at(
773                None,
774                &BodySample {
775                    time_s: s.time_s,
776                    cg_enu_m: s.cg_enu_m,
777                    cg_velocity_enu_m_s: s.cg_velocity_enu_m_s,
778                    height_above_ground_m: s.height_above_ground_m,
779                    vertical_speed_m_s: s.vertical_speed_m_s,
780                    airspeed_m_s: s.airspeed_m_s,
781                    recovery_drag_area_m2: s.recovery_drag_area_m2,
782                    mass_kg: s.mass_kg,
783                },
784                environment,
785            )?)
786        } else {
787            None
788        };
789        let body_landings = result
790            .bodies
791            .iter()
792            .filter(|body| body.termination == Termination::GroundHit)
793            .map(|body| Landing::at(Some(body.body), &body.final_sample, environment))
794            .collect::<Result<Vec<_>, _>>()?;
795        let body_max_descent_acceleration_m_s2 = self
796            .body_descent_peaks
797            .iter()
798            .map(|(&body, peak)| BodyPeak {
799                body,
800                value: peak.value,
801                time_s: peak.time_s,
802                height_above_ground_m: peak.height_above_ground_m,
803            })
804            .collect();
805        Ok(FlightSummary {
806            termination: result.termination,
807            launch_height_m: self.launch_height_m,
808            rail_exit_speed_m_s: rail_exit.map(|s| Peak {
809                value: s.cg_velocity_enu_m_s.length(),
810                time_s: s.time_s,
811                height_above_ground_m: s.height_above_ground_m,
812            }),
813            apogee,
814            max_speed_m_s: self.max_speed,
815            max_mach: self.max_mach,
816            max_dynamic_pressure_pa: self.max_q,
817            max_acceleration_m_s2: self.max_acceleration,
818            max_descent_acceleration_m_s2: max_descent_acceleration,
819            body_max_descent_acceleration_m_s2,
820            max_deployment_airspeed_m_s: max_deployment_airspeed,
821            min_static_margin_cal: self.min_static_margin,
822            min_flight_margin_cal: self.min_flight_margin,
823            min_powered_static_margin_cal: self.min_powered_static_margin,
824            max_powered_moment_slope_per_rad: self.max_powered_moment_slope,
825            rail_exit_stability: self.rail_exit,
826            max_angle_of_attack_rad: self.max_angle_of_attack,
827            landing,
828            body_landings,
829        })
830    }
831
832    fn slot(&mut self, quantity: Quantity, phase: Phase) -> &mut Option<Peak> {
833        match quantity {
834            Quantity::Speed => &mut self.max_speed,
835            Quantity::Mach => &mut self.max_mach,
836            Quantity::DynamicPressure => &mut self.max_q,
837            Quantity::Acceleration if phase == Phase::Descent => &mut self.max_descent_acceleration,
838            Quantity::Acceleration => &mut self.max_acceleration,
839        }
840    }
841}
842
843impl Observer for FlightMetrics {
844    fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
845        let phase = step.phase();
846        let (a, b) = (step.start_s(), step.end_s());
847        let start = step.sample(a)?;
848        if self.last_end_s.is_none() {
849            match phase {
850                Phase::Pad | Phase::Rail | Phase::TipOff => {
851                    self.launch_height_m = Some(start.height_above_ground_m)
852                }
853                // A flight begun in the air on its way down has no apogee to come.
854                _ if start.vertical_speed_m_s <= 0.0 => self.past_apogee = true,
855                _ => {}
856            }
857        }
858        self.steps += 1;
859        self.last_end_s = Some(b);
860        if phase == Phase::Pad {
861            return Ok(());
862        }
863        let samples = [start, step.sample(0.5 * (a + b))?, step.sample(b)?];
864        for quantity in Quantity::ALL {
865            let best = step_peak(step, quantity, &samples)?;
866            let slot = self.slot(quantity, phase);
867            if slot.is_none_or(|peak| best.value > peak.value) {
868                *slot = Some(best);
869            }
870            if matches!(quantity, Quantity::Mach) {
871                if self.vehicle_max_mach.is_empty() {
872                    self.vehicle_max_mach.push(None);
873                }
874                if let Some(slot) = self.vehicle_max_mach.last_mut()
875                    && slot.is_none_or(|peak| best.value > peak.value)
876                {
877                    *slot = Some(best);
878                }
879            }
880        }
881        if matches!(phase, Phase::Rail | Phase::TipOff) {
882            self.on_rail = true;
883        }
884        // On the rail the rail holds the rocket, so stability starts at the rail exit.
885        if !self.past_apogee && phase == Phase::Free {
886            let from_s = *self.free_start_s.get_or_insert(samples[0].time_s);
887            // A step starts where the last ended, on the same rocket, unless a separation came
888            // between: then the sustainer's own margins at the split start the step.
889            let first = match self.stability.last() {
890                Some(last) if !self.separated => *last,
891                _ => {
892                    let first = step.stability(a)?;
893                    if self.stability.is_empty() && self.on_rail {
894                        self.rail_exit = Some(first);
895                    }
896                    self.stability.push(first);
897                    first
898                }
899            };
900            let end = step.stability(b)?;
901            let entries = [first, step.stability(0.5 * (a + b))?, end];
902            for (sample, entry) in samples.iter().zip(&entries) {
903                // The normal force a 15° angle would give here: whether the air could turn the
904                // rocket at all.
905                let force_n = envelope::normal_force_n(
906                    sample.dynamic_pressure_pa,
907                    entry.reference_diameter_m,
908                    entry.flight_margin.normal_force_slope_per_rad,
909                    HIGH_ANGLE_OF_ATTACK_RAD,
910                );
911                // A NaN angle is kept, and then nothing replaces it: it can't hide a flag.
912                if sample.time_s - from_s > HIGH_ANGLE_GRACE_S
913                    && envelope::force_counts(force_n, sample.mass_kg)
914                    && self.max_angle_of_attack.is_none_or(|peak| {
915                        !peak.value.is_nan()
916                            && (sample.angle_of_attack_rad.is_nan()
917                                || sample.angle_of_attack_rad > peak.value)
918                    })
919                {
920                    self.max_angle_of_attack = Some(Peak {
921                        value: sample.angle_of_attack_rad,
922                        time_s: sample.time_s,
923                        height_above_ground_m: sample.height_above_ground_m,
924                    });
925                }
926            }
927            let least_static = least_margin(step, a, b, &entries, static_of)?;
928            for (least, slot) in [
929                (least_static, &mut self.min_static_margin),
930                (
931                    least_margin(step, a, b, &entries, flight_of)?,
932                    &mut self.min_flight_margin,
933                ),
934            ] {
935                if let Some(least) = least
936                    && slot.is_none_or(|peak| replaces(least.value, peak.value))
937                {
938                    *slot = Some(least);
939                }
940            }
941            // Every ignition, thrust-curve knot and burnout ends a step, so the thrust at the
942            // middle says whether a motor burns through the step. A NaN counts as burning.
943            let thrust_n = samples[1].thrust_n;
944            if thrust_n > 0.0 || thrust_n.is_nan() {
945                keep_powered(&mut self.min_powered_static_margin, &entries, least_static);
946                keep_moment_without_margin(&mut self.max_powered_moment_slope, &entries);
947            }
948            self.stability.push(end);
949        }
950        self.separated = false;
951        Ok(())
952    }
953
954    fn event(&mut self, event: &FlightEvent) {
955        match event.kind {
956            EventKind::Apogee => self.past_apogee = true,
957            EventKind::Deployment(_) => {
958                let sample = &event.sample;
959                if self
960                    .max_deployment_airspeed
961                    .is_none_or(|peak| sample.airspeed_m_s > peak.value)
962                {
963                    self.max_deployment_airspeed = Some(Peak {
964                        value: sample.airspeed_m_s,
965                        time_s: sample.time_s,
966                        height_above_ground_m: sample.height_above_ground_m,
967                    });
968                }
969            }
970            EventKind::Separation => {
971                self.separated = true;
972                // The vehicle that flies on starts its own peak; the stack's is the first.
973                if self.vehicle_max_mach.is_empty() {
974                    self.vehicle_max_mach.push(None);
975                }
976                self.vehicle_max_mach.push(None);
977            }
978            _ => {}
979        }
980    }
981
982    /// Each body's opening shock: the largest of its specific force over each step (found as a
983    /// stack's step is read), and the largest of those over its flight, the first of equals.
984    /// With no device of its own open the force is zero, and is not kept. A step's peak that is
985    /// not a number is kept, and then nothing replaces it. (A step's peak is not a number when
986    /// the force at its start is not one; body 0's list below, for the flight's figure, lets a
987    /// later number replace a first such value, so on one the two figures can differ.)
988    ///
989    /// Body 0's step peaks are also kept with the step's start for [`Self::summary`] to cut at
990    /// an ejection, for the flight's own figure; a step's peak that doesn't beat the last one
991    /// kept is not, since the summary takes the largest before a time and the first of equals.
992    /// A body's steps are not the flight's: they are counted apart, by body, for the
993    /// summary's check.
994    fn body_step(&mut self, body: usize, step: &dyn BodyStep) -> Result<(), SimError> {
995        *self.body_steps.entry(body).or_insert(0) += 1;
996        let best = body_step_peak(step)?;
997        if best.value > 0.0 || best.value.is_nan() {
998            self.body_descent_peaks
999                .entry(body)
1000                .and_modify(|peak| {
1001                    if !peak.value.is_nan() && (best.value.is_nan() || best.value > peak.value) {
1002                        *peak = best;
1003                    }
1004                })
1005                .or_insert(best);
1006        }
1007        if body != 0 {
1008            return Ok(());
1009        }
1010        // A value that is not a number is kept only as the first entry, where the summary would
1011        // take it; the next number then counts as beating it, as it does in the summary when the
1012        // stack has a shock of its own.
1013        let beats = match self.nose_descent_peaks.last() {
1014            None => best.value > 0.0 || best.value.is_nan(),
1015            Some((_, last)) => best.value > last.value || (last.value.is_nan() && best.value > 0.0),
1016        };
1017        if beats {
1018            self.nose_descent_peaks.push((step.start_s(), best));
1019        }
1020        Ok(())
1021    }
1022}
1023
1024/// The largest specific force on a separated body over one of its steps: from the step's start,
1025/// middle and end and, where the parabola through them tops inside, a search between, as a
1026/// stack's step is read.
1027pub(crate) fn body_step_peak(step: &dyn BodyStep) -> Result<Peak, SimError> {
1028    let peak_at = |t_s: f64| -> Result<Peak, SimError> {
1029        let sample = step.sample(t_s)?;
1030        Ok(Peak {
1031            value: step.specific_force_enu_m_s2(t_s)?.length(),
1032            time_s: sample.time_s,
1033            height_above_ground_m: sample.height_above_ground_m,
1034        })
1035    };
1036    let (a, b) = (step.start_s(), step.end_s());
1037    let [start, middle, end] = [peak_at(a)?, peak_at(0.5 * (a + b))?, peak_at(b)?];
1038    let mut best = [middle, end]
1039        .into_iter()
1040        .fold(start, |x, y| if y.value > x.value { y } else { x });
1041    if top_inside(start.value, middle.value, end.value) {
1042        let found = golden_max(a, b, peak_at)?;
1043        if found.value > best.value {
1044            best = found;
1045        }
1046    }
1047    Ok(best)
1048}
1049
1050/// The golden ratio's inverse, `(√5 − 1)/2`.
1051const INVERSE_PHI: f64 = 0.618_033_988_749_894_9;
1052
1053/// How finely a peak's time is found, relative to the flight's clock (at least 1 s): 1e-9. The
1054/// value's error goes as the square of the time's, so it is far below the integration's.
1055const PEAK_TIME_RESOLUTION: f64 = 1e-9;
1056
1057/// The largest of `value` on `[a, b]`, where it has one top: a golden-section search (Kiefer
1058/// 1953) on a step's dense output, to [`PEAK_TIME_RESOLUTION`].
1059fn golden_max(
1060    mut a: f64,
1061    mut b: f64,
1062    mut value: impl FnMut(f64) -> Result<Peak, SimError>,
1063) -> Result<Peak, SimError> {
1064    let mut c = b - INVERSE_PHI * (b - a);
1065    let mut d = a + INVERSE_PHI * (b - a);
1066    let mut fc = value(c)?;
1067    let mut fd = value(d)?;
1068    while b - a > PEAK_TIME_RESOLUTION * b.abs().max(1.0) {
1069        if fc.value >= fd.value {
1070            b = d;
1071            (d, fd) = (c, fc);
1072            c = b - INVERSE_PHI * (b - a);
1073            fc = value(c)?;
1074        } else {
1075            a = c;
1076            (c, fc) = (d, fd);
1077            d = a + INVERSE_PHI * (b - a);
1078            fd = value(d)?;
1079        }
1080    }
1081    Ok(if fc.value >= fd.value { fc } else { fd })
1082}
1083
1084/// Where the parabola through `(−1, va)`, `(0, vm)` and `(1, vb)` has its top inside: it bends
1085/// down, and its top `x = (va − vb) / (2 (va − 2 vm + vb))` has `|x| < 1`.
1086fn top_inside(va: f64, vm: f64, vb: f64) -> bool {
1087    let bend = va - 2.0 * vm + vb;
1088    bend < 0.0 && (va - vb).abs() < -2.0 * bend
1089}
1090
1091/// The peak of `quantity` on the step, from its start, middle and end samples and, when the
1092/// parabola through them has its top inside, a search between.
1093fn step_peak(
1094    step: &dyn FlightStep,
1095    quantity: Quantity,
1096    samples: &[Sample; 3],
1097) -> Result<Peak, SimError> {
1098    let peak_of = |sample: &Sample| Peak {
1099        value: quantity.of(sample),
1100        time_s: sample.time_s,
1101        height_above_ground_m: sample.height_above_ground_m,
1102    };
1103    let [start, middle, end] = samples.each_ref().map(peak_of);
1104    let mut best = [middle, end]
1105        .into_iter()
1106        .fold(start, |x, y| if y.value > x.value { y } else { x });
1107    if top_inside(start.value, middle.value, end.value) {
1108        let found = golden_max(step.start_s(), step.end_s(), |t| {
1109            step.sample(t).map(|sample| peak_of(&sample))
1110        })?;
1111        if found.value > best.value {
1112            best = found;
1113        }
1114    }
1115    Ok(best)
1116}
1117
1118fn static_of(s: &Stability) -> &Margin {
1119    &s.static_margin
1120}
1121
1122fn flight_of(s: &Stability) -> &Margin {
1123    &s.flight_margin
1124}
1125
1126/// How far below a least margin another must be to replace it: this fraction of the least, or of
1127/// 1 caliber below 1 caliber. A flat margin, which rounding can nudge by an ulp, keeps its first
1128/// time.
1129const MARGIN_TIE: f64 = 1e-12;
1130
1131/// Whether margin `a` is below `b` by more than [`MARGIN_TIE`].
1132fn clearly_below(a: f64, b: f64) -> bool {
1133    b - a > MARGIN_TIE * b.abs().max(1.0)
1134}
1135
1136/// Whether margin `a` replaces the least so far, `b`: clearly below it, or below zero where `b`
1137/// is not, so a tie can't keep a margin on the stable side of zero over one past it.
1138fn replaces(a: f64, b: f64) -> bool {
1139    clearly_below(a, b) || (a < 0.0 && b >= 0.0)
1140}
1141
1142/// Keeps the least static margin of a step where a motor burns in `slot`: a NaN among the step's
1143/// `entries` first, which then stays, so a broken number can't hide the flag; else `least`, the
1144/// step's least, when it [`replaces`] the slot's.
1145fn keep_powered(slot: &mut Option<Peak>, entries: &[Stability; 3], least: Option<Peak>) {
1146    if slot.is_some_and(|peak| peak.value.is_nan()) {
1147        return;
1148    }
1149    let broken = entries.iter().find_map(|s| {
1150        s.static_margin
1151            .margin_cal
1152            .filter(|margin| margin.is_nan())
1153            .map(|value| Peak {
1154                value,
1155                time_s: s.time_s,
1156                height_above_ground_m: s.height_above_ground_m,
1157            })
1158    });
1159    if let Some(broken) = broken {
1160        *slot = Some(broken);
1161    } else if let Some(least) = least
1162        && slot.is_none_or(|peak| replaces(least.value, peak.value))
1163    {
1164        *slot = Some(least);
1165    }
1166}
1167
1168/// Keeps in `slot` the largest static pitch-moment slope among a powered step's `entries` where
1169/// the static margin is undefined: a NaN first, which then stays, so a broken number can't hide
1170/// the flag; else a larger slope.
1171fn keep_moment_without_margin(slot: &mut Option<Peak>, entries: &[Stability; 3]) {
1172    for entry in entries
1173        .iter()
1174        .filter(|s| s.static_margin.margin_cal.is_none())
1175    {
1176        let slope = entry.static_margin.pitch_moment_slope_per_rad;
1177        if slot.is_none_or(|peak| !peak.value.is_nan() && (slope.is_nan() || slope > peak.value)) {
1178            *slot = Some(Peak {
1179                value: slope,
1180                time_s: entry.time_s,
1181                height_above_ground_m: entry.height_above_ground_m,
1182            });
1183        }
1184    }
1185}
1186
1187/// The least of one margin on the step `[a, b]`, from its `entries` at the start, middle and end
1188/// and, when all three are defined and the parabola through them has its bottom inside, a search
1189/// between; `None` if it is nowhere defined among them.
1190fn least_margin(
1191    step: &dyn FlightStep,
1192    a: f64,
1193    b: f64,
1194    entries: &[Stability; 3],
1195    pick: fn(&Stability) -> &Margin,
1196) -> Result<Option<Peak>, SimError> {
1197    let at = |s: &Stability| {
1198        pick(s).margin_cal.map(|value| Peak {
1199            value,
1200            time_s: s.time_s,
1201            height_above_ground_m: s.height_above_ground_m,
1202        })
1203    };
1204    let mut best: Option<Peak> = None;
1205    let mut keep = |candidate: Peak| {
1206        if best.is_none_or(|peak| replaces(candidate.value, peak.value)) {
1207            best = Some(candidate);
1208        }
1209    };
1210    let points = entries.each_ref().map(at);
1211    points.into_iter().flatten().for_each(&mut keep);
1212    if let [Some(start), Some(middle), Some(end)] = points
1213        && top_inside(-start.value, -middle.value, -end.value)
1214    {
1215        // Searched as the largest of its negative; an undefined margin is never the least.
1216        let found = golden_max(a, b, |t| {
1217            step.stability(t).map(|s| {
1218                let peak = at(&s);
1219                Peak {
1220                    value: peak.map_or(f64::NEG_INFINITY, |p| -p.value),
1221                    time_s: s.time_s,
1222                    height_above_ground_m: s.height_above_ground_m,
1223                }
1224            })
1225        })?;
1226        if found.value.is_finite() {
1227            keep(Peak {
1228                value: -found.value,
1229                ..found
1230            });
1231        }
1232    }
1233    Ok(best)
1234}
1235
1236/// The ejection delay that would fire a motor's charge at apogee.
1237#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1238pub struct OptimumDelay {
1239    /// The motor, by its index in [`hpr_design::Assembly::motors`].
1240    pub motor: usize,
1241    /// When it burned out, s after launch.
1242    pub burnout_s: f64,
1243    /// When the rocket reached apogee with its charges held, s after launch.
1244    pub apogee_s: f64,
1245    /// How high its center of mass was then, m above the launch site.
1246    pub apogee_height_above_ground_m: f64,
1247    /// The delay from its burnout to that apogee, s.
1248    pub delay_s: f64,
1249}
1250
1251/// The optimum ejection delay of each motor that burns out before apogee: the time from its
1252/// burnout to the apogee of the same flight with every recovery charge held, so that the answer
1253/// is a property of the rocket, its motors and its air, and not of the delay flown
1254/// ([Loft lesson L94][l94]).
1255///
1256/// - The held flight holds the stack's devices and any separation with nothing ahead of it left
1257///   to burn, which is part of the recovery, and a mass shift or release fired by a motor's delay,
1258///   whose charge is held. A powered separation still happens, and so does a shift or release
1259///   on any other trigger.
1260/// - A motor that burns out after that apogee, or never lights, has none. Nor does a motor in a
1261///   body a powered separation drops: its charge fires in that body, which never reaches the
1262///   stack's apogee.
1263///
1264/// It is `None` when the held flight has no apogee (it never lifted off, or hit its time cap).
1265///
1266/// # Errors
1267///
1268/// The flight's.
1269///
1270/// [l94]: https://hpr.fusionspace.co/decisions-and-roadmap.html#l94
1271pub fn optimum_delays(simulation: &Simulation) -> Result<Option<Vec<OptimumDelay>>, SimError> {
1272    optimum_delays_observed(simulation, &mut ())
1273}
1274
1275/// [`optimum_delays`], with `observer` seeing the held flight as it flies. Until a held device,
1276/// split, mass shift or release would have fired, the held flight is the one flown, so up to then
1277/// its steps give, for instance, how fast the rocket moves when a delay of that length fires.
1278///
1279/// # Errors
1280///
1281/// The flight's.
1282pub fn optimum_delays_observed(
1283    simulation: &Simulation,
1284    observer: &mut dyn crate::Observer,
1285) -> Result<Option<Vec<OptimumDelay>>, SimError> {
1286    let held = simulation.with_recovery_held();
1287    let result = held.run(observer)?;
1288    let Some((apogee_s, apogee_height_above_ground_m)) = result
1289        .event(EventKind::Apogee)
1290        .map(|event| (event.sample.time_s, event.sample.height_above_ground_m))
1291    else {
1292        return Ok(None);
1293    };
1294    let assembly = simulation.assembly();
1295    // A motor lit by a separation has its time only from the flight's ignition event.
1296    let known = assembly.ignition_times_s(|_| None);
1297    let dropped = |stage: usize| {
1298        result
1299            .bodies
1300            .iter()
1301            .any(|body| (body.stages.0..=body.stages.1).contains(&stage))
1302    };
1303    Ok(Some(
1304        assembly
1305            .motors
1306            .iter()
1307            .enumerate()
1308            .filter(|(_, placed)| !dropped(placed.stage))
1309            .filter_map(|(motor, placed)| {
1310                let ignition_s = result
1311                    .event(EventKind::Ignition(motor))
1312                    .map(|event| event.sample.time_s)
1313                    .or(known.get(motor).copied().flatten())?;
1314                let burnout_s = ignition_s + placed.mounted.motor.burnout_time_s();
1315                (burnout_s <= apogee_s).then_some(OptimumDelay {
1316                    motor,
1317                    burnout_s,
1318                    apogee_s,
1319                    apogee_height_above_ground_m,
1320                    delay_s: apogee_s - burnout_s,
1321                })
1322            })
1323            .collect(),
1324    ))
1325}
1326
1327#[cfg(test)]
1328mod tests {
1329    use hpr_aero::{AeroModel, Flow};
1330    use hpr_atmos::ConstantWind;
1331    use hpr_core::DVec3;
1332    use hpr_design::Rocket;
1333    use serde_json::json;
1334
1335    use super::*;
1336    use crate::envelope::HIGH_ANGLE_MIN_FORCE_SHARE;
1337    use crate::flight::FlightSettings;
1338    use crate::integrator::{Adaptive, Method};
1339    use crate::rail::Rail;
1340    use crate::recorder::{Channel, Recorder};
1341    use crate::recovery::{Device, DeviceDrag, Trigger};
1342    use crate::testing::{UniformAir, analytic_environment, design, site, windy_environment};
1343
1344    const G: f64 = 9.806_65;
1345
1346    fn valetudo(environment: Environment, settings: FlightSettings) -> Simulation {
1347        Simulation::new(
1348            &design("rocketpy-valetudo"),
1349            "example",
1350            environment,
1351            Rail::vertical(3.0),
1352            settings,
1353        )
1354        .unwrap()
1355    }
1356
1357    fn capped(max_time_s: f64) -> FlightSettings {
1358        FlightSettings {
1359            max_time_s,
1360            ..FlightSettings::default()
1361        }
1362    }
1363
1364    fn fly(simulation: &Simulation) -> (FlightResult, FlightMetrics) {
1365        let mut metrics = FlightMetrics::new();
1366        let result = simulation.run(&mut metrics).unwrap();
1367        (result, metrics)
1368    }
1369
1370    /// A conical nose `0.3` m long of radius `R = 0.05` m, a `0.5` m tube, and a conical boattail
1371    /// `0.4` m long down to `r_m`, with no fins: Barrowman gives the nose a slope of 2 at
1372    /// `2/3` of its length and the boattail `2((r/R)² − 1)` at `L/3 · (1 + 1/(1 + R/r))` aft of
1373    /// its fore end (Barrowman's eq. 44, `hpr_aero`'s hand values, L89).
1374    fn nose_and_boattail(r_m: f64) -> AeroModel {
1375        let material = json!({"name": "test", "density": {"kind": "bulk", "kg_m3": 1000.0}});
1376        let rocket: Rocket = serde_json::from_value(json!({
1377            "name": "",
1378            "stages": [{
1379                "id": "stage",
1380                "name": "",
1381                "components": [
1382                    {"id": "nose", "name": "", "part": {"nose_cone": {
1383                        "shape": {"kind": "conical"}, "length_m": 0.3, "base_radius_m": 0.05,
1384                        "wall": {"kind": "filled"}, "shoulder": null, "material": material}}},
1385                    {"id": "tube", "name": "", "part": {"body_tube": {
1386                        "length_m": 0.5, "outer_radius_m": 0.05, "thickness_m": 0.005,
1387                        "material": material}}},
1388                    {"id": "boattail", "name": "", "part": {"transition": {
1389                        "shape": {"kind": "conical"}, "length_m": 0.4, "fore_radius_m": 0.05,
1390                        "aft_radius_m": r_m, "wall": {"kind": "filled"}, "material": material}}}
1391                ]
1392            }],
1393            "reference_diameter": {"kind": "maximum"},
1394            "configurations": []
1395        }))
1396        .unwrap();
1397        AeroModel::new(&rocket.layout().unwrap()).unwrap()
1398    }
1399
1400    /// The hand values of [`nose_and_boattail`]: `(slope, Σ |slopes|, C_mα about x_cg, x_cp)`.
1401    fn nose_and_boattail_by_hand(r_m: f64, cg_m: f64) -> (f64, f64, f64, f64) {
1402        let (big_r, d) = (0.05, 0.1);
1403        let (nose_slope, nose_x) = (2.0, 0.3 * 2.0 / 3.0);
1404        let tail_slope = 2.0 * ((r_m / big_r).powi(2) - 1.0);
1405        let tail_x = 0.8 + 0.4 / 3.0 * (1.0 + 1.0 / (1.0 + big_r / r_m));
1406        let slope = nose_slope + tail_slope;
1407        let moment = -(nose_slope * (nose_x - cg_m) + tail_slope * (tail_x - cg_m)) / d;
1408        let cp = (nose_slope * nose_x + tail_slope * tail_x) / slope;
1409        (slope, nose_slope + tail_slope.abs(), moment, cp)
1410    }
1411
1412    fn close(got: f64, want: f64, rel: f64, what: &str) {
1413        let err = ((got - want) / want).abs();
1414        assert!(
1415            err <= rel,
1416            "{what}: got {got}, want {want}, rel err {err:e}"
1417        );
1418    }
1419
1420    #[test]
1421    fn static_margin_undefined_when_cn_alpha_near_zero() {
1422        // L33: a boattail down to a tenth of the radius all but cancels the nose's slope
1423        // (2 − 1.98 = 0.02 against a sum of 3.98). The quotient still exists, and it is the kind
1424        // of number Loft published: hundreds of calibers.
1425        let cg_m = 0.5;
1426        let aero = nose_and_boattail(0.005);
1427        let (slope, sum, moment, cp) = nose_and_boattail_by_hand(0.005, cg_m);
1428        let raw = aero.normal_force(&Flow::axial(0.0)).unwrap();
1429        close(raw.slope_per_rad, slope, 1e-9, "net slope");
1430        close(raw.cp_station_m.unwrap(), cp, 1e-9, "the quotient");
1431        assert!(
1432            ((cp - cg_m) / 0.1).abs() > 100.0,
1433            "a margin of {} cal",
1434            (cp - cg_m) / 0.1
1435        );
1436        let static_margin = stability(&aero, 0.0, 0.0, 0.0, cg_m, 0.3)
1437            .unwrap()
1438            .static_margin;
1439        assert_eq!(static_margin.margin_cal, None);
1440        assert_eq!(static_margin.cp_station_m, None);
1441        close(
1442            static_margin.slope_magnitude_sum_per_rad,
1443            sum,
1444            1e-12,
1445            "Σ |slopes|",
1446        );
1447        // The couple stays: finite, and destabilizing (positive).
1448        close(
1449            static_margin.pitch_moment_slope_per_rad,
1450            moment,
1451            1e-9,
1452            "C_mα",
1453        );
1454        assert!(moment > 0.0);
1455
1456        // Both sides of the limit: κ = Σ|C_Nα,i| / C_Nα = 2/ρ² − 1 with ρ = r/R, so the margin
1457        // is given from κ = √10, ρ = √(2/(1 + √10)) = 0.6932, up.
1458        for (r_m, defined) in [
1459            (0.035, true),
1460            (0.0345, false),
1461            (0.04, true),
1462            (0.0215, false),
1463        ] {
1464            let (slope, sum, moment, cp) = nose_and_boattail_by_hand(r_m, cg_m);
1465            assert_eq!(sum / slope <= MARGIN_CONDITION_LIMIT, defined, "r = {r_m}");
1466            let m = margin(&nose_and_boattail(r_m), &Flow::axial(0.0), cg_m).unwrap();
1467            close(m.pitch_moment_slope_per_rad, moment, 1e-9, "C_mα");
1468            if defined {
1469                close(m.margin_cal.unwrap(), (cp - cg_m) / 0.1, 1e-9, "margin");
1470                // C_mα = −C_Nα · margin.
1471                close(
1472                    m.pitch_moment_slope_per_rad,
1473                    -slope * m.margin_cal.unwrap(),
1474                    1e-9,
1475                    "C_mα",
1476                );
1477            } else {
1478                assert_eq!(m.margin_cal, None, "r = {r_m}");
1479            }
1480        }
1481    }
1482
1483    /// A rocket with one fin at 0° and a pair at `pair_rad`: the pair is edge-on to air crossing
1484    /// in its own plane, and the lone fin to air crossing in its. A fin set of one or two fins
1485    /// carries `Σ sin²(φ − θ_k)` of its force in the plane at `φ` (Niskanen 2009 eq. 3.51).
1486    fn uneven_fins(single_m: f64, pair_m: f64, pair_rad: f64) -> AeroModel {
1487        let material = json!({"name": "test", "density": {"kind": "bulk", "kg_m3": 1000.0}});
1488        let fins = |id: &str, count: u32, angle_rad: f64, span_m: f64| {
1489            json!({"id": id, "name": "", "part": {"fin_set": {
1490                "count": count, "base_angle_rad": angle_rad,
1491                "planform": {"kind": "trapezoidal", "root_chord_m": 0.12, "tip_chord_m": 0.06,
1492                    "span_m": span_m, "sweep_m": 0.05},
1493                "thickness_m": 0.003, "cross_section": "rounded", "tab": null,
1494                "cant_rad": 0.0, "material": material}},
1495                "position": {"from": "bottom", "aft_offset_m": 0.0}})
1496        };
1497        let rocket: Rocket = serde_json::from_value(json!({
1498            "name": "",
1499            "stages": [{"id": "stage", "name": "", "components": [
1500                {"id": "nose", "name": "", "part": {"nose_cone": {
1501                    "shape": {"kind": "conical"}, "length_m": 0.2, "base_radius_m": 0.025,
1502                    "wall": {"kind": "filled"}, "shoulder": null, "material": material}}},
1503                {"id": "tube", "name": "", "part": {"body_tube": {"length_m": 0.6,
1504                    "outer_radius_m": 0.025, "thickness_m": 0.001, "material": material}},
1505                    "children": [
1506                        fins("single", 1, 0.0, single_m),
1507                        fins("pair", 2, pair_rad, pair_m)
1508                    ]}
1509            ]}],
1510            "reference_diameter": {"kind": "maximum"},
1511            "configurations": []
1512        }))
1513        .unwrap();
1514        AeroModel::new(&rocket.layout().unwrap()).unwrap()
1515    }
1516
1517    /// The least margin over the direction the air crosses the rocket (#329): never above any
1518    /// plane's, met in a plane a fine scan can't beat, and found in closed form wherever it is.
1519    /// A rocket whose fin sets are each of three or more keeps its axial margin bit for bit.
1520    #[test]
1521    fn the_least_margin_is_the_weakest_plane_s() {
1522        let scan = |aero: &AeroModel, mach: f64, cg_m: f64| {
1523            (0..3600)
1524                .map(|k| {
1525                    let roll = std::f64::consts::PI * f64::from(k) / 3600.0;
1526                    margin(aero, &Flow::new(mach, 0.0, roll), cg_m).unwrap()
1527                })
1528                .collect::<Vec<_>>()
1529        };
1530        // Spans either way round, and centers of mass either side of a margin that vanishes in
1531        // some planes. With the pair at right angles to the lone fin every sum is even in `φ`
1532        // (`c = 0`), and the weak plane lies on a fin's plane; with it at 0.6 rad the weak plane
1533        // lies between them, where a wrong sign on the `sin 2φ` terms would land on a strong one.
1534        let right = std::f64::consts::FRAC_PI_2;
1535        let mut off_fins = 0;
1536        for (single_m, pair_m, pair_rad) in [
1537            (0.06, 0.03, right),
1538            (0.03, 0.06, right),
1539            (0.05, 0.05, right),
1540            (0.07, 0.02, right),
1541            (0.06, 0.03, 0.6),
1542            (0.03, 0.06, 0.6),
1543        ] {
1544            let aero = uneven_fins(single_m, pair_m, pair_rad);
1545            assert!(aero.rolls());
1546            for mach in [0.1, 0.6, 1.5] {
1547                for cg_m in [0.35, 0.45, 0.55] {
1548                    let least = weakest_margin(&aero, mach, cg_m).unwrap();
1549                    let planes = scan(&aero, mach, cg_m);
1550                    let at = margin(&aero, &Flow::new(mach, 0.0, least.roll_rad), cg_m).unwrap();
1551                    assert_eq!(at, least, "the least margin is its plane's");
1552                    // Distance, in the margin's period of π, to the nearest plane of a fin or
1553                    // square to one.
1554                    let off = [0.0, right, pair_rad, pair_rad + right]
1555                        .iter()
1556                        .map(|plane| {
1557                            let d = (least.roll_rad - plane).rem_euclid(std::f64::consts::PI);
1558                            d.min(std::f64::consts::PI - d)
1559                        })
1560                        .fold(f64::INFINITY, f64::min);
1561                    if off > 0.05 {
1562                        off_fins += 1;
1563                    }
1564                    match least.margin_cal {
1565                        None => assert!(
1566                            planes.iter().any(|m| m.margin_cal.is_none()) || {
1567                                // The plane where no margin can be given lies between two scan lines.
1568                                let near = |m: &Margin| {
1569                                    m.slope_magnitude_sum_per_rad
1570                                        / m.normal_force_slope_per_rad.max(f64::MIN_POSITIVE)
1571                                };
1572                                planes.iter().map(near).fold(0.0, f64::max)
1573                                    > 0.99 * MARGIN_CONDITION_LIMIT
1574                            }
1575                        ),
1576                        Some(cal) => {
1577                            for m in &planes {
1578                                let plane = m.margin_cal.expect("a margin in every plane");
1579                                assert!(
1580                                    cal <= plane + 1e-12,
1581                                    "{cal} above {plane} at {}",
1582                                    m.roll_rad
1583                                );
1584                            }
1585                            let scanned = planes
1586                                .iter()
1587                                .filter_map(|m| m.margin_cal)
1588                                .fold(f64::INFINITY, f64::min);
1589                            assert!(scanned - cal < 1e-5, "{cal} against the scan's {scanned}");
1590                        }
1591                    }
1592                }
1593            }
1594        }
1595        assert!(off_fins > 0, "no weak plane off the fins' planes");
1596        // With the pair the larger, the axial plane, where it works whole, is the strong one: the
1597        // reported margin is well below it.
1598        let aero = uneven_fins(0.03, 0.06, right);
1599        let axial = margin(&aero, &Flow::axial(0.3), 0.45)
1600            .unwrap()
1601            .margin_cal
1602            .unwrap();
1603        let least = weakest_margin(&aero, 0.3, 0.45)
1604            .unwrap()
1605            .margin_cal
1606            .unwrap();
1607        assert!(least < axial - 0.5, "{least} against {axial}");
1608        // Even fins: the axial margin, bit for bit.
1609        for name in [
1610            "synthetic-54mm-three-fin",
1611            "rocketpy-valetudo",
1612            "rocketpy-juno-iii",
1613        ] {
1614            let aero = AeroModel::new(&design(name).layout().unwrap()).unwrap();
1615            assert!(!aero.rolls(), "{name}");
1616            for mach in [0.0, 0.3, 1.2] {
1617                assert_eq!(
1618                    weakest_margin(&aero, mach, 1.0).unwrap(),
1619                    margin(&aero, &Flow::axial(mach), 1.0).unwrap(),
1620                    "{name}"
1621                );
1622            }
1623        }
1624    }
1625
1626    #[test]
1627    fn ordinary_rockets_keep_their_margin() {
1628        // The other side of the limit: every design in `validation/designs/`, at Mach 0 to 2 and
1629        // angles of attack of 0° to 20° (the points below), is far from it. Its slopes nearly all push one way.
1630        let mut worst: f64 = 0.0;
1631        for name in [
1632            "synthetic-54mm-three-fin",
1633            "rocketpy-valetudo",
1634            "rocketpy-calisto-tests-motor-at-minus-1.373",
1635            "rocketpy-ndrt-2020-nose-to-tail",
1636            "rocketpy-prometheus-2022-generic-motor",
1637            "rocketpy-juno-iii",
1638            "synthetic-two-stage-75mm-54mm",
1639            "mil-hdbk-762-sample-rocket",
1640            "rocketpy-bella-lui",
1641            "rocketpy-calisto-getting-started-motor-at-minus-1.255",
1642            "rocketpy-cavour",
1643            "wind-tunnel-arcas-robin-long",
1644            "wind-tunnel-arcas-robin-short",
1645        ] {
1646            let aero = AeroModel::new(&design(name).layout().unwrap()).unwrap();
1647            for mach in [0.0, 0.3, 0.8, 1.2, 2.0] {
1648                for alpha_deg in [0.0, 5.0, 10.0, 20.0] {
1649                    let flow = Flow::new(mach, f64::to_radians(alpha_deg), 0.0);
1650                    let m = margin(&aero, &flow, 0.0).unwrap();
1651                    assert!(m.margin_cal.is_some(), "{name} at {mach}, {alpha_deg}°");
1652                    worst = worst.max(m.slope_magnitude_sum_per_rad / m.normal_force_slope_per_rad);
1653                }
1654            }
1655        }
1656        // 1.35 at worst.
1657        assert!(worst < 1.5, "{worst}");
1658    }
1659
1660    #[test]
1661    fn a_pure_couple_keeps_its_moment() {
1662        // A nose (slope 2 at 0.2 m), then a step down from R = 0.05 m to 0.03 m at 0.8 m and a
1663        // conical flare back to 0.05 m over 0.2 m: the step's −2(1 − 0.36) = −1.28 at 0.8 m and
1664        // the flare's +1.28 at 0.8 + (0.2/3)(1 + 1/1.6) m cancel, leaving that component a pure
1665        // couple. It still turns the rocket.
1666        let material = json!({"name": "test", "density": {"kind": "bulk", "kg_m3": 1000.0}});
1667        let tube = |length_m: f64| {
1668            json!({"body_tube": {"length_m": length_m, "outer_radius_m": 0.05,
1669                "thickness_m": 0.005, "material": material}})
1670        };
1671        let rocket: Rocket = serde_json::from_value(json!({
1672            "name": "",
1673            "stages": [{"id": "stage", "name": "", "components": [
1674                {"id": "nose", "name": "", "part": {"nose_cone": {
1675                    "shape": {"kind": "conical"}, "length_m": 0.3, "base_radius_m": 0.05,
1676                    "wall": {"kind": "filled"}, "shoulder": null, "material": material}}},
1677                {"id": "tube", "name": "", "part": tube(0.5)},
1678                {"id": "flare", "name": "", "part": {"transition": {
1679                    "shape": {"kind": "conical"}, "length_m": 0.2, "fore_radius_m": 0.03,
1680                    "aft_radius_m": 0.05, "wall": {"kind": "filled"}, "material": material}}},
1681                {"id": "tail", "name": "", "part": tube(0.3)}
1682            ]}],
1683            "reference_diameter": {"kind": "maximum"},
1684            "configurations": []
1685        }))
1686        .unwrap();
1687        let aero = AeroModel::new(&rocket.layout().unwrap()).unwrap();
1688        let cg_m = 0.6;
1689        let couple = -1.28 * 0.8 + 1.28 * (0.8 + 0.2 / 3.0 * (1.0 + 1.0 / 1.6));
1690        let m = margin(&aero, &Flow::axial(0.0), cg_m).unwrap();
1691        close(m.normal_force_slope_per_rad, 2.0, 1e-12, "net slope");
1692        let cp = (2.0 * 0.2 + couple) / 2.0;
1693        close(m.margin_cal.unwrap(), (cp - cg_m) / 0.1, 1e-9, "margin");
1694        let moment = -(2.0 * 0.2 + couple - 2.0 * cg_m) / 0.1;
1695        close(m.pitch_moment_slope_per_rad, moment, 1e-9, "C_mα");
1696        close(
1697            m.pitch_moment_slope_per_rad,
1698            -2.0 * m.margin_cal.unwrap(),
1699            1e-12,
1700            "−C_Nα · margin",
1701        );
1702    }
1703
1704    #[test]
1705    fn a_normal_force_table_gives_its_own_margin() {
1706        // A table of one column: C_Nα = 10 on the rocket's reference area, at 1.2 m at every Mach
1707        // number. The margin is the table's, and κ is 1.
1708        use hpr_aero::{NormalForceColumn, NormalForceTable};
1709        use hpr_core::interp::{Extrapolation, Interpolation, Table1D};
1710        let constant = |y: f64| {
1711            Table1D::new(
1712                vec![0.0, 2.0],
1713                vec![y, y],
1714                Interpolation::Linear,
1715                Extrapolation::Clamp,
1716            )
1717            .unwrap()
1718        };
1719        let table = NormalForceTable::new(vec![NormalForceColumn::new(
1720            0.0,
1721            constant(10.0),
1722            constant(1.2),
1723        )])
1724        .unwrap();
1725        let sim = valetudo(Environment::standard(site()).unwrap(), capped(60.0))
1726            .with_normal_force_table(table)
1727            .unwrap();
1728        let d = sim.aero().reference_diameter_m();
1729        let m = margin(sim.aero(), &Flow::axial(0.3), 0.8).unwrap();
1730        close(m.normal_force_slope_per_rad, 10.0, 1e-12, "slope");
1731        assert_eq!(m.slope_magnitude_sum_per_rad, m.normal_force_slope_per_rad);
1732        close(m.margin_cal.unwrap(), (1.2 - 0.8) / d, 1e-12, "margin");
1733        close(
1734            m.pitch_moment_slope_per_rad,
1735            -10.0 * (1.2 - 0.8) / d,
1736            1e-12,
1737            "C_mα",
1738        );
1739    }
1740
1741    #[test]
1742    fn peak_acceleration_is_analytic_and_excludes_opening_shock() {
1743        // L34, first half: a vertical boost in a vacuum under uniform gravity, with no rotation.
1744        // The nose tip's acceleration is (T − m r″ − 2ṁ r′ + m̈(n − r))/m − g along the axis, from
1745        // the motor and the assembly directly (as the powered-climb test integrates it). Its
1746        // largest value on a fine scan, and at every thrust-curve knot from both sides, is the
1747        // peak.
1748        let sim = valetudo(analytic_environment(UniformAir::vacuum(), G), capped(4.0));
1749        let (_, metrics) = fly(&sim);
1750        let assembly = sim.assembly();
1751        let placed = &assembly.motors[0];
1752        let motor = &placed.mounted.motor;
1753        let burnout_s = motor.burnout_time_s();
1754        let h = 1e-5;
1755        let mut knots: Vec<f64> = motor
1756            .curve()
1757            .times_s()
1758            .iter()
1759            .copied()
1760            .filter(|t| *t > 0.0 && *t < burnout_s)
1761            .collect();
1762        knots.insert(0, 0.0);
1763        knots.push(burnout_s);
1764        let props = |t: f64| assembly.mass_properties(t);
1765        // On the knot interval [a, b], derivatives taken inside it and extended to t.
1766        let by_hand = |t: f64, a: f64, b: f64| {
1767            let c = t.clamp(a + h, b - h);
1768            let (m, r) = (props(t).mass_kg, props(t).cg_m.z);
1769            let r_mid = props(c).cg_m.z;
1770            let r2 = (props(c + h).cg_m.z - 2.0 * r_mid + props(c - h).cg_m.z) / (h * h);
1771            let r1 = (props(c + h).cg_m.z - props(c - h).cg_m.z) / (2.0 * h) + (t - c) * r2;
1772            let mdot = -motor.state(t).mass_flow_kg_s;
1773            let mddot = -(motor.state(c + h).mass_flow_kg_s - motor.state(c - h).mass_flow_kg_s)
1774                / (2.0 * h);
1775            let thrust = motor.thrust_at_pressure_n(t, 0.0);
1776            (thrust - m * r2 - 2.0 * mdot * r1 + mddot * (placed.nozzle_m.z - r)) / m - G
1777        };
1778        let mut expected: f64 = 0.0;
1779        for pair in knots.windows(2) {
1780            let (a, b) = (pair[0], pair[1]);
1781            let n = 2000;
1782            for i in 0..=n {
1783                let t = a + (b - a) * f64::from(i) / f64::from(n);
1784                expected = expected.max(by_hand(t, a, b));
1785            }
1786        }
1787        let peak = metrics.max_acceleration.unwrap();
1788        close(peak.value, expected, 1e-6, "peak acceleration");
1789        assert!(peak.time_s < burnout_s);
1790        // What Loft did: a finite difference of the speed recorded at 100 Hz, which averages the
1791        // acceleration over each interval and reads the thrust spike low.
1792        let mut recorder =
1793            Recorder::new(vec![Channel::Time, Channel::Velocity], Some(0.01)).unwrap();
1794        sim.run(&mut recorder).unwrap();
1795        let rows = recorder.rows();
1796        let differenced = rows
1797            .windows(2)
1798            .map(|w| (w[1][3] - w[0][3]) / (w[1][0] - w[0][0]))
1799            .fold(0.0, f64::max);
1800        // 1.3% low on this motor's first ramp.
1801        assert!(
1802            differenced < 0.99 * peak.value,
1803            "{differenced} vs {}",
1804            peak.value
1805        );
1806
1807        // Second half: the same boost in air, with a large canopy opening at once while the rocket
1808        // still climbs fast. The boost's peak is the flight's without the canopy, and the opening
1809        // shock, several times larger, is kept apart.
1810        let air = || analytic_environment(UniformAir::sea_level(), G);
1811        let (_, plain) = fly(&valetudo(air(), capped(60.0)));
1812        let canopy = Device::new(
1813            "main",
1814            DeviceDrag::DragArea { cd_s_m2: 4.0 },
1815            Trigger::Time { time_s: 4.0 },
1816        );
1817        let early = valetudo(air(), capped(60.0))
1818            .with_recovery(vec![canopy])
1819            .unwrap();
1820        let (result, shocked) = fly(&early);
1821        let deployed = result.event(EventKind::Deployment(0)).unwrap().sample;
1822        assert!(deployed.airspeed_m_s > 100.0, "{}", deployed.airspeed_m_s);
1823        let boost = shocked.max_acceleration.unwrap();
1824        close(
1825            boost.value,
1826            plain.max_acceleration.unwrap().value,
1827            1e-12,
1828            "boost peak",
1829        );
1830        let shock = shocked.max_descent_acceleration.unwrap();
1831        assert!(
1832            shock.value > 3.0 * boost.value,
1833            "{} vs {}",
1834            shock.value,
1835            boost.value
1836        );
1837        assert_eq!(shock.time_s, deployed.time_s);
1838        assert_eq!(plain.max_descent_acceleration, None);
1839    }
1840
1841    #[test]
1842    fn the_opening_shock_is_the_drag_over_the_mass_without_gravity() {
1843        // #1258: under a canopy the motion's acceleration is (D + W)/m. Falling straight down,
1844        // the drag points up and the weight down, so |a| = D/m − g, low by g. The opening load
1845        // over the mass is D/m (Knacke, NWC TP 6575, p. 5-50: F = (C_D S) q C_x X₁; the canopy
1846        // opens at once here, so C_x X₁ = 1).
1847        let air = || analytic_environment(UniformAir::sea_level(), G);
1848        let (plain, _) = fly(&valetudo(air(), capped(600.0)));
1849        let apogee_s = plain.event(EventKind::Apogee).unwrap().sample.time_s;
1850        let cd_s_m2 = 0.5;
1851        let drogue = Device::new(
1852            "drogue",
1853            DeviceDrag::DragArea { cd_s_m2 },
1854            Trigger::Time {
1855                time_s: apogee_s + 5.0,
1856            },
1857        );
1858        let sim = valetudo(air(), capped(600.0))
1859            .with_recovery(vec![drogue])
1860            .unwrap();
1861        let (result, metrics) = fly(&sim);
1862        let deployed = result.event(EventKind::Deployment(0)).unwrap().sample;
1863        // Falling, nearly straight down (the vertical flight's arc leans a little), in still air.
1864        let velocity = deployed.cg_velocity_enu_m_s;
1865        assert!(velocity.z < -40.0, "{velocity}");
1866        assert!(velocity.z.abs() > 0.99 * velocity.length(), "{velocity}");
1867        let drag_per_kg = deployed.dynamic_pressure_pa * cd_s_m2 / deployed.mass_kg;
1868        let shock = metrics.max_descent_acceleration.unwrap();
1869        close(shock.value, drag_per_kg, 1e-9, "opening shock");
1870        assert_eq!(shock.time_s, deployed.time_s);
1871        // What the motion's |a| reads there, what was reported before: about g less, as the hand
1872        // relation |a| ≈ D/m − g cos θ (θ from the vertical) has it.
1873        let motion = deployed.acceleration_enu_m_s2.length();
1874        let hand = drag_per_kg - G * velocity.z.abs() / velocity.length();
1875        assert!((motion - hand).abs() < 0.05, "{motion} vs {hand}");
1876        assert!(
1877            shock.value - motion > 0.99 * G,
1878            "{} vs {motion}",
1879            shock.value
1880        );
1881        // The deployment's airspeed, kept for the opening load: still air, so the speed's.
1882        let airspeed = metrics.max_deployment_airspeed.unwrap();
1883        close(
1884            airspeed.value,
1885            velocity.length(),
1886            1e-9,
1887            "deployment airspeed",
1888        );
1889        assert_eq!(airspeed.time_s, deployed.time_s);
1890        // At the ground the drogue has long reached its steady fall: the drag holds the weight,
1891        // so the specific force is g, up, and the motion's acceleration nearly nothing.
1892        let landed = result.event(EventKind::GroundHit).unwrap().sample;
1893        let force = landed.specific_force_enu_m_s2;
1894        close(force.length(), G, 1e-3, "steady specific force");
1895        assert!(force.z > 0.999 * force.length(), "{force}");
1896        assert!(
1897            landed.acceleration_enu_m_s2.length() < 1e-3 * G,
1898            "{}",
1899            landed.acceleration_enu_m_s2
1900        );
1901    }
1902
1903    #[test]
1904    fn unlanded_flight_has_no_ground_hit_speed_and_outputs_name_datum() {
1905        // L35: a flight stopped by its time cap at 5 s has no landing, no ground-hit speed and no
1906        // apogee, and says so with `None`, not a zero.
1907        let environment = || Environment::standard(site()).unwrap();
1908        let sim = valetudo(environment(), capped(5.0));
1909        let (result, metrics) = fly(&sim);
1910        assert_eq!(result.termination, Termination::TimeCap);
1911        let summary = metrics.summary(&result, sim.environment()).unwrap();
1912        assert_eq!(summary.landing, None);
1913        assert_eq!(summary.ground_hit_speed_m_s(), None);
1914        assert_eq!(summary.apogee, None);
1915        assert_eq!(summary.max_descent_acceleration_m_s2, None);
1916        let json = serde_json::to_value(&summary).unwrap();
1917        assert_eq!(json["landing"], serde_json::Value::Null);
1918        assert_eq!(json["apogee"], serde_json::Value::Null);
1919
1920        // The whole flight: the heights name their datum. The center of mass starts above the
1921        // site, the apogee's gain counts from there, and the landing is on the site's ellipsoidal
1922        // height, where the flight stops.
1923        let sim = valetudo(environment(), capped(600.0));
1924        let (result, metrics) = fly(&sim);
1925        let summary = metrics.summary(&result, sim.environment()).unwrap();
1926        // On a vertical rail the nose tip starts at the aft guide's station above the site, and
1927        // the center of mass that far less its own station.
1928        let start = summary.launch_height_m.unwrap();
1929        let cg_station_m = -sim.assembly().mass_properties(0.0).cg_m.z;
1930        close(
1931            start,
1932            sim.guides().aft_station_m - cg_station_m,
1933            1e-9,
1934            "start",
1935        );
1936        let apogee = summary.apogee.unwrap();
1937        assert_eq!(apogee.gain_m, Some(apogee.height_above_ground_m - start));
1938        let landing = summary.landing.unwrap();
1939        assert_eq!(
1940            summary.ground_hit_speed_m_s(),
1941            Some(landing.ground_hit_speed_m_s)
1942        );
1943        assert!(result.final_sample.height_above_ground_m.abs() < 1e-6);
1944        let json = serde_json::to_value(&summary).unwrap();
1945        for field in ["launch_height_m", "apogee"] {
1946            assert!(
1947                json[field].is_number() || json[field].is_object(),
1948                "{field}"
1949            );
1950        }
1951        assert!(json["apogee"]["height_above_ground_m"].is_number());
1952        assert!(json["apogee"]["gain_m"].is_number());
1953    }
1954
1955    #[test]
1956    fn optimum_delay_independent_of_flown_delay() {
1957        // L94: a delay of 1 s opens the canopy while the rocket climbs; one of 20 s opens it long
1958        // after apogee. The optimum is the same for both, and is the time from burnout to the
1959        // apogee of a flight with no recovery at all.
1960        let environment = || Environment::standard(site()).unwrap();
1961        let flown = |delay_s: f64| {
1962            valetudo(environment(), capped(600.0))
1963                .with_recovery(vec![Device::new(
1964                    "main",
1965                    DeviceDrag::DragArea { cd_s_m2: 1.0 },
1966                    Trigger::Burnout { motor: 0, delay_s },
1967                )])
1968                .unwrap()
1969        };
1970        let (early, late) = (flown(1.0), flown(20.0));
1971        let bare = valetudo(environment(), capped(600.0));
1972        let bare_apogee_s = bare
1973            .run(&mut ())
1974            .unwrap()
1975            .event(EventKind::Apogee)
1976            .unwrap()
1977            .sample
1978            .time_s;
1979        let early_result = early.run(&mut ()).unwrap();
1980        let opened_s = early_result
1981            .event(EventKind::Deployment(0))
1982            .unwrap()
1983            .sample
1984            .time_s;
1985        assert!(
1986            opened_s < bare_apogee_s - 5.0,
1987            "{opened_s} vs {bare_apogee_s}"
1988        );
1989
1990        let a = optimum_delays(&early).unwrap().unwrap();
1991        let b = optimum_delays(&late).unwrap().unwrap();
1992        assert_eq!(a, b);
1993        assert_eq!(a.len(), 1);
1994        let burnout_s = bare.assembly().motors[0].mounted.motor.burnout_time_s();
1995        assert_eq!(a[0].burnout_s, burnout_s);
1996        close(a[0].apogee_s, bare_apogee_s, 1e-9, "apogee");
1997        close(a[0].delay_s, bare_apogee_s - burnout_s, 1e-9, "delay");
1998        // It doesn't touch the simulation it was given.
1999        assert_eq!(early.run(&mut ()).unwrap(), early_result);
2000    }
2001
2002    #[test]
2003    fn peaks_are_refined_inside_steps() {
2004        // Max q and max Mach come between the integrator's steps, some in a step's outer quarter,
2005        // where its middle sample is below an end. On each rocket every peak is at least every
2006        // sample of a millisecond record, and within the record's spacing of the best.
2007        for (name, configuration) in [
2008            ("rocketpy-valetudo", "example"),
2009            ("rocketpy-juno-iii", "example"),
2010            ("rocketpy-calisto-tests-motor-at-minus-1.373", "example"),
2011        ] {
2012            let sim = Simulation::new(
2013                &design(name),
2014                configuration,
2015                Environment::standard(site()).unwrap(),
2016                Rail::vertical(5.0),
2017                capped(20.0),
2018            )
2019            .unwrap();
2020            let mut recorder = Recorder::new(
2021                vec![Channel::Time, Channel::DynamicPressure, Channel::Mach],
2022                Some(1e-3),
2023            )
2024            .unwrap();
2025            sim.run(&mut recorder).unwrap();
2026            let (result, metrics) = fly(&sim);
2027            let summary = metrics.summary(&result, sim.environment()).unwrap();
2028            for (column, peak) in [
2029                (1, summary.max_dynamic_pressure_pa.unwrap()),
2030                (2, summary.max_mach.unwrap()),
2031            ] {
2032                let recorded = recorder
2033                    .rows()
2034                    .iter()
2035                    .map(|row| row[column])
2036                    .fold(0.0, f64::max);
2037                assert!(
2038                    peak.value >= recorded,
2039                    "{name}: {} < {recorded}",
2040                    peak.value
2041                );
2042                assert!(
2043                    peak.value - recorded < 1e-4 * peak.value,
2044                    "{name}: {}",
2045                    peak.value
2046                );
2047            }
2048            if name == "rocketpy-valetudo" {
2049                // At the speed's peak the acceleration is zero, so q = ½ρv² falls there with the
2050                // density (dq/dt = ½v² dρ/dt < 0) and peaked earlier; the Mach number still rises
2051                // with the falling speed of sound, and peaks later.
2052                let (q, mach) = (
2053                    summary.max_dynamic_pressure_pa.unwrap(),
2054                    summary.max_mach.unwrap(),
2055                );
2056                let speed = summary.max_speed_m_s.unwrap();
2057                assert!(q.time_s < speed.time_s, "{} vs {}", q.time_s, speed.time_s);
2058                assert!(
2059                    speed.time_s < mach.time_s,
2060                    "{} vs {}",
2061                    speed.time_s,
2062                    mach.time_s
2063                );
2064                assert!(q.height_above_ground_m > 0.0);
2065            }
2066        }
2067    }
2068
2069    #[test]
2070    fn landings_are_placed_on_the_ellipsoid() {
2071        // A 6 m/s wind from the west carries the rocket east. Over a few hundred meters the
2072        // landing's latitude and longitude are the site's plus the local displacement over the
2073        // radii of curvature M and N at the site's height, to second order in distance/radius.
2074        let wind = ConstantWind::new(6.0, 1.5 * std::f64::consts::PI).unwrap();
2075        let canopy = Device::new(
2076            "main",
2077            DeviceDrag::DragArea { cd_s_m2: 0.5 },
2078            Trigger::Apogee,
2079        );
2080        let sim = Simulation::new(
2081            &design("rocketpy-valetudo"),
2082            "example",
2083            windy_environment(wind),
2084            Rail::vertical(3.0),
2085            capped(600.0),
2086        )
2087        .unwrap()
2088        .with_recovery(vec![canopy])
2089        .unwrap();
2090        let (result, metrics) = fly(&sim);
2091        let summary = metrics.summary(&result, sim.environment()).unwrap();
2092        let landing = summary.landing.unwrap();
2093        assert!(landing.east_m > 100.0, "{}", landing.east_m);
2094        let place = site();
2095        let (a, f) = (6_378_137.0, 1.0 / 298.257_223_563);
2096        let e2 = f * (2.0 - f);
2097        let s = place.latitude_rad.sin();
2098        let w = (1.0 - e2 * s * s).sqrt();
2099        let n = a / w + place.height_m;
2100        let m = a * (1.0 - e2) / (w * w * w) + place.height_m;
2101        let lat = place.latitude_rad + landing.north_m / m;
2102        let lon = place.longitude_rad + landing.east_m / (n * place.latitude_rad.cos());
2103        let second_order = (landing.distance_m / a).powi(2);
2104        assert!((landing.latitude_deg.to_radians() - lat).abs() < 10.0 * second_order);
2105        assert!((landing.longitude_deg.to_radians() - lon).abs() < 10.0 * second_order);
2106        close(
2107            landing.distance_m,
2108            landing.east_m.hypot(landing.north_m),
2109            1e-15,
2110            "distance",
2111        );
2112        assert_eq!(landing.body, None);
2113        assert!(landing.descent_rate_m_s > 0.0);
2114    }
2115
2116    #[test]
2117    fn stability_is_kept_from_rail_exit_to_apogee() {
2118        let sim = valetudo(Environment::standard(site()).unwrap(), capped(600.0));
2119        let (result, metrics) = fly(&sim);
2120        let summary = metrics.summary(&result, sim.environment()).unwrap();
2121        let series = metrics.stability();
2122        let exit_s = result.event(EventKind::RailExit).unwrap().sample.time_s;
2123        let apogee_s = summary.apogee.unwrap().time_s;
2124        assert_eq!(series.first().unwrap().time_s, exit_s);
2125        assert_eq!(series.last().unwrap().time_s, apogee_s);
2126        assert!(series.windows(2).all(|w| w[0].time_s < w[1].time_s));
2127        // The static margin at the rail exit: the center of pressure at Mach 0 against the center
2128        // of mass then, from the assembly and the aerodynamic model directly.
2129        let first = series[0];
2130        let lit = sim.assembly().ignition_times_s(|_| None);
2131        let cg_m = -sim.assembly().mass_properties_lit(exit_s, &lit).cg_m.z;
2132        close(first.cg_station_m, cg_m, 1e-12, "center of mass");
2133        let cp_m = sim
2134            .aero()
2135            .normal_force(&Flow::axial(0.0))
2136            .unwrap()
2137            .cp_station_m
2138            .unwrap();
2139        let d = sim.aero().reference_diameter_m();
2140        close(
2141            first.static_margin.margin_cal.unwrap(),
2142            (cp_m - cg_m) / d,
2143            1e-12,
2144            "static margin",
2145        );
2146        assert_eq!(summary.rail_exit_stability, Some(first));
2147        let min = summary.min_static_margin_cal.unwrap();
2148        assert!(
2149            series
2150                .iter()
2151                .all(|s| s.static_margin.margin_cal.unwrap() >= min.value)
2152        );
2153        // The least margins are found inside steps, so they are at or below every entry.
2154        let least = summary.min_flight_margin_cal.unwrap();
2155        assert!(
2156            series
2157                .iter()
2158                .all(|s| s.flight_margin.margin_cal.unwrap() >= least.value)
2159        );
2160        assert!(least.value > 3.0, "{least:?}");
2161
2162        // The flight margin is the model's at the flight's own Mach number with the air along the
2163        // axis, whatever the angle of attack: at the rail exit in a crosswind the rocket meets the
2164        // air more than 0.2 rad off its axis, and the margin leaves that out.
2165        let windy = valetudo(
2166            windy_environment(ConstantWind::new(5.0, 1.5 * std::f64::consts::PI).unwrap()),
2167            capped(600.0),
2168        );
2169        let (result, metrics) = fly(&windy);
2170        let summary = metrics.summary(&result, windy.environment()).unwrap();
2171        let exit = result.event(EventKind::RailExit).unwrap().sample;
2172        assert!(
2173            exit.angle_of_attack_rad > 0.2,
2174            "{}",
2175            exit.angle_of_attack_rad
2176        );
2177        let cg_m = -windy
2178            .assembly()
2179            .mass_properties_lit(exit.time_s, &lit)
2180            .cg_m
2181            .z;
2182        let expected = margin(windy.aero(), &Flow::axial(exit.mach), cg_m).unwrap();
2183        let got = summary.rail_exit_stability.unwrap().flight_margin;
2184        assert_eq!(got.angle_of_attack_rad, 0.0);
2185        close(got.mach, exit.mach, 1e-12, "Mach number");
2186        close(
2187            got.margin_cal.unwrap(),
2188            expected.margin_cal.unwrap(),
2189            1e-12,
2190            "flight margin",
2191        );
2192    }
2193
2194    #[test]
2195    fn least_margins_do_not_depend_on_where_steps_end() {
2196        // The same flight flown in steps of at most 1 ms gives the same least margins, to a
2197        // millionth of a caliber: Valetudo in calm air off a vertical and an 84° rail and in a
2198        // crosswind, and Prometheus. On all four both leasts are at the rail exit, where the rocket
2199        // is heaviest and its center of mass furthest aft: the search inside steps is checked on a
2200        // two-stage flight (`staging::tests::metrics_follow_a_powered_separation`) instead.
2201        let fine = |settings: FlightSettings| FlightSettings {
2202            method: Method::DormandPrince54(Adaptive {
2203                max_step_s: Some(1e-3),
2204                ..Adaptive::default()
2205            }),
2206            ..settings
2207        };
2208        let tilted = Rail {
2209            elevation_rad: 84.0_f64.to_radians(),
2210            ..Rail::vertical(2.0)
2211        };
2212        let calm = || Environment::standard(site()).unwrap();
2213        let wind =
2214            || windy_environment(ConstantWind::new(5.0, 1.5 * std::f64::consts::PI).unwrap());
2215        let cases = [
2216            ("rocketpy-valetudo", calm(), Rail::vertical(3.0), 15.0),
2217            ("rocketpy-valetudo", calm(), tilted, 15.0),
2218            ("rocketpy-valetudo", wind(), Rail::vertical(3.0), 15.0),
2219            (
2220                "rocketpy-prometheus-2022-generic-motor",
2221                calm(),
2222                Rail::vertical(5.0),
2223                60.0,
2224            ),
2225        ];
2226        for (name, environment, rail, max_time_s) in cases {
2227            let least = |settings: FlightSettings| {
2228                let sim = Simulation::new(
2229                    &design(name),
2230                    "example",
2231                    environment.clone(),
2232                    rail,
2233                    settings,
2234                )
2235                .unwrap();
2236                let (result, metrics) = fly(&sim);
2237                let summary = metrics.summary(&result, sim.environment()).unwrap();
2238                let series = metrics.stability().to_vec();
2239                (
2240                    summary.min_static_margin_cal.unwrap(),
2241                    summary.min_flight_margin_cal.unwrap(),
2242                    series,
2243                )
2244            };
2245            let (coarse_static, coarse_flight, series) = least(capped(max_time_s));
2246            assert_eq!(coarse_flight.time_s, series[0].time_s, "{name}");
2247            assert_eq!(coarse_static.time_s, series[0].time_s, "{name}");
2248            let (fine_static, fine_flight, _) = least(fine(capped(max_time_s)));
2249            for (coarse, fine, what) in [
2250                (coarse_static, fine_static, "static"),
2251                (coarse_flight, fine_flight, "flight"),
2252            ] {
2253                assert!(
2254                    (coarse.value - fine.value).abs() < 1e-6,
2255                    "{name} {what}: {coarse:?} against {fine:?}"
2256                );
2257            }
2258        }
2259    }
2260
2261    /// A step whose only use is its margins: both are `margin_cal(t)`.
2262    struct MarginStep {
2263        margin_cal: fn(f64) -> Option<f64>,
2264    }
2265
2266    impl FlightStep for MarginStep {
2267        fn phase(&self) -> Phase {
2268            Phase::Free
2269        }
2270        fn start_s(&self) -> f64 {
2271            0.0
2272        }
2273        fn end_s(&self) -> f64 {
2274            1.0
2275        }
2276        fn state_at(&self, _t_s: f64) -> crate::state::State {
2277            unreachable!("the margin search reads only the stability")
2278        }
2279        fn sample(&self, _t_s: f64) -> Result<Sample, SimError> {
2280            unreachable!("the margin search reads only the stability")
2281        }
2282        fn stability(&self, t_s: f64) -> Result<Stability, SimError> {
2283            let margin_cal = (self.margin_cal)(t_s);
2284            let margin = Margin {
2285                mach: 0.0,
2286                angle_of_attack_rad: 0.0,
2287                roll_rad: 0.0,
2288                normal_force_slope_per_rad: 1.0,
2289                slope_magnitude_sum_per_rad: 1.0,
2290                pitch_moment_slope_per_rad: -margin_cal.unwrap_or(0.0),
2291                cp_station_m: margin_cal,
2292                margin_cal,
2293            };
2294            Ok(Stability {
2295                time_s: t_s,
2296                height_above_ground_m: 100.0 * t_s,
2297                dynamic_pressure_pa: 0.0,
2298                cg_station_m: 0.0,
2299                reference_diameter_m: 1.0,
2300                static_margin: margin,
2301                flight_margin: margin,
2302            })
2303        }
2304    }
2305
2306    fn least_of(margin_cal: fn(f64) -> Option<f64>) -> Option<Peak> {
2307        let step = MarginStep { margin_cal };
2308        let entries = [0.0, 0.5, 1.0].map(|t| step.stability(t).unwrap());
2309        least_margin(&step, 0.0, 1.0, &entries, flight_of).unwrap()
2310    }
2311
2312    #[test]
2313    fn a_least_margin_between_step_ends_is_found() {
2314        // 2 + (t − 0.37)² reads 2.137, 2.017 and 2.397 at the step's start, middle and end; the
2315        // parabola through them has its bottom inside, and the search finds 2 at 0.37 s.
2316        let least = least_of(|t| Some(2.0 + (t - 0.37).powi(2))).unwrap();
2317        close(least.value, 2.0, 1e-15, "least");
2318        assert!((least.time_s - 0.37).abs() < 1e-7, "{least:?}");
2319        close(least.height_above_ground_m, 37.0, 1e-5, "height");
2320        // Falling across the step, it is least at the end, with no search.
2321        let least = least_of(|t| Some(3.0 - t)).unwrap();
2322        assert_eq!((least.value, least.time_s), (2.0, 1.0));
2323        // Undefined at the middle: the least of the defined ends, and no search through the gap.
2324        let least = least_of(|t| (t != 0.5).then_some(2.0 + (t - 0.37).powi(2))).unwrap();
2325        assert_eq!(least.time_s, 0.0);
2326        assert_eq!(least_of(|_| None), None);
2327    }
2328
2329    #[test]
2330    fn a_summary_needs_the_flight_it_watched() {
2331        // A watcher that saw nothing, or saw another flight too, refuses to sum one up; cleared, it
2332        // sums up the next. A flight started in the air has no launch height, and no climb.
2333        // The refusal names the steps the watcher saw.
2334        let refused = |summary: Result<FlightSummary, SimError>, steps: u64| match summary {
2335            Err(SimError::Domain { what, value }) => {
2336                assert!(what.starts_with("steps this watcher saw"), "{what}");
2337                assert_eq!(value, steps as f64);
2338            }
2339            other => panic!("{other:?}"),
2340        };
2341        let sim = valetudo(Environment::standard(site()).unwrap(), capped(20.0));
2342        let (result, mut metrics) = fly(&sim);
2343        let steps = result.stats.accepted_steps;
2344        refused(FlightMetrics::new().summary(&result, sim.environment()), 0);
2345        // The same steps, but a flight that ended before the watcher's last step did.
2346        let mut early = result.clone();
2347        early.final_sample.time_s -= 1.0;
2348        refused(metrics.summary(&early, sim.environment()), steps);
2349        let other = valetudo(Environment::standard(site()).unwrap(), capped(15.0));
2350        let other_result = other.run(&mut metrics).unwrap();
2351        refused(
2352            metrics.summary(&other_result, other.environment()),
2353            steps + other_result.stats.accepted_steps,
2354        );
2355        metrics.clear();
2356        let other_result = other.run(&mut metrics).unwrap();
2357        let summary = metrics.summary(&other_result, other.environment()).unwrap();
2358        assert!(summary.rail_exit_stability.is_some());
2359
2360        let burnout = result.event(EventKind::Burnout).unwrap().sample;
2361        let mut aloft = FlightMetrics::new();
2362        let free = sim
2363            .run_free(burnout.time_s, burnout.state, &mut aloft)
2364            .unwrap();
2365        let summary = aloft.summary(&free, sim.environment()).unwrap();
2366        assert_eq!(summary.launch_height_m, None);
2367        assert_eq!(summary.apogee.unwrap().gain_m, None);
2368        assert_eq!(summary.rail_exit_stability, None);
2369
2370        // Reused forward in time, not cleared: the first flight's steps are still counted.
2371        let short = valetudo(Environment::standard(site()).unwrap(), capped(5.0));
2372        let (short_result, mut reused) = fly(&short);
2373        let apogee = result.event(EventKind::Apogee).unwrap().sample;
2374        let free = sim
2375            .run_free(apogee.time_s, apogee.state, &mut reused)
2376            .unwrap();
2377        refused(
2378            reused.summary(&free, sim.environment()),
2379            short_result.stats.accepted_steps + free.stats.accepted_steps,
2380        );
2381
2382        // Begun in the air on its way down, it keeps no stability: its apogee is behind it.
2383        let mut falling = FlightMetrics::new();
2384        let mut state = apogee.state;
2385        state.velocity_enu_m_s.z = -1.0;
2386        let free = sim.run_free(apogee.time_s, state, &mut falling).unwrap();
2387        falling.summary(&free, sim.environment()).unwrap();
2388        assert!(falling.stability().is_empty());
2389
2390        // A flight can end without a step, or on a stop so close ahead that the clock just moves
2391        // there; it is still summed up.
2392        let stepless = valetudo(
2393            Environment::standard(site()).unwrap(),
2394            FlightSettings {
2395                step_limit: 0,
2396                ..capped(20.0)
2397            },
2398        );
2399        let (result, metrics) = fly(&stepless);
2400        assert_eq!(result.stats.accepted_steps, 0);
2401        let summary = metrics.summary(&result, stepless.environment()).unwrap();
2402        assert_eq!(summary.termination, Termination::StepLimit);
2403        assert_eq!(summary.max_speed_m_s, None);
2404        let cap_s = f64::from_bits(5.0_f64.to_bits() + 3);
2405        let at_cap = valetudo(Environment::standard(site()).unwrap(), capped(cap_s))
2406            .with_recovery(vec![Device::new(
2407                "main",
2408                DeviceDrag::canopy(crate::recovery::CanopyType::FlatCircular, 1.0),
2409                Trigger::Time { time_s: 5.0 },
2410            )])
2411            .unwrap();
2412        let (result, metrics) = fly(&at_cap);
2413        assert_eq!(result.termination, Termination::TimeCap);
2414        assert_eq!(result.final_sample.time_s, cap_s);
2415        metrics.summary(&result, at_cap.environment()).unwrap();
2416    }
2417
2418    /// A separated body's step with one specific force all through it, straight up.
2419    struct LoadStep {
2420        span: (f64, f64),
2421        force_m_s2: f64,
2422    }
2423
2424    impl crate::recorder::sealed::Sealed for LoadStep {}
2425
2426    impl BodyStep for LoadStep {
2427        fn start_s(&self) -> f64 {
2428            self.span.0
2429        }
2430        fn end_s(&self) -> f64 {
2431            self.span.1
2432        }
2433        fn sample(&self, t_s: f64) -> Result<crate::BodySample, SimError> {
2434            Ok(crate::BodySample {
2435                time_s: t_s,
2436                cg_enu_m: DVec3::ZERO,
2437                cg_velocity_enu_m_s: DVec3::ZERO,
2438                height_above_ground_m: 1_000.0 - t_s,
2439                vertical_speed_m_s: -1.0,
2440                airspeed_m_s: 1.0,
2441                recovery_drag_area_m2: 1.0,
2442                mass_kg: 1.0,
2443            })
2444        }
2445        fn acceleration_enu_m_s2(&self, _t_s: f64) -> Result<DVec3, SimError> {
2446            unreachable!("the watcher reads the specific force")
2447        }
2448        fn specific_force_enu_m_s2(&self, _t_s: f64) -> Result<DVec3, SimError> {
2449            Ok(DVec3::new(0.0, 0.0, self.force_m_s2))
2450        }
2451    }
2452
2453    #[test]
2454    fn a_summary_refuses_separated_bodies_steps_from_another_flight() {
2455        // #1532, found in review: each body's opening shock is read from that body's own steps,
2456        // which the stack's step count doesn't cover. A watcher that saw the steps of a body the
2457        // flight doesn't have, or not each step of a body it has, is refused, not summed up
2458        // with another flight's figures.
2459        let refused = |summary: Result<FlightSummary, SimError>, steps: u64| match summary {
2460            Err(SimError::Domain { what, value }) => {
2461                assert!(
2462                    what.starts_with("steps this watcher saw of a separated body"),
2463                    "{what}"
2464                );
2465                assert_eq!(value, steps as f64);
2466            }
2467            other => panic!("{other:?}"),
2468        };
2469        let sim = valetudo(Environment::standard(site()).unwrap(), capped(20.0));
2470        let (result, metrics) = fly(&sim);
2471        assert!(result.bodies.is_empty());
2472        metrics.summary(&result, sim.environment()).unwrap();
2473        let step = LoadStep {
2474            span: (1.0, 2.0),
2475            force_m_s2: 30.0,
2476        };
2477        // A body the flight doesn't have: one step of it is enough.
2478        let mut stray = metrics.clone();
2479        stray.body_step(1, &step).unwrap();
2480        refused(stray.summary(&result, sim.environment()), 1);
2481        // A flight with a body, whose steps the watcher saw none of, then one too few, then
2482        // each once, then one twice.
2483        let mut flown = result.clone();
2484        let at = crate::BodySample {
2485            time_s: 1.0,
2486            cg_enu_m: DVec3::ZERO,
2487            cg_velocity_enu_m_s: DVec3::ZERO,
2488            height_above_ground_m: 999.0,
2489            vertical_speed_m_s: -1.0,
2490            airspeed_m_s: 1.0,
2491            recovery_drag_area_m2: 1.0,
2492            mass_kg: 1.0,
2493        };
2494        flown.bodies.push(crate::BodyFlight {
2495            body: 1,
2496            stages: (1, 1),
2497            pieces: vec![1],
2498            mass_kg: 1.0,
2499            start_sample: at,
2500            termination: Termination::TimeCap,
2501            events: Vec::new(),
2502            final_sample: at,
2503            stats: crate::Stats {
2504                accepted_steps: 2,
2505                ..crate::Stats::default()
2506            },
2507            impulse_left_n_s: 0.0,
2508        });
2509        refused(metrics.summary(&flown, sim.environment()), 0);
2510        let mut watched = metrics.clone();
2511        watched.body_step(1, &step).unwrap();
2512        refused(watched.summary(&flown, sim.environment()), 1);
2513        watched.body_step(1, &step).unwrap();
2514        let summary = watched.summary(&flown, sim.environment()).unwrap();
2515        assert_eq!(
2516            summary
2517                .body_max_descent_acceleration_m_s2
2518                .iter()
2519                .map(|peak| (peak.body, peak.value))
2520                .collect::<Vec<_>>(),
2521            [(1, 30.0)]
2522        );
2523        watched.body_step(1, &step).unwrap();
2524        refused(watched.summary(&flown, sim.environment()), 3);
2525        // Cleared, the watcher holds no body's steps.
2526        watched.clear();
2527        assert!(watched.body_steps.is_empty() && watched.body_descent_peaks.is_empty());
2528    }
2529
2530    #[test]
2531    fn each_bodys_own_shock_is_its_largest_step_peak_and_a_nan_stays() {
2532        // #1532: each separated body's own figure is the largest of its steps' peaks, the first
2533        // of equals, kept by body number whatever order the bodies step in. A body whose steps
2534        // carry no load has none.
2535        let shocks = |loads: &[(usize, f64)]| -> Vec<(usize, f64, f64)> {
2536            let mut metrics = FlightMetrics::new();
2537            for (i, &(body, force_m_s2)) in loads.iter().enumerate() {
2538                let span = (i as f64, i as f64 + 1.0);
2539                metrics
2540                    .body_step(body, &LoadStep { span, force_m_s2 })
2541                    .unwrap();
2542            }
2543            metrics
2544                .body_descent_peaks
2545                .iter()
2546                .map(|(&body, peak)| (body, peak.value, peak.time_s))
2547                .collect()
2548        };
2549        assert_eq!(
2550            shocks(&[
2551                (2, 5.0),
2552                (0, 30.0),
2553                (2, 40.0),
2554                (0, 30.0),
2555                (1, 0.0),
2556                (2, 40.0),
2557                (0, 12.0),
2558                (2, 9.81),
2559            ]),
2560            [(0, 30.0, 1.0), (2, 40.0, 2.0)]
2561        );
2562        // A step's peak that is not a number is kept, first or later, and then nothing replaces
2563        // it: a larger number after it can't hide it.
2564        for loads in [
2565            &[(1, f64::NAN), (1, 50.0)][..],
2566            &[(1, 20.0), (1, f64::NAN), (1, 50.0)][..],
2567        ] {
2568            let kept = shocks(loads);
2569            assert_eq!(kept.len(), 1);
2570            assert!(kept[0].1.is_nan(), "{kept:?}");
2571        }
2572    }
2573
2574    #[test]
2575    fn body_0s_kept_peaks_are_the_first_of_equals_and_each_larger_one() {
2576        // #1533: the summary takes the largest of body 0's step peaks that start before a time,
2577        // and the first of equals, so only a step's peak that beats the last one kept is kept.
2578        // Steps with no load, an equal load or a smaller one add nothing; another body's never.
2579        let kept = |loads: &[f64]| {
2580            let mut metrics = FlightMetrics::new();
2581            for (i, &force_m_s2) in loads.iter().enumerate() {
2582                let span = (i as f64, i as f64 + 1.0);
2583                let step = LoadStep { span, force_m_s2 };
2584                metrics.body_step(1, &step).unwrap();
2585                metrics.body_step(0, &step).unwrap();
2586            }
2587            metrics.nose_descent_peaks
2588        };
2589        let starts_and_values = |peaks: &[(f64, Peak)]| -> Vec<(f64, f64)> {
2590            peaks
2591                .iter()
2592                .map(|(start, peak)| (*start, peak.value))
2593                .collect()
2594        };
2595        let peaks = kept(&[0.0, 30.0, 30.0, 12.0, 45.0, 45.0, 9.81, 0.0]);
2596        assert_eq!(starts_and_values(&peaks), [(1.0, 30.0), (4.0, 45.0)]);
2597        // A kept peak is at its step's start, where the three points first reach it.
2598        assert_eq!(peaks[0].1.time_s, 1.0);
2599        assert_eq!(peaks[0].1.height_above_ground_m, 999.0);
2600        // The summary's rule over every step, cut before each time: the same from the kept ones.
2601        let every = [0.0, 30.0, 30.0, 12.0, 45.0, 45.0, 9.81, 0.0];
2602        for cut in 0..=every.len() {
2603            let mut best: Option<(f64, f64)> = None;
2604            for (i, &value) in every.iter().enumerate().take(cut) {
2605                if value > 0.0 && best.is_none_or(|(_, top)| value > top) {
2606                    best = Some((i as f64, value));
2607                }
2608            }
2609            let from_kept = starts_and_values(&peaks)
2610                .into_iter()
2611                .take_while(|(start, _)| *start < cut as f64)
2612                .last();
2613            assert_eq!(from_kept, best, "cut before {cut} s");
2614        }
2615        // A value that is not a number is kept only first, where the summary would take it for a
2616        // flight whose stack has no shock; the numbers after it are kept as if it weren't there.
2617        let peaks = kept(&[f64::NAN, f64::NAN, 5.0, f64::NAN, 3.0, 7.0]);
2618        assert!(peaks[0].1.value.is_nan());
2619        assert_eq!(starts_and_values(&peaks[1..]), [(2.0, 5.0), (5.0, 7.0)]);
2620        let peaks = kept(&[5.0, f64::NAN, 7.0]);
2621        assert_eq!(starts_and_values(&peaks), [(0.0, 5.0), (2.0, 7.0)]);
2622    }
2623
2624    /// A free-flight step from `start_s` to `end_s` whose samples copy `template` but for the
2625    /// time, the dynamic pressure and the angle of attack, both functions of time.
2626    struct AngleStep {
2627        template: Sample,
2628        span: (f64, f64),
2629        phase: Phase,
2630        dynamic_pressure_pa: fn(f64) -> f64,
2631        angle_of_attack_rad: fn(f64) -> f64,
2632    }
2633
2634    impl FlightStep for AngleStep {
2635        fn phase(&self) -> Phase {
2636            self.phase
2637        }
2638        fn start_s(&self) -> f64 {
2639            self.span.0
2640        }
2641        fn end_s(&self) -> f64 {
2642            self.span.1
2643        }
2644        fn state_at(&self, _t_s: f64) -> crate::state::State {
2645            unreachable!("the watcher reads samples and stability")
2646        }
2647        fn sample(&self, t_s: f64) -> Result<Sample, SimError> {
2648            Ok(Sample {
2649                time_s: t_s,
2650                dynamic_pressure_pa: (self.dynamic_pressure_pa)(t_s),
2651                angle_of_attack_rad: (self.angle_of_attack_rad)(t_s),
2652                ..self.template
2653            })
2654        }
2655        fn stability(&self, t_s: f64) -> Result<Stability, SimError> {
2656            MarginStep {
2657                margin_cal: |_| Some(2.0),
2658            }
2659            .stability(t_s)
2660        }
2661    }
2662
2663    /// The largest counted angle of attack, rad, after watching free-flight steps that end at
2664    /// each of `ends` in turn (the first starting at 0 s), then an apogee and a step after it.
2665    fn largest_angle(
2666        ends: &[f64],
2667        dynamic_pressure_pa: fn(f64) -> f64,
2668        angle_of_attack_rad: fn(f64) -> f64,
2669    ) -> Option<Peak> {
2670        let sim = valetudo(Environment::standard(site()).unwrap(), capped(2.0));
2671        let template = fly(&sim).0.final_sample;
2672        let mut metrics = FlightMetrics::new();
2673        let mut start = 0.0;
2674        for &end in ends {
2675            let step = AngleStep {
2676                template,
2677                span: (start, end),
2678                phase: Phase::Free,
2679                dynamic_pressure_pa,
2680                angle_of_attack_rad,
2681            };
2682            metrics.step(&step).unwrap();
2683            start = end;
2684        }
2685        // Nothing after apogee counts, however steep.
2686        metrics.event(&FlightEvent {
2687            kind: EventKind::Apogee,
2688            sample: template,
2689        });
2690        let after = AngleStep {
2691            template,
2692            span: (start, start + 1.0),
2693            phase: Phase::Free,
2694            dynamic_pressure_pa: |_| 1e5,
2695            angle_of_attack_rad: |_| 3.0,
2696        };
2697        metrics.step(&after).unwrap();
2698        metrics.max_angle_of_attack
2699    }
2700
2701    #[test]
2702    fn the_angle_of_attack_counts_from_just_past_one_second_after_the_rail() {
2703        // The free flight starts at 0 s. 40° exactly 1 s after it is the transient and doesn't
2704        // count; 20° at 1.5 s, the next step's middle, does.
2705        let spike = |t: f64| if t == 1.0 { 40_f64 } else { 20.0 }.to_radians();
2706        let peak = largest_angle(&[0.5, 1.0, 2.0], |_| 1e3, spike).unwrap();
2707        assert_eq!((peak.value, peak.time_s), (20_f64.to_radians(), 1.5));
2708        // The same spike a step end later, at the next time after 1 s, counts.
2709        let spike = |t: f64| if t == 1.0_f64.next_up() { 40_f64 } else { 20.0 }.to_radians();
2710        let ends = [0.5, 1.0_f64.next_up(), 2.0];
2711        let peak = largest_angle(&ends, |_| 1e3, spike).unwrap();
2712        assert_eq!(
2713            (peak.value, peak.time_s),
2714            (40_f64.to_radians(), 1.0_f64.next_up())
2715        );
2716        // Nothing past 1 s: no peak.
2717        assert_eq!(largest_angle(&[0.5, 1.0], |_| 1e3, spike), None);
2718    }
2719
2720    #[test]
2721    fn the_angle_of_attack_counts_only_with_a_fifth_of_the_weight_in_normal_force() {
2722        // The step's normal-force slope is 1 on a diameter of 1 m: at 1000 Pa a 15° angle gives
2723        // 206 N, far past a fifth of the rocket's weight; at 1 mPa, far short of it. The edge
2724        // itself is `envelope::force_counts`'s, tested there.
2725        let angle = |t: f64| t / 10.0;
2726        let peak = largest_angle(&[1.0, 2.0, 3.0], |_| 1000.0, angle).unwrap();
2727        assert_eq!(peak.time_s, 3.0);
2728        let fading = |t: f64| if t > 2.0 { 1e-3 } else { 1000.0 };
2729        let peak = largest_angle(&[1.0, 2.0, 3.0], fading, angle).unwrap();
2730        assert_eq!(peak.time_s, 2.0);
2731        // A NaN angle that counts stays the largest, so it can't hide a flag.
2732        let broken = |t: f64| if t == 1.5 { f64::NAN } else { t / 10.0 };
2733        let peak = largest_angle(&[1.0, 2.0, 3.0], |_| 1000.0, broken).unwrap();
2734        assert!(peak.value.is_nan() && peak.time_s == 1.5, "{peak:?}");
2735    }
2736
2737    /// No wind below `height_msl_m`, and `speed_m_s` from the north above it.
2738    #[derive(Debug)]
2739    struct Layer {
2740        height_msl_m: f64,
2741        speed_m_s: f64,
2742    }
2743
2744    impl hpr_atmos::Wind for Layer {
2745        fn wind(&self, height_msl_m: f64) -> Result<hpr_atmos::WindSample, hpr_atmos::AtmosError> {
2746            let speed = if height_msl_m < self.height_msl_m {
2747                0.0
2748            } else {
2749                self.speed_m_s
2750            };
2751            Ok(hpr_atmos::WindSample {
2752                velocity_enu_m_s: hpr_atmos::wind::velocity_from_speed_direction(speed, 0.0),
2753                extrapolated: None,
2754            })
2755        }
2756    }
2757
2758    /// Every step end's angle of attack before apogee, with its time and the normal force a 15°
2759    /// angle would give then, as a share of the rocket's weight.
2760    #[derive(Default)]
2761    struct Angles {
2762        climbing: Vec<(f64, f64, f64)>,
2763        past_apogee: bool,
2764    }
2765
2766    impl Observer for Angles {
2767        fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
2768            let sample = step.sample(step.end_s())?;
2769            if !self.past_apogee && step.phase() == Phase::Free {
2770                let stability = step.stability(step.end_s())?;
2771                let force_n = envelope::normal_force_n(
2772                    sample.dynamic_pressure_pa,
2773                    stability.reference_diameter_m,
2774                    stability.flight_margin.normal_force_slope_per_rad,
2775                    HIGH_ANGLE_OF_ATTACK_RAD,
2776                );
2777                let weight_n = sample.mass_kg * hpr_core::gravity::STANDARD_GRAVITY_MPS2;
2778                self.climbing.push((
2779                    sample.time_s,
2780                    sample.angle_of_attack_rad,
2781                    force_n / weight_n,
2782                ));
2783            }
2784            Ok(())
2785        }
2786        fn event(&mut self, event: &FlightEvent) {
2787            self.past_apogee |= event.kind == EventKind::Apogee;
2788        }
2789    }
2790
2791    #[test]
2792    fn a_tilted_calm_climb_passes_15_degrees_only_with_too_little_force() {
2793        // Off an 84° rail in calm air the path turns over near apogee faster than the slowing
2794        // rocket can follow, and its angle of attack passes 15° there, at about the rail exit's
2795        // airspeed; a 15° angle then gives a normal force of 1.0% to 1.5% of its weight, far short of
2796        // a fifth, so the flight raises no flag.
2797        let tilted = Rail {
2798            elevation_rad: 84.0_f64.to_radians(),
2799            ..Rail::vertical(3.0)
2800        };
2801        let sim = Simulation::new(
2802            &design("rocketpy-valetudo"),
2803            "example",
2804            Environment::standard(site()).unwrap(),
2805            tilted,
2806            FlightSettings::default(),
2807        )
2808        .unwrap();
2809        let mut watchers = (FlightMetrics::new(), Angles::default());
2810        let result = sim.run(&mut watchers).unwrap();
2811        let (metrics, angles) = watchers;
2812        let summary = metrics.summary(&result, sim.environment()).unwrap();
2813        let steep: Vec<_> = angles
2814            .climbing
2815            .iter()
2816            .filter(|(_, angle, _)| *angle > HIGH_ANGLE_OF_ATTACK_RAD)
2817            .collect();
2818        assert!(!steep.is_empty(), "the climb passes 15° before apogee");
2819        for (_, _, share) in &steep {
2820            assert!(*share < 0.15 * HIGH_ANGLE_MIN_FORCE_SHARE, "{steep:?}");
2821        }
2822        let counted = summary.max_angle_of_attack_rad.unwrap();
2823        assert!(counted.value < HIGH_ANGLE_OF_ATTACK_RAD, "{counted:?}");
2824        assert!(summary.envelope_flags().is_empty());
2825    }
2826
2827    #[test]
2828    fn a_wind_layer_met_at_speed_raises_the_high_angle_flag() {
2829        // Valetudo climbs into a 30 m/s wind 300 m up, fast, well after its first second: the
2830        // crosswind turns its angle of attack past 15° until it weathercocks.
2831        let environment = Environment::standard(site()).unwrap().with_wind(Layer {
2832            height_msl_m: site().height_m + 300.0,
2833            speed_m_s: 30.0,
2834        });
2835        let sim = valetudo(environment, FlightSettings::default());
2836        let (result, metrics) = fly(&sim);
2837        let summary = metrics.summary(&result, sim.environment()).unwrap();
2838        let flags = summary.envelope_flags();
2839        let exit = summary.rail_exit_speed_m_s.unwrap();
2840        let [
2841            EnvelopeFlag::HighAngleOfAttack {
2842                angle_of_attack_rad,
2843            },
2844        ] = flags[..]
2845        else {
2846            panic!("{flags:?}");
2847        };
2848        assert!(angle_of_attack_rad.value > HIGH_ANGLE_OF_ATTACK_RAD);
2849        assert!(angle_of_attack_rad.time_s > exit.time_s + HIGH_ANGLE_GRACE_S);
2850        assert!(
2851            (angle_of_attack_rad.height_above_ground_m - 300.0).abs() < 50.0,
2852            "{angle_of_attack_rad:?}"
2853        );
2854        // Calm, the same flight raises nothing.
2855        let calm = valetudo(
2856            Environment::standard(site()).unwrap(),
2857            FlightSettings::default(),
2858        );
2859        let (result, metrics) = fly(&calm);
2860        let summary = metrics.summary(&result, calm.environment()).unwrap();
2861        assert!(summary.envelope_flags().is_empty(), "{summary:?}");
2862    }
2863
2864    #[test]
2865    fn a_wind_layer_met_in_a_fast_coast_raises_the_high_angle_flag() {
2866        // The synthetic two-stage rocket, flown as one stack, burns out within 2 s and coasts at
2867        // several thousand pascals into a 40 m/s wind 2000 m up, long after its boost's peak:
2868        // the crosswind turns its angle of attack past 15° with a normal force larger than its
2869        // weight. A floor at a tenth of the boost's dynamic pressure missed it.
2870        let environment = Environment::standard(site()).unwrap().with_wind(Layer {
2871            height_msl_m: site().height_m + 2000.0,
2872            speed_m_s: 40.0,
2873        });
2874        let sim = Simulation::new(
2875            &design("synthetic-two-stage-75mm-54mm"),
2876            "j760-i175",
2877            environment,
2878            Rail::vertical(3.0),
2879            FlightSettings::default(),
2880        )
2881        .unwrap();
2882        let (result, metrics) = fly(&sim);
2883        let summary = metrics.summary(&result, sim.environment()).unwrap();
2884        let flags: Vec<_> = summary
2885            .envelope_flags()
2886            .iter()
2887            .map(EnvelopeFlag::name)
2888            .collect();
2889        assert_eq!(flags, ["beyond_validated_range", "high_angle_of_attack"]);
2890        let angle = summary.max_angle_of_attack_rad.unwrap();
2891        assert!(
2892            (angle.height_above_ground_m - 2000.0).abs() < 100.0,
2893            "{angle:?}"
2894        );
2895    }
2896
2897    /// A free-flight step from `span.0` to `span.1` whose samples copy `template` but for the
2898    /// time and the thrust, and whose margins are both `margin_cal(t)`, with their pitch-moment
2899    /// slopes `moment_slope_per_rad(t)` when given (else [`MarginStep`]'s).
2900    struct PoweredStep {
2901        template: Sample,
2902        span: (f64, f64),
2903        thrust_n: fn(f64) -> f64,
2904        margin_cal: fn(f64) -> Option<f64>,
2905        moment_slope_per_rad: Option<fn(f64) -> f64>,
2906    }
2907
2908    impl FlightStep for PoweredStep {
2909        fn phase(&self) -> Phase {
2910            Phase::Free
2911        }
2912        fn start_s(&self) -> f64 {
2913            self.span.0
2914        }
2915        fn end_s(&self) -> f64 {
2916            self.span.1
2917        }
2918        fn state_at(&self, _t_s: f64) -> crate::state::State {
2919            unreachable!("the watcher reads samples and stability")
2920        }
2921        fn sample(&self, t_s: f64) -> Result<Sample, SimError> {
2922            Ok(Sample {
2923                time_s: t_s,
2924                thrust_n: (self.thrust_n)(t_s),
2925                ..self.template
2926            })
2927        }
2928        fn stability(&self, t_s: f64) -> Result<Stability, SimError> {
2929            let mut stability = MarginStep {
2930                margin_cal: self.margin_cal,
2931            }
2932            .stability(t_s)?;
2933            if let Some(slope) = self.moment_slope_per_rad {
2934                stability.static_margin.pitch_moment_slope_per_rad = slope(t_s);
2935                stability.flight_margin.pitch_moment_slope_per_rad = slope(t_s);
2936            }
2937            Ok(stability)
2938        }
2939    }
2940
2941    /// The least static margin while a motor burns, and the least over the whole span, after
2942    /// watching free-flight steps from 0 s that end at 0.5, 1 and 2 s, with a motor that burns
2943    /// out at 1 s, a step's end.
2944    fn least_powered(margin_cal: fn(f64) -> Option<f64>) -> (Option<Peak>, Option<Peak>) {
2945        let metrics = watch_powered(margin_cal, None);
2946        (metrics.min_powered_static_margin, metrics.min_static_margin)
2947    }
2948
2949    /// The watcher after [`least_powered`]'s steps, with margins `margin_cal(t)` and, when given,
2950    /// pitch-moment slopes `moment_slope_per_rad(t)`.
2951    fn watch_powered(
2952        margin_cal: fn(f64) -> Option<f64>,
2953        moment_slope_per_rad: Option<fn(f64) -> f64>,
2954    ) -> FlightMetrics {
2955        let sim = valetudo(Environment::standard(site()).unwrap(), capped(2.0));
2956        let template = fly(&sim).0.final_sample;
2957        let mut metrics = FlightMetrics::new();
2958        let mut start = 0.0;
2959        for end in [0.5, 1.0, 2.0] {
2960            let step = PoweredStep {
2961                template,
2962                span: (start, end),
2963                thrust_n: |t| if t < 1.0 { 50.0 } else { 0.0 },
2964                margin_cal,
2965                moment_slope_per_rad,
2966            };
2967            metrics.step(&step).unwrap();
2968            start = end;
2969        }
2970        metrics
2971    }
2972
2973    #[test]
2974    fn the_powered_margin_counts_only_while_a_motor_burns() {
2975        let tiny = 2_f64.powi(-30);
2976        let names = |least: Option<Peak>| {
2977            envelope::flags(None, None, least, None)
2978                .iter()
2979                .map(EnvelopeFlag::name)
2980                .collect::<Vec<_>>()
2981        };
2982        // The margin falls by 1 caliber a second. From 1 − 2⁻³⁰ it is −2⁻³⁰ at the burnout:
2983        // unstable under power, however little.
2984        let (powered, least) = least_powered(|t| Some(1.0 - 2_f64.powi(-30) - t));
2985        let powered = powered.unwrap();
2986        assert_eq!((powered.value, powered.time_s), (-tiny, 1.0));
2987        assert_eq!(names(Some(powered)), ["unstable_under_power"]);
2988        assert_eq!(least.unwrap().time_s, 2.0);
2989        // From 1 + 2⁻³⁰ it is +2⁻³⁰ at the burnout, and falls to −1 caliber in the coast after:
2990        // no flag, as only the margin under power counts.
2991        let (powered, least) = least_powered(|t| Some(1.0 + 2_f64.powi(-30) - t));
2992        let powered = powered.unwrap();
2993        assert_eq!((powered.value, powered.time_s), (tiny, 1.0));
2994        assert!(names(Some(powered)).is_empty());
2995        assert!(least.unwrap().value < -0.99, "{least:?}");
2996        // Least inside a powered step, below zero, found by the search there.
2997        let (powered, _) = least_powered(|t| Some((t - 0.37).powi(2) - 0.01));
2998        let powered = powered.unwrap();
2999        assert!((powered.value + 0.01).abs() < 1e-15, "{powered:?}");
3000        assert!((powered.time_s - 0.37).abs() < 1e-7, "{powered:?}");
3001        // A NaN margin under power is kept, so it raises the flag; one in the coast doesn't count.
3002        let (powered, _) = least_powered(|t| Some(if t == 0.25 { f64::NAN } else { 2.0 - t }));
3003        let powered = powered.unwrap();
3004        assert!(
3005            powered.value.is_nan() && powered.time_s == 0.25,
3006            "{powered:?}"
3007        );
3008        assert_eq!(names(Some(powered)), ["unstable_under_power"]);
3009        let (powered, _) = least_powered(|t| Some(if t == 1.5 { f64::NAN } else { 2.0 - t }));
3010        assert_eq!(powered.unwrap().value, 1.0);
3011        // A margin defined nowhere under power: none.
3012        let (powered, _) = least_powered(|t| (t > 1.0).then_some(-1.0));
3013        assert_eq!(powered, None);
3014        // A tie can't keep a margin on the stable side of zero: +10⁻¹³ at the start, then
3015        // −10⁻¹³ (closer than the tie of 10⁻¹² calibers) from 0.25 s on, all under power.
3016        let (powered, _) = least_powered(|t| Some(if t < 0.2 { 1e-13 } else { -1e-13 }));
3017        let powered = powered.unwrap();
3018        assert_eq!((powered.value, powered.time_s), (-1e-13, 0.25));
3019        assert_eq!(names(Some(powered)), ["unstable_under_power"]);
3020    }
3021
3022    #[test]
3023    fn a_moment_slope_without_a_margin_counts_only_while_a_motor_burns() {
3024        // 2⁻³⁰, a const so the closures below stay fn pointers.
3025        const TINY: f64 = 1.0 / 1_073_741_824.0;
3026        let flag_names = |metrics: &FlightMetrics| {
3027            envelope::flags(
3028                None,
3029                None,
3030                metrics.min_powered_static_margin,
3031                metrics.max_powered_moment_slope,
3032            )
3033            .iter()
3034            .map(EnvelopeFlag::name)
3035            .collect::<Vec<_>>()
3036        };
3037        // No margin anywhere; C_mα is +2⁻³⁰ per radian at 0.75 s, while the motor burns, and
3038        // −1 elsewhere: unstable under power, however little.
3039        let metrics = watch_powered(|_| None, Some(|t| if t == 0.75 { TINY } else { -1.0 }));
3040        let peak = metrics.max_powered_moment_slope.unwrap();
3041        assert_eq!((peak.value, peak.time_s), (TINY, 0.75));
3042        assert_eq!(flag_names(&metrics), ["unstable_without_margin"]);
3043        // −2⁻³⁰ there instead: the air turns it back, no flag.
3044        let metrics = watch_powered(|_| None, Some(|t| if t == 0.75 { -TINY } else { -1.0 }));
3045        let peak = metrics.max_powered_moment_slope.unwrap();
3046        assert_eq!((peak.value, peak.time_s), (-TINY, 0.75));
3047        assert!(flag_names(&metrics).is_empty());
3048        // +2⁻³⁰ only after the burnout at 1 s: not under power, no flag.
3049        let metrics = watch_powered(|_| None, Some(|t| if t > 1.0 { TINY } else { -1.0 }));
3050        assert_eq!(metrics.max_powered_moment_slope.unwrap().value, -1.0);
3051        assert!(flag_names(&metrics).is_empty());
3052        // A NaN slope under power is kept, so it raises the flag; nothing larger replaces it, nor
3053        // does a later NaN.
3054        let metrics = watch_powered(
3055            |_| None,
3056            Some(|t| {
3057                if t == 0.25 || t == 0.75 {
3058                    f64::NAN
3059                } else {
3060                    5.0 * t
3061                }
3062            }),
3063        );
3064        let peak = metrics.max_powered_moment_slope.unwrap();
3065        assert!(peak.value.is_nan() && peak.time_s == 0.25, "{peak:?}");
3066        assert_eq!(flag_names(&metrics), ["unstable_without_margin"]);
3067        // Where the margin is defined, its slope doesn't count, even above zero: the margin says
3068        // it all there.
3069        let metrics = watch_powered(|t| (t != 0.75).then_some(1.0), Some(|_| 3.0));
3070        let peak = metrics.max_powered_moment_slope.unwrap();
3071        assert_eq!((peak.value, peak.time_s), (3.0, 0.75));
3072        let metrics = watch_powered(|_| Some(1.0), Some(|_| 3.0));
3073        assert_eq!(metrics.max_powered_moment_slope, None);
3074        assert!(flag_names(&metrics).is_empty());
3075        // A margin below zero under power and a slope above zero where it is undefined: one flag.
3076        let metrics = watch_powered(|t| (t != 0.75).then_some(-1.0), Some(|_| 3.0));
3077        assert_eq!(flag_names(&metrics), ["unstable_under_power"]);
3078    }
3079
3080    #[test]
3081    fn a_rocket_without_fins_is_unstable_under_power() {
3082        // Valetudo, its fins taken off, flown for 2 s: its nose alone carries the normal force,
3083        // ahead of the center of mass, so the margin is below zero while the motor burns. With
3084        // its fins it raises nothing (above, and in the angle-of-attack tests).
3085        let mut rocket = serde_json::to_value(design("rocketpy-valetudo")).unwrap();
3086        let children = rocket["stages"][0]["components"][1]["children"]
3087            .as_array_mut()
3088            .unwrap();
3089        let before = children.len();
3090        children.retain(|child| child["id"] != "fins-1");
3091        assert_eq!(children.len(), before - 1);
3092        let rocket: Rocket = serde_json::from_value(rocket).unwrap();
3093        let sim = Simulation::new(
3094            &rocket,
3095            "example",
3096            Environment::standard(site()).unwrap(),
3097            Rail::vertical(3.0),
3098            capped(2.0),
3099        )
3100        .unwrap();
3101        let (result, metrics) = fly(&sim);
3102        let summary = metrics.summary(&result, sim.environment()).unwrap();
3103        let powered = summary.min_powered_static_margin_cal.unwrap();
3104        assert!(powered.value < -1.0, "{powered:?}");
3105        let burnout_s = sim.assembly().motors[0].mounted.motor.burnout_time_s();
3106        assert!(powered.time_s <= burnout_s, "{powered:?}");
3107        let flags = summary.envelope_flags();
3108        assert_eq!(
3109            flags[0],
3110            EnvelopeFlag::UnstableUnderPower {
3111                static_margin_cal: powered
3112            }
3113        );
3114        // Stock, its least margin under power is the least of all, and above zero.
3115        let sim = valetudo(Environment::standard(site()).unwrap(), capped(2.0));
3116        let (result, metrics) = fly(&sim);
3117        let summary = metrics.summary(&result, sim.environment()).unwrap();
3118        let powered = summary.min_powered_static_margin_cal.unwrap();
3119        assert_eq!(Some(powered), summary.min_static_margin_cal);
3120        assert!(powered.value > 1.0, "{powered:?}");
3121        assert!(summary.envelope_flags().is_empty());
3122    }
3123}