Skip to main content

hpr_motor/
catalog.rs

1//! An offline motor catalog: motor metadata, thrust curves, and each curve's provenance and
2//! license.
3//!
4//! [`Catalog::bundled`] is the catalog compiled into the crate: ThrustCurve.org's whole solid
5//! catalog, captured 2026-10-28, with 1,004 motors and 1,701 curve files; 80 of the motors have no
6//! file that reads, and can't fly. Every lookup reads it ([ADR-302][adr-302]). The decision record
7//! on solid motors and the first bundled catalog is [ADR-005][adr-005]. Newer curves are fetched
8//! and cached by `hpr-net`, the online layer that starts at [M5.1][m5-1].
9//!
10//! Every figure a motor lists in the bundled index comes from its curve file alone, written by
11//! `cargo xtask motor-catalog` (the rule [ADR-186][adr-186] set, issue #295). ThrustCurve.org
12//! grants no license for its API's motor records and reserves copyright. [ADR-287][adr-287] lets
13//! the project use those records as published facts, with credit, so each motor also carries its
14//! record's [`StatedFigures`], and each curve file its [`CurveCheck`] against them, the 1% rule
15//! of [ADR-005][adr-005]. A motor flies its [`CatalogMotor::default_curve`], a passing file
16//! where it has one ([ADR-298][adr-298]). [ADR-288][adr-288] plans the whole solid catalog for
17//! [M5.7][m5-7].
18//!
19//! Size, masses and delays are the file header's; total impulse, average and peak thrust and burn
20//! time are worked out from the curve by [`ThrustCurve`]'s own methods, the ones the simulator
21//! flies (the trapezoid integral and the NFPA 1125 burn window; their definitions and sources are
22//! on [`crate::curve`]). Only the
23//! names that identify a motor (ThrustCurve.org's id for it, designation, maker, single-use or
24//! reload, case, propellant) and the file's provenance (its ThrustCurve.org data-file id, who
25//! produced the data, its license and the download date) are written by hand, in the command's
26//! table.
27//!
28//! The index keeps the units motor files and catalogs use (mm, g, N·s, N, s), in fields named for
29//! them. [`CatalogMotor::motor`] converts to SI and takes the envelope (diameter, length and
30//! masses) from the index rather than the curve file's header. In the bundled index the two are
31//! the same; another index (from [`Catalog::from_json`]) can correct a header that is wrong
32//! ([Loft lesson L43][l43]: one said 75 mm for a 54 mm motor).
33//!
34//! [adr-005]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-005-solid-motors-statistics-consumption-grains-file-models-and-the-bundled-catalog-2026-09-17
35//! [adr-186]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-186-the-data-network-and-python-fixes-of-release-01-2026-10-06
36//! [adr-287]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-287-thrustcurveorgs-motor-records-used-as-published-facts-2026-10-20
37//! [adr-288]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-288-every-solid-motor-ships-in-the-package-2026-10-21
38//! [adr-298]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0298-every-solid-motor-in-four-increments.md
39//! [adr-302]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0302-every-motor-by-name.md
40//! [l43]: https://hpr.fusionspace.co/decisions-and-roadmap.html#l43
41//! [m5-1]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m5-1
42//! [m5-7]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m5-7
43
44use serde::{Deserialize, Serialize};
45
46use std::borrow::Cow;
47use std::collections::BTreeSet;
48
49use crate::bundled;
50use crate::class::ImpulseClass;
51use crate::curve::ThrustCurve;
52use crate::delay::DelayList;
53use crate::error::MotorError;
54use crate::motor::SolidMotor;
55use crate::{eng, rse};
56
57/// The bundled index's text, as a static: each use of the constant compiled apart would add
58/// another copy of its 2 MB to the binary.
59static BUNDLED_INDEX: &str = bundled::CATALOG_JSON;
60
61/// A motor catalog.
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub struct Catalog {
64    /// Where the curve files come from.
65    pub source: String,
66    /// Where and when the curve files were downloaded.
67    pub snapshot: Snapshot,
68    /// The rule that chose the curves.
69    pub selection: String,
70    /// The motors.
71    pub motors: Vec<CatalogMotor>,
72    /// The snapshot's files the index leaves out, each with its reason.
73    #[serde(default)]
74    pub left_out: Vec<LeftOut>,
75}
76
77/// A snapshot file a catalog leaves out, and why: a file whose uploader restricted it, or one
78/// that can't be read as one motor's curve.
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80pub struct LeftOut {
81    /// ThrustCurve.org's data-file id.
82    pub simfile_id: String,
83    /// ThrustCurve.org's id for the motor the file is listed under.
84    pub motor_id: String,
85    /// Why it is left out.
86    pub reason: String,
87}
88
89/// Where and when a catalog's curve files were downloaded. Each file's own URL and SHA-256 are on
90/// its [`CatalogCurve`].
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct Snapshot {
93    /// The site the files were downloaded from.
94    pub files_url: String,
95    /// The download date, `YYYY-MM-DD` (the latest, if the files were downloaded on several).
96    pub captured: String,
97}
98
99/// Whether a motor is used once or reloaded into a reusable case.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
101#[non_exhaustive]
102pub enum MotorType {
103    /// A single-use motor (ThrustCurve `SU`).
104    #[serde(rename = "SU")]
105    SingleUse,
106    /// A reload for a reusable case (ThrustCurve `reload`).
107    #[serde(rename = "reload")]
108    Reload,
109    /// A hybrid motor (ThrustCurve `hybrid`). ThrustCurve lists them; HPR Sim doesn't model them (COTS
110    /// solids only), and the bundled catalog has none.
111    #[serde(rename = "hybrid")]
112    Hybrid,
113}
114
115/// One motor's catalog entry, in the units motor files use.
116#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
117pub struct CatalogMotor {
118    /// ThrustCurve.org's id for the motor.
119    pub motor_id: String,
120    /// Manufacturer name.
121    pub manufacturer: String,
122    /// Manufacturer abbreviation.
123    pub manufacturer_abbrev: String,
124    /// Full designation, such as `1266J760-19A`.
125    pub designation: String,
126    /// Common name, such as `J760`.
127    pub common_name: String,
128    /// Impulse class letter.
129    pub impulse_class: ImpulseClass,
130    /// Single-use or reload.
131    pub motor_type: MotorType,
132    /// The case a reload fits, such as `Pro54-3G`.
133    pub case_info: Option<String>,
134    /// The propellant.
135    pub prop_info: Option<String>,
136    /// Available delays as written (`6,10,14`, `4-6`, `P`; the bundled index copies the curve
137    /// file's header); see [`CatalogMotor::delays`].
138    pub delays: Option<String>,
139    /// Diameter, mm.
140    pub diameter_mm: f64,
141    /// Length, mm.
142    pub length_mm: f64,
143    /// Total impulse, N·s ([`ThrustCurve::total_impulse_ns`] in the bundled index).
144    pub total_impulse_ns: f64,
145    /// Average thrust, N ([`ThrustCurve::average_thrust_n`] in the bundled index).
146    pub average_thrust_n: f64,
147    /// Peak thrust, N ([`ThrustCurve::peak_thrust_n`] in the bundled index).
148    pub max_thrust_n: Option<f64>,
149    /// Burn time, s ([`ThrustCurve::burn_time_s`], the NFPA 1125 window, in the bundled index).
150    pub burn_time_s: f64,
151    /// Propellant mass, g.
152    pub propellant_mass_g: Option<f64>,
153    /// Loaded mass, g.
154    pub total_mass_g: Option<f64>,
155    /// The figures ThrustCurve.org's record states for the motor, which each curve file is
156    /// checked against ([`CurveCheck`]).
157    pub stated: StatedFigures,
158    /// The motor's curves.
159    pub curves: Vec<CatalogCurve>,
160}
161
162/// The figures ThrustCurve.org's record of a motor states (its API's `totImpulseNs`,
163/// `avgThrustN`, `burnTimeS` and `maxThrustN`), copied unchanged: published facts, used with
164/// credit ([ADR-287][adr-287]). ThrustCurve.org stores them with the motor, from the certifying
165/// body or derived from its data or a curve, not worked out from each file; some are printed
166/// coarser than 1%. Its *Motor Statistics* page
167/// (<https://www.thrustcurve.org/info/motorstats.html>) defines the burn time between the
168/// 5%-of-peak crossings.
169///
170/// [adr-287]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0287-thrustcurve-orgs-motor-records-used-as-published-facts.md
171#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
172pub struct StatedFigures {
173    /// Total impulse, N·s.
174    pub total_impulse_ns: f64,
175    /// Average thrust, N.
176    pub average_thrust_n: f64,
177    /// Burn time, s.
178    pub burn_time_s: f64,
179    /// Peak thrust, N, where the record states one. No file is checked against it.
180    pub max_thrust_n: Option<f64>,
181    /// Propellant mass, g, where the record states one. A file isn't checked against it, but
182    /// flying with a propellant mass more than [`PROPELLANT_SHORT_BOUND`] less (the entry's, else
183    /// the file header's) warns ([`CatalogMotor::propellant_warning`]).
184    #[serde(default)]
185    pub propellant_mass_g: Option<f64>,
186    /// Loaded mass, g, propellant and case, where the record states one (its API's
187    /// `totalWeightG`). Flying a file whose loaded mass is more than [`LOADED_MASS_BOUND`] from it
188    /// warns ([`CatalogMotor::mass_warnings`]).
189    #[serde(default)]
190    pub total_mass_g: Option<f64>,
191}
192
193/// What a warning for flying a catalog motor's file is about
194/// ([`CatalogMotor::flight_warning_kinds`]).
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
196#[serde(rename_all = "snake_case")]
197#[non_exhaustive]
198pub enum MotorWarningKind {
199    /// The file's total impulse, average thrust or burn time is more than 1% from the record's
200    /// ([`CatalogMotor::check_warning`]).
201    FailedCheck,
202    /// The propellant mass flown is more than [`PROPELLANT_SHORT_BOUND`] below the record's
203    /// ([`CatalogMotor::propellant_warning`]).
204    LightPropellant,
205    /// The loaded mass flown is more than [`LOADED_MASS_BOUND`] above the record's.
206    HeavyLoadedMass,
207    /// The loaded mass flown is more than [`LOADED_MASS_BOUND`] below the record's.
208    LightLoadedMass,
209    /// With the loaded mass within its bound, the burnout mass is more than
210    /// [`BURNOUT_MASS_BOUND`] from the record's, either way.
211    BurnoutMass,
212    /// The propellant's share of the loaded mass is outside [`PROPELLANT_SHARE_SPAN`].
213    PropellantShare,
214}
215
216/// A warning for flying a catalog motor's file, with what it is about.
217#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
218#[non_exhaustive]
219pub struct MotorWarning {
220    /// What the warning is about.
221    pub kind: MotorWarningKind,
222    /// The warning, in words.
223    pub message: String,
224}
225
226impl MotorWarning {
227    fn new(kind: MotorWarningKind, message: String) -> Self {
228        Self { kind, message }
229    }
230}
231
232/// The masses flying a catalog file takes, g ([`CatalogMotor::flown_masses`]).
233#[derive(Debug, Clone, Copy)]
234struct FlownMasses {
235    propellant_g: f64,
236    total_g: f64,
237}
238
239/// How far a flown loaded mass may be from its motor's record, either way, as a share of the
240/// record's, before flying it warns: 5%, the bound a file's propellant mass has had since issue
241/// #578 ([`PROPELLANT_SHORT_BOUND`]). A heavy loaded mass gives too low an apogee, the side that
242/// flatters a waiver; a light one puts the center of gravity forward, so the margin after burnout
243/// reads high. Of the 840 bundled motors whose default file and record both give one, 36 are
244/// further apart than this (issue #1233); the Quest D8's file gives 454 g against 45.6 g.
245pub const LOADED_MASS_BOUND: f64 = 0.05;
246
247/// How far a flown burnout mass (loaded less propellant: the empty case) may be from its record's,
248/// either way, as a share of the record's burnout mass, before flying it warns: 5%, the share
249/// [`LOADED_MASS_BOUND`] and [`PROPELLANT_SHORT_BOUND`] hold, applied to the motor's mass after
250/// burnout. For a motor aft of the center of gravity, as on nearly every rocket, a light burnout
251/// mass puts the center of gravity forward after burnout, so the margin then reads high, the
252/// flattering side; a heavy one gives too low an apogee and too low a margin.
253///
254/// The margin it moves: a mass `Δm` missing at the motor's center of gravity moves the rocket's
255/// center of gravity forward by `Δm·(x_motor − x_cg)/(M − Δm)`, `x` measured aft from the nose and `M` the rocket's
256/// mass after burnout with the case at its record's mass, so the margin in calibers rises by that
257/// over the reference diameter. On RocketPy's Calisto (its getting-started design,
258/// `validation/designs/rocketpy-calisto-getting-started-motor-at-minus-1.255.json`, from RocketPy
259/// 1.13.0's getting-started notebook; the project's paper is G. H. Ceotto et al., "RocketPy: Six
260/// Degree-of-Freedom Rocket Trajectory Simulator", *J. Aerosp. Eng.* 34(6), 2021), whose motor
261/// inputs (RocketPy's 1.815 kg case and five grains, 4.771 kg loaded, flown on an M1378LR thrust
262/// curve) leave the case in a 16.24 kg rocket after burnout, a case 5% light raises the margin
263/// after burnout by 0.037 calibers (3.1786 to 3.2155); the earlier bound, 5% of the loaded mass
264/// (the case and the grains' 2.956 kg), let the case be 13.1% light, 0.098 calibers. A rocket whose case is a larger share
265/// of its mass after burnout, sits further aft of its center of gravity, or has a smaller reference
266/// diameter moves further in calibers (not measured here).
267pub const BURNOUT_MASS_BOUND: f64 = 0.05;
268
269/// Whether a mass gap `gap_g` is within `bound` of a record's mass `record_g`,
270/// `|gap| ≤ bound × record`; a NaN either side isn't.
271fn within_share(gap_g: f64, record_g: f64, bound: f64) -> bool {
272    gap_g.abs() <= bound * record_g
273}
274
275/// The span of propellant shares, propellant over loaded mass, that the bundled ThrustCurve.org
276/// records state: from 2.1 g of 18.2 g (Quest A3) to 0.75 (Jambol B1, Ultra B1, AMW
277/// GG-75-6000), over the 878 records giving both masses, leaving out one whose propellant is twice its loaded mass,
278/// which no motor can be. A flown share outside it warns ([`CatalogMotor::mass_warnings`]).
279pub const PROPELLANT_SHARE_SPAN: (f64, f64) = (2.1 / 18.2, 0.75);
280
281/// How far below its motor's record a file's propellant mass may be, as a share of the record's,
282/// before flying it warns: 5%, the rule a fetched file has had since issue #578 (the reasoning,
283/// with its survey, is `hpr_net::on_demand::PROPELLANT_SHORT_BOUND`'s, which is this). A light
284/// propellant mass with a right loaded mass flies too heavy a burnout mass and too low an apogee,
285/// the flattering side for a waiver; a heavy one isn't warned of.
286pub const PROPELLANT_SHORT_BOUND: f64 = 0.05;
287
288/// The relative bound of a curve file's check: each figure within 1% of the motor's stated one
289/// ([ADR-005][adr-005], [ADR-298][adr-298]).
290///
291/// [adr-005]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0005-solid-motors-statistics-consumption-grains-file.md
292/// [adr-298]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0298-every-solid-motor-in-four-increments.md
293pub const CHECK_BOUND: f64 = 0.01;
294
295/// How far, in mm, a motor named for a mount may be wider than its bore and still fit, and by how
296/// much another motor must fit more closely to make the name ambiguous
297/// ([`Catalog::find_for_bore`]): the 1 mm [`Catalog::find_for_design`] allows between a design's
298/// case and a catalog motor ([ADR-302][adr-302] §1).
299///
300/// [adr-302]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0302-every-motor-by-name.md
301pub const BORE_TOLERANCE_MM: f64 = 1.0;
302
303/// A curve file's check against its motor's [`StatedFigures`] ([ADR-005][adr-005]'s 1% rule,
304/// definition A of the ThrustCurve.org data notes): the file's total impulse over its whole
305/// curve, its NFPA 1125 burn time between the 5%-of-peak crossings, and its average thrust as
306/// that impulse over that burn time, each worked out by [`ThrustCurve`]'s own methods, the ones
307/// the simulator flies. The file passes when all three are within [`CHECK_BOUND`] of the stated
308/// figures: `|file − stated| ≤ 0.01 × stated`, so a gap of exactly 1% passes. A pass says the
309/// file agrees with the published figures; it says nothing about the curve's shape between them.
310///
311/// [adr-005]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0005-solid-motors-statistics-consumption-grains-file.md
312#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
313pub struct CurveCheck {
314    /// The file's total impulse, N·s ([`ThrustCurve::total_impulse_ns`]).
315    pub total_impulse_ns: f64,
316    /// The file's average thrust, N ([`ThrustCurve::average_thrust_n`]).
317    pub average_thrust_n: f64,
318    /// The file's burn time, s ([`ThrustCurve::burn_time_s`]).
319    pub burn_time_s: f64,
320    /// Whether all three are within [`CHECK_BOUND`] of the motor's stated figures.
321    pub passes: bool,
322}
323
324/// A figure a curve file's check compares.
325#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
326#[serde(rename_all = "snake_case")]
327#[non_exhaustive]
328pub enum CheckedFigure {
329    /// Total impulse.
330    TotalImpulse,
331    /// Average thrust.
332    AverageThrust,
333    /// Burn time.
334    BurnTime,
335}
336
337impl CheckedFigure {
338    /// The figure's name in words: `total impulse`, `average thrust`, `burn time`.
339    pub fn name(self) -> &'static str {
340        match self {
341            Self::TotalImpulse => "total impulse",
342            Self::AverageThrust => "average thrust",
343            Self::BurnTime => "burn time",
344        }
345    }
346}
347
348/// One figure of a curve file's check: the file's value and the motor's stated one.
349#[derive(Debug, Clone, Copy, PartialEq)]
350pub struct FigureGap {
351    /// Which figure.
352    pub figure: CheckedFigure,
353    /// The file's value.
354    pub file: f64,
355    /// ThrustCurve.org's stated value.
356    pub stated: f64,
357}
358
359impl FigureGap {
360    /// The signed relative gap, `(file − stated) / stated`: positive when the file's figure is
361    /// the larger.
362    pub fn relative(&self) -> f64 {
363        (self.file - self.stated) / self.stated
364    }
365
366    /// The signed gap in percent, as the warning and `hpr motors show` print it: two decimals,
367    /// and more for a figure that fails, so it never prints as within 1% (`+1.004%`, not
368    /// `+1.00%`). A failing gap so close to 1% that its quotient rounds to it prints as `>+1%` or
369    /// `<-1%`, and one against a stated figure that isn't positive as `n/a`.
370    pub fn percent_text(&self) -> String {
371        let percent = 100.0 * self.relative();
372        let mut decimals = 2;
373        let mut text = format!("{percent:+.decimals$}%");
374        if self.within_bound() {
375            return text;
376        }
377        if self.stated.is_nan() || self.stated <= 0.0 {
378            return "n/a".to_owned();
379        }
380        while decimals < 17 && rounds_inside(&text) {
381            decimals += 1;
382            text = format!("{percent:+.decimals$}%");
383        }
384        // `within_bound` compares the difference with 1% of the stated figure, and the quotient
385        // can round onto 1% when the difference is one unit past it.
386        if rounds_inside(&text) {
387            let over = if self.file > self.stated {
388                ">+1%"
389            } else {
390                "<-1%"
391            };
392            return over.to_owned();
393        }
394        text
395    }
396
397    /// Whether the file's figure is within [`CHECK_BOUND`] of the stated one,
398    /// `|file − stated| ≤ 0.01 × stated`. A stated figure that isn't positive, or a NaN either
399    /// side, fails.
400    pub fn within_bound(&self) -> bool {
401        self.stated > 0.0 && (self.file - self.stated).abs() <= CHECK_BOUND * self.stated
402    }
403}
404
405/// Whether a signed percentage as text (`+1.00%`) reads as within 1%.
406fn rounds_inside(text: &str) -> bool {
407    text.trim_start_matches(['+', '-'])
408        .trim_end_matches('%')
409        .parse::<f64>()
410        .is_ok_and(|magnitude| magnitude <= 100.0 * CHECK_BOUND)
411}
412
413impl CurveCheck {
414    /// The check of a curve against a motor's stated figures.
415    pub fn of(thrust: &ThrustCurve, stated: &StatedFigures) -> Self {
416        let mut check = Self {
417            total_impulse_ns: thrust.total_impulse_ns(),
418            average_thrust_n: thrust.average_thrust_n(),
419            burn_time_s: thrust.burn_time_s(),
420            passes: false,
421        };
422        check.passes = check.gaps(stated).iter().all(FigureGap::within_bound);
423        check
424    }
425
426    /// The three figures against `stated`: total impulse, average thrust, burn time.
427    pub fn gaps(&self, stated: &StatedFigures) -> [FigureGap; 3] {
428        [
429            FigureGap {
430                figure: CheckedFigure::TotalImpulse,
431                file: self.total_impulse_ns,
432                stated: stated.total_impulse_ns,
433            },
434            FigureGap {
435                figure: CheckedFigure::AverageThrust,
436                file: self.average_thrust_n,
437                stated: stated.average_thrust_n,
438            },
439            FigureGap {
440                figure: CheckedFigure::BurnTime,
441                file: self.burn_time_s,
442                stated: stated.burn_time_s,
443            },
444        ]
445    }
446}
447
448/// Where a thrust curve came from, under what terms, and how it compares with its motor's stated
449/// figures.
450#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
451pub struct CatalogCurve {
452    /// ThrustCurve's simfile id.
453    pub simfile_id: String,
454    /// The file format.
455    pub format: CurveFormat,
456    /// Who produced the data.
457    pub source: CurveSource,
458    /// The data license.
459    #[serde(default)]
460    pub license: CurveLicense,
461    /// The file's path relative to the catalog index.
462    pub file: String,
463    /// SHA-256 of the file's bytes, hex.
464    pub sha256: String,
465    /// Where the file was downloaded from.
466    pub url: String,
467    /// ThrustCurve's page for the file.
468    pub info_url: Option<String>,
469    /// The download date, `YYYY-MM-DD`.
470    pub retrieved: String,
471    /// The file's check against its motor's stated figures, worked out when the index is written.
472    pub check: CurveCheck,
473}
474
475/// A thrust-curve file format.
476#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
477#[non_exhaustive]
478pub enum CurveFormat {
479    /// RASP `.eng`.
480    #[serde(rename = "RASP")]
481    Rasp,
482    /// RockSim `.rse`.
483    #[serde(rename = "RockSim")]
484    RockSim,
485}
486
487/// Who produced a curve (ThrustCurve's `source`).
488#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
489#[non_exhaustive]
490pub enum CurveSource {
491    /// A certification body's test data.
492    #[serde(rename = "cert")]
493    Certification,
494    /// The manufacturer.
495    #[serde(rename = "mfr")]
496    Manufacturer,
497    /// A ThrustCurve user.
498    #[serde(rename = "user")]
499    User,
500}
501
502/// A curve's data license, as ThrustCurve records it. ThrustCurve's API leaves the key out when no
503/// license is recorded, which reads as [`CurveLicense::Unknown`].
504#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
505#[non_exhaustive]
506pub enum CurveLicense {
507    /// Public domain.
508    #[serde(rename = "PD")]
509    PublicDomain,
510    /// "Free": by ThrustCurve's definition this includes GPL and Creative Commons terms.
511    #[serde(rename = "free")]
512    Free,
513    /// Other, restricted terms.
514    #[serde(rename = "other")]
515    Other,
516    /// No license recorded.
517    #[default]
518    #[serde(rename = "unknown", alias = "")]
519    Unknown,
520}
521
522impl CurveLicense {
523    /// Whether a curve under this license is bundled: every one but a file its uploader marked
524    /// "other", restricted ([ADR-288][adr-288] §1). A file's measured points are used as facts,
525    /// as ThrustCurve.org's records are ([ADR-287]); free-usage files and files with no license
526    /// go in like the rest, each with its label kept beside it ([ADR-288][adr-288] §2).
527    ///
528    /// [ADR-287]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0287-thrustcurve-orgs-motor-records-used-as-published-facts.md
529    ///
530    /// [adr-288]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0288-every-solid-motor-ships-in-the-package.md
531    pub fn is_bundleable(self) -> bool {
532        self != Self::Other
533    }
534}
535
536impl Catalog {
537    /// The catalog compiled into this crate, which `hpr motors`, `hpr sim --motor` and a design's
538    /// motors are looked up in: ThrustCurve.org's whole solid catalog ([M5.7][m5-7]), every solid
539    /// motor in the snapshot and every file but a restricted one, each with its stored check, and
540    /// each file left out with its reason ([ADR-301][adr-301]).
541    ///
542    /// [m5-7]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m5-7
543    /// [adr-301]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0301-the-whole-catalog-in-two-increments.md
544    ///
545    /// # Errors
546    ///
547    /// [`MotorError::Catalog`] if the index doesn't deserialize, which a test rules out.
548    pub fn bundled() -> Result<&'static Self, MotorError> {
549        // Read once and shared: the index of every solid motor is a few megabytes of JSON.
550        static BUNDLED: std::sync::OnceLock<Result<Catalog, MotorError>> =
551            std::sync::OnceLock::new();
552        BUNDLED
553            .get_or_init(|| Self::from_json(BUNDLED_INDEX))
554            .as_ref()
555            .map_err(Clone::clone)
556    }
557
558    /// Reads a catalog index.
559    ///
560    /// # Errors
561    ///
562    /// [`MotorError::Catalog`] if the text isn't a catalog index, or a curve's stored
563    /// [`CurveCheck::passes`] isn't what its stored figures give against its motor's stated ones:
564    /// the flag ranks the files, so one that says a failing file passes would fly it silently.
565    pub fn from_json(text: &str) -> Result<Self, MotorError> {
566        let catalog: Self =
567            serde_json::from_str(text).map_err(|error| MotorError::Catalog(error.to_string()))?;
568        catalog.motors.iter().try_for_each(stored_passes_hold)?;
569        Ok(catalog)
570    }
571
572    /// The bundled catalog holding only the motors `name` lookups can find: those whose
573    /// designation or common name is one of `names`, ignoring ASCII case, spaces and hyphens.
574    ///
575    /// [`Catalog::find_for_design`] answers each of `names` here as it does in
576    /// [`Catalog::bundled`], which reading a design needs. Nothing else is promised: a listing of
577    /// this catalog is not the catalog's. It isn't shared either: each call reads the index again.
578    ///
579    /// # Errors
580    ///
581    /// As [`Catalog::from_json`], for the motors kept (the bundled index's tests read them all).
582    pub fn bundled_named<'a>(names: impl IntoIterator<Item = &'a str>) -> Result<Self, MotorError> {
583        let keys: BTreeSet<String> = names.into_iter().map(normalize).collect();
584        Self::narrowed(BUNDLED_INDEX, &|motor| {
585            keys.iter().any(|key| {
586                normalized_is(&motor.designation, key) || normalized_is(&motor.common_name, key)
587            })
588        })
589    }
590
591    /// The bundled catalog holding only the motors with one of `ids`, as
592    /// [`Catalog::bundled_named`] holds those of its names.
593    ///
594    /// # Errors
595    ///
596    /// As [`Catalog::from_json`], for the motors kept.
597    pub fn bundled_with_ids<'a>(
598        ids: impl IntoIterator<Item = &'a str>,
599    ) -> Result<Self, MotorError> {
600        let ids: BTreeSet<&str> = ids.into_iter().collect();
601        Self::narrowed(BUNDLED_INDEX, &|motor| {
602            ids.contains(motor.motor_id.as_ref())
603        })
604    }
605
606    /// The bundled catalog's [`Snapshot`], without reading its motors: every `hpr sim` states the
607    /// catalog's date, whether a motor came from it or not.
608    ///
609    /// # Errors
610    ///
611    /// As [`Catalog::bundled`], when the index's head can't be read alone and the whole is read.
612    pub fn bundled_snapshot() -> Result<Snapshot, MotorError> {
613        match snapshot_in_head(BUNDLED_INDEX) {
614            Some(snapshot) => Ok(snapshot),
615            None => Self::bundled().map(|catalog| catalog.snapshot.clone()),
616        }
617    }
618
619    /// Reads a catalog index as JSON's pretty writer lays it out, as the bundled one is, building
620    /// only the motors `keep` takes. The others cost a look at their lines, 0.45 ms for the bundled
621    /// index against 1.65 ms to parse it whole, and no memory. A test holds the bundled index to
622    /// this reading of it.
623    fn narrowed(text: &str, keep: &dyn Fn(&MotorKeys<'_>) -> bool) -> Result<Self, MotorError> {
624        let invalid = |what: String| MotorError::Catalog(what);
625        let not_laid_out =
626            || invalid("the index isn't laid out as JSON's pretty writer does".to_owned());
627        let (head, rest) = text.split_once("\"motors\":").ok_or_else(not_laid_out)?;
628        let head = format!(
629            "{}}}",
630            head.trim_end().strip_suffix(',').ok_or_else(not_laid_out)?
631        );
632        let head: IndexHead =
633            serde_json::from_str(&head).map_err(|error| invalid(error.to_string()))?;
634        let mut motors = Vec::new();
635        // No line of a motor but its own last starts `    }`: its fields are indented further and
636        // a JSON string can't hold a line break. The search is `memchr`'s: with `str`'s, this read
637        // took 1.44 ms.
638        const END: &str = "\n    }";
639        let ends = memchr::memmem::Finder::new(END);
640        let mut left = rest;
641        loop {
642            // A list with no end isn't read as a shorter one, nor as none.
643            let end = ends.find(left.as_bytes()).ok_or_else(not_laid_out)?;
644            let entry = left
645                .find('{')
646                .and_then(|start| left.get(start..end + END.len()))
647                .ok_or_else(not_laid_out)?;
648            let keys = MotorKeys::in_lines(entry).ok_or_else(not_laid_out)?;
649            if keep(&keys) {
650                let motor: CatalogMotor =
651                    serde_json::from_str(entry).map_err(|error| invalid(error.to_string()))?;
652                stored_passes_hold(&motor)?;
653                motors.push(motor);
654            }
655            left = &left[end + END.len()..];
656            // A comma ahead of the next motor; anything else closes the list.
657            if !left.starts_with(',') {
658                break;
659            }
660        }
661        Ok(Self {
662            source: head.source,
663            snapshot: head.snapshot,
664            selection: head.selection,
665            motors,
666            left_out: Vec::new(),
667        })
668    }
669
670    /// The motors `name` names ([ADR-302][adr-302]): those whose designation or common name
671    /// matches it, ignoring ASCII case, spaces and hyphens (`j760`, `1266J760-19A`, `K 940`).
672    ///
673    /// - A name may start with a maker, its full name or short one and a space, such as
674    ///   `AeroTech H128W` or `Estes Industries C6`: then only that maker's motors match.
675    /// - Of one maker's matches, a motor whose designation is the name is the one it names: `D5`
676    ///   is Quest's D5, not the D5-P whose common name is D5. Matches of different makers all
677    ///   stay, whether by designation or common name: `G80` finds Roadrunner's and Estes' G80 and
678    ///   AeroTech's G80T, so a caller that wants one refuses it as ambiguous rather than flying a
679    ///   maker the name didn't say. Each maker's short name and designation names one alone, as
680    ///   no maker has two motors of one designation (a test holds it).
681    ///
682    /// [adr-302]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0302-every-motor-by-name.md
683    pub fn find<'a>(&'a self, name: &str) -> impl Iterator<Item = &'a CatalogMotor> + 'a {
684        let (maker, rest) = self.maker_and_name(name);
685        self.named(rest, |motor| {
686            maker.is_none_or(|maker| maker == motor.manufacturer)
687        })
688    }
689
690    /// As [`Catalog::find`], among the motors of the maker `maker` names, by its full or short
691    /// name with only its ASCII letters and digits compared, ignoring case (`Cesaroni
692    /// Technology Inc.` is Cesaroni Technology's, `AEROTECH` AeroTech's): the lookup a design
693    /// file's motor, which names its maker apart, takes.
694    pub fn find_by_maker<'a>(
695        &'a self,
696        maker: &str,
697        name: &str,
698    ) -> impl Iterator<Item = &'a CatalogMotor> + 'a {
699        let maker = maker_key(maker);
700        self.named(name, move |motor| {
701            maker_key(&motor.manufacturer) == maker
702                || maker_key(&motor.manufacturer_abbrev) == maker
703        })
704    }
705
706    /// As [`Catalog::find_by_maker`], for a design file's motor, which may also give its curve's
707    /// `digest` and its case's `diameter_mm`. Cesaroni's 54 mm `1016J360-15A` has the common
708    /// name `J360`, which is the designation of a 38 mm Cesaroni motor; a file that saved the
709    /// first as `J360` must not fly the second, about 20% short on impulse:
710    ///
711    /// - where `digest` maps to a bundled file ([`crate::openrocket_curves::file_for`]) of
712    ///   exactly one motor the name matches by designation or common name, that motor alone;
713    /// - else, where every motor [`Catalog::find_by_maker`] gives is more than 1 mm from
714    ///   `diameter_mm` and another the name matches is within it, every match, so the caller
715    ///   refuses the motor as ambiguous rather than flying a case the design doesn't hold.
716    pub fn find_for_design<'a>(
717        &'a self,
718        maker: &str,
719        name: &str,
720        digest: Option<&str>,
721        diameter_mm: Option<f64>,
722    ) -> Vec<&'a CatalogMotor> {
723        let maker = maker_key(maker);
724        let of = |motor: &CatalogMotor| {
725            maker_key(&motor.manufacturer) == maker
726                || maker_key(&motor.manufacturer_abbrev) == maker
727        };
728        let all = self.matching(name, of);
729        if let Some(id) = digest.and_then(crate::openrocket_curves::file_for) {
730            let owners: Vec<&CatalogMotor> = all
731                .iter()
732                .copied()
733                .filter(|motor| motor.curves.iter().any(|curve| curve.simfile_id == id))
734                .collect();
735            if let [owner] = owners[..] {
736                return vec![owner];
737            }
738        }
739        let picked = prefer_designations(all.clone(), name);
740        let fits = |motor: &&CatalogMotor| {
741            diameter_mm.is_some_and(|mm| (motor.diameter_mm - mm).abs() <= 1.0)
742        };
743        let misfit = diameter_mm.is_some() && !picked.iter().any(fits);
744        if misfit
745            && all
746                .iter()
747                .any(|motor| fits(motor) && !picked.iter().any(|kept| std::ptr::eq(*kept, *motor)))
748        {
749            return all;
750        }
751        picked
752    }
753
754    /// As [`Catalog::find`], for a motor named by hand to go into a mount whose bore is `bore_mm`
755    /// across. It follows the diameter guard of [ADR-302][adr-302] §1, on looking a motor up by
756    /// name, which [`Catalog::find_for_design`] applies to a design file's motor against the file's
757    /// case diameter; here it is measured against the mount's bore. Where another motor the name matches, by designation or
758    /// common name, fits the bore more closely by more than [`BORE_TOLERANCE_MM`] than every motor
759    /// [`Catalog::find`] gives (or where none of those fits and another does), every match, so the
760    /// caller refuses the name as ambiguous; else what [`Catalog::find`] gives. A motor fits when
761    /// it is no wider than the bore and the tolerance; the closer fit leaves less room around it.
762    /// So `J360` in a 54 mm mount names both Cesaroni's 38 mm `J360` and its 54 mm `1016J360-15A`,
763    /// and in a 38 mm mount the `J360` alone.
764    ///
765    /// [adr-302]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0302-every-motor-by-name.md
766    pub fn find_for_bore<'a>(&'a self, name: &str, bore_mm: f64) -> Vec<&'a CatalogMotor> {
767        let (maker, rest) = self.maker_and_name(name);
768        let all = self.matching(rest, |motor| {
769            maker.is_none_or(|maker| maker == motor.manufacturer)
770        });
771        let picked = prefer_designations(all.clone(), rest);
772        let room = |motor: &CatalogMotor| {
773            (motor.diameter_mm <= bore_mm + BORE_TOLERANCE_MM)
774                .then_some(bore_mm - motor.diameter_mm)
775        };
776        let best = picked
777            .iter()
778            .filter_map(|motor| room(motor))
779            .fold(f64::INFINITY, f64::min);
780        let closer = all.iter().any(|motor| {
781            !picked.iter().any(|kept| std::ptr::eq(*kept, *motor))
782                && room(motor).is_some_and(|room| room + BORE_TOLERANCE_MM < best)
783        });
784        if closer { all } else { picked }
785    }
786
787    /// The motors `of` keeps whose designation or common name is `name`, narrowed as
788    /// [`Catalog::find`] says: within one maker, those whose designation is the name if any is.
789    fn named<'a>(
790        &'a self,
791        name: &str,
792        of: impl Fn(&CatalogMotor) -> bool,
793    ) -> std::vec::IntoIter<&'a CatalogMotor> {
794        prefer_designations(self.matching(name, of), name).into_iter()
795    }
796
797    /// Every motor `of` keeps whose designation or common name is `name`.
798    fn matching(&self, name: &str, of: impl Fn(&CatalogMotor) -> bool) -> Vec<&CatalogMotor> {
799        let key = normalize(name);
800        self.motors
801            .iter()
802            .filter(|motor| {
803                of(motor)
804                    && (normalized_is(&motor.designation, &key)
805                        || normalized_is(&motor.common_name, &key))
806            })
807            .collect()
808    }
809
810    /// The maker `name` starts with, by full or short name, followed by a space, and the rest of
811    /// the name; or no maker and the whole name. The longest maker's name that fits is taken.
812    fn maker_and_name<'a>(&'a self, name: &'a str) -> (Option<&'a str>, &'a str) {
813        let name = name.trim();
814        let mut best: Option<(&str, &str, usize)> = None;
815        for motor in &self.motors {
816            for said in [&motor.manufacturer, &motor.manufacturer_abbrev] {
817                let Some(head) = name.get(..said.len()) else {
818                    continue;
819                };
820                let rest = &name[said.len()..];
821                if head.eq_ignore_ascii_case(said)
822                    && rest.starts_with(char::is_whitespace)
823                    && best.is_none_or(|(_, _, length)| said.len() > length)
824                {
825                    best = Some((motor.manufacturer.as_str(), rest.trim_start(), said.len()));
826                }
827            }
828        }
829        best.map_or((None, name), |(maker, rest, _)| (Some(maker), rest))
830    }
831
832    /// The name that selects `motor` alone through [`Catalog::find`]: its designation where that
833    /// finds it alone, else its maker's short name and its designation, such as `Estes C6`.
834    pub fn selector(&self, motor: &CatalogMotor) -> String {
835        let alone = self.find(&motor.designation).count() == 1;
836        if alone {
837            motor.designation.clone()
838        } else {
839            format!("{} {}", motor.manufacturer_abbrev, motor.designation)
840        }
841    }
842}
843
844/// Of `matches` for `name`, each maker's motors whose designation is the name where that maker
845/// has one, and the rest of its matches where it hasn't: a name never picks one maker over
846/// another.
847fn prefer_designations<'a>(matches: Vec<&'a CatalogMotor>, name: &str) -> Vec<&'a CatalogMotor> {
848    let key = normalize(name);
849    let exact = |motor: &CatalogMotor| normalize(&motor.designation) == key;
850    let makers_with_exact: Vec<&str> = matches
851        .iter()
852        .filter(|motor| exact(motor))
853        .map(|motor| motor.manufacturer.as_str())
854        .collect();
855    matches
856        .into_iter()
857        .filter(|motor| exact(motor) || !makers_with_exact.contains(&motor.manufacturer.as_str()))
858        .collect()
859}
860
861/// A maker's name with only its ASCII letters and digits, lowercase, and a trailing company
862/// suffix (`Inc`, `Ltd`, `LLC`) dropped: `Cesaroni Technology Inc.` compares as Cesaroni
863/// Technology.
864fn maker_key(text: &str) -> String {
865    let key: String = text
866        .chars()
867        .filter(char::is_ascii_alphanumeric)
868        .map(|c| c.to_ascii_lowercase())
869        .collect();
870    ["inc", "ltd", "llc"]
871        .iter()
872        .find_map(|suffix| key.strip_suffix(suffix).filter(|rest| !rest.is_empty()))
873        .map_or_else(|| key.clone(), str::to_owned)
874}
875
876/// Whether `normalize(name)` is `key`, without building it: a lookup compares every motor's two
877/// names, and `hpr motors list` looks each listed motor's selector up, so building them made the
878/// listing quadratic in allocations (51.7 ms for 1,004 motors; 12.5 ms without).
879fn normalized_is(name: &str, key: &str) -> bool {
880    name.chars()
881        .filter(|c| !c.is_whitespace() && *c != '-')
882        .map(|c| c.to_ascii_lowercase())
883        .eq(key.chars())
884}
885
886/// The snapshot of an index that states it ahead of its motors, read from the text before them;
887/// `None` for any other index, which has to be read whole.
888fn snapshot_in_head(text: &str) -> Option<Snapshot> {
889    #[derive(Deserialize)]
890    struct Head {
891        snapshot: Snapshot,
892    }
893    let (head, _) = text.split_once("\"motors\":")?;
894    let head = format!("{}}}", head.trim_end().strip_suffix(',')?);
895    serde_json::from_str::<Head>(&head)
896        .ok()
897        .map(|head| head.snapshot)
898}
899
900/// What an index states ahead of its motors ([`Catalog::narrowed`]).
901#[derive(Deserialize)]
902struct IndexHead {
903    source: String,
904    snapshot: Snapshot,
905    selection: String,
906}
907
908/// What [`Catalog::narrowed`] decides on, read from an unbuilt motor's lines. `Cow`, as a name with
909/// an escape in it can't be borrowed from the text.
910struct MotorKeys<'a> {
911    motor_id: Cow<'a, str>,
912    designation: Cow<'a, str>,
913    common_name: Cow<'a, str>,
914}
915
916impl<'a> MotorKeys<'a> {
917    /// The keys in a motor's text, each on its own line as the motor's own field.
918    fn in_lines(entry: &'a str) -> Option<Self> {
919        let field = |key: &str| -> Option<Cow<'a, str>> {
920            let (_, value) = entry.split_once(key)?;
921            let line = value.split('\n').next()?;
922            let line = line.strip_suffix(',').unwrap_or(line);
923            if line.contains('\\') {
924                return serde_json::from_str::<String>(line).ok().map(Cow::Owned);
925            }
926            line.strip_prefix('"')?.strip_suffix('"').map(Cow::Borrowed)
927        };
928        Some(Self {
929            motor_id: field("\n      \"motor_id\": ")?,
930            designation: field("\n      \"designation\": ")?,
931            common_name: field("\n      \"common_name\": ")?,
932        })
933    }
934}
935
936/// Refuses a motor whose curve stores a pass its figures contradict ([`Catalog::from_json`]).
937fn stored_passes_hold(motor: &CatalogMotor) -> Result<(), MotorError> {
938    for curve in &motor.curves {
939        let passes = curve
940            .check
941            .gaps(&motor.stated)
942            .iter()
943            .all(FigureGap::within_bound);
944        if passes != curve.check.passes {
945            return Err(MotorError::Catalog(format!(
946                "{}'s curve {} stores passes: {}, but its figures give {passes}",
947                motor.designation, curve.simfile_id, curve.check.passes
948            )));
949        }
950    }
951    Ok(())
952}
953
954/// Lowercase, without spaces or hyphens.
955fn normalize(name: &str) -> String {
956    name.chars()
957        .filter(|c| !c.is_whitespace() && *c != '-')
958        .map(|c| c.to_ascii_lowercase())
959        .collect()
960}
961
962/// A curve file's thrust curve and its header's propellant and loaded masses, kg.
963fn read_curve_file(
964    curve: &CatalogCurve,
965    text: &str,
966) -> Result<(ThrustCurve, f64, f64), MotorError> {
967    let one = |count: usize| {
968        if count == 1 {
969            Ok(())
970        } else {
971            Err(MotorError::Inconsistent(format!(
972                "the curve file {} holds {count} motors, not one",
973                curve.file
974            )))
975        }
976    };
977    match curve.format {
978        CurveFormat::Rasp => {
979            let file = eng::parse(text)?.value;
980            one(file.entries.len())?;
981            let entry = &file.entries[0];
982            Ok((
983                entry.thrust_curve()?,
984                entry.propellant_mass_kg,
985                entry.total_mass_kg,
986            ))
987        }
988        CurveFormat::RockSim => {
989            let file = rse::parse(text)?.value;
990            one(file.engines.len())?;
991            let engine = &file.engines[0];
992            Ok((
993                engine.thrust_curve()?,
994                engine.propellant_mass_g * 1e-3,
995                engine.initial_mass_g * 1e-3,
996            ))
997        }
998    }
999}
1000
1001/// How many motors and files a catalog holds, and how many of them pass their check: the figures
1002/// `cargo xtask motor-catalog` and `hpr motors update` print for the bundled catalog.
1003#[non_exhaustive]
1004#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1005pub struct CatalogCounts {
1006    /// Every motor listed.
1007    pub motors: usize,
1008    /// The motors with a file that reads, which fly.
1009    pub motors_flying: usize,
1010    /// The files indexed.
1011    pub files: usize,
1012    /// The snapshot's files the index leaves out, each with its reason ([`Catalog::left_out`]).
1013    pub left_out: usize,
1014    /// The files whose [`CurveCheck::passes`].
1015    pub files_passing: usize,
1016    /// The motors with at least one passing file.
1017    pub motors_passing: usize,
1018}
1019
1020impl Catalog {
1021    /// Its [`CatalogCounts`].
1022    #[must_use]
1023    pub fn counts(&self) -> CatalogCounts {
1024        let curves = || self.motors.iter().flat_map(|m| &m.curves);
1025        CatalogCounts {
1026            motors: self.motors.len(),
1027            motors_flying: self.motors.iter().filter(|m| !m.curves.is_empty()).count(),
1028            files: curves().count(),
1029            left_out: self.left_out.len(),
1030            files_passing: curves().filter(|c| c.check.passes).count(),
1031            motors_passing: self
1032                .motors
1033                .iter()
1034                .filter(|m| m.curves.iter().any(|c| c.check.passes))
1035                .count(),
1036        }
1037    }
1038}
1039
1040/// The bytes of data compiled into the crate for [`Catalog::bundled`]: the index and every curve
1041/// file it reads, as UTF-8 text. It counts the data alone, not the code that reads it; how much a
1042/// binary grows by it isn't measured.
1043#[must_use]
1044pub fn bundled_size_bytes() -> usize {
1045    bundled::CATALOG_JSON.len()
1046        + bundled::CURVE_FILES
1047            .iter()
1048            .map(|(_, text)| text.len())
1049            .sum::<usize>()
1050}
1051
1052/// The text of a bundled curve file, by its path in the bundled index.
1053pub fn bundled_curve_text(file: &str) -> Option<&'static str> {
1054    bundled::CURVE_FILES
1055        .iter()
1056        .find(|(path, _)| *path == file)
1057        .map(|(_, text)| *text)
1058}
1059
1060impl CatalogMotor {
1061    /// The delay settings read from [`CatalogMotor::delays`]; empty when none are recorded.
1062    pub fn delays(&self) -> DelayList {
1063        DelayList::parse(self.delays.as_deref().unwrap_or(""))
1064    }
1065
1066    /// Reads a curve of this motor from its file's text.
1067    ///
1068    /// # Errors
1069    ///
1070    /// - [`MotorError::Inconsistent`] if `curve` is not one of this motor's curves, or the file
1071    ///   doesn't hold exactly one motor.
1072    /// - The format's parse error ([`eng::parse`], [`rse::parse`]).
1073    /// - [`ThrustCurve::new`]'s errors.
1074    pub fn thrust_curve(
1075        &self,
1076        curve: &CatalogCurve,
1077        text: &str,
1078    ) -> Result<ThrustCurve, MotorError> {
1079        self.check_own(curve)?;
1080        read_curve_file(curve, text).map(|(thrust, _, _)| thrust)
1081    }
1082
1083    /// Refuses a curve listed under another motor, which would pair this motor's masses and
1084    /// envelope with the wrong thrust.
1085    fn check_own(&self, curve: &CatalogCurve) -> Result<(), MotorError> {
1086        if self.curves.contains(curve) {
1087            Ok(())
1088        } else {
1089            Err(MotorError::Inconsistent(format!(
1090                "curve {} is not one of {}'s curves",
1091                curve.simfile_id, self.designation
1092            )))
1093        }
1094    }
1095
1096    /// The motor with the curve read from `text`, built with [`SolidMotor::from_envelope`] from
1097    /// this entry's diameter, length and masses. The curve file's header is used only for a mass
1098    /// the metadata lacks.
1099    ///
1100    /// # Errors
1101    ///
1102    /// As [`CatalogMotor::thrust_curve`] and [`SolidMotor::from_envelope`], and
1103    /// [`MotorError::Inconsistent`] for a hybrid (HPR Sim models solids only) or when neither the
1104    /// metadata nor the file gives the masses. The text is not checked against the curve's SHA-256:
1105    /// pass the file the curve names.
1106    pub fn motor(&self, curve: &CatalogCurve, text: &str) -> Result<SolidMotor, MotorError> {
1107        if self.motor_type == MotorType::Hybrid {
1108            return Err(MotorError::Inconsistent(format!(
1109                "{} is a hybrid; HPR Sim models solid motors only",
1110                self.designation
1111            )));
1112        }
1113        self.check_own(curve)?;
1114        let (thrust, header_propellant_kg, header_total_kg) = read_curve_file(curve, text)?;
1115        let propellant_kg = self
1116            .propellant_mass_g
1117            .map_or(header_propellant_kg, |g| g * 1e-3);
1118        let total_kg = self.total_mass_g.map_or(header_total_kg, |g| g * 1e-3);
1119        if !(propellant_kg > 0.0 && total_kg > 0.0) {
1120            return Err(MotorError::Inconsistent(format!(
1121                "{} has no propellant and loaded masses",
1122                self.designation
1123            )));
1124        }
1125        SolidMotor::from_envelope(
1126            thrust,
1127            self.diameter_mm * 1e-3,
1128            self.length_mm * 1e-3,
1129            propellant_kg,
1130            total_kg,
1131        )
1132    }
1133
1134    /// The motor with its default curve ([`CatalogMotor::default_curve`]).
1135    ///
1136    /// # Errors
1137    ///
1138    /// [`MotorError::Inconsistent`] if the entry has no bundled curve file, and
1139    /// [`CatalogMotor::motor`]'s errors.
1140    pub fn bundled_motor(&self) -> Result<SolidMotor, MotorError> {
1141        let (curve, text) = self.default_curve_text().ok_or_else(|| {
1142            MotorError::Inconsistent(format!("{} has no bundled curve", self.designation))
1143        })?;
1144        self.motor(curve, text)
1145    }
1146
1147    /// The motor's curves in the order its default is taken ([ADR-298][adr-298] §5): a file
1148    /// whose check passes first, then the order [ADR-154][adr-154] fetches in, RASP before
1149    /// RockSim, each ranked by who measured it (a certification test, the maker, then a user),
1150    /// the index's order within a rank.
1151    ///
1152    /// [adr-154]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0154-motors-fetched-from-thrustcurve-by-name.md
1153    /// [adr-298]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0298-every-solid-motor-in-four-increments.md
1154    pub fn ranked_curves(&self) -> Vec<&CatalogCurve> {
1155        let mut curves: Vec<&CatalogCurve> = self.curves.iter().collect();
1156        // Stable: within a rank, the index's order.
1157        curves.sort_by_key(|curve| {
1158            let format = match curve.format {
1159                CurveFormat::Rasp => 0,
1160                CurveFormat::RockSim => 1,
1161            };
1162            let source = match curve.source {
1163                CurveSource::Certification => 0,
1164                CurveSource::Manufacturer => 1,
1165                CurveSource::User => 2,
1166            };
1167            (!curve.check.passes, format, source)
1168        });
1169        curves
1170    }
1171
1172    /// The curve a flight takes when none is named: the first of
1173    /// [`CatalogMotor::ranked_curves`] whose file is bundled, so a passing file where one is.
1174    pub fn default_curve(&self) -> Option<&CatalogCurve> {
1175        self.default_curve_text().map(|(curve, _)| curve)
1176    }
1177
1178    /// The curve a design file's motor flies, with its bundled file's text: the file OpenRocket's
1179    /// curve for `digest` maps to ([`crate::openrocket_curves::file_for`]) where it is one of this
1180    /// motor's bundled files ([ADR-288][adr-288] §3), else [`CatalogMotor::default_curve`].
1181    ///
1182    /// [adr-288]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0288-every-solid-motor-ships-in-the-package.md
1183    pub fn curve_for_digest(&self, digest: Option<&str>) -> Option<(&CatalogCurve, &'static str)> {
1184        let mapped = digest.and_then(crate::openrocket_curves::file_for);
1185        mapped
1186            .and_then(|id| {
1187                let curve = self.curves.iter().find(|curve| curve.simfile_id == id)?;
1188                Some((curve, bundled_curve_text(&curve.file)?))
1189            })
1190            .or_else(|| self.default_curve_text())
1191    }
1192
1193    /// [`CatalogMotor::default_curve`] with its bundled file's text.
1194    pub fn default_curve_text(&self) -> Option<(&CatalogCurve, &'static str)> {
1195        self.ranked_curves()
1196            .into_iter()
1197            .find_map(|curve| Some((curve, bundled_curve_text(&curve.file)?)))
1198    }
1199
1200    /// The figures of `curve`'s check outside [`CHECK_BOUND`] of this motor's stated ones, in the
1201    /// order total impulse, average thrust, burn time; empty when the file passes.
1202    pub fn failing_figures(&self, curve: &CatalogCurve) -> Vec<FigureGap> {
1203        curve
1204            .check
1205            .gaps(&self.stated)
1206            .into_iter()
1207            .filter(|gap| !gap.within_bound())
1208            .collect()
1209    }
1210
1211    /// The warning for flying `curve` when the propellant mass it flies with (the entry's, else
1212    /// its header's; [`CatalogMotor::motor`]) is more than [`PROPELLANT_SHORT_BOUND`] below the
1213    /// record's, naming both masses and the gap; `None` when
1214    /// it isn't (a file exactly at the bound draws none), when the record states no propellant
1215    /// mass, or when the file isn't bundled or doesn't read.
1216    pub fn propellant_warning(&self, curve: &CatalogCurve) -> Option<String> {
1217        self.propellant_warning_for(curve, &self.flown_masses(curve)?)
1218    }
1219
1220    /// The masses flying `curve` takes ([`CatalogMotor::motor`]), read from its file once: the
1221    /// entry's, which are its default file's, where it gives them, else the file header's, so a
1222    /// file other than the default is held to the masses it flies with. `None` when the file
1223    /// isn't bundled or doesn't read.
1224    fn flown_masses(&self, curve: &CatalogCurve) -> Option<FlownMasses> {
1225        let text = bundled_curve_text(&curve.file)?;
1226        let (_, propellant_kg, total_kg) = read_curve_file(curve, text).ok()?;
1227        Some(FlownMasses {
1228            propellant_g: self.propellant_mass_g.unwrap_or(propellant_kg * 1000.0),
1229            total_g: self.total_mass_g.unwrap_or(total_kg * 1000.0),
1230        })
1231    }
1232
1233    /// [`CatalogMotor::propellant_warning`] on masses already read.
1234    fn propellant_warning_for(&self, curve: &CatalogCurve, masses: &FlownMasses) -> Option<String> {
1235        let record_g = self
1236            .stated
1237            .propellant_mass_g
1238            .filter(|g| g.is_finite() && *g > 0.0)?;
1239        let flown_g = masses.propellant_g;
1240        // Compared as masses, so a mass exactly at the bound doesn't warn; a NaN warns.
1241        if flown_g >= record_g * (1.0 - PROPELLANT_SHORT_BOUND) {
1242            return None;
1243        }
1244        let gap = (flown_g / record_g - 1.0) * 100.0;
1245        // The entry's masses are its default file's, so that file, or any where the entry gives
1246        // none, flies its own.
1247        let own = self.propellant_mass_g.is_none()
1248            || self
1249                .default_curve()
1250                .is_some_and(|default| default.simfile_id == curve.simfile_id);
1251        Some(if own {
1252            format!(
1253                "{} {}'s curve file {} gives {flown_g:.1} g of propellant, {gap:+.2}% from \
1254                 ThrustCurve.org's record of {record_g:.1} g. If the file's loaded mass is right, \
1255                 it flies too heavy a burnout mass and too low an apogee",
1256                self.manufacturer_abbrev, self.designation, curve.simfile_id,
1257            )
1258        } else {
1259            format!(
1260                "{} {} flies curve file {} with the default file's {flown_g:.1} g of propellant, \
1261                 {gap:+.2}% from ThrustCurve.org's record of {record_g:.1} g. If the loaded mass \
1262                 is right, it flies too heavy a burnout mass and too low an apogee",
1263                self.manufacturer_abbrev, self.designation, curve.simfile_id,
1264            )
1265        })
1266    }
1267
1268    /// The warnings for the masses flying `curve` takes ([`CatalogMotor::motor`]): a loaded mass
1269    /// more than [`LOADED_MASS_BOUND`] from the record's, either way, naming both masses; else a
1270    /// burnout mass, loaded less propellant, more than [`BURNOUT_MASS_BOUND`] of the record's
1271    /// burnout mass from it, either way, naming both; and a
1272    /// propellant share outside [`PROPELLANT_SHARE_SPAN`], the span the records state. Empty when
1273    /// neither holds, or when the file isn't bundled or doesn't read. Compared as masses, so a
1274    /// loaded mass exactly at the bound draws none. A NaN flown mass warns. A record loaded mass that
1275    /// is NaN, infinite or not above zero, or a record propellant mass that is NaN, infinite or
1276    /// below zero, counts as no record.
1277    pub fn mass_warnings(&self, curve: &CatalogCurve) -> Vec<String> {
1278        self.flown_masses(curve)
1279            .map(|masses| self.mass_warnings_for(&masses))
1280            .unwrap_or_default()
1281            .into_iter()
1282            .map(|warning| warning.message)
1283            .collect()
1284    }
1285
1286    /// [`CatalogMotor::mass_warnings`] on masses already read, each with its kind.
1287    fn mass_warnings_for(&self, masses: &FlownMasses) -> Vec<MotorWarning> {
1288        let FlownMasses {
1289            propellant_g,
1290            total_g,
1291        } = *masses;
1292        let mut warnings = Vec::new();
1293        let record_g = self
1294            .stated
1295            .total_mass_g
1296            .filter(|g| g.is_finite() && *g > 0.0);
1297        let loaded_off = record_g
1298            .is_some_and(|record_g| !within_share(total_g - record_g, record_g, LOADED_MASS_BOUND));
1299        // The burnout mass, loaded less propellant, held to its own share of the record's burnout
1300        // mass: it is what sets the center of gravity after burnout (issue #1294).
1301        let record_burnout_g = record_g.zip(
1302            self.stated
1303                .propellant_mass_g
1304                .filter(|g| g.is_finite() && *g >= 0.0),
1305        );
1306        if let Some((record_g, record_propellant_g)) = record_burnout_g
1307            && !loaded_off
1308            && record_propellant_g < record_g
1309            && !within_share(
1310                (total_g - propellant_g) - (record_g - record_propellant_g),
1311                record_g - record_propellant_g,
1312                BURNOUT_MASS_BOUND,
1313            )
1314        {
1315            let record_burnout_g = record_g - record_propellant_g;
1316            warnings.push(MotorWarning::new(
1317                MotorWarningKind::BurnoutMass,
1318                format!(
1319                    "{} {} flies a burnout mass, loaded less propellant, of {:.1} g where \
1320                 ThrustCurve.org's record gives {record_burnout_g:.1} g, {:+.1}%, more than \
1321                 {:.0}% apart. Too heavy gives too low an apogee; too light, too high a margin \
1322                 after burnout",
1323                    self.manufacturer_abbrev,
1324                    self.designation,
1325                    total_g - propellant_g,
1326                    ((total_g - propellant_g) / record_burnout_g - 1.0) * 100.0,
1327                    BURNOUT_MASS_BOUND * 100.0
1328                ),
1329            ));
1330        }
1331        if let Some(record_g) = record_g
1332            && loaded_off
1333        {
1334            let kind = if total_g > record_g {
1335                MotorWarningKind::HeavyLoadedMass
1336            } else {
1337                MotorWarningKind::LightLoadedMass
1338            };
1339            warnings.push(MotorWarning::new(kind, format!(
1340                "{} {} flies a loaded mass of {total_g:.1} g, {:+.1}% from ThrustCurve.org's \
1341                 record of {record_g:.1} g; the two disagree, so check which describes the motor you fly. \
1342                 Too heavy a motor gives too low an apogee; too light, too high a margin after \
1343                 burnout",
1344                self.manufacturer_abbrev,
1345                self.designation,
1346                (total_g / record_g - 1.0) * 100.0
1347            )));
1348        }
1349        let share = propellant_g / total_g;
1350        let (low, high) = PROPELLANT_SHARE_SPAN;
1351        if !(low..=high).contains(&share) {
1352            warnings.push(MotorWarning::new(MotorWarningKind::PropellantShare, format!(
1353                "{} {} flies {propellant_g:.1} g of propellant in a loaded mass of {total_g:.1} g, a \
1354                 propellant share of {:.1}%, outside the {:.1}% to {:.0}% ThrustCurve.org's records \
1355                 span; check the motor's masses",
1356                self.manufacturer_abbrev,
1357                self.designation,
1358                share * 100.0,
1359                low * 100.0,
1360                high * 100.0
1361            )));
1362        }
1363        warnings
1364    }
1365
1366    /// Every warning flying `curve` draws: its failing check ([`CatalogMotor::check_warning`]),
1367    /// a light propellant mass ([`CatalogMotor::propellant_warning`]) and its masses against the
1368    /// record ([`CatalogMotor::mass_warnings`]), in that order.
1369    pub fn flight_warnings(&self, curve: &CatalogCurve) -> Vec<String> {
1370        self.flight_warning_kinds(curve)
1371            .into_iter()
1372            .map(|warning| warning.message)
1373            .collect()
1374    }
1375
1376    /// [`CatalogMotor::flight_warnings`], each with its kind, so a count by kind doesn't hang on
1377    /// the words (issue #1287). The file is read once.
1378    pub fn flight_warning_kinds(&self, curve: &CatalogCurve) -> Vec<MotorWarning> {
1379        let mut warnings: Vec<MotorWarning> = self
1380            .check_warning(curve)
1381            .map(|message| MotorWarning::new(MotorWarningKind::FailedCheck, message))
1382            .into_iter()
1383            .collect();
1384        if let Some(masses) = self.flown_masses(curve) {
1385            warnings.extend(
1386                self.propellant_warning_for(curve, &masses)
1387                    .map(|message| MotorWarning::new(MotorWarningKind::LightPropellant, message)),
1388            );
1389            warnings.extend(self.mass_warnings_for(&masses));
1390        }
1391        warnings
1392    }
1393
1394    /// The warning for flying `curve` when its check fails, naming the motor, the file and each
1395    /// failing figure's signed gap, file against ThrustCurve.org's stated figure; `None` when it
1396    /// passes.
1397    pub fn check_warning(&self, curve: &CatalogCurve) -> Option<String> {
1398        if curve.check.passes {
1399            return None;
1400        }
1401        let gaps: Vec<String> = self
1402            .failing_figures(curve)
1403            .iter()
1404            .map(|gap| format!("{} {}", gap.figure.name(), gap.percent_text()))
1405            .collect();
1406        Some(format!(
1407            "{}'s curve file {} is more than 1% from ThrustCurve.org's figures for it: {}",
1408            self.designation,
1409            curve.simfile_id,
1410            gaps.join(", ")
1411        ))
1412    }
1413}
1414
1415#[cfg(test)]
1416mod tests {
1417    use sha2::{Digest, Sha256};
1418
1419    use super::*;
1420    use crate::delay::Delay;
1421
1422    /// The bundled catalog, which these tests hold.
1423    fn bundled() -> &'static Catalog {
1424        Catalog::bundled().unwrap()
1425    }
1426
1427    /// M5.7a's 32 files, as OpenRocket's fixture lists them, are each indexed under their motor
1428    /// and pass their check, so none of them warns.
1429    #[test]
1430    fn m5_7a_s_32_files_are_indexed_and_pass() {
1431        let fixture: serde_json::Value = serde_json::from_str(include_str!(
1432            "../../../validation/fixtures/motor/openrocket-curve-stats.json"
1433        ))
1434        .unwrap();
1435        let files: Vec<&str> = fixture["curves"]
1436            .as_array()
1437            .unwrap()
1438            .iter()
1439            .map(|c| {
1440                c["file"]
1441                    .as_str()
1442                    .unwrap()
1443                    .trim_start_matches("crates/hpr-motor/data/thrustcurve/")
1444            })
1445            .collect();
1446        assert_eq!(files.len(), 32);
1447        for file in files {
1448            let (motor, curve) = bundled()
1449                .motors
1450                .iter()
1451                .find_map(|m| m.curves.iter().find(|c| c.file == file).map(|c| (m, c)))
1452                .unwrap_or_else(|| panic!("{file} isn't indexed"));
1453            assert!(curve.check.passes, "{file}");
1454            assert_eq!(motor.check_warning(curve), None, "{file}");
1455        }
1456    }
1457
1458    /// Loft lesson L41: Loft's bundled curves were 45 public domain, 38 with no license, 22
1459    /// unknown and 3 "free" (which can include GPL), with no label kept. Here every bundled file
1460    /// carries ThrustCurve.org's label for it, and none is one its uploader restricted
1461    /// ([ADR-288][adr-288] §1–2 takes in the rest).
1462    ///
1463    /// [adr-288]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0288-every-solid-motor-ships-in-the-package.md
1464    #[test]
1465    fn bundled_curves_have_permissive_license() {
1466        let catalog = bundled();
1467        assert!(!catalog.motors.is_empty());
1468        let mut files = 0;
1469        for motor in &catalog.motors {
1470            for curve in &motor.curves {
1471                assert!(
1472                    curve.license.is_bundleable(),
1473                    "{} {}: {:?}",
1474                    motor.designation,
1475                    curve.simfile_id,
1476                    curve.license
1477                );
1478                assert!(bundled_curve_text(&curve.file).is_some(), "{}", curve.file);
1479                files += 1;
1480            }
1481        }
1482        // Every compiled-in file is indexed, so nothing unlicensed rides along.
1483        assert_eq!(files, bundled::CURVE_FILES.len());
1484        // Each file is byte for byte what was downloaded from its recorded URL.
1485        for motor in &catalog.motors {
1486            for curve in &motor.curves {
1487                let text = bundled_curve_text(&curve.file).unwrap();
1488                let digest: String = Sha256::digest(text.as_bytes())
1489                    .iter()
1490                    .map(|byte| format!("{byte:02x}"))
1491                    .collect();
1492                assert_eq!(digest, curve.sha256, "{}", curve.file);
1493                assert!(curve.url.contains(&curve.simfile_id));
1494            }
1495        }
1496        assert!(!CurveLicense::Other.is_bundleable());
1497        assert!(CurveLicense::Free.is_bundleable());
1498        assert!(CurveLicense::Unknown.is_bundleable());
1499        assert!(CurveLicense::PublicDomain.is_bundleable());
1500    }
1501
1502    /// Loft lesson L42: Loft's impulse checks allowed −8% to +8%, and a mis-sourced curve flew
1503    /// about 26% high until caught. Every figure the bundled index lists for a motor is its
1504    /// default file's own, bit for bit: `cargo xtask motor-catalog` works them out with the
1505    /// methods the simulator flies (#295), so what `hpr motors` lists is what flies. Every file
1506    /// stored as passing (M5.7c, [ADR-304][adr-304]) is within 1% of its motor's ThrustCurve.org
1507    /// record in total impulse, average thrust and burn time, worked out here from its text, and
1508    /// within 1% of what ThrustCurve.org's own code works out from it in those and its peak
1509    /// thrust, reading two samples at one time as a step as hpr does (M1.3's bound;
1510    /// [`every_bundled_curve_matches_thrustcurve_statistics_code`] holds the figures to 1e-12, and
1511    /// pins the files where the code's standard 50 µs merge moves them). The oracle fixture holds
1512    /// exactly the files stored as passing.
1513    ///
1514    /// [adr-304]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0304-every-passing-file-held-to-the-oracles.md
1515    #[test]
1516    fn every_bundled_curve_impulse_within_1pct_of_thrustcurve() {
1517        let oracle: AnalyzeOracle = serde_json::from_str(include_str!(
1518            "../../../validation/fixtures/motor/thrustcurve-analyze-stats.json"
1519        ))
1520        .unwrap();
1521        let catalog = bundled();
1522        let mut checked = 0;
1523        let mut listed = 0;
1524        for motor in &catalog.motors {
1525            for curve in &motor.curves {
1526                if motor.default_curve() != Some(curve)
1527                    && !oracle.curves.iter().any(|c| c.file == curve.file)
1528                {
1529                    continue;
1530                }
1531                let text = bundled_curve_text(&curve.file).unwrap();
1532                let thrust = motor.thrust_curve(curve, text).unwrap();
1533                let theirs = oracle
1534                    .curves
1535                    .iter()
1536                    .find(|c| c.file == curve.file)
1537                    .map(|c| c.unmerged.unwrap_or(c.standard()));
1538                for (stated, computed, by_thrustcurve, what) in [
1539                    (
1540                        motor.total_impulse_ns,
1541                        thrust.total_impulse_ns(),
1542                        theirs.map(|t| t.total_impulse_ns),
1543                        "total impulse",
1544                    ),
1545                    (
1546                        motor.average_thrust_n,
1547                        thrust.average_thrust_n(),
1548                        theirs.map(|t| t.average_thrust_n),
1549                        "average thrust",
1550                    ),
1551                    (
1552                        motor.burn_time_s,
1553                        thrust.burn_time_s(),
1554                        theirs.map(|t| t.burn_time_s),
1555                        "burn time",
1556                    ),
1557                    (
1558                        motor.max_thrust_n.unwrap(),
1559                        thrust.peak_thrust_n(),
1560                        theirs.map(|t| t.max_thrust_n),
1561                        "peak thrust",
1562                    ),
1563                ] {
1564                    if curve.check.passes && what != "peak thrust" {
1565                        let record = match what {
1566                            "total impulse" => motor.stated.total_impulse_ns,
1567                            "average thrust" => motor.stated.average_thrust_n,
1568                            _ => motor.stated.burn_time_s,
1569                        };
1570                        assert!(
1571                            (computed - record).abs() <= 0.01 * record,
1572                            "{} ({}) is stored as passing, but its {what} {computed} is {:+.3}% \
1573                             from its record's {record}",
1574                            motor.designation,
1575                            curve.simfile_id,
1576                            100.0 * (computed - record) / record
1577                        );
1578                    }
1579                    if motor.default_curve() == Some(curve) {
1580                        assert_eq!(
1581                            stated.to_bits(),
1582                            computed.to_bits(),
1583                            "{} ({}): the index's {what} {stated} is not its curve's {computed}",
1584                            motor.designation,
1585                            curve.simfile_id,
1586                        );
1587                    }
1588                    let Some(by_thrustcurve) = by_thrustcurve else {
1589                        continue;
1590                    };
1591                    let error = (computed - by_thrustcurve) / by_thrustcurve;
1592                    assert!(
1593                        error.abs() <= 0.01,
1594                        "{} ({}): {what} {computed} against ThrustCurve's code's {by_thrustcurve} \
1595                         ({:+.2}%)",
1596                        motor.designation,
1597                        curve.simfile_id,
1598                        100.0 * error
1599                    );
1600                }
1601                if motor.default_curve() == Some(curve) {
1602                    assert_eq!(
1603                        ImpulseClass::from_total_impulse(motor.total_impulse_ns).unwrap(),
1604                        motor.impulse_class,
1605                        "{}",
1606                        motor.designation
1607                    );
1608                    listed += 1;
1609                }
1610                assert_eq!(
1611                    theirs.is_some(),
1612                    curve.check.passes,
1613                    "{} ({}): the oracle fixture should hold exactly the files stored as passing",
1614                    motor.designation,
1615                    curve.simfile_id
1616                );
1617                checked += usize::from(theirs.is_some());
1618            }
1619        }
1620        assert_eq!(checked, oracle.curves.len());
1621        let passing = catalog
1622            .motors
1623            .iter()
1624            .flat_map(|m| &m.curves)
1625            .filter(|c| c.check.passes)
1626            .count();
1627        assert_eq!(checked, passing);
1628        // M5.7b1's snapshot: 412 of its 1,701 files pass (`cargo xtask motor-catalog`).
1629        assert_eq!(passing, 412);
1630        assert_eq!(
1631            listed,
1632            catalog
1633                .motors
1634                .iter()
1635                .filter(|m| !m.curves.is_empty())
1636                .count()
1637        );
1638    }
1639
1640    /// The bundled catalog's counts are M5.7b1's snapshot's, each recounted here by hand, and its
1641    /// size is the bytes of the index and of each curve file it reads, each once.
1642    #[test]
1643    fn bundled_counts_and_size_are_the_files() {
1644        let catalog = Catalog::bundled().unwrap();
1645        let counts = catalog.counts();
1646        let mut flying = 0;
1647        let mut files = 0;
1648        let mut passing = 0;
1649        let mut motors_passing = 0;
1650        let mut bytes = bundled::CATALOG_JSON.len();
1651        for motor in &catalog.motors {
1652            flying += usize::from(!motor.curves.is_empty());
1653            files += motor.curves.len();
1654            let here = motor.curves.iter().filter(|c| c.check.passes).count();
1655            passing += here;
1656            motors_passing += usize::from(here > 0);
1657            for curve in &motor.curves {
1658                bytes += bundled_curve_text(&curve.file).unwrap().len();
1659            }
1660        }
1661        assert_eq!(
1662            (
1663                counts.motors,
1664                counts.motors_flying,
1665                counts.files,
1666                counts.left_out
1667            ),
1668            (catalog.motors.len(), flying, files, catalog.left_out.len())
1669        );
1670        assert_eq!(
1671            (counts.files_passing, counts.motors_passing),
1672            (passing, motors_passing)
1673        );
1674        // M5.7b1's snapshot (`cargo xtask motor-catalog` prints the same).
1675        assert_eq!(
1676            (
1677                counts.motors,
1678                counts.motors_flying,
1679                counts.files,
1680                counts.left_out
1681            ),
1682            (1_004, 924, 1_701, 5)
1683        );
1684        assert_eq!((counts.files_passing, counts.motors_passing), (412, 239));
1685        // Every file compiled in is one the index reads, so the two sums agree; and the total is
1686        // the bytes `wc -c` gives for `data/thrustcurve/catalog.json` and those 1,701 files.
1687        assert_eq!(bundled::CURVE_FILES.len(), files);
1688        assert_eq!(bundled_size_bytes(), bytes);
1689        assert_eq!(bytes, 4_196_056);
1690    }
1691
1692    /// Every bundled entry's size, masses and delays are its default curve file header's (#295):
1693    /// the masses to the microgram, as `cargo xtask motor-catalog` writes a `.eng` header's
1694    /// kilograms in grams. A motor with no file that reads lists its record's (`xtask`'s
1695    /// `every_record_is_a_motor_and_every_file_is_indexed_or_left_out`).
1696    #[test]
1697    fn every_bundled_size_mass_and_delay_is_the_header_s() {
1698        let catalog = bundled();
1699        for motor in &catalog.motors {
1700            let Some(curve) = motor.default_curve() else {
1701                assert!(motor.curves.is_empty(), "{}", motor.designation);
1702                continue;
1703            };
1704            let text = bundled_curve_text(&curve.file).unwrap();
1705            let (diameter_mm, length_mm, delays, propellant_g, total_g) = match curve.format {
1706                CurveFormat::Rasp => {
1707                    let entry = eng::parse(text).unwrap().value.entries.remove(0);
1708                    (
1709                        entry.diameter_mm,
1710                        entry.length_mm,
1711                        Some(entry.delays),
1712                        entry.propellant_mass_kg * 1e3,
1713                        entry.total_mass_kg * 1e3,
1714                    )
1715                }
1716                CurveFormat::RockSim => {
1717                    let engine = rse::parse(text).unwrap().value.engines.remove(0);
1718                    (
1719                        engine.diameter_mm,
1720                        engine.length_mm,
1721                        engine.delays,
1722                        engine.propellant_mass_g,
1723                        engine.initial_mass_g,
1724                    )
1725                }
1726            };
1727            let name = &motor.designation;
1728            assert_eq!(motor.diameter_mm, diameter_mm, "{name}");
1729            assert_eq!(motor.length_mm, length_mm, "{name}");
1730            assert_eq!(motor.delays, delays, "{name}");
1731            assert!(
1732                (motor.propellant_mass_g.unwrap() - propellant_g).abs() <= 5e-7,
1733                "{name}"
1734            );
1735            assert!(
1736                (motor.total_mass_g.unwrap() - total_g).abs() <= 5e-7,
1737                "{name}"
1738            );
1739        }
1740    }
1741
1742    /// Of ThrustCurve.org's API records the bundled index copies only each motor's four stated
1743    /// figures (ADR-298; `records.json` beside the files holds the records unchanged): no
1744    /// certifying body, update date, availability or adjustable-delay flag, and no API capture.
1745    #[test]
1746    fn bundled_index_holds_no_thrustcurve_record_fields() {
1747        for key in [
1748            "cert_org",
1749            "updated_on",
1750            "availability",
1751            "delay_adjustable",
1752            "motors_url",
1753            "api/v1",
1754        ] {
1755            assert!(
1756                !bundled::CATALOG_JSON.contains(key),
1757                "the bundled index holds {key}"
1758            );
1759        }
1760        let catalog = bundled();
1761        assert_eq!(
1762            catalog.snapshot.files_url,
1763            "https://www.thrustcurve.org/simfiles/"
1764        );
1765        for curve in catalog.motors.iter().flat_map(|m| &m.curves) {
1766            assert!(curve.url.starts_with(&catalog.snapshot.files_url));
1767        }
1768    }
1769
1770    /// Loft lesson L43: a catalog's envelope overrides the curve file's header; one header said
1771    /// 75 mm for a 54 mm motor. The bundled index now takes its envelope from the headers
1772    /// themselves (#295; `cargo xtask motor-catalog` refuses a reload whose case names another
1773    /// diameter), so the override is shown on an index entry made to differ from its header: an
1774    /// invented 1000 mm and 12,000 g for the N3300R, whose file says 1060 mm.
1775    #[test]
1776    fn metadata_overrides_header_envelope() {
1777        let catalog = bundled();
1778        let bundled_entry = catalog.find("N3300R").next().unwrap();
1779        let curve = &bundled_entry.curves[0];
1780        let text = bundled_curve_text(&curve.file).unwrap();
1781        let header = &eng::parse(text).unwrap().value.entries[0];
1782        assert_eq!(header.length_mm, 1060.0);
1783        assert_eq!(bundled_entry.length_mm, 1060.0);
1784        let motor = CatalogMotor {
1785            length_mm: 1000.0,
1786            total_mass_g: Some(12000.0),
1787            ..bundled_entry.clone()
1788        };
1789        let built = motor.motor(curve, text).unwrap();
1790        // The envelope default centers the dry mass on the index's length, not the header's.
1791        assert!((built.dry().cg_m - 0.500).abs() < 1e-12);
1792        let loaded = built.state(0.0).total;
1793        assert!((loaded.mass_kg - 12.000).abs() < 1e-9);
1794        assert!((bundled_entry.bundled_motor().unwrap().dry().cg_m - 0.530).abs() < 1e-12);
1795        // With no index masses, the header's are used.
1796        let bare = CatalogMotor {
1797            propellant_mass_g: None,
1798            total_mass_g: None,
1799            ..motor.clone()
1800        };
1801        let fallback = bare.motor(curve, text).unwrap();
1802        assert!((fallback.state(0.0).total.mass_kg - header.total_mass_kg).abs() < 1e-12);
1803        assert!((fallback.dry().cg_m - 0.500).abs() < 1e-12);
1804    }
1805
1806    /// M1.3's done-when: parse-write-parse round trips are identical, on every bundled file.
1807    #[test]
1808    fn every_bundled_file_round_trips_bit_for_bit() {
1809        let catalog = bundled();
1810        for motor in &catalog.motors {
1811            for curve in &motor.curves {
1812                let text = bundled_curve_text(&curve.file).unwrap();
1813                match curve.format {
1814                    CurveFormat::Rasp => {
1815                        let first = eng::parse(text).unwrap().value;
1816                        let written = eng::write(&first).unwrap();
1817                        let second = eng::parse(&written).unwrap().value;
1818                        assert_eq!(second, first, "{}", curve.file);
1819                        assert_eq!(eng::tests::bits(&second), eng::tests::bits(&first));
1820                        assert_eq!(eng::write(&second).unwrap(), written);
1821                    }
1822                    CurveFormat::RockSim => {
1823                        let first = rse::parse(text).unwrap().value;
1824                        let written = rse::write(&first).unwrap();
1825                        let second = rse::parse(&written).unwrap().value;
1826                        assert_eq!(second, first, "{}", curve.file);
1827                        assert_eq!(rse::tests::bits(&second), rse::tests::bits(&first));
1828                        assert_eq!(rse::write(&second).unwrap(), written);
1829                    }
1830                }
1831            }
1832        }
1833    }
1834
1835    #[test]
1836    fn finds_motors_and_reads_delays() {
1837        let catalog = bundled();
1838        let j760: Vec<_> = catalog.find("j760").collect();
1839        assert!(j760.iter().any(|m| m.designation == "1266J760-19A"));
1840        assert!(j760.iter().all(|m| m.common_name == "J760"));
1841        assert_eq!(catalog.find("1266J760-19A").count(), 1);
1842        let plugged = catalog.find("L3200").next().unwrap();
1843        assert_eq!(plugged.delays().delays, [Delay::Plugged]);
1844        assert!(catalog.find("no such motor").next().is_none());
1845        // ADR-302: a maker's name narrows the match, and within one maker a designation beats
1846        // a common name; across makers both stay, so `C6` finds Southern Cross's SCR-C6 too.
1847        let c6: Vec<_> = catalog.find("C6").collect();
1848        assert!(c6.len() > 1 && c6.iter().any(|m| m.designation == "SCR-C6"));
1849        let estes: Vec<_> = catalog.find("Estes C6").collect();
1850        assert_eq!(estes.len(), 1);
1851        assert_eq!(estes[0].manufacturer_abbrev, "Estes");
1852        assert_eq!(catalog.find("estes industries c6").count(), 1);
1853        assert_eq!(catalog.find("EstesC6").count(), 0);
1854        let d5: Vec<_> = catalog.find("D5").collect();
1855        assert_eq!(d5.len(), 1);
1856        assert_eq!(d5[0].designation, "D5");
1857        assert!(catalog.find("D5-P").all(|m| m.designation == "D5-P"));
1858        assert_eq!(catalog.find("Quest no such motor").count(), 0);
1859        // Every motor's selector finds it alone, and no maker has two motors of one designation.
1860        for motor in &catalog.motors {
1861            let selector = catalog.selector(motor);
1862            let found: Vec<_> = catalog.find(&selector).collect();
1863            assert_eq!(found.len(), 1, "{selector}");
1864            assert_eq!(found[0].motor_id, motor.motor_id, "{selector}");
1865        }
1866        // Every bundled motor with a file that reads builds; one with none can't fly.
1867        for motor in &catalog.motors {
1868            if motor.curves.is_empty() {
1869                assert!(motor.bundled_motor().is_err(), "{}", motor.designation);
1870                continue;
1871            }
1872            let built = motor.bundled_motor().unwrap();
1873            assert!(
1874                built.propellant_initial_mass_kg() > 0.0,
1875                "{}",
1876                motor.designation
1877            );
1878        }
1879    }
1880
1881    #[test]
1882    fn catalog_json_reads_thrustcurve_license_values_and_rejects_others() {
1883        assert!(matches!(
1884            Catalog::from_json("{}"),
1885            Err(MotorError::Catalog(_))
1886        ));
1887        let with = |license: &str| {
1888            Catalog::from_json(&bundled::CATALOG_JSON.replacen("\"license\": \"PD\",", license, 1))
1889        };
1890        // The index's first public-domain file, the one `with` relabels.
1891        let first_pd = bundled()
1892            .motors
1893            .iter()
1894            .flat_map(|m| &m.curves)
1895            .find(|c| c.license == CurveLicense::PublicDomain)
1896            .unwrap()
1897            .simfile_id
1898            .clone();
1899        let first_license = |catalog: Catalog| {
1900            catalog
1901                .motors
1902                .iter()
1903                .flat_map(|m| &m.curves)
1904                .find(|c| c.simfile_id == first_pd)
1905                .unwrap()
1906                .license
1907        };
1908        assert!(with("\"license\": \"GPL\",").is_err());
1909        assert_eq!(
1910            first_license(with("\"license\": \"free\",").unwrap()),
1911            CurveLicense::Free
1912        );
1913        // ThrustCurve's API leaves the key out, or blank, when no license is recorded.
1914        assert_eq!(first_license(with("").unwrap()), CurveLicense::Unknown);
1915        assert_eq!(
1916            first_license(with("\"license\": \"\",").unwrap()),
1917            CurveLicense::Unknown
1918        );
1919        let hybrid = bundled::CATALOG_JSON.replacen(
1920            "\"motor_type\": \"SU\"",
1921            "\"motor_type\": \"hybrid\"",
1922            1,
1923        );
1924        let hybrid = Catalog::from_json(&hybrid).unwrap();
1925        let first_su = bundled()
1926            .motors
1927            .iter()
1928            .position(|m| m.motor_type == MotorType::SingleUse)
1929            .unwrap();
1930        assert_eq!(hybrid.motors[first_su].motor_type, MotorType::Hybrid);
1931        assert!(hybrid.motors[first_su].bundled_motor().is_err());
1932    }
1933
1934    #[test]
1935    fn a_curve_of_another_motor_is_refused() {
1936        let catalog = Catalog::bundled().unwrap();
1937        let (this, other) = (&catalog.motors[0], &catalog.motors[1]);
1938        let curve = &other.curves[0];
1939        let text = bundled_curve_text(&curve.file).unwrap();
1940        assert!(other.motor(curve, text).is_ok());
1941        assert!(matches!(
1942            this.motor(curve, text),
1943            Err(MotorError::Inconsistent(message)) if message.contains(&curve.simfile_id)
1944        ));
1945        assert!(this.thrust_curve(curve, text).is_err());
1946    }
1947
1948    #[derive(Debug, serde::Deserialize)]
1949    struct AnalyzeOracle {
1950        oracle: String,
1951        selection: String,
1952        curves: Vec<AnalyzeCurve>,
1953    }
1954
1955    /// One file's figures from ThrustCurve.org's code: with its standard 50 µs merge, and, where
1956    /// that merge folded any points, with every sample kept (`unmerged`).
1957    #[derive(Debug, serde::Deserialize)]
1958    struct AnalyzeCurve {
1959        file: String,
1960        merged_points: usize,
1961        total_impulse_ns: f64,
1962        burn_time_s: f64,
1963        average_thrust_n: f64,
1964        max_thrust_n: f64,
1965        burn_start_s: f64,
1966        burn_end_s: f64,
1967        unmerged: Option<AnalyzeFigures>,
1968    }
1969
1970    #[derive(Debug, Clone, Copy, serde::Deserialize)]
1971    struct AnalyzeFigures {
1972        total_impulse_ns: f64,
1973        burn_time_s: f64,
1974        average_thrust_n: f64,
1975        max_thrust_n: f64,
1976        burn_start_s: f64,
1977        burn_end_s: f64,
1978    }
1979
1980    impl AnalyzeCurve {
1981        /// The figures with ThrustCurve.org's standard 50 µs merge.
1982        fn standard(&self) -> AnalyzeFigures {
1983            AnalyzeFigures {
1984                total_impulse_ns: self.total_impulse_ns,
1985                burn_time_s: self.burn_time_s,
1986                average_thrust_n: self.average_thrust_n,
1987                max_thrust_n: self.max_thrust_n,
1988                burn_start_s: self.burn_start_s,
1989                burn_end_s: self.burn_end_s,
1990            }
1991        }
1992    }
1993
1994    /// The passing files where ThrustCurve.org's 50 µs merge averages two samples at one time
1995    /// into one point and so moves a figure past 1e-12, each with that figure's gap there
1996    /// (ADR-304): hpr reads the two as a step, and matches the code with every sample kept. A
1997    /// merging file past these must match the merged figures too, and each of these must still
1998    /// differ.
1999    /// The figure is the one of total impulse, burn time, average and peak thrust that moves
2000    /// most, hpr's against the merged, in percent to the digits written.
2001    const MERGE_MOVES: &[(&str, &str, &str)] = &[
2002        ("curves/5f4294d20002e9000000013c.eng", "burn time", "+0.50"),
2003        ("curves/5f4294d20002e90000000591.rse", "peak thrust", "+6.5"),
2004        ("curves/5f4294d20002e90000000144.eng", "burn time", "+0.61"),
2005        (
2006            "curves/5f4294d20002e9000000014b.eng",
2007            "average thrust",
2008            "+0.28",
2009        ),
2010        ("curves/5f4294d20002e9000000014e.eng", "burn time", "+0.19"),
2011        (
2012            "curves/5f4294d20002e900000005a3.rse",
2013            "average thrust",
2014            "+0.023",
2015        ),
2016    ];
2017
2018    /// hpr's statistics against ThrustCurve.org's own code (`simulate/analyze/analyze.js`, run
2019    /// unchanged by `validation/oracles/thrustcurve/analyze_stats.js`) on every file stored as
2020    /// passing (M5.7c). Unlike the 1% check against the records, which sorts the files, this can
2021    /// fail: it checks that hpr computes what ThrustCurve computes, to rounding. Where the code's
2022    /// 50 µs merge folds points, hpr matches it with every sample kept, and moves a figure only on
2023    /// the files [`MERGE_MOVES`] names.
2024    #[test]
2025    fn every_bundled_curve_matches_thrustcurve_statistics_code() {
2026        let oracle: AnalyzeOracle = serde_json::from_str(include_str!(
2027            "../../../validation/fixtures/motor/thrustcurve-analyze-stats.json"
2028        ))
2029        .unwrap();
2030        assert!(oracle.oracle.contains("analyze.js at commit 577afa6"));
2031        assert!(oracle.selection.contains("stores as passing"));
2032        let catalog = bundled();
2033        let mut worst = 0.0f64;
2034        let mut moved = Vec::new();
2035        for expected in &oracle.curves {
2036            let (motor, curve) = catalog
2037                .motors
2038                .iter()
2039                .find_map(|m| {
2040                    m.curves
2041                        .iter()
2042                        .find(|c| c.file == expected.file)
2043                        .map(|c| (m, c))
2044                })
2045                .unwrap();
2046            assert!(curve.check.passes, "{}", expected.file);
2047            assert_eq!(
2048                expected.unmerged.is_some(),
2049                expected.merged_points > 0,
2050                "{}",
2051                expected.file
2052            );
2053            let thrust = motor
2054                .thrust_curve(curve, bundled_curve_text(&curve.file).unwrap())
2055                .unwrap();
2056            let (start, end) = thrust.burn_window_s();
2057            let ours = AnalyzeFigures {
2058                total_impulse_ns: thrust.total_impulse_ns(),
2059                burn_time_s: thrust.burn_time_s(),
2060                average_thrust_n: thrust.average_thrust_n(),
2061                max_thrust_n: thrust.peak_thrust_n(),
2062                burn_start_s: start,
2063                burn_end_s: end,
2064            };
2065            let gaps = |theirs: AnalyzeFigures| {
2066                [
2067                    (
2068                        ours.total_impulse_ns,
2069                        theirs.total_impulse_ns,
2070                        "total impulse",
2071                    ),
2072                    (ours.burn_time_s, theirs.burn_time_s, "burn time"),
2073                    (
2074                        ours.average_thrust_n,
2075                        theirs.average_thrust_n,
2076                        "average thrust",
2077                    ),
2078                    (ours.max_thrust_n, theirs.max_thrust_n, "peak thrust"),
2079                    (ours.burn_start_s, theirs.burn_start_s, "burn start"),
2080                    (ours.burn_end_s, theirs.burn_end_s, "burn end"),
2081                ]
2082                .map(|(ours, theirs, what)| {
2083                    (
2084                        (ours - theirs).abs() / theirs.abs().max(1e-3),
2085                        ours,
2086                        theirs,
2087                        what,
2088                    )
2089                })
2090            };
2091            for (error, ours, theirs, what) in
2092                gaps(expected.unmerged.unwrap_or(expected.standard()))
2093            {
2094                worst = worst.max(error);
2095                assert!(
2096                    error <= 1e-12,
2097                    "{}: {what} {ours} against {theirs}",
2098                    expected.file
2099                );
2100            }
2101            let merged = gaps(expected.standard());
2102            if merged.iter().any(|(error, ..)| *error > 1e-12) {
2103                moved.push(expected.file.as_str());
2104                // The headline figure the merge moves most, and its signed gap in percent.
2105                let (_, ours, theirs, what) = merged[..4]
2106                    .iter()
2107                    .copied()
2108                    .max_by(|a, b| a.0.total_cmp(&b.0))
2109                    .unwrap();
2110                let named = MERGE_MOVES.iter().find(|(file, ..)| *file == expected.file);
2111                if let Some((_, figure, percent)) = named {
2112                    let decimals = percent.split('.').nth(1).map_or(0, str::len);
2113                    let measured = format!("{:+.decimals$}", 100.0 * (ours - theirs) / theirs);
2114                    assert_eq!(
2115                        (what, measured.as_str()),
2116                        (*figure, *percent),
2117                        "{}: the merge's largest move",
2118                        expected.file
2119                    );
2120                }
2121            }
2122        }
2123        let named: Vec<&str> = MERGE_MOVES.iter().map(|(file, ..)| *file).collect();
2124        assert_eq!(
2125            moved, named,
2126            "the files whose figures ThrustCurve's 50 µs merge moves aren't the ones named"
2127        );
2128        eprintln!("largest relative difference from ThrustCurve's code: {worst:.2e}");
2129    }
2130
2131    /// OpenRocket 24.12's record of the same files, written by
2132    /// `validation/oracles/openrocket/motors.py`.
2133    #[derive(Debug, serde::Deserialize)]
2134    struct OpenRocketRecord {
2135        openrocket: String,
2136        inputs_sha256: std::collections::BTreeMap<String, String>,
2137        jar_sha256: String,
2138        curves: Vec<OpenRocketCurve>,
2139    }
2140
2141    #[derive(Debug, serde::Deserialize)]
2142    struct OpenRocketCurve {
2143        file: String,
2144        sha256: String,
2145        #[serde(default)]
2146        motors: Vec<OpenRocketMotor>,
2147        #[serde(default)]
2148        driver_error: Option<String>,
2149    }
2150
2151    #[derive(Debug, serde::Deserialize)]
2152    struct OpenRocketMotor {
2153        common_name: String,
2154        total_impulse_ns: f64,
2155        max_thrust_n: f64,
2156        average_thrust_n: f64,
2157        burn_time_s: f64,
2158        burn_time_estimate_s: f64,
2159        first_time_s: f64,
2160        points: usize,
2161    }
2162
2163    /// hpr's total impulse against OpenRocket 24.12's own estimate for the same file, on every
2164    /// bundled curve (M2.2c1). Both integrate the file's points with the trapezoid rule, so the
2165    /// milestone's 0.1% is met with room to spare; the check is the bound the milestone names, and
2166    /// the run prints the spread.
2167    ///
2168    /// Three more of OpenRocket's numbers are the same quantity as one of hpr's, so they are held
2169    /// too: `getMaxThrustEstimate` is the largest *listed* thrust, which is
2170    /// [`ThrustCurve::peak_thrust_n`] on every bundled curve (none lists a sample a step skips),
2171    /// `getBurnTimeEstimate` is the 5%-of-peak window ([`ThrustCurve::burn_time_s`], the NFPA 1125
2172    /// rule), and `getBurnTime` is the curve's whole duration ([`ThrustCurve::end_time_s`]), not a
2173    /// window. OpenRocket prepends an origin to a file whose first point is after ignition, exactly
2174    /// as hpr does, so the point counts are held equal as well.
2175    ///
2176    /// One quantity is a real difference, printed here and written down with its size in ADR-066
2177    /// rather than held: OpenRocket's average thrust divides the impulse *inside* the window by the
2178    /// window, where hpr (with ThrustCurve.org's code) divides the whole curve's impulse by it, so
2179    /// hpr's is the higher on every curve.
2180    #[test]
2181    fn openrocket_s_total_impulse_matches_every_bundled_curve() {
2182        let record: OpenRocketRecord = serde_json::from_str(include_str!(
2183            "../../../validation/fixtures/motor/openrocket-curve-stats.json"
2184        ))
2185        .unwrap();
2186        assert_eq!(record.openrocket, "24.12");
2187        // The record moves only when its script runs, never by hand (Loft lesson L76).
2188        assert_eq!(
2189            record.inputs_sha256["motors.py"],
2190            "1049b94c2c0da896dd84887a06b5ff8fd72865350aa98a2f9e1c8b7e14d5e3e7",
2191        );
2192        assert_eq!(
2193            record.jar_sha256,
2194            "4959b72f52f5f607941e9722abbb7b7f0c4a38ebbbf84204a329db9f31c4f897",
2195        );
2196        // ADR-066's check holds M5.7a's 32 files, and the whole catalog doesn't widen it (ADR-288).
2197        assert_eq!(record.curves.len(), 32);
2198        let catalog = bundled();
2199        let mut worst_impulse = 0.0f64;
2200        let mut worst_peak = 0.0f64;
2201        let mut average = Vec::new();
2202        let mut identical = true;
2203        let mut files = std::collections::BTreeSet::new();
2204        for entry in &record.curves {
2205            let file = entry
2206                .file
2207                .strip_prefix("crates/hpr-motor/data/thrustcurve/")
2208                .expect("the record names the bundled file");
2209            assert_eq!(entry.driver_error, None, "{file}");
2210            let [theirs] = &entry.motors[..] else {
2211                panic!("{file}: OpenRocket read {} motors", entry.motors.len());
2212            };
2213            let (motor, curve) = catalog
2214                .motors
2215                .iter()
2216                .find_map(|m| m.curves.iter().find(|c| c.file == file).map(|c| (m, c)))
2217                .unwrap_or_else(|| panic!("{file} is not a bundled curve"));
2218            // The record is tied to the bytes OpenRocket read, which are the bytes hpr reads.
2219            assert_eq!(curve.sha256, entry.sha256, "{file}");
2220            assert!(files.insert(file.to_owned()), "{file} twice");
2221            // The two catalogs spell a designation differently (ThrustCurve's `131G84-10A` is
2222            // OpenRocket's `131-G84-GR-10A`, read from the file's own header), so the common name
2223            // is what can be compared; the file's SHA-256 is what ties the record to the motor.
2224            assert_eq!(
2225                normalize(&motor.common_name),
2226                normalize(&theirs.common_name),
2227                "{file}"
2228            );
2229            let text = bundled_curve_text(file).unwrap();
2230            let thrust = motor.thrust_curve(curve, text).unwrap();
2231            for (ours, theirs, what, bound) in [
2232                (
2233                    thrust.total_impulse_ns(),
2234                    theirs.total_impulse_ns,
2235                    "total impulse",
2236                    1e-3,
2237                ),
2238                (
2239                    thrust.peak_thrust_n(),
2240                    theirs.max_thrust_n,
2241                    "peak thrust",
2242                    1e-12,
2243                ),
2244                (
2245                    thrust.burn_time_s(),
2246                    theirs.burn_time_estimate_s,
2247                    "burn time",
2248                    1e-12,
2249                ),
2250                (
2251                    thrust.end_time_s(),
2252                    theirs.burn_time_s,
2253                    "curve duration",
2254                    1e-12,
2255                ),
2256            ] {
2257                assert!(theirs > 0.0, "{file}: {what} {theirs}");
2258                let error = (ours - theirs).abs() / theirs;
2259                if what == "total impulse" {
2260                    worst_impulse = worst_impulse.max(error);
2261                } else {
2262                    worst_peak = worst_peak.max(error);
2263                }
2264                assert!(error <= bound, "{file}: {what} {ours} against {theirs}");
2265                // Each is the same quantity computed twice, and each comes out bit for bit equal,
2266                // which is what the guide and ADR-066 claim.
2267                identical &= ours == theirs;
2268            }
2269            // Both readers prepend `(0, 0)` to a file whose first point is after ignition (29 of
2270            // the 32), so both count that point and neither starts late.
2271            assert_eq!(thrust.times_s()[0], 0.0, "{file}");
2272            assert_eq!(theirs.first_time_s, 0.0, "{file}");
2273            assert_eq!(thrust.times_s().len(), theirs.points, "{file}");
2274            // The one definition that differs, measured rather than held, and signed: hpr's
2275            // whole-curve numerator makes it the higher on every curve.
2276            average.push(
2277                (thrust.average_thrust_n() - theirs.average_thrust_n) / theirs.average_thrust_n,
2278            );
2279        }
2280        assert_eq!(files.len(), record.curves.len(), "a file twice or missing");
2281        assert!(
2282            identical,
2283            "impulse, peak thrust, burn time and duration are no longer bit for bit OpenRocket's"
2284        );
2285        average.sort_by(f64::total_cmp);
2286        let mid = average.len() / 2;
2287        let median = if average.len().is_multiple_of(2) {
2288            0.5 * (average[mid - 1] + average[mid])
2289        } else {
2290            average[mid]
2291        };
2292        let (low, high) = (average[0] * 100.0, average[average.len() - 1] * 100.0);
2293        assert!(low > 0.0, "hpr's average thrust is no longer the higher");
2294        eprintln!(
2295            "against OpenRocket 24.12 on {} curves: total impulse, peak thrust, the 5% burn-time \
2296             window and the curve's duration are all bit for bit equal (worst relative differences \
2297             {worst_impulse:.2e} and {worst_peak:.2e}); hpr's average thrust is higher by \
2298             {low:+.4}% to {high:+.4}% (median {:+.4}%), because its numerator is the whole curve's \
2299             impulse and OpenRocket's is the window's",
2300            average.len(),
2301            median * 100.0,
2302        );
2303    }
2304
2305    /// ADR-298 §4: every bundled file's stored check is its curve's figures against its motor's
2306    /// stated ones, worked out again here, and the stated figures are the committed record's,
2307    /// bit for bit, over every file of the whole catalog. A failing file is stored with its
2308    /// failing check, and its warning names it.
2309    #[test]
2310    fn every_bundled_check_is_its_file_against_its_record() {
2311        let records: serde_json::Value =
2312            serde_json::from_str(include_str!("../data/thrustcurve/records.json")).unwrap();
2313        let records = records["records"].as_array().unwrap();
2314        let bits = |value: &serde_json::Value| value.as_f64().map(f64::to_bits);
2315        let catalog = bundled();
2316        let mut checked = 0;
2317        for motor in &catalog.motors {
2318            let name = &motor.designation;
2319            let record = records
2320                .iter()
2321                .find(|r| r["motorId"] == motor.motor_id.as_str())
2322                .unwrap_or_else(|| panic!("{name}: no record"));
2323            let stated = &motor.stated;
2324            assert_eq!(
2325                Some(stated.total_impulse_ns.to_bits()),
2326                bits(&record["totImpulseNs"])
2327            );
2328            assert_eq!(
2329                Some(stated.average_thrust_n.to_bits()),
2330                bits(&record["avgThrustN"])
2331            );
2332            assert_eq!(
2333                Some(stated.burn_time_s.to_bits()),
2334                bits(&record["burnTimeS"])
2335            );
2336            assert_eq!(
2337                stated.max_thrust_n.map(f64::to_bits),
2338                bits(&record["maxThrustN"])
2339            );
2340            for curve in &motor.curves {
2341                let text = bundled_curve_text(&curve.file).unwrap();
2342                let thrust = motor.thrust_curve(curve, text).unwrap();
2343                assert_eq!(CurveCheck::of(&thrust, stated), curve.check, "{name}");
2344                // A failing file is stored with its check (ADR-298 §2) and warned of when flown.
2345                assert_eq!(
2346                    curve.check.passes,
2347                    motor.failing_figures(curve).is_empty(),
2348                    "{name}"
2349                );
2350                match motor.check_warning(curve) {
2351                    None => assert!(curve.check.passes, "{name}"),
2352                    Some(warning) => {
2353                        assert!(!curve.check.passes, "{name}");
2354                        assert!(warning.contains(&curve.simfile_id), "{name}: {warning}");
2355                    }
2356                }
2357                checked += 1;
2358            }
2359        }
2360        assert_eq!(checked, bundled::CURVE_FILES.len());
2361    }
2362
2363    /// ADR-298 §4: a figure exactly 1% from the stated one passes on either side, and the next
2364    /// float past it fails. A stated figure that isn't positive, or a NaN, fails.
2365    #[test]
2366    fn a_figure_exactly_one_percent_away_passes_and_one_past_fails() {
2367        let gap = |file: f64, stated: f64| FigureGap {
2368            figure: CheckedFigure::BurnTime,
2369            file,
2370            stated,
2371        };
2372        assert!(gap(101.0, 100.0).within_bound());
2373        assert!(gap(99.0, 100.0).within_bound());
2374        assert!(gap(100.0, 100.0).within_bound());
2375        assert!(!gap(101.0_f64.next_up(), 100.0).within_bound());
2376        assert!(!gap(99.0_f64.next_down(), 100.0).within_bound());
2377        assert_eq!(gap(101.0, 100.0).relative(), 0.01);
2378        assert_eq!(gap(99.0, 100.0).relative(), -0.01);
2379        assert!(!gap(0.0, 0.0).within_bound());
2380        assert!(!gap(-1.0, -1.0).within_bound());
2381        assert!(!gap(f64::NAN, 100.0).within_bound());
2382        assert!(!gap(100.0, f64::NAN).within_bound());
2383        // A failing figure never prints as within 1%; a passing one keeps two decimals.
2384        assert_eq!(gap(101.004, 100.0).percent_text(), "+1.004%");
2385        assert_eq!(gap(98.9996, 100.0).percent_text(), "-1.0004%");
2386        assert_eq!(
2387            gap(101.0_f64.next_up(), 100.0).percent_text(),
2388            "+1.00000000000001%"
2389        );
2390        assert_eq!(gap(101.0, 100.0).percent_text(), "+1.00%");
2391        assert_eq!(gap(100.996, 100.0).percent_text(), "+1.00%");
2392        assert_eq!(gap(102.0, 100.0).percent_text(), "+2.00%");
2393        // One unit past 1%, the quotient needs 16 decimals to read as past it.
2394        let past = gap(242.70152480324737, 240.2985394091558);
2395        assert!(!past.within_bound());
2396        assert_eq!(past.percent_text(), "+1.0000000000000002%");
2397        assert_eq!(gap(-1.0, -1.0).percent_text(), "n/a");
2398    }
2399
2400    /// A stored pass its figures contradict is refused when the index is read: the flag ranks the
2401    /// files, so a wrong one would fly a failing file silently.
2402    #[test]
2403    fn a_stored_pass_its_figures_contradict_is_refused() {
2404        let flipped = bundled::CATALOG_JSON.replacen("\"passes\": true", "\"passes\": false", 1);
2405        assert!(matches!(
2406            Catalog::from_json(&flipped),
2407            Err(MotorError::Catalog(message)) if message.contains("stores passes: false")
2408        ));
2409    }
2410
2411    /// A narrowed read refuses what the whole index's read does, for a motor it keeps.
2412    #[test]
2413    fn a_narrowed_read_refuses_a_contradicted_pass_it_keeps() {
2414        let flipped = bundled::CATALOG_JSON.replacen("\"passes\": true", "\"passes\": false", 1);
2415        assert!(matches!(
2416            Catalog::narrowed(&flipped, &|_| true),
2417            Err(MotorError::Catalog(message)) if message.contains("stores passes: false")
2418        ));
2419    }
2420
2421    /// Reading every motor by the narrowed route builds what the whole index's read builds, so
2422    /// the bundled index is laid out as that route reads it.
2423    #[test]
2424    fn a_narrowed_read_keeping_everything_is_the_catalog() {
2425        let whole = bundled();
2426        let narrowed = Catalog::narrowed(bundled::CATALOG_JSON, &|_| true).unwrap();
2427        assert_eq!(narrowed.motors, whole.motors);
2428        assert_eq!(narrowed.source, whole.source);
2429        assert_eq!(narrowed.selection, whole.selection);
2430        assert_eq!(narrowed.snapshot, whole.snapshot);
2431    }
2432
2433    /// A motor's keys are its own, however its strings read: a name with escapes or the text of
2434    /// another field in it, and a curve's fields, which sit deeper, don't stand in for them.
2435    #[test]
2436    fn a_narrowed_read_takes_each_motors_own_keys() {
2437        let mut catalog = bundled().clone();
2438        catalog.motors.truncate(3);
2439        catalog.motors[0].designation = "A\"8\\n\n      \"designation\": \"Z9".to_owned();
2440        catalog.motors[1].common_name = "\n    }\n  ]".to_owned();
2441        let text = serde_json::to_string_pretty(&catalog).unwrap();
2442        let read = Catalog::narrowed(&text, &|_| true).unwrap();
2443        assert_eq!(read.motors, catalog.motors);
2444        let named = |name: String| {
2445            let name = std::cell::RefCell::new(name);
2446            Catalog::narrowed(&text, &|keys: &MotorKeys<'_>| {
2447                keys.designation == *name.borrow()
2448            })
2449            .unwrap()
2450            .motors
2451            .len()
2452        };
2453        assert_eq!(named(catalog.motors[0].designation.clone()), 1);
2454        assert_eq!(named("Z9".to_owned()), 0);
2455        // Text not laid out so is refused, not read as no motors.
2456        let compact = serde_json::to_string(&catalog).unwrap();
2457        assert!(Catalog::narrowed(&compact, &|_| true).is_err());
2458    }
2459
2460    /// `bundled_named` must answer a design's lookup as the whole catalog does, whatever the
2461    /// spelling of the name, for names that a rival or another maker shares as well: spread over
2462    /// the catalog, each motor by its designation and its common name, respelled, at its own case
2463    /// size and at another.
2464    #[test]
2465    fn a_narrowed_catalog_finds_for_a_design_as_the_whole_one_does() {
2466        let whole = bundled();
2467        let ids = |found: Vec<&CatalogMotor>| -> Vec<String> {
2468            found.iter().map(|motor| motor.motor_id.clone()).collect()
2469        };
2470        let mut compared = 0;
2471        let mut shared = 0;
2472        for motor in whole.motors.iter().step_by(23) {
2473            let respelled = motor.designation.to_lowercase().replace('-', " ");
2474            for name in [
2475                motor.designation.as_str(),
2476                motor.common_name.as_str(),
2477                respelled.as_str(),
2478            ] {
2479                let narrow = Catalog::bundled_named([name]).unwrap();
2480                for maker in [
2481                    motor.manufacturer.as_str(),
2482                    motor.manufacturer_abbrev.as_str(),
2483                ] {
2484                    for diameter_mm in [None, Some(motor.diameter_mm), Some(1.0)] {
2485                        let expected = whole.find_for_design(maker, name, None, diameter_mm);
2486                        shared += usize::from(expected.len() > 1);
2487                        assert_eq!(
2488                            ids(narrow.find_for_design(maker, name, None, diameter_mm)),
2489                            ids(expected),
2490                            "{maker} {name} at {diameter_mm:?}"
2491                        );
2492                        compared += 1;
2493                    }
2494                }
2495            }
2496        }
2497        assert!(compared > 500, "{compared}");
2498        assert!(shared > 0, "no name found two motors, so the check is thin");
2499        // A name no motor has keeps none, rather than all.
2500        assert!(Catalog::bundled_named(["Z9999"]).unwrap().motors.is_empty());
2501    }
2502
2503    /// The date every `hpr sim` prints is the whole index's, read from its head alone; an index
2504    /// with its motors first has no head to read, and is read whole.
2505    #[test]
2506    fn the_snapshot_is_read_from_the_index_head() {
2507        assert_eq!(
2508            snapshot_in_head(bundled::CATALOG_JSON).as_ref(),
2509            Some(&bundled().snapshot)
2510        );
2511        assert_eq!(Catalog::bundled_snapshot().unwrap(), bundled().snapshot);
2512        let snapshot = r#""snapshot": { "files_url": "u", "captured": "c" }"#;
2513        assert!(snapshot_in_head(&format!(r#"{{ "motors": [], {snapshot} }}"#)).is_none());
2514        assert!(snapshot_in_head(&format!(r#"{{ {snapshot} }}"#)).is_none());
2515        assert!(snapshot_in_head(&format!(r#"{{ {snapshot}, "motors": [] }}"#)).is_some());
2516    }
2517
2518    /// The motor with an id, and only that one.
2519    #[test]
2520    fn a_catalog_narrowed_by_id_holds_those_motors() {
2521        let whole = bundled();
2522        let wanted = [&whole.motors[3], &whole.motors[700]];
2523        let narrow =
2524            Catalog::bundled_with_ids(wanted.iter().map(|motor| motor.motor_id.as_str())).unwrap();
2525        assert_eq!(narrow.motors.len(), 2);
2526        assert_eq!(&narrow.motors[0], wanted[0]);
2527        assert_eq!(&narrow.motors[1], wanted[1]);
2528    }
2529
2530    /// A failing figure never prints as within 1%: over 20,000 stated figures from 0.1 to about
2531    /// 40,000, the first few floats past 1% on either side each print past it.
2532    #[test]
2533    fn a_failing_gap_never_prints_inside_one_percent() {
2534        let mut checked = 0;
2535        for i in 0..20_000 {
2536            let stated = 0.1 + f64::from(i) * 1.999_37;
2537            for (start, step) in [(stated * 1.01, 1.0), (stated * 0.99, -1.0)] {
2538                let mut file: f64 = start;
2539                for _ in 0..4 {
2540                    let gap = FigureGap {
2541                        figure: CheckedFigure::TotalImpulse,
2542                        file,
2543                        stated,
2544                    };
2545                    if !gap.within_bound() {
2546                        let text = gap.percent_text();
2547                        assert!(!rounds_inside(&text), "{file} against {stated}: {text}");
2548                        checked += 1;
2549                    }
2550                    file = if step > 0.0 {
2551                        file.next_up()
2552                    } else {
2553                        file.next_down()
2554                    };
2555                }
2556            }
2557        }
2558        assert!(checked > 100_000, "{checked}");
2559    }
2560
2561    /// ADR-298 §4 and §6: each checked figure fails the check alone, and the warning names that
2562    /// figure only, with its signed gap, file against stated. Each case moves one stated figure
2563    /// of the bundled J760 so its file's figure sits 1.5% to 3% from it.
2564    #[test]
2565    fn each_figure_alone_fails_the_check_and_is_named() {
2566        let catalog = bundled();
2567        let motor = catalog.find("J760").next().unwrap();
2568        let curve = &motor.curves[0];
2569        let thrust = motor
2570            .thrust_curve(curve, bundled_curve_text(&curve.file).unwrap())
2571            .unwrap();
2572        let all = [
2573            CheckedFigure::TotalImpulse,
2574            CheckedFigure::AverageThrust,
2575            CheckedFigure::BurnTime,
2576        ];
2577        for (figure, scale, gap) in [
2578            (CheckedFigure::TotalImpulse, 1.02, "+2.00%"),
2579            (CheckedFigure::AverageThrust, 0.97, "-3.00%"),
2580            (CheckedFigure::BurnTime, 1.015, "+1.50%"),
2581        ] {
2582            let mut moved = motor.clone();
2583            let check = &curve.check;
2584            match figure {
2585                CheckedFigure::TotalImpulse => {
2586                    moved.stated.total_impulse_ns = check.total_impulse_ns / scale;
2587                }
2588                CheckedFigure::AverageThrust => {
2589                    moved.stated.average_thrust_n = check.average_thrust_n / scale;
2590                }
2591                CheckedFigure::BurnTime => moved.stated.burn_time_s = check.burn_time_s / scale,
2592            }
2593            moved.curves[0].check = CurveCheck::of(&thrust, &moved.stated);
2594            let moved_curve = &moved.curves[0];
2595            assert!(!moved_curve.check.passes, "{figure:?}");
2596            let failing = moved.failing_figures(moved_curve);
2597            assert_eq!(failing.len(), 1, "{figure:?}");
2598            assert_eq!(failing[0].figure, figure);
2599            assert!((failing[0].relative() - (scale - 1.0)).abs() < 1e-12);
2600            let warning = moved.check_warning(moved_curve).unwrap();
2601            assert_eq!(
2602                warning,
2603                format!(
2604                    "1266J760-19A's curve file {} is more than 1% from ThrustCurve.org's \
2605                     figures for it: {} {gap}",
2606                    curve.simfile_id,
2607                    figure.name()
2608                )
2609            );
2610            for other in all.iter().filter(|other| **other != figure) {
2611                assert!(!warning.contains(other.name()), "{warning}");
2612            }
2613        }
2614    }
2615
2616    /// ADR-298 §5: a motor's files rank a passing file first, then RASP before RockSim, each by
2617    /// who measured it (a certification test, the maker, a user), the index's order within a
2618    /// rank.
2619    #[test]
2620    fn files_rank_passing_first_then_by_format_and_source() {
2621        let catalog = bundled();
2622        let base = &catalog.motors[0];
2623        let file = |id: &str, format, source, passes| {
2624            let mut curve = base.curves[0].clone();
2625            curve.simfile_id = id.to_owned();
2626            curve.format = format;
2627            curve.source = source;
2628            curve.check.passes = passes;
2629            curve
2630        };
2631        use CurveFormat::{Rasp, RockSim};
2632        use CurveSource::{Certification, Manufacturer, User};
2633        let mut motor = base.clone();
2634        motor.curves = vec![
2635            file("user rasp pass", Rasp, User, true),
2636            file("cert rse fail", RockSim, Certification, false),
2637            file("cert rasp fail", Rasp, Certification, false),
2638            file("mfr rse pass", RockSim, Manufacturer, true),
2639            file("user rasp fail", Rasp, User, false),
2640            file("mfr rasp pass", Rasp, Manufacturer, true),
2641            file("user rasp pass 2", Rasp, User, true),
2642        ];
2643        let order: Vec<&str> = motor
2644            .ranked_curves()
2645            .iter()
2646            .map(|curve| curve.simfile_id.as_str())
2647            .collect();
2648        assert_eq!(
2649            order,
2650            [
2651                "mfr rasp pass",
2652                "user rasp pass",
2653                "user rasp pass 2",
2654                "mfr rse pass",
2655                "cert rasp fail",
2656                "user rasp fail",
2657                "cert rse fail",
2658            ]
2659        );
2660    }
2661
2662    /// ADR-298 §5's default on the whole catalog: every motor with a bundled file has a default,
2663    /// and it passes the 1% check wherever one of its files does (M5.7b2).
2664    #[test]
2665    fn every_motor_s_default_passes_where_one_of_its_files_does() {
2666        let catalog = bundled();
2667        let mut passing = 0;
2668        for motor in &catalog.motors {
2669            let default = motor.default_curve();
2670            assert_eq!(
2671                default.is_some(),
2672                !motor.curves.is_empty(),
2673                "{}",
2674                motor.designation
2675            );
2676            if motor.curves.iter().any(|c| c.check.passes) {
2677                passing += 1;
2678                assert!(
2679                    default.is_some_and(|c| c.check.passes),
2680                    "{}",
2681                    motor.designation
2682                );
2683            }
2684        }
2685        assert_eq!(passing, 239);
2686    }
2687
2688    /// A `.ork` motor's digest picks the file OpenRocket's curve maps to, ahead of the default,
2689    /// only when that file is one of the motor's own (ADR-288 §3, ADR-302 §4).
2690    #[test]
2691    fn a_digest_takes_its_own_file_first() {
2692        let catalog = bundled();
2693        let table: serde_json::Value =
2694            serde_json::from_str(include_str!("../data/openrocket-curves.json")).unwrap();
2695        // Every digest in the table whose file belongs to a motor with another default.
2696        let mut moved = 0;
2697        for entry in table["files"].as_array().unwrap() {
2698            let digest = entry["digest"].as_str().unwrap();
2699            let mapped = crate::openrocket_curves::file_for(digest).unwrap();
2700            let Some(motor) = catalog
2701                .motors
2702                .iter()
2703                .find(|m| m.curves.iter().any(|c| c.simfile_id == mapped))
2704            else {
2705                continue;
2706            };
2707            let default = &motor.default_curve().unwrap().simfile_id;
2708            let picked = |digest| motor.curve_for_digest(digest).map(|(c, _)| &c.simfile_id);
2709            assert_eq!(picked(Some(digest)), Some(&mapped), "{digest}");
2710            assert_eq!(picked(None), Some(default));
2711            assert_eq!(
2712                picked(Some("00000000000000000000000000000000")),
2713                Some(default)
2714            );
2715            if *default != mapped {
2716                moved += 1;
2717                // Another motor's digest leaves the default standing.
2718                let other = table["files"]
2719                    .as_array()
2720                    .unwrap()
2721                    .iter()
2722                    .filter_map(|e| e["digest"].as_str())
2723                    .find(|d| {
2724                        crate::openrocket_curves::file_for(d)
2725                            .is_some_and(|f| motor.curves.iter().all(|c| c.simfile_id != f))
2726                    })
2727                    .unwrap();
2728                assert_eq!(picked(Some(other)), Some(default));
2729            }
2730        }
2731        assert!(
2732            moved > 0,
2733            "no digest in the table picks a file other than its default"
2734        );
2735    }
2736
2737    /// ADR-302's light-propellant warning errs toward warning, the side a light file flatters:
2738    /// a file more than 5% under the record warns with its negative gap, one at 5% or less, or
2739    /// heavier, doesn't, and a record with no mass (none, zero or not finite) gives none.
2740    #[test]
2741    fn a_light_propellant_file_warns_and_only_then() {
2742        let catalog = bundled();
2743        let (base, curve, file_g) = catalog
2744            .motors
2745            .iter()
2746            .find_map(|motor| {
2747                let (curve, text) = motor.default_curve_text()?;
2748                let (_, propellant_kg, _) = read_curve_file(curve, text).ok()?;
2749                (propellant_kg > 0.0).then(|| (motor, curve.clone(), propellant_kg * 1000.0))
2750            })
2751            .unwrap();
2752        let warning = |record_g: Option<f64>| {
2753            let mut motor = base.clone();
2754            motor.stated.propellant_mass_g = record_g;
2755            motor.propellant_warning(&curve)
2756        };
2757        let light = warning(Some(file_g / 0.949)).expect("5.1% light warns");
2758        assert!(light.contains("-5.10%"), "{light}");
2759        assert!(light.contains(&curve.simfile_id), "{light}");
2760        assert_eq!(warning(Some(file_g / 0.951)), None, "4.9% light");
2761        assert_eq!(warning(Some(file_g)), None, "equal");
2762        assert_eq!(warning(Some(file_g * 0.5)), None, "heavier");
2763        for record in [None, Some(0.0), Some(f64::NAN), Some(f64::INFINITY)] {
2764            assert_eq!(warning(record), None, "{record:?}");
2765        }
2766        // Both of a flight's warnings come back, the check's first; the record gives no loaded
2767        // mass, so no mass warning joins them (#1233's have their own test).
2768        let mut motor = base.clone();
2769        motor.stated.propellant_mass_g = Some(file_g / 0.9);
2770        motor.stated.total_mass_g = None;
2771        assert!(motor.mass_warnings(&curve).is_empty());
2772        let mut failing = curve.clone();
2773        failing.check.passes = false;
2774        let warnings = motor.flight_warnings(&failing);
2775        assert_eq!(warnings.len(), 2, "{warnings:?}");
2776        assert!(warnings[0].contains("is more than 1% from"), "{warnings:?}");
2777        assert!(warnings[1].contains("of propellant"), "{warnings:?}");
2778    }
2779
2780    /// Issue #1287: each flight warning carries its kind, in the order and with the words
2781    /// `flight_warnings` gives, so `cargo xtask motor-catalog` counts by kind, not by the words.
2782    #[test]
2783    fn flight_warnings_carry_their_kinds() {
2784        let catalog = bundled();
2785        let d8 = catalog
2786            .motors
2787            .iter()
2788            .find(|motor| motor.manufacturer_abbrev == "Quest" && motor.designation == "D8")
2789            .expect("the Quest D8");
2790        let curve = d8.default_curve().expect("a bundled file");
2791        let typed = d8.flight_warning_kinds(curve);
2792        let words: Vec<String> = typed.iter().map(|w| w.message.clone()).collect();
2793        assert_eq!(words, d8.flight_warnings(curve));
2794        let kinds: Vec<MotorWarningKind> = typed.iter().map(|w| w.kind).collect();
2795        assert!(
2796            kinds.ends_with(&[
2797                MotorWarningKind::HeavyLoadedMass,
2798                MotorWarningKind::PropellantShare
2799            ]),
2800            "{kinds:?}"
2801        );
2802        // Every motor: the typed list and the words agree.
2803        for motor in &catalog.motors {
2804            let Some(curve) = motor.default_curve() else {
2805                continue;
2806            };
2807            let typed: Vec<String> = motor
2808                .flight_warning_kinds(curve)
2809                .into_iter()
2810                .map(|w| w.message)
2811                .collect();
2812            assert_eq!(typed, motor.flight_warnings(curve), "{}", motor.designation);
2813        }
2814    }
2815
2816    /// Issue #1287: a record whose propellant mass is not below its loaded mass gives no burnout
2817    /// mass to hold a file to, so the burnout check doesn't run and draws no warning, whatever
2818    /// the file's burnout mass, rather than one against a burnout mass of zero or less. The
2819    /// control, a record whose burnout mass is half the file's, does draw it.
2820    #[test]
2821    fn a_record_with_no_burnout_mass_draws_no_burnout_warning() {
2822        let catalog = bundled();
2823        let (base, curve) = catalog
2824            .motors
2825            .iter()
2826            .find_map(|motor| {
2827                let curve = motor.default_curve()?;
2828                (motor.mass_warnings(curve).is_empty()
2829                    && motor.total_mass_g.is_some()
2830                    && motor.propellant_mass_g.is_some())
2831                .then_some((motor, curve))
2832            })
2833            .expect("a motor drawing no mass warning");
2834        let flown_g = base.total_mass_g.expect("a loaded mass");
2835        let burnout_g = flown_g - base.propellant_mass_g.expect("a propellant mass");
2836        let kinds = |record_propellant_g: f64| -> Vec<MotorWarning> {
2837            let mut motor = base.clone();
2838            motor.stated.total_mass_g = Some(flown_g);
2839            motor.stated.propellant_mass_g = Some(record_propellant_g);
2840            motor.flight_warning_kinds(curve)
2841        };
2842        let burnout = |warnings: &[MotorWarning]| {
2843            warnings
2844                .iter()
2845                .filter(|w| w.kind == MotorWarningKind::BurnoutMass)
2846                .count()
2847        };
2848        // The control: the record's burnout mass is half the file's, its propellant between the
2849        // file's and the loaded mass.
2850        let control = kinds(flown_g - 0.5 * burnout_g);
2851        assert_eq!(burnout(&control), 1, "{control:?}");
2852        // No burnout mass in the record: its propellant equals, then exceeds, its loaded mass.
2853        for record_propellant_g in [flown_g, flown_g * 1.2] {
2854            let warnings = kinds(record_propellant_g);
2855            assert_eq!(burnout(&warnings), 0, "{record_propellant_g}: {warnings:?}");
2856            for warning in &warnings {
2857                assert!(
2858                    !warning.message.contains("inf") && !warning.message.contains("NaN"),
2859                    "{warning:?}"
2860                );
2861            }
2862        }
2863    }
2864
2865    /// Issue #1233: the Quest D8's default file gives 454 g loaded where ThrustCurve.org's record
2866    /// gives 45.6 g, ten times as heavy, so it flew a 32 m apogee where the record's mass gives
2867    /// about 369 m, with no word. Flying it now warns twice, naming both loaded masses and its
2868    /// 4.8% propellant share, below every record's. A loaded mass 4.9% from the record draws no
2869    /// warning, one 5.1% from it either way does, and a record with no mass gives none.
2870    #[test]
2871    fn a_loaded_mass_far_from_its_record_warns_naming_both() {
2872        let catalog = bundled();
2873        let d8 = catalog
2874            .motors
2875            .iter()
2876            .find(|motor| motor.manufacturer_abbrev == "Quest" && motor.designation == "D8")
2877            .expect("the Quest D8");
2878        assert_eq!(d8.stated.total_mass_g, Some(45.6));
2879        let curve = d8.default_curve().expect("a bundled file");
2880        let warnings = d8.mass_warnings(curve);
2881        assert_eq!(warnings.len(), 2, "{warnings:?}");
2882        assert!(
2883            warnings[0].contains(
2884                "a loaded mass of 454.0 g, +895.6% from ThrustCurve.org's record of 45.6 g"
2885            ),
2886            "{warnings:?}"
2887        );
2888        assert!(
2889            warnings[1].contains("a propellant share of 4.8%"),
2890            "{warnings:?}"
2891        );
2892        assert!(
2893            warnings[1].contains("outside the 11.5% to 75%"),
2894            "{warnings:?}"
2895        );
2896        assert!(d8.flight_warnings(curve).ends_with(&warnings));
2897
2898        // Either side of the bound, on a motor whose share is inside the span.
2899        let (base, curve) = catalog
2900            .motors
2901            .iter()
2902            .find_map(|motor| {
2903                let curve = motor.default_curve()?;
2904                (motor.mass_warnings(curve).is_empty() && motor.stated.total_mass_g.is_some())
2905                    .then_some((motor, curve))
2906            })
2907            .expect("a motor drawing no mass warning");
2908        let flown_g = base.total_mass_g.expect("a loaded mass");
2909        let flown_propellant_g = base.propellant_mass_g.expect("a propellant mass");
2910        // A record scaled as a whole, its propellant with its loaded mass, so that its burnout
2911        // mass is the same share from the flown one and only the loaded bound is tried.
2912        let warning = |record_g: Option<f64>| {
2913            let mut motor = base.clone();
2914            motor.stated.total_mass_g = record_g;
2915            motor.stated.propellant_mass_g = record_g.map(|g| flown_propellant_g * g / flown_g);
2916            motor.mass_warnings(curve)
2917        };
2918        let heavy = warning(Some(flown_g / 1.051));
2919        assert_eq!(heavy.len(), 1, "5.1% heavy: {heavy:?}");
2920        assert!(heavy[0].contains("a loaded mass of"), "{heavy:?}");
2921        assert!(heavy[0].contains("+5.1%"), "{heavy:?}");
2922        let light = warning(Some(flown_g / 0.949));
2923        assert_eq!(light.len(), 1, "5.1% light: {light:?}");
2924        assert!(light[0].contains("a loaded mass of"), "{light:?}");
2925        assert!(light[0].contains("-5.1%"), "{light:?}");
2926        assert!(warning(Some(flown_g / 1.049)).is_empty(), "4.9% heavy");
2927        assert!(warning(Some(flown_g / 0.951)).is_empty(), "4.9% light");
2928        for record in [None, Some(0.0), Some(f64::INFINITY)] {
2929            assert!(warning(record).is_empty(), "{record:?}");
2930        }
2931        assert_eq!(
2932            warning(Some(f64::NAN)).len(),
2933            0,
2934            "a NaN record is no record"
2935        );
2936
2937        // The loaded mass the record's, the burnout mass 5.1% of the record's burnout mass from
2938        // it either way: warns, naming both burnout masses and the gap; at 4.9%, not (issue
2939        // #1294). The earlier bound, 5% of the loaded mass, warned of neither 5.1% gap.
2940        let flown_burnout_g = flown_g - flown_propellant_g;
2941        let burnout = |gap: f64| {
2942            // The record whose burnout mass the flown one is `gap` of it from.
2943            let mut motor = base.clone();
2944            motor.stated.total_mass_g = Some(flown_g);
2945            motor.stated.propellant_mass_g = Some(flown_g - flown_burnout_g / (1.0 + gap));
2946            motor.mass_warnings(curve)
2947        };
2948        for (gap, said) in [(0.051, "+5.1%"), (-0.051, "-5.1%")] {
2949            let warnings = burnout(gap);
2950            assert_eq!(warnings.len(), 1, "{gap}: {warnings:?}");
2951            let record_burnout = format!("gives {:.1} g", flown_burnout_g / (1.0 + gap));
2952            assert!(warnings[0].contains("burnout mass"), "{warnings:?}");
2953            assert!(
2954                warnings[0].contains(&record_burnout) && warnings[0].contains(said),
2955                "{record_burnout} {said}: {warnings:?}"
2956            );
2957            // History, not the library: the earlier bound, 5% of the loaded mass, passed it.
2958            assert!(
2959                (flown_burnout_g / (1.0 + gap) - flown_burnout_g).abs()
2960                    < LOADED_MASS_BOUND * flown_g,
2961                "the earlier bound passed it"
2962            );
2963        }
2964        for gap in [0.049, -0.049] {
2965            assert!(burnout(gap).is_empty(), "{gap}");
2966        }
2967        // A loaded mass 4.9% light with the record's propellant: the whole gap falls on the case,
2968        // more than 5% of its mass, so the burnout mass warns, though the loaded mass doesn't.
2969        let mut light_case = base.clone();
2970        light_case.stated.total_mass_g = Some(flown_g / 0.951);
2971        light_case.stated.propellant_mass_g = Some(flown_propellant_g);
2972        let warnings = light_case.mass_warnings(curve);
2973        assert_eq!(warnings.len(), 1, "{warnings:?}");
2974        assert!(warnings[0].contains("burnout mass"), "{warnings:?}");
2975    }
2976
2977    /// Issue #1233's physics review: a file other than the default flies the entry's propellant
2978    /// mass (the default file's), so the propellant warning is held to that mass, not the
2979    /// file's header. AeroTech I225FJ's other file flies 241.7 g against the record's 264 g.
2980    #[test]
2981    fn a_non_default_file_is_warned_of_the_propellant_it_flies() {
2982        let catalog = bundled();
2983        let mut checked = 0;
2984        for motor in &catalog.motors {
2985            let Some(record_g) = motor.stated.propellant_mass_g.filter(|g| *g > 0.0) else {
2986                continue;
2987            };
2988            let Some(flown_g) = motor.propellant_mass_g else {
2989                continue;
2990            };
2991            for curve in &motor.curves {
2992                if bundled_curve_text(&curve.file).is_none() {
2993                    continue;
2994                }
2995                let short = flown_g < record_g * (1.0 - PROPELLANT_SHORT_BOUND);
2996                assert_eq!(
2997                    motor.propellant_warning(curve).is_some(),
2998                    short,
2999                    "{} {}",
3000                    motor.designation,
3001                    curve.simfile_id
3002                );
3003                checked += 1;
3004            }
3005        }
3006        assert!(checked > 1_000, "{checked}");
3007        let i225 = catalog
3008            .motors
3009            .iter()
3010            .find(|motor| motor.designation == "I225FJ")
3011            .expect("the I225FJ");
3012        let other = i225
3013            .curves
3014            .iter()
3015            .find(|curve| {
3016                Some(curve.simfile_id.as_str())
3017                    != i225.default_curve().map(|c| c.simfile_id.as_str())
3018                    && bundled_curve_text(&curve.file).is_some()
3019            })
3020            .expect("a second bundled file");
3021        let warning = i225.propellant_warning(other).expect("warns");
3022        assert!(
3023            warning.contains("the default file's 241.7 g of propellant"),
3024            "{warning}"
3025        );
3026        assert!(warning.contains("record of 264.0 g"), "{warning}");
3027    }
3028
3029    /// [`PROPELLANT_SHARE_SPAN`] is the span of the bundled records' shares, propellant over
3030    /// loaded mass, leaving out only shares above 1, which no motor can have.
3031    #[test]
3032    fn the_propellant_share_span_is_the_records() {
3033        let shares: Vec<f64> = bundled()
3034            .motors
3035            .iter()
3036            .filter_map(|motor| Some(motor.stated.propellant_mass_g? / motor.stated.total_mass_g?))
3037            .filter(|share| share.is_finite() && *share > 0.0)
3038            .collect();
3039        let impossible = shares.iter().filter(|share| **share > 1.0).count();
3040        assert_eq!(impossible, 1);
3041        let possible = shares.iter().copied().filter(|share| *share <= 1.0);
3042        let low = possible.clone().fold(f64::INFINITY, f64::min);
3043        let high = possible.fold(f64::NEG_INFINITY, f64::max);
3044        assert_eq!((low, high), PROPELLANT_SHARE_SPAN);
3045    }
3046
3047    /// ADR-302: a name never picks one maker's motor over another's. Each motor is found by each
3048    /// of its names, unless its own maker has another motor whose designation is that name; and
3049    /// a name several makers use finds each of them (`G80`, `J300`).
3050    #[test]
3051    fn a_name_never_picks_one_maker_over_another() {
3052        let catalog = bundled();
3053        for motor in &catalog.motors {
3054            for name in [&motor.designation, &motor.common_name] {
3055                let shadowed = normalize(name) != normalize(&motor.designation)
3056                    && catalog.motors.iter().any(|other| {
3057                        other.manufacturer == motor.manufacturer
3058                            && normalize(&other.designation) == normalize(name)
3059                    });
3060                let found = catalog.find(name).any(|other| std::ptr::eq(other, motor));
3061                assert_eq!(found, !shadowed, "{} by {name}", motor.motor_id);
3062            }
3063        }
3064        for name in ["G80", "J300"] {
3065            let makers: std::collections::BTreeSet<&str> = catalog
3066                .find(name)
3067                .map(|motor| motor.manufacturer.as_str())
3068                .collect();
3069            assert!(makers.len() > 1, "{name}: {makers:?}");
3070        }
3071    }
3072
3073    /// `normalized_is` answers as comparing `normalize`'s strings does, on every pair of names of
3074    /// the catalog's first 200 motors.
3075    #[test]
3076    fn normalized_is_is_normalize_compared() {
3077        let catalog = bundled();
3078        let names: Vec<&str> = catalog
3079            .motors
3080            .iter()
3081            .take(200)
3082            .flat_map(|motor| [motor.designation.as_str(), motor.common_name.as_str()])
3083            .chain(["", "J 760", "j-760", "1266J760-19A", "ÄÖ", "K\u{a0}940"])
3084            .collect();
3085        for name in &names {
3086            for other in &names {
3087                let key = normalize(other);
3088                assert_eq!(
3089                    normalized_is(name, &key),
3090                    normalize(name) == key,
3091                    "{name} {other}"
3092                );
3093            }
3094        }
3095    }
3096
3097    /// A design file's `J360` from Cesaroni is the 38 mm motor of that designation where the
3098    /// design's case is 38 mm or not given, and is refused (both motors given) where the case is
3099    /// 54 mm, the size of the motor whose common name is `J360`; a maker's company suffix is
3100    /// ignored.
3101    #[test]
3102    fn a_design_s_case_size_keeps_a_common_name_from_flying_another_motor() {
3103        let catalog = bundled();
3104        let found = |maker: &str, diameter_mm: Option<f64>| -> Vec<(String, f64)> {
3105            catalog
3106                .find_for_design(maker, "J360", None, diameter_mm)
3107                .into_iter()
3108                .map(|motor| (motor.designation.clone(), motor.diameter_mm))
3109                .collect()
3110        };
3111        let small = vec![("J360".to_owned(), 38.0)];
3112        assert_eq!(found("Cesaroni Technology", None), small);
3113        assert_eq!(found("Cesaroni Technology", Some(38.4)), small);
3114        assert_eq!(found("Cesaroni Technology Inc.", Some(38.0)), small);
3115        assert_eq!(found("Cesaroni", Some(54.0)).len(), 2);
3116        assert_eq!(
3117            catalog
3118                .find_by_maker("Cesaroni Technology Inc.", "J360")
3119                .count(),
3120            1
3121        );
3122    }
3123
3124    /// ADR-302 §1's guard for a motor named by hand (issue #1261): `J360` in a 54 mm mount names
3125    /// both Cesaroni motors, the 38 mm `J360` and the 54 mm `1016J360-15A`, so it is refused as
3126    /// ambiguous; in a 38 mm mount, or one a little narrower than 38 mm, the `J360` alone. A name
3127    /// the bore doesn't split stays as [`Catalog::find`] gives it.
3128    #[test]
3129    fn a_mount_s_bore_keeps_a_common_name_from_flying_another_motor() {
3130        let catalog = bundled();
3131        let found = |name: &str, bore_mm: f64| -> Vec<(String, f64)> {
3132            let mut found: Vec<(String, f64)> = catalog
3133                .find_for_bore(name, bore_mm)
3134                .into_iter()
3135                .map(|motor| (motor.designation.clone(), motor.diameter_mm))
3136                .collect();
3137            found.sort_by(|a, b| a.0.cmp(&b.0));
3138            found
3139        };
3140        let both = vec![("1016J360-15A".to_owned(), 54.0), ("J360".to_owned(), 38.0)];
3141        let small = vec![("J360".to_owned(), 38.0)];
3142        // A 54 mm mount tube's bore, 2.17 in, and one drawn at the case's own size.
3143        assert_eq!(found("J360", 55.1), both);
3144        assert_eq!(found("J360", 54.0), both);
3145        assert_eq!(found("Cesaroni J360", 54.0), both);
3146        // A 38 mm bore, and one a little under (a tight fit the design checks warn of).
3147        assert_eq!(found("J360", 38.4), small);
3148        assert_eq!(found("J360", 37.5), small);
3149        // A 76.2 mm bore fits neither closely: the 54 mm motor is closer by 16 mm, so both.
3150        assert_eq!(found("J360", 76.2), both);
3151        // Its own designation names the 54 mm motor alone, whatever the bore.
3152        assert_eq!(
3153            found("1016J360-15A", 38.4),
3154            vec![("1016J360-15A".to_owned(), 54.0)]
3155        );
3156        // A name the bore doesn't split: what `find` gives.
3157        for (name, bore_mm) in [("H128W", 29.0), ("G80", 29.0), ("K1100T", 55.1)] {
3158            let find: Vec<&str> = catalog.find(name).map(|m| m.designation.as_str()).collect();
3159            let bore: Vec<&str> = catalog
3160                .find_for_bore(name, bore_mm)
3161                .into_iter()
3162                .map(|m| m.designation.as_str())
3163                .collect();
3164            assert_eq!(bore, find, "{name}");
3165        }
3166    }
3167
3168    /// ADR-298 §5: the default is the first ranked file that is bundled. A passing file listed
3169    /// after a failing one flies; a passing file that isn't bundled is passed over for a failing
3170    /// one that is, and a motor with no bundled file has no default.
3171    #[test]
3172    fn the_default_file_passes_where_a_bundled_one_does() {
3173        let catalog = bundled();
3174        let base = catalog
3175            .motors
3176            .iter()
3177            .find(|m| m.curves.first().is_some_and(|c| c.check.passes))
3178            .unwrap();
3179        let passing = base.curves[0].clone();
3180        let mut failing = passing.clone();
3181        failing.simfile_id = "failing".to_owned();
3182        failing.check.passes = false;
3183        let mut not_bundled = passing.clone();
3184        not_bundled.simfile_id = "not bundled".to_owned();
3185        not_bundled.file = "curves/not-bundled.eng".to_owned();
3186        let mut motor = base.clone();
3187        motor.curves = vec![failing.clone(), passing.clone()];
3188        assert_eq!(motor.default_curve(), Some(&passing));
3189        motor.curves = vec![not_bundled.clone(), failing.clone()];
3190        assert_eq!(motor.default_curve(), Some(&failing));
3191        assert!(motor.bundled_motor().is_ok());
3192        motor.curves = vec![not_bundled];
3193        assert_eq!(motor.default_curve(), None);
3194        assert!(matches!(
3195            motor.bundled_motor(),
3196            Err(MotorError::Inconsistent(message)) if message.contains("no bundled curve")
3197        ));
3198    }
3199}