Skip to main content

hpr_forensics/synthetic/
intervals.rs

1//! The readings' 90% intervals held to the synthetic flights' truth ([ADR-257][adr-257] §1–2,
2//! [ADR-308][adr-308]).
3//!
4//! Each flight's own log is read by `hpr_flightdata::readings`, and each reading that states a
5//! 90% interval ([`hpr_flightdata::readings::interval`]) is compared with the flight's truth:
6//! below the interval, inside it, or above it. The coverage test of [ADR-257][adr-257] §1,
7//! calibrated intervals, takes the three counts over a
8//! set, each with its two-sided 99.9% Clopper–Pearson band: the two tails' bands must each hold
9//! 5%, and the band of the count inside must hold 90%. At 1,000 readings a tail passes with 29 to
10//! 74 misses. Three probes must each fail it: every interval narrowed to 0.8 of its width about
11//! its middle, widened to 1.25, and shifted down by one stated standard error, the width over
12//! `2 × 1.645`. For normal errors those hold the truth about 81% and 96% of the time, and the
13//! shifted one misses above about 26% of the time.
14//!
15//! A floor's truth may lie any amount above it, so it states only a lower end, tested on its lower
16//! tail alone: the band on the share of truths below it must hold 5%, raised one stated standard
17//! error and lowered two it must not ([`FloorCheck`]). A top acceleration's floors come from logs
18//! clipping at 8 g, its top scaled to anywhere the reader can call it clipped and the part may
19//! not have clipped ([`top_over_clip`]), and its top as flown, which may miss less but not more.
20//!
21//! The intervals' shares are fitted on [`Set::Calibration`](super::Set::Calibration) ([`fitted`]); the test runs on
22//! [`Set::A`](super::Set::A) and [`Set::B`](super::Set::B), which the shares never see.
23//!
24//! [adr-257]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0257-the-2026-10-13-review-calibrated-intervals-and-the-post-flight-comparison.md
25//! [adr-308]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0308-m7-2e-in-four-the-intervals-by-reading-then-the-surfaces.md
26
27use std::collections::BTreeMap;
28
29use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
30use hpr_flightdata::log::FlightLog;
31use hpr_flightdata::readings::interval::{self, FloorShares, Interval, Shares, Z_90};
32use hpr_flightdata::readings::{self, GRAVITY_TOLERANCE_G, Reading, Reason};
33use serde::{Deserialize, Serialize};
34
35use super::designs::DESIGNS;
36use super::held::{Quantity, top_specific_force};
37use super::logger::{
38    ACCEL_BIAS_G, LOWER_RANGE_G, accelerometer_log_clipping_at, accelerometer_log_top_scaled,
39};
40use super::smoothed::{BAND_CONFIDENCE, MISS_SHARE, clopper_pearson_lower, clopper_pearson_upper};
41use super::{Flight, SyntheticError};
42
43/// The readings that state a 90% interval, in the report's order.
44pub const STATED: [Quantity; 12] = [
45    Quantity::Liftoff,
46    Quantity::ApogeeHeight,
47    Quantity::ApogeeTime,
48    Quantity::TopSpeed,
49    Quantity::Landing,
50    Quantity::FlightTime,
51    Quantity::DescentRate,
52    Quantity::TopAcceleration,
53    Quantity::Burnout,
54    Quantity::DrogueRate,
55    Quantity::MainOpening,
56    Quantity::MainRate,
57];
58
59/// The share of readings whose truth the interval must hold.
60pub const INSIDE_SHARE: f64 = 0.90;
61
62/// The fewest floors whose test a probe can fail: of 148, no truth below still holds 5%.
63pub const LEAST_FLOORS: u64 = 149;
64
65/// The readings that state a lower end where they are a floor, in the report's order.
66pub const FLOORED: [Quantity; 2] = [Quantity::TopAcceleration, Quantity::Burnout];
67
68/// The library's shares for `quantity`; `None` for a reading that states no interval yet.
69pub fn shares(quantity: Quantity) -> Option<Shares> {
70    match quantity {
71        Quantity::ApogeeHeight => Some(interval::APOGEE_HEIGHT_SHARES),
72        Quantity::ApogeeTime => Some(interval::APOGEE_TIME_SHARES),
73        Quantity::Liftoff => Some(interval::LIFTOFF_SHARES),
74        Quantity::TopSpeed => Some(interval::TOP_SPEED_SHARES),
75        Quantity::Landing => Some(interval::LANDING_SHARES),
76        Quantity::FlightTime => Some(interval::FLIGHT_TIME_SHARES),
77        Quantity::DescentRate => Some(interval::DESCENT_RATE_SHARES),
78        Quantity::TopAcceleration => Some(interval::TOP_ACCELERATION_SHARES),
79        Quantity::Burnout => Some(interval::BURNOUT_SHARES),
80        Quantity::DrogueRate => Some(interval::DROGUE_RATE_SHARES),
81        Quantity::MainOpening => Some(interval::MAIN_OPENING_SHARES),
82        Quantity::MainRate => Some(interval::MAIN_RATE_SHARES),
83    }
84}
85
86/// The library's floor shares for `quantity`; `None` for a reading that is never a floor here.
87pub fn floor_shares(quantity: Quantity) -> Option<FloorShares> {
88    match quantity {
89        Quantity::TopAcceleration => Some(interval::TOP_ACCELERATION_FLOOR_SHARES),
90        Quantity::Burnout => Some(interval::BURNOUT_FLOOR_SHARES),
91        _ => None,
92    }
93}
94
95/// Whether `quantity` withheld for `reason` from a log with a barometer is the reading's own rule
96/// and not a reading lost: the top speed is withheld at or above
97/// `hpr_flightdata::readings::TRANSONIC_SPEED_M_S`, 227.7 m/s, where the barometer's port may
98/// read the transonic flow over the nose. The rule looks at the reading, not the truth, so the
99/// test holds the readings it lets through, as a user sees them. A burnout taken from that speed
100/// goes with it, and a log with no accelerometer gives no top acceleration.
101pub fn withheld_by_rule(quantity: Quantity, reason: Reason) -> bool {
102    matches!(
103        (quantity, reason),
104        (Quantity::TopSpeed | Quantity::Burnout, Reason::Transonic)
105            | (Quantity::TopAcceleration, Reason::NoAccelerometer)
106    )
107}
108
109/// One reading's interval against its truth.
110#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
111pub struct Compared {
112    /// The reading.
113    pub reading: f64,
114    /// The bound it states.
115    pub bound: f64,
116    /// Its 90% interval.
117    pub interval: Interval,
118    /// The truth, on the reading's own scale and clock.
119    pub truth: f64,
120}
121
122impl Compared {
123    /// Its error as a share of its bound, `(reading − truth)/bound`: what the shares are fitted
124    /// to.
125    pub fn share(&self) -> f64 {
126        (self.reading - self.truth) / self.bound
127    }
128}
129
130/// One floor's lower end against its truth.
131#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
132pub struct ComparedFloor {
133    /// The reading.
134    pub reading: f64,
135    /// The bound it states.
136    pub bound: f64,
137    /// Its lower end.
138    pub low: f64,
139    /// The lower end's standard error.
140    pub standard_error: f64,
141    /// The truth.
142    pub truth: f64,
143}
144
145impl ComparedFloor {
146    /// Its error as a share of its bound, `(reading − truth)/bound`: what its share is fitted to.
147    pub fn share(&self) -> f64 {
148        (self.reading - self.truth) / self.bound
149    }
150
151    /// Whether its truth lies below `low`. A truth that isn't a number counts, as does a `low`
152    /// that isn't one.
153    pub fn below(&self, low: f64) -> bool {
154        self.truth.is_nan() || low.is_nan() || self.truth < low
155    }
156}
157
158/// What one log said of one reading.
159#[derive(Debug, Clone, Copy, PartialEq)]
160pub enum Said {
161    /// Read, with a 90% interval.
162    Stated(Compared),
163    /// Read as a floor, with its lower end.
164    Floor(ComparedFloor),
165    /// Read with neither: a bound no interval can be formed from.
166    Unstated,
167    /// A top acceleration's floor on the flight's log with its top as flown, past the clip by as
168    /// much as its design takes it: checked apart, not fitted or tested as [`Said::Floor`] is.
169    PastClip(ComparedFloor),
170    /// A top acceleration read whole, or as a floor no lower end is stated on, on the log scaled
171    /// near the clip: no floor, so out of the floors' count, and counted.
172    WholeAtClip,
173    /// The same on the log with its top as flown.
174    WholePastClip,
175    /// None to read: a drogue, or a main's opening, on a flight that came down under one canopy
176    /// or none.
177    Absent,
178    /// Withheld, for this reason.
179    Withheld(Reason),
180}
181
182/// A flight's index, its design, logger and day's air, and what its own log said of each of
183/// [`STATED`].
184#[derive(Debug, Clone, PartialEq)]
185pub struct FlightSaid {
186    /// Its index in its set.
187    pub index: u64,
188    /// Its design, an index into [`DESIGNS`].
189    pub design: usize,
190    /// Its logger's name.
191    pub logger: &'static str,
192    /// The day's air, K from the 1976 standard atmosphere.
193    pub air_offset_k: f64,
194    /// Each of [`STATED`], in that order.
195    pub said: Vec<(Quantity, Said)>,
196}
197
198/// What a log read of one reading, with its truth.
199struct Part {
200    reading: f64,
201    bound: f64,
202    interval: Option<Interval>,
203    lower_end: Option<f64>,
204    truth: f64,
205}
206
207impl Part {
208    /// A reading that gives no floor's lower end: a floor of its own, with no interval, is unstated.
209    fn of(reading: f64, bound: f64, interval: Option<Interval>, truth: f64) -> Self {
210        Self {
211            reading,
212            bound,
213            interval,
214            lower_end: None,
215            truth,
216        }
217    }
218}
219
220/// What `flight`'s own log says of each of [`STATED`], against its truth.
221///
222/// # Errors
223///
224/// [`SyntheticError`] if the log the top acceleration's floors are read from can't be written.
225pub fn said(seed: u64, index: u64, flight: &Flight) -> Result<FlightSaid, SyntheticError> {
226    let read = readings::read(&flight.log);
227    let truth = &flight.truth;
228    let pad_s = flight.draw.logger.pad_s;
229    let events = &truth.events;
230    // The truths are `held::outcomes`' own: times on the log's clock, the apogee above the pad,
231    // the mean descent rate the apogee's height over the time from apogee to landing, and a leg's
232    // rate the true height lost over the leg the reading names.
233    let descent_rate = events.apogee_m / (events.landing_s - events.apogee_s);
234    let height = |t_log: f64| truth.at(t_log - pad_s).map_or(f64::NAN, |x| x.height_m);
235    let chord = |from_s: f64, to_s: f64| (height(from_s) - height(to_s)) / (to_s - from_s);
236    let deployments = events.deployments.len();
237    let two_canopies = deployments >= 2;
238    fn of<T>(reading: &Reading<T>, take: impl Fn(&T) -> Part) -> Result<Part, Said> {
239        match reading {
240            Reading::Read(value) => Ok(take(value)),
241            Reading::Withheld(withheld) => Err(Said::Withheld(withheld.reason)),
242        }
243    }
244    let mut said: Vec<(Quantity, Said)> = STATED
245        .iter()
246        .map(|&quantity| {
247            let part = match quantity {
248                Quantity::Liftoff => of(&read.liftoff, |l| {
249                    Part::of(l.time_s, l.bound_s, l.interval_s, pad_s + events.liftoff_s)
250                }),
251                Quantity::ApogeeHeight => of(&read.apogee, |a| {
252                    Part::of(
253                        a.height_m,
254                        a.bound_m,
255                        a.height_interval_m,
256                        truth.apogee_above_pad_m(),
257                    )
258                }),
259                Quantity::ApogeeTime => of(&read.apogee, |a| {
260                    Part::of(
261                        a.time_s,
262                        a.time_bound_s,
263                        a.time_interval_s,
264                        pad_s + events.apogee_s,
265                    )
266                }),
267                Quantity::TopSpeed => of(&read.max_speed, |s| {
268                    Part::of(
269                        s.speed_m_s,
270                        s.bound_m_s,
271                        s.interval_m_s,
272                        truth.top_speed().0,
273                    )
274                }),
275                Quantity::Landing => of(&read.landing, |l| {
276                    Part::of(l.time_s, l.bound_s, l.interval_s, pad_s + events.landing_s)
277                }),
278                Quantity::FlightTime => of(&read.flight_time, |f| {
279                    Part::of(
280                        f.time_s,
281                        f.bound_s,
282                        f.interval_s,
283                        events.landing_s - events.liftoff_s,
284                    )
285                }),
286                Quantity::DescentRate => of(&read.landing, |l| {
287                    Part::of(
288                        l.mean_descent_rate_m_s,
289                        l.mean_descent_rate_bound_m_s,
290                        l.mean_descent_rate_interval_m_s,
291                        descent_rate,
292                    )
293                }),
294                Quantity::TopAcceleration => of(&read.max_acceleration, |a| Part {
295                    reading: a.acceleration_m_s2,
296                    bound: a.bound_m_s2,
297                    interval: a.interval_m_s2,
298                    lower_end: a.lower_end_m_s2,
299                    truth: top_specific_force(flight),
300                }),
301                Quantity::Burnout => of(&read.burnout, |b| Part {
302                    reading: b.time_s,
303                    bound: b.bound_s,
304                    interval: b.interval_s,
305                    lower_end: b.lower_end_s,
306                    truth: pad_s + events.burnout_s,
307                }),
308                Quantity::DrogueRate => match &read.drogue_descent {
309                    Reading::Withheld(withheld)
310                        if withheld.reason == Reason::OneCanopy && !two_canopies =>
311                    {
312                        Err(Said::Absent)
313                    }
314                    drogue => of(drogue, |d| {
315                        Part::of(
316                            d.rate_m_s,
317                            d.bound_m_s,
318                            d.interval_m_s,
319                            chord(d.from_s, d.to_s),
320                        )
321                    }),
322                },
323                Quantity::MainOpening => match &read.main_descent {
324                    Reading::Withheld(withheld) => Err(Said::Withheld(withheld.reason)),
325                    Reading::Read(main) => match main.opening {
326                        // A main named where the flight opened one canopy, or none, misses both
327                        // ways.
328                        Some(opening) => Ok(Part::of(
329                            opening.time_s,
330                            opening.bound_s,
331                            opening.interval_s,
332                            if two_canopies {
333                                pad_s + events.deployments[deployments - 1].1
334                            } else {
335                                f64::NAN
336                            },
337                        )),
338                        // One canopy read where the flight opened two.
339                        None if two_canopies => Err(Said::Withheld(Reason::OneCanopy)),
340                        None => Err(Said::Absent),
341                    },
342                },
343                Quantity::MainRate => of(&read.main_descent, |d| {
344                    Part::of(
345                        d.rate_m_s,
346                        d.bound_m_s,
347                        d.interval_m_s,
348                        chord(d.from_s, d.to_s),
349                    )
350                }),
351            };
352            let said = match part {
353                Err(said) => said,
354                Ok(Part {
355                    reading,
356                    bound,
357                    interval: Some(interval),
358                    truth,
359                    ..
360                }) => Said::Stated(Compared {
361                    reading,
362                    bound,
363                    interval,
364                    truth,
365                }),
366                Ok(Part {
367                    reading,
368                    bound,
369                    lower_end: Some(low),
370                    truth,
371                    ..
372                }) => Said::Floor(compared_floor(quantity, reading, bound, low, truth)),
373                Ok(_) => Said::Unstated,
374            };
375            (quantity, said)
376        })
377        .collect();
378    // No flight's own accelerometer clips, so a top acceleration's floors come from logs that do.
379    let top = top_specific_force(flight);
380    if let (Some(scale), true) = (
381        flight.draw.logger.profile.accelerometer_scale(),
382        top > STANDARD_GRAVITY_MPS2,
383    ) {
384        let range = LOWER_RANGE_G * STANDARD_GRAVITY_MPS2;
385        let near = range * top_over_clip(seed, index, scale);
386        let log = accelerometer_log_top_scaled(
387            &flight.draw.logger,
388            truth,
389            (top, near),
390            LOWER_RANGE_G,
391            seed,
392            index,
393        )?;
394        if let Some(log) = log {
395            said.push((
396                Quantity::TopAcceleration,
397                clipped_top(&log, near, Said::Floor, Said::WholeAtClip),
398            ));
399        }
400        let log =
401            accelerometer_log_clipping_at(&flight.draw.logger, truth, LOWER_RANGE_G, seed, index)?;
402        if let Some(log) = log {
403            said.push((
404                Quantity::TopAcceleration,
405                clipped_top(&log, top, Said::PastClip, Said::WholePastClip),
406            ));
407        }
408    }
409    Ok(FlightSaid {
410        index,
411        design: flight.draw.design,
412        logger: flight.draw.logger.profile.name(),
413        air_offset_k: flight.draw.temperature_offset_k,
414        said,
415    })
416}
417
418/// Flight `index`'s top over the clip on the log its lower end is fitted on, for a part whose
419/// scale error runs to ±`scale`. It spreads evenly over every top the reader can call clipped and
420/// the part may not have clipped. At the bottom, the reader calls a top clipped from
421/// [`GRAVITY_TOLERANCE_G`] under the range, and the part's gain and [`ACCEL_BIAS_G`] can carry a
422/// truth up to that: `(1 − (tolerance + bias)/range)/(1 + scale)`. At the top, past
423/// `1/(1 − scale)` every such part clips and the truth lies above the reading. A lower top simply
424/// reads whole, and doesn't count. Each flight's place is its own, the golden ratio's multiples
425/// from a start each set's seed sets, so no design's thrust sets it and no two sets share it.
426pub fn top_over_clip(seed: u64, index: u64, scale: f64) -> f64 {
427    let least = (1.0 - (GRAVITY_TOLERANCE_G + ACCEL_BIAS_G) / LOWER_RANGE_G) / (1.0 + scale);
428    let most = 1.0 / (1.0 - scale);
429    let start = (seed % 1_000_000) as f64 * 0.754_877_666_246_692_7;
430    let place = (start + index as f64 * 0.618_033_988_749_894_9).fract();
431    least + (most - least) * place
432}
433
434/// What `log` reads of its top acceleration against the `truth`: as `floor` where it's clipped
435/// with a lower end; as `whole` where it isn't; withheld, which `xtask synthetic` fails on.
436fn clipped_top(log: &FlightLog, truth: f64, floor: fn(ComparedFloor) -> Said, whole: Said) -> Said {
437    let top = match readings::read(log).max_acceleration {
438        Reading::Read(top) => top,
439        Reading::Withheld(withheld) => return Said::Withheld(withheld.reason),
440    };
441    let Some(low) = top.lower_end_m_s2 else {
442        return whole;
443    };
444    floor(compared_floor(
445        Quantity::TopAcceleration,
446        top.acceleration_m_s2,
447        top.bound_m_s2,
448        low,
449        truth,
450    ))
451}
452
453/// A floor with its lower end's standard error. A quantity with no floor shares states none, so
454/// its probes don't move it.
455fn compared_floor(
456    quantity: Quantity,
457    reading: f64,
458    bound: f64,
459    low: f64,
460    truth: f64,
461) -> ComparedFloor {
462    ComparedFloor {
463        reading,
464        bound,
465        low,
466        standard_error: floor_shares(quantity).map_or(0.0, |shares| shares.standard_error(bound)),
467        truth,
468    }
469}
470
471/// A change to every floor's lower end that its test must catch.
472#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
473#[serde(rename_all = "kebab-case")]
474pub enum FloorProbe {
475    /// Raised by one stated standard error.
476    Raised,
477    /// Lowered by two stated standard errors. One is too little to fail on a few hundred floors:
478    /// of 210 the band holds 5% down to 2 truths below, and a floor's lower side has a long tail.
479    Lowered,
480}
481
482impl FloorProbe {
483    /// Every probe.
484    pub const ALL: [Self; 2] = [Self::Raised, Self::Lowered];
485
486    /// Its name in the report.
487    pub fn name(self) -> &'static str {
488        match self {
489            Self::Raised => "raised one standard error",
490            Self::Lowered => "lowered two standard errors",
491        }
492    }
493
494    /// `floor`'s lower end, changed.
495    pub fn apply(self, floor: &ComparedFloor) -> f64 {
496        match self {
497            Self::Raised => floor.low + floor.standard_error,
498            Self::Lowered => floor.low - 2.0 * floor.standard_error,
499        }
500    }
501}
502
503/// The test of a floor's lower end, the coverage test's lower tail: the band on the share of
504/// truths below it must hold 5%.
505#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
506pub struct FloorTest {
507    /// Floors compared.
508    pub given: u64,
509    /// The truth below the lower end. A truth that isn't a number counts.
510    pub below: u64,
511    /// The band on the share below.
512    pub band: Band,
513}
514
515impl FloorTest {
516    /// The test on `below` of `given`.
517    pub fn of(given: u64, below: u64) -> Self {
518        Self {
519            given,
520            below,
521            band: Band::of(below, given),
522        }
523    }
524
525    /// Whether it passes: the band holds 5%.
526    pub fn passes(&self) -> bool {
527        self.band.holds(MISS_SHARE)
528    }
529
530    /// Whether its band reaches down to 5% or lower: the truths below it aren't more than 5%.
531    pub fn no_more_than_its_share(&self) -> bool {
532        self.band.low <= MISS_SHARE
533    }
534}
535
536/// One reading's floors on one set.
537#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
538pub struct FloorCheck {
539    /// The test on the lower ends as stated.
540    pub test: FloorTest,
541    /// The test on each probe's lower ends; each must fail.
542    pub probes: BTreeMap<FloorProbe, FloorTest>,
543    /// Compared and below, by logger.
544    pub by_logger: BTreeMap<String, (u64, u64)>,
545    /// Compared and below, by design.
546    pub by_design: BTreeMap<String, (u64, u64)>,
547}
548
549impl FloorCheck {
550    /// Whether it comes out as it must: the test passes and every probe fails it.
551    pub fn holds(&self) -> bool {
552        self.test.passes() && self.probes.values().all(|t| !t.passes())
553    }
554
555    /// The check over `floors`, each with its logger and design; `None` when there are none.
556    fn of<'a>(floors: impl Iterator<Item = (&'a str, usize, &'a ComparedFloor)>) -> Option<Self> {
557        let (mut given, mut misses) = (0, 0);
558        let mut probed: BTreeMap<FloorProbe, u64> =
559            FloorProbe::ALL.iter().map(|&p| (p, 0)).collect();
560        let mut by_logger: BTreeMap<String, (u64, u64)> = BTreeMap::new();
561        let mut by_design: BTreeMap<String, (u64, u64)> = BTreeMap::new();
562        for (logger, design, floor) in floors {
563            let missed = u64::from(floor.below(floor.low));
564            given += 1;
565            misses += missed;
566            let entry = by_logger.entry(logger.to_owned()).or_default();
567            entry.0 += 1;
568            entry.1 += missed;
569            let entry = by_design
570                .entry(DESIGNS[design].name.to_owned())
571                .or_default();
572            entry.0 += 1;
573            entry.1 += missed;
574            for (probe, count) in &mut probed {
575                *count += u64::from(floor.below(probe.apply(floor)));
576            }
577        }
578        (given > 0).then(|| Self {
579            test: FloorTest::of(given, misses),
580            probes: probed
581                .into_iter()
582                .map(|(p, x)| (p, FloorTest::of(given, x)))
583                .collect(),
584            by_logger,
585            by_design,
586        })
587    }
588}
589
590/// A change to every interval that the coverage test must catch.
591#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
592#[serde(rename_all = "kebab-case")]
593pub enum Probe {
594    /// Narrowed to 0.8 of its width about its middle.
595    Narrowed,
596    /// Widened to 1.25 of its width about its middle.
597    Widened,
598    /// Shifted down by one stated standard error, its width over `2 Z_90`.
599    ShiftedDown,
600}
601
602impl Probe {
603    /// Every probe.
604    pub const ALL: [Self; 3] = [Self::Narrowed, Self::Widened, Self::ShiftedDown];
605
606    /// Its name in the report.
607    pub fn name(self) -> &'static str {
608        match self {
609            Self::Narrowed => "narrowed to 0.8",
610            Self::Widened => "widened to 1.25",
611            Self::ShiftedDown => "shifted down one standard error",
612        }
613    }
614
615    /// `interval`, changed.
616    pub fn apply(self, interval: Interval) -> Interval {
617        let middle = 0.5 * (interval.low + interval.high);
618        let half = 0.5 * (interval.high - interval.low);
619        let about = |factor: f64| Interval {
620            low: middle - factor * half,
621            high: middle + factor * half,
622        };
623        match self {
624            Self::Narrowed => about(0.8),
625            Self::Widened => about(1.25),
626            Self::ShiftedDown => {
627                let sd = half / Z_90;
628                Interval {
629                    low: interval.low - sd,
630                    high: interval.high - sd,
631                }
632            }
633        }
634    }
635}
636
637/// Readings whose truth lay below their interval, inside it and above it.
638#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
639pub struct Counts {
640    /// Readings compared.
641    pub given: u64,
642    /// The truth below the interval.
643    pub below: u64,
644    /// The truth inside it, ends included.
645    pub inside: u64,
646    /// The truth above it.
647    pub above: u64,
648}
649
650impl Counts {
651    /// Counts `truth` against `interval`. A truth that isn't a number misses on both sides.
652    pub(crate) fn add(&mut self, interval: Interval, truth: f64) {
653        self.given += 1;
654        let below = truth.is_nan() || truth < interval.low;
655        let above = truth.is_nan() || truth > interval.high;
656        self.below += u64::from(below);
657        self.above += u64::from(above);
658        self.inside += u64::from(!below && !above);
659    }
660}
661
662/// A share's two-sided 99.9% Clopper–Pearson band.
663#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
664pub struct Band {
665    /// Its lower edge.
666    pub low: f64,
667    /// Its upper edge.
668    pub high: f64,
669}
670
671impl Band {
672    /// The band on `x` of `n`; NaN, which holds nothing, when `n` is 0.
673    fn of(x: u64, n: u64) -> Self {
674        if n == 0 {
675            return Self {
676                low: f64::NAN,
677                high: f64::NAN,
678            };
679        }
680        Self {
681            low: clopper_pearson_lower(x, n, BAND_CONFIDENCE),
682            high: clopper_pearson_upper(x, n, BAND_CONFIDENCE),
683        }
684    }
685
686    /// Whether it holds `share`. A band that isn't a number holds nothing.
687    pub fn holds(&self, share: f64) -> bool {
688        self.low <= share && share <= self.high
689    }
690}
691
692/// The coverage test on one set of counts: each tail's band must hold 5%, the inside's 90%.
693#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
694pub struct Test {
695    /// The counts.
696    pub counts: Counts,
697    /// The band on the share below.
698    pub below: Band,
699    /// The band on the share inside.
700    pub inside: Band,
701    /// The band on the share above.
702    pub above: Band,
703}
704
705impl Test {
706    /// The test on `counts`.
707    pub fn of(counts: Counts) -> Self {
708        Self {
709            counts,
710            below: Band::of(counts.below, counts.given),
711            inside: Band::of(counts.inside, counts.given),
712            above: Band::of(counts.above, counts.given),
713        }
714    }
715
716    /// Whether it passes: each tail's band holds 5% and the inside's 90%.
717    pub fn passes(&self) -> bool {
718        self.below.holds(MISS_SHARE)
719            && self.above.holds(MISS_SHARE)
720            && self.inside.holds(INSIDE_SHARE)
721    }
722}
723
724/// One reading's check on one set.
725#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
726pub struct Check {
727    /// The reading.
728    pub quantity: Quantity,
729    /// Flights flown.
730    pub flights: u64,
731    /// Read with neither an interval nor a lower end.
732    pub unstated: u64,
733    /// Read as floors.
734    pub floors: u64,
735    /// The floors' test, where any were read.
736    pub floor: Option<FloorCheck>,
737    /// The top acceleration's floors with their tops as flown, past the clip by as much as a
738    /// design takes them: a lower end fitted near the clip must miss no more than 5% of them.
739    pub past_clip: Option<FloorTest>,
740    /// None to read.
741    pub absent: u64,
742    /// Read with no lower end on the log scaled near the clip: out of the floors' count.
743    pub whole_at_clip: u64,
744    /// Read with no lower end on the log with its top as flown: out of the tops past the clip.
745    pub whole_past_clip: u64,
746    /// Withheld, by reason.
747    pub withheld: BTreeMap<Reason, u64>,
748    /// The test on the intervals as stated.
749    pub test: Test,
750    /// The test on each probe's intervals; each must fail.
751    pub probes: BTreeMap<Probe, Test>,
752    /// The counts by design.
753    pub by_design: BTreeMap<String, Counts>,
754    /// The counts by logger.
755    pub by_logger: BTreeMap<String, Counts>,
756    /// The counts by the day's air, in [`AirBand`]'s order.
757    pub by_air: BTreeMap<AirBand, Counts>,
758    /// The mean error, reading less truth, over the readings with an interval, with its sign
759    /// (the apogee's error side, which a reading too low flatters).
760    pub mean_error: f64,
761    /// The largest error's size, `|reading − truth|`, over the same readings: the scale the mean
762    /// is a small difference on. Not a number if any truth isn't one.
763    pub largest_error: f64,
764}
765
766impl Check {
767    /// Whether it comes out as it must: the test passes and every probe fails it.
768    pub fn holds(&self) -> bool {
769        self.test.passes()
770            && self.probes.values().all(|t| !t.passes())
771            && self.floor.as_ref().is_none_or(FloorCheck::holds)
772            && self
773                .past_clip
774                .as_ref()
775                .is_none_or(FloorTest::no_more_than_its_share)
776    }
777}
778
779/// `quantity`'s check over `flights`.
780pub fn check(quantity: Quantity, flights: &[FlightSaid]) -> Check {
781    let mut counts = Counts::default();
782    let mut probes: BTreeMap<Probe, Counts> =
783        Probe::ALL.iter().map(|&p| (p, Counts::default())).collect();
784    let mut by_design: BTreeMap<String, Counts> = BTreeMap::new();
785    let mut by_logger: BTreeMap<String, Counts> = BTreeMap::new();
786    let mut by_air: BTreeMap<AirBand, Counts> = BTreeMap::new();
787    let mut withheld: BTreeMap<Reason, u64> = BTreeMap::new();
788    let mut unstated = 0;
789    let mut floors = 0;
790    let mut absent = 0;
791    let (mut whole_at_clip, mut whole_past_clip) = (0, 0);
792    let mut error_sum = 0.0;
793    let mut largest_error = 0.0_f64;
794    for flight in flights {
795        for (q, said) in &flight.said {
796            if *q != quantity {
797                continue;
798            }
799            match said {
800                Said::Stated(c) => {
801                    counts.add(c.interval, c.truth);
802                    for (probe, counted) in &mut probes {
803                        counted.add(probe.apply(c.interval), c.truth);
804                    }
805                    by_design
806                        .entry(DESIGNS[flight.design].name.to_owned())
807                        .or_default()
808                        .add(c.interval, c.truth);
809                    by_logger
810                        .entry(flight.logger.to_owned())
811                        .or_default()
812                        .add(c.interval, c.truth);
813                    by_air
814                        .entry(AirBand::of(flight.air_offset_k))
815                        .or_default()
816                        .add(c.interval, c.truth);
817                    let error = c.reading - c.truth;
818                    error_sum += error;
819                    // `f64::max` would drop a NaN; a NaN, once in, stays.
820                    if error.is_nan() || error.abs() > largest_error {
821                        largest_error = error.abs();
822                    }
823                }
824                Said::Floor(_) => floors += 1,
825                Said::PastClip(_) => {}
826                Said::WholeAtClip => whole_at_clip += 1,
827                Said::WholePastClip => whole_past_clip += 1,
828                Said::Unstated => unstated += 1,
829                Said::Absent => absent += 1,
830                Said::Withheld(reason) => *withheld.entry(*reason).or_default() += 1,
831            }
832        }
833    }
834    Check {
835        quantity,
836        flights: flights.len() as u64,
837        unstated,
838        floors,
839        past_clip: {
840            let (mut given, mut below) = (0, 0);
841            for (q, said) in flights.iter().flat_map(|f| &f.said) {
842                if let (true, Said::PastClip(floor)) = (*q == quantity, said) {
843                    given += 1;
844                    below += u64::from(floor.below(floor.low));
845                }
846            }
847            (given > 0).then(|| FloorTest::of(given, below))
848        },
849        floor: FloorCheck::of(flights.iter().flat_map(|flight| {
850            flight.said.iter().filter_map(move |(q, said)| match said {
851                Said::Floor(floor) if *q == quantity => Some((flight.logger, flight.design, floor)),
852                _ => None,
853            })
854        })),
855        absent,
856        whole_at_clip,
857        whole_past_clip,
858        withheld,
859        test: Test::of(counts),
860        probes: probes.into_iter().map(|(p, c)| (p, Test::of(c))).collect(),
861        by_design,
862        by_logger,
863        by_air,
864        mean_error: if counts.given == 0 {
865            f64::NAN
866        } else {
867            error_sum / counts.given as f64
868        },
869        largest_error: if counts.given == 0 {
870            f64::NAN
871        } else {
872            largest_error
873        },
874    }
875}
876
877/// `quantity`'s shares fitted again on `flights`, which should be [`Set::Calibration`](super::Set::Calibration)'s; `None`
878/// when fewer than 20 state an interval or a share isn't a number.
879pub fn fitted(quantity: Quantity, flights: &[FlightSaid]) -> Option<Shares> {
880    let shares: Vec<f64> = flights
881        .iter()
882        .flat_map(|f| &f.said)
883        .filter_map(|(q, said)| match said {
884            Said::Stated(c) if *q == quantity => Some(c.share()),
885            _ => None,
886        })
887        .collect();
888    interval::fit(&shares)
889}
890
891/// `quantity`'s floor shares fitted again on `flights`; `None` when fewer than 20 floors are read
892/// or a share isn't a number.
893pub fn fitted_floor(quantity: Quantity, flights: &[FlightSaid]) -> Option<FloorShares> {
894    let shares: Vec<f64> = flights
895        .iter()
896        .flat_map(|f| &f.said)
897        .filter_map(|(q, said)| match said {
898            Said::Floor(floor) if *q == quantity => Some(floor.share()),
899            _ => None,
900        })
901        .collect();
902    interval::fit_floor(&shares)
903}
904
905/// `x` to three significant figures, as the library's shares are written.
906pub fn three_figures(x: f64) -> f64 {
907    if x == 0.0 || !x.is_finite() {
908        return x;
909    }
910    let scale = 10f64.powi(2 - x.abs().log10().floor() as i32);
911    (x * scale).round() / scale
912}
913
914/// A band of the day's air, K from the 1976 standard atmosphere. A barometric height is off by
915/// about `ΔT/T` of itself, so the height's errors, and its misses, gather at the ends of the
916/// synthetic flights' ±15 K: a warm day reads low, a cold one high.
917#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
918#[serde(rename_all = "kebab-case")]
919pub enum AirBand {
920    /// Colder than −10 K.
921    Cold,
922    /// From −10 K to +10 K.
923    Middle,
924    /// Warmer than +10 K.
925    Warm,
926}
927
928impl AirBand {
929    /// Every band, coldest first.
930    pub const ALL: [Self; 3] = [Self::Cold, Self::Middle, Self::Warm];
931
932    /// The band `offset_k` lies in.
933    pub fn of(offset_k: f64) -> Self {
934        if offset_k < -10.0 {
935            Self::Cold
936        } else if offset_k > 10.0 {
937            Self::Warm
938        } else {
939            Self::Middle
940        }
941    }
942
943    /// Its name in the report.
944    pub fn name(self) -> &'static str {
945        match self {
946            Self::Cold => "colder than −10 K",
947            Self::Middle => "−10 to +10 K",
948            Self::Warm => "warmer than +10 K",
949        }
950    }
951}
952
953#[cfg(test)]
954mod tests {
955    use super::*;
956
957    fn compared(truth: f64) -> Said {
958        Said::Stated(Compared {
959            reading: 0.0,
960            bound: 1.0,
961            interval: Interval {
962                low: -Z_90,
963                high: Z_90,
964            },
965            truth,
966        })
967    }
968
969    /// 1,000 flights whose truths sit at the standard normal's quantiles about a reading of 0
970    /// with the interval ±`Z_90`: exactly what a correct 90% interval sees.
971    fn normal_flights() -> Vec<FlightSaid> {
972        (0..1000)
973            .map(|k| {
974                let p = (k as f64 + 0.5) / 1000.0;
975                FlightSaid {
976                    index: k,
977                    design: (k % 10) as usize,
978                    logger: "altos",
979                    air_offset_k: 0.0,
980                    said: vec![(Quantity::ApogeeHeight, compared(normal_quantile(p)))],
981                }
982            })
983            .collect()
984    }
985
986    /// The standard normal's quantile by bisection on its distribution, `½ erfc(−x/√2)`.
987    fn normal_quantile(p: f64) -> f64 {
988        let cdf = |x: f64| 0.5 * erfc(-x / std::f64::consts::SQRT_2);
989        let (mut lo, mut hi) = (-10.0, 10.0);
990        for _ in 0..200 {
991            let mid = 0.5 * (lo + hi);
992            if cdf(mid) < p {
993                lo = mid;
994            } else {
995                hi = mid;
996            }
997        }
998        0.5 * (lo + hi)
999    }
1000
1001    /// `erfc` by its Chebyshev fit, fractional error below 1.2e-7 everywhere (W. H. Press et al.,
1002    /// *Numerical Recipes in C*, 2nd ed., 1992, §6.2, `erfcc`).
1003    fn erfc(x: f64) -> f64 {
1004        let z = x.abs();
1005        let t = 2.0 / (2.0 + z);
1006        let ans = t
1007            * (-z * z - 1.265_512_23
1008                + t * (1.000_023_68
1009                    + t * (0.374_091_96
1010                        + t * (0.096_784_18
1011                            + t * (-0.186_288_06
1012                                + t * (0.278_868_07
1013                                    + t * (-1.135_203_98
1014                                        + t * (1.488_515_87
1015                                            + t * (-0.822_152_23 + t * 0.170_872_77)))))))))
1016                .exp();
1017        if x >= 0.0 { ans } else { 2.0 - ans }
1018    }
1019
1020    #[test]
1021    fn a_correct_interval_passes_and_every_probe_fails() {
1022        let flights = normal_flights();
1023        let check = check(Quantity::ApogeeHeight, &flights);
1024        assert_eq!(check.test.counts.given, 1000);
1025        assert_eq!(check.test.counts.below, 50);
1026        assert_eq!(check.test.counts.above, 50);
1027        assert!(check.test.passes());
1028        for (probe, test) in &check.probes {
1029            assert!(!test.passes(), "{probe:?}: {:?}", test.counts);
1030        }
1031        assert!(check.holds());
1032        assert_eq!(check.by_design.len(), 10);
1033        assert!(check.mean_error.abs() < 1e-3, "{}", check.mean_error);
1034        // The farthest of the 1,000 points is the 0.05% one.
1035        let farthest = normal_quantile(0.0005)
1036            .abs()
1037            .max(normal_quantile(0.9995).abs());
1038        assert_eq!(check.largest_error, farthest);
1039        // The narrowed probe holds about 81%, the widened about 96%, and the shifted one misses
1040        // above about 26% of the time.
1041        let narrowed = check.probes[&Probe::Narrowed].counts;
1042        assert!(
1043            (185..=195).contains(&(narrowed.below + narrowed.above)),
1044            "{narrowed:?}"
1045        );
1046        let widened = check.probes[&Probe::Widened].counts;
1047        assert!(
1048            (35..=45).contains(&(widened.below + widened.above)),
1049            "{widened:?}"
1050        );
1051        let shifted = check.probes[&Probe::ShiftedDown].counts;
1052        assert!((255..=265).contains(&shifted.above), "{shifted:?}");
1053    }
1054
1055    #[test]
1056    fn a_one_sided_miss_fails_on_its_own_tail() {
1057        // Shift every truth up by 0.3: the inside count stays near 90%, the tails don't.
1058        let mut flights = normal_flights();
1059        for f in &mut flights {
1060            if let (_, Said::Stated(c)) = &mut f.said[0] {
1061                c.truth += 0.3;
1062            }
1063        }
1064        let check = check(Quantity::ApogeeHeight, &flights);
1065        assert!(!check.test.passes(), "{:?}", check.test.counts);
1066        assert!(!check.test.above.holds(MISS_SHARE));
1067        assert!(!check.test.below.holds(MISS_SHARE));
1068    }
1069
1070    #[test]
1071    fn a_truth_that_is_not_a_number_leaves_no_error_scale() {
1072        let mut flights = normal_flights();
1073        flights[3].said = vec![(Quantity::ApogeeHeight, compared(f64::NAN))];
1074        let check = check(Quantity::ApogeeHeight, &flights);
1075        assert!(check.mean_error.is_nan());
1076        assert!(check.largest_error.is_nan(), "{}", check.largest_error);
1077    }
1078
1079    #[test]
1080    fn a_truth_that_is_not_a_number_misses_both_ways() {
1081        let mut counts = Counts::default();
1082        counts.add(
1083            Interval {
1084                low: 0.0,
1085                high: 1.0,
1086            },
1087            f64::NAN,
1088        );
1089        assert_eq!(
1090            (counts.given, counts.below, counts.inside, counts.above),
1091            (1, 1, 0, 1)
1092        );
1093        counts.add(
1094            Interval {
1095                low: 0.0,
1096                high: 1.0,
1097            },
1098            1.0,
1099        );
1100        assert_eq!(counts.inside, 1);
1101    }
1102
1103    /// Withheld by its own rule: the top speed past its transonic mark, a burnout taken from it,
1104    /// and a top acceleration where the log has no accelerometer; no reading for another reason.
1105    #[test]
1106    fn a_reading_withheld_by_rule_is_named() {
1107        for (quantity, reason) in [
1108            (Quantity::TopSpeed, Reason::Transonic),
1109            (Quantity::Burnout, Reason::Transonic),
1110            (Quantity::TopAcceleration, Reason::NoAccelerometer),
1111        ] {
1112            assert!(withheld_by_rule(quantity, reason), "{quantity:?}");
1113        }
1114        assert!(!withheld_by_rule(Quantity::TopSpeed, Reason::NoClimb));
1115        for quantity in STATED {
1116            assert!(
1117                !withheld_by_rule(quantity, Reason::EndsBeforeLanding),
1118                "{quantity:?}"
1119            );
1120            if !matches!(quantity, Quantity::TopSpeed | Quantity::Burnout) {
1121                assert!(
1122                    !withheld_by_rule(quantity, Reason::Transonic),
1123                    "{quantity:?}"
1124                );
1125            }
1126            if quantity != Quantity::TopAcceleration {
1127                assert!(
1128                    !withheld_by_rule(quantity, Reason::NoAccelerometer),
1129                    "{quantity:?}"
1130                );
1131            }
1132        }
1133    }
1134
1135    /// 1,000 floors whose errors sit at the standard normal's quantiles: `reading − truth` from
1136    /// −3 to +3 about −1.645, the lower end at the 5% tail, its standard error 1.
1137    fn normal_floors() -> Vec<FlightSaid> {
1138        (0..1000)
1139            .map(|k| {
1140                let p = (k as f64 + 0.5) / 1000.0;
1141                FlightSaid {
1142                    index: k,
1143                    design: 0,
1144                    logger: if k % 2 == 0 { "altos" } else { "rrc3" },
1145                    air_offset_k: 0.0,
1146                    said: vec![(
1147                        Quantity::Burnout,
1148                        Said::Floor(ComparedFloor {
1149                            reading: 0.0,
1150                            bound: 1.0,
1151                            low: -Z_90,
1152                            standard_error: 1.0,
1153                            truth: normal_quantile(p),
1154                        }),
1155                    )],
1156                }
1157            })
1158            .collect()
1159    }
1160
1161    #[test]
1162    fn a_correct_floor_passes_on_its_lower_tail_and_its_probes_fail() {
1163        let check = check(Quantity::Burnout, &normal_floors());
1164        assert_eq!(check.floors, 1000);
1165        // A floor isn't compared as an interval is.
1166        assert_eq!(check.test.counts.given, 0);
1167        let floor = check.floor.as_ref().unwrap();
1168        assert_eq!((floor.test.given, floor.test.below), (1000, 50));
1169        assert!(floor.test.passes());
1170        assert!(floor.holds());
1171        // Raised one standard error: about 26% below. Lowered two: about 0.1%.
1172        let raised = floor.probes[&FloorProbe::Raised];
1173        assert!((250..=270).contains(&raised.below), "{raised:?}");
1174        assert!(!raised.passes());
1175        let lowered = floor.probes[&FloorProbe::Lowered];
1176        assert!(lowered.below <= 3, "{lowered:?}");
1177        assert!(!lowered.passes());
1178        assert_eq!(floor.by_logger["altos"].0, 500);
1179        assert_eq!(floor.by_design[DESIGNS[0].name].0, 1000);
1180    }
1181
1182    #[test]
1183    fn a_floor_missing_too_often_or_too_rarely_fails() {
1184        for (shift, tail) in [(-1.0, "too often"), (2.0, "too rarely")] {
1185            let mut flights = normal_floors();
1186            for f in &mut flights {
1187                if let (_, Said::Floor(c)) = &mut f.said[0] {
1188                    // Higher truths leave fewer below the lower end.
1189                    c.truth += shift;
1190                }
1191            }
1192            let floor = check(Quantity::Burnout, &flights).floor.unwrap();
1193            assert!(!floor.test.passes(), "{tail}: {:?}", floor.test);
1194            assert!(!floor.holds(), "{tail}");
1195        }
1196    }
1197
1198    #[test]
1199    fn a_floors_truth_that_is_not_a_number_counts_below() {
1200        let mut flights = normal_floors();
1201        if let (_, Said::Floor(c)) = &mut flights[500].said[0] {
1202            c.truth = f64::NAN;
1203        }
1204        let floor = check(Quantity::Burnout, &flights).floor.unwrap();
1205        assert_eq!(floor.test.below, 51);
1206        // No normal quantile of the 1,000 lies as low as the lowered end: only the NaN does.
1207        assert_eq!(floor.probes[&FloorProbe::Lowered].below, 1);
1208    }
1209
1210    /// Tops past the clip are checked apart: never fitted, and failing only by missing more than
1211    /// their share. All 200 missing fails; none missing doesn't.
1212    #[test]
1213    fn tops_past_the_clip_may_miss_less_than_their_share_but_not_more() {
1214        let past = |truth: f64| -> Vec<FlightSaid> {
1215            (0..200)
1216                .map(|k| FlightSaid {
1217                    index: k,
1218                    design: 0,
1219                    logger: "altos",
1220                    air_offset_k: 0.0,
1221                    said: vec![(
1222                        Quantity::TopAcceleration,
1223                        Said::PastClip(ComparedFloor {
1224                            reading: 0.0,
1225                            bound: 1.0,
1226                            low: 0.0,
1227                            standard_error: 1.0,
1228                            truth,
1229                        }),
1230                    )],
1231                })
1232                .collect()
1233        };
1234        let none = check(Quantity::TopAcceleration, &past(1.0));
1235        let test = none.past_clip.unwrap();
1236        assert_eq!((test.given, test.below), (200, 0));
1237        assert!(test.no_more_than_its_share());
1238        assert!(fitted_floor(Quantity::TopAcceleration, &past(1.0)).is_none());
1239        let all = check(Quantity::TopAcceleration, &past(-1.0));
1240        let test = all.past_clip.unwrap();
1241        assert!(!test.no_more_than_its_share(), "{test:?}");
1242        // Exactly its share: the band reaches 5% from both sides, and that doesn't fail.
1243        let mut some = past(1.0);
1244        for flight in &mut some[..10] {
1245            flight.said = past(-1.0)[0].said.clone();
1246        }
1247        let test = check(Quantity::TopAcceleration, &some).past_clip.unwrap();
1248        assert_eq!(test.below, 10);
1249        assert!(test.band.low < MISS_SHARE && test.band.high > MISS_SHARE);
1250        assert!(test.no_more_than_its_share(), "{test:?}");
1251    }
1252
1253    #[test]
1254    fn a_flight_with_no_canopy_to_read_is_counted_apart() {
1255        let flights = vec![FlightSaid {
1256            index: 0,
1257            design: 0,
1258            logger: "altos",
1259            air_offset_k: 0.0,
1260            said: vec![(Quantity::DrogueRate, Said::Absent)],
1261        }];
1262        let check = check(Quantity::DrogueRate, &flights);
1263        assert_eq!((check.absent, check.test.counts.given), (1, 0));
1264        assert!(check.withheld.is_empty());
1265    }
1266
1267    /// A top lands wherever the reader can call it clipped and the part may not have clipped: for
1268    /// the IMU's ±3% from 0.9345 to 1.031 of the clip, for the AltOS part's ±10% from 0.875 to
1269    /// 1.111, evenly, and at another place on each set's flight.
1270    #[test]
1271    fn a_top_lands_wherever_the_reader_can_call_it_clipped() {
1272        let reach = 1.0 - 0.3 / 8.0;
1273        for (scale, least, most) in [
1274            (0.03, reach / 1.03, 1.0 / 0.97),
1275            (0.10, reach / 1.1, 1.0 / 0.9),
1276        ] {
1277            let ratios: Vec<f64> = (0..1000)
1278                .map(|k| top_over_clip(2_026_102_900, k, scale))
1279                .collect();
1280            assert!(ratios.iter().all(|r| (least..most).contains(r)));
1281            let tenth = least + 0.1 * (most - least);
1282            let lowest = ratios.iter().filter(|r| **r < tenth).count();
1283            assert!((98..=102).contains(&lowest), "{lowest}");
1284        }
1285        // No two sets' flights share a place, nor one set's its neighbor's a flight on.
1286        let (a, b) = (2_026_101_701, 2_026_101_702);
1287        assert_ne!(top_over_clip(a, 7, 0.03), top_over_clip(b, 7, 0.03));
1288        assert_ne!(top_over_clip(a, 8, 0.03), top_over_clip(b, 7, 0.03));
1289        // The reader's threshold reaches the window's bottom with the gain and bias at their
1290        // limits. Only sample noise and the reader's two steps of slack reach under that, by
1291        // about 1% of the clip at most.
1292        let read = reach / 1.03 * 1.03 * 8.0 + ACCEL_BIAS_G;
1293        assert!((read - (8.0 - GRAVITY_TOLERANCE_G)).abs() < 1e-9, "{read}");
1294    }
1295
1296    /// Scaled near the clip, a flight's log reads a floor whose truth the fitted lower end is
1297    /// measured against; with its top as flown, past the clip, the same.
1298    #[test]
1299    fn a_flight_says_its_top_accelerations_floors_from_clipping_logs() {
1300        use super::super::designs::DesignFiles;
1301        use super::super::{Flyer, Set};
1302        let mut flyer = Flyer::new(DesignFiles::committed());
1303        let range = LOWER_RANGE_G * STANDARD_GRAVITY_MPS2;
1304        // Past 1.2 times the clip, and with its scaled top read as a floor, as most are.
1305        let (index, flight, said) = (0..120)
1306            .filter_map(|k| flyer.flight(Set::Tuning, k).ok().map(|f| (k, f)))
1307            .filter(|(_, f)| {
1308                f.draw.logger.profile.accelerometer_range_m_s2().is_some()
1309                    && top_specific_force(f) > 1.2 * range
1310            })
1311            .map(|(k, f)| {
1312                let said = said(Set::Tuning.seed(), k, &f).unwrap();
1313                (k, f, said)
1314            })
1315            .find(|(_, _, s)| s.said.iter().any(|(_, x)| matches!(x, Said::Floor(_))))
1316            .unwrap();
1317        let tops: Vec<&Said> = said
1318            .said
1319            .iter()
1320            .filter(|(q, _)| *q == Quantity::TopAcceleration)
1321            .map(|(_, s)| s)
1322            .collect();
1323        // Its own log's reading, whole, then the floor near the clip and the floor as flown.
1324        assert!(matches!(tops[0], Said::Stated(_)), "{tops:?}");
1325        let Said::Floor(at_clip) = tops[1] else {
1326            panic!("{tops:?}");
1327        };
1328        let scale = flight.draw.logger.profile.accelerometer_scale().unwrap();
1329        assert_eq!(
1330            at_clip.truth,
1331            range * top_over_clip(Set::Tuning.seed(), index, scale)
1332        );
1333        assert!((at_clip.reading - range).abs() < 0.2 * range, "{at_clip:?}");
1334        let Said::PastClip(past) = tops[2] else {
1335            panic!("{tops:?}");
1336        };
1337        let top = top_specific_force(&flight);
1338        assert_eq!(past.truth, top);
1339        assert!(past.reading < top, "{past:?}");
1340        assert!(past.low < past.reading, "{past:?}");
1341    }
1342
1343    #[test]
1344    fn floors_and_withheld_readings_are_counted_apart() {
1345        let flights = vec![
1346            FlightSaid {
1347                index: 0,
1348                design: 0,
1349                logger: "altos",
1350                air_offset_k: 0.0,
1351                said: vec![(Quantity::ApogeeHeight, Said::Unstated)],
1352            },
1353            FlightSaid {
1354                index: 1,
1355                design: 0,
1356                logger: "altos",
1357                air_offset_k: 0.0,
1358                said: vec![(Quantity::ApogeeHeight, Said::Withheld(Reason::NoClimb))],
1359            },
1360        ];
1361        let check = check(Quantity::ApogeeHeight, &flights);
1362        assert_eq!(
1363            (check.flights, check.unstated, check.test.counts.given),
1364            (2, 1, 0)
1365        );
1366        assert_eq!(check.withheld[&Reason::NoClimb], 1);
1367        // No reading compared: nothing to pass on.
1368        assert!(!check.test.passes());
1369    }
1370
1371    #[test]
1372    fn the_fit_reads_the_errors_as_shares_of_the_bound() {
1373        let flights: Vec<FlightSaid> = (0..199)
1374            .map(|k| FlightSaid {
1375                index: k,
1376                design: 0,
1377                logger: "altos",
1378                air_offset_k: 0.0,
1379                said: vec![(
1380                    Quantity::ApogeeHeight,
1381                    Said::Stated(Compared {
1382                        reading: k as f64,
1383                        bound: 2.0,
1384                        interval: Interval {
1385                            low: 0.0,
1386                            high: 1.0,
1387                        },
1388                        truth: 0.0,
1389                    }),
1390                )],
1391            })
1392            .collect();
1393        // Shares 0, 0.5, …, 99: n = 199, the 10th from each end.
1394        let fitted = fitted(Quantity::ApogeeHeight, &flights).unwrap();
1395        assert_eq!((fitted.low, fitted.high), (4.5, 94.5));
1396        assert!(fitted_none_below_twenty());
1397    }
1398
1399    fn fitted_none_below_twenty() -> bool {
1400        fitted(Quantity::ApogeeTime, &[]).is_none()
1401    }
1402
1403    #[test]
1404    fn three_figures_rounds_as_the_library_writes() {
1405        assert_eq!(three_figures(0.612_49), 0.612);
1406        assert_eq!(three_figures(-0.000_123_56), -0.000_124);
1407        assert_eq!(three_figures(12_345.0), 12_300.0);
1408        assert_eq!(three_figures(0.0), 0.0);
1409    }
1410}