Skip to main content

hpr_forensics/synthetic/
census.rs

1//! A set's census: how many flights each design and logger flew, the ranges they span, and every
2//! draw that didn't fly, with its reason. `cargo xtask synthetic` commits it.
3//!
4//! Values are kept to three significant figures, the digits every platform shares: a flight's
5//! numbers match across platforms to many digits, not to the bit (`docs/physics/monte-carlo.md`).
6
7use std::collections::BTreeMap;
8
9use serde::{Deserialize, Serialize};
10
11use super::designs::{DESIGNS, DesignFiles};
12use super::{Flight, Flyer, Model, Set};
13
14/// The least, middle and greatest of a quantity over a set's flights.
15#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
16pub struct Range {
17    /// The least.
18    pub min: f64,
19    /// The median.
20    pub median: f64,
21    /// The greatest.
22    pub max: f64,
23}
24
25/// `x` to three significant figures, nearest.
26pub fn three_figures(x: f64) -> f64 {
27    to_three_figures(x, Toward::Nearest)
28}
29
30/// `x` rounded at the decimal place of `spread`'s third significant figure: a mean given no finer
31/// than the spread of the values it is taken over. A mean near zero is a small number, so three
32/// figures of its own would show a few of its values moved by a platform's arithmetic; three of the
33/// spread are the digits every platform shares. With `spread` zero or not finite, `x` to three
34/// significant figures of its own; a zero is never −0.
35pub fn at_the_figures_of(x: f64, spread: f64) -> f64 {
36    if spread == 0.0 || !spread.is_finite() || !x.is_finite() {
37        return three_figures(x);
38    }
39    #[expect(
40        clippy::cast_possible_truncation,
41        reason = "the decimal exponent of a finite, nonzero f64 lies within ±400"
42    )]
43    let place = 2 - spread.abs().log10().floor() as i32;
44    let rounded = if place >= 0 {
45        // Rust's own decimal formatting rounds the exact binary value, the same on every
46        // platform, and parses back to the nearest f64 of the printed digits.
47        let digits = usize::try_from(place).unwrap_or(0);
48        format!("{x:.digits$}").parse().unwrap_or(x)
49    } else {
50        let step = 10_f64.powi(-place);
51        (x / step).round() * step
52    };
53    if rounded == 0.0 { 0.0 } else { rounded }
54}
55
56/// Which way [`to_three_figures`] rounds.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58enum Toward {
59    Nearest,
60    Down,
61    Up,
62}
63
64/// `x` to three significant figures. Rounded down or up, the result is stepped once more if the
65/// division by the scale left it a hair on the wrong side of `x`, so a range's ends hold every
66/// value exactly.
67fn to_three_figures(x: f64, toward: Toward) -> f64 {
68    if x == 0.0 || !x.is_finite() {
69        return x;
70    }
71    let scale = 10_f64.powi(2 - x.abs().log10().floor() as i32);
72    let scaled = x * scale;
73    let whole = match toward {
74        Toward::Nearest => scaled.round(),
75        Toward::Down => scaled.floor(),
76        Toward::Up => scaled.ceil(),
77    };
78    let rounded = whole / scale;
79    match toward {
80        Toward::Down if rounded > x => (whole - 1.0) / scale,
81        Toward::Up if rounded < x => (whole + 1.0) / scale,
82        _ => rounded,
83    }
84}
85
86impl Range {
87    /// The range of `values` to three significant figures, its ends rounded outward (the least
88    /// down, the greatest up) so that the range holds every value, and its median to the nearest;
89    /// `None` if there are none.
90    fn of(mut values: Vec<f64>) -> Option<Self> {
91        if values.is_empty() {
92            return None;
93        }
94        values.sort_by(f64::total_cmp);
95        let n = values.len();
96        let median = if n % 2 == 1 {
97            values[n / 2]
98        } else {
99            0.5 * (values[n / 2 - 1] + values[n / 2])
100        };
101        Some(Self {
102            min: to_three_figures(values[0], Toward::Down),
103            median: three_figures(median),
104            max: to_three_figures(values[n - 1], Toward::Up),
105        })
106    }
107}
108
109/// A draw that didn't fly.
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111pub struct NotFlown {
112    /// Its index in the set.
113    pub index: u64,
114    /// Its design.
115    pub design: String,
116    /// Why.
117    pub reason: String,
118}
119
120/// One set's census.
121#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
122pub struct SetCensus {
123    /// The set.
124    pub set: Set,
125    /// Its seed.
126    pub seed: u64,
127    /// The flights drawn.
128    pub drawn: u64,
129    /// The flights flown to the ground and logged.
130    pub flown: u64,
131    /// Of those, the flights of set B's model.
132    pub other_model: u64,
133    /// Flights flown, by design.
134    pub by_design: BTreeMap<String, u64>,
135    /// Flights flown, by logger profile.
136    pub by_logger: BTreeMap<String, u64>,
137    /// The apogee above where the logger sat on the pad, m.
138    pub apogee_m: Option<Range>,
139    /// The top Mach number.
140    pub top_mach: Option<Range>,
141    /// The top vertical speed, m/s.
142    pub top_speed_m_s: Option<Range>,
143    /// The flight's time, liftoff to landing, s.
144    pub flight_time_s: Option<Range>,
145    /// The wind's speed, m/s.
146    pub wind_m_s: Option<Range>,
147    /// The rail's angle from vertical, degrees.
148    pub tilt_deg: Option<Range>,
149    /// The site's elevation, m.
150    pub elevation_m: Option<Range>,
151    /// The air's offset from the standard, K.
152    pub temperature_offset_k: Option<Range>,
153    /// Every draw that didn't fly.
154    pub not_flown: Vec<NotFlown>,
155}
156
157/// What a census keeps of one flight: a few numbers, not its log, so that a census of 1,000
158/// flights holds 1,000 rows rather than 1,000 logs.
159#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
160pub struct Row {
161    /// The design's name.
162    pub design: String,
163    /// The logger profile's name.
164    pub logger: String,
165    /// Whether it flew set B's model.
166    pub other_model: bool,
167    /// The apogee above where the logger sat on the pad, m.
168    pub apogee_m: f64,
169    /// The top Mach number.
170    pub top_mach: f64,
171    /// The top vertical speed, m/s.
172    pub top_speed_m_s: f64,
173    /// Liftoff to landing, s.
174    pub flight_time_s: f64,
175    /// The wind's speed, m/s.
176    pub wind_m_s: f64,
177    /// The rail's angle from vertical, degrees.
178    pub tilt_deg: f64,
179    /// The site's elevation, m.
180    pub elevation_m: f64,
181    /// The air's offset from the standard, K.
182    pub temperature_offset_k: f64,
183}
184
185impl Row {
186    /// A flight's row; a reason instead if any of its numbers isn't finite, so that a census
187    /// counts the flight as not flown rather than ranking around a NaN.
188    pub fn of(flight: &Flight) -> Result<Self, String> {
189        let draw = &flight.draw;
190        let truth = &flight.truth;
191        let row = Self {
192            design: design_name(draw.design).to_owned(),
193            logger: draw.logger.profile.name().to_owned(),
194            other_model: matches!(draw.model, Model::Other { .. }),
195            apogee_m: truth.apogee_above_pad_m(),
196            top_mach: truth.top_mach(),
197            top_speed_m_s: truth.top_speed().0,
198            flight_time_s: truth.events.landing_s - truth.events.liftoff_s,
199            wind_m_s: draw.wind_speed_m_s,
200            tilt_deg: draw.tilt_rad.to_degrees(),
201            elevation_m: draw.elevation_m,
202            temperature_offset_k: draw.temperature_offset_k,
203        };
204        let numbers = [
205            row.apogee_m,
206            row.top_mach,
207            row.top_speed_m_s,
208            row.flight_time_s,
209            row.wind_m_s,
210            row.tilt_deg,
211            row.elevation_m,
212            row.temperature_offset_k,
213        ];
214        if numbers.iter().all(|x| x.is_finite()) {
215            Ok(row)
216        } else {
217            Err("a number in its row isn't finite".to_owned())
218        }
219    }
220}
221
222/// Design `design`'s name, or a placeholder for an index that names none.
223fn design_name(design: usize) -> &'static str {
224    DESIGNS.get(design).map_or("not one of the ten", |d| d.name)
225}
226
227/// Flight `index` of `set` as a census row, or why it didn't fly.
228pub fn row(flyer: &mut Flyer, set: Set, index: u64) -> Result<Row, String> {
229    flyer
230        .flight(set, index)
231        .map_err(|error| error.to_string())
232        .and_then(|flight| Row::of(&flight))
233}
234
235/// The census of `set` from every flight's row, `rows[k]` flight `k`'s.
236pub fn from_rows(set: Set, rows: &[Result<Row, String>]) -> SetCensus {
237    let mut by_design = BTreeMap::new();
238    let mut by_logger = BTreeMap::new();
239    let mut not_flown = Vec::new();
240    let mut other_model = 0;
241    let mut columns: [Vec<f64>; 8] = Default::default();
242    for (index, row) in rows.iter().enumerate() {
243        match row {
244            Ok(row) => {
245                *by_design.entry(row.design.clone()).or_insert(0) += 1;
246                *by_logger.entry(row.logger.clone()).or_insert(0) += 1;
247                other_model += u64::from(row.other_model);
248                let values = [
249                    row.apogee_m,
250                    row.top_mach,
251                    row.top_speed_m_s,
252                    row.flight_time_s,
253                    row.wind_m_s,
254                    row.tilt_deg,
255                    row.elevation_m,
256                    row.temperature_offset_k,
257                ];
258                for (column, value) in columns.iter_mut().zip(values) {
259                    column.push(value);
260                }
261            }
262            Err(reason) => {
263                let index = index as u64;
264                not_flown.push(NotFlown {
265                    index,
266                    design: design_name(super::draw(set, index).design).to_owned(),
267                    reason: reason.clone(),
268                });
269            }
270        }
271    }
272    let drawn = rows.len() as u64;
273    let [apogee, mach, speed, time, wind, tilt, elevation, offset] = columns;
274    SetCensus {
275        set,
276        seed: set.seed(),
277        drawn,
278        flown: drawn - not_flown.len() as u64,
279        other_model,
280        by_design,
281        by_logger,
282        apogee_m: Range::of(apogee),
283        top_mach: Range::of(mach),
284        top_speed_m_s: Range::of(speed),
285        flight_time_s: Range::of(time),
286        wind_m_s: Range::of(wind),
287        tilt_deg: Range::of(tilt),
288        elevation_m: Range::of(elevation),
289        temperature_offset_k: Range::of(offset),
290        not_flown,
291    }
292}
293
294/// Flies the first `count` flights of `set` one after another and counts what came of them;
295/// `cargo xtask synthetic` flies whole sets on several threads and gives each flight's row to
296/// [`from_rows`] in order, which comes to the same.
297pub fn census(set: Set, count: u64, files: DesignFiles) -> SetCensus {
298    let mut flyer = Flyer::new(files);
299    let rows: Vec<_> = (0..count)
300        .map(|index| row(&mut flyer, set, index))
301        .collect();
302    from_rows(set, &rows)
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308
309    fn a_row(design: &str, logger: &str, other_model: bool, apogee_m: f64) -> Row {
310        Row {
311            design: design.to_owned(),
312            logger: logger.to_owned(),
313            other_model,
314            apogee_m,
315            top_mach: 0.5,
316            top_speed_m_s: 170.0,
317            flight_time_s: 100.0,
318            wind_m_s: 3.0,
319            tilt_deg: 5.0,
320            elevation_m: 200.0,
321            temperature_offset_k: 0.0,
322        }
323    }
324
325    #[test]
326    fn a_census_counts_the_flown_rows_and_names_each_draw_not_flown() {
327        let rows = vec![
328            Ok(a_row("x", "altos", false, 1_000.0)),
329            Err("it hit a wall".to_owned()),
330            Ok(a_row("y", "altos", true, 3_000.0)),
331            Ok(a_row("x", "rrc3", true, 2_000.0)),
332            Err("its row isn't finite".to_owned()),
333        ];
334        let census = from_rows(Set::B, &rows);
335        assert_eq!((census.drawn, census.flown, census.other_model), (5, 3, 2));
336        assert_eq!(census.by_design.get("x"), Some(&2));
337        assert_eq!(census.by_design.get("y"), Some(&1));
338        assert_eq!(census.by_logger.get("altos"), Some(&2));
339        assert_eq!(census.by_logger.get("rrc3"), Some(&1));
340        let apogee = census.apogee_m.unwrap();
341        assert_eq!(
342            (apogee.min, apogee.median, apogee.max),
343            (1_000.0, 2_000.0, 3_000.0)
344        );
345        // Each draw not flown keeps its own index, its drawn design and its reason.
346        let missing: Vec<_> = census
347            .not_flown
348            .iter()
349            .map(|n| (n.index, n.design.as_str(), n.reason.as_str()))
350            .collect();
351        let name = |index| DESIGNS[super::super::draw(Set::B, index).design].name;
352        assert_eq!(
353            missing,
354            [
355                (1, name(1), "it hit a wall"),
356                (4, name(4), "its row isn't finite")
357            ]
358        );
359        // With nothing flown, every range is empty.
360        let none = from_rows(Set::A, &[Err("no".to_owned())]);
361        assert_eq!((none.drawn, none.flown), (1, 0));
362        assert!(none.apogee_m.is_none() && none.top_mach.is_none());
363    }
364
365    #[test]
366    fn three_figures_rounds_to_three_significant_digits() {
367        assert_eq!(three_figures(1234.5), 1230.0);
368        assert_eq!(three_figures(0.012_345), 0.0123);
369        assert_eq!(three_figures(-8.886), -8.89);
370        assert_eq!(three_figures(0.0), 0.0);
371    }
372
373    /// A mean is rounded where its spread's third figure lies: the tuning set's apogee time,
374    /// 0.0401 s on one platform and 0.0398 s on another, a spread of 1.2 s, is 0.04 s on both.
375    #[test]
376    fn a_mean_takes_its_spreads_figures() {
377        assert_eq!(at_the_figures_of(0.0401, 1.2), 0.04);
378        assert_eq!(at_the_figures_of(0.0398, 1.2), 0.04);
379        assert_eq!(at_the_figures_of(-0.0118, 0.0943), -0.0118);
380        assert_eq!(at_the_figures_of(0.659, 13.6), 0.7);
381        assert_eq!(at_the_figures_of(1234.0, 5678.0), 1230.0);
382        let zero = at_the_figures_of(-0.0329, 12.4);
383        assert!(zero == 0.0 && zero.is_sign_positive(), "{zero}");
384        assert_eq!(at_the_figures_of(0.012_345, 0.0), 0.0123);
385    }
386
387    #[test]
388    fn a_range_has_its_least_median_and_greatest() {
389        let r = Range::of(vec![3.0, 1.0, 2.0, 10.0]).unwrap();
390        assert_eq!((r.min, r.median, r.max), (1.0, 2.5, 10.0));
391        // The ends round outward, so the range holds every value; the median to the nearest.
392        let r = Range::of(vec![1.174_9, 412.6, -14.62, 1.0]).unwrap();
393        assert_eq!((r.min, r.max), (-14.7, 413.0));
394        assert!(r.median <= 1.18 && r.median >= 1.08);
395        let r = Range::of(vec![1.174_9]).unwrap();
396        assert_eq!((r.min, r.median, r.max), (1.17, 1.17, 1.18));
397        assert_eq!(Range::of(Vec::new()), None);
398    }
399}