Skip to main content

hpr_forensics/synthetic/
fits.rs

1//! The least-squares fit's 90% intervals held to the synthetic flights ([M7.3b][m7-3],
2//! [ADR-257][adr-257] §1, [ADR-316][adr-316]).
3//!
4//! Each flight's log is fitted ([`crate::fit`]), told what a flyer knows: the design, its motor at
5//! its rated impulse and burn, the rail, the site and the day's air, and the structure's mass as
6//! weighed, [`weighed_factor`] off the truth. The drag scale, impulse scale, wind and mass are each
7//! compared with the flight's truth by the same three counts as the readings'
8//! ([`super::intervals::Test`]), with the same three probes.
9//!
10//! **The truth.** On [`Set::A`] a parameter's truth is what the flight drew. On
11//! [`Set::B`], whose drag curve, wind and thrust are shaped otherwise, it is the fit
12//! to the noise-free flight ([`noise_free`]): the same bins of height and drift, as the sensor would
13//! have read them with no noise, with the sensors' unknowns open as a log's are. The mass's truth is what the
14//! flight drew on both.
15//!
16//! **What a log can tell.** A parameter counts as identified only when its median interval over
17//! the flights is at most half the width of the 90% interval of its stated range with no log:
18//! [`Identification`]. Pure noise in place of the log must leave every parameter not identified
19//! ([`noise_log`]).
20//!
21//! [m7-3]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m7-3
22//! [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
23//! [adr-316]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0316-m7-3b-the-least-squares-fit.md
24
25use std::collections::BTreeMap;
26
27use hpr_atmos::PowerLawWind;
28use hpr_core::random::SeededRng;
29use hpr_flightdata::log::FlightLog;
30use hpr_flightdata::readings;
31use hpr_flightdata::readings::interval::{Interval, Shares, Z_90};
32use hpr_sim::Simulation;
33use serde::{Deserialize, Serialize};
34
35use super::designs::{DESIGNS, DesignFiles};
36use super::intervals::{Counts, Probe, Test};
37use super::logger::Profile;
38use super::noise::between;
39use super::truth::{self};
40use super::{Draw, Flight, Model, Set, SyntheticError};
41use crate::fit::{
42    self, FLOWN, Fit, Forward, Noise, Observations, Parameters, Prior, Sampling, Stated,
43};
44use crate::posterior::Posterior;
45use crate::residuals::{HeightKind, Simulated, Track};
46
47/// The parameters asked of the fit, in the report's order.
48pub const ASKED: [Asked; 5] = [
49    Asked::DragScale,
50    Asked::ImpulseScale,
51    Asked::WindEast,
52    Asked::WindNorth,
53    Asked::MassScale,
54];
55
56/// How a fit states a parameter's 90% interval.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
58#[serde(rename_all = "kebab-case")]
59pub enum Method {
60    /// The least-squares fit's standard error times the shares fitted on the calibration set
61    /// ([`shares`]).
62    LeastSquares,
63    /// The Bayesian option's 5% and 95% points as they come ([`fit::bayesian`]).
64    Bayesian,
65}
66
67impl Method {
68    /// Both, in the report's order.
69    pub const ALL: [Self; 2] = [Self::LeastSquares, Self::Bayesian];
70
71    /// Its name in the report.
72    #[must_use]
73    pub fn name(self) -> &'static str {
74        match self {
75            Self::LeastSquares => "least squares",
76            Self::Bayesian => "Bayesian",
77        }
78    }
79}
80
81/// The pilot's draws the Bayesian option makes of a flight's posterior, which widen its proposal
82/// where the posterior reaches further ([`crate::posterior::sample_in_two`]), and the draws read
83/// after them; each draw flies twice, once for the middle of the unknowns other than the wind and
84/// once for its weight. By estimate a few hundred keep 100 effective draws
85/// ([`crate::posterior::MIN_EFFECTIVE_DRAWS`]) on a posterior near its peak's Gaussian. A judgment;
86/// the report counts the flights where they fell short.
87pub const POSTERIOR_PILOT: usize = 100;
88/// And the draws read.
89pub const POSTERIOR_DRAWS: usize = 400;
90
91/// How flight `index` of `set` draws its posterior: [`POSTERIOR_PILOT`] and [`POSTERIOR_DRAWS`],
92/// on a seed of its own.
93#[must_use]
94pub fn sampling(set: Set, index: u64) -> Sampling {
95    Sampling {
96        pilot: POSTERIOR_PILOT,
97        draws: POSTERIOR_DRAWS,
98        seed: SeededRng::for_stream(set.seed(), &[index, super::POSTERIOR_KEY]).next_u64(),
99    }
100}
101
102/// A parameter asked of the fit.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
104#[serde(rename_all = "kebab-case")]
105pub enum Asked {
106    /// The drag scale.
107    DragScale,
108    /// The impulse scale.
109    ImpulseScale,
110    /// The constant wind's speed toward the east, m/s.
111    WindEast,
112    /// Its speed toward the north, m/s.
113    WindNorth,
114    /// The factor on the weighed mass.
115    MassScale,
116}
117
118impl Asked {
119    /// Its name in the report.
120    #[must_use]
121    pub fn name(self) -> &'static str {
122        match self {
123            Self::DragScale => "drag scale",
124            Self::ImpulseScale => "impulse scale",
125            Self::WindEast => "wind toward the east, m/s",
126            Self::WindNorth => "wind toward the north, m/s",
127            Self::MassScale => "mass on the weighed mass",
128        }
129    }
130
131    /// Whether a log of height alone states an interval on it. The wind's doesn't: nothing in a
132    /// height speaks to it, and with nothing from the log an interval is only the range stated, which
133    /// can't be right on both sets, as set B's shear widens its truth ([ADR-316][adr-316], the
134    /// fit's decisions).
135    ///
136    /// [adr-316]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0316-m7-3b-the-least-squares-fit.md
137    #[must_use]
138    pub fn stated_on_height_alone(self) -> bool {
139        !matches!(self, Self::WindEast | Self::WindNorth)
140    }
141
142    /// Its place in [`Parameters::to_array`].
143    #[must_use]
144    pub fn index(self) -> usize {
145        match self {
146            Self::DragScale => 0,
147            Self::ImpulseScale => 1,
148            Self::WindEast => 3,
149            Self::WindNorth => 4,
150            Self::MassScale => 5,
151        }
152    }
153
154    /// The 90% interval's width that its stated range gives with no log: the 5% to 95% points of
155    /// what the flights draw. A wind component is a uniform speed along a uniform direction, whose
156    /// points are [`wind_component_point`] either way.
157    #[must_use]
158    pub fn stated_width(self) -> f64 {
159        match self {
160            Self::DragScale => 0.9 * 0.4,
161            Self::ImpulseScale => 0.9 * 0.12,
162            Self::WindEast | Self::WindNorth => 2.0 * wind_component_point(),
163            Self::MassScale => 0.9 * 2.0 * WEIGHED_WITHIN,
164        }
165    }
166}
167
168/// What's stated of a flight read as `observed`. A log of height alone can't tell the wind, and a
169/// wind of either sign lowers a flight's top, so a fit in no wind would put that loss in the drag
170/// and impulse: by 0.7% of the impulse in a wind of 6 to 9 m/s, on the first 240 flights of set A,
171/// and by nothing under 3 m/s. It flies instead in a wind of the stated range's RMS speed, toward
172/// the east, which leaves the mean of that loss out of them; the wind's way, which a tilted rail
173/// would tell, is left to the wind's own stated range.
174#[must_use]
175pub fn stated_for(observed: Option<&Observations>) -> Stated {
176    let mut stated = stated();
177    if observed.is_some_and(|o| o.horizontal.is_empty()) {
178        stated[Asked::WindEast.index()].mean = super::MAX_WIND_M_S / 3.0_f64.sqrt();
179    }
180    stated
181}
182
183/// How far a flight's weighed mass lies from its structure's, a share of it, either way: a
184/// kitchen scale's and a loaded airframe's error, the maintainer's judgment; drawn uniform.
185pub const WEIGHED_WITHIN: f64 = 0.02;
186
187/// The 95% point of a wind component drawn as [`super::draw`] draws it, m/s: `x` with
188/// `P(v sin θ ≤ x) = 0.95` for `v` uniform on `0..V` and `θ` uniform on a turn, found by bisection
189/// on a midpoint sum over the direction.
190#[must_use]
191pub fn wind_component_point() -> f64 {
192    let v_max = super::MAX_WIND_M_S;
193    let upper_share = |x: f64| {
194        // P(v sin θ > x) = mean over θ in the half turn of (1 − x/(V sin θ))⁺, over 2.
195        let steps = 20_000_u32;
196        let sum: f64 = (0..steps)
197            .map(|k| {
198                let theta = std::f64::consts::PI * (f64::from(k) + 0.5) / f64::from(steps);
199                (1.0 - x / (v_max * theta.sin())).max(0.0)
200            })
201            .sum();
202        0.5 * sum / f64::from(steps)
203    };
204    let (mut low, mut high) = (0.0, v_max);
205    for _ in 0..60 {
206        let middle = 0.5 * (low + high);
207        if upper_share(middle) > 0.05 {
208            low = middle;
209        } else {
210            high = middle;
211        }
212    }
213    0.5 * (low + high)
214}
215
216/// What the fit is told of each parameter: normal, so that with no log its 90% interval is its
217/// stated range's. The drag and impulse scales are centered on their rated 1; the burn time's range
218/// is the draw's. These are the flights' stated ranges, so they mean something on these flights
219/// alone; a caller on a real flight states its own.
220#[must_use]
221pub fn stated() -> Stated {
222    let of_width = |mean: f64, width: f64| Prior {
223        mean,
224        sd: width / (2.0 * Z_90),
225    };
226    [
227        of_width(1.0, Asked::DragScale.stated_width()),
228        of_width(1.0, Asked::ImpulseScale.stated_width()),
229        of_width(1.0, 0.9 * 0.2),
230        of_width(0.0, Asked::WindEast.stated_width()),
231        of_width(0.0, Asked::WindNorth.stated_width()),
232        of_width(1.0, Asked::MassScale.stated_width()),
233    ]
234}
235
236/// The factor between flight `index`'s weighed structure and its true one, from a stream of its own,
237/// so that no flight's draw moves.
238#[must_use]
239pub fn weighed_factor(set: Set, index: u64) -> f64 {
240    let mut rng = SeededRng::for_stream(set.seed(), &[index, super::WEIGHING_KEY]);
241    between(&mut rng, 1.0 - WEIGHED_WITHIN, 1.0 + WEIGHED_WITHIN)
242}
243
244/// Flies a draw's design for a fit: told the rail, site and air, its motor rated, its wind and
245/// scales as asked. The structure's mass is `weighed` times the true one, times the asked factor.
246#[derive(Debug)]
247pub struct Flown<'a> {
248    draw: Draw,
249    files: &'a DesignFiles,
250    weighed: f64,
251    tables: &'a mut BTreeMap<usize, Simulation>,
252}
253
254impl<'a> Flown<'a> {
255    /// The fit's flights of `draw`.
256    pub fn new(
257        draw: &Draw,
258        files: &'a DesignFiles,
259        weighed: f64,
260        tables: &'a mut BTreeMap<usize, Simulation>,
261    ) -> Self {
262        Self {
263            draw: *draw,
264            files,
265            weighed,
266            tables,
267        }
268    }
269}
270
271impl Forward for Flown<'_> {
272    fn fly(&mut self, p: &Parameters, until_s: f64) -> Result<Simulated, String> {
273        self.flown(p, until_s, None)
274    }
275
276    /// The stated wind is at [`truth::SHEAR_REFERENCE_HEIGHT_M`] above the pad, as the draws'.
277    fn fly_sheared(
278        &mut self,
279        p: &Parameters,
280        until_s: f64,
281        exponent: f64,
282    ) -> Result<Simulated, String> {
283        self.flown(p, until_s, Some(exponent))
284    }
285}
286
287impl Flown<'_> {
288    /// The flight on `p`, its wind constant or growing with height by `shear`.
289    fn flown(
290        &mut self,
291        p: &Parameters,
292        until_s: f64,
293        shear: Option<f64>,
294    ) -> Result<Simulated, String> {
295        if p.drag_scale <= 0.0 || p.impulse_scale <= 0.0 || p.burn_time_scale <= 0.0 {
296            return Err("a scale that isn't positive".to_owned());
297        }
298        let wind_speed_m_s = p.wind_east_m_s.hypot(p.wind_north_m_s);
299        // It blows toward (east, north), so from the opposite way, clockwise from north.
300        let wind_from_rad = (-p.wind_east_m_s)
301            .atan2(-p.wind_north_m_s)
302            .rem_euclid(std::f64::consts::TAU);
303        let told = Draw {
304            impulse_scale: p.impulse_scale,
305            burn_time_scale: p.burn_time_scale,
306            drag_scale: p.drag_scale,
307            wind_speed_m_s,
308            wind_from_rad,
309            model: Model::Same,
310            ..self.draw
311        };
312        let mut inputs = truth::inputs(&told, self.files).map_err(|e| e.to_string())?;
313        if let Some(exponent) = shear {
314            inputs.environment = inputs.environment.with_wind(
315                PowerLawWind::new(
316                    wind_speed_m_s,
317                    truth::SHEAR_REFERENCE_HEIGHT_M,
318                    exponent,
319                    wind_from_rad,
320                    told.elevation_m,
321                )
322                .map_err(|e| e.to_string())?,
323            );
324        }
325        inputs.recovery.clear();
326        inputs.settings.max_time_s = until_s;
327        let mut simulation = inputs.simulation().map_err(|e| e.to_string())?;
328        match self.tables.get(&told.design) {
329            Some(nominal) => {
330                simulation.share_supersonic_table(nominal.aero());
331            }
332            None => {
333                let nominal = inputs.simulation().map_err(|e| e.to_string())?;
334                self.tables.insert(told.design, nominal);
335            }
336        }
337        let simulation = simulation
338            .with_structure_mass_scale(self.weighed * p.mass_scale)
339            .map_err(|e| e.to_string())?;
340        let mut track = Track::new();
341        simulation.run(&mut track).map_err(|e| e.to_string())?;
342        track
343            .simulated(&inputs.environment)
344            .map_err(|e| e.to_string())
345    }
346}
347
348/// A fit's reading of one parameter against its truth.
349#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
350pub struct Compared {
351    /// The fit's value.
352    pub value: f64,
353    /// Its standard error.
354    pub standard_error: f64,
355    /// The truth.
356    pub truth: f64,
357}
358
359impl Compared {
360    /// `(value − truth)/standard error`, what the shares are fitted on.
361    #[must_use]
362    pub fn share(&self) -> f64 {
363        (self.value - self.truth) / self.standard_error
364    }
365}
366
367/// One flight's fit.
368#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
369pub struct FlightFit {
370    /// The flight's index in its set.
371    pub index: u64,
372    /// The design's index in [`DESIGNS`].
373    pub design: usize,
374    /// Whether the log was fitted, or said nothing.
375    pub fitted: bool,
376    /// Whether its log was fitted and holds a horizontal track.
377    pub drift: bool,
378    /// Whether its fit, and any noise-free fit for its truth, stopped at the bottom.
379    pub converged: bool,
380    /// Its fit's residual as a share of the spread of the heights it read, where it came to one.
381    pub misfit_share: Option<f64>,
382    /// Each asked parameter, in [`ASKED`]'s order.
383    pub compared: [Compared; ASKED.len()],
384    /// The heights' residual's RMS, m.
385    pub rms_m: Option<f64>,
386    /// Flights flown for it, the noise-free fit's included, the Bayesian option's draws not.
387    pub flown: u64,
388    /// The Bayesian option's posterior of the flown parameters, where it was asked for and the
389    /// least-squares fit had something to fit.
390    pub posterior: Option<Posterior<FLOWN>>,
391}
392
393/// The bins of `observed` that its fit read (`read`, [`Fit::read`]) as the noise-free flight fills
394/// them, on the flight's own clock: what the log's sensors would have read with no noise, no gain,
395/// no drift and no port, in the same bins, so that the fit to them differs from the log's by the
396/// noise alone.
397///
398/// # Errors
399///
400/// [`SyntheticError`] if the flight's air doesn't reach it.
401pub fn noise_free_observations(
402    observed: &Observations,
403    read: &[bool],
404    flight: &Flight,
405    files: &DesignFiles,
406) -> Result<Observations, SyntheticError> {
407    let environment = truth::inputs(&flight.draw, files)?.environment;
408    let flown = Simulated::new(flight.truth.samples.clone(), &environment).map_err(|_| {
409        SyntheticError::Flight {
410            what: "a truth the day's air doesn't reach",
411        }
412    })?;
413    if read.len() != observed.heights.len() {
414        return Err(SyntheticError::Flight {
415            what: "a fit's bins that aren't this log's",
416        });
417    }
418    let to_flight = |t: f64| t - flight.draw.logger.pad_s;
419    Ok(Observations {
420        kind: observed.kind,
421        // The bins the log's fit read, and no others: a fit reads a different part of the flight
422        // where it finds the rocket faster or slower, and a drag that isn't a scale of the
423        // simulation's would then differ by more than the noise.
424        heights: observed
425            .heights
426            .iter()
427            .zip(read)
428            .filter(|(_, read)| **read)
429            .map(|(&(t, _), _)| {
430                let at = to_flight(t);
431                (at, flown.read_height_m(at, observed.kind))
432            })
433            .collect(),
434        // The drift at every bin, whatever the log's own sensors held: a flight's truth is what the
435        // whole flight says of it, and a log of height alone can't tell the wind's loss from the
436        // drag's, which its errors must then hold.
437        horizontal: observed
438            .heights
439            .iter()
440            .map(|&(t, _)| {
441                let at = to_flight(t);
442                let (east, north) = flown.drift_m(at);
443                (at, east, north)
444            })
445            .collect(),
446        liftoff_s: flight.truth.events.liftoff_s,
447        flown_s: observed.flown_s,
448        // Those bins are already chosen.
449        reads_transonic: true,
450    })
451}
452
453/// The parameters' truth on a flight of another model: the fit to the noise-free flight
454/// ([ADR-257][adr-257] §1). Where the log said anything it is the same fit as `answer`, on the same
455/// bins at the same noise with the sensors' unknowns open, so that the two differ by the noise alone.
456/// The structure's mass is held as flown. Where the log said nothing, the flight's height and drift
457/// known exactly.
458///
459/// [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
460///
461/// # Errors
462///
463/// [`SyntheticError`] if the flight's air doesn't reach it.
464pub fn noise_free(
465    observed: &Observations,
466    answer: &Fit,
467    flight: &Flight,
468    files: &DesignFiles,
469    tables: &mut BTreeMap<usize, Simulation>,
470) -> Result<Fit, SyntheticError> {
471    let filled = noise_free_observations(observed, &answer.read, flight, files)?;
472    let mut told = stated_for(Some(&filled));
473    told[Asked::MassScale.index()] = Prior {
474        mean: 1.0,
475        sd: 1e-6,
476    };
477    Ok(fit::fit(
478        Some(&filled),
479        &told,
480        Noise::Given {
481            height_m: answer.height_noise_m,
482            horizontal_m: answer.horizontal_noise_m,
483        },
484        &mut Flown::new(&flight.draw, files, 1.0, tables),
485    ))
486}
487
488/// A log's fit, `log` being the flight's own or one in place of it, against the flight's truth. A
489/// flight of another model whose log said nothing has none: it isn't counted.
490///
491/// # Errors
492///
493/// [`SyntheticError::Flight`] if a flight of another model can't be fitted noise-free: a truth is
494/// needed for the count.
495pub fn fit_log(
496    log: &FlightLog,
497    flight: &Flight,
498    set: Set,
499    bayesian: bool,
500    files: &DesignFiles,
501    tables: &mut BTreeMap<usize, Simulation>,
502) -> Result<FlightFit, SyntheticError> {
503    let draw = &flight.draw;
504    let weighed = weighed_factor(set, draw.index);
505    let read = readings::read(log);
506    let observed = fit::observations(log, &read);
507    let told = stated_for(observed.as_ref());
508    let (answer, posterior) = fitted_and_sampled(
509        observed.as_ref(),
510        &told,
511        bayesian.then(|| sampling(set, draw.index)),
512        &mut Flown::new(draw, files, weighed, tables),
513    );
514    let mut flown = answer.flown;
515    let mut converged = answer.converged;
516    let truth: [f64; FLOWN] = match draw.model {
517        Model::Same => {
518            // It blows from `wind_from_rad`, so toward the opposite way.
519            let (speed, from) = (draw.wind_speed_m_s, draw.wind_from_rad);
520            [
521                draw.drag_scale,
522                draw.impulse_scale,
523                draw.burn_time_scale,
524                -speed * from.sin(),
525                -speed * from.cos(),
526                f64::NAN,
527            ]
528        }
529        Model::Other { .. } => match observed.as_ref().filter(|_| answer.fitted) {
530            Some(observed) => {
531                let free = noise_free(observed, &answer, flight, files, tables)?;
532                if !free.fitted {
533                    return Err(SyntheticError::Flight {
534                        what: "no noise-free fit",
535                    });
536                }
537                converged &= free.converged;
538                flown += free.flown;
539                free.parameters.to_array()
540            }
541            None => [f64::NAN; FLOWN],
542        },
543    };
544    let values = answer.parameters.to_array();
545    let compared = ASKED.map(|asked| {
546        let i = asked.index();
547        Compared {
548            value: values[i],
549            standard_error: answer.standard_errors[i],
550            // The fit's mass is a factor on the weighed mass: the truth undoes the weighing.
551            truth: if asked == Asked::MassScale {
552                1.0 / weighed
553            } else {
554                truth[i]
555            },
556        }
557    });
558    Ok(FlightFit {
559        index: draw.index,
560        design: draw.design,
561        fitted: answer.fitted,
562        drift: answer.fitted && observed.is_some_and(|o| !o.horizontal.is_empty()),
563        converged,
564        misfit_share: answer.misfit_share,
565        compared,
566        rms_m: answer.rms_m,
567        flown,
568        posterior,
569    })
570}
571
572/// A log's fit from its residuals' noise, and with `sampling` the Bayesian option's posterior.
573fn fitted_and_sampled(
574    observed: Option<&Observations>,
575    told: &Stated,
576    sampling: Option<Sampling>,
577    forward: &mut dyn Forward,
578) -> (Fit, Option<Posterior<FLOWN>>) {
579    match sampling {
580        Some(sampling) => {
581            let answer = fit::bayesian(observed, told, Noise::FromResiduals, forward, sampling);
582            (answer.least_squares, answer.posterior)
583        }
584        None => (
585            fit::fit(observed, told, Noise::FromResiduals, forward),
586            None,
587        ),
588    }
589}
590
591/// A log of pure noise in place of `log`: the same clock, each height a uniform draw of `size_m`
592/// about nothing, and no other channel.
593#[must_use]
594pub fn noise_log(log: &FlightLog, size_m: f64, seed: u64, index: u64) -> FlightLog {
595    let mut rng = SeededRng::for_stream(seed, &[index, super::NOISE_LOG_KEY]);
596    let (time_s, _) = readings::height_track(log).unwrap_or_default();
597    let altitude_m = time_s
598        .iter()
599        .map(|_| between(&mut rng, -size_m, size_m))
600        .collect();
601    FlightLog {
602        time_s,
603        altitude_m,
604        vertical_speed_m_s: None,
605        channels: Vec::new(),
606        events: Vec::new(),
607        ..log.clone()
608    }
609}
610
611/// The shares a flight's parameter takes: those of what its log holds, and on a log that said
612/// nothing, its stated range's own, the normal's, as the fit held it to.
613fn shares_of(fit: &FlightFit, asked: Asked) -> Shares {
614    if fit.fitted {
615        shares(asked, fit.drift)
616    } else {
617        Shares {
618            low: -Z_90,
619            high: Z_90,
620        }
621    }
622}
623
624/// A flight's fit with bins of pure noise handed to it past the reader, as if the reader had found
625/// a flight of 20 s in them: heights of `size_m` either way, and a track of `track_m` in each
626/// direction where that's a size.
627pub fn fit_noise_bins(
628    flight: &Flight,
629    set: Set,
630    bayesian: bool,
631    size_m: f64,
632    track_m: Option<f64>,
633    files: &DesignFiles,
634    tables: &mut BTreeMap<usize, Simulation>,
635) -> FlightFit {
636    let index = flight.draw.index;
637    let mut rng = SeededRng::for_stream(set.seed(), &[index, super::NOISE_LOG_KEY, 1]);
638    let heights = (0..80)
639        .map(|k| (0.25 * f64::from(k), between(&mut rng, -size_m, size_m)))
640        .collect();
641    let horizontal: Vec<(f64, f64, f64)> = track_m.map_or_else(Vec::new, |track_m| {
642        (0..80)
643            .map(|k| {
644                (
645                    0.25 * f64::from(k),
646                    between(&mut rng, -track_m, track_m),
647                    between(&mut rng, -track_m, track_m),
648                )
649            })
650            .collect()
651    });
652    let drift = !horizontal.is_empty();
653    let observed = Observations {
654        kind: HeightKind::Barometric,
655        heights,
656        horizontal,
657        liftoff_s: 0.0,
658        flown_s: 20.0,
659        reads_transonic: false,
660    };
661    let weighed = weighed_factor(set, index);
662    let (answer, posterior) = fitted_and_sampled(
663        Some(&observed),
664        &stated_for(Some(&observed)),
665        bayesian.then(|| sampling(set, index)),
666        &mut Flown::new(&flight.draw, files, weighed, tables),
667    );
668    let values = answer.parameters.to_array();
669    FlightFit {
670        index,
671        design: flight.draw.design,
672        fitted: answer.fitted,
673        drift: answer.fitted && drift,
674        converged: answer.converged,
675        misfit_share: answer.misfit_share,
676        compared: ASKED.map(|asked| Compared {
677            value: values[asked.index()],
678            standard_error: answer.standard_errors[asked.index()],
679            truth: f64::NAN,
680        }),
681        rms_m: answer.rms_m,
682        flown: answer.flown,
683        posterior,
684    }
685}
686
687/// `asked`'s 90% interval on `fit` by `method`; `None` where it can't be stated. A log that said
688/// nothing states the stated range's own by either: what was stated of it is all there is.
689#[must_use]
690pub fn interval_of(method: Method, fit: &FlightFit, asked: Asked) -> Option<Interval> {
691    let slot = ASKED.iter().position(|a| *a == asked)?;
692    let compared = fit.compared[slot];
693    match method {
694        Method::Bayesian if fit.fitted => {
695            let [low, _, high] = fit.posterior.as_ref()?.quantiles[asked.index()];
696            (low.is_finite() && high.is_finite() && low <= high).then_some(Interval { low, high })
697        }
698        _ => shares_of(fit, asked).interval(compared.value, compared.standard_error),
699    }
700}
701
702/// `asked`'s point on `fit` by `method`: the least-squares answer, or the posterior's median.
703fn point_of(method: Method, fit: &FlightFit, asked: Asked, slot: usize) -> f64 {
704    match (method, &fit.posterior) {
705        (Method::Bayesian, Some(posterior)) if fit.fitted => posterior.quantiles[asked.index()][1],
706        (Method::Bayesian, None) if fit.fitted => f64::NAN,
707        _ => fit.compared[slot].value,
708    }
709}
710
711/// Whether a parameter is identified on a set: [ADR-257][adr-257] §1's rule.
712///
713/// [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
714#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
715pub struct Identification {
716    /// The median interval's width over the flights.
717    pub median_width: f64,
718    /// The 90% interval's width of its stated range.
719    pub stated_width: f64,
720    /// Whether the median is at most half the stated.
721    pub identified: bool,
722}
723
724impl Identification {
725    /// `asked`'s, over `fits`.
726    #[must_use]
727    pub fn of(asked: Asked, fits: &[FlightFit]) -> Self {
728        Self::by(Method::LeastSquares, asked, fits)
729    }
730
731    /// `asked`'s, over `fits`, by `method`. An interval that can't be stated counts as wider than
732    /// any.
733    #[must_use]
734    pub fn by(method: Method, asked: Asked, fits: &[FlightFit]) -> Self {
735        let slot = ASKED.iter().position(|a| *a == asked).unwrap_or(0);
736        let mut widths: Vec<f64> = fits
737            .iter()
738            .map(|f| match method {
739                Method::LeastSquares => {
740                    let shares = shares_of(f, asked);
741                    (shares.high - shares.low) * f.compared[slot].standard_error
742                }
743                Method::Bayesian => interval_of(method, f, asked)
744                    .map_or(f64::INFINITY, |interval| interval.high - interval.low),
745            })
746            .collect();
747        widths.sort_by(f64::total_cmp);
748        let median_width = widths.get(widths.len() / 2).copied().unwrap_or(f64::NAN);
749        let stated_width = asked.stated_width();
750        Self {
751            median_width,
752            stated_width,
753            identified: median_width <= 0.5 * stated_width,
754        }
755    }
756}
757
758/// The residual that splits [`Check::by_residual`], m: past it a flight's errors run larger than
759/// its standard errors say, and the shares, one pair for both sides, cover it less.
760pub const RESIDUAL_SPLIT_M: f64 = 1.0;
761
762/// One parameter's check on one set.
763#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
764pub struct Check {
765    /// The parameter.
766    pub asked: Asked,
767    /// The test on the intervals as stated.
768    pub test: Test,
769    /// The test on each probe's intervals; each must fail.
770    pub probes: BTreeMap<Probe, Test>,
771    /// The counts by design.
772    pub by_design: BTreeMap<String, Counts>,
773    /// The counts of flights whose log holds a horizontal track, and of those that don't.
774    pub by_drift: BTreeMap<String, Counts>,
775    /// The counts by how well the flight's heights fit, [`RESIDUAL_SPLIT_M`]: the shares are one
776    /// pair for both, so each side's coverage shows here.
777    pub by_residual: BTreeMap<String, Counts>,
778    /// The mean error, fit less truth, with its sign.
779    pub mean_error: f64,
780    /// What the log can tell of it.
781    pub identification: Identification,
782}
783
784/// `asked`'s check over `fits`, of the least-squares fit's intervals.
785#[must_use]
786pub fn check(asked: Asked, fits: &[FlightFit]) -> Check {
787    check_by(Method::LeastSquares, asked, fits)
788}
789
790/// `asked`'s check over `fits`, of `method`'s intervals.
791#[must_use]
792pub fn check_by(method: Method, asked: Asked, fits: &[FlightFit]) -> Check {
793    let slot = ASKED.iter().position(|a| *a == asked).unwrap_or(0);
794    let mut counts = Counts::default();
795    let mut probes: BTreeMap<Probe, Counts> =
796        Probe::ALL.iter().map(|&p| (p, Counts::default())).collect();
797    let mut by_design: BTreeMap<String, Counts> = BTreeMap::new();
798    let mut by_drift: BTreeMap<String, Counts> = BTreeMap::new();
799    let mut by_residual: BTreeMap<String, Counts> = BTreeMap::new();
800    let mut error_sum = 0.0;
801    let mut stated_count = 0_u32;
802    for fit in fits {
803        // A log that said nothing states no interval of its own, and its range would hold 90%
804        // whatever the fit did. A wind is counted only where a track speaks to it.
805        if !fit.fitted || (!fit.drift && !asked.stated_on_height_alone()) {
806            continue;
807        }
808        stated_count += 1;
809        let compared = fit.compared[slot];
810        let Some(interval) = interval_of(method, fit, asked) else {
811            // An interval that can't be stated misses on both sides.
812            let nowhere = Interval {
813                low: f64::NAN,
814                high: f64::NAN,
815            };
816            counts.add(nowhere, f64::NAN);
817            continue;
818        };
819        counts.add(interval, compared.truth);
820        for (probe, counted) in &mut probes {
821            counted.add(probe.apply(interval), compared.truth);
822        }
823        by_design
824            .entry(
825                DESIGNS
826                    .get(fit.design)
827                    .map_or("an unknown design", |design| design.name)
828                    .to_owned(),
829            )
830            .or_default()
831            .add(interval, compared.truth);
832        by_drift
833            .entry(
834                if fit.drift {
835                    "with a horizontal track"
836                } else {
837                    "height alone"
838                }
839                .to_owned(),
840            )
841            .or_default()
842            .add(interval, compared.truth);
843        if let Some(rms_m) = fit.rms_m {
844            by_residual
845                .entry(
846                    if rms_m < RESIDUAL_SPLIT_M {
847                        "heights fit within 1 m"
848                    } else {
849                        "heights fit to 1 m or worse"
850                    }
851                    .to_owned(),
852                )
853                .or_default()
854                .add(interval, compared.truth);
855        }
856        error_sum += point_of(method, fit, asked, slot) - compared.truth;
857    }
858    Check {
859        asked,
860        test: Test::of(counts),
861        probes: probes.into_iter().map(|(p, c)| (p, Test::of(c))).collect(),
862        by_design,
863        by_drift,
864        by_residual,
865        mean_error: error_sum / f64::from(stated_count.max(1)),
866        identification: Identification::by(method, asked, fits),
867    }
868}
869
870/// The first `count` flights of `set` whose logger holds a horizontal track and a barometer, whose
871/// fits are what the wind is counted on. A set's draw at any index is fixed, so these run on past
872/// its count without moving its flights.
873#[must_use]
874pub fn track_flights(set: Set, count: u64) -> Vec<u64> {
875    (0..)
876        .filter(|&index| super::draw(set, index).logger.profile == Profile::Altos)
877        .take(usize::try_from(count).unwrap_or(usize::MAX))
878        .collect()
879}
880
881/// The shares of `asked`, fitted on the fits of `fits` whose logs hold a horizontal track or don't,
882/// by `drift`: its share's 5% and 95% points; `None` for fewer than 20, or one that isn't a number.
883#[must_use]
884pub fn fitted(asked: Asked, drift: bool, fits: &[FlightFit]) -> Option<Shares> {
885    let slot = ASKED.iter().position(|a| *a == asked)?;
886    let shares: Vec<f64> = fits
887        .iter()
888        .filter(|f| f.fitted && f.drift == drift)
889        .map(|f| f.compared[slot].share())
890        .collect();
891    hpr_flightdata::readings::interval::fit(&shares)
892}
893
894/// The shares in force on a log that holds a horizontal track, or doesn't, by `drift`, fitted on
895/// [`Set::Calibration`]: `cargo xtask fit --calibrate` prints them. A
896/// track speaks to the wind, so its errors are small and of another kind: the two are told apart,
897/// as the log itself says which it is.
898#[must_use]
899pub fn shares(asked: Asked, drift: bool) -> Shares {
900    let (low, high) = match (asked, drift) {
901        (Asked::DragScale, false) => (-1.26, 1.43),
902        (Asked::ImpulseScale, false) => (-1.53, 1.47),
903        (Asked::WindEast, false) => (-0.374, 3.25),
904        (Asked::WindNorth, false) => (-1.71, 1.74),
905        (Asked::MassScale, false) => (-1.66, 1.67),
906        (Asked::DragScale, true) => (-1.29, 2.12),
907        (Asked::ImpulseScale, true) => (-1.5, 1.84),
908        (Asked::WindEast, true) => (-1.4, 1.29),
909        (Asked::WindNorth, true) => (-1.5, 1.38),
910        (Asked::MassScale, true) => (-1.68, 1.7),
911    };
912    Shares { low, high }
913}
914
915#[cfg(test)]
916#[allow(
917    clippy::unwrap_used,
918    clippy::expect_used,
919    reason = "a test stops at the failure (clippy.toml)"
920)]
921mod tests {
922    use super::*;
923
924    #[test]
925    fn the_wind_components_stated_width_is_what_the_draw_gives() {
926        // The draw's own component's 5% and 95% points, on many uniform draws.
927        let mut rng = SeededRng::for_stream(7, &[1]);
928        let mut values: Vec<f64> = (0..200_000)
929            .map(|_| {
930                let v = between(&mut rng, 0.0, super::super::MAX_WIND_M_S);
931                let theta = between(&mut rng, 0.0, std::f64::consts::TAU);
932                v * theta.sin()
933            })
934            .collect();
935        values.sort_by(f64::total_cmp);
936        let point = wind_component_point();
937        assert!(
938            (values[190_000] - point).abs() < 0.05,
939            "{} against {point}",
940            values[190_000]
941        );
942        assert!((values[10_000] + point).abs() < 0.05);
943    }
944
945    #[test]
946    fn with_no_log_each_interval_is_its_stated_range() {
947        for asked in ASKED {
948            let told = stated()[asked.index()];
949            let width = 2.0 * Z_90 * told.sd;
950            assert!((width - asked.stated_width()).abs() < 1e-12, "{asked:?}");
951        }
952    }
953
954    #[test]
955    fn each_method_states_its_own_interval() {
956        let compared = Compared {
957            value: 1.0,
958            standard_error: 0.1,
959            truth: 1.05,
960        };
961        let posterior = Posterior {
962            // Each unknown's row its own: 0.9 − i/10 to 1.3 + i/10.
963            quantiles: std::array::from_fn(|i| {
964                let i = f64::from(u8::try_from(i).unwrap());
965                [0.9 - 0.1 * i, 1.0, 1.3 + 0.1 * i]
966            }),
967            effective_draws: 150.0,
968            draws: 500,
969            failed: 0,
970            enough: true,
971        };
972        let fit = FlightFit {
973            index: 0,
974            design: 0,
975            fitted: true,
976            drift: false,
977            converged: true,
978            misfit_share: Some(0.01),
979            compared: [compared; ASKED.len()],
980            rms_m: Some(0.5),
981            flown: 70,
982            posterior: Some(posterior),
983        };
984        // The posterior's 5% and 95% points as they come, for the parameter's own row.
985        let bayes = interval_of(Method::Bayesian, &fit, Asked::DragScale).unwrap();
986        assert_eq!((bayes.low, bayes.high), (0.9, 1.3));
987        let mass = interval_of(Method::Bayesian, &fit, Asked::MassScale).unwrap();
988        assert!((mass.low - 0.4).abs() < 1e-12 && (mass.high - 1.8).abs() < 1e-12);
989        // The least squares' from its shares.
990        let shares = shares(Asked::DragScale, false);
991        let least = interval_of(Method::LeastSquares, &fit, Asked::DragScale).unwrap();
992        assert!((least.low - (1.0 - shares.high * 0.1)).abs() < 1e-12);
993        // A fitted log whose posterior had no weight states none; a log that said nothing states
994        // its stated range by either.
995        let without = FlightFit {
996            posterior: None,
997            ..fit.clone()
998        };
999        assert!(interval_of(Method::Bayesian, &without, Asked::DragScale).is_none());
1000        let nothing = FlightFit {
1001            fitted: false,
1002            posterior: None,
1003            ..fit
1004        };
1005        let both = Method::ALL.map(|m| interval_of(m, &nothing, Asked::DragScale).unwrap());
1006        assert_eq!(both[0], both[1]);
1007        assert!((both[0].high - (1.0 + Z_90 * 0.1)).abs() < 1e-12);
1008    }
1009
1010    #[test]
1011    fn the_weighing_factor_stays_in_its_range_and_fills_it() {
1012        let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
1013        for k in 0..2_000 {
1014            let f = weighed_factor(Set::A, k);
1015            low = low.min(f);
1016            high = high.max(f);
1017        }
1018        assert!((0.98..0.981).contains(&low), "{low}");
1019        assert!(high <= 1.02 && high > 1.019, "{high}");
1020    }
1021}