Skip to main content

hpr_forensics/synthetic/
logger.rs

1//! The loggers of the synthetic flights: six profiles, each like a family HPR Sim's readers read,
2//! and the log one writes of a flight's truth.
3//!
4//! Rates are the makers' (`docs/research/altimeter-smoothing-methods.md` §2); parts, noise, ranges
5//! and steps are their datasheets' (`altimeter-sensor-noise.md` §2, §4–6); a logger turns pressure
6//! into height by the standard atmosphere and zeroes it on the pad
7//! (`altimeter-height-formulas.md`). Every range is
8//! [ADR-280, the synthetic flights first](https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0280-m7-2-in-seven-the-synthetic-flights-first.md) §3's.
9
10use hpr_core::DVec3;
11use hpr_core::earth::Earth;
12use hpr_core::geodesy::Geodetic;
13use hpr_core::gravity::STANDARD_GRAVITY_MPS2 as G;
14use hpr_core::random::SeededRng;
15use hpr_flightdata::log::{Channel, FlightLog, LogFormat, Quantity, Stated};
16use serde::{Deserialize, Serialize};
17
18use super::noise::{self, Lag, between, ornstein_uhlenbeck, quantize, tau_for};
19use super::truth::{SITE_LATITUDE_DEG, SITE_LONGITUDE_DEG, TRUTH_STEP_S, Truth, TruthSample};
20use super::{Key, SyntheticError, stream};
21
22/// The foot, m.
23const FOOT_M: f64 = 0.3048;
24/// One atmosphere, Pa.
25const ATMOSPHERE_PA: f64 = 101_325.0;
26
27/// A logger profile.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
29#[serde(rename_all = "kebab-case")]
30pub enum Profile {
31    /// Like a PerfectFlite StratoLoggerCF: 20 Hz, its altitude in whole feet.
32    PerfectFlite,
33    /// Like a Missile Works RRC3: 20 Hz, an MS5607's pressure in 10 Pa steps.
34    Rrc3,
35    /// Like an Eggtimer Quantum: 20 Hz, a Bosch barometer's altitude in whole feet.
36    Eggtimer,
37    /// Like an Altus Metrum TeleMetrum: 100 Hz up and 10 Hz down, an MS5607's pressure, a high-g
38    /// accelerometer and a GNSS receiver.
39    Altos,
40    /// Like a Featherweight Blue Raven: 500 Hz, a Bosch barometer and a low-g accelerometer.
41    Imu500,
42    /// A GNSS tracker: position and altitude only.
43    GnssTracker,
44}
45
46impl Profile {
47    /// Every profile, each equally likely in a draw.
48    pub const ALL: [Self; 6] = [
49        Self::PerfectFlite,
50        Self::Rrc3,
51        Self::Eggtimer,
52        Self::Altos,
53        Self::Imu500,
54        Self::GnssTracker,
55    ];
56
57    /// Its name in the census.
58    pub fn name(self) -> &'static str {
59        match self {
60            Self::PerfectFlite => "perfectflite",
61            Self::Rrc3 => "rrc3",
62            Self::Eggtimer => "eggtimer",
63            Self::Altos => "altos",
64            Self::Imu500 => "imu-500hz",
65            Self::GnssTracker => "gnss-tracker",
66        }
67    }
68
69    /// The format of the family it is like, which its logs are tagged with.
70    pub fn format(self) -> LogFormat {
71        match self {
72            Self::PerfectFlite => LogFormat::PerfectFlitePf2,
73            Self::Rrc3 => LogFormat::Rrc3Csv,
74            Self::Eggtimer => LogFormat::EggtimerCsv,
75            Self::Altos => LogFormat::AltosCsv,
76            Self::Imu500 => LogFormat::BlueRavenCsv,
77            Self::GnssTracker => LogFormat::FeatherweightGpsCsv,
78        }
79    }
80
81    /// How its log is written: its rates and its barometer's step, `None` for a profile with no
82    /// barometer.
83    pub fn recording(self) -> Option<Recording> {
84        self.barometer().map(|baro| Recording {
85            climbing_hz: self.rate_hz(true),
86            descending_hz: self.rate_hz(false),
87            written: baro.written,
88        })
89    }
90
91    /// The barometer's sample rate, Hz, climbing or not: PerfectFlite 20 Hz ([PF1] p. 47),
92    /// RRC3 20 Hz ([MW1]), Eggtimer 20 Hz ([E1] p. 25), AltOS 100 Hz up and 10 down ([A1]
93    /// p. 77), Blue Raven's 500 Hz set ([F2]).
94    fn rate_hz(self, climbing: bool) -> f64 {
95        match self {
96            Self::PerfectFlite | Self::Rrc3 | Self::Eggtimer => 20.0,
97            Self::Altos if climbing => 100.0,
98            Self::Altos => 10.0,
99            Self::Imu500 => 500.0,
100            Self::GnssTracker => 0.0,
101        }
102    }
103
104    /// The pressure sensor.
105    fn barometer(self) -> Option<Barometer> {
106        match self {
107            // PerfectFlite names no part: the noise measured at rest in public logs, the
108            // MS5607's offset (sensor noise §3, §6), and its stated ±0.1% of the height, read as
109            // a gain on the pressure's change (§1, "Steps and accuracy").
110            Self::PerfectFlite => Some(Barometer {
111                white_pa: (0.0, 0.0),
112                offset_pa: 100.0,
113                relative_gain: 1.0e-3,
114                written: Written::Altitude { step_m: FOOT_M },
115            }),
116            // An MS5607 at 2.3 Pa, logged in 10 Pa steps (sensor noise §6). Its ±1.0 mbar after
117            // the pad's zero, over the 400 mbar the datasheet states it on (700–1100 mbar, §2
118            // note †), is read as a gain of ±0.25% on the change from the pad (an inference).
119            Self::Rrc3 => Some(Barometer {
120                white_pa: (2.3, 2.3),
121                offset_pa: 100.0,
122                relative_gain: MS5607_RELATIVE_GAIN,
123                written: Written::Pressure { step_pa: 10.0 },
124            }),
125            // An MS5607 at 2.4–13 Pa by its oversampling, logged to 1 Pa, its error after the
126            // pad's zero as the RRC3's.
127            Self::Altos => Some(Barometer {
128                white_pa: (2.4, 13.0),
129                offset_pa: 100.0,
130                relative_gain: MS5607_RELATIVE_GAIN,
131                written: Written::Pressure { step_pa: 1.0 },
132            }),
133            // A Bosch BMP-class part, 0.2–6.6 Pa by its setting, relative accuracy 0.03–0.08 hPa
134            // per 100 hPa (sensor noise §2, §6).
135            Self::Eggtimer => Some(Barometer {
136                white_pa: (0.2, 6.6),
137                offset_pa: 0.0,
138                relative_gain: 8.0e-4,
139                written: Written::Altitude { step_m: FOOT_M },
140            }),
141            // The same part, logged in Blue Raven's 2 × 10⁻⁵ atm steps (its user's guide, p. 23).
142            Self::Imu500 => Some(Barometer {
143                white_pa: (0.2, 6.6),
144                offset_pa: 0.0,
145                relative_gain: 8.0e-4,
146                written: Written::Pressure {
147                    step_pa: 2.0e-5 * ATMOSPHERE_PA,
148                },
149            }),
150            Self::GnssTracker => None,
151        }
152    }
153
154    /// The accelerometer.
155    fn accelerometer(self) -> Option<Accelerometer> {
156        match self {
157            // ADXL375: 5 mg/√Hz, 49 mg steps, its minimum range ±180 g, scale ±10% ([D1] p. 3).
158            Self::Altos => Some(Accelerometer {
159                density_g_per_root_hz: (0.005, 0.005),
160                step_g: 0.049,
161                range_g: 180.0,
162                lower_range_g: None,
163                scale: 0.10,
164            }),
165            // A low-g IMU axis: 160–400 µg/√Hz ([D3], [D9]), ±32 g as Blue Raven's parts ([F3]
166            // p. 24) on 16 bits, scale ±3% ([D9]); past 32 g it clips, as the high-range part
167            // that takes over isn't modeled. Such a part offers ±8 g too, as the BMX160 ([D8]
168            // p. 8) and the MPU-6000 ([D9] p. 13) do, on the same 16 bits.
169            Self::Imu500 => Some(Accelerometer {
170                density_g_per_root_hz: (0.000_16, 0.000_4),
171                step_g: 64.0 / 65_536.0,
172                range_g: 32.0,
173                lower_range_g: Some(LOWER_RANGE_G),
174                scale: 0.03,
175            }),
176            _ => None,
177        }
178    }
179
180    /// The range its accelerometer clips at, m/s²; `None` with no accelerometer.
181    pub fn accelerometer_range_m_s2(self) -> Option<f64> {
182        self.accelerometer().map(|accel| accel.range_g * G)
183    }
184
185    /// The lower range its accelerometer can be set to, m/s², which
186    /// [`accelerometer_log_set_lower`] logs it at; `None` with no accelerometer or no such
187    /// setting.
188    pub fn accelerometer_lower_range_m_s2(self) -> Option<f64> {
189        self.accelerometer()
190            .and_then(|accel| accel.lower_range_g)
191            .map(|range_g| range_g * G)
192    }
193
194    /// How far its accelerometer's per-flight scale error runs either way, as a share; `None`
195    /// with no accelerometer.
196    pub fn accelerometer_scale(self) -> Option<f64> {
197        self.accelerometer().map(|accel| accel.scale)
198    }
199
200    /// Whether it has a GNSS receiver.
201    fn gnss(self) -> bool {
202        matches!(self, Self::Altos | Self::GnssTracker)
203    }
204}
205
206/// How a log is written: the barometer's rates and how its reading is written. A profile's own
207/// is [`Profile::recording`]; the readings' check ([`super::held`]) writes each tuning flight
208/// again at other rates and steps.
209#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
210pub struct Recording {
211    /// Samples a second while climbing, to the first sample past apogee.
212    pub climbing_hz: f64,
213    /// Samples a second after it.
214    pub descending_hz: f64,
215    /// How the barometer's reading is written.
216    pub written: Written,
217}
218
219/// How a barometer's reading is written.
220#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
221#[serde(rename_all = "snake_case")]
222pub enum Written {
223    /// As the logger's altitude in steps of `step_m`, none if 0: the record's primary track, as
224    /// a PerfectFlite writes whole feet.
225    Altitude {
226        /// The step, m.
227        step_m: f64,
228    },
229    /// As a pressure in steps of `step_pa`, kept in a channel, its altitude worked out beside it
230    /// as the primary track.
231    Pressure {
232        /// The step, Pa.
233        step_pa: f64,
234    },
235    /// As a pressure in steps of `step_pa` alone, in a channel, as a raw download keeps it.
236    PressureAlone {
237        /// The step, Pa.
238        step_pa: f64,
239    },
240}
241
242/// A pressure sensor's stated terms.
243#[derive(Debug, Clone, Copy, PartialEq)]
244struct Barometer {
245    /// The range of its white noise, 1σ, Pa.
246    white_pa: (f64, f64),
247    /// Its per-flight offset is drawn from ±this, Pa.
248    offset_pa: f64,
249    /// Its per-flight gain error on the pressure's change from the pad is drawn from ±this.
250    relative_gain: f64,
251    /// How it is written.
252    written: Written,
253}
254
255/// An accelerometer's stated terms.
256#[derive(Debug, Clone, Copy, PartialEq)]
257struct Accelerometer {
258    /// The range of its noise density, g/√Hz.
259    density_g_per_root_hz: (f64, f64),
260    /// Its step, g.
261    step_g: f64,
262    /// It clips at ±this, g.
263    range_g: f64,
264    /// A lower full scale the part can be set to, g, on the same bits; `None` for a part with
265    /// none.
266    lower_range_g: Option<f64>,
267    /// Its per-flight scale error is drawn from ±this.
268    scale: f64,
269}
270
271/// The lower full scale a low-g IMU axis is set to in [`accelerometer_log_set_lower`], g: ±8 g,
272/// as the BMX160 and the MPU-6000 offer, which most of the IMU-like logger's tuning flights' tops
273/// pass and the rest don't, as the synthetic flights' report counts. The readings know it by its
274/// column,
275/// [`hpr_flightdata::readings::SYNTHETIC_LOWER_RANGE_COLUMN`], whose family states it.
276pub const LOWER_RANGE_G: f64 = 8.0;
277
278/// The MS5607's error after a zero at one pressure, ±1.0 mbar over 0–50 °C, read over the
279/// 400 mbar (700–1100 mbar) its datasheet states the figure on as a gain on the pressure's change
280/// from the pad (sensor noise §2 note †, §6; an inference).
281pub const MS5607_RELATIVE_GAIN: f64 = 100.0 / 40_000.0;
282/// The fast correlated barometer noise: 0.5 m at 50 Hz, lag-one correlation 0.5, as on the pads of
283/// five Blue Raven logs (sensor noise §3, §6).
284pub const CORRELATED_NOISE_M: f64 = 0.5;
285/// The correlated noise's lag-one correlation at [`CORRELATED_NOISE_RATE_HZ`].
286pub const CORRELATED_NOISE_PHI: f64 = 0.5;
287/// The rate at which it was measured, Hz.
288pub const CORRELATED_NOISE_RATE_HZ: f64 = 50.0;
289/// The slow correlated barometer noise, a first-order Gauss–Markov term of 0.24–0.29 m and time
290/// constant 0.65–1.26 s, as a BMP085's ten minutes at rest gave (sensor noise §3; Sabatini and
291/// Genovese, Sensors 13(11):15692, 2013, Tables 1–2): the noise that a reading averaged over a
292/// second keeps, which the fast term alone leaves out.
293pub const SLOW_NOISE_M: (f64, f64) = (0.24, 0.29);
294/// Its time constant's range, s.
295pub const SLOW_NOISE_TAU_S: (f64, f64) = (0.65, 1.26);
296/// The residual accelerometer bias after the pad's zero is drawn from ±this, g: the top of the
297/// ±10–50 mg that sensor noise's *What this suggests* 1 calls a guess, as no source states one.
298pub const ACCEL_BIAS_G: f64 = 0.05;
299/// A GNSS fix's noise, 1σ along each axis, m: the filter's σ in GNSS in boost §4's simulation,
300/// which was fed noise-free fixes, taken as a receiver's noise (an assumption).
301pub const GNSS_NOISE_M: f64 = 3.0;
302
303/// What one flight's logger draws.
304#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
305pub struct LoggerDraw {
306    /// The profile.
307    pub profile: Profile,
308    /// Seconds logged on the pad before launch.
309    pub pad_s: f64,
310    /// Seconds logged on the ground after landing.
311    pub ground_s: f64,
312    /// The barometer's white noise, 1σ, Pa.
313    pub white_pa: f64,
314    /// Its offset, Pa.
315    pub offset_pa: f64,
316    /// Its gain error on the pressure's change from the pad.
317    pub gain: f64,
318    /// Its drift, Pa/s.
319    pub drift_pa_s: f64,
320    /// Its port's distance behind the nose's shoulder, calibers.
321    pub port_calibers: f64,
322    /// The ejection pulses' scale on the Pnut's.
323    pub pulse_scale: f64,
324    /// The accelerometer's noise density, g/√Hz.
325    pub density_g_per_root_hz: f64,
326    /// Its scale error.
327    pub accel_scale: f64,
328    /// Its residual bias, m/s².
329    pub accel_bias_m_s2: f64,
330    /// The barometer's fast correlated noise, 1σ at the pad, m.
331    pub fast_noise_m: f64,
332    /// Its slow correlated noise, 1σ at the pad, m.
333    pub slow_noise_m: f64,
334    /// The slow noise's time constant, s.
335    pub slow_noise_tau_s: f64,
336    /// The GNSS receiver's fix rate, Hz.
337    pub gnss_rate_hz: f64,
338    /// Its loop's natural frequency, rad/s.
339    pub gnss_omega_rad_s: f64,
340    /// Its dropout from liftoff, s.
341    pub gnss_dropout_liftoff_s: f64,
342    /// Its dropout from burnout, s.
343    pub gnss_dropout_burnout_s: f64,
344}
345
346impl LoggerDraw {
347    /// Draws a profile's terms from their stated ranges.
348    pub fn draw(rng: &mut SeededRng, profile: Profile) -> Self {
349        let baro = profile.barometer();
350        let accel = profile.accelerometer();
351        let sign = |rng: &mut SeededRng| if rng.uniform() < 0.5 { -1.0 } else { 1.0 };
352        let pad_s = between(rng, 2.0, 10.0);
353        let ground_s = between(rng, 2.0, 10.0);
354        let white_pa = baro.map_or(0.0, |b| between(rng, b.white_pa.0, b.white_pa.1));
355        let offset_pa = baro.map_or(0.0, |b| between(rng, -b.offset_pa, b.offset_pa));
356        let gain = baro.map_or(0.0, |b| between(rng, -b.relative_gain, b.relative_gain));
357        // 1–3 Pa over 30–300 s, either way (sensor noise §3).
358        let drift_pa_s = sign(rng) * between(rng, 1.0, 3.0) / between(rng, 30.0, 300.0);
359        let port_calibers = between(rng, 1.0, 5.0);
360        let pulse_scale = between(rng, 0.0, 2.0);
361        let density = accel.map_or(0.0, |a| {
362            between(rng, a.density_g_per_root_hz.0, a.density_g_per_root_hz.1)
363        });
364        let accel_scale = accel.map_or(0.0, |a| between(rng, -a.scale, a.scale));
365        let accel_bias_m_s2 = between(rng, -ACCEL_BIAS_G, ACCEL_BIAS_G) * G;
366        // 1 Hz by default, faster where set ([GNSS in boost] §1).
367        let gnss_rate_hz = [1.0, 5.0, 10.0][(rng.uniform() * 3.0) as usize % 3];
368        // About the simulated filter's 0.47–0.69 rad/s (GNSS in boost §4), widened both ways: an
369        // assumption.
370        let gnss_omega_rad_s = between(rng, 0.25, 1.0);
371        let gnss_dropout_liftoff_s = between(rng, 0.0, 10.0);
372        let gnss_dropout_burnout_s = between(rng, 0.0, 10.0);
373        let fast_noise_m = baro.map_or(0.0, |_| CORRELATED_NOISE_M);
374        let slow_noise_m = baro.map_or(0.0, |_| between(rng, SLOW_NOISE_M.0, SLOW_NOISE_M.1));
375        let slow_noise_tau_s = between(rng, SLOW_NOISE_TAU_S.0, SLOW_NOISE_TAU_S.1);
376        Self {
377            profile,
378            pad_s,
379            ground_s,
380            white_pa,
381            offset_pa,
382            gain,
383            drift_pa_s,
384            port_calibers,
385            pulse_scale,
386            density_g_per_root_hz: density,
387            accel_scale,
388            accel_bias_m_s2,
389            fast_noise_m,
390            slow_noise_m,
391            slow_noise_tau_s,
392            gnss_rate_hz,
393            gnss_omega_rad_s,
394            gnss_dropout_liftoff_s,
395            gnss_dropout_burnout_s,
396        }
397    }
398}
399
400/// The logger's clock, s from its own zero, `pad_s` before launch to `ground_s` after landing.
401fn clock(recording: &Recording, draw: &LoggerDraw, truth: &Truth) -> Vec<f64> {
402    let end = draw.pad_s + truth.events.landing_s + draw.ground_s;
403    let apogee = draw.pad_s + truth.events.apogee_s;
404    let mut times = Vec::new();
405    let mut t = 0.0;
406    let mut k = 0_u64;
407    let mut base = 0.0;
408    let mut rate = recording.climbing_hz;
409    while t <= end {
410        times.push(t);
411        k += 1;
412        let next = base + k as f64 / rate;
413        if next > apogee && rate != recording.descending_hz {
414            // The rate changes at the first sample past apogee.
415            rate = recording.descending_hz;
416            base = next;
417            k = 0;
418            t = next;
419        } else {
420            t = next;
421        }
422    }
423    times
424}
425
426/// A logger's height of `pressure_pa`, m: the standard atmosphere's pressure altitude, except the
427/// RRC3's NOAA formula, h = 145,366.45 ft × (1 − (P/1013.25 hPa)^0.190284) (MW1 p. 23).
428fn height_of(profile: Profile, pressure_pa: f64) -> Result<f64, SyntheticError> {
429    Ok(match profile {
430        Profile::Rrc3 => 145_366.45 * FOOT_M * (1.0 - (pressure_pa / 101_325.0).powf(0.190_284)),
431        _ => hpr_atmos::Ussa76::standard().pressure_altitude_m(pressure_pa)?,
432    })
433}
434
435/// Refuses a draw or a truth no logger could write: a clock that doesn't run forward, a truth
436/// with no samples or a time that isn't finite.
437fn check(draw: &LoggerDraw, truth: &Truth) -> Result<(), SyntheticError> {
438    let invalid = |what| Err(SyntheticError::Invalid { what });
439    let spans = [draw.pad_s, draw.ground_s];
440    if spans.iter().any(|s| !s.is_finite() || *s < 0.0) {
441        return invalid("a logger's pad or ground span that isn't a finite length");
442    }
443    if draw.profile.gnss() && !(draw.gnss_rate_hz.is_finite() && draw.gnss_rate_hz > 0.0) {
444        return invalid("a GNSS fix rate that isn't a positive number");
445    }
446    if !(draw.slow_noise_tau_s.is_finite() && draw.slow_noise_tau_s > 0.0) {
447        return invalid("a slow noise time constant that isn't a positive number");
448    }
449    let events = &truth.events;
450    let times = [
451        events.liftoff_s,
452        events.burnout_s,
453        events.apogee_s,
454        events.landing_s,
455    ];
456    if truth.samples.is_empty() || times.iter().any(|t| !t.is_finite()) {
457        return invalid("a truth with no samples or an event at no finite time");
458    }
459    if truth.samples.iter().any(|s| !s.time_s.is_finite()) {
460        return invalid("a truth sample at no finite time");
461    }
462    // The clock writes a sample for every step it runs, so a log longer than a day, which no
463    // flight lasts, is refused rather than allocated.
464    let length_s = draw.pad_s + events.landing_s + draw.ground_s;
465    if length_s.is_nan() || length_s > MAX_LOG_S {
466        return invalid("a log longer than a day");
467    }
468    Ok(())
469}
470
471/// The longest log a logger writes, s: a day.
472const MAX_LOG_S: f64 = 86_400.0;
473
474/// The truth at `t`, refused where there is none.
475fn truth_at(truth: &Truth, t: f64) -> Result<TruthSample, SyntheticError> {
476    truth.at(t).ok_or(SyntheticError::Invalid {
477        what: "a truth with no sample at that time",
478    })
479}
480
481/// The log `draw`'s logger writes of `truth`, with noise drawn from `seed`'s streams for flight
482/// `index`.
483///
484/// # Errors
485///
486/// [`SyntheticError`] for a pressure or a position the atmosphere or the frame can't take, and
487/// [`SyntheticError::Invalid`] for a draw or truth that `check` refuses.
488pub fn log(
489    draw: &LoggerDraw,
490    truth: &Truth,
491    seed: u64,
492    index: u64,
493) -> Result<FlightLog, SyntheticError> {
494    let recording = draw.profile.recording();
495    write(draw, recording.as_ref(), true, truth, seed, index)
496}
497
498/// The log `draw`'s barometer would write of `truth` at `recording`'s rates and step, with the
499/// same noise terms and streams, and nothing else: no accelerometer, no GNSS receiver. Tagged as a
500/// table read by a mapping ([`LogFormat::GenericTable`]), so that a reading takes the track's
501/// step from the track itself. `None` for a profile with no barometer.
502///
503/// # Errors
504///
505/// As [`log`].
506pub fn barometer_log(
507    draw: &LoggerDraw,
508    recording: &Recording,
509    truth: &Truth,
510    seed: u64,
511    index: u64,
512) -> Result<Option<FlightLog>, SyntheticError> {
513    if draw.profile.barometer().is_none() {
514        return Ok(None);
515    }
516    let mut log = write(draw, Some(recording), false, truth, seed, index)?;
517    log.format = LogFormat::GenericTable;
518    Ok(Some(log))
519}
520
521/// The accelerometer's channel at `times`, the part sampled at `rate_hz` while climbing, under
522/// the synthetic flights' column.
523fn accelerometer_channel(
524    draw: &LoggerDraw,
525    accel: &Accelerometer,
526    rate_hz: f64,
527    times: &[f64],
528    truth: &Truth,
529    (seed, index): (u64, u64),
530) -> Result<Channel, SyntheticError> {
531    accelerometer_channel_under(
532        hpr_flightdata::readings::SYNTHETIC_COLUMN,
533        draw,
534        accel,
535        rate_hz,
536        times,
537        truth,
538        (seed, index),
539    )
540}
541
542/// The accelerometer's channel under `column`, as [`accelerometer_channel`].
543fn accelerometer_channel_under(
544    column: &str,
545    draw: &LoggerDraw,
546    accel: &Accelerometer,
547    rate_hz: f64,
548    times: &[f64],
549    truth: &Truth,
550    (seed, index): (u64, u64),
551) -> Result<Channel, SyntheticError> {
552    let accel_noise = noise::white(&mut stream(seed, index, Key::Accel), times.len(), 1.0);
553    // RMS from the density over the part's bandwidth, half the climbing rate it is sampled at:
554    // σ = density × √(1.57 × bandwidth) (sensor noise §4). A logger that writes fewer samples
555    // after apogee keeps the part's bandwidth, so its noise.
556    let bandwidth_hz = rate_hz / 2.0;
557    let sigma = draw.density_g_per_root_hz * (1.57 * bandwidth_hz).sqrt() * G;
558    let range = accel.range_g * G;
559    let values = times
560        .iter()
561        .enumerate()
562        .map(|(k, &t_log)| {
563            let f = truth_at(truth, t_log - draw.pad_s)?.axial_specific_force_m_s2;
564            let read = (1.0 + draw.accel_scale) * f + draw.accel_bias_m_s2 + sigma * accel_noise[k];
565            Ok(quantize(read.clamp(-range, range), accel.step_g * G))
566        })
567        .collect::<Result<Vec<_>, SyntheticError>>()?;
568    Ok(Channel::new(
569        column,
570        Quantity::Acceleration,
571        times.to_vec(),
572        values,
573    ))
574}
575
576/// The log `draw`'s logger writes of `truth`, its accelerometer set to the lower full scale its
577/// part offers ([`Profile::accelerometer_lower_range_m_s2`]): the same part, noise terms and
578/// streams on the same clock, clipping at the lower range, as the BMX160 holds its maximum code
579/// past it (sensor noise §5, its datasheet p. 32), in steps of the part's 16 bits over it, under
580/// [`hpr_flightdata::readings::SYNTHETIC_LOWER_RANGE_COLUMN`]. `None` for a part with no such
581/// setting.
582///
583/// # Errors
584///
585/// As [`log`].
586pub fn accelerometer_log_set_lower(
587    draw: &LoggerDraw,
588    truth: &Truth,
589    seed: u64,
590    index: u64,
591) -> Result<Option<FlightLog>, SyntheticError> {
592    let Some(lower_g) = draw
593        .profile
594        .accelerometer()
595        .and_then(|accel| accel.lower_range_g)
596    else {
597        return Ok(None);
598    };
599    accelerometer_log_clipping_at(draw, truth, lower_g, seed, index)
600}
601
602/// The log `draw`'s logger writes of `truth`, its accelerometer clipping at `lower_g` whatever
603/// ranges its part offers, in [`hpr_flightdata::readings::SYNTHETIC_LOWER_RANGE_COLUMN`]. The
604/// reader knows that column's range on the IMU's table, and on an AltOS log, whose family states
605/// none, tells the clip by its flat top. No flight's own accelerometer clips, so the 90%
606/// intervals' test ([`super::intervals`]) reads a top acceleration's floors from such logs. `None`
607/// for a profile with no accelerometer.
608///
609/// # Errors
610///
611/// [`SyntheticError`] if the log can't be written.
612pub(super) fn accelerometer_log_clipping_at(
613    draw: &LoggerDraw,
614    truth: &Truth,
615    lower_g: f64,
616    seed: u64,
617    index: u64,
618) -> Result<Option<FlightLog>, SyntheticError> {
619    let Some(accel) = draw.profile.accelerometer() else {
620        return Ok(None);
621    };
622    let set = Accelerometer {
623        range_g: lower_g,
624        // The part's bits over the range it is set to: its step over its own range, scaled.
625        step_g: accel.step_g * lower_g / accel.range_g,
626        ..accel
627    };
628    let mut log = log(draw, truth, seed, index)?;
629    for kept in &mut log.channels {
630        if kept.quantity == Quantity::Acceleration {
631            *kept = accelerometer_channel_under(
632                hpr_flightdata::readings::SYNTHETIC_LOWER_RANGE_COLUMN,
633                draw,
634                &set,
635                draw.profile.rate_hz(true),
636                &kept.time_s,
637                truth,
638                (seed, index),
639            )?;
640        }
641    }
642    Ok(Some(log))
643}
644
645/// [`accelerometer_log_clipping_at`] of `truth`, its specific force above the 1 g it reads on the
646/// pad scaled so that its top is `top_m_s2`; its coast and the rest of the flight as flown.
647/// `truth_top_m_s2` is `truth`'s own top, which must be above 1 g.
648///
649/// # Errors
650///
651/// [`SyntheticError`] if the log can't be written.
652pub(super) fn accelerometer_log_top_scaled(
653    draw: &LoggerDraw,
654    truth: &Truth,
655    (truth_top_m_s2, top_m_s2): (f64, f64),
656    lower_g: f64,
657    seed: u64,
658    index: u64,
659) -> Result<Option<FlightLog>, SyntheticError> {
660    let mut scaled = truth.clone();
661    let factor = (top_m_s2 - G) / (truth_top_m_s2 - G);
662    for sample in &mut scaled.samples {
663        let force = sample.axial_specific_force_m_s2;
664        if force > G {
665            sample.axial_specific_force_m_s2 = G + factor * (force - G);
666        }
667    }
668    accelerometer_log_clipping_at(draw, &scaled, lower_g, seed, index)
669}
670
671/// The log `draw`'s logger writes of `truth`, its accelerometer sampled at `rate_hz` on its own
672/// clock in place of the barometer's: the same part, noise terms and streams, its noise grown
673/// with the rate's bandwidth. `None` for a profile with no accelerometer.
674///
675/// # Errors
676///
677/// As [`log`].
678pub fn accelerometer_log(
679    draw: &LoggerDraw,
680    rate_hz: f64,
681    truth: &Truth,
682    seed: u64,
683    index: u64,
684) -> Result<Option<FlightLog>, SyntheticError> {
685    let Some(accel) = draw.profile.accelerometer() else {
686        return Ok(None);
687    };
688    let mut log = log(draw, truth, seed, index)?;
689    let times = clock(
690        &Recording {
691            climbing_hz: rate_hz,
692            descending_hz: rate_hz,
693            written: Written::Altitude { step_m: 0.0 },
694        },
695        draw,
696        truth,
697    );
698    let channel = accelerometer_channel(draw, &accel, rate_hz, &times, truth, (seed, index))?;
699    for kept in &mut log.channels {
700        if kept.quantity == Quantity::Acceleration {
701            *kept = channel.clone();
702        }
703    }
704    Ok(Some(log))
705}
706
707/// The log of `truth` its barometer writes at `recording`, and, `with_others`, its
708/// accelerometer and GNSS receiver as the profile has them.
709fn write(
710    draw: &LoggerDraw,
711    recording: Option<&Recording>,
712    with_others: bool,
713    truth: &Truth,
714    seed: u64,
715    index: u64,
716) -> Result<FlightLog, SyntheticError> {
717    check(draw, truth)?;
718    let profile = draw.profile;
719    let mut channels = Vec::new();
720    let mut time_s = Vec::new();
721    let mut altitude_m = Vec::new();
722    if let (Some(_), Some(recording)) = (profile.barometer(), recording) {
723        let written = recording.written;
724        let times = clock(recording, draw, truth);
725        let sim = |t: f64| t - draw.pad_s;
726        let air = truth.air()?;
727        let pad_pa = truth.pressure_pa(0.0)?;
728        let pad_density = air.sample(truth.site_elevation_m)?.air.density_kg_m3;
729        let tau = tau_for(CORRELATED_NOISE_PHI, CORRELATED_NOISE_RATE_HZ);
730        let fast = ornstein_uhlenbeck(
731            &mut stream(seed, index, Key::BaroCorrelated),
732            &times,
733            draw.fast_noise_m * pad_density * G,
734            tau,
735        );
736        let slow = ornstein_uhlenbeck(
737            &mut stream(seed, index, Key::BaroSlow),
738            &times,
739            draw.slow_noise_m * pad_density * G,
740            draw.slow_noise_tau_s,
741        );
742        let white = noise::white(
743            &mut stream(seed, index, Key::BaroWhite),
744            times.len(),
745            draw.white_pa,
746        );
747        let mut pressures = Vec::with_capacity(times.len());
748        for (k, &t_log) in times.iter().enumerate() {
749            let t = sim(t_log);
750            let state = truth_at(truth, t)?;
751            let h = truth.site_elevation_m + state.height_m;
752            let sample = air.sample(h)?;
753            let p = sample.air.pressure_pa;
754            let pulse_m: f64 = truth
755                .events
756                .charges
757                .iter()
758                .map(|(_, at)| noise::pulse_m(t - at, draw.pulse_scale))
759                .sum();
760            let measured = p
761                + draw.offset_pa
762                + draw.gain * (p - pad_pa)
763                + draw.drift_pa_s * t_log
764                + fast[k]
765                + slow[k]
766                + white[k]
767                + noise::port_error_pa(draw.port_calibers, state.mach, state.dynamic_pressure_pa)
768                - sample.air.density_kg_m3 * G * pulse_m;
769            pressures.push(match written {
770                Written::Pressure { step_pa } | Written::PressureAlone { step_pa } => {
771                    quantize(measured, step_pa)
772                }
773                Written::Altitude { .. } => measured,
774            });
775        }
776        let heights = pressures
777            .iter()
778            .map(|&p| height_of(profile, p))
779            .collect::<Result<Vec<_>, _>>()?;
780        // The pad's zero: the mean of the samples before launch.
781        let on_pad: Vec<f64> = times
782            .iter()
783            .zip(&heights)
784            .filter(|(t, _)| sim(**t) < 0.0)
785            .map(|(_, h)| *h)
786            .collect();
787        let zero = on_pad.iter().sum::<f64>() / on_pad.len().max(1) as f64;
788        let alone = matches!(written, Written::PressureAlone { .. });
789        if !alone {
790            altitude_m = heights
791                .iter()
792                .map(|h| match written {
793                    Written::Altitude { step_m } => quantize(h - zero, step_m),
794                    Written::Pressure { .. } | Written::PressureAlone { .. } => h - zero,
795                })
796                .collect();
797        }
798        if let Written::Pressure { .. } | Written::PressureAlone { .. } = written {
799            channels.push(Channel::new(
800                "Pressure (synthetic)",
801                Quantity::Pressure,
802                times.clone(),
803                pressures,
804            ));
805        }
806        if let Some(accel) = profile.accelerometer().filter(|_| with_others) {
807            channels.push(accelerometer_channel(
808                draw,
809                &accel,
810                profile.rate_hz(true),
811                &times,
812                truth,
813                (seed, index),
814            )?);
815        }
816        if !alone {
817            time_s = times;
818        }
819    }
820    if profile.gnss() && with_others {
821        channels.extend(gnss(draw, truth, seed, index)?);
822    }
823    Ok(FlightLog {
824        format: profile.format(),
825        logger: format!("HPR Sim synthetic flight, {} profile", profile.name()),
826        serial_number: None,
827        firmware: None,
828        flight_number: Some(u32::try_from(index).unwrap_or(u32::MAX)),
829        stated: Stated::default(),
830        time_s,
831        altitude_m,
832        vertical_speed_m_s: None,
833        temperature_k: None,
834        battery_v: None,
835        channels,
836        events: Vec::new(),
837        notes: vec![
838            "A synthetic flight (hpr_forensics::synthetic, ADR-280): HPR Sim's flight with noise drawn \
839             as a logger of this family would add it, not a logged flight."
840                .to_owned(),
841        ],
842    })
843}
844
845/// The GNSS receiver's channels: latitude, longitude and altitude, each fix through the loop's
846/// lag and noise, none in the dropouts.
847fn gnss(
848    draw: &LoggerDraw,
849    truth: &Truth,
850    seed: u64,
851    index: u64,
852) -> Result<Vec<Channel>, SyntheticError> {
853    let site = Geodetic::from_degrees(
854        SITE_LATITUDE_DEG,
855        SITE_LONGITUDE_DEG,
856        truth.site_elevation_m,
857    )?;
858    let earth = Earth::wgs84(site)?;
859    let mut rng = stream(seed, index, Key::Gnss);
860    let end = draw.pad_s + truth.events.landing_s + draw.ground_s;
861    let start = truth_at(truth, 0.0)?;
862    let mut lags: Vec<Lag> = (0..3)
863        .map(|axis| {
864            let mut lag = Lag::new(draw.gnss_omega_rad_s, start.position_enu_m[axis]);
865            lag.step(
866                0.0,
867                start.position_enu_m[axis],
868                start.velocity_enu_m_s[axis],
869            );
870            lag
871        })
872        .collect();
873    let (ignition, burnout) = (truth.events.liftoff_s, truth.events.burnout_s);
874    let mut now = 0.0;
875    let mut out = [Vec::new(), Vec::new(), Vec::new(), Vec::new()];
876    let mut k = 0_u64;
877    loop {
878        let t_log = k as f64 / draw.gnss_rate_hz;
879        if t_log > end {
880            break;
881        }
882        k += 1;
883        let t = t_log - draw.pad_s;
884        // The loop runs from launch; before it, the receiver sits on the pad's position.
885        while now < t {
886            let dt = (t - now).min(TRUTH_STEP_S);
887            now += dt;
888            let state = truth_at(truth, now)?;
889            for (axis, lag) in lags.iter_mut().enumerate() {
890                lag.step(dt, state.position_enu_m[axis], state.velocity_enu_m_s[axis]);
891            }
892        }
893        let position: Vec<f64> = lags.iter().map(Lag::output).collect();
894        let noisy = DVec3::new(
895            position[0] + GNSS_NOISE_M * rng.standard_normal(),
896            position[1] + GNSS_NOISE_M * rng.standard_normal(),
897            position[2] + GNSS_NOISE_M * rng.standard_normal(),
898        );
899        let dropped = (ignition..ignition + draw.gnss_dropout_liftoff_s).contains(&t)
900            || (burnout..burnout + draw.gnss_dropout_burnout_s).contains(&t);
901        if dropped {
902            continue;
903        }
904        let fix = earth.frame().geodetic_from_enu(noisy)?;
905        out[0].push(t_log);
906        out[1].push(fix.latitude_rad.to_degrees());
907        out[2].push(fix.longitude_rad.to_degrees());
908        // Mean sea level is the ellipsoid here: the flights' environment sets N = 0.
909        out[3].push(fix.height_m);
910    }
911    let [times, latitude, longitude, altitude] = out;
912    Ok(vec![
913        Channel::new(
914            "Latitude (synthetic)",
915            Quantity::Latitude,
916            times.clone(),
917            latitude,
918        ),
919        Channel::new(
920            "Longitude (synthetic)",
921            Quantity::Longitude,
922            times.clone(),
923            longitude,
924        ),
925        Channel::new(
926            "GNSS altitude (synthetic)",
927            Quantity::GnssAltitude,
928            times,
929            altitude,
930        ),
931    ])
932}
933
934#[cfg(test)]
935mod tests {
936    use super::*;
937    use crate::synthetic::truth::{TruthEvents, TruthSample};
938    use crate::synthetic::{Flyer, Set, draw};
939
940    const SEED: u64 = 9_901;
941
942    /// A truth standing still `seconds` long at 500 m, its axial specific force `f`, Mach number
943    /// `mach` and dynamic pressure `q`, accelerating up at `climb` m/s² from launch: a truth for
944    /// one noise term at a time.
945    fn still(seconds: f64, f: f64, mach: f64, q: f64, climb: f64) -> Truth {
946        let samples = (0..=(seconds / TRUTH_STEP_S) as usize)
947            .map(|k| {
948                let t = k as f64 * TRUTH_STEP_S;
949                let z = 0.5 * climb * t * t;
950                TruthSample {
951                    time_s: t,
952                    height_m: if climb > 0.0 { z } else { 0.0 },
953                    vertical_speed_m_s: climb * t,
954                    axial_specific_force_m_s2: f,
955                    mach,
956                    dynamic_pressure_pa: q,
957                    position_enu_m: [0.0, 0.0, z],
958                    velocity_enu_m_s: [0.0, 0.0, climb * t],
959                }
960            })
961            .collect();
962        Truth {
963            samples,
964            events: TruthEvents {
965                liftoff_s: 0.0,
966                rail_exit_s: 0.0,
967                burnout_s: 10.0 * seconds,
968                apogee_s: seconds,
969                apogee_m: 0.0,
970                charges: Vec::new(),
971                deployments: Vec::new(),
972                landing_s: seconds,
973            },
974            pad_height_m: 0.0,
975            site_elevation_m: 500.0,
976            temperature_offset_k: 0.0,
977        }
978    }
979
980    /// A draw of `profile` with every per-flight term zero and the pad and ground spans short.
981    fn quiet(profile: Profile) -> LoggerDraw {
982        LoggerDraw {
983            profile,
984            pad_s: 2.0,
985            ground_s: 0.0,
986            white_pa: 0.0,
987            offset_pa: 0.0,
988            gain: 0.0,
989            drift_pa_s: 0.0,
990            port_calibers: 1.0,
991            pulse_scale: 0.0,
992            density_g_per_root_hz: 0.0,
993            accel_scale: 0.0,
994            accel_bias_m_s2: 0.0,
995            fast_noise_m: 0.0,
996            slow_noise_m: 0.0,
997            slow_noise_tau_s: 1.0,
998            gnss_rate_hz: 10.0,
999            gnss_omega_rad_s: 0.5,
1000            gnss_dropout_liftoff_s: 0.0,
1001            gnss_dropout_burnout_s: 0.0,
1002        }
1003    }
1004
1005    fn channel(log: &FlightLog, quantity: Quantity) -> &Channel {
1006        log.channels_of(quantity).next().unwrap()
1007    }
1008
1009    /// Each logged pressure less the truth's, Pa, with each sample's time on the log's clock.
1010    fn pressure_residuals(log: &FlightLog, truth: &Truth, pad_s: f64) -> Vec<(f64, f64)> {
1011        let p = channel(log, Quantity::Pressure);
1012        p.time_s
1013            .iter()
1014            .zip(&p.values)
1015            .map(|(&t, &v)| (t, v - truth.pressure_pa(t - pad_s).unwrap()))
1016            .collect()
1017    }
1018
1019    /// The accelerometer's readings up to `end_s` s after launch, the log's clock starting `pad_s`
1020    /// before it: the span the truth covers, before the rocket lies still.
1021    fn acceleration_until(log: &FlightLog, pad_s: f64, end_s: f64) -> Vec<f64> {
1022        let a = channel(log, Quantity::Acceleration);
1023        a.time_s
1024            .iter()
1025            .zip(&a.values)
1026            .filter(|(t, _)| **t - pad_s < end_s)
1027            .map(|(_, v)| *v)
1028            .collect()
1029    }
1030
1031    fn mean(x: &[f64]) -> f64 {
1032        x.iter().sum::<f64>() / x.len() as f64
1033    }
1034
1035    fn sd(x: &[f64]) -> f64 {
1036        let m = mean(x);
1037        (x.iter().map(|v| (v - m) * (v - m)).sum::<f64>() / (x.len() - 1) as f64).sqrt()
1038    }
1039
1040    /// The residuals' least-squares slope against time, and their mean and spread about it.
1041    fn line_fit(residuals: &[(f64, f64)]) -> (f64, f64, f64) {
1042        let t: Vec<f64> = residuals.iter().map(|r| r.0).collect();
1043        let r: Vec<f64> = residuals.iter().map(|r| r.1).collect();
1044        let (tm, rm) = (mean(&t), mean(&r));
1045        let stt: f64 = t.iter().map(|x| (x - tm) * (x - tm)).sum();
1046        let slope = t
1047            .iter()
1048            .zip(&r)
1049            .map(|(x, y)| (x - tm) * (y - rm))
1050            .sum::<f64>()
1051            / stt;
1052        let detrended: Vec<f64> = t.iter().zip(&r).map(|(x, y)| y - slope * x).collect();
1053        (slope, mean(&detrended), sd(&detrended))
1054    }
1055
1056    /// The lag-`k` autocorrelation of `x`.
1057    fn autocorrelation(x: &[f64], k: usize) -> f64 {
1058        let m = mean(x);
1059        let num: f64 = x.iter().zip(&x[k..]).map(|(a, b)| (a - m) * (b - m)).sum();
1060        let den: f64 = x.iter().map(|v| (v - m) * (v - m)).sum();
1061        num / den
1062    }
1063
1064    #[test]
1065    fn a_barometers_offset_drift_and_white_noise_each_hold_alone_and_fail_at_half_and_half_again() {
1066        // 300 s at AltOS's 100 Hz, every other term off: each term is all the residual holds,
1067        // but for the 1 Pa step (0.29 Pa of spread).
1068        let truth = still(300.0, G, 0.0, 0.0, 0.0);
1069        let fit = |draw: &LoggerDraw| {
1070            let log = log(draw, &truth, SEED, 1).unwrap();
1071            line_fit(&pressure_residuals(&log, &truth, draw.pad_s))
1072        };
1073        let quiet = quiet(Profile::Altos);
1074        for factor in [1.0, 0.5, 1.5] {
1075            let (_, offset, _) = fit(&LoggerDraw {
1076                offset_pa: 80.0 * factor,
1077                ..quiet
1078            });
1079            let (drift, _, _) = fit(&LoggerDraw {
1080                drift_pa_s: 0.02 * factor,
1081                ..quiet
1082            });
1083            let (_, _, white) = fit(&LoggerDraw {
1084                white_pa: 13.0 * factor,
1085                ..quiet
1086            });
1087            // 30,000 samples: a mean to 0.5 Pa, a slope to the step's share, a spread to 0.41%.
1088            let held = (offset - 80.0).abs() < 0.5
1089                && (drift - 0.02).abs() < 1e-4
1090                && (white - 13.0).abs() < 5.0 * 0.0041 * 13.0;
1091            assert_eq!(held, factor == 1.0, "{factor}: {offset} {drift} {white}");
1092        }
1093    }
1094
1095    #[test]
1096    fn the_correlated_noise_correlates_as_stated_at_the_loggers_rate() {
1097        let truth = still(300.0, G, 0.0, 0.0, 0.0);
1098        let fast_only = |profile| LoggerDraw {
1099            fast_noise_m: CORRELATED_NOISE_M,
1100            ..quiet(profile)
1101        };
1102        let slow = log(&fast_only(Profile::Altos), &truth, SEED, 2).unwrap();
1103        let r: Vec<f64> = pressure_residuals(&slow, &truth, 2.0)
1104            .iter()
1105            .map(|r| r.1)
1106            .collect();
1107        let m = mean(&r);
1108        let num: f64 = r.windows(2).map(|w| (w[0] - m) * (w[1] - m)).sum();
1109        let den: f64 = r.iter().map(|v| (v - m) * (v - m)).sum();
1110        // 0.5 at 50 Hz is exp(−Δt/τ) = 0.5^(50/100) ≈ 0.707 at AltOS's 100 Hz, less a little for
1111        // the 1 Pa step. White noise of the same spread would correlate by 0.
1112        let expect = 0.5_f64.sqrt();
1113        assert!((num / den - expect).abs() < 0.03, "{}", num / den);
1114        // At 500 Hz the same noise correlates by 0.5^(50/500) ≈ 0.933, less the 2.03 Pa step's
1115        // share; a correlation fixed per sample, rather than by the time between them, would
1116        // read 0.5 at every rate.
1117        let fast = log(&fast_only(Profile::Imu500), &truth, SEED, 2).unwrap();
1118        let r: Vec<f64> = pressure_residuals(&fast, &truth, 2.0)
1119            .iter()
1120            .map(|r| r.1)
1121            .collect();
1122        let m = mean(&r);
1123        let num: f64 = r.windows(2).map(|w| (w[0] - m) * (w[1] - m)).sum();
1124        let den: f64 = r.iter().map(|v| (v - m) * (v - m)).sum();
1125        assert!(
1126            (num / den - 0.5_f64.powf(0.1)).abs() < 0.03,
1127            "{}",
1128            num / den
1129        );
1130    }
1131
1132    #[test]
1133    fn the_fast_and_slow_noise_hold_their_spreads_and_time_constants_and_fail_changed() {
1134        let truth = still(300.0, G, 0.0, 0.0, 0.0);
1135        let density = truth
1136            .air()
1137            .unwrap()
1138            .sample(500.0)
1139            .unwrap()
1140            .air
1141            .density_kg_m3;
1142        let residuals = |draw: &LoggerDraw, truth: &Truth| -> Vec<f64> {
1143            let log = log(draw, truth, SEED, 12).unwrap();
1144            pressure_residuals(&log, truth, draw.pad_s)
1145                .iter()
1146                .map(|r| r.1)
1147                .collect()
1148        };
1149        // The fast term at 100 Hz: 30,000 samples correlated by 0.707 hold its spread to about 1%.
1150        let fast = |m: f64| {
1151            sd(&residuals(
1152                &LoggerDraw {
1153                    fast_noise_m: m,
1154                    ..quiet(Profile::Altos)
1155                },
1156                &truth,
1157            ))
1158        };
1159        let stated = CORRELATED_NOISE_M * density * G;
1160        assert!(
1161            (fast(CORRELATED_NOISE_M) - stated).abs() < 0.05 * stated,
1162            "{}",
1163            fast(CORRELATED_NOISE_M)
1164        );
1165        assert!((fast(0.5 * CORRELATED_NOISE_M) - stated).abs() > 0.3 * stated);
1166        // The slow term over 3,000 s at AltOS's 10 Hz (its rate after apogee, here at launch): its
1167        // correlation one second apart is e^(−1/τ), 0.368 at τ = 1 s, to about 0.03 over some
1168        // 1,500 time constants, and its spread to about 2%.
1169        let mut long = still(3_000.0, G, 0.0, 0.0, 0.0);
1170        long.events.apogee_s = 0.0;
1171        let slow = |m: f64, tau: f64| {
1172            let draw = LoggerDraw {
1173                slow_noise_m: m,
1174                slow_noise_tau_s: tau,
1175                ..quiet(Profile::Altos)
1176            };
1177            let r = residuals(&draw, &long);
1178            (sd(&r), autocorrelation(&r, 10))
1179        };
1180        let stated = 0.27 * density * G;
1181        let (spread, one_second) = slow(0.27, 1.0);
1182        assert!(
1183            (spread - stated).abs() < 0.1 * stated,
1184            "{spread} against {stated}"
1185        );
1186        assert!((one_second - (-1.0_f64).exp()).abs() < 0.1, "{one_second}");
1187        let (halved, _) = slow(0.135, 1.0);
1188        assert!((halved - stated).abs() > 0.3 * stated);
1189        let (_, quicker) = slow(0.27, 0.5);
1190        assert!((quicker - (-1.0_f64).exp()).abs() > 0.15, "{quicker}");
1191    }
1192
1193    #[test]
1194    fn a_gain_error_scales_the_pressures_change_from_the_pad() {
1195        // On a climb the gain shows; on a still truth it doesn't.
1196        let truth = still(20.0, G, 0.0, 0.0, 10.0);
1197        let base = log(&quiet(Profile::Imu500), &truth, SEED, 3).unwrap();
1198        let b = channel(&base, Quantity::Pressure);
1199        let k = b.values.len() - 1;
1200        let pad = truth.pressure_pa(0.0).unwrap();
1201        let change = truth.pressure_pa(b.time_s[k] - 2.0).unwrap() - pad;
1202        assert!(change < -10_000.0, "the climb moves the pressure: {change}");
1203        let step = 2.0e-5 * ATMOSPHERE_PA;
1204        // The last sample's pressure with `gain` drawn, less the one with none, against the
1205        // stated 0.08% of the change: within one of the part's steps.
1206        let holds = |gain: f64| {
1207            let gained = log(
1208                &LoggerDraw {
1209                    gain,
1210                    ..quiet(Profile::Imu500)
1211                },
1212                &truth,
1213                SEED,
1214                3,
1215            )
1216            .unwrap();
1217            let g = channel(&gained, Quantity::Pressure);
1218            (g.values[k] - b.values[k] - 8.0e-4 * change).abs() <= step
1219        };
1220        assert!(holds(8.0e-4));
1221        // About 8 steps of gain over the climb: none, half or half again reads off by 4 or more.
1222        for changed in [0.0, 4.0e-4, 1.2e-3] {
1223            assert!(!holds(changed), "{changed}");
1224        }
1225    }
1226
1227    #[test]
1228    fn the_ports_transonic_error_reads_the_tunnels_coefficient() {
1229        let q = 40_000.0;
1230        let truth = still(60.0, G, 1.0, q, 0.0);
1231        let at = |calibers: f64| {
1232            let draw = LoggerDraw {
1233                port_calibers: calibers,
1234                ..quiet(Profile::Altos)
1235            };
1236            let r: Vec<f64> =
1237                pressure_residuals(&log(&draw, &truth, SEED, 4).unwrap(), &truth, 2.0)
1238                    .iter()
1239                    .map(|r| r.1)
1240                    .collect();
1241            mean(&r)
1242        };
1243        let expect = noise::port_pressure_coefficient(1.0, 1.0) * q;
1244        assert!(
1245            (at(1.0) - expect).abs() < 5.0,
1246            "{} against {expect}",
1247            at(1.0)
1248        );
1249        // Three calibers back the sign flips: a port there reads +1.2 kPa, not −3.2 kPa.
1250        assert!((at(3.0) - expect).abs() > 1_000.0);
1251    }
1252
1253    #[test]
1254    fn a_charge_punches_the_pnut_pulse_scaled_and_none_without_a_charge() {
1255        let mut truth = still(60.0, G, 0.0, 0.0, 0.0);
1256        truth.events.charges = vec![("Drogue".to_owned(), 30.0)];
1257        let density = truth
1258            .air()
1259            .unwrap()
1260            .sample(500.0)
1261            .unwrap()
1262            .air
1263            .density_kg_m3;
1264        let residual_at = |scale: f64, since: f64| {
1265            let draw = LoggerDraw {
1266                pulse_scale: scale,
1267                ..quiet(Profile::Altos)
1268            };
1269            let log = log(&draw, &truth, SEED, 5).unwrap();
1270            let p = channel(&log, Quantity::Pressure);
1271            let k = p
1272                .time_s
1273                .iter()
1274                .position(|&t| (t - 2.0 - 30.0 - since).abs() < 1e-9)
1275                .unwrap();
1276            p.values[k] - truth.pressure_pa(p.time_s[k] - 2.0).unwrap()
1277        };
1278        // 0.15 s after the charge the Pnut's pulse reads +15 m: 1.5 times that is about −270 Pa,
1279        // against noise of a few pascals.
1280        let expect = -density * G * 1.5 * 15.0;
1281        assert!((residual_at(1.5, 0.15) - expect).abs() < 30.0);
1282        assert!(residual_at(0.0, 0.15).abs() < 30.0);
1283    }
1284
1285    #[test]
1286    fn an_accelerometer_holds_its_scale_bias_and_noise_and_clips_at_its_range() {
1287        let f = 10.0 * G;
1288        let truth = still(60.0, f, 0.0, 0.0, 0.0);
1289        let stated = LoggerDraw {
1290            density_g_per_root_hz: 0.005,
1291            accel_scale: 0.08,
1292            accel_bias_m_s2: 0.03 * G,
1293            ..quiet(Profile::Altos)
1294        };
1295        let mean_reading = |draw: &LoggerDraw| {
1296            mean(&acceleration_until(
1297                &log(draw, &truth, SEED, 6).unwrap(),
1298                2.0,
1299                60.0,
1300            ))
1301        };
1302        let expect = 1.08 * f + 0.03 * G;
1303        // 44 mg of noise and a 49 mg step over 6,000 samples: the mean holds to about 1 mg.
1304        assert!((mean_reading(&stated) - expect).abs() < 0.005 * G);
1305        assert!(
1306            (mean_reading(&LoggerDraw {
1307                accel_scale: 0.0,
1308                ..stated
1309            }) - expect)
1310                .abs()
1311                > 0.5 * G
1312        );
1313        assert!(
1314            (mean_reading(&LoggerDraw {
1315                accel_bias_m_s2: 0.0,
1316                ..stated
1317            }) - expect)
1318                .abs()
1319                > 0.02 * G
1320        );
1321        let spread_of = |draw: &LoggerDraw| {
1322            sd(&acceleration_until(
1323                &log(draw, &truth, SEED, 6).unwrap(),
1324                2.0,
1325                60.0,
1326            ))
1327        };
1328        let sigma = 0.005 * (1.57 * 50.0_f64).sqrt() * G;
1329        let spread = spread_of(&stated);
1330        assert!(
1331            (spread - sigma).abs() < 0.1 * sigma,
1332            "{spread} against {sigma}"
1333        );
1334        let doubled = spread_of(&LoggerDraw {
1335            density_g_per_root_hz: 0.01,
1336            ..stated
1337        });
1338        assert!((doubled - sigma).abs() > 0.5 * sigma, "{doubled}");
1339        // Past apogee (here from launch) AltOS logs at 10 Hz, but its part keeps the 50 Hz
1340        // bandwidth of the climb and so its noise; a σ taken from the descent's rate reads √10
1341        // lower (0.31σ measured, the step's scatter included).
1342        let mut descending = still(600.0, f, 0.0, 0.0, 0.0);
1343        descending.events.apogee_s = 0.0;
1344        let descent_log = log(&stated, &descending, SEED, 6).unwrap();
1345        let a = channel(&descent_log, Quantity::Acceleration);
1346        let after: Vec<f64> = a
1347            .time_s
1348            .iter()
1349            .zip(&a.values)
1350            .filter(|(t, _)| **t > 3.0 && **t - 2.0 < 600.0)
1351            .map(|(_, v)| *v)
1352            .collect();
1353        assert!(after.len() > 5_000, "{}", after.len());
1354        let descent = sd(&after);
1355        assert!(
1356            (descent - sigma).abs() < 0.1 * sigma,
1357            "{descent} against {sigma}"
1358        );
1359        // A 40 g load on a ±32 g part reads 32 g on every sample.
1360        let hard = still(10.0, 40.0 * G, 0.0, 0.0, 0.0);
1361        let clipped = log(&quiet(Profile::Imu500), &hard, SEED, 7).unwrap();
1362        let values = acceleration_until(&clipped, 2.0, 10.0);
1363        assert!(!values.is_empty());
1364        assert!(
1365            values
1366                .iter()
1367                .all(|&v| (v - quantize(32.0 * G, 64.0 / 65_536.0 * G)).abs() < 1e-9)
1368        );
1369        // The ±180 g part reads the same 40 g load unclipped.
1370        let high = acceleration_until(
1371            &log(&quiet(Profile::Altos), &hard, SEED, 7).unwrap(),
1372            2.0,
1373            10.0,
1374        );
1375        assert!(!high.is_empty());
1376        assert!(
1377            high.iter()
1378                .all(|&v| (v - quantize(40.0 * G, 0.049 * G)).abs() < 1e-9)
1379        );
1380    }
1381
1382    #[test]
1383    fn gnss_lags_a_constant_climb_by_a_over_omega_squared_and_drops_out_as_drawn() {
1384        let climb = 20.0;
1385        let truth = still(40.0, G, 0.0, 0.0, climb);
1386        let behind = |draw: &LoggerDraw| {
1387            let log = log(draw, &truth, SEED, 8).unwrap();
1388            let h = channel(&log, Quantity::GnssAltitude);
1389            let lags: Vec<f64> = h
1390                .time_s
1391                .iter()
1392                .zip(&h.values)
1393                .filter(|(t, _)| (**t - 2.0) > 25.0 && (**t - 2.0) < 40.0)
1394                .map(|(t, v)| truth.at(t - 2.0).unwrap().height_m + truth.site_elevation_m - v)
1395                .collect();
1396            mean(&lags)
1397        };
1398        let stated = quiet(Profile::GnssTracker);
1399        let expect = climb / (0.5 * 0.5);
1400        // 150 fixes of 3 m noise; the frame's curvature adds under a meter at 16 km.
1401        assert!(
1402            (behind(&stated) - expect).abs() < 3.0,
1403            "{}",
1404            behind(&stated)
1405        );
1406        assert!(
1407            (behind(&LoggerDraw {
1408                gnss_omega_rad_s: 1.0,
1409                ..stated
1410            }) - expect)
1411                .abs()
1412                > 30.0
1413        );
1414        // A dropout of 4 s from liftoff, or from burnout at 20 s, leaves no fix in it; none drawn
1415        // leaves the fixes there.
1416        let mut truth = truth;
1417        truth.events.burnout_s = 20.0;
1418        let fixes_in = |draw: &LoggerDraw, from: f64| {
1419            let log = log(draw, &truth, SEED, 9).unwrap();
1420            let times = &channel(&log, Quantity::Latitude).time_s;
1421            times
1422                .iter()
1423                .filter(|t| (from..from + 4.0).contains(&(**t - 2.0)))
1424                .count()
1425        };
1426        let at_liftoff = LoggerDraw {
1427            gnss_dropout_liftoff_s: 4.0,
1428            ..stated
1429        };
1430        let at_burnout = LoggerDraw {
1431            gnss_dropout_burnout_s: 4.0,
1432            ..stated
1433        };
1434        assert_eq!(fixes_in(&at_liftoff, 0.0), 0);
1435        assert_eq!(fixes_in(&at_liftoff, 20.0), 40);
1436        assert_eq!(fixes_in(&at_burnout, 20.0), 0);
1437        assert_eq!(fixes_in(&at_burnout, 0.0), 40);
1438        assert_eq!(fixes_in(&stated, 0.0), 40);
1439        assert_eq!(fixes_in(&stated, 20.0), 40);
1440    }
1441
1442    #[test]
1443    fn the_log_lines_up_with_the_truth_by_its_drawn_pad_span() {
1444        // A climb at 10 m/s² from launch, its specific force rising 1 m/s² each second, logged
1445        // 7 s before launch with every noise term off: each value is the truth's 7 s earlier on
1446        // the log's clock, to its step. A log lined up by the 2 s every other test uses is off by
1447        // 125 m or more from launch; the pressure's half a step catches a shift of 0.05 s.
1448        let mut truth = still(30.0, 0.0, 0.0, 0.0, 10.0);
1449        for sample in &mut truth.samples {
1450            sample.axial_specific_force_m_s2 = sample.time_s;
1451        }
1452        let pad_s = 7.0;
1453        let draw = LoggerDraw {
1454            pad_s,
1455            gnss_omega_rad_s: 5.0,
1456            ..quiet(Profile::Altos)
1457        };
1458        let log = log(&draw, &truth, SEED, 13).unwrap();
1459        for (t, r) in pressure_residuals(&log, &truth, pad_s) {
1460            assert!(r.abs() <= 0.5 + 1e-9, "{t}: {r}");
1461        }
1462        let a = channel(&log, Quantity::Acceleration);
1463        for (&t, &v) in a.time_s.iter().zip(&a.values) {
1464            let f = (t - pad_s).clamp(0.0, 30.0);
1465            assert!((v - quantize(f, 0.049 * G)).abs() < 1e-9, "{t}: {v}");
1466        }
1467        // The fixes, lagging 0.4 m at 5 rad/s, each within five of its 3 m (9.8 ft) of noise.
1468        let h = channel(&log, Quantity::GnssAltitude);
1469        for (&t, &v) in h.time_s.iter().zip(&h.values) {
1470            let z = truth.at(t - pad_s).unwrap().height_m;
1471            assert!((v - truth.site_elevation_m - z).abs() < 15.0, "{t}: {v}");
1472        }
1473    }
1474
1475    #[test]
1476    fn a_draw_or_truth_no_logger_could_write_is_refused_by_name() {
1477        let truth = still(10.0, G, 0.0, 0.0, 0.0);
1478        let refused = |draw: &LoggerDraw, truth: &Truth| match log(draw, truth, SEED, 1) {
1479            Err(SyntheticError::Invalid { what }) => what,
1480            other => panic!("{other:?}"),
1481        };
1482        let altos = quiet(Profile::Altos);
1483        assert_eq!(
1484            refused(
1485                &LoggerDraw {
1486                    pad_s: -1.0,
1487                    ..altos
1488                },
1489                &truth
1490            ),
1491            "a logger's pad or ground span that isn't a finite length"
1492        );
1493        assert_eq!(
1494            refused(
1495                &LoggerDraw {
1496                    ground_s: f64::NAN,
1497                    ..altos
1498                },
1499                &truth
1500            ),
1501            "a logger's pad or ground span that isn't a finite length"
1502        );
1503        assert_eq!(
1504            refused(
1505                &LoggerDraw {
1506                    gnss_rate_hz: 0.0,
1507                    ..altos
1508                },
1509                &truth
1510            ),
1511            "a GNSS fix rate that isn't a positive number"
1512        );
1513        assert_eq!(
1514            refused(
1515                &LoggerDraw {
1516                    slow_noise_tau_s: 0.0,
1517                    ..altos
1518                },
1519                &truth
1520            ),
1521            "a slow noise time constant that isn't a positive number"
1522        );
1523        assert_eq!(
1524            refused(
1525                &LoggerDraw {
1526                    ground_s: 1.0e6,
1527                    ..altos
1528                },
1529                &truth
1530            ),
1531            "a log longer than a day"
1532        );
1533        let mut empty = truth.clone();
1534        empty.samples.clear();
1535        assert_eq!(
1536            refused(&altos, &empty),
1537            "a truth with no samples or an event at no finite time"
1538        );
1539        let mut late = truth.clone();
1540        late.events.landing_s = f64::INFINITY;
1541        assert_eq!(
1542            refused(&altos, &late),
1543            "a truth with no samples or an event at no finite time"
1544        );
1545        let mut unclocked = truth;
1546        unclocked.samples[3].time_s = f64::NAN;
1547        assert_eq!(
1548            refused(&altos, &unclocked),
1549            "a truth sample at no finite time"
1550        );
1551        // A barometer-only logger has no fix rate to refuse.
1552        assert!(
1553            log(
1554                &LoggerDraw {
1555                    gnss_rate_hz: 0.0,
1556                    ..quiet(Profile::Rrc3)
1557                },
1558                &still(10.0, G, 0.0, 0.0, 0.0),
1559                SEED,
1560                1
1561            )
1562            .is_ok()
1563        );
1564    }
1565
1566    #[test]
1567    fn the_clock_runs_from_the_pad_to_the_ground_at_each_parts_rate() {
1568        // A 40 s flight with apogee at 10 s, logged 3 s before launch and 5 s after landing.
1569        let mut truth = still(40.0, G, 0.0, 0.0, 0.0);
1570        truth.events.apogee_s = 10.0;
1571        let end = 3.0 + 40.0 + 5.0;
1572        // The log's own clock, or its fixes' for a GNSS receiver.
1573        let spans = |draw: &LoggerDraw| {
1574            let log = log(draw, &truth, SEED, 12).unwrap();
1575            if draw.profile == Profile::GnssTracker {
1576                channel(&log, Quantity::Latitude).time_s.clone()
1577            } else {
1578                log.time_s
1579            }
1580        };
1581        let steps = |times: &[f64]| times.windows(2).map(|w| w[1] - w[0]).collect::<Vec<_>>();
1582        let span = |profile| LoggerDraw {
1583            pad_s: 3.0,
1584            ground_s: 5.0,
1585            ..quiet(profile)
1586        };
1587        // PerfectFlite logs at 20 Hz throughout; its first sample is at its own zero and its
1588        // last within one sample of the end.
1589        let times = spans(&span(Profile::PerfectFlite));
1590        assert_eq!(times[0], 0.0);
1591        assert!(steps(&times).iter().all(|d| (d - 0.05).abs() < 1e-9));
1592        let last = times[times.len() - 1];
1593        assert!(last <= end && last > end - 0.05, "{last}");
1594        // AltOS logs at 100 Hz to the first sample past apogee, then at 10 Hz.
1595        let times = spans(&span(Profile::Altos));
1596        let apogee = 3.0 + 10.0;
1597        for (w, d) in times.windows(2).zip(steps(&times)) {
1598            let expect = if w[0] <= apogee { 0.01 } else { 0.1 };
1599            assert!((d - expect).abs() < 1e-9, "{} to {}", w[0], w[1]);
1600        }
1601        let last = times[times.len() - 1];
1602        assert!(last <= end && last > end - 0.1, "{last}");
1603        // A GNSS receiver fixes at its drawn rate, 1, 5 or 10 Hz, over the same span.
1604        for rate in [1.0, 5.0, 10.0] {
1605            let times = spans(&LoggerDraw {
1606                gnss_rate_hz: rate,
1607                ..span(Profile::GnssTracker)
1608            });
1609            assert_eq!(times[0], 0.0);
1610            assert!(steps(&times).iter().all(|d| (d - 1.0 / rate).abs() < 1e-9));
1611            let last = times[times.len() - 1];
1612            assert!(last <= end && last > end - 1.0 / rate, "{rate}: {last}");
1613        }
1614    }
1615
1616    #[test]
1617    fn gnss_fixes_scatter_three_meters_on_each_axis() {
1618        let truth = still(120.0, G, 0.0, 0.0, 0.0);
1619        let log = log(&quiet(Profile::GnssTracker), &truth, SEED, 10).unwrap();
1620        let h = channel(&log, Quantity::GnssAltitude);
1621        let lat = channel(&log, Quantity::Latitude);
1622        let up: Vec<f64> = h
1623            .values
1624            .iter()
1625            .map(|v| v - truth.site_elevation_m)
1626            .collect();
1627        // A degree of latitude is about 110.94 km at 35° N on WGS84, and a degree of longitude
1628        // 91.29 km.
1629        let north: Vec<f64> = lat
1630            .values
1631            .iter()
1632            .map(|v| (v - SITE_LATITUDE_DEG) * 110_940.0)
1633            .collect();
1634        let east: Vec<f64> = channel(&log, Quantity::Longitude)
1635            .values
1636            .iter()
1637            .map(|v| (v - SITE_LONGITUDE_DEG) * 91_290.0)
1638            .collect();
1639        // About 1,200 fixes: the spread's standard error is about 0.06 m.
1640        for axis in [&up, &north, &east] {
1641            assert!((sd(axis) - GNSS_NOISE_M).abs() < 0.3, "{}", sd(axis));
1642            assert!(mean(axis).abs() < 0.5, "{}", mean(axis));
1643        }
1644    }
1645
1646    #[test]
1647    fn a_barometers_height_is_its_formulas_pressure_altitude_from_the_pad() {
1648        // 5,000 ft of the 1976 standard is 843.07 hPa; the NOAA formula the RRC3 uses reads 4,998 ft.
1649        let p = 84_307.0;
1650        assert!((height_of(Profile::Altos, p).unwrap() - 1_524.0).abs() < 0.5);
1651        assert!((height_of(Profile::Rrc3, p).unwrap() - 4_998.0 * FOOT_M).abs() < 0.5);
1652        // On a climb in standard air each barometer reads the truth's height above the pad, to its
1653        // correlated noise (0.5 m), its step and, for the RRC3, its formula's 0.83 m in 2 km.
1654        let truth = still(20.0, G, 0.0, 0.0, 10.0);
1655        for profile in [
1656            Profile::PerfectFlite,
1657            Profile::Rrc3,
1658            Profile::Eggtimer,
1659            Profile::Altos,
1660            Profile::Imu500,
1661        ] {
1662            let log = log(&quiet(profile), &truth, SEED, 11).unwrap();
1663            let worst = log
1664                .time_s
1665                .iter()
1666                .zip(&log.altitude_m)
1667                .map(|(t, h)| (h - truth.at(t - 2.0).unwrap().height_m).abs())
1668                .fold(0.0, f64::max);
1669            assert!(worst < 4.0, "{profile:?}: {worst}");
1670            assert!(log.altitude_m.iter().copied().fold(0.0, f64::max) > 1_900.0);
1671        }
1672    }
1673
1674    #[test]
1675    fn each_logger_writes_its_familys_rate_step_and_channels() {
1676        let mut flyer = Flyer::new(crate::synthetic::designs::DesignFiles::committed());
1677        for profile in Profile::ALL {
1678            let index = (0..)
1679                .find(|&k| draw(Set::Tuning, k).logger.profile == profile)
1680                .unwrap();
1681            let flight = flyer.flight(Set::Tuning, index).unwrap();
1682            let log = &flight.log;
1683            assert_eq!(log.format, profile.format());
1684            let apogee = flight.draw.logger.pad_s + flight.truth.events.apogee_s;
1685            for pair in log.time_s.windows(2) {
1686                let rate = profile.rate_hz(pair[1] <= apogee + 1e-9);
1687                let step = pair[1] - pair[0];
1688                assert!(
1689                    (step - 1.0 / rate).abs() < 1e-9 || profile == Profile::Altos,
1690                    "{profile:?}"
1691                );
1692            }
1693            match profile.barometer().map(|b| b.written) {
1694                Some(Written::Altitude { step_m }) => {
1695                    assert_eq!(step_m, FOOT_M);
1696                    assert!(
1697                        log.altitude_m
1698                            .iter()
1699                            .all(|h| ((h / FOOT_M) - (h / FOOT_M).round()).abs() < 1e-9)
1700                    );
1701                    assert_eq!(log.channels_of(Quantity::Pressure).count(), 0);
1702                }
1703                Some(Written::Pressure { step_pa } | Written::PressureAlone { step_pa }) => {
1704                    let p = channel(log, Quantity::Pressure);
1705                    assert!(
1706                        p.values
1707                            .iter()
1708                            .all(|v| ((v / step_pa) - (v / step_pa).round()).abs() < 1e-6)
1709                    );
1710                    assert_eq!(p.values.len(), log.time_s.len());
1711                }
1712                None => {
1713                    assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
1714                }
1715            }
1716            match profile.accelerometer() {
1717                Some(a) => {
1718                    let values = &channel(log, Quantity::Acceleration).values;
1719                    let step = a.step_g * G;
1720                    assert!(values.iter().all(|v| v.abs() <= a.range_g * G + step));
1721                    assert!(
1722                        values
1723                            .iter()
1724                            .all(|v| ((v / step) - (v / step).round()).abs() < 1e-6)
1725                    );
1726                }
1727                None => assert_eq!(log.channels_of(Quantity::Acceleration).count(), 0),
1728            }
1729            assert_eq!(
1730                log.channels_of(Quantity::GnssAltitude).count(),
1731                usize::from(profile.gnss())
1732            );
1733        }
1734    }
1735
1736    #[test]
1737    fn each_loggers_draw_stays_inside_its_parts_ranges() {
1738        // Each part's stated terms, as the page and its sources give them, so that a changed
1739        // constant fails here and not only the draws it bounds.
1740        let stated_barometer = |profile| match profile {
1741            Profile::PerfectFlite => Some(((0.0, 0.0), 100.0, 0.001)),
1742            Profile::Rrc3 => Some(((2.3, 2.3), 100.0, 0.0025)),
1743            Profile::Altos => Some(((2.4, 13.0), 100.0, 0.0025)),
1744            Profile::Eggtimer | Profile::Imu500 => Some(((0.2, 6.6), 0.0, 0.0008)),
1745            Profile::GnssTracker => None,
1746        };
1747        let stated_accelerometer = |profile| match profile {
1748            Profile::Altos => Some(((0.005, 0.005), 0.049, 180.0, 0.10)),
1749            Profile::Imu500 => Some(((0.000_16, 0.000_4), 64.0 / 65_536.0, 32.0, 0.03)),
1750            _ => None,
1751        };
1752        // Every draw inside [lo, hi], and the least and greatest within 2% of the span of its
1753        // ends.
1754        let spans = |values: Vec<f64>, lo: f64, hi: f64| {
1755            let least = values.iter().copied().fold(f64::INFINITY, f64::min);
1756            let greatest = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1757            let slack = 0.02 * (hi - lo);
1758            least >= lo && greatest <= hi && least <= lo + slack && greatest >= hi - slack
1759        };
1760        let mut rng = SeededRng::for_stream(SEED, &[0]);
1761        for profile in Profile::ALL {
1762            let draws: Vec<LoggerDraw> = (0..2_000)
1763                .map(|_| LoggerDraw::draw(&mut rng, profile))
1764                .collect();
1765            let column = |f: &dyn Fn(&LoggerDraw) -> f64| draws.iter().map(f).collect::<Vec<_>>();
1766            assert_eq!(
1767                profile
1768                    .barometer()
1769                    .map(|b| (b.white_pa, b.offset_pa, b.relative_gain)),
1770                stated_barometer(profile),
1771                "{profile:?}"
1772            );
1773            assert_eq!(
1774                profile.accelerometer().map(|a| (
1775                    a.density_g_per_root_hz,
1776                    a.step_g,
1777                    a.range_g,
1778                    a.scale
1779                )),
1780                stated_accelerometer(profile),
1781                "{profile:?}"
1782            );
1783            assert!(spans(column(&|d| d.slow_noise_tau_s), 0.65, 1.26));
1784            assert!(spans(column(&|d| d.accel_bias_m_s2 / G), -0.05, 0.05));
1785            assert!(spans(column(&|d| d.gnss_omega_rad_s), 0.25, 1.0));
1786            if let Some(((white_lo, white_hi), offset, gain)) = stated_barometer(profile) {
1787                assert!(spans(column(&|d| d.slow_noise_m), 0.24, 0.29));
1788                assert!(column(&|d| d.fast_noise_m).iter().all(|&m| m == 0.5));
1789                assert!(spans(column(&|d| d.gain), -gain, gain), "{profile:?}");
1790                if offset > 0.0 {
1791                    assert!(spans(column(&|d| d.offset_pa), -offset, offset));
1792                }
1793                if white_hi > white_lo {
1794                    assert!(spans(column(&|d| d.white_pa), white_lo, white_hi));
1795                }
1796            }
1797            if let Some(((lo, hi), _, _, scale)) = stated_accelerometer(profile) {
1798                if hi > lo {
1799                    assert!(spans(column(&|d| d.density_g_per_root_hz), lo, hi));
1800                }
1801                assert!(spans(column(&|d| d.accel_scale), -scale, scale));
1802            }
1803            let all = |f: &dyn Fn(&LoggerDraw) -> bool| draws.iter().all(f);
1804            assert!(all(
1805                &|d| (2.0..=10.0).contains(&d.pad_s) && (2.0..=10.0).contains(&d.ground_s)
1806            ));
1807            assert!(all(
1808                &|d| (1.0..=5.0).contains(&d.port_calibers) && (0.0..=2.0).contains(&d.pulse_scale)
1809            ));
1810            assert!(all(
1811                &|d| (1.0 / 300.0..=3.0 / 30.0).contains(&d.drift_pa_s.abs())
1812            ));
1813            assert!(
1814                draws.iter().any(|d| d.drift_pa_s < 0.0)
1815                    && draws.iter().any(|d| d.drift_pa_s > 0.0)
1816            );
1817            assert!(all(&|d| [1.0, 5.0, 10.0].contains(&d.gnss_rate_hz)));
1818            for rate in [1.0, 5.0, 10.0] {
1819                assert!(draws.iter().any(|d| d.gnss_rate_hz == rate));
1820            }
1821            assert!(all(&|d| (0.25..=1.0).contains(&d.gnss_omega_rad_s)));
1822            assert!(all(&|d| (0.0..=10.0).contains(&d.gnss_dropout_liftoff_s)));
1823            assert!(all(&|d| (0.0..=10.0).contains(&d.gnss_dropout_burnout_s)));
1824            assert!(all(&|d| d.accel_bias_m_s2.abs() <= ACCEL_BIAS_G * G));
1825            assert!(all(
1826                &|d| (SLOW_NOISE_TAU_S.0..=SLOW_NOISE_TAU_S.1).contains(&d.slow_noise_tau_s)
1827            ));
1828            match profile.barometer() {
1829                Some(b) => {
1830                    assert!(all(&|d| (b.white_pa.0..=b.white_pa.1).contains(&d.white_pa)));
1831                    assert!(all(&|d| d.offset_pa.abs() <= b.offset_pa));
1832                    assert!(all(&|d| d.gain.abs() <= b.relative_gain));
1833                    assert!(all(&|d| d.fast_noise_m == CORRELATED_NOISE_M));
1834                    assert!(all(
1835                        &|d| (SLOW_NOISE_M.0..=SLOW_NOISE_M.1).contains(&d.slow_noise_m)
1836                    ));
1837                }
1838                None => assert!(all(&|d| d.white_pa == 0.0
1839                    && d.offset_pa == 0.0
1840                    && d.gain == 0.0
1841                    && d.fast_noise_m == 0.0
1842                    && d.slow_noise_m == 0.0)),
1843            }
1844            match profile.accelerometer() {
1845                Some(a) => {
1846                    let (lo, hi) = a.density_g_per_root_hz;
1847                    assert!(all(&|d| (lo..=hi).contains(&d.density_g_per_root_hz)));
1848                    assert!(all(&|d| d.accel_scale.abs() <= a.scale));
1849                }
1850                None => assert!(all(
1851                    &|d| d.density_g_per_root_hz == 0.0 && d.accel_scale == 0.0
1852                )),
1853            }
1854        }
1855    }
1856
1857    #[test]
1858    fn altos_logs_100_hz_to_apogee_and_10_hz_after() {
1859        let mut flyer = Flyer::new(crate::synthetic::designs::DesignFiles::committed());
1860        let index = (0..)
1861            .find(|&k| draw(Set::A, k).logger.profile == Profile::Altos)
1862            .unwrap();
1863        let flight = flyer.flight(Set::A, index).unwrap();
1864        let apogee = flight.draw.logger.pad_s + flight.truth.events.apogee_s;
1865        let steps: Vec<(f64, f64)> = flight
1866            .log
1867            .time_s
1868            .windows(2)
1869            .map(|w| (w[1], w[1] - w[0]))
1870            .collect();
1871        assert!(
1872            steps
1873                .iter()
1874                .filter(|(t, _)| *t <= apogee)
1875                .all(|(_, d)| (d - 0.01).abs() < 1e-9)
1876        );
1877        assert!(
1878            steps
1879                .iter()
1880                .filter(|(t, _)| *t > apogee + 0.1)
1881                .all(|(_, d)| (d - 0.1).abs() < 1e-9)
1882        );
1883    }
1884}