Skip to main content

hpr_validate/
predicted_first.rs

1//! The public flights predicted before they were compared, each beside its log's apogee and its
2//! error ([the errors][m2-3d2], decisions [ADR-328][adr-328] §1b and [ADR-342][adr-342]).
3//!
4//! [`crate::public_predictions`] flies five public flights from their records and holds no
5//! measured value. This module is the comparison that module left for later. For each flight it
6//! reads the log's apogee by the rule merged with the prediction ([`ApogeeRule`], the machine's
7//! form of [`crate::public_predictions::Reference::rule`]) and puts beside it:
8//!
9//! - the prediction as first merged ([`crate::public_predictions::MERGED`]), to the digit its
10//!   page printed;
11//! - the prediction HPR Sim flies today, which is the merged one unless a revision says why it
12//!   changed ([`crate::public_predictions::REVISIONS`]);
13//! - the error of each against the log's apogee, per cent of the log's:
14//!   `100 (predicted − logged) / logged`.
15//!
16//! The error counted in the report's means is today's prediction's. Where any prediction was
17//! revised, the report also gives the means over the merged numbers, so a revision can't lower
18//! an error out of sight.
19//!
20//! Two more numbers are shown beside a flight and never counted: Andromeda's prediction on its
21//! catalog curve, and for the Macie XL flights the apogee of the OpenRocket simulation stored in
22//! the design file.
23//!
24//! [m2-3d2]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m2-3d2
25//! [adr-328]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0328-the-2026-11-08-review-twelve-public-flights-predictions-first.md
26//! [adr-342]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0342-the-errors-before-the-remaining-openrocket-parity-probes.md
27
28use std::path::Path;
29
30use serde::{Deserialize, Serialize};
31
32use crate::public_predictions::{
33    DESIGN_FILE_FLIGHTS, MERGED, MergedPrediction, NEW_FLIGHTS, PredictionsReport, REVISIONS,
34    Revision, held_to,
35};
36use crate::real_flight::{RealFlightError, read_bytes, sha256_hex};
37
38/// How a log's apogee is read: what [`crate::public_predictions::Reference::rule`] says in
39/// words, as code.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum ApogeeRule {
42    /// The highest reading of the named column of a comma-separated log whose first line names
43    /// its columns, in meters, the log read whole: a row whose reading isn't a number fails the
44    /// read; it is never skipped.
45    HighestOfColumn(&'static str),
46    /// The apogee a PerfectFlite altimeter worked out, on the `Apogee:` line of its `.pf2`
47    /// log's header, in feet above the pad (0.3048 m to the foot, exactly); never the highest
48    /// sample, which an ejection charge's pressure spike can raise.
49    PerfectFliteHeader,
50}
51
52/// Each predicted flight's rule, by its public id, in [`MERGED`]'s order.
53///
54/// The words were merged with the predictions and are not edited here; a test holds each entry
55/// to them: the column it reads is the one the words name, and the header rule is the one the
56/// words give for a PerfectFlite log.
57pub const RULES: [(&str, ApogeeRule); 5] = [
58    ("astra", ApogeeRule::HighestOfColumn("alt")),
59    ("andromeda", ApogeeRule::HighestOfColumn("alt(m)")),
60    ("erebus-11", ApogeeRule::HighestOfColumn("alt")),
61    ("macie-xl-1", ApogeeRule::PerfectFliteHeader),
62    ("macie-xl-2", ApogeeRule::PerfectFliteHeader),
63];
64
65/// A log's apogee as its rule reads it.
66#[derive(Debug, Clone, Copy, PartialEq)]
67pub struct LogApogee {
68    /// The apogee, m above the pad.
69    pub apogee_m: f64,
70    /// The rows or samples the log holds.
71    pub rows: usize,
72    /// The highest sample, m, where the rule reads a header line and not the samples: shown,
73    /// never compared.
74    pub highest_sample_m: Option<f64>,
75}
76
77impl ApogeeRule {
78    /// Whether the rule merged in words, `words`, is this one: the words name the column this
79    /// reads, or give the header rule.
80    #[must_use]
81    pub fn is_the_rule_in(self, words: &str) -> bool {
82        match self {
83            Self::HighestOfColumn(column) => {
84                words.contains(&format!(
85                    "the highest reading of the log's `{column}` column"
86                )) && words.contains("the log read whole")
87            }
88            Self::PerfectFliteHeader => {
89                words.contains("its `Apogee:` line")
90                    && words.contains("0.3048 m to the foot")
91                    && words.contains("never the highest sample")
92            }
93        }
94    }
95
96    /// The apogee of the log whose text is `text`.
97    ///
98    /// # Errors
99    ///
100    /// What the rule can't read, in words: no such column or two of them, a row whose reading
101    /// isn't a finite number, no rows, a `.pf2` the reader refuses, or a header that states no
102    /// apogee.
103    pub fn read(self, text: &str) -> Result<LogApogee, String> {
104        match self {
105            Self::HighestOfColumn(column) => highest_of_column(column, text),
106            Self::PerfectFliteHeader => {
107                let log = hpr_flightdata::perfectflite::read(text)
108                    .map_err(|error| format!("the `.pf2` doesn't read: {error}"))?;
109                let apogee_m = log
110                    .stated
111                    .apogee_m
112                    .filter(|apogee| apogee.is_finite() && *apogee > 0.0)
113                    .ok_or_else(|| "its header states no apogee".to_owned())?;
114                let highest = log
115                    .altitude_m
116                    .iter()
117                    .copied()
118                    .filter(|height| height.is_finite())
119                    .fold(f64::NEG_INFINITY, f64::max);
120                Ok(LogApogee {
121                    apogee_m,
122                    rows: log.time_s.len(),
123                    highest_sample_m: highest.is_finite().then_some(highest),
124                })
125            }
126        }
127    }
128}
129
130/// The highest reading of `column` in a comma-separated log whose first line names its columns.
131fn highest_of_column(column: &str, text: &str) -> Result<LogApogee, String> {
132    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
133    let mut lines = text.lines();
134    let header = lines.next().ok_or_else(|| "the log is empty".to_owned())?;
135    let mut places = header
136        .split(',')
137        .enumerate()
138        .filter(|(_, name)| name.trim() == column)
139        .map(|(index, _)| index);
140    let index = places
141        .next()
142        .ok_or_else(|| format!("its first line names no `{column}` column"))?;
143    if places.next().is_some() {
144        return Err(format!("its first line names `{column}` twice"));
145    }
146    let mut highest = f64::NEG_INFINITY;
147    let mut rows = 0_usize;
148    for (number, line) in lines.enumerate() {
149        if line.trim().is_empty() {
150            continue;
151        }
152        // Line numbers count from 1, and the header is line 1.
153        let reading = line
154            .split(',')
155            .nth(index)
156            .and_then(|field| field.trim().parse::<f64>().ok())
157            .filter(|reading| reading.is_finite())
158            .ok_or_else(|| {
159                format!(
160                    "line {}: its `{column}` is not a number, and the rule reads the log whole",
161                    number + 2
162                )
163            })?;
164        highest = highest.max(reading);
165        rows += 1;
166    }
167    if rows == 0 {
168        return Err("the log has no rows".to_owned());
169    }
170    if highest <= 0.0 {
171        return Err(format!(
172            "its highest `{column}` is {highest}: a flight's apogee is above its pad"
173        ));
174    }
175    Ok(LogApogee {
176        apogee_m: highest,
177        rows,
178        highest_sample_m: None,
179    })
180}
181
182/// A number shown beside a flight's counted prediction and never counted.
183#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
184pub struct ShownOnly {
185    /// What it is, in words.
186    pub what: String,
187    /// Its apogee, m: for a catalog curve, HPR Sim's flight as the log's altimeter would read
188    /// it; for a design file's stored simulation, the height above the site OpenRocket recorded.
189    pub apogee_m: f64,
190    /// Its error against the log's apogee, per cent.
191    pub apogee_error_percent: f64,
192}
193
194/// One predicted flight beside its log, as the real-flights report keeps it.
195#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
196pub struct ComparedPrediction {
197    /// The flight's public id.
198    pub id: String,
199    /// The rocket, the team and the event.
200    pub title: String,
201    /// What measured the log's height ([`crate::real_flight::Altimeter::kind`]).
202    pub altimeter: String,
203    /// Where that comes from.
204    pub altimeter_evidence: String,
205    /// Whether the flight was flown in the ERA5 air of its launch hour; otherwise in the
206    /// standard atmosphere and steady wind of a stored simulation.
207    pub era5_weather: bool,
208    /// What was flown, in words: the design built from RocketPy's example, or the design file as
209    /// saved in the stored simulation that names the flight.
210    pub design: String,
211    /// The air it was flown in, in words: the ERA5 hour of its launch, or the atmosphere its
212    /// stored simulation states.
213    pub weather: String,
214    /// The impulse of the thrust flown, N s.
215    pub total_impulse_ns: f64,
216    /// The impulse of the catalog's curve, N s, where [`Self::catalog_curve`] shows that flight:
217    /// the gap from the impulse flown is stated beside the flight's error.
218    pub catalog_total_impulse_ns: Option<f64>,
219    /// The log, from the repository root.
220    pub reference_log: String,
221    /// Its SHA-256, in hex: the file the rule was merged for.
222    pub reference_log_sha256: String,
223    /// The rule its apogee is read by, as merged with the prediction.
224    pub reference_rule: String,
225    /// The rows or samples the log holds.
226    pub log_rows: usize,
227    /// The log's apogee by that rule, m above the pad.
228    pub log_apogee_m: f64,
229    /// The log's highest sample, m, where the rule reads a header line: shown, never compared.
230    pub log_highest_sample_m: Option<f64>,
231    /// The prediction as first merged, m, to the digit its page printed
232    /// ([`MergedPrediction::apogee_m`]).
233    pub merged_apogee_m: f64,
234    /// The same as a height above the pad, m.
235    pub merged_height_apogee_m: f64,
236    /// The merged prediction's error against the log's apogee, per cent.
237    pub merged_apogee_error_percent: f64,
238    /// The prediction HPR Sim flies today, m, as the log's altimeter would read it: the merged
239    /// one to its printed digit, unless revised.
240    pub hpr_apogee_m: f64,
241    /// The same as a height above the pad, m.
242    pub hpr_height_apogee_m: f64,
243    /// Today's prediction less the log's apogee, per cent of the log's: the error counted.
244    pub apogee_error_percent: f64,
245    /// Why today's prediction is not the merged one, when it isn't
246    /// ([`Revision::because`]).
247    pub revised_because: Option<String>,
248    /// Whether every input is traced to the flight's record, as tagged with the prediction.
249    pub all_inputs_traced: bool,
250    /// What moves the apogee and no record states, as tagged with the prediction.
251    pub untraced: Vec<String>,
252    /// HPR Sim's largest Mach number over the flight.
253    pub hpr_max_mach: f64,
254    /// The flight on its catalog curve, where the counted curve is not the catalog's.
255    pub catalog_curve: Option<ShownOnly>,
256    /// The OpenRocket simulation stored in the design file, for a flight read from one.
257    pub openrocket_stored: Option<ShownOnly>,
258}
259
260fn percent_of(value: f64, reference: f64) -> f64 {
261    100.0 * (value - reference) / reference
262}
263
264/// What a prediction's row gives the comparison, whichever kind of flight it is.
265struct Predicted<'a> {
266    id: &'a str,
267    title: &'a str,
268    altimeter: &'a str,
269    altimeter_evidence: &'a str,
270    era5_weather: bool,
271    design: String,
272    weather: String,
273    total_impulse_ns: f64,
274    catalog_total_impulse_ns: Option<f64>,
275    reference_log: &'a str,
276    reference_log_sha256: &'a str,
277    reference_rule: &'a str,
278    apogee_m: f64,
279    height_apogee_m: f64,
280    all_inputs_traced: bool,
281    untraced: &'a [String],
282    hpr_max_mach: f64,
283    catalog_curve: Option<(String, f64)>,
284    openrocket_stored_apogee_m: Option<f64>,
285}
286
287fn predicted(report: &PredictionsReport) -> Vec<Predicted<'_>> {
288    let examples = report.flights.iter().map(|row| Predicted {
289        id: &row.id,
290        title: &row.title,
291        altimeter: &row.altimeter,
292        altimeter_evidence: &row.altimeter_evidence,
293        era5_weather: true,
294        design: format!("the design built from RocketPy's example, `{}`", row.design),
295        weather: format!("the ERA5 weather of {}", row.weather_time_utc),
296        total_impulse_ns: row.total_impulse_ns,
297        catalog_total_impulse_ns: row
298            .catalog_curve
299            .as_ref()
300            .map(|catalog| catalog.total_impulse_ns),
301        reference_log: &row.reference_log,
302        reference_log_sha256: &row.reference_log_sha256,
303        reference_rule: &row.reference_rule,
304        apogee_m: row.predicted_apogee_m,
305        height_apogee_m: row.predicted_height_apogee_m,
306        all_inputs_traced: row.all_inputs_traced,
307        untraced: &row.untraced,
308        hpr_max_mach: row.hpr_max_mach,
309        catalog_curve: row.catalog_curve.as_ref().map(|catalog| {
310            (
311                format!("on the catalog's curve, {}", catalog.motor),
312                catalog.predicted_apogee_m,
313            )
314        }),
315        openrocket_stored_apogee_m: None,
316    });
317    let design_files = report.design_file_flights.iter().map(|row| Predicted {
318        id: &row.id,
319        title: &row.title,
320        altimeter: &row.altimeter,
321        altimeter_evidence: &row.altimeter_evidence,
322        era5_weather: false,
323        design: format!(
324            "the design file `{}` as saved, as its stored simulation `{}` flies it",
325            row.design_file, row.simulation
326        ),
327        weather: row.atmosphere.clone(),
328        total_impulse_ns: row.total_impulse_ns,
329        catalog_total_impulse_ns: None,
330        reference_log: &row.reference_log,
331        reference_log_sha256: &row.reference_log_sha256,
332        reference_rule: &row.reference_rule,
333        apogee_m: row.predicted_apogee_m,
334        height_apogee_m: row.predicted_height_apogee_m,
335        all_inputs_traced: row.all_inputs_traced,
336        untraced: &row.untraced,
337        hpr_max_mach: row.hpr_max_mach,
338        catalog_curve: None,
339        openrocket_stored_apogee_m: Some(row.openrocket_stored_apogee_m),
340    });
341    examples.chain(design_files).collect()
342}
343
344/// Reads each predicted flight's log by its rule and puts it beside the prediction `flown` gives
345/// and the one first merged.
346///
347/// `committed` is the predictions report as committed: each log must be the file whose SHA-256
348/// it holds, the file the rule was merged for.
349///
350/// # Errors
351///
352/// [`RealFlightError`] for a log that can't be read, isn't the committed predictions' file or
353/// doesn't read by its rule, and for a prediction that differs from its merged number without a
354/// revision that says why.
355pub fn compare(
356    root: &Path,
357    flown: &PredictionsReport,
358    committed: &PredictionsReport,
359) -> Result<Vec<ComparedPrediction>, RealFlightError> {
360    let input = |flight: &str, what: String| RealFlightError::Input {
361        flight: flight.to_owned(),
362        what,
363    };
364    let committed = predicted(committed);
365    predicted(flown)
366        .into_iter()
367        .map(|flight| {
368            let id = flight.id;
369            let rule = RULES
370                .iter()
371                .find(|(rule_id, _)| *rule_id == id)
372                .map(|(_, rule)| *rule)
373                .ok_or_else(|| input(id, "it has no apogee rule".to_owned()))?;
374            if !rule.is_the_rule_in(flight.reference_rule) {
375                return Err(input(
376                    id,
377                    format!(
378                        "its rule as code, {rule:?}, is not the rule merged with it: {}",
379                        flight.reference_rule
380                    ),
381                ));
382            }
383            let bytes = read_bytes(root, flight.reference_log, "reading the flight's log")?;
384            let sha256 = sha256_hex(&bytes);
385            let pinned = committed
386                .iter()
387                .find(|row| row.id == id)
388                .ok_or_else(|| input(id, "the committed predictions don't hold it".to_owned()))?;
389            if sha256 != pinned.reference_log_sha256 || sha256 != flight.reference_log_sha256 {
390                return Err(input(
391                    id,
392                    format!(
393                        "{} is not the log its prediction was merged for (SHA-256 {sha256}, \
394                         committed {})",
395                        flight.reference_log, pinned.reference_log_sha256
396                    ),
397                ));
398            }
399            let text = String::from_utf8(bytes)
400                .map_err(|_| input(id, format!("{} is not UTF-8", flight.reference_log)))?;
401            let log = rule
402                .read(&text)
403                .map_err(|what| input(id, format!("{}: {what}", flight.reference_log)))?;
404            let row =
405                compared(&MERGED, &REVISIONS, &flight, log).map_err(|what| input(id, what))?;
406            row.check(&MERGED, &REVISIONS)
407                .map_err(|what| input(id, what))?;
408            Ok(row)
409        })
410        .collect()
411}
412
413/// The row of `flight` against `log`: the merged numbers from `merged`, and the reason from
414/// the flight's entry in `revisions` where today's prediction is not the merged one.
415fn compared(
416    merged: &[MergedPrediction],
417    revisions: &[Revision],
418    flight: &Predicted<'_>,
419    log: LogApogee,
420) -> Result<ComparedPrediction, String> {
421    let first = merged
422        .iter()
423        .find(|merged| merged.id == flight.id)
424        .ok_or_else(|| "it has no merged prediction".to_owned())?;
425    let shown = |what: String, apogee_m: f64| ShownOnly {
426        what,
427        apogee_m,
428        apogee_error_percent: percent_of(apogee_m, log.apogee_m),
429    };
430    let catalog_apogee_m = flight.catalog_curve.as_ref().map(|(_, apogee_m)| *apogee_m);
431    let revision = held_to(
432        merged,
433        revisions,
434        flight.id,
435        flight.apogee_m,
436        flight.height_apogee_m,
437        catalog_apogee_m,
438    )?;
439    Ok(ComparedPrediction {
440        id: flight.id.to_owned(),
441        title: flight.title.to_owned(),
442        altimeter: flight.altimeter.to_owned(),
443        altimeter_evidence: flight.altimeter_evidence.to_owned(),
444        era5_weather: flight.era5_weather,
445        design: flight.design.clone(),
446        weather: flight.weather.clone(),
447        total_impulse_ns: flight.total_impulse_ns,
448        catalog_total_impulse_ns: flight.catalog_total_impulse_ns,
449        reference_log: flight.reference_log.to_owned(),
450        reference_log_sha256: flight.reference_log_sha256.to_owned(),
451        reference_rule: flight.reference_rule.to_owned(),
452        log_rows: log.rows,
453        log_apogee_m: log.apogee_m,
454        log_highest_sample_m: log.highest_sample_m,
455        merged_apogee_m: first.apogee_m,
456        merged_height_apogee_m: first.height_apogee_m,
457        merged_apogee_error_percent: percent_of(first.apogee_m, log.apogee_m),
458        hpr_apogee_m: flight.apogee_m,
459        hpr_height_apogee_m: flight.height_apogee_m,
460        apogee_error_percent: percent_of(flight.apogee_m, log.apogee_m),
461        revised_because: revision.map(|revision| revision.because.to_owned()),
462        all_inputs_traced: flight.all_inputs_traced,
463        untraced: flight.untraced.to_vec(),
464        hpr_max_mach: flight.hpr_max_mach,
465        catalog_curve: flight
466            .catalog_curve
467            .as_ref()
468            .map(|(what, apogee_m)| shown(what.clone(), *apogee_m)),
469        openrocket_stored: flight.openrocket_stored_apogee_m.map(|apogee_m| {
470            shown(
471                "OpenRocket 24.12's simulation stored in the design file".to_owned(),
472                apogee_m,
473            )
474        }),
475    })
476}
477
478impl ComparedPrediction {
479    /// Whether the row holds together without the files it was read from, as CI checks it: its
480    /// merged numbers are `merged`'s, today's prediction is the merged one or the one a revision
481    /// in `revisions` gives, the reason kept is that revision's, each percentage is its meters',
482    /// and the traced tag is its list's.
483    ///
484    /// # Errors
485    ///
486    /// The first thing that doesn't hold, in words.
487    pub fn check(&self, merged: &[MergedPrediction], revisions: &[Revision]) -> Result<(), String> {
488        let first = merged
489            .iter()
490            .find(|merged| merged.id == self.id)
491            .ok_or_else(|| "it has no merged prediction".to_owned())?;
492        if (self.merged_apogee_m, self.merged_height_apogee_m)
493            != (first.apogee_m, first.height_apogee_m)
494        {
495            return Err(format!(
496                "its merged prediction is kept as {} m ({} m as a height), and the one merged is \
497                 {} m ({} m)",
498                self.merged_apogee_m,
499                self.merged_height_apogee_m,
500                first.apogee_m,
501                first.height_apogee_m
502            ));
503        }
504        let revision = held_to(
505            merged,
506            revisions,
507            &self.id,
508            self.hpr_apogee_m,
509            self.hpr_height_apogee_m,
510            self.catalog_curve.as_ref().map(|catalog| catalog.apogee_m),
511        )?;
512        if self.revised_because.as_deref() != revision.map(|revision| revision.because) {
513            return Err("its revision's reason is not the one in `REVISIONS`".to_owned());
514        }
515        if !(self.log_apogee_m.is_finite() && self.log_apogee_m > 0.0) {
516            return Err(format!("its log's apogee is {}", self.log_apogee_m));
517        }
518        if self.reference_log_sha256.len() != 64 {
519            return Err("its log has no SHA-256".to_owned());
520        }
521        if self.all_inputs_traced != self.untraced.is_empty() {
522            return Err("its traced tag is not its list's".to_owned());
523        }
524        if !(self.hpr_max_mach.is_finite() && self.hpr_max_mach > 0.0) {
525            return Err(format!("its largest Mach number is {}", self.hpr_max_mach));
526        }
527        if self.design.trim().is_empty() || self.weather.trim().is_empty() {
528            return Err("its design or its weather is not named".to_owned());
529        }
530        if !(self.total_impulse_ns.is_finite() && self.total_impulse_ns > 0.0) {
531            return Err(format!("its impulse flown is {}", self.total_impulse_ns));
532        }
533        // A flight shown on its catalog's curve states that curve's impulse, so the gap from the
534        // impulse flown is beside its error; no other flight has one to state.
535        if self.catalog_total_impulse_ns.is_some() != self.catalog_curve.is_some()
536            || self
537                .catalog_total_impulse_ns
538                .is_some_and(|impulse| !(impulse.is_finite() && impulse > 0.0))
539        {
540            return Err("its catalog curve's impulse is not its catalog curve's".to_owned());
541        }
542        let same = crate::report::same_but_for_platform_rounding;
543        let shown = [&self.catalog_curve, &self.openrocket_stored];
544        let percentages = [
545            (
546                "apogee error",
547                self.apogee_error_percent,
548                percent_of(self.hpr_apogee_m, self.log_apogee_m),
549            ),
550            (
551                "merged prediction's error",
552                self.merged_apogee_error_percent,
553                percent_of(self.merged_apogee_m, self.log_apogee_m),
554            ),
555        ]
556        .into_iter()
557        .chain(shown.into_iter().flatten().map(|shown| {
558            (
559                "error of a number shown beside it",
560                shown.apogee_error_percent,
561                percent_of(shown.apogee_m, self.log_apogee_m),
562            )
563        }));
564        for (what, kept, derived) in percentages {
565            if !same(kept, derived) {
566                return Err(format!("its {what} is {kept}, its meters give {derived}"));
567            }
568        }
569        Ok(())
570    }
571}
572
573/// Whether the ids of `rows` are the predicted flights', in [`MERGED`]'s order, and each row is
574/// the flight the code lists: its title, its log and its rule.
575///
576/// # Errors
577///
578/// The first thing that doesn't hold, in words.
579pub fn check_listed(rows: &[ComparedPrediction]) -> Result<(), String> {
580    if !rows
581        .iter()
582        .map(|row| row.id.as_str())
583        .eq(MERGED.iter().map(|merged| merged.id))
584    {
585        return Err(format!(
586            "the predicted flights compared are not the {} merged, in their order",
587            MERGED.len()
588        ));
589    }
590    let listed = NEW_FLIGHTS
591        .iter()
592        .map(|flight| {
593            (
594                flight.id,
595                flight.title,
596                flight.reference.rule,
597                flight.reference.altimeter.kind(),
598                true,
599            )
600        })
601        .chain(DESIGN_FILE_FLIGHTS.iter().map(|flight| {
602            (
603                flight.id,
604                flight.title,
605                flight.reference.rule,
606                flight.reference.altimeter.kind(),
607                false,
608            )
609        }));
610    for (row, (id, title, rule, altimeter, era5_weather)) in rows.iter().zip(listed) {
611        if (
612            row.id.as_str(),
613            row.title.as_str(),
614            row.reference_rule.as_str(),
615            row.altimeter.as_str(),
616        ) != (id, title, rule, altimeter)
617            || row.era5_weather != era5_weather
618        {
619            return Err(format!(
620                "{}: its title, rule, altimeter or air is not the code's for {id}",
621                row.id
622            ));
623        }
624        // A flight read from a design file shows that file's stored simulation beside it, and
625        // no other flight has one: a row can't lose the number, or gain one, unseen.
626        if row.openrocket_stored.is_some() == era5_weather {
627            return Err(format!(
628                "{id}: a design file's stored simulation is shown beside a flight read from \
629                 one, and beside no other"
630            ));
631        }
632        let read_by = RULES.iter().find(|(rule_id, _)| *rule_id == id);
633        if !read_by.is_some_and(|(_, read_by)| read_by.is_the_rule_in(rule)) {
634            return Err(format!("{id}: its rule as code is not its rule in words"));
635        }
636    }
637    Ok(())
638}
639
640#[cfg(test)]
641mod tests {
642    use super::*;
643
644    /// A comma-separated log reads its named column whole: the highest reading, every row
645    /// counted, whichever place the column has.
646    #[test]
647    fn the_highest_reading_of_the_named_column_is_the_apogee() {
648        let log = ApogeeRule::HighestOfColumn("alt(m)")
649            .read("t(s),alt(ft),alt(m)\n0,0,0.0\n1,328.1,100.0\n2,656.2,200.5\n3,600,182.9\n\n")
650            .expect("it reads");
651        assert_eq!(
652            log,
653            LogApogee {
654                apogee_m: 200.5,
655                rows: 4,
656                highest_sample_m: None
657            }
658        );
659        // The column first, as Erebus 11's log has it, and a byte-order mark before the header.
660        let first = ApogeeRule::HighestOfColumn("alt")
661            .read("\u{feff}alt,t\n0,0\n31.5,1\n12,2\n")
662            .expect("it reads");
663        assert_eq!((first.apogee_m, first.rows), (31.5, 3));
664    }
665
666    /// The rule reads the log whole, so nothing is skipped: a row that isn't a number, a missing
667    /// column, a column named twice and an empty log each fail, with the place.
668    #[test]
669    fn a_log_that_does_not_read_whole_is_refused() {
670        // A log that never leaves its pad has no apogee to compare.
671        let grounded = ApogeeRule::HighestOfColumn("alt")
672            .read("t,alt\n0,0.0\n1,-0.4\n")
673            .expect_err("never above the pad");
674        assert!(grounded.contains("above its pad"), "{grounded}");
675
676        let read = |text: &str| {
677            ApogeeRule::HighestOfColumn("alt")
678                .read(text)
679                .expect_err("it is refused")
680        };
681        assert!(read("t,alt\n0,1\n1,n/a\n").contains("line 3"), "a word");
682        assert!(read("t,alt\n0,1\n1\n").contains("line 3"), "a short row");
683        assert!(read("t,alt\n0,NaN\n").contains("line 2"), "not finite");
684        assert!(read("t,alt\n0,inf\n").contains("line 2"), "not finite");
685        assert!(read("t,height\n0,1\n").contains("no `alt` column"));
686        assert!(read("alt,t,alt\n0,1,2\n").contains("twice"));
687        assert!(read("t,alt\n").contains("no rows"));
688        assert!(read("").contains("empty"));
689    }
690
691    /// A PerfectFlite log's apogee is its header's, in feet at 0.3048 m, never its highest
692    /// sample: here a spike of 3,000 ft among samples that peak at 2,765 ft.
693    #[test]
694    fn a_perfectflite_logs_apogee_is_its_headers_not_its_highest_sample() {
695        let text = "PerfectFlite SLCF\r\nApogee: 2765' AGL\r\nGround Elevation: 12' MSL\r\n\
696                    NumSamps: 4\r\n0.00, 0, 0\r\n0.05, 2765, 10\r\n0.10, 3000, 10\r\n\
697                    0.15, 2700, -10\r\n";
698        let log = ApogeeRule::PerfectFliteHeader.read(text).expect("it reads");
699        assert!((log.apogee_m - 2765.0 * 0.3048).abs() < 1e-9, "{log:?}");
700        assert_eq!(log.rows, 4);
701        let highest = log.highest_sample_m.expect("it has samples");
702        assert!((highest - 3000.0 * 0.3048).abs() < 1e-9, "{highest}");
703        // A header that states a power loss, not a height, gives no apogee to compare.
704        let lost = ApogeeRule::PerfectFliteHeader
705            .read("PerfectFlite SLCF\nApogee: PWRLOSS\n0, 0, 0\n")
706            .expect_err("no apogee");
707        assert!(lost.contains("states no apogee"), "{lost}");
708    }
709
710    /// Each rule as code is the rule merged in words with its prediction, and no predicted
711    /// flight is without one.
712    #[test]
713    fn each_rule_is_the_one_merged_in_words() {
714        let words = NEW_FLIGHTS
715            .iter()
716            .map(|flight| (flight.id, flight.reference.rule))
717            .chain(
718                DESIGN_FILE_FLIGHTS
719                    .iter()
720                    .map(|flight| (flight.id, flight.reference.rule)),
721            );
722        assert!(
723            RULES
724                .iter()
725                .map(|(id, _)| *id)
726                .eq(MERGED.iter().map(|merged| merged.id))
727        );
728        for ((id, rule), (flight, words)) in RULES.iter().zip(words) {
729            assert_eq!(*id, flight);
730            assert!(rule.is_the_rule_in(words), "{id}: {words}");
731        }
732        // The other kind of rule is not the one in a flight's words, so a swap fails.
733        assert!(!ApogeeRule::PerfectFliteHeader.is_the_rule_in(NEW_FLIGHTS[0].reference.rule));
734        assert!(
735            !ApogeeRule::HighestOfColumn("alt").is_the_rule_in(NEW_FLIGHTS[1].reference.rule),
736            "Andromeda's column is `alt(m)`"
737        );
738        assert!(
739            !ApogeeRule::HighestOfColumn("alt")
740                .is_the_rule_in(DESIGN_FILE_FLIGHTS[0].reference.rule)
741        );
742    }
743
744    /// An invented row: a flight merged at 1,000.0 m against a log at 1,100 m.
745    fn row(hpr_apogee_m: f64, revised_because: Option<&str>) -> ComparedPrediction {
746        ComparedPrediction {
747            id: "invented".to_owned(),
748            title: "An invented flight".to_owned(),
749            altimeter: "barometric".to_owned(),
750            altimeter_evidence: "invented".to_owned(),
751            era5_weather: true,
752            design: "an invented design".to_owned(),
753            weather: "invented air".to_owned(),
754            total_impulse_ns: 500.0,
755            catalog_total_impulse_ns: None,
756            reference_log: "refs/invented.csv".to_owned(),
757            reference_log_sha256: "0".repeat(64),
758            reference_rule: "invented".to_owned(),
759            log_rows: 3,
760            log_apogee_m: 1100.0,
761            log_highest_sample_m: None,
762            merged_apogee_m: 1000.0,
763            merged_height_apogee_m: 1040.0,
764            merged_apogee_error_percent: percent_of(1000.0, 1100.0),
765            hpr_apogee_m,
766            hpr_height_apogee_m: hpr_apogee_m + 40.0,
767            apogee_error_percent: percent_of(hpr_apogee_m, 1100.0),
768            revised_because: revised_because.map(str::to_owned),
769            all_inputs_traced: true,
770            untraced: Vec::new(),
771            hpr_max_mach: 0.5,
772            catalog_curve: None,
773            openrocket_stored: None,
774        }
775    }
776
777    const INVENTED: [MergedPrediction; 1] = [MergedPrediction {
778        id: "invented",
779        apogee_m: 1000.0,
780        height_apogee_m: 1040.0,
781        catalog_apogee_m: None,
782    }];
783
784    fn revision(apogee_m: f64, because: &'static str) -> Revision {
785        Revision {
786            id: "invented",
787            apogee_m,
788            height_apogee_m: apogee_m + 40.0,
789            catalog_apogee_m: None,
790            because,
791        }
792    }
793
794    /// A prediction that differs from its merged number fails unless a revision keeps both
795    /// numbers and says why ([ADR-328][adr-328] §1b); a revision without a reason, one that
796    /// states another number, one that changes nothing, and two for one flight fail too.
797    ///
798    /// [adr-328]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0328-the-2026-11-08-review-twelve-public-flights-predictions-first.md
799    #[test]
800    fn a_changed_prediction_needs_a_revision_that_keeps_both_numbers() {
801        // As merged, to the printed digit: no revision needed, none allowed to be claimed.
802        row(1000.04, None).check(&INVENTED, &[]).expect("as merged");
803        let claimed = row(1000.04, Some("a reason"))
804            .check(&INVENTED, &[])
805            .expect_err("no revision is listed");
806        assert!(claimed.contains("reason is not the one"), "{claimed}");
807
808        // Changed, with no revision: refused, and the message names the list.
809        let changed = row(1050.0, None)
810            .check(&INVENTED, &[])
811            .expect_err("a changed prediction");
812        assert!(
813            changed.contains("1050") && changed.contains("1000") && changed.contains("REVISIONS"),
814            "{changed}"
815        );
816
817        // Changed, with its revision and the reason: passes, and the merged number stays.
818        let revised = row(1050.0, Some("the fins' sweep was read from the wrong edge"));
819        let listed = [revision(
820            1050.0,
821            "the fins' sweep was read from the wrong edge",
822        )];
823        revised.check(&INVENTED, &listed).expect("revised");
824        assert_eq!(revised.merged_apogee_m, 1000.0);
825        assert!(revised.merged_apogee_error_percent < revised.apogee_error_percent);
826
827        // The row must carry the revision's reason, not another and not none.
828        for reason in [None, Some("another reason")] {
829            let error = row(1050.0, reason)
830                .check(&INVENTED, &listed)
831                .expect_err("the reason differs");
832            assert!(error.contains("reason is not the one"), "{error}");
833        }
834        // A revision with no reason.
835        let silent = row(1050.0, Some(" "))
836            .check(&INVENTED, &[revision(1050.0, " ")])
837            .expect_err("no reason");
838        assert!(silent.contains("gives no reason"), "{silent}");
839        // A revision that states a number other than the one flown.
840        let stale = row(1050.0, Some("a reason"))
841            .check(&INVENTED, &[revision(1060.0, "a reason")])
842            .expect_err("another number");
843        assert!(stale.contains("revision says 1060"), "{stale}");
844        // A revision that gives the merged numbers back.
845        let empty = row(1000.0, Some("a reason"))
846            .check(&INVENTED, &[revision(1000.0, "a reason")])
847            .expect_err("nothing changed");
848        assert!(empty.contains("changes nothing"), "{empty}");
849        // Two revisions of one flight.
850        let twice = row(1050.0, Some("a reason"))
851            .check(
852                &INVENTED,
853                &[revision(1050.0, "a reason"), revision(1050.0, "a reason")],
854            )
855            .expect_err("revised twice");
856        assert!(twice.contains("revised twice"), "{twice}");
857        // A revision of a flight that was never merged: it would revise nothing, so it is
858        // refused whichever flight is being held.
859        let stray = Revision {
860            id: "invente",
861            ..revision(1050.0, "a reason")
862        };
863        let error = row(1000.0, None)
864            .check(&INVENTED, &[stray])
865            .expect_err("a revision of no flight");
866        assert!(error.contains("`invente`, which has no merged"), "{error}");
867    }
868
869    /// The predictions' page prints a revision beside the number first merged, and prints
870    /// nothing while there is none.
871    #[test]
872    fn a_revision_is_printed_beside_the_merged_number() {
873        use crate::public_predictions::revisions_section;
874        assert_eq!(revisions_section(&INVENTED, &[]), "");
875        let section = revisions_section(&INVENTED, &[revision(1050.0, "the fins were measured.")]);
876        assert!(
877            section.starts_with("## Revised since merging\n"),
878            "{section}"
879        );
880        assert!(
881            section.contains(
882                "- **`invented`:** merged 1000.0 m, now 1050.0 m. Revised, because the fins \
883                 were measured.\n"
884            ),
885            "{section}"
886        );
887    }
888
889    /// The merged number a row keeps is the code's, and its percentages are its meters'.
890    #[test]
891    fn a_rows_merged_number_and_percentages_are_held() {
892        let mut edited = row(1000.0, None);
893        edited.merged_apogee_m = 1090.0;
894        edited.merged_apogee_error_percent = percent_of(1090.0, 1100.0);
895        let error = edited.check(&INVENTED, &[]).expect_err("an edited merge");
896        assert!(error.contains("the one merged is 1000"), "{error}");
897
898        let mut flattered = row(1000.0, None);
899        flattered.apogee_error_percent = -1.0;
900        let error = flattered.check(&INVENTED, &[]).expect_err("a wrong error");
901        assert!(error.contains("its meters give"), "{error}");
902
903        let mut shown = row(1000.0, None);
904        shown.openrocket_stored = Some(ShownOnly {
905            what: "invented".to_owned(),
906            apogee_m: 990.0,
907            apogee_error_percent: 0.0,
908        });
909        let error = shown
910            .check(&INVENTED, &[])
911            .expect_err("a wrong shown error");
912        assert!(error.contains("shown beside it"), "{error}");
913
914        let mut tagged = row(1000.0, None);
915        tagged.untraced = vec!["the mass".to_owned()];
916        let error = tagged.check(&INVENTED, &[]).expect_err("a wrong tag");
917        assert!(error.contains("traced tag"), "{error}");
918
919        // The weather is named, the impulse flown is a real one, and a catalog curve's impulse
920        // goes with a catalog curve shown, never without one.
921        let mut unnamed = row(1000.0, None);
922        unnamed.weather = " ".to_owned();
923        let error = unnamed.check(&INVENTED, &[]).expect_err("no weather");
924        assert!(error.contains("weather is not named"), "{error}");
925        let mut undesigned = row(1000.0, None);
926        undesigned.design = String::new();
927        let error = undesigned.check(&INVENTED, &[]).expect_err("no design");
928        assert!(error.contains("its design or"), "{error}");
929        let mut spent = row(1000.0, None);
930        spent.total_impulse_ns = 0.0;
931        let error = spent.check(&INVENTED, &[]).expect_err("no impulse");
932        assert!(error.contains("impulse flown"), "{error}");
933        let mut lone = row(1000.0, None);
934        lone.catalog_total_impulse_ns = Some(450.0);
935        let error = lone
936            .check(&INVENTED, &[])
937            .expect_err("an impulse without its curve");
938        assert!(error.contains("catalog curve's impulse"), "{error}");
939    }
940
941    /// The error's sign: a prediction below its log is negative.
942    #[test]
943    fn an_error_is_the_prediction_less_the_log_over_the_log() {
944        assert_eq!(percent_of(900.0, 1000.0), -10.0);
945        assert_eq!(percent_of(1100.0, 1000.0), 10.0);
946    }
947}