Skip to main content

hpr_validate/
tip_off.rs

1//! HPR Sim's tip-off phase, flown as RocketPy flew its own: the flights behind
2//! `validation/reports/tip-off-model.json` ([the tip-off phase, held to RocketPy's][m1-14b11];
3//! the tip-off decision record, [ADR-357][adr-357], decision 4).
4//!
5//! `validation/reports/tip-off.json` holds what RocketPy's tip-off phase does to thirteen designs
6//! built from its examples, in still air and in a crosswind, with everything each flight carried. [`fly`]
7//! flies one of those flights in HPR Sim from that record: the public design built from the same
8//! example, the record's rail, site, wind, parachutes and declared drag coefficient, guided to
9//! the last guide as HPR Sim flies by default, or with its tip-off phase
10//! ([`hpr_sim::Simulation::with_tip_off`]).
11//!
12//! [Loft lesson L75][l75]: the inputs come from the oracle's own record of what it flew, and the
13//! design is checked against that record (its dry mass, the area its drag acts on, its motor)
14//! before any difference is read as physics.
15//!
16//! What is measured, as the oracle's script measures it:
17//!
18//! - **The apogee** is the center of mass's greatest height above where the center of dry mass
19//!   started, which is where RocketPy's tracked point starts.
20//! - **The landing point** is where the center of dry mass is, east and north of where it
21//!   started, when it is back at its starting height.
22//! - **Where the last guide leaves the rail**, the angle between the rocket's axis and the
23//!   rail's as two parts, nose below the rail's line in the rail's vertical plane and nose to the
24//!   right of its heading, and the rate at which the nose's direction moves, as the same two
25//!   parts.
26//!
27//! [m1-14b11]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-14b11
28//! [adr-357]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0357-tip-off-measured-with-rocketpys-past-the-plans-bar-the-model-in-two-more-increments.md
29//! [l75]: https://hpr.fusionspace.co/decisions-and-roadmap.html#l75
30
31use std::path::Path;
32
33use hpr_aero::{DragTable, Flow, NormalForceColumn, NormalForceTable};
34use hpr_core::DVec3;
35use hpr_core::interp::{Extrapolation, Interpolation, Table1D};
36use hpr_design::{MassProperties, Rocket};
37use hpr_sim::{
38    Device, DeviceDrag, Direction, EventKind, FlightSettings, Rail, Sample, Simulation,
39    Termination, Trigger, UserEvent,
40};
41use serde::{Deserialize, Serialize};
42use serde_json::Value;
43
44use crate::run::{AREA_AGREEMENT, MASS_AGREEMENT, ValidateError, rocketpy_environment};
45
46/// The state where the last guide leaves the rail.
47#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
48pub struct Release {
49    /// The time after ignition, s.
50    pub time_s: f64,
51    /// The nose tip's speed, m/s.
52    pub speed_m_s: f64,
53    /// The angle of the rocket's axis below the rail's line, in the rail's vertical plane, deg.
54    pub nose_down_deg: f64,
55    /// Its angle to the right of the rail's heading, deg.
56    pub nose_right_deg: f64,
57    /// How fast the nose's direction swings below the rail's line, deg/s.
58    pub pitch_rate_nose_down_deg_s: f64,
59    /// How fast it swings to the right of the heading, deg/s.
60    pub pitch_rate_nose_right_deg_s: f64,
61    /// The angle of attack there, deg.
62    pub angle_of_attack_deg: f64,
63    /// The Mach number there.
64    pub mach: f64,
65    /// The normal-force coefficient the flight's aerodynamics give at that Mach number and angle
66    /// of attack, on the reference area.
67    pub normal_force_coefficient: f64,
68    /// That force's moment about the last guide's middle per unit dynamic pressure and reference
69    /// area, m: `Σ C_N,i (x_guide − X_i)`, positive when the force acts ahead of the guide and so
70    /// swings the nose downwind.
71    pub pivot_moment_m: f64,
72}
73
74/// One flight's figures.
75#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
76pub struct Flown {
77    /// The apogee above the starting height, m.
78    pub apogee_agl_m: f64,
79    /// The landing point east of the start, m.
80    pub landing_east_m: f64,
81    /// The landing point north of the start, m.
82    pub landing_north_m: f64,
83    /// The time of the landing, s.
84    pub flight_time_s: f64,
85    /// Where the last guide leaves the rail.
86    pub last_guide_leaves: Release,
87}
88
89/// Which normal force a flight flies.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum NormalForce {
93    /// HPR Sim's own, from the design.
94    Own,
95    /// The one the oracle recorded as RocketPy's for the rocket (the record's `normal_force`):
96    /// a slope against Mach number times the angle of attack, at a center of pressure against
97    /// Mach number. The pitch and yaw damping stay HPR Sim's
98    /// ([`hpr_sim::Simulation::with_normal_force_table`]).
99    Recorded,
100}
101
102/// The largest angle of attack the recorded normal force's table is given at, rad: RocketPy's
103/// force is its slope times the angle at any angle, and between two columns of one slope the
104/// table is exactly that. Past it the table's own rule takes over. Where the last guide leaves
105/// the angle is at most 0.45 rad (25.6°), far inside. Whether a flight passes 1.5 rad later, at
106/// the top of its path, is not recorded; the guided and the tip-off flight fly the same table.
107const RECORDED_TOP_ANGLE_RAD: f64 = 1.5;
108
109/// Flies, in HPR Sim, the flight of `case` (a case of the oracle's report, with its `rail` and
110/// `site`) in `wind` (one of the case's `winds`, with the wind and what the flight carried) on
111/// the constant drag coefficient `declared_cd0` (the report's `[Mach, C_D]` rows) and the
112/// normal force `normal_force`, with the tip-off phase if `tip_off` and guided to the last
113/// guide otherwise.
114///
115/// # Errors
116///
117/// [`ValidateError`] if the record is not the oracle's shape, the design is not the rocket the
118/// record flew (its dry mass, reference area, motor or the distance between its last two guides
119/// differ past rounding), or the flight fails
120/// or does not end at the ground.
121pub fn fly(
122    root: &Path,
123    case: &Value,
124    wind: &Value,
125    declared_cd0: &Value,
126    (normal_force, tip_off): (NormalForce, bool),
127) -> Result<Flown, ValidateError> {
128    let name = case["name"].as_str().unwrap_or("(unnamed)").to_owned();
129    let label = format!(
130        "{name}, {}, {}, {}",
131        wind["wind"].as_str().unwrap_or("(no wind named)"),
132        match normal_force {
133            NormalForce::Own => "its own normal force",
134            NormalForce::Recorded => "the recorded normal force",
135        },
136        if tip_off { "tip-off" } else { "guided" }
137    );
138    let refuse = |what: String| ValidateError::Flight {
139        case: label.clone(),
140        what,
141        source: None,
142    };
143    let failed = |source: hpr_sim::SimError| ValidateError::Flight {
144        case: label.clone(),
145        what: "the flight failed".to_owned(),
146        source: Some(Box::new(source)),
147    };
148    let number = |value: &Value, what: &str| {
149        value
150            .as_f64()
151            .filter(|x| x.is_finite())
152            .ok_or_else(|| refuse(format!("the record has no number for {what}")))
153    };
154    let (rail, site, carried) = (&case["rail"], &case["site"], &wind["flown_with"]);
155    let path = root.join(format!("validation/designs/rocketpy-{name}.json"));
156    let text = std::fs::read_to_string(&path).map_err(|source| ValidateError::Io {
157        what: "reading a design",
158        path: path.display().to_string(),
159        source,
160    })?;
161    let rocket: Rocket = serde_json::from_str(&text).map_err(|source| ValidateError::Json {
162        path: path.display().to_string(),
163        source: Box::new(source),
164    })?;
165    let [configuration] = rocket.configurations.as_slice() else {
166        return Err(refuse(
167            "the design has other than one configuration".to_owned(),
168        ));
169    };
170    let elevation_m = number(&site["elevation"], "the site's elevation")?;
171    let environment = rocketpy_environment(
172        number(&site["latitude"], "the site's latitude")?,
173        number(&site["longitude"], "the site's longitude")?,
174        elevation_m,
175        &[(
176            elevation_m,
177            number(&wind["wind_east_m_s"], "the wind's east part")?,
178            number(&wind["wind_north_m_s"], "the wind's north part")?,
179        )],
180    )
181    .map_err(&failed)?;
182    let rail = Rail {
183        length_m: number(&rail["rail_length_m"], "the rail's length")?,
184        azimuth_rad: number(&rail["heading_deg"], "the rail's heading")?.to_radians(),
185        elevation_rad: number(&rail["inclination_deg"], "the rail's inclination")?.to_radians(),
186        roll_rad: 0.0,
187        // RocketPy's rail has no friction (ADR-011).
188        friction_coefficient: 0.0,
189    };
190    let rows = declared_cd0
191        .as_array()
192        .ok_or_else(|| refuse("the record declares no drag table".to_owned()))?
193        .iter()
194        .map(|row| Ok((number(&row[0], "a Mach number")?, number(&row[1], "a C_D")?)))
195        .collect::<Result<Vec<_>, ValidateError>>()?;
196    let (machs, coefficients): (Vec<f64>, Vec<f64>) = rows.into_iter().unzip();
197    let radius_m = number(&carried["reference_radius_m"], "the reference radius")?;
198    let simulation = Simulation::new(
199        &rocket,
200        &configuration.id,
201        environment,
202        rail,
203        FlightSettings {
204            max_time_s: 6000.0,
205            ..FlightSettings::default()
206        },
207    )
208    .map_err(&failed)?;
209    let table = Table1D::new(
210        machs,
211        coefficients,
212        Interpolation::Linear,
213        // Outside the declared Mach range there is no declared drag, so none is invented.
214        Extrapolation::Error,
215    )
216    .map_err(|error| refuse(format!("the declared drag table: {error}")))?;
217    let simulation = simulation.with_drag_table(
218        DragTable::new(table.clone(), Some(table))
219            .with_reference_diameter_m(2.0 * radius_m)
220            .map_err(|error| refuse(format!("the declared drag's reference diameter: {error}")))?,
221    );
222    let simulation = match normal_force {
223        NormalForce::Own => simulation,
224        NormalForce::Recorded => {
225            let recorded = &carried["normal_force"];
226            let column = |what: &str| {
227                recorded[what]
228                    .as_array()
229                    .ok_or_else(|| refuse(format!("the record's normal force has no {what}")))?
230                    .iter()
231                    .map(|value| number(value, what))
232                    .collect::<Result<Vec<_>, ValidateError>>()
233            };
234            let against_mach = |values: Vec<f64>| {
235                Table1D::new(
236                    column("mach")?,
237                    values,
238                    Interpolation::Linear,
239                    Extrapolation::Clamp,
240                )
241                .map_err(|error| refuse(format!("the recorded normal force: {error}")))
242            };
243            let slope = against_mach(column("slope_per_rad")?)?;
244            let station = against_mach(column("cp_station_m")?)?;
245            let table = NormalForceTable::new(vec![
246                NormalForceColumn::new(0.0, slope.clone(), station.clone()),
247                NormalForceColumn::new(RECORDED_TOP_ANGLE_RAD, slope, station),
248            ])
249            .and_then(|table| table.with_reference_diameter_m(2.0 * radius_m))
250            .map_err(|error| refuse(format!("the recorded normal force: {error}")))?;
251            simulation.with_normal_force_table(table).map_err(&failed)?
252        }
253    };
254    let simulation = if tip_off {
255        simulation.with_tip_off()
256    } else {
257        simulation
258    };
259
260    // L75: the same rocket has to weigh the same, fly its drag on the same area, burn the same
261    // motor and carry its last two guides as far apart in both codes.
262    let assembly = simulation.assembly();
263    let dry = assembly
264        .motors
265        .iter()
266        .fold(assembly.layout.structure, |sum, motor| {
267            MassProperties::combine([&sum, &motor.dry_mass_properties()])
268        });
269    let [placed] = assembly.motors.as_slice() else {
270        return Err(refuse(format!(
271            "the design flies {} motors, where RocketPy's examples fly one",
272            assembly.motors.len()
273        )));
274    };
275    let motor = &placed.mounted.motor;
276    let recorded = &carried["motor"];
277    // The stretch the phase runs over: from the guide ahead of the last one leaving the rail to
278    // the last one leaving it, RocketPy's distance between its two buttons.
279    let guides = simulation.guides();
280    let stretch_m = guides
281        .tip_off_travel_m(rail.length_m)
282        .map(|begins| guides.exit_travel_m(rail.length_m) - begins)
283        .ok_or_else(|| refuse("the design has fewer than two guides".to_owned()))?;
284    for (what, hpr, rocketpy, agreement) in [
285        (
286            "distance between the last two guides, m",
287            stretch_m,
288            number(&case["button_spacing_m"], "the button spacing")?,
289            AREA_AGREEMENT,
290        ),
291        (
292            "dry mass, kg",
293            dry.mass_kg,
294            number(&carried["dry_mass_kg"], "the dry mass")?,
295            MASS_AGREEMENT,
296        ),
297        (
298            "reference radius, m",
299            0.5 * assembly.layout.reference_diameter_m,
300            radius_m,
301            AREA_AGREEMENT,
302        ),
303        (
304            "total impulse, N s",
305            motor.curve().total_impulse_ns(),
306            number(&recorded["total_impulse_ns"], "the total impulse")?,
307            MASS_AGREEMENT,
308        ),
309        (
310            "burn-out time, s",
311            motor.burnout_time_s(),
312            number(&recorded["burn_out_time_s"], "the burn-out time")?,
313            MASS_AGREEMENT,
314        ),
315        (
316            "initial propellant mass, kg",
317            motor.propellant_initial_mass_kg(),
318            number(
319                &recorded["propellant_initial_mass_kg"],
320                "the propellant mass",
321            )?,
322            MASS_AGREEMENT,
323        ),
324    ] {
325        let gap = (hpr - rocketpy).abs() / rocketpy.abs();
326        if !gap.is_finite() || gap > agreement {
327            return Err(refuse(format!(
328                "hpr's {what} is {hpr} where the record flew {rocketpy}, a relative {gap:.3e}"
329            )));
330        }
331    }
332
333    // RocketPy's tracked point, the center of dry mass, starts at the ground; hpr's starts `h0`
334    // above it, with the rocket's aft end at the rail's foot. Heights are measured from `h0`.
335    let start = simulation.initial_state();
336    let origin = start.position_enu_m + start.attitude.mul_vec3(dry.cg_m);
337    let h0 = origin.z;
338    let devices = carried["devices"]
339        .as_array()
340        .ok_or_else(|| refuse("the record lists no devices".to_owned()))?;
341    let count = devices.len();
342    let devices = devices
343        .iter()
344        .enumerate()
345        .map(|(index, device)| {
346            let trigger = match device["trigger"]["kind"].as_str() {
347                Some("apogee") if index == 0 => Trigger::Apogee,
348                Some("descending_below_height_agl") if index > 0 => Trigger::Altitude {
349                    height_above_ground_m: number(
350                        &device["trigger"]["height_m"],
351                        "a deployment height",
352                    )? + h0,
353                },
354                other => {
355                    return Err(refuse(format!(
356                        "device {index} has the trigger {other:?}; RocketPy's first parachute \
357                         opens at apogee and the rest at a height"
358                    )));
359                }
360            };
361            let mut built = Device::new(
362                device["name"].as_str().unwrap_or("parachute"),
363                DeviceDrag::DragArea {
364                    cd_s_m2: number(&device["cd_s_m2"], "a drag area")?,
365                },
366                trigger,
367            )
368            .with_lag_s(number(&device["lag_s"], "a lag")?);
369            // RocketPy flies one parachute at a time, the last deployed; hpr sums its open
370            // devices, so each one releases the one before as it opens.
371            if index + 1 < count {
372                built = built.with_release_by(index + 1);
373            }
374            Ok(built)
375        })
376        .collect::<Result<Vec<_>, ValidateError>>()?;
377    let simulation = simulation
378        .with_recovery(devices)
379        .map_err(&failed)?
380        .with_event(UserEvent {
381            name: "back at the starting height".to_owned(),
382            direction: Direction::Falling,
383            function: Box::new(move |sample: &Sample| sample.height_above_ground_m - h0),
384        });
385    let result = simulation.run(&mut ()).map_err(&failed)?;
386    if result.termination != Termination::GroundHit {
387        return Err(refuse(format!(
388            "the flight ended as {:?}, not at the ground",
389            result.termination
390        )));
391    }
392    let event = |kind: EventKind| {
393        result
394            .event(kind)
395            .map(|event| event.sample)
396            .ok_or_else(|| refuse(format!("the flight has no {kind:?} event")))
397    };
398    let (exit, apogee, landing) = (
399        event(EventKind::RailExit)?,
400        event(EventKind::Apogee)?,
401        event(EventKind::User(0))?,
402    );
403    let landed = landing.state.position_enu_m + landing.state.attitude.mul_vec3(dry.cg_m) - origin;
404
405    // The rail's axis, the axis square to it in its vertical plane (pointing up) and the
406    // horizontal axis to the right of its heading, as the oracle's script takes them.
407    let (heading, inclination) = (rail.azimuth_rad, rail.elevation_rad);
408    let up = DVec3::new(
409        -inclination.sin() * heading.sin(),
410        -inclination.sin() * heading.cos(),
411        inclination.cos(),
412    );
413    let right = DVec3::new(heading.cos(), -heading.sin(), 0.0);
414    // The static normal force where the last guide leaves, and its moment about that guide.
415    let pivot_station_m = simulation
416        .guides()
417        .pivot_station_m
418        .ok_or_else(|| refuse("the design has no guides".to_owned()))?;
419    let force = simulation
420        .aero()
421        .normal_force(&Flow::new(exit.mach, exit.angle_of_attack_rad, 0.0))
422        .map_err(|error| {
423            refuse(format!(
424                "the normal force where the last guide leaves: {error}"
425            ))
426        })?;
427    let attitude = exit.state.unit_attitude();
428    let axis = attitude.mul_vec3(DVec3::Z);
429    // How fast the nose's direction moves: the body rate crossed with the long axis.
430    let turning = attitude.mul_vec3(exit.state.body_rate_rad_s.cross(DVec3::Z));
431    let flown = Flown {
432        apogee_agl_m: apogee.height_above_ground_m - h0,
433        landing_east_m: landed.x,
434        landing_north_m: landed.y,
435        flight_time_s: landing.time_s,
436        last_guide_leaves: Release {
437            time_s: exit.time_s,
438            speed_m_s: exit.state.velocity_enu_m_s.length(),
439            nose_down_deg: (-axis.dot(up)).asin().to_degrees(),
440            nose_right_deg: axis.dot(right).asin().to_degrees(),
441            pitch_rate_nose_down_deg_s: (-turning.dot(up)).to_degrees(),
442            pitch_rate_nose_right_deg_s: turning.dot(right).to_degrees(),
443            angle_of_attack_deg: exit.angle_of_attack_rad.to_degrees(),
444            mach: exit.mach,
445            normal_force_coefficient: force.coefficient,
446            pivot_moment_m: force.coefficient * pivot_station_m - force.moment_m,
447        },
448    };
449    let figures = [
450        flown.apogee_agl_m,
451        flown.landing_east_m,
452        flown.landing_north_m,
453        flown.flight_time_s,
454        flown.last_guide_leaves.time_s,
455        flown.last_guide_leaves.speed_m_s,
456        flown.last_guide_leaves.nose_down_deg,
457        flown.last_guide_leaves.nose_right_deg,
458        flown.last_guide_leaves.pitch_rate_nose_down_deg_s,
459        flown.last_guide_leaves.pitch_rate_nose_right_deg_s,
460        flown.last_guide_leaves.angle_of_attack_deg,
461        flown.last_guide_leaves.mach,
462        flown.last_guide_leaves.normal_force_coefficient,
463        flown.last_guide_leaves.pivot_moment_m,
464    ];
465    if figures.iter().any(|figure| !figure.is_finite()) {
466        return Err(refuse(format!("a figure is not a number: {flown:?}")));
467    }
468    Ok(flown)
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474    use crate::tests::root;
475
476    /// The committed reference's flights, and the case and wind named.
477    fn reference() -> Value {
478        let text = std::fs::read_to_string(root().join("validation/reports/tip-off.json"))
479            .expect("the reference is committed");
480        serde_json::from_str(&text).expect("the reference parses")
481    }
482
483    fn row(reference: &Value, name: &str, wind: &str) -> (Value, Value) {
484        let case = reference["flown"]["cases"]
485            .as_array()
486            .expect("the reference lists its cases")
487            .iter()
488            .find(|case| case["name"] == name)
489            .expect("the case is in the reference");
490        let wind = case["winds"]
491            .as_array()
492            .expect("the case lists its winds")
493            .iter()
494            .find(|row| row["wind"] == wind)
495            .expect("the wind is in the case");
496        (case.clone(), wind.clone())
497    }
498
499    #[test]
500    fn the_recorded_normal_force_is_rocketpys_line_at_the_angle_the_guide_leaves_at() {
501        // RocketPy's normal force is its slope at the Mach number times the angle of attack, at
502        // any angle. The table flown here has two columns of that one slope, so the coefficient
503        // where the last guide leaves is the slope times the angle, at 22° as at 1°: a table
504        // that bent, or a slope scaled by the wrong area, fails here.
505        let reference = reference();
506        let drag = &reference["flown"]["drag"]["declared_cd0"];
507        let (case, wind) = row(&reference, "valetudo", "crosswind");
508        let flown = fly(&root(), &case, &wind, drag, (NormalForce::Recorded, true))
509            .expect("the flight flies");
510        let release = flown.last_guide_leaves;
511        assert!(
512            release.angle_of_attack_deg > 20.0,
513            "the crosswind flight leaves at a large angle: {release:?}"
514        );
515        let recorded = &wind["flown_with"]["normal_force"];
516        let column = |what: &str| -> Vec<f64> {
517            recorded[what]
518                .as_array()
519                .expect("the column is recorded")
520                .iter()
521                .map(|value| value.as_f64().expect("a number"))
522                .collect()
523        };
524        let slope = Table1D::new(
525            column("mach"),
526            column("slope_per_rad"),
527            Interpolation::Linear,
528            Extrapolation::Error,
529        )
530        .expect("the recorded slope is a table")
531        .eval(release.mach)
532        .expect("the Mach number is inside the record");
533        let line = slope * release.angle_of_attack_deg.to_radians();
534        assert!(
535            (release.normal_force_coefficient - line).abs() < 1e-9 * line,
536            "C_N {} against slope × angle {line}",
537            release.normal_force_coefficient
538        );
539        // HPR Sim's own normal force at that angle is more than twice the line.
540        let own = fly(&root(), &case, &wind, drag, (NormalForce::Own, true))
541            .expect("the flight flies")
542            .last_guide_leaves;
543        assert!(
544            own.normal_force_coefficient > 2.0 * slope * own.angle_of_attack_deg.to_radians(),
545            "{own:?}"
546        );
547    }
548
549    #[test]
550    fn a_design_that_is_not_the_rocket_the_record_flew_is_refused() {
551        // L75: a comparison of two rockets is no comparison. Each of the record's five figures
552        // moved by 1% is refused by name, as is a record with no normal force to fly on.
553        let reference = reference();
554        let drag = &reference["flown"]["drag"]["declared_cd0"];
555        let (case, wind) = row(&reference, "valetudo", "still");
556        for (pointer, named) in [
557            ("/flown_with/dry_mass_kg", "dry mass"),
558            ("/flown_with/reference_radius_m", "reference radius"),
559            ("/flown_with/motor/total_impulse_ns", "total impulse"),
560            ("/flown_with/motor/burn_out_time_s", "burn-out time"),
561            (
562                "/flown_with/motor/propellant_initial_mass_kg",
563                "initial propellant mass",
564            ),
565        ] {
566            let mut other = wind.clone();
567            let figure = other
568                .pointer_mut(pointer)
569                .expect("the record has the figure");
570            *figure = (1.01 * figure.as_f64().expect("a number")).into();
571            let error = fly(&root(), &case, &other, drag, (NormalForce::Own, true))
572                .expect_err("another rocket is refused")
573                .to_string();
574            assert!(error.contains(named), "{pointer}: {error}");
575        }
576        // And the stretch the phase runs over: buttons another distance apart are another
577        // rocket on the rail.
578        let mut other = case.clone();
579        other["button_spacing_m"] = (1.01 * case["button_spacing_m"].as_f64().unwrap()).into();
580        let error = fly(&root(), &other, &wind, drag, (NormalForce::Own, true))
581            .expect_err("other buttons are refused")
582            .to_string();
583        assert!(
584            error.contains("distance between the last two guides"),
585            "{error}"
586        );
587        let mut bare = wind.clone();
588        bare["flown_with"]["normal_force"] = Value::Null;
589        let error = fly(&root(), &case, &bare, drag, (NormalForce::Recorded, true))
590            .expect_err("no recorded normal force, no flight on it")
591            .to_string();
592        assert!(error.contains("normal force"), "{error}");
593        // The same record flies on HPR Sim's own.
594        fly(&root(), &case, &bare, drag, (NormalForce::Own, true)).expect("the flight flies");
595    }
596
597    #[test]
598    fn the_phase_is_only_flown_when_asked_for() {
599        // Guided, the rocket leaves its last guide along the rail with no turning rate; with the
600        // phase it leaves turning nose down under gravity, at the same time and speed to a part
601        // in a thousand.
602        let reference = reference();
603        let drag = &reference["flown"]["drag"]["declared_cd0"];
604        let (case, wind) = row(&reference, "valetudo", "still");
605        let guided = fly(&root(), &case, &wind, drag, (NormalForce::Own, false))
606            .expect("the flight flies")
607            .last_guide_leaves;
608        let tipped = fly(&root(), &case, &wind, drag, (NormalForce::Own, true))
609            .expect("the flight flies")
610            .last_guide_leaves;
611        assert!(guided.pitch_rate_nose_down_deg_s.abs() < 1e-9, "{guided:?}");
612        assert!(guided.nose_down_deg.abs() < 1e-9, "{guided:?}");
613        assert!(tipped.pitch_rate_nose_down_deg_s > 0.1, "{tipped:?}");
614        assert!(tipped.nose_down_deg > 0.0, "{tipped:?}");
615        assert!((tipped.time_s - guided.time_s).abs() < 1e-3 * guided.time_s);
616        assert!((tipped.speed_m_s - guided.speed_m_s).abs() < 1e-3 * guided.speed_m_s);
617    }
618}