Skip to main content

hpr_validate/
public_predictions.rs

1//! Predictions merged before their errors: the public real flights that join the seven of
2//! [`crate::real_flight`], each flown from its record alone ([M2.3d3][m2-3d3], decisions
3//! [ADR-328][adr-328] §1a and [ADR-334][adr-334]).
4//!
5//! A flight here has a design, a motor, a mass, a site, a rail and its air (the day's weather, or
6//! a stored simulation's standard atmosphere and wind), each from a
7//! named record, and a *rule* for the apogee its log is read at. It has no measured apogee:
8//! nothing in this module parses a flight log, and neither [`PredictionRow`] nor
9//! [`PredictionsReport`] has a field for a measured height or an error. The log's bytes are
10//! hashed, so the report pins the file the rule is applied to, and never read as numbers. The
11//! comparison is [`crate::predicted_first`]'s, in the real-flights report ([the
12//! errors][m2-3d2]): it prints each prediction here beside its log's apogee and its error, and a
13//! prediction that changes is revised beside its merged number, never edited ([`REVISIONS`]).
14//!
15//! What is flown is what [`crate::real_flight`] flies for the seven: the design under
16//! `validation/designs/` built from the example's inputs, on the example's own thrust file with
17//! its burn time, from the example's rail and site, in the ERA5 air of the launch hour, on HPR
18//! Sim's own aerodynamics. The three EuRoC 2022 flights' weather file is netCDF-4, which
19//! [`hpr_io::netcdf`] refuses; `validation/oracles/netcdf/euroc_2022.py` converts it as the guide
20//! says and checks the result, and [`CONVERSION_RECORD`] holds both files' SHA-256 and the levels
21//! RocketPy read at each flight's site and hour. The converted file is flown only if its SHA-256
22//! is the committed one and HPR Sim reads those levels from it. Each prediction is held to the
23//! apogee first merged ([`MERGED`]), or to its revision's ([`REVISIONS`]).
24//!
25//! The predicted apogee is read as the log's altimeter would read it ([`Barometer`]: the standard
26//! atmosphere's altitude of the flown air's pressure at the apogee, less the pad's), because that
27//! is what it is compared with; the height climbed is kept beside it.
28//!
29//! Two more flights have no example notebook ([the Macie XL predictions][m2-3d5], decision
30//! [ADR-337][adr-337]): [`DESIGN_FILE_FLIGHTS`], both of one OpenRocket design saved in a pinned
31//! public repository ([`ROCKETRY_FILES`]). Each is flown from that file alone, read as OpenRocket
32//! 24.12 saved it: the motor configuration, rod, wind and air of the stored simulation the
33//! repository names for the flight, on the bundled curve the file's digest names. With them all
34//! five predictions are here ([`MERGED`]).
35//!
36//! [m2-3d3]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m2-3d3
37//! [m2-3d2]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m2-3d2
38//! [adr-328]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0328-the-2026-11-08-review-twelve-public-flights-predictions-first.md
39//! [adr-334]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0334-m2-3d1-in-three-the-euroc-2022-predictions-first.md
40//! [m2-3d5]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m2-3d5
41//! [adr-337]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0337-the-macie-xl-predictions-each-flight-s-stored-simulation-flown-as-saved.md
42
43use std::fmt::Write as _;
44use std::path::Path;
45
46use hpr_atmos::ConstantWind;
47use hpr_core::geodesy::Geodetic;
48use hpr_design::Rocket;
49use hpr_io::era5::{Era5Profile, Era5Request, UtcTime};
50use hpr_io::netcdf::NetCdf;
51use hpr_io::ork;
52use hpr_sim::{Environment, EventKind, FlightMetrics, FlightSettings, Rail, Simulation};
53use serde::{Deserialize, Serialize};
54use serde_json::Value;
55
56use crate::correction::{Correction, Variant};
57use crate::real_flight::Varied;
58use crate::real_flight::{
59    Altimeter, Barometer, FileRead, Heights, MASS_FIXTURE, ROCKETPY, RealFlightError,
60    example_thrust_of, fixture_case_of, fmt_number, launch_day_at, parse_thrust, rail_from,
61    read_bytes, rocket_with_curve, sha256_hex,
62};
63
64/// The predictions, as data.
65pub const PREDICTIONS_JSON: &str = "validation/reports/public-predictions.json";
66
67/// The predictions, as a page.
68pub const PREDICTIONS_MD: &str = "validation/reports/public-predictions.md";
69
70/// The record of the EuRoC 2022 weather file's conversion: the source's and the converted file's
71/// path and SHA-256, and the levels RocketPy read at each flight's site and hour, written by
72/// `validation/oracles/netcdf/euroc_2022.py`.
73pub const CONVERSION_RECORD: &str = "validation/fixtures/weather/euroc-2022-conversion.json";
74
75/// How long a prediction flies at most, s. Every flight here reaches its apogee in under a
76/// minute; with no parachute in the design it then falls to the ground and stops.
77const MAX_TIME_S: f64 = 600.0;
78
79/// What "traced" means in [`PredictedFlight::untraced`], as the page says it.
80pub const TRACED_RULE: &str = "An input is traced when the flight's own record states it: here \
81    RocketPy's example notebook, which holds the team's inputs. What no RocketPy example records \
82    is a placeholder in the designs built from them, the seven compared flights' too, and doesn't \
83    count against the tag: the surface finish, the rail buttons' size, the fins' thickness where \
84    no airfoil file gives it, and their edge shape where no airfoil file or published section \
85    does. They move the drag, so a traced flight's inputs are stated, not exact. A flight is \
86    tagged not traced when its record leaves out, or contradicts, something else that moves the \
87    apogee.";
88
89/// A prediction as it was first merged, in the digits its page prints.
90#[derive(Debug, Clone, Copy, PartialEq)]
91pub struct MergedPrediction {
92    /// The flight's public id.
93    pub id: &'static str,
94    /// Its predicted apogee as the log's altimeter would read it, m.
95    pub apogee_m: f64,
96    /// Its predicted apogee as a height above the pad, m.
97    pub height_apogee_m: f64,
98    /// Its catalog curve's predicted apogee as the altimeter would read it, m, where it has one.
99    pub catalog_apogee_m: Option<f64>,
100}
101
102/// The predictions as first merged ([the EuRoC 2022 predictions][m2-3d3], then [the Macie XL
103/// predictions][m2-3d5]), which [`PredictionsReport::check_consistent`] holds every report to,
104/// the committed one in CI and a flown one before it is written: each flight's apogee as a
105/// reading and as a height, and Andromeda's on the catalog curve. The order is
106/// [`NEW_FLIGHTS`]', then [`DESIGN_FILE_FLIGHTS`]'.
107///
108/// These lines are not edited. A prediction that has to change is revised beside its merged
109/// number, with the reason, in [`REVISIONS`] ([twelve public flights, predictions first][adr-328],
110/// §1b); without an entry there, a changed prediction fails here and the writers refuse it.
111///
112/// [m2-3d3]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m2-3d3
113/// [m2-3d5]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m2-3d5
114/// [adr-328]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0328-the-2026-11-08-review-twelve-public-flights-predictions-first.md
115pub const MERGED: [MergedPrediction; 5] = [
116    MergedPrediction {
117        id: "astra",
118        apogee_m: 3037.1,
119        height_apogee_m: 3155.4,
120        catalog_apogee_m: None,
121    },
122    MergedPrediction {
123        id: "andromeda",
124        apogee_m: 3581.0,
125        height_apogee_m: 3729.5,
126        catalog_apogee_m: Some(3050.3),
127    },
128    MergedPrediction {
129        id: "erebus-11",
130        apogee_m: 2714.1,
131        height_apogee_m: 2808.7,
132        catalog_apogee_m: None,
133    },
134    MergedPrediction {
135        id: "macie-xl-1",
136        apogee_m: 706.2,
137        height_apogee_m: 706.3,
138        catalog_apogee_m: None,
139    },
140    MergedPrediction {
141        id: "macie-xl-2",
142        apogee_m: 692.6,
143        height_apogee_m: 692.7,
144        catalog_apogee_m: None,
145    },
146];
147
148/// How far a prediction may sit from its merged number and still print as it: half of the last
149/// digit the page prints, m.
150pub(crate) const MERGED_WITHIN_M: f64 = 0.05;
151
152/// A merged prediction that had to change: the number HPR Sim flies now, kept beside the merged
153/// one, with the reason ([twelve public flights, predictions first][adr-328], §1b).
154///
155/// [adr-328]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0328-the-2026-11-08-review-twelve-public-flights-predictions-first.md
156#[derive(Debug, Clone, Copy, PartialEq)]
157pub struct Revision {
158    /// The flight's public id, one of [`MERGED`]'s.
159    pub id: &'static str,
160    /// Its predicted apogee now, as the log's altimeter would read it, m.
161    pub apogee_m: f64,
162    /// Its predicted apogee now, as a height above the pad, m.
163    pub height_apogee_m: f64,
164    /// Its catalog curve's predicted apogee now, m, where the flight has one.
165    pub catalog_apogee_m: Option<f64>,
166    /// What changed and why, in words a reader of the report can check: the change to HPR Sim or
167    /// to an input, and the record it rests on. Never empty.
168    pub because: &'static str,
169}
170
171/// The revisions: one. Erebus 11's apogee rose 46.0 m with the base drag behind a boattail
172/// that [ADR-362][adr-362] relieved; the other eleven fly as they were merged.
173///
174/// An entry here is the only way a prediction may differ from [`MERGED`] by more than 0.05 m
175/// (`MERGED_WITHIN_M`): the real-flights
176/// report then prints both numbers and both errors, and its summary gives the means over the
177/// merged predictions beside the means over the revised ones. A revision is added in the pull
178/// request that changes the number, by hand, with its reason; nothing writes one.
179///
180/// [adr-362]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0362-base-drag-behind-a-boattail-below-mach-0-8-held-to-the-hermes-a-3a.md
181pub const REVISIONS: [Revision; 1] = [Revision {
182    id: "erebus-11",
183    apogee_m: 2760.1,
184    height_apogee_m: 2856.5,
185    catalog_apogee_m: None,
186    because: "M1.14i3 (ADR-362) changed HPR Sim's base drag below Mach 0.8: behind a boattail \
187              the base is d_B/d of a flat base's value (NASA TR R-100, 1961, p. 11), set on the \
188              Hermes A-3A's measured base drag (NACA RM SL55F15), where the old rule read 0.050 \
189              to 0.064 high on its largest cross-section and the new one 0.025 to 0.035. Erebus \
190              11 has a boattail; nothing in its design or inputs changed.",
191}];
192
193/// The apogee a flight's log is read at: the rule, never the value.
194#[derive(Debug, Clone, Copy, PartialEq)]
195pub struct Reference {
196    /// The log: under `refs/rocketpy/data/rockets/` for a flight in [`NEW_FLIGHTS`], under the
197    /// pinned repository's checkout for one in [`DESIGN_FILE_FLIGHTS`]. Its bytes are hashed and
198    /// never parsed here.
199    pub log: &'static str,
200    /// The rule, in words: which column, read how far.
201    pub rule: &'static str,
202    /// What the log's height is taken to be, and so how the prediction is read.
203    pub altimeter: Altimeter,
204}
205
206/// A second prediction shown beside a flight's counted one and never counted: the design flown
207/// as committed, on its own bundled catalog curve.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub struct CatalogCurve {
210    /// The motor, as the catalog names it.
211    pub motor: &'static str,
212    /// Why it is shown, and why it is not the counted one.
213    pub why: &'static str,
214}
215
216/// One flight predicted before its log is compared.
217#[derive(Debug, Clone, Copy, PartialEq)]
218pub struct PredictedFlight {
219    /// The flight's public id, the one the real-flights report will list it under.
220    pub id: &'static str,
221    /// The rocket, the team and the event, in words.
222    pub title: &'static str,
223    /// The design flown, by file stem under `validation/designs/`, which, less its `rocketpy-`,
224    /// is its case name in [`MASS_FIXTURE`].
225    pub design: &'static str,
226    /// Where the site, date, rail and geometry come from, in RocketPy 1.13.0's notebook.
227    pub source: &'static str,
228    /// The motor, as its record names it.
229    pub motor: &'static str,
230    /// Where the thrust file and its burn time come from.
231    pub motor_source: &'static str,
232    /// Where the mass comes from.
233    pub mass_source: &'static str,
234    /// The site: latitude and longitude, degrees, and elevation above sea level, m.
235    pub site: (f64, f64, f64),
236    /// The launch hour the weather is read at, UTC: year, month, day, hour.
237    pub utc: (i32, u32, u32, u32),
238    /// The rail: length, m; inclination from the horizontal and heading from north, degrees.
239    pub rail: (f64, f64, f64),
240    /// The apogee rule.
241    pub reference: Reference,
242    /// What moves the apogee and no record states, or a record contradicts; empty when every
243    /// input is traced ([`TRACED_RULE`]).
244    pub untraced: &'static [&'static str],
245    /// The catalog curve's prediction, where the counted curve is not the catalog's.
246    pub catalog_curve: Option<CatalogCurve>,
247    /// What else a reader should know before the comparison; empty when nothing.
248    pub note: &'static str,
249}
250
251/// The flights, in the order the page lists them: EuRoC 2022's three.
252///
253/// Each site, date and rail is the example notebook's (`docs/examples/<name>_flight_sim.ipynb` in
254/// RocketPy 1.13.0). The notebooks give local time with `timezone="Portugal"`: Western European
255/// Summer Time, UTC+1, until 30 October 2022, so 16 h is 15:00Z and 14 h is 13:00Z.
256///
257/// Every rule and tag here was written before any of the three was flown, and each log was looked
258/// at only for its columns and for a transient near its peak (none: each peak is the whole log's
259/// highest reading). That order is the maintainer's statement: the rules and the first flown
260/// numbers reached the repository in one change, so no check can show it.
261pub const NEW_FLIGHTS: [PredictedFlight; 3] = [
262    PredictedFlight {
263        id: "astra",
264        title: "Astra, Faraday Rocketry UPV, EuRoC 2022 (L1350)",
265        design: "rocketpy-astra",
266        source: "astra_flight_sim.ipynb:123-131 (site, date), :247-280 (rocket, rail buttons, \
267                 motor position, nose, fins), :316-318 (rail)",
268        motor: "Cesaroni 4263L1350-P",
269        motor_source: "astra_flight_sim.ipynb:155-157: RocketPy's copy of the certified curve, \
270                       cut at the notebook's burn time",
271        mass_source: "astra_flight_sim.ipynb:249-251 (mass, inertia and center without the motor), \
272                      :158-162 (the grain, whose density and size give the propellant), :168-170 \
273                      (no motor dry mass or inertia)",
274        site: (39.3897, -8.288_963_9, 160.0),
275        utc: (2022, 10, 13, 15),
276        rail: (12.0, 84.0, 133.0),
277        reference: Reference {
278            log: "astra/flight_data.csv",
279            rule: "the highest reading of the log's `alt` column, in meters, the log read whole",
280            altimeter: Altimeter::AssumedBarometric(
281                "the notebook calls it a COTS altimeter's flight (astra_flight_sim.ipynb:383-385), \
282                 one row a second beside a latitude and a longitude, and records no more: \
283                 barometric assumed, as hobby altimeters are",
284            ),
285        },
286        untraced: &[],
287        catalog_curve: None,
288        note: "",
289    },
290    PredictedFlight {
291        id: "andromeda",
292        title: "Andromeda, Aristotle Space and Aeronautics Team, EuRoC 2022 (the team's curve)",
293        design: "rocketpy-andromeda",
294        source: "andromeda_flight_sim.ipynb:123-131 (site, date), :244-277 (rocket, rail buttons, \
295                 motor position, nose, fins), :388-390 (rail)",
296        motor: "the team's thrust file, flown in the notebook under the name of a Cesaroni M2020",
297        motor_source: "andromeda_flight_sim.ipynb:153 and :162-165: \"obtained by the team, after \
298                       testing\", cut at the notebook's burn time; the catalog file is commented \
299                       out at :163",
300        mass_source: "andromeda_flight_sim.ipynb:246-248 (mass, inertia and center without the \
301                      motor), :166-170 (the grain), :176-178 (no motor dry mass or inertia)",
302        site: (39.388_692, -8.287_814, 160.0),
303        utc: (2022, 10, 14, 13),
304        rail: (12.0, 84.0, 133.0),
305        reference: Reference {
306            log: "andromeda/flight_data.csv",
307            rule: "the highest reading of the log's `alt(m)` column, the log read whole",
308            altimeter: Altimeter::AssumedBarometric(
309                "the notebook calls it a COTS altimeter (andromeda_flight_sim.ipynb:459-461), \
310                 logged in feet and in meters with a vertical speed, and records no more: barometric assumed, as \
311                 hobby altimeters are",
312            ),
313        },
314        untraced: &[
315            "the flight carried the team's air brakes, and no record says when or how far they \
316             opened: none is flown here, so any opening leaves this prediction high",
317            "the thrust file holds more impulse than the Cesaroni M2020 reload it is named for is \
318             certified at, so the notebook does not settle which motor the logged flight burned",
319        ],
320        catalog_curve: Some(CatalogCurve {
321            motor: "Cesaroni 8429M2020-P",
322            why: "the reload the notebook names, on its certified curve as bundled, whole. Shown \
323                  beside the counted prediction and never counted: every RocketPy flight here \
324                  is counted on its example's own thrust file",
325        }),
326        note: "both tags are the research note's findings (docs/research/andromeda-impulse.md), \
327               written down before this flight was flown",
328    },
329    PredictedFlight {
330        id: "erebus-11",
331        title: "Erebus 11, BME Suborbitals, EuRoC 2022 (a Cesaroni Pro54 K)",
332        design: "rocketpy-erebus-11",
333        source: "erebus_flight_sim.ipynb:123-131 (site, date), :251-284 (rocket, rail buttons, \
334                 motor position, nose, fins, tail), :320-322 (rail)",
335        motor: "a Cesaroni Pro54 K-class motor, as the notebook says; the example's thrust file",
336        motor_source: "erebus_flight_sim.ipynb:153 and :162-165, cut at the notebook's burn time",
337        mass_source: "erebus_flight_sim.ipynb:253-255 (mass, inertia and center without the \
338                      motor), :166-172 (the grain), :163 and :173-174 (no motor dry mass or \
339                      inertia)",
340        site: (39.3897, -8.288_963_9, 160.0),
341        utc: (2022, 10, 15, 15),
342        rail: (12.0, 84.0, 133.0),
343        reference: Reference {
344            log: "erebus11/flight_data_filtered.csv",
345            rule: "the highest reading of the log's `alt` column, in meters, the log read whole",
346            altimeter: Altimeter::AssumedBarometric(
347                "the notebook calls it a COTS altimeter (erebus_flight_sim.ipynb:390-392), a file \
348                 named filtered, and records no more: barometric assumed, as hobby altimeters are",
349            ),
350        },
351        untraced: &[],
352        catalog_curve: None,
353        note: "",
354    },
355];
356
357/// A public repository pinned in `validation/refs.lock.toml`, which a design-file flight's
358/// design and log are read from.
359#[derive(Debug, Clone, Copy, PartialEq, Eq)]
360pub struct PinnedRepository {
361    /// Its name in the lock, which `cargo xtask refs fetch <name>` takes.
362    pub name: &'static str,
363    /// Where it is cloned from.
364    pub url: &'static str,
365    /// The commit it is pinned at.
366    pub commit: &'static str,
367    /// Its checkout, from the repository root.
368    pub dest: &'static str,
369    /// Its license, as GitHub's license API reads its `LICENSE`.
370    pub license: &'static str,
371}
372
373/// The repository both Macie XL flights are read from: its design file and the two logs, as
374/// they stand at its pinned commit of 27 June 2026. No file of it is committed here: only SHA-256
375/// hashes and numbers read from it.
376pub const ROCKETRY_FILES: PinnedRepository = PinnedRepository {
377    name: "rocketry-files",
378    url: "https://github.com/rlhatcher/rocketry-files.git",
379    commit: "2ddcaf8858a71f9b4d910877c603ed95fe0a9769",
380    dest: "refs/public-flights/rocketry-files",
381    license: "MIT",
382};
383
384/// What "traced" means for a flight in [`DESIGN_FILE_FLIGHTS`], as the page says it.
385pub const DESIGN_FILE_TRACED_RULE: &str = "For a flight read from a design file, the record is \
386    that file and its repository's page about the flight. The file states the rocket and names \
387    the motor. A stored simulation's launch conditions are what a simulation was run with, not a \
388    record of the day, so the site, the air, the wind and the rod count as not traced unless \
389    the page states them. So does the mass, unless the page says the rocket was weighed as \
390    flown, and the motor's curve where the reader warns that its file and its certifier's \
391    record disagree.";
392
393/// One flight predicted from a design file in a pinned public repository, before its log is
394/// compared.
395#[derive(Debug, Clone, Copy, PartialEq)]
396pub struct DesignFileFlight {
397    /// The flight's public id, the one the real-flights report will list it under.
398    pub id: &'static str,
399    /// The rocket and the flight, in words.
400    pub title: &'static str,
401    /// The repository.
402    pub repository: PinnedRepository,
403    /// The design file, in the repository.
404    pub design: &'static str,
405    /// The stored simulation flown, by its name in the design file: its motor configuration and
406    /// its launch conditions.
407    pub simulation: &'static str,
408    /// Where the pairing of flight and simulation, and the design, come from.
409    pub source: &'static str,
410    /// The motor, as the stored simulation's configuration names it.
411    pub motor: &'static str,
412    /// Where the motor and its curve come from.
413    pub motor_source: &'static str,
414    /// Where the mass comes from.
415    pub mass_source: &'static str,
416    /// Where the site, rod, wind and air come from.
417    pub conditions_source: &'static str,
418    /// The apogee rule; its log is in the repository.
419    pub reference: Reference,
420    /// What moves the apogee and no record states, or a record contradicts
421    /// ([`DESIGN_FILE_TRACED_RULE`]).
422    pub untraced: &'static [&'static str],
423    /// What else a reader should know before the comparison; empty when nothing.
424    pub note: &'static str,
425}
426
427/// What both Macie XL flights leave untraced.
428const MACIE_XL_SITE_UNTRACED: &str = "no record gives the day, its air and wind, or the rail, \
429    and of the site only each log's header gives the pad's height above sea level (12 ft for \
430    flight 1, 37 ft for flight 2): the stored simulation's are flown, its sea level among them, \
431    and all nine simulations in the file carry the same ones";
432/// The same, for the mass.
433const MACIE_XL_MASS_UNTRACED: &str = "no record says the rocket was weighed as flown: the \
434    file's parts and overrides are flown";
435/// The same, for the motor's curve.
436const MACIE_XL_CURVE_UNTRACED: &str = "the reader warns that the motor's curve file disagrees \
437    with ThrustCurve.org's record of the motor (the figures are in the flight's \
438    `reader_warnings` in the JSON); the file the design's digest names is flown";
439/// Flight 1's own: the masses its motor flies are not the ones OpenRocket flew.
440const MACIE_XL_1_MOTOR_MASS_UNTRACED: &str = "the motor flies the bundled catalog's masses for \
441    it, 313.6 g of propellant and 555.52 g loaded, as every catalog motor does, where the curve \
442    file the design's digest names, and OpenRocket's own record of that digest, give 310.016 g \
443    and 555.072 g (the table's `mass_difference`)";
444/// What the page says of how both are flown.
445const MACIE_XL_NOTE: &str = "the stored simulation's wind carries a turbulence of a tenth of \
446    its speed, which is not flown: the wind here is steady. The parachutes are not flown \
447    either; the file opens one at apogee and the other lower, on the way down, so neither \
448    moves it";
449
450/// The flights read from a design file, in the order the page lists them: Macie XL's two.
451///
452/// Both fly `macie/macie-xl.ork`, an OpenRocket 24.12 design. The repository's page about the
453/// rocket (`macie/index.md`) lists the two flights and names each flight's files
454/// `maciexl-<flight>-<source>`, `or` for the OpenRocket simulation; the design file holds a
455/// stored simulation under each of those names, and that one is flown.
456///
457/// The apogee rule is the one [twelve public flights, predictions first][adr-328] fixed for a
458/// log with an ejection spike, merged before HPR Sim could fly this file at all. The tags, and
459/// the choice to fly each stored simulation's own conditions, were written after `hpr sim` had
460/// flown the file at that command's defaults, and with both measured apogees already in the
461/// research notes. Neither choice was made on a number: the file is flown as it is saved, and
462/// nothing in it was changed.
463///
464/// [adr-328]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0328-the-2026-11-08-review-twelve-public-flights-predictions-first.md
465pub const DESIGN_FILE_FLIGHTS: [DesignFileFlight; 2] = [
466    DesignFileFlight {
467        id: "macie-xl-1",
468        title: "Macie XL, flight 1 (AeroTech I284W)",
469        repository: ROCKETRY_FILES,
470        design: "macie/macie-xl.ork",
471        simulation: "maciexl-1-or",
472        source: "macie/index.md (the two flights; the file names that pair `maciexl-1-or` with \
473                 flight 1) and macie/macie-xl.ork, read whole as OpenRocket 24.12 saved it",
474        motor: "AeroTech I284W",
475        motor_source: "the stored simulation's motor configuration in macie/macie-xl.ork, which \
476                       names the motor and the digest of its curve; the bundled ThrustCurve.org \
477                       file that digest names is flown",
478        mass_source: "macie/macie-xl.ork: its parts and the stage's mass and center overrides, \
479                      which add to the parts as OpenRocket 24.12 weighs them; the motor's masses \
480                      are the bundled catalog's for the motor, 313.6 g of propellant and 555.52 g \
481                      loaded",
482        conditions_source: "the stored simulation's launch conditions in macie/macie-xl.ork",
483        reference: Reference {
484            log: "macie/flights/MRC Summer 26/maciexl-1-sl.pf2",
485            rule: "the apogee the altimeter worked out, in the log's header (its `Apogee:` \
486                   line, in feet above the pad, 0.3048 m to the foot), which leaves out the \
487                   ejection spike among the samples; never the highest sample",
488            altimeter: Altimeter::Barometric(
489                "the log's first line names a PerfectFlite altimeter, `PerfectFlite SLCF`, and \
490                 a PerfectFlite has a barometer and no accelerometer (docs/format/pf2.md)",
491            ),
492        },
493        untraced: &[
494            MACIE_XL_SITE_UNTRACED,
495            MACIE_XL_MASS_UNTRACED,
496            MACIE_XL_CURVE_UNTRACED,
497            MACIE_XL_1_MOTOR_MASS_UNTRACED,
498        ],
499        note: MACIE_XL_NOTE,
500    },
501    DesignFileFlight {
502        id: "macie-xl-2",
503        title: "Macie XL, flight 2 (Cesaroni 601I350-16A)",
504        repository: ROCKETRY_FILES,
505        design: "macie/macie-xl.ork",
506        simulation: "maciexl-2-or",
507        source: "macie/index.md (the two flights; the file names that pair `maciexl-2-or` with \
508                 flight 2) and macie/macie-xl.ork, read whole as OpenRocket 24.12 saved it",
509        motor: "Cesaroni 601I350-16A",
510        motor_source: "the stored simulation's motor configuration in macie/macie-xl.ork, which \
511                       names the motor and the digest of its curve; the bundled ThrustCurve.org \
512                       file that digest names is flown",
513        mass_source: "macie/macie-xl.ork: its parts and the stage's mass and center overrides, \
514                      which add to the parts as OpenRocket 24.12 weighs them; the motor's masses \
515                      are the bundled catalog's for the motor, which are OpenRocket's for the \
516                      design's digest",
517        conditions_source: "the stored simulation's launch conditions in macie/macie-xl.ork",
518        reference: Reference {
519            log: "macie/flights/MRC Summer 26/maciexl-2-sl.pf2",
520            rule: "the apogee the altimeter worked out, in the log's header (its `Apogee:` \
521                   line, in feet above the pad, 0.3048 m to the foot); never the highest sample",
522            altimeter: Altimeter::Barometric(
523                "the log's first line names a PerfectFlite altimeter, `PerfectFlite SLCF`, and \
524                 a PerfectFlite has a barometer and no accelerometer (docs/format/pf2.md)",
525            ),
526        },
527        untraced: &[
528            MACIE_XL_SITE_UNTRACED,
529            MACIE_XL_MASS_UNTRACED,
530            MACIE_XL_CURVE_UNTRACED,
531        ],
532        note: MACIE_XL_NOTE,
533    },
534];
535
536/// The catalog curve's prediction, as the report keeps it.
537#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
538pub struct CatalogCurveRow {
539    /// The motor, as the catalog names it.
540    pub motor: String,
541    /// Why it is shown and not counted.
542    pub why: String,
543    /// The impulse flown, N s.
544    pub total_impulse_ns: f64,
545    /// The mass at liftoff, kg: the counted flight's, since the design's propellant is its
546    /// grains' and only the curve differs.
547    pub liftoff_mass_kg: f64,
548    /// Its predicted apogee as the log's altimeter would read it, m. Never counted.
549    pub predicted_apogee_m: f64,
550    /// Its predicted apogee as a height above the pad, m.
551    pub predicted_height_apogee_m: f64,
552}
553
554/// One flight's prediction, as the report keeps it. It has no field for a measured apogee or an
555/// error, on purpose.
556#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
557pub struct PredictionRow {
558    /// The flight's public id.
559    pub id: String,
560    /// The rocket, team and event.
561    pub title: String,
562    /// The design flown.
563    pub design: String,
564    /// Where the site, date, rail and geometry come from.
565    pub source: String,
566    /// The motor, as its record names it.
567    pub motor: String,
568    /// Where the thrust file and its burn time come from.
569    pub motor_source: String,
570    /// The thrust file flown, from the repository root.
571    pub thrust_file: String,
572    /// The burn time the example cuts it at, s.
573    pub burn_time_s: Option<f64>,
574    /// The impulse flown, N s.
575    pub total_impulse_ns: f64,
576    /// Where the mass comes from.
577    pub mass_source: String,
578    /// The mass the record gives without the motor, kg.
579    pub mass_without_motor_kg: f64,
580    /// The mass flown at liftoff, kg: the above and the grain.
581    pub liftoff_mass_kg: f64,
582    /// The site's latitude, degrees north.
583    pub latitude_deg: f64,
584    /// The site's longitude, degrees east.
585    pub longitude_deg: f64,
586    /// The site's elevation above sea level, m.
587    pub elevation_m: f64,
588    /// The rail's length, m.
589    pub rail_length_m: f64,
590    /// The rail's inclination from the horizontal, degrees.
591    pub rail_inclination_deg: f64,
592    /// The rail's heading from north, degrees.
593    pub rail_heading_deg: f64,
594    /// The hour the weather is read at.
595    pub weather_time_utc: String,
596    /// The log the rule is applied to, from the repository root.
597    pub reference_log: String,
598    /// That log's SHA-256: its bytes hashed, never parsed.
599    pub reference_log_sha256: String,
600    /// The apogee rule.
601    pub reference_rule: String,
602    /// What the log's height is taken to be.
603    pub altimeter: String,
604    /// Where that comes from.
605    pub altimeter_evidence: String,
606    /// Whether every input is traced to the record.
607    pub all_inputs_traced: bool,
608    /// What isn't, in words.
609    pub untraced: Vec<String>,
610    /// The predicted apogee as the log's altimeter would read it, m: the counted prediction.
611    pub predicted_apogee_m: f64,
612    /// The predicted apogee as a height above the pad, m.
613    pub predicted_height_apogee_m: f64,
614    /// The predicted time from ignition to apogee, s.
615    pub predicted_time_to_apogee_s: f64,
616    /// The flight's largest Mach number.
617    pub hpr_max_mach: f64,
618    /// The catalog curve's prediction, shown beside and never counted.
619    pub catalog_curve: Option<CatalogCurveRow>,
620    /// Every file read, with its SHA-256; the log's is its bytes' alone.
621    pub files: Vec<FileRead>,
622    /// The SHA-256 of the flight's entry in [`NEW_FLIGHTS`].
623    pub inputs_sha256: String,
624    /// What else a reader should know.
625    pub note: String,
626}
627
628/// One design-file flight's prediction, as the report keeps it. Like [`PredictionRow`], it has
629/// no field for a measured apogee or an error, on purpose.
630#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
631pub struct DesignFilePredictionRow {
632    /// The flight's public id.
633    pub id: String,
634    /// The rocket and the flight.
635    pub title: String,
636    /// The repository the design and the log are read from.
637    pub repository: String,
638    /// The commit it is pinned at.
639    pub repository_commit: String,
640    /// Its license.
641    pub repository_license: String,
642    /// The design file flown, from the repository root.
643    pub design_file: String,
644    /// Its SHA-256.
645    pub design_file_sha256: String,
646    /// The stored simulation flown, by name.
647    pub simulation: String,
648    /// The motor configuration that simulation flies, by the file's id for it.
649    pub configuration: String,
650    /// Where the pairing and the design come from.
651    pub source: String,
652    /// The motor.
653    pub motor: String,
654    /// Where the motor and its curve come from.
655    pub motor_source: String,
656    /// The digest the design file records for the motor's curve.
657    pub motor_digest: String,
658    /// ThrustCurve.org's id of the bundled curve file flown, the one that digest names.
659    pub curve_file: String,
660    /// The impulse flown, N s.
661    pub total_impulse_ns: f64,
662    /// Where the mass comes from.
663    pub mass_source: String,
664    /// The mass flown without the motor, kg.
665    pub mass_without_motor_kg: f64,
666    /// The mass flown at liftoff, kg.
667    pub liftoff_mass_kg: f64,
668    /// Where the site, rod, wind and air come from.
669    pub conditions_source: String,
670    /// The site's latitude, degrees north.
671    pub latitude_deg: f64,
672    /// The site's longitude, degrees east.
673    pub longitude_deg: f64,
674    /// The site's elevation above sea level, m.
675    pub elevation_m: f64,
676    /// The rod's length, m.
677    pub rail_length_m: f64,
678    /// The rod's inclination from the horizontal, degrees.
679    pub rail_inclination_deg: f64,
680    /// The rod's heading from north, degrees.
681    pub rail_heading_deg: f64,
682    /// The steady wind's speed, m/s.
683    pub wind_speed_m_s: f64,
684    /// The bearing it blows from, degrees from north.
685    pub wind_from_deg: f64,
686    /// The air.
687    pub atmosphere: String,
688    /// The log the rule is applied to, from the repository root.
689    pub reference_log: String,
690    /// That log's SHA-256: its bytes hashed, never parsed.
691    pub reference_log_sha256: String,
692    /// The apogee rule.
693    pub reference_rule: String,
694    /// What the log's height is taken to be.
695    pub altimeter: String,
696    /// Where that comes from.
697    pub altimeter_evidence: String,
698    /// Whether every input is traced to the record.
699    pub all_inputs_traced: bool,
700    /// What isn't, in words.
701    pub untraced: Vec<String>,
702    /// What the reader warned of in the design file and the flown motor, each with its place.
703    pub reader_warnings: Vec<String>,
704    /// The predicted apogee as the log's altimeter would read it, m: the counted prediction.
705    pub predicted_apogee_m: f64,
706    /// The predicted apogee as a height above the pad, m.
707    pub predicted_height_apogee_m: f64,
708    /// The predicted time from ignition to apogee, s.
709    pub predicted_time_to_apogee_s: f64,
710    /// The flight's largest Mach number.
711    pub hpr_max_mach: f64,
712    /// The apogee OpenRocket's own run of this simulation reached, as the design file stores
713    /// it, m: another simulator's number, not a measurement. Shown, and never counted.
714    pub openrocket_stored_apogee_m: f64,
715    /// Every file read, with its SHA-256; the log's is its bytes' alone.
716    pub files: Vec<FileRead>,
717    /// The SHA-256 of the flight's entry in [`DESIGN_FILE_FLIGHTS`].
718    pub inputs_sha256: String,
719    /// What else a reader should know.
720    pub note: String,
721}
722
723/// The weather file's conversion, as [`CONVERSION_RECORD`] holds it.
724#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
725pub struct WeatherConversion {
726    /// The record's path.
727    pub record: String,
728    /// The conversion, as code.
729    pub conversion: String,
730    /// The netCDF-4 file, from the repository root.
731    pub source: String,
732    /// Its SHA-256.
733    pub source_sha256: String,
734    /// The converted file flown, from the repository root.
735    pub converted: String,
736    /// Its SHA-256.
737    pub converted_sha256: String,
738}
739
740/// The predictions.
741#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
742pub struct PredictionsReport {
743    /// What wrote it.
744    pub generator: String,
745    /// What "traced" means.
746    pub traced_rule: String,
747    /// The EuRoC 2022 weather file's conversion.
748    pub weather_conversion: WeatherConversion,
749    /// The flights, in [`NEW_FLIGHTS`]' order.
750    pub flights: Vec<PredictionRow>,
751    /// What "traced" means for a flight read from a design file.
752    pub design_file_traced_rule: String,
753    /// The flights read from a design file, in [`DESIGN_FILE_FLIGHTS`]' order.
754    pub design_file_flights: Vec<DesignFilePredictionRow>,
755}
756
757/// What one flight of a rocket gave.
758struct Flown {
759    apogee_m: f64,
760    height_apogee_m: f64,
761    time_to_apogee_s: f64,
762    max_mach: f64,
763    total_impulse_ns: f64,
764    liftoff_mass_kg: f64,
765    /// The motors' mass at liftoff, kg: each one's case and propellant.
766    motor_mass_kg: f64,
767    /// Whether the design has two or more guides at different stations.
768    two_guides: bool,
769}
770
771/// Reads [`CONVERSION_RECORD`].
772fn conversion(root: &Path) -> Result<WeatherConversion, RealFlightError> {
773    let input = |what: String| RealFlightError::Input {
774        flight: "the EuRoC 2022 weather".to_owned(),
775        what,
776    };
777    let bytes = read_bytes(root, CONVERSION_RECORD, "reading the conversion's record")?;
778    let record: Value = serde_json::from_slice(&bytes)
779        .map_err(|error| input(format!("{CONVERSION_RECORD}: {error}")))?;
780    let text = |pointer: &str| -> Result<String, RealFlightError> {
781        record
782            .pointer(pointer)
783            .and_then(Value::as_str)
784            .map(str::to_owned)
785            .ok_or_else(|| input(format!("{CONVERSION_RECORD} has no {pointer}")))
786    };
787    Ok(WeatherConversion {
788        record: CONVERSION_RECORD.to_owned(),
789        conversion: text("/conversion")?,
790        source: text("/source/path")?,
791        source_sha256: text("/source/sha256")?,
792        converted: text("/converted/path")?,
793        converted_sha256: text("/converted/sha256")?,
794    })
795}
796
797/// How far HPR Sim's reading of a level may sit from RocketPy's, relative (to 1 for a value under
798/// 1): the two do the same arithmetic on the same stored numbers, and this leaves room for its
799/// order, as `hpr_io`'s own comparison on the committed extracts does.
800const LEVELS_WITHIN: f64 = 1e-12;
801
802/// Holds HPR Sim's reading of the converted weather file, at a flight's site and hour, to the
803/// levels RocketPy read from it, which [`CONVERSION_RECORD`] keeps: the same pressures, and the
804/// temperature, both wind components and the geopotential height within [`LEVELS_WITHIN`].
805///
806/// RocketPy records a geometric height `h = R Z/(R − Z)` for its Earth radius `R`; it is turned
807/// back into the geopotential height `Z = R h/(R + h)` to compare with the file's own.
808///
809/// # Errors
810///
811/// [`RealFlightError::Input`] naming the first level that differs, or what the record lacks.
812fn levels_are_rocketpys(
813    root: &Path,
814    flight: &PredictedFlight,
815    weather: &WeatherConversion,
816    weather_bytes: &[u8],
817) -> Result<usize, RealFlightError> {
818    let input = |what: String| RealFlightError::Input {
819        flight: flight.id.to_owned(),
820        what,
821    };
822    let bytes = read_bytes(root, CONVERSION_RECORD, "reading the conversion's record")?;
823    let record: Value = serde_json::from_slice(&bytes)
824        .map_err(|error| input(format!("{CONVERSION_RECORD}: {error}")))?;
825    let lacks = || input(format!("{CONVERSION_RECORD} has no levels for this flight"));
826    let reading = record["rocketpy_readings"]
827        .as_array()
828        .and_then(|readings| readings.iter().find(|reading| reading["id"] == flight.id))
829        .ok_or_else(lacks)?;
830    let radius = reading["earth_radius_m"].as_f64().ok_or_else(lacks)?;
831    let theirs = reading["levels"].as_array().ok_or_else(lacks)?;
832    let file = NetCdf::parse(weather_bytes)
833        .map_err(|error| input(format!("{}: {error}", weather.converted)))?;
834    let (year, month, day, hour) = flight.utc;
835    let (latitude_deg, longitude_deg, _) = flight.site;
836    let time = UtcTime::from_civil(year, month, day, hour, 0, 0.0)
837        .map_err(|error| input(error.to_string()))?;
838    let profile = Era5Profile::read(
839        &file,
840        Era5Request {
841            latitude_deg,
842            longitude_deg,
843            time,
844        },
845    )
846    .map_err(|error| input(format!("{}: {error}", weather.converted)))?;
847    if profile.times.len() != 1 || profile.levels.len() != theirs.len() || theirs.is_empty() {
848        return Err(input(format!(
849            "{}: HPR Sim reads {} levels at {} times, and RocketPy read {} at one",
850            weather.converted,
851            profile.levels.len(),
852            profile.times.len(),
853            theirs.len()
854        )));
855    }
856    // RocketPy sorts by height and HPR Sim by pressure; both are lowest first.
857    for (ours, theirs) in profile.levels.iter().zip(theirs) {
858        let number = |key: &str| theirs[key].as_f64().ok_or_else(lacks);
859        let pressure_pa = number("pressure_pa")?;
860        let height_m = number("height_m")?;
861        let pairs = [
862            ("pressure", ours.pressure_pa, pressure_pa, 0.0),
863            (
864                "temperature",
865                ours.temperature_k,
866                number("temperature_k")?,
867                LEVELS_WITHIN,
868            ),
869            (
870                "east wind",
871                ours.wind_east_m_s,
872                number("wind_east_m_s")?,
873                LEVELS_WITHIN,
874            ),
875            (
876                "north wind",
877                ours.wind_north_m_s,
878                number("wind_north_m_s")?,
879                LEVELS_WITHIN,
880            ),
881            (
882                "geopotential height",
883                ours.geopotential_height_m,
884                radius * height_m / (radius + height_m),
885                LEVELS_WITHIN,
886            ),
887        ];
888        for (what, ours, theirs, within) in pairs {
889            // A NaN on either side is a difference too.
890            let gap = (ours - theirs).abs();
891            if gap.is_nan() || gap > within * theirs.abs().max(1.0) {
892                return Err(input(format!(
893                    "{}: at {pressure_pa} Pa HPR Sim reads a {what} of {ours}, and RocketPy \
894                     read {theirs}",
895                    weather.converted
896                )));
897            }
898        }
899    }
900    Ok(theirs.len())
901}
902
903/// Predicts one flight: flies it from its record and reads its apogee as its log's altimeter
904/// would. The log is hashed, never parsed.
905///
906/// # Errors
907///
908/// [`RealFlightError`] if a file is missing or doesn't read, the thrust file holds negative
909/// thrust, the converted weather file is not the committed conversion or doesn't read as the
910/// levels RocketPy read, or HPR Sim can't fly it.
911pub fn predict(
912    root: &Path,
913    flight: &PredictedFlight,
914    weather: &WeatherConversion,
915) -> Result<PredictionRow, RealFlightError> {
916    predict_with(root, flight, weather, None).map(|(row, _)| row)
917}
918
919/// A predicted flight's row, and whether its design has two or more guides at different
920/// stations.
921fn predict_with(
922    root: &Path,
923    flight: &PredictedFlight,
924    weather: &WeatherConversion,
925    variant: Option<Variant>,
926) -> Result<(PredictionRow, bool), RealFlightError> {
927    let input = |what: String| RealFlightError::Input {
928        flight: flight.id.to_owned(),
929        what,
930    };
931    let mut files = Vec::new();
932    let mut read = |relative: String, what: &'static str| -> Result<Vec<u8>, RealFlightError> {
933        let bytes = read_bytes(root, &relative, what)?;
934        files.push(FileRead {
935            sha256: sha256_hex(&bytes),
936            path: relative,
937        });
938        Ok(bytes)
939    };
940
941    // The design, with the example's own thrust and burn time from the fixture.
942    read(MASS_FIXTURE.to_owned(), "reading the design fixture")?;
943    let case = fixture_case_of(root, flight.id, flight.design)?;
944    let mass_without_motor_kg = case["rocket"]["mass"]
945        .as_f64()
946        .ok_or_else(|| input(format!("{MASS_FIXTURE} gives {} no mass", flight.design)))?;
947    let (thrust_path, burn, reshape) = example_thrust_of(root, flight.id, flight.design)?;
948    if reshape.is_some() {
949        return Err(input(
950            "the example reshapes its thrust file, which no prediction here expects".to_owned(),
951        ));
952    }
953    let thrust_bytes = read(thrust_path.clone(), "reading a thrust file")?;
954    let (curve, zeroed_ns) = parse_thrust(
955        flight.id,
956        &thrust_path,
957        &String::from_utf8_lossy(&thrust_bytes),
958        burn,
959        None,
960    )?;
961    // The seven's report records the impulse a zeroed negative thrust removes; this one has no
962    // place for it, so a file that holds one is refused, not flown changed.
963    if zeroed_ns != 0.0 {
964        return Err(input(format!(
965            "{thrust_path} holds negative thrust ({zeroed_ns} N s), which no prediction here \
966             expects"
967        )));
968    }
969    let design_path = format!("validation/designs/{}.json", flight.design);
970    let design_bytes = read(design_path.clone(), "reading a design")?;
971    let design: Value = serde_json::from_slice(&design_bytes)
972        .map_err(|error| input(format!("{design_path}: {error}")))?;
973    let rocket = rocket_with_curve(flight.id, &design, &design_path, &thrust_path, &curve)?;
974
975    // The weather: the converted file, only if it is the committed conversion.
976    let weather_bytes = read(
977        weather.converted.clone(),
978        "reading the converted ERA5 file, which validation/oracles/netcdf/euroc_2022.py writes",
979    )?;
980    if sha256_hex(&weather_bytes) != weather.converted_sha256 {
981        return Err(input(format!(
982            "{} is not the conversion {CONVERSION_RECORD} records: run \
983             validation/oracles/netcdf/euroc_2022.py",
984            weather.converted
985        )));
986    }
987    // And only if HPR Sim reads from it, here and now, the levels RocketPy read.
988    levels_are_rocketpys(root, flight, weather, &weather_bytes)?;
989    let (environment, air) = launch_day_at(
990        flight.id,
991        flight.site,
992        flight.utc,
993        &weather.converted,
994        &weather_bytes,
995    )?;
996    let (latitude_deg, longitude_deg, elevation_m) = flight.site;
997    let rail = rail_from(flight.rail);
998
999    // The log: its bytes' SHA-256, and nothing else of it.
1000    let log_path = format!("{ROCKETPY}/data/rockets/{}", flight.reference.log);
1001    let log_sha256 = sha256_hex(&read(log_path.clone(), "hashing a flight log")?);
1002
1003    let launch = Launch {
1004        id: flight.id,
1005        configuration: "example",
1006        environment: &environment,
1007        air: &air,
1008        air_name: &weather.converted,
1009        elevation_m,
1010        rail,
1011        altimeter: flight.reference.altimeter,
1012        variant,
1013    };
1014    let fly_once = |rocket: &Rocket| flown_to_apogee(rocket, &launch);
1015    let counted = fly_once(&rocket)?;
1016    // The design as committed, on its own bundled catalog curve: shown, never counted.
1017    let catalog_curve = match flight.catalog_curve {
1018        Some(catalog) => {
1019            let as_committed: Rocket = serde_json::from_value(design.clone())
1020                .map_err(|error| input(format!("{design_path}: {error}")))?;
1021            let flown = fly_once(&as_committed)?;
1022            Some(CatalogCurveRow {
1023                motor: catalog.motor.to_owned(),
1024                why: catalog.why.to_owned(),
1025                total_impulse_ns: flown.total_impulse_ns,
1026                liftoff_mass_kg: flown.liftoff_mass_kg,
1027                predicted_apogee_m: flown.apogee_m,
1028                predicted_height_apogee_m: flown.height_apogee_m,
1029            })
1030        }
1031        None => None,
1032    };
1033    let (year, month, day, hour) = flight.utc;
1034    let (rail_length_m, rail_inclination_deg, rail_heading_deg) = flight.rail;
1035
1036    let row = PredictionRow {
1037        id: flight.id.to_owned(),
1038        title: flight.title.to_owned(),
1039        design: flight.design.to_owned(),
1040        source: flight.source.to_owned(),
1041        motor: flight.motor.to_owned(),
1042        motor_source: flight.motor_source.to_owned(),
1043        thrust_file: thrust_path,
1044        burn_time_s: burn,
1045        total_impulse_ns: counted.total_impulse_ns,
1046        mass_source: flight.mass_source.to_owned(),
1047        mass_without_motor_kg,
1048        liftoff_mass_kg: counted.liftoff_mass_kg,
1049        latitude_deg,
1050        longitude_deg,
1051        elevation_m,
1052        rail_length_m,
1053        rail_inclination_deg,
1054        rail_heading_deg,
1055        weather_time_utc: format!("{year:04}-{month:02}-{day:02}T{hour:02}:00Z"),
1056        reference_log: log_path,
1057        reference_log_sha256: log_sha256,
1058        reference_rule: flight.reference.rule.to_owned(),
1059        altimeter: flight.reference.altimeter.kind().to_owned(),
1060        altimeter_evidence: flight.reference.altimeter.evidence().to_owned(),
1061        all_inputs_traced: flight.untraced.is_empty(),
1062        untraced: flight
1063            .untraced
1064            .iter()
1065            .map(|&what| what.to_owned())
1066            .collect(),
1067        predicted_apogee_m: counted.apogee_m,
1068        predicted_height_apogee_m: counted.height_apogee_m,
1069        predicted_time_to_apogee_s: counted.time_to_apogee_s,
1070        hpr_max_mach: counted.max_mach,
1071        catalog_curve,
1072        files,
1073        inputs_sha256: sha256_hex(format!("{flight:?}").as_bytes()),
1074        note: flight.note.to_owned(),
1075    };
1076    Ok((row, counted.two_guides))
1077}
1078
1079/// What flying a rocket to its apogee needs beside the rocket.
1080struct Launch<'a> {
1081    /// The flight's id, for an error.
1082    id: &'a str,
1083    /// The motor configuration, by id.
1084    configuration: &'a str,
1085    /// The site, its air and its wind.
1086    environment: &'a Environment,
1087    /// The air a barometer reads, the environment's own.
1088    air: &'a dyn hpr_atmos::Atmosphere,
1089    /// What the air is called in an error.
1090    air_name: &'a str,
1091    /// The site's elevation above sea level, m.
1092    elevation_m: f64,
1093    /// The rail.
1094    rail: Rail,
1095    /// What the log's height is taken to be.
1096    altimeter: Altimeter,
1097    /// A variant flown on the flight, or none: the flight as predicted.
1098    variant: Option<Variant>,
1099}
1100
1101/// Flies `rocket` to its apogee and reads it as the log's altimeter would.
1102fn flown_to_apogee(rocket: &Rocket, launch: &Launch<'_>) -> Result<Flown, RealFlightError> {
1103    let input = |what: String| RealFlightError::Input {
1104        flight: launch.id.to_owned(),
1105        what,
1106    };
1107    let sim = |source: hpr_sim::SimError| RealFlightError::Sim {
1108        flight: launch.id.to_owned(),
1109        source,
1110    };
1111    let settings = FlightSettings {
1112        max_time_s: MAX_TIME_S,
1113        ..FlightSettings::default()
1114    };
1115    let corrected = match launch.variant {
1116        Some(variant) => variant
1117            .rocket(rocket)
1118            .map_err(|error| input(error.to_string()))?,
1119        None => None,
1120    };
1121    let rocket = corrected.as_ref().unwrap_or(rocket);
1122    let simulation = Simulation::new(
1123        rocket,
1124        launch.configuration,
1125        match launch.variant {
1126            Some(variant) => variant.environment(launch.environment.clone()),
1127            None => launch.environment.clone(),
1128        },
1129        launch.rail,
1130        settings,
1131    )
1132    .map_err(sim)?;
1133    let simulation = match launch.variant {
1134        Some(variant) => variant.simulation(simulation).map_err(sim)?,
1135        None => simulation,
1136    };
1137    let two_guides = simulation.guides().next_guide_station_m.is_some();
1138    let motors = &simulation.assembly().motors;
1139    let total_impulse_ns = motors
1140        .iter()
1141        .map(|motor| motor.mounted.motor.curve().total_impulse_ns())
1142        .sum();
1143    let motor_mass_kg = motors
1144        .iter()
1145        .map(|motor| {
1146            let motor = &motor.mounted.motor;
1147            motor.dry().mass_kg + motor.propellant_initial_mass_kg()
1148        })
1149        .sum();
1150    let liftoff_mass_kg = simulation.assembly().mass_properties(0.0).mass_kg;
1151    let mut heights = Heights {
1152        next: 0,
1153        rows: Vec::new(),
1154    };
1155    let mut metrics = FlightMetrics::new();
1156    let result = simulation
1157        .run(&mut (&mut heights, &mut metrics))
1158        .map_err(sim)?;
1159    let max_mach = metrics
1160        .summary(&result, launch.environment)
1161        .map_err(sim)?
1162        .max_mach
1163        .ok_or_else(|| input("the flight has no Mach number".to_owned()))?
1164        .value;
1165    let apogee = result
1166        .event(EventKind::Apogee)
1167        .ok_or_else(|| input("the flight has no apogee".to_owned()))?
1168        .sample;
1169    let start_m = heights
1170        .rows
1171        .first()
1172        .map(|row| row.1)
1173        .ok_or_else(|| input("the flight has no steps".to_owned()))?;
1174    // What the log's altimeter would read at the apogee, above its start.
1175    let atmos = |error: hpr_atmos::AtmosError| input(format!("{}: {error}", launch.air_name));
1176    let apogee_m = match launch.altimeter {
1177        Altimeter::Height(_) => apogee.height_above_ground_m - start_m,
1178        Altimeter::Barometric(_) | Altimeter::AssumedBarometric(_) => {
1179            Barometer::on_pad(launch.air, launch.elevation_m, start_m)
1180                .map_err(atmos)?
1181                .reading_m(apogee.height_above_ground_m)
1182                .map_err(atmos)?
1183        }
1184    };
1185    Ok(Flown {
1186        apogee_m,
1187        height_apogee_m: apogee.height_above_ground_m - start_m,
1188        time_to_apogee_s: apogee.time_s,
1189        max_mach,
1190        total_impulse_ns,
1191        liftoff_mass_kg,
1192        motor_mass_kg,
1193        two_guides,
1194    })
1195}
1196
1197/// The air a design-file flight is flown in, as the report names it.
1198const STANDARD_AIR: &str = "the 1976 US Standard Atmosphere, for the stored simulation's `isa`";
1199
1200/// What a design file's stored simulation states for a flight: its motor configuration, its
1201/// launch conditions and its one motor's curve.
1202#[derive(Debug, Clone, Copy, PartialEq)]
1203pub(crate) struct StoredLaunch<'a> {
1204    /// The motor configuration's id.
1205    pub(crate) configuration_id: &'a str,
1206    /// The launch rod's length, m.
1207    pub(crate) rod_length_m: f64,
1208    /// The rod's angle from the vertical, rad.
1209    pub(crate) rod_angle_rad: f64,
1210    /// The compass direction the rod leans toward, rad.
1211    pub(crate) rod_direction_rad: f64,
1212    /// The steady wind's speed, m/s.
1213    pub(crate) wind_speed_m_s: f64,
1214    /// The compass direction the wind blows from, rad.
1215    pub(crate) wind_from_rad: f64,
1216    /// The launch site's height above sea level, m.
1217    pub(crate) elevation_m: f64,
1218    /// The launch site's latitude, degrees north.
1219    pub(crate) latitude_deg: f64,
1220    /// The launch site's longitude, degrees east.
1221    pub(crate) longitude_deg: f64,
1222    /// The apogee OpenRocket stored for its own run, m above the site.
1223    pub(crate) openrocket_stored_apogee_m: f64,
1224    /// The configuration's one motor.
1225    pub(crate) motor: &'a ork::OrkMotor,
1226    /// The digest the file gives the motor.
1227    pub(crate) motor_digest: &'a str,
1228    /// The bundled curve file that digest names.
1229    pub(crate) simfile_id: &'a str,
1230}
1231
1232/// Read the stored simulation named `simulation` out of `design`, refusing whatever the
1233/// prediction would otherwise have to choose ([ADR-337][adr-337] §2 and §3).
1234///
1235/// It refuses unless the design holds one simulation of that name, the simulation states its
1236/// configuration, rod, wind, site and its own apogee, it ran in the standard atmosphere and in
1237/// OpenRocket's average wind, the configuration is one the reader flies, with one motor and no
1238/// staging, and that motor's digest names, in the committed table
1239/// ([`hpr_motor::openrocket_curves`]), the bundled curve file the reader chose.
1240///
1241/// # Errors
1242///
1243/// A sentence naming what the stored simulation lacks; `design_path` names the file in it.
1244///
1245/// [adr-337]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0337-the-macie-xl-predictions-each-flight-s-stored-simulation-flown-as-saved.md
1246pub(crate) fn stored_launch<'a>(
1247    design: &'a ork::Design,
1248    simulation: &str,
1249    design_path: &str,
1250) -> Result<StoredLaunch<'a>, String> {
1251    let named: Vec<_> = design
1252        .simulations
1253        .iter()
1254        .filter(|stored| stored.name == simulation)
1255        .collect();
1256    let [stored] = named.as_slice() else {
1257        return Err(format!(
1258            "{design_path} holds {} simulations named `{}`",
1259            named.len(),
1260            simulation
1261        ));
1262    };
1263    let unstated = |what: &str| format!("the stored simulation `{}` states no {what}", simulation);
1264    let conditions = stored
1265        .conditions
1266        .as_ref()
1267        .ok_or_else(|| unstated("launch conditions"))?;
1268    let configuration_id = conditions
1269        .configuration
1270        .as_deref()
1271        .ok_or_else(|| unstated("motor configuration"))?;
1272    let rod_length_m = conditions
1273        .rod_length_m
1274        .ok_or_else(|| unstated("rod length"))?;
1275    let rod_angle_rad = conditions
1276        .rod_angle_rad
1277        .ok_or_else(|| unstated("rod angle"))?;
1278    let rod_direction_rad = conditions
1279        .rod_direction_rad
1280        .ok_or_else(|| unstated("rod direction"))?;
1281    let wind_speed_m_s = conditions
1282        .wind_speed_m_s
1283        .ok_or_else(|| unstated("wind speed"))?;
1284    let wind_from_rad = conditions
1285        .wind_from_rad
1286        .ok_or_else(|| unstated("wind direction"))?;
1287    let elevation_m = conditions
1288        .launch_altitude_m
1289        .ok_or_else(|| unstated("launch altitude"))?;
1290    let latitude_deg = conditions
1291        .latitude_deg
1292        .ok_or_else(|| unstated("latitude"))?;
1293    let longitude_deg = conditions
1294        .longitude_deg
1295        .ok_or_else(|| unstated("longitude"))?;
1296    if !matches!(conditions.atmosphere, Some(ork::Atmosphere::Isa {})) {
1297        return Err(format!(
1298            "the stored simulation `{}` was not run in the standard atmosphere",
1299            simulation
1300        ));
1301    }
1302    if !conditions
1303        .wind_model
1304        .as_deref()
1305        .is_some_and(|model| model.eq_ignore_ascii_case("average"))
1306    {
1307        return Err(format!(
1308            "the stored simulation `{}` was not run in an average wind",
1309            simulation
1310        ));
1311    }
1312    let openrocket_stored_apogee_m = stored
1313        .results
1314        .as_ref()
1315        .and_then(|results| results.max_altitude_m)
1316        .ok_or_else(|| unstated("apogee of OpenRocket's own run"))?;
1317
1318    // Its configuration: one motor, lit at launch, on the bundled curve the file's digest names.
1319    let configuration = design
1320        .motors
1321        .configurations
1322        .iter()
1323        .find(|configuration| configuration.id == configuration_id)
1324        .ok_or_else(|| format!("{design_path} has no motor configuration `{configuration_id}`"))?;
1325    if let Some(left_out) = &configuration.left_out {
1326        return Err(format!(
1327            "the configuration of `{}` is not flown: {}",
1328            simulation, left_out.message
1329        ));
1330    }
1331    if configuration.stagings().next().is_some() {
1332        return Err(format!(
1333            "the configuration of `{}` stages, which no prediction here expects",
1334            simulation
1335        ));
1336    }
1337    let [motor] = configuration.motors.as_slice() else {
1338        return Err(format!(
1339            "the configuration of `{}` flies {} motors, not one",
1340            simulation,
1341            configuration.motors.len()
1342        ));
1343    };
1344    let (Some(motor_digest), ork::Curve::Catalog { simfile_id, .. }) =
1345        (&motor.digest, &motor.curve)
1346    else {
1347        return Err(format!(
1348            "{} is not flown on a bundled curve named by a digest",
1349            motor.designation
1350        ));
1351    };
1352    if hpr_motor::openrocket_curves::file_for(motor_digest).as_deref() != Some(simfile_id.as_str())
1353    {
1354        return Err(format!(
1355            "{}: the bundled curve file {simfile_id} is not the one the design's digest \
1356             {motor_digest} names",
1357            motor.designation
1358        ));
1359    }
1360    Ok(StoredLaunch {
1361        configuration_id,
1362        rod_length_m,
1363        rod_angle_rad,
1364        rod_direction_rad,
1365        wind_speed_m_s,
1366        wind_from_rad,
1367        elevation_m,
1368        latitude_deg,
1369        longitude_deg,
1370        openrocket_stored_apogee_m,
1371        motor,
1372        motor_digest,
1373        simfile_id,
1374    })
1375}
1376
1377/// Predicts one design-file flight: flies the stored simulation the repository names for it,
1378/// from the design file as saved, and reads its apogee as its log's altimeter would. The log is
1379/// hashed, never parsed.
1380///
1381/// # Errors
1382///
1383/// [`RealFlightError`] if a file is missing or doesn't read; the design holds a part HPR Sim
1384/// doesn't read; the stored simulation is missing, named twice, or lacks a condition; it was
1385/// run in other than the standard atmosphere and an average wind; its configuration is left
1386/// out, stages, or flies other than one motor on the bundled curve its digest names; or HPR Sim
1387/// can't fly it.
1388pub fn predict_design_file(
1389    root: &Path,
1390    flight: &DesignFileFlight,
1391) -> Result<DesignFilePredictionRow, RealFlightError> {
1392    predict_design_file_with(root, flight, None).map(|(row, _)| row)
1393}
1394
1395/// A design-file flight's row, and whether its design has two or more guides at different
1396/// stations.
1397fn predict_design_file_with(
1398    root: &Path,
1399    flight: &DesignFileFlight,
1400    variant: Option<Variant>,
1401) -> Result<(DesignFilePredictionRow, bool), RealFlightError> {
1402    let input = |what: String| RealFlightError::Input {
1403        flight: flight.id.to_owned(),
1404        what,
1405    };
1406    let sim = |source: hpr_sim::SimError| RealFlightError::Sim {
1407        flight: flight.id.to_owned(),
1408        source,
1409    };
1410    let mut files = Vec::new();
1411    let mut read = |relative: String, what: &'static str| -> Result<Vec<u8>, RealFlightError> {
1412        let bytes = read_bytes(root, &relative, what)?;
1413        files.push(FileRead {
1414            sha256: sha256_hex(&bytes),
1415            path: relative,
1416        });
1417        Ok(bytes)
1418    };
1419
1420    // The design, whole, as OpenRocket saved it.
1421    let design_path = format!("{}/{}", flight.repository.dest, flight.design);
1422    let design_bytes = read(
1423        design_path.clone(),
1424        "reading a design file, which `cargo xtask refs fetch rocketry-files` fetches,",
1425    )?;
1426    let file =
1427        ork::read(&design_bytes).map_err(|error| input(format!("{design_path}: {error}")))?;
1428    let design = ork::design(&file.value);
1429    if design.value.is_reduced() {
1430        return Err(input(format!(
1431            "{design_path} holds a part HPR Sim doesn't read, so it is not flown as saved"
1432        )));
1433    }
1434
1435    // The stored simulation the repository names for the flight: its configuration and its
1436    // launch conditions, each one stated, and its one motor on the curve its digest names.
1437    let StoredLaunch {
1438        configuration_id,
1439        rod_length_m,
1440        rod_angle_rad,
1441        rod_direction_rad,
1442        wind_speed_m_s,
1443        wind_from_rad,
1444        elevation_m,
1445        latitude_deg,
1446        longitude_deg,
1447        openrocket_stored_apogee_m,
1448        motor,
1449        motor_digest,
1450        simfile_id,
1451    } = stored_launch(&design.value, flight.simulation, &design_path).map_err(input)?;
1452    // The reader's warnings, less those about another configuration's motor.
1453    let others: Vec<&str> = design
1454        .value
1455        .motors
1456        .configurations
1457        .iter()
1458        .flat_map(|other| &other.motors)
1459        .map(|other| other.designation.as_str())
1460        .filter(|designation| !designation.is_empty() && *designation != motor.designation)
1461        .collect();
1462    let reader_warnings: Vec<String> = file
1463        .warnings
1464        .iter()
1465        .chain(&design.warnings)
1466        .filter(|warning| {
1467            warning.message.contains(motor.designation.as_str())
1468                || !others.iter().any(|other| warning.message.contains(other))
1469        })
1470        .map(|warning| format!("{}: {}", warning.at, warning.message))
1471        .collect();
1472
1473    // The site, the steady wind and the standard air of the stored simulation.
1474    let site = Geodetic::from_degrees(latitude_deg, longitude_deg, elevation_m)
1475        .map_err(|error| sim(error.into()))?;
1476    let wind = ConstantWind::new(wind_speed_m_s, wind_from_rad)
1477        .map_err(|error| input(format!("the stored wind: {error}")))?;
1478    let environment = Environment::standard(site).map_err(sim)?.with_wind(wind);
1479    let rail = Rail {
1480        azimuth_rad: rod_direction_rad,
1481        elevation_rad: std::f64::consts::FRAC_PI_2 - rod_angle_rad,
1482        ..Rail::vertical(rod_length_m)
1483    };
1484
1485    // The log: its bytes' SHA-256, and nothing else of it.
1486    let log_path = format!("{}/{}", flight.repository.dest, flight.reference.log);
1487    let log_sha256 = sha256_hex(&read(log_path.clone(), "hashing a flight log")?);
1488
1489    let flown = flown_to_apogee(
1490        &design.value.rocket,
1491        &Launch {
1492            id: flight.id,
1493            configuration: configuration_id,
1494            environment: &environment,
1495            air: &*environment.atmosphere,
1496            air_name: "the standard atmosphere",
1497            elevation_m,
1498            rail,
1499            altimeter: flight.reference.altimeter,
1500            variant,
1501        },
1502    )?;
1503
1504    let row = DesignFilePredictionRow {
1505        id: flight.id.to_owned(),
1506        title: flight.title.to_owned(),
1507        repository: flight.repository.url.to_owned(),
1508        repository_commit: flight.repository.commit.to_owned(),
1509        repository_license: flight.repository.license.to_owned(),
1510        design_file_sha256: sha256_hex(&design_bytes),
1511        design_file: design_path,
1512        simulation: flight.simulation.to_owned(),
1513        configuration: configuration_id.to_owned(),
1514        source: flight.source.to_owned(),
1515        motor: flight.motor.to_owned(),
1516        motor_source: flight.motor_source.to_owned(),
1517        motor_digest: motor_digest.to_owned(),
1518        curve_file: simfile_id.to_owned(),
1519        total_impulse_ns: flown.total_impulse_ns,
1520        mass_source: flight.mass_source.to_owned(),
1521        mass_without_motor_kg: flown.liftoff_mass_kg - flown.motor_mass_kg,
1522        liftoff_mass_kg: flown.liftoff_mass_kg,
1523        conditions_source: flight.conditions_source.to_owned(),
1524        latitude_deg,
1525        longitude_deg,
1526        elevation_m,
1527        rail_length_m: rail.length_m,
1528        rail_inclination_deg: rail.elevation_rad.to_degrees(),
1529        rail_heading_deg: rail.azimuth_rad.to_degrees(),
1530        wind_speed_m_s,
1531        wind_from_deg: wind_from_rad.to_degrees(),
1532        atmosphere: STANDARD_AIR.to_owned(),
1533        reference_log: log_path,
1534        reference_log_sha256: log_sha256,
1535        reference_rule: flight.reference.rule.to_owned(),
1536        altimeter: flight.reference.altimeter.kind().to_owned(),
1537        altimeter_evidence: flight.reference.altimeter.evidence().to_owned(),
1538        all_inputs_traced: flight.untraced.is_empty(),
1539        untraced: flight
1540            .untraced
1541            .iter()
1542            .map(|&what| what.to_owned())
1543            .collect(),
1544        reader_warnings,
1545        predicted_apogee_m: flown.apogee_m,
1546        predicted_height_apogee_m: flown.height_apogee_m,
1547        predicted_time_to_apogee_s: flown.time_to_apogee_s,
1548        hpr_max_mach: flown.max_mach,
1549        openrocket_stored_apogee_m,
1550        files,
1551        inputs_sha256: sha256_hex(format!("{flight:?}").as_bytes()),
1552        note: flight.note.to_owned(),
1553    };
1554    Ok((row, flown.two_guides))
1555}
1556
1557/// Predicts every flight in [`NEW_FLIGHTS`], then every one in [`DESIGN_FILE_FLIGHTS`].
1558///
1559/// # Errors
1560///
1561/// The first flight's [`RealFlightError`].
1562pub fn run(root: &Path) -> Result<PredictionsReport, RealFlightError> {
1563    run_with(root, None)
1564}
1565
1566/// One predicted flight's id and its corrected apogee, m, or why it didn't fly.
1567pub type CorrectedApogee = (String, Result<f64, RealFlightError>);
1568
1569/// Each predicted flight's apogee with `correction` flown, by its id: every motor's impulse and the
1570/// drag scaled ([`Correction`]), the rest as [`run`] flies it, each flight's result on its own (a
1571/// flight that fails to fly fails alone). Each is the predicted apogee as the log's altimeter
1572/// would read it, m.
1573///
1574/// # Errors
1575///
1576/// The committed weather conversion that doesn't hold: no flight is flown then.
1577pub fn corrected_apogees(
1578    root: &Path,
1579    correction: Correction,
1580) -> Result<Vec<CorrectedApogee>, RealFlightError> {
1581    Ok(varied_apogees(root, Variant::corrected(correction))?
1582        .into_iter()
1583        .map(|(id, varied)| (id, varied.map(|varied| varied.apogee_m)))
1584        .collect())
1585}
1586
1587/// One predicted flight's id and its flight as a [`Variant`], or why it didn't fly.
1588pub type VariedApogee = (String, Result<Varied, RealFlightError>);
1589
1590/// Each predicted flight flown as `variant`, by its id, as [`corrected_apogees`] flies a
1591/// correction: its predicted apogee as the log's altimeter would read it, m, and whether its
1592/// design has two guides at different stations. With [`Variant::GUIDED`] each is the
1593/// prediction [`run`] makes.
1594///
1595/// # Errors
1596///
1597/// As [`corrected_apogees`].
1598pub fn varied_apogees(root: &Path, variant: Variant) -> Result<Vec<VariedApogee>, RealFlightError> {
1599    let weather_conversion = checked_conversion(root)?;
1600    let variant = Some(variant);
1601    let varied = |apogee_m: f64, two_guides: bool| Varied {
1602        apogee_m,
1603        two_guides,
1604    };
1605    Ok(NEW_FLIGHTS
1606        .iter()
1607        .map(|flight| {
1608            let apogee = predict_with(root, flight, &weather_conversion, variant)
1609                .map(|(row, two)| varied(row.predicted_apogee_m, two));
1610            (flight.id.to_owned(), apogee)
1611        })
1612        .chain(DESIGN_FILE_FLIGHTS.iter().map(|flight| {
1613            let apogee = predict_design_file_with(root, flight, variant)
1614                .map(|(row, two)| varied(row.predicted_apogee_m, two));
1615            (flight.id.to_owned(), apogee)
1616        }))
1617        .collect())
1618}
1619
1620/// The committed weather conversion, once the file it was made from is the one in the checkout.
1621fn checked_conversion(root: &Path) -> Result<WeatherConversion, RealFlightError> {
1622    let weather_conversion = conversion(root)?;
1623    // The file the conversion was made from is the one in the checkout.
1624    let source = read_bytes(
1625        root,
1626        &weather_conversion.source,
1627        "reading RocketPy's EuRoC 2022 ERA5 file",
1628    )?;
1629    if sha256_hex(&source) != weather_conversion.source_sha256 {
1630        return Err(RealFlightError::Input {
1631            flight: "the EuRoC 2022 weather".to_owned(),
1632            what: format!(
1633                "{} is not the file {CONVERSION_RECORD} was made from: fetch it again with \
1634                 `cargo xtask refs fetch rocketpy`",
1635                weather_conversion.source
1636            ),
1637        });
1638    }
1639    Ok(weather_conversion)
1640}
1641
1642fn run_with(root: &Path, variant: Option<Variant>) -> Result<PredictionsReport, RealFlightError> {
1643    let weather_conversion = checked_conversion(root)?;
1644    let flights = NEW_FLIGHTS
1645        .iter()
1646        .map(|flight| predict_with(root, flight, &weather_conversion, variant).map(|(row, _)| row))
1647        .collect::<Result<Vec<_>, _>>()?;
1648    let design_file_flights = DESIGN_FILE_FLIGHTS
1649        .iter()
1650        .map(|flight| predict_design_file_with(root, flight, variant).map(|(row, _)| row))
1651        .collect::<Result<Vec<_>, _>>()?;
1652    Ok(PredictionsReport {
1653        generator: "cargo xtask public-predictions".to_owned(),
1654        traced_rule: TRACED_RULE.to_owned(),
1655        weather_conversion,
1656        flights,
1657        design_file_traced_rule: DESIGN_FILE_TRACED_RULE.to_owned(),
1658        design_file_flights,
1659    })
1660}
1661
1662/// Whether the prediction of the flight `id` is the one first merged ([`MERGED`]), to the digit
1663/// the page prints, or the one its revision gives ([`REVISIONS`]): its apogee as a reading and
1664/// as a height, and its catalog curve's where it has one. Returns the revision it was held to,
1665/// if any.
1666pub(crate) fn held_to_merged(
1667    id: &str,
1668    apogee_m: f64,
1669    height_apogee_m: f64,
1670    catalog_apogee_m: Option<f64>,
1671) -> Result<Option<&'static Revision>, String> {
1672    held_to(
1673        &MERGED,
1674        &REVISIONS,
1675        id,
1676        apogee_m,
1677        height_apogee_m,
1678        catalog_apogee_m,
1679    )
1680}
1681
1682/// [`held_to_merged`] against the lists given: a flown prediction passes when it is `merged`'s
1683/// number for `id`, or when `revisions` holds exactly one entry for `id`, with a reason, that
1684/// differs from the merged number and gives the flown one.
1685///
1686/// A revision that the flight no longer needs fails too, so that a stale entry can't keep a
1687/// reason on the page for a number that is the merged one again.
1688pub(crate) fn held_to<'a>(
1689    merged: &[MergedPrediction],
1690    revisions: &'a [Revision],
1691    id: &str,
1692    apogee_m: f64,
1693    height_apogee_m: f64,
1694    catalog_apogee_m: Option<f64>,
1695) -> Result<Option<&'a Revision>, String> {
1696    // A revision is of a merged prediction: an entry under any other id would revise nothing
1697    // and still be printed.
1698    if let Some(stray) = revisions
1699        .iter()
1700        .find(|revision| !merged.iter().any(|merged| merged.id == revision.id))
1701    {
1702        return Err(format!(
1703            "a revision names `{}`, which has no merged prediction",
1704            stray.id
1705        ));
1706    }
1707    let merged = merged
1708        .iter()
1709        .find(|merged| merged.id == id)
1710        .ok_or_else(|| format!("{id}: it has no merged prediction to be held to"))?;
1711    if merged.catalog_apogee_m.is_some() != catalog_apogee_m.is_some() {
1712        return Err(format!(
1713            "{id}: its catalog curve is not its merged prediction's"
1714        ));
1715    }
1716    let mut entries = revisions.iter().filter(|revision| revision.id == id);
1717    let revision = entries.next();
1718    if entries.next().is_some() {
1719        return Err(format!(
1720            "{id}: it is revised twice: one entry keeps the merged number and the one flown now"
1721        ));
1722    }
1723    // What the flown numbers are held to, and what each differs from the merged one by.
1724    // A gap that isn't a number differs too.
1725    let differs = |now: Option<f64>, first: Option<f64>| match (now, first) {
1726        (Some(now), Some(first)) => {
1727            let gap_m = (now - first).abs();
1728            gap_m.is_nan() || gap_m > MERGED_WITHIN_M
1729        }
1730        _ => false,
1731    };
1732    let flown = [
1733        ("predicted apogee", Some(apogee_m), Some(merged.apogee_m)),
1734        (
1735            "predicted apogee as a height",
1736            Some(height_apogee_m),
1737            Some(merged.height_apogee_m),
1738        ),
1739        (
1740            "catalog curve's apogee",
1741            catalog_apogee_m,
1742            merged.catalog_apogee_m,
1743        ),
1744    ];
1745    let Some(revision) = revision else {
1746        for (what, now, first) in flown {
1747            if let (Some(now), Some(first)) = (now, first)
1748                && differs(Some(now), Some(first))
1749            {
1750                return Err(format!(
1751                    "{id}: its {what} is {now} m, and its merged prediction is {first} m: a \
1752                     merged prediction is not changed, it is revised beside the old one, with \
1753                     the reason, in `REVISIONS` (ADR-328 §1b)"
1754                ));
1755            }
1756        }
1757        return Ok(None);
1758    };
1759    if revision.because.trim().is_empty() {
1760        return Err(format!("{id}: its revision gives no reason"));
1761    }
1762    if revision.catalog_apogee_m.is_some() != merged.catalog_apogee_m.is_some() {
1763        return Err(format!(
1764            "{id}: its revision's catalog curve is not its merged prediction's"
1765        ));
1766    }
1767    let revised = [
1768        (Some(revision.apogee_m), Some(merged.apogee_m)),
1769        (Some(revision.height_apogee_m), Some(merged.height_apogee_m)),
1770        (revision.catalog_apogee_m, merged.catalog_apogee_m),
1771    ];
1772    if !revised.iter().any(|(now, first)| differs(*now, *first)) {
1773        return Err(format!(
1774            "{id}: its revision changes nothing: it gives the merged numbers"
1775        ));
1776    }
1777    let held = [
1778        ("predicted apogee", Some(apogee_m), Some(revision.apogee_m)),
1779        (
1780            "predicted apogee as a height",
1781            Some(height_apogee_m),
1782            Some(revision.height_apogee_m),
1783        ),
1784        (
1785            "catalog curve's apogee",
1786            catalog_apogee_m,
1787            revision.catalog_apogee_m,
1788        ),
1789    ];
1790    for (what, now, stated) in held {
1791        if let (Some(now), Some(stated)) = (now, stated)
1792            && differs(Some(now), Some(stated))
1793        {
1794            return Err(format!(
1795                "{id}: its {what} is {now} m, and its revision says {stated} m: a revision \
1796                 states the number flown now"
1797            ));
1798        }
1799    }
1800    Ok(Some(revision))
1801}
1802
1803/// The page's section on the predictions revised since they were merged: each one's merged
1804/// number beside the one flown now, with the reason. Empty when `revisions` is.
1805pub(crate) fn revisions_section(merged: &[MergedPrediction], revisions: &[Revision]) -> String {
1806    if revisions.is_empty() {
1807        return String::new();
1808    }
1809    let mut out = String::from(
1810        "## Revised since merging\n\n\
1811         A merged prediction is never edited. Each of these changed, and is kept beside the \
1812         number first merged; the real-flights report gives both errors.\n\n",
1813    );
1814    for revision in revisions {
1815        let first = merged
1816            .iter()
1817            .find(|merged| merged.id == revision.id)
1818            .map_or_else(
1819                || "no merged prediction".to_owned(),
1820                |merged| format!("{} m", fmt_number(merged.apogee_m, 1)),
1821            );
1822        let _ = writeln!(
1823            out,
1824            "- **`{}`:** merged {first}, now {} m. Revised, because {}.",
1825            revision.id,
1826            fmt_number(revision.apogee_m, 1),
1827            revision.because.trim_end_matches('.')
1828        );
1829    }
1830    out.push('\n');
1831    out
1832}
1833
1834impl PredictionsReport {
1835    /// Whether the report holds together without the files it was flown from, as CI checks it:
1836    /// every prediction is a positive, finite height, each tag is its list's, each apogee is the
1837    /// one first merged ([`MERGED`]) to the digit the page prints, and the page is this report's
1838    /// rendering.
1839    ///
1840    /// # Errors
1841    ///
1842    /// The first thing that doesn't hold, in words.
1843    pub fn check_consistent(&self, markdown: &str) -> Result<(), String> {
1844        for row in &self.flights {
1845            let mut heights = vec![
1846                ("predicted apogee", row.predicted_apogee_m),
1847                (
1848                    "predicted apogee as a height",
1849                    row.predicted_height_apogee_m,
1850                ),
1851                ("time to apogee", row.predicted_time_to_apogee_s),
1852                ("largest Mach number", row.hpr_max_mach),
1853                ("impulse", row.total_impulse_ns),
1854                ("liftoff mass", row.liftoff_mass_kg),
1855            ];
1856            if let Some(catalog) = &row.catalog_curve {
1857                heights.push(("catalog curve's apogee", catalog.predicted_apogee_m));
1858                heights.push((
1859                    "catalog curve's apogee as a height",
1860                    catalog.predicted_height_apogee_m,
1861                ));
1862                heights.push(("catalog curve's impulse", catalog.total_impulse_ns));
1863                heights.push(("catalog curve's liftoff mass", catalog.liftoff_mass_kg));
1864            }
1865            if let Some((what, value)) = heights
1866                .iter()
1867                .find(|(_, value)| !(value.is_finite() && *value > 0.0))
1868            {
1869                return Err(format!("{}: its {what} is {value}", row.id));
1870            }
1871            if row.all_inputs_traced != row.untraced.is_empty() {
1872                return Err(format!("{}: its traced tag is not its list's", row.id));
1873            }
1874            if row.liftoff_mass_kg <= row.mass_without_motor_kg {
1875                return Err(format!(
1876                    "{}: it lifts off no heavier than without its motor",
1877                    row.id
1878                ));
1879            }
1880            if row.reference_log_sha256.len() != 64 {
1881                return Err(format!("{}: its log has no SHA-256", row.id));
1882            }
1883            held_to_merged(
1884                &row.id,
1885                row.predicted_apogee_m,
1886                row.predicted_height_apogee_m,
1887                row.catalog_curve
1888                    .as_ref()
1889                    .map(|catalog| catalog.predicted_apogee_m),
1890            )?;
1891        }
1892        for row in &self.design_file_flights {
1893            let heights = [
1894                ("predicted apogee", row.predicted_apogee_m),
1895                (
1896                    "predicted apogee as a height",
1897                    row.predicted_height_apogee_m,
1898                ),
1899                ("time to apogee", row.predicted_time_to_apogee_s),
1900                ("largest Mach number", row.hpr_max_mach),
1901                ("impulse", row.total_impulse_ns),
1902                ("liftoff mass", row.liftoff_mass_kg),
1903                ("mass without the motor", row.mass_without_motor_kg),
1904                (
1905                    "apogee of OpenRocket's own stored run",
1906                    row.openrocket_stored_apogee_m,
1907                ),
1908            ];
1909            if let Some((what, value)) = heights
1910                .iter()
1911                .find(|(_, value)| !(value.is_finite() && *value > 0.0))
1912            {
1913                return Err(format!("{}: its {what} is {value}", row.id));
1914            }
1915            if row.all_inputs_traced != row.untraced.is_empty() {
1916                return Err(format!("{}: its traced tag is not its list's", row.id));
1917            }
1918            if row.liftoff_mass_kg <= row.mass_without_motor_kg {
1919                return Err(format!(
1920                    "{}: it lifts off no heavier than without its motor",
1921                    row.id
1922                ));
1923            }
1924            if row.reference_log_sha256.len() != 64 {
1925                return Err(format!("{}: its log has no SHA-256", row.id));
1926            }
1927            if row.design_file_sha256.len() != 64 {
1928                return Err(format!("{}: its design file has no SHA-256", row.id));
1929            }
1930            held_to_merged(
1931                &row.id,
1932                row.predicted_apogee_m,
1933                row.predicted_height_apogee_m,
1934                None,
1935            )?;
1936        }
1937        // Every merged prediction is here, in the order it was merged.
1938        let ids = self
1939            .flights
1940            .iter()
1941            .map(|row| row.id.as_str())
1942            .chain(self.design_file_flights.iter().map(|row| row.id.as_str()));
1943        if !ids.eq(MERGED.iter().map(|merged| merged.id)) {
1944            return Err(format!(
1945                "the {} flights here are not the {} merged predictions, in their order",
1946                self.flights.len() + self.design_file_flights.len(),
1947                MERGED.len()
1948            ));
1949        }
1950        if markdown != self.to_markdown() {
1951            return Err(format!(
1952                "{PREDICTIONS_MD} is not {PREDICTIONS_JSON}'s rendering: rerun `cargo xtask \
1953                 public-predictions`"
1954            ));
1955        }
1956        Ok(())
1957    }
1958
1959    /// Whether `other`, flown now, is this committed report: the same words, files and digests,
1960    /// and the same numbers but for the last digits platforms round differently.
1961    ///
1962    /// # Errors
1963    ///
1964    /// The first difference, in words.
1965    pub fn reproduces(&self, other: &PredictionsReport) -> Result<(), String> {
1966        if (
1967            &self.generator,
1968            &self.traced_rule,
1969            &self.weather_conversion,
1970            &self.design_file_traced_rule,
1971        ) != (
1972            &other.generator,
1973            &other.traced_rule,
1974            &other.weather_conversion,
1975            &other.design_file_traced_rule,
1976        ) {
1977            return Err("the report's header differs".to_owned());
1978        }
1979        if (self.flights.len(), self.design_file_flights.len())
1980            != (other.flights.len(), other.design_file_flights.len())
1981        {
1982            return Err(format!(
1983                "{} flights committed, {} flown",
1984                self.flights.len() + self.design_file_flights.len(),
1985                other.flights.len() + other.design_file_flights.len()
1986            ));
1987        }
1988        let same = crate::report::same_but_for_platform_rounding;
1989        for (a, b) in self.flights.iter().zip(&other.flights) {
1990            // Every field that is not a flown number, compared whole.
1991            let words = |row: &PredictionRow| {
1992                let mut row = row.clone();
1993                for value in [
1994                    &mut row.total_impulse_ns,
1995                    &mut row.liftoff_mass_kg,
1996                    &mut row.predicted_apogee_m,
1997                    &mut row.predicted_height_apogee_m,
1998                    &mut row.predicted_time_to_apogee_s,
1999                    &mut row.hpr_max_mach,
2000                ] {
2001                    *value = 0.0;
2002                }
2003                if let Some(catalog) = &mut row.catalog_curve {
2004                    catalog.total_impulse_ns = 0.0;
2005                    catalog.liftoff_mass_kg = 0.0;
2006                    catalog.predicted_apogee_m = 0.0;
2007                    catalog.predicted_height_apogee_m = 0.0;
2008                }
2009                row
2010            };
2011            if words(a) != words(b) {
2012                return Err(format!(
2013                    "{}: its inputs, sources or files differ from the committed prediction's",
2014                    a.id
2015                ));
2016            }
2017            let mut numbers = vec![
2018                ("impulse", a.total_impulse_ns, b.total_impulse_ns),
2019                ("liftoff mass", a.liftoff_mass_kg, b.liftoff_mass_kg),
2020                (
2021                    "predicted apogee",
2022                    a.predicted_apogee_m,
2023                    b.predicted_apogee_m,
2024                ),
2025                (
2026                    "predicted apogee as a height",
2027                    a.predicted_height_apogee_m,
2028                    b.predicted_height_apogee_m,
2029                ),
2030                (
2031                    "time to apogee",
2032                    a.predicted_time_to_apogee_s,
2033                    b.predicted_time_to_apogee_s,
2034                ),
2035                ("largest Mach number", a.hpr_max_mach, b.hpr_max_mach),
2036            ];
2037            if let (Some(x), Some(y)) = (&a.catalog_curve, &b.catalog_curve) {
2038                numbers.push((
2039                    "catalog curve's impulse",
2040                    x.total_impulse_ns,
2041                    y.total_impulse_ns,
2042                ));
2043                numbers.push((
2044                    "catalog curve's liftoff mass",
2045                    x.liftoff_mass_kg,
2046                    y.liftoff_mass_kg,
2047                ));
2048                numbers.push((
2049                    "catalog curve's apogee",
2050                    x.predicted_apogee_m,
2051                    y.predicted_apogee_m,
2052                ));
2053                numbers.push((
2054                    "catalog curve's apogee as a height",
2055                    x.predicted_height_apogee_m,
2056                    y.predicted_height_apogee_m,
2057                ));
2058            }
2059            if let Some((what, x, y)) = numbers.iter().find(|(_, x, y)| !same(*x, *y)) {
2060                return Err(format!(
2061                    "{}: the {what} is {x} committed and {y} flown: a merged prediction is not \
2062                     changed, it is revised beside the old one (ADR-328 §1b)",
2063                    a.id
2064                ));
2065            }
2066        }
2067        for (a, b) in self
2068            .design_file_flights
2069            .iter()
2070            .zip(&other.design_file_flights)
2071        {
2072            // Every field that is not a flown number, compared whole: the words, the files and
2073            // their digests, the stored simulation's conditions and OpenRocket's stored apogee.
2074            let words = |row: &DesignFilePredictionRow| {
2075                let mut row = row.clone();
2076                for value in [
2077                    &mut row.total_impulse_ns,
2078                    &mut row.mass_without_motor_kg,
2079                    &mut row.liftoff_mass_kg,
2080                    &mut row.predicted_apogee_m,
2081                    &mut row.predicted_height_apogee_m,
2082                    &mut row.predicted_time_to_apogee_s,
2083                    &mut row.hpr_max_mach,
2084                ] {
2085                    *value = 0.0;
2086                }
2087                row
2088            };
2089            if words(a) != words(b) {
2090                return Err(format!(
2091                    "{}: its inputs, sources or files differ from the committed prediction's",
2092                    a.id
2093                ));
2094            }
2095            let numbers = [
2096                ("impulse", a.total_impulse_ns, b.total_impulse_ns),
2097                (
2098                    "mass without the motor",
2099                    a.mass_without_motor_kg,
2100                    b.mass_without_motor_kg,
2101                ),
2102                ("liftoff mass", a.liftoff_mass_kg, b.liftoff_mass_kg),
2103                (
2104                    "predicted apogee",
2105                    a.predicted_apogee_m,
2106                    b.predicted_apogee_m,
2107                ),
2108                (
2109                    "predicted apogee as a height",
2110                    a.predicted_height_apogee_m,
2111                    b.predicted_height_apogee_m,
2112                ),
2113                (
2114                    "time to apogee",
2115                    a.predicted_time_to_apogee_s,
2116                    b.predicted_time_to_apogee_s,
2117                ),
2118                ("largest Mach number", a.hpr_max_mach, b.hpr_max_mach),
2119            ];
2120            if let Some((what, x, y)) = numbers.iter().find(|(_, x, y)| !same(*x, *y)) {
2121                return Err(format!(
2122                    "{}: the {what} is {x} committed and {y} flown: a merged prediction is not \
2123                     changed, it is revised beside the old one (ADR-328 §1b)",
2124                    a.id
2125                ));
2126            }
2127        }
2128        Ok(())
2129    }
2130
2131    /// The predictions as a page.
2132    #[must_use]
2133    pub fn to_markdown(&self) -> String {
2134        let mut out = String::new();
2135        let weather = &self.weather_conversion;
2136        let _ = write!(
2137            out,
2138            "# Public flights predicted before they are compared\n\n\
2139             Written by `cargo xtask public-predictions` ([the EuRoC 2022 predictions, \
2140             M2.3d3][m2-3d3], and [the Macie XL predictions, M2.3d5][m2-3d5]; decisions: [twelve \
2141             public flights, predictions first, ADR-328][adr-328], [the predictions in two \
2142             parts, ADR-334][adr-334] and [the Macie XL predictions, ADR-337][adr-337]). What it \
2143             is for is on the [documentation site][site].\n\n\
2144             - **What this is:** {} public real flights that join the seven of the \
2145             [real-flights report][real], each flown by HPR Sim from its record alone. Each \
2146             flight's prediction was merged before its log was compared: the three EuRoC 2022 \
2147             flights' first, then the two Macie XL flights'. Their measured apogees were \
2148             already public, so the targets were known; what merging first does is make an input \
2149             changed after seeing HPR Sim's own miss show as a change to a merged number. The \
2150             code holds each prediction to the number first merged.\n\
2151             - **What it holds:** each flight's inputs with their sources, the rule its log's \
2152             apogee is read by, and HPR Sim's predicted apogee. It holds no measured apogee \
2153             and no error: those are in the [real-flights report][real], which prints each \
2154             prediction below beside its log's apogee and its error.\n\
2155             - **How it is flown:** the three EuRoC 2022 flights by the seven's method. The \
2156             design is built from the example's inputs and flown on the example's own thrust \
2157             file, from its rail and site, in the ERA5 air of its launch hour, on HPR Sim's own \
2158             aerodynamics. The two Macie XL flights have no example: their design is an \
2159             OpenRocket file in a pinned public repository, read whole as OpenRocket 24.12 \
2160             saved it. Each is flown as the stored simulation the repository names for it: on \
2161             its motor, from its rod, in its steady wind and standard atmosphere, on HPR Sim's \
2162             own aerodynamics.\n\
2163             - **The predicted apogee** is read as the log's altimeter would read it: the standard \
2164             atmosphere's altitude of the flown air's pressure at the apogee, less the pad's. The \
2165             height \
2166             climbed is beside it.\n\
2167             - **Traced:** {} {}\n\
2168             - **Files:** the examples' thrust files and the logs are read from the pinned \
2169             RocketPy checkout (`refs/rocketpy`, which `cargo xtask refs fetch rocketpy` \
2170             fetches), and the weather file is converted from the checkout's. The Macie XL \
2171             design file and logs are read from the pinned `{}` checkout (`{}`, which `cargo \
2172             xtask refs fetch {}` fetches). None is \
2173             committed, and each one's SHA-256 is in the JSON. A log's \
2174             bytes are hashed to pin the file its rule is applied to; they are never read as \
2175             numbers here.\n\n\
2176             [m2-3d3]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m2-3d3\n\
2177             [adr-328]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0328-the-2026-11-08-review-twelve-public-flights-predictions-first.md\n\
2178             [adr-334]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0334-m2-3d1-in-three-the-euroc-2022-predictions-first.md\n\
2179             [m2-3d5]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m2-3d5\n\
2180             [adr-337]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0337-the-macie-xl-predictions-each-flight-s-stored-simulation-flown-as-saved.md\n\
2181             [site]: https://hpr.fusionspace.co/accuracy.html#predicted-before-compared\n\
2182             [real]: real-flights.md\n\n",
2183            self.flights.len() + self.design_file_flights.len(),
2184            self.traced_rule,
2185            self.design_file_traced_rule,
2186            ROCKETRY_FILES.name,
2187            ROCKETRY_FILES.dest,
2188            ROCKETRY_FILES.name,
2189        );
2190        out.push_str(&revisions_section(&MERGED, &REVISIONS));
2191        out.push_str(
2192            "## Predictions\n\n\
2193             | flight | impulse flown (N s) | liftoff mass (kg) | predicted apogee (m) | as a \
2194             height (m) | time to apogee (s) | largest Mach | every input traced |\n\
2195             |---|---:|---:|---:|---:|---:|---:|---|\n",
2196        );
2197        for row in &self.flights {
2198            let _ = writeln!(
2199                out,
2200                "| {} | {} | {} | {} | {} | {} | {} | {} |",
2201                row.title,
2202                fmt_number(row.total_impulse_ns, 1),
2203                fmt_number(row.liftoff_mass_kg, 3),
2204                fmt_number(row.predicted_apogee_m, 1),
2205                fmt_number(row.predicted_height_apogee_m, 1),
2206                fmt_number(row.predicted_time_to_apogee_s, 2),
2207                fmt_number(row.hpr_max_mach, 3),
2208                if row.all_inputs_traced { "yes" } else { "no" },
2209            );
2210        }
2211        for row in &self.design_file_flights {
2212            let _ = writeln!(
2213                out,
2214                "| {} | {} | {} | {} | {} | {} | {} | {} |",
2215                row.title,
2216                fmt_number(row.total_impulse_ns, 1),
2217                fmt_number(row.liftoff_mass_kg, 3),
2218                fmt_number(row.predicted_apogee_m, 1),
2219                fmt_number(row.predicted_height_apogee_m, 1),
2220                fmt_number(row.predicted_time_to_apogee_s, 2),
2221                fmt_number(row.hpr_max_mach, 3),
2222                if row.all_inputs_traced { "yes" } else { "no" },
2223            );
2224        }
2225        let catalog: Vec<(&PredictionRow, &CatalogCurveRow)> = self
2226            .flights
2227            .iter()
2228            .filter_map(|row| row.catalog_curve.as_ref().map(|catalog| (row, catalog)))
2229            .collect();
2230        // A title without the bracket that says which curve the counted flight is on.
2231        let name = |row: &PredictionRow| -> String {
2232            row.title
2233                .rsplit_once(" (")
2234                .map_or(row.title.as_str(), |(name, _)| name)
2235                .to_owned()
2236        };
2237        if !catalog.is_empty() {
2238            out.push_str(
2239                "\n## On the catalog curve, never counted\n\n\
2240                 The same design, at the same mass, on the bundled certified curve of the motor \
2241                 its record names, where the counted flight is on another curve. It is here so \
2242                 the reader can see what the choice of curve moves; it enters no mean.\n\n\
2243                 | flight | catalog motor | impulse flown (N s) | liftoff mass (kg) | predicted \
2244                 apogee (m) | as a height (m) |\n|---|---|---:|---:|---:|---:|\n",
2245            );
2246            for (row, catalog) in &catalog {
2247                let _ = writeln!(
2248                    out,
2249                    "| {} | {} | {} | {} | {} | {} |",
2250                    name(row),
2251                    catalog.motor,
2252                    fmt_number(catalog.total_impulse_ns, 1),
2253                    fmt_number(catalog.liftoff_mass_kg, 3),
2254                    fmt_number(catalog.predicted_apogee_m, 1),
2255                    fmt_number(catalog.predicted_height_apogee_m, 1),
2256                );
2257            }
2258            out.push('\n');
2259            for (row, catalog) in &catalog {
2260                let _ = writeln!(out, "- **{}:** {}.", name(row), catalog.why);
2261            }
2262        }
2263        out.push_str("\n## Each flight's inputs and its apogee rule\n\n");
2264        for row in &self.flights {
2265            let _ = writeln!(
2266                out,
2267                "- **{}** (`{}`, design `{}`):\n  \
2268                 - Design, site and rail: RocketPy 1.13.0's {}. The site is {}°, {}° at {} m; the \
2269                 rail is {} m long, {}° from the horizontal, heading {}°.\n  \
2270                 - Motor: {} ({}). Thrust file `{}`{}.\n  \
2271                 - Mass: {} kg without the motor, {} kg at liftoff ({}).\n  \
2272                 - Weather: ERA5 at {}, from the converted file below.\n  \
2273                 - Apogee rule: {}, in `{}`. Altimeter: {} ({}).\n  \
2274                 - Every input traced: {}{}",
2275                row.title,
2276                row.id,
2277                row.design,
2278                row.source,
2279                row.latitude_deg,
2280                row.longitude_deg,
2281                row.elevation_m,
2282                row.rail_length_m,
2283                row.rail_inclination_deg,
2284                row.rail_heading_deg,
2285                row.motor,
2286                row.motor_source,
2287                row.thrust_file,
2288                row.burn_time_s
2289                    .map_or_else(String::new, |burn| format!(", burn time {burn} s")),
2290                row.mass_without_motor_kg,
2291                fmt_number(row.liftoff_mass_kg, 3),
2292                row.mass_source,
2293                row.weather_time_utc,
2294                row.reference_rule,
2295                row.reference_log,
2296                row.altimeter,
2297                row.altimeter_evidence,
2298                if row.all_inputs_traced {
2299                    "yes.".to_owned()
2300                } else {
2301                    format!("no. Not traced: {}.", row.untraced.join("; "))
2302                },
2303                if row.note.is_empty() {
2304                    String::new()
2305                } else {
2306                    format!(" Note: {}.", row.note)
2307                },
2308            );
2309        }
2310        for row in &self.design_file_flights {
2311            let _ = writeln!(
2312                out,
2313                "- **{}** (`{}`):\n  \
2314                 - Design: `{}`, SHA-256 `{}`, at commit `{}` of `{}` ({}). From {}.\n  \
2315                 - Flown as: the stored simulation `{}`, motor configuration `{}` ({}). The site \
2316                 is {}°, {}° at {} m; the rod is {} m long, {}° from the horizontal, heading \
2317                 {}°; the wind is a steady {} m/s from {}°; the air is {}.\n  \
2318                 - Motor: {} ({}). Curve file `{}`, for the digest `{}`.\n  \
2319                 - Mass: {} kg without the motor, {} kg at liftoff ({}).\n  \
2320                 - Apogee rule: {}, in `{}`. Altimeter: {} ({}).\n  \
2321                 - Every input traced: {}{}\n  \
2322                 - OpenRocket's own run of this simulation, stored in the design file, reached \
2323                 {} m. That is another simulator's number, not a measurement; it is shown and \
2324                 never counted.\n  \
2325                 - The reader's warnings on this file and motor are in the JSON under this \
2326                 flight's `reader_warnings`: {} in all.",
2327                row.title,
2328                row.id,
2329                row.design_file,
2330                row.design_file_sha256,
2331                row.repository_commit,
2332                row.repository,
2333                row.repository_license,
2334                row.source,
2335                row.simulation,
2336                row.configuration,
2337                row.conditions_source,
2338                row.latitude_deg,
2339                row.longitude_deg,
2340                row.elevation_m,
2341                row.rail_length_m,
2342                fmt_number(row.rail_inclination_deg, 1),
2343                fmt_number(row.rail_heading_deg, 1),
2344                row.wind_speed_m_s,
2345                fmt_number(row.wind_from_deg, 1),
2346                row.atmosphere,
2347                row.motor,
2348                row.motor_source,
2349                row.curve_file,
2350                row.motor_digest,
2351                fmt_number(row.mass_without_motor_kg, 3),
2352                fmt_number(row.liftoff_mass_kg, 3),
2353                row.mass_source,
2354                row.reference_rule,
2355                row.reference_log,
2356                row.altimeter,
2357                row.altimeter_evidence,
2358                if row.all_inputs_traced {
2359                    "yes.".to_owned()
2360                } else {
2361                    format!("no. Not traced: {}.", row.untraced.join("; "))
2362                },
2363                if row.note.is_empty() {
2364                    String::new()
2365                } else {
2366                    format!(" Note: {}.", row.note)
2367                },
2368                fmt_number(row.openrocket_stored_apogee_m, 1),
2369                row.reader_warnings.len(),
2370            );
2371        }
2372        let _ = write!(
2373            out,
2374            "\n## The weather file\n\n\
2375             The three EuRoC 2022 flights' ERA5 file is netCDF-4, which HPR Sim does not read. \
2376             `validation/oracles/netcdf/euroc_2022.py` converts it as the [guide][era5] says, \
2377             `{}`, and checks the result: the four fields hold the source's values bit for bit, \
2378             and RocketPy reads the same levels from both files at each flight's site and hour. \
2379             Its record is `{}`.\n\n\
2380             | file | SHA-256 |\n|---|---|\n\
2381             | `{}` (netCDF-4, as RocketPy ships it) | `{}` |\n\
2382             | `{}` (converted, flown) | `{}` |\n\n\
2383             [era5]: https://hpr.fusionspace.co/format/era5.html#converting-a-current-file\n",
2384            weather.conversion,
2385            weather.record,
2386            weather.source,
2387            weather.source_sha256,
2388            weather.converted,
2389            weather.converted_sha256,
2390        );
2391        out
2392    }
2393}