Skip to main content

hpr_flightdata/readings/
accelerometer.rs

1//! The readings of the axial accelerometer: the top acceleration and burnout ([M7.2c][m7-2c],
2//! the rest of the readings), and burnout from the speed's peak where the accelerometer gives
3//! none.
4//!
5//! **The channel.** Only an accelerometer along the rocket's axis is read, as its family names it
6//! ([`family`]): a board's three axes don't say which lies along the axis, and their magnitude
7//! never falls below zero at burnout. A sample that isn't a number is left out, and a clock faster
8//! than [`MIN_INTERVAL_S`], the fastest the bounds were checked at, withholds both readings
9//! ([`Reason::SampledTooFast`]).
10//!
11//! **The thrust, on a cleaned trace.** Where the thrust starts and ends, and burnout, are found on
12//! the trace cleaned by a Hampel filter over [`SPIKE_WINDOW_S`] at [`SPIKE_THRESHOLD`]
13//! ([`hampel`]), which takes out a spike narrower than half its window, a charge's shock or one
14//! bad sample, and keeps a step or a steady run as it was.
15//!
16//! **Which way up, by three witnesses** ([`direction`]), each read on the trace as written, each
17//! from physics that holds whether or not the part takes gravity out, within
18//! [`GRAVITY_TOLERANCE_G`]. The pad: a part at rest reads 1 g nose up and −1 g nose down where it
19//! holds gravity, and 0 either way where it doesn't; it is read as gravity's pad is (below), but
20//! ends where the trace first moves from it either way. The coast's last [`COAST_SPAN_S`] before
21//! apogee's earliest time: a part reads `−D/m` there, or `−D/m − g` without gravity, never above
22//! 0 nose up and never below it nose down, so 1 g less the tolerance or more below 0 says nose up
23//! and as far above it nose down, a drag only pushing it further; it is read only where a coast
24//! was flown, from after liftoff's latest time and before an apogee the log doesn't end at. The
25//! thrust ([`thrust_witness`]): the first span of the cleaned trace, either way up, from liftoff's
26//! earliest time, that holds past [`LIFTOFF_ACCELERATION_M_S2`] for [`BURN_LEAST_S`], found as
27//! the burns are (below), unless a span the other way comes before it, as a short burn before a
28//! heavy drag or a knock's rebound does; where none holds that long, the way every span shares, a
29//! short burn's. As the thrust is what lifts the rocket, the span that says must rise by
30//! liftoff's latest time, or, where liftoff is withheld as a log that starts in the climb has
31//! it, within [`BURN_LEAST_S`] of the log's start; one that rises later is a drag after a weak
32//! thrust, or a second burn. A pad or a coast near 0, or spans both ways or none, say nothing. The way is
33//! settled when the pad or the thrust says and no witness disagrees: a coast's second can hold a
34//! weak thrust still burning or a canopy opened early, either of which reads the other way, so a
35//! coast alone settles nothing, though it can disagree; otherwise, or where the trace so
36//! turned, gravity put back, never passes [`LIFTOFF_ACCELERATION_M_S2`] and so shows no thrust,
37//! both readings are withheld ([`Reason::DirectionUnstated`]).
38//!
39//! **Gravity.** Its 1 g is put back where the logger took it out. Three witnesses, on the trace
40//! turned, say whether it did, each within [`GRAVITY_TOLERANCE_G`]: the family's word; the pad,
41//! where about 1 g holds gravity and about 0 doesn't; and the coast's last [`COAST_SPAN_S`] before
42//! apogee, where a rocket falls freely but for a small drag, so about 0 holds gravity and about
43//! −1 g doesn't. The pad is read off the accelerometer itself, the steady reading before the
44//! thrust lifts it by half [`LIFTOFF_ACCELERATION_M_S2`], if that comes no later than liftoff's
45//! latest time by the heights; the coast is read only where one was flown, after the trace first
46//! moves and before an apogee the log doesn't end at, but not held to liftoff's latest time as
47//! the direction's coast is; a pad or a coast that reads neither, such as a log that starts in
48//! the thrust, says nothing. Gravity is settled when one witness or more says and none
49//! disagrees, except that a coast at about −1 g doesn't settle it alone: a part that holds
50//! gravity reads its drag there, and a rocket still fast at apogee, arcing over, can drag about 1 g
51//! ([#806](https://github.com/nrdptel/fusionspace-eridanus/issues/806)). Its about 0 can
52//! stand alone, as a part without gravity reads −1 g or below in a coast, unless a net push
53//! forward (thrust less drag) of between about 0.75 and 1.25 g still acts in that second.
54//! Otherwise nothing is read ([`Reason::GravityUnstated`]). A sample that repeats the time before
55//! it is left out, as the primary track leaves it ([`first_at_each_time`]).
56//!
57//! **The top acceleration** is the highest reading over the burns: each from a cleaned reading past
58//! [`LIFTOFF_ACCELERATION_M_S2`] to where the cleaned trace's mean over [`BURNOUT_MEAN_S`] next
59//! falls through zero, or apogee if it doesn't, that holds past [`LIFTOFF_ACCELERATION_M_S2`] for
60//! [`BURN_LEAST_S`], as a shock doesn't, or the first such span where none does; searched from
61//! liftoff's earliest time by the heights, as a rocket at rest reads 1 g and anything more before
62//! it moves is a knock on the pad, or from the log's start where liftoff is withheld. In a burn
63//! the reading is the thrust less the drag, over the mass. A charge or a canopy's shock in a coast lies outside the burns, and
64//! isn't taken for the top. The top is read off the samples, not the cleaned trace. It is clipped,
65//! two causes kept apart ([`Clip`]), where it reaches the part's range, as the family states it,
66//! or else holds flat at its top for [`FLAT_TOP_SAMPLES`] samples or [`FLAT_TOP_S`], within
67//! [`FLAT_TOP_SHARE`] of it or [`FLAT_TOP_M_S2`], as Debrief tells a part that clipped
68//! (`lib/analyze/index.ts`, MIT, the project owner's own); HPR Sim narrows that to half the
69//! part's noise where it is quieter, never below half a step ([`flat_top`]). A clipped top is a
70//! floor, and so is one whose last burn never falls through zero before the accelerometer ends
71//! or apogee: the thrust doesn't end on the channel, so the top may lie past its samples, and
72//! burnout isn't read off it. Neither the top nor burnout comes before liftoff's earliest time.
73//!
74//! **Burnout.** In the climb an accelerometer reads `(T − D)/m`: positive while the thrust beats
75//! the drag, below zero once it doesn't, and after burnout `−D/m`, which eases as the coast slows.
76//! So the reading falls through zero as the thrust tails off, and is least at burnout, where the
77//! thrust's fall ends and the drag's easing begins; the fall through zero, Debrief's mark, comes
78//! before it, by as long as the thrust takes to tail off below the drag. The cleaned trace is
79//! averaged over [`BURNOUT_MEAN_S`] in whole samples, an odd count, which cuts the noise by the
80//! square root of the samples averaged and reads the least late by up to half the window. With `N`
81//! five times the averaged trace's noise ([`noise`], from the top acceleration to a second past
82//! the fall through zero) and a step, an averaged sample lies within `N` of its truth but about
83//! once in 1.7 million, so the samples next to burnout read within `2N` of the least. The thrust
84//! falls steeply and the coast's drag eases slowly, so burnout lies near the first such sample:
85//! the reading is the first, less half the window, and its bound the span of those samples, an
86//! interval, as a part's filter spreads a thrust cut off at once over about a sample, and the
87//! window's `2h` intervals, or two intervals if that is more. The search runs from the fall
88//! through zero until the averaged trace climbs `4N` above its least so far, as the coast's easing
89//! drag lifts it. If it never does before apogee, or the least lies within `3N` of zero, too
90//! little drag to see, the accelerometer gives no burnout; nor after more than one burn, an air
91//! start's or a sustainer's, as the tuning set's flights burn once.
92//!
93//! **From the speed's peak.** A rocket gains speed only while the thrust beats the drag and its
94//! weight, and after burnout its speed up falls at least as fast as gravity pulls it, so the top
95//! speed comes at or before burnout, the last burn's end. Burnout from it is a floor: no sooner
96//! than the peak's time, less the time a coast slowing at g takes to lose twice
97//! [`SPEED_NOISE_M_S`], by which the fit's noise can place the peak late, half the fit and an
98//! interval. How far before burnout it falls on the tuning flights is in the synthetic flights'
99//! report, as the floor's errors.
100//!
101//! [m7-2c]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m7-2c
102
103use super::interval;
104use super::{
105    ACCEL_BIAS_M_S2, ACCEL_NOISE_SIGMAS, ACCEL_SCALE_SHARE, Accelerometer, Apogee, BURN_LEAST_S,
106    BURNOUT_MEAN_S, Burnout, COAST_SPAN_S, Clip, FLAT_TOP_M_S2, FLAT_TOP_S, FLAT_TOP_SAMPLES,
107    FLAT_TOP_SHARE, GRAVITY_TOLERANCE_G, Gravity, GravityBy, LIFTOFF_ACCELERATION_M_S2, Liftoff,
108    MIN_INTERVAL_S, MaxAcceleration, Method, NOISE_SPAN_S, PAD_MIN_SAMPLES, Provenance,
109    RAIL_TILT_DEG, Reading, Readings, Reason, SPEED_NOISE_M_S, SPEED_WINDOW_S, SPIKE_THRESHOLD,
110    SPIKE_WINDOW_S, STANDARD_GRAVITY_MPS2, Source, Withheld, clocked, local_interval, median,
111    smallest_step,
112};
113use crate::filter::hampel;
114use crate::log::{Channel, FlightLog, LogFormat, Quantity};
115
116/// The column the synthetic flights' loggers write their axial accelerometer under
117/// (`hpr_forensics::synthetic::logger`), gravity in.
118pub const SYNTHETIC_COLUMN: &str = "Axial acceleration (synthetic)";
119
120/// The column the synthetic flights' IMU-like logger writes its axial accelerometer under, gravity
121/// in, when its part is set to ±8 g (`hpr_forensics::synthetic::logger::LOWER_RANGE_G`).
122pub const SYNTHETIC_LOWER_RANGE_COLUMN: &str = "Axial acceleration, ±8 g (synthetic)";
123
124/// What a family states of its axial accelerometer.
125#[derive(Debug, Clone, Copy, PartialEq)]
126pub(super) struct Axial {
127    /// Whether its readings hold gravity; `None` where the family doesn't say.
128    pub gravity: Option<Gravity>,
129    /// The part's range, g; `None` where the family doesn't state one part.
130    pub range_g: Option<f64>,
131}
132
133/// The axial accelerometer a family writes under `column`, or `None` if the column isn't one.
134/// Each entry is the reader's own account of its family (`docs/format/flight-logs.md`) and the
135/// range its maker states (`docs/research/altimeter-sensor-noise.md`).
136pub(super) fn family(format: LogFormat, column: &str) -> Option<Axial> {
137    use Gravity::{In, Out};
138    use LogFormat as F;
139    let axial = |gravity, range_g| Some(Axial { gravity, range_g });
140    match (format, column) {
141        // The synthetic flights' loggers: the AltOS-like part an ADXL375, clipping at its least
142        // stated range, ±180 g; the IMU like Blue Raven's ±32 g.
143        (F::AltosCsv, SYNTHETIC_COLUMN) => axial(Some(In), Some(180.0)),
144        (F::BlueRavenCsv, SYNTHETIC_COLUMN) => axial(Some(In), Some(32.0)),
145        // The same IMU set to ±8 g, as the BMX160 and the MPU-6000 can be.
146        (F::BlueRavenCsv, SYNTHETIC_LOWER_RANGE_COLUMN) => axial(Some(In), Some(8.0)),
147        // AltOS's `acceleration` is along the flight path, its ground reading taken out; the
148        // part varies by board (MMA2202, ADXL78, MMA6555, ADXL375).
149        (
150            F::AltosCsv | F::AltosEeprom | F::AltosTelemetry | F::AltosTelemetryCsv,
151            "acceleration",
152        ) => axial(Some(Out), None),
153        // Raven and Blue Raven name the axis; neither says whether gravity is in it, and each
154        // has carried more than one part (Raven3 ±70 or ±250 g, Raven4 ±105 g; Blue Raven ±32 g
155        // and a high-range part).
156        (F::RavenFipCsv | F::RavenFipa | F::BlueRavenCsv, "Axial Accel (Gs)") => axial(None, None),
157        // The Eggtimer Proton's one accelerometer, its pad's reading taken out; 120 g or 200 g by
158        // board. The filtered columns (`FAccel…`) are the logger's own smoothing.
159        (F::EggtimerCsv | F::EggtimerText | F::EggtimerRtf, "Accel" | "AccelG" | "AccelFPSS") => {
160            axial(Some(Out), None)
161        }
162        // The AIM XTRA's long axis, gravity in, 100 g (the AIM BASE writes the XTRA's telemetry).
163        (F::EntacoreAimCsv | F::EntacoreXtra | F::EntacoreDump, "acceleration") => {
164            axial(Some(In), Some(100.0))
165        }
166        // Fluctus's vertical acceleration, from a ±200 g part; the file doesn't say whether
167        // gravity is in it.
168        (F::FluctusCsv, "vert-accel (m/s2)") => axial(None, Some(200.0)),
169        // MARSA's, its rest reading taken out; the part isn't named.
170        (F::Marsa, "acceleration") => axial(Some(Out), None),
171        // Altimax's points down the rocket, gravity in: about −1 g at rest, turned over below.
172        (F::AltimaxXls, "ACCEL [m/s2]") | (F::AltimaxAls, "ACCEL") => axial(Some(In), None),
173        // The ARTS2's ADXL78, ±50 g, its pad's reading taken out.
174        (F::Arts2Csv, "Acc") | (F::Arts2Odf, "Acc(HI)") => axial(Some(Out), Some(50.0)),
175        // A column that names the axis, as a table's or a mapping's may: nothing else is known.
176        _ if column.to_ascii_lowercase().contains("axial") => axial(None, None),
177        _ => None,
178    }
179}
180
181/// The channel with each sample that has no time left out, and each that repeats the time of the
182/// last kept, the first at each time kept: AltOS writes rows that share a time with the row
183/// before, and its primary track keeps the first, as Debrief does (`lib/flight/build.ts`). A
184/// clock that runs back is left for [`clocked`] to refuse.
185fn first_at_each_time(channel: &Channel) -> Channel {
186    let mut kept = channel.clone();
187    kept.time_s.clear();
188    kept.values.clear();
189    for (&t, &value) in channel.time_s.iter().zip(&channel.values) {
190        if t.is_finite() && kept.time_s.last() != Some(&t) {
191            kept.time_s.push(t);
192            kept.values.push(value);
193        }
194    }
195    kept
196}
197
198/// Whether `channel` is AltOS's `acceleration` from a board with no accelerometer of its own.
199/// AltosUI's CSV writes the column for every board. An EasyMini or a TeleMini has a barometer
200/// and no accelerometer (*The Altus Metrum System*'s specifications; the `.eeprom` reader's
201/// `Board::EasyMini`), so on one the column is the board's estimate from its barometer, not a
202/// sensor's reading. Each AltOS board with an axial accelerometer carries an inertial unit
203/// (TeleMega, EasyMega) or a GPS receiver (TeleMetrum), whose columns the export adds, so a file
204/// with neither holds no accelerometer's reading. A TeleGPS, a GPS receiver with no
205/// accelerometer, would pass if its export wrote the column.
206fn from_the_barometer(log: &FlightLog, channel: &Channel) -> bool {
207    log.format == LogFormat::AltosCsv
208        && channel.column == "acceleration"
209        && !log
210            .channels
211            .iter()
212            .any(|other| matches!(other.column.as_str(), "accel_x" | "latitude"))
213}
214
215/// The robust noise of `values`, 1σ: the median of each sample's distance from the mean of its
216/// two neighbors, over the 0.6745 a normal distribution's median absolute deviation is of its σ
217/// and the √1.5 the neighbors' mean adds. A curve's bend between three samples is left out with
218/// the outliers; 0 with fewer than three samples.
219pub(super) fn noise(values: &[f64]) -> f64 {
220    let mut distances: Vec<f64> = values
221        .windows(3)
222        .map(|w| (w[1] - 0.5 * (w[0] + w[2])).abs())
223        .filter(|d| d.is_finite())
224        .collect();
225    median(&mut distances).map_or(0.0, |m| m / (0.674_489_750_196_081_7 * 1.5_f64.sqrt()))
226}
227
228/// The accelerometer's readings: the channel they came from, the top acceleration and burnout.
229pub(super) fn read(
230    log: &FlightLog,
231    heights: &Readings,
232) -> (
233    Option<Accelerometer>,
234    Reading<MaxAcceleration>,
235    Reading<Burnout>,
236) {
237    let fallback = |detail: Option<String>| from_speed(heights, detail);
238    let withheld = |reason, detail: String| {
239        (
240            None,
241            Reading::withheld(reason, detail.clone()),
242            fallback(Some(detail)),
243        )
244    };
245    let accelerometers: Vec<_> = log
246        .channels_of(Quantity::Acceleration)
247        .filter(|channel| !from_the_barometer(log, channel))
248        .collect();
249    if accelerometers.is_empty() {
250        let detail = if log
251            .channels_of(Quantity::Acceleration)
252            .any(|channel| from_the_barometer(log, channel))
253        {
254            "the log has no accelerometer. The file holds neither an inertial unit's columns \
255             (`accel_x` and on) nor a GPS receiver's. Every AltOS board with an axial \
256             accelerometer adds one of the two. So the file's `acceleration` is taken for a board with \
257             none of its own, an EasyMini's or a TeleMini's. That column is the board's \
258             estimate from its barometer, and HPR Sim doesn't read a top from it"
259        } else {
260            "the log has no accelerometer; HPR Sim doesn't difference a height twice to make \
261             one, as its steps would read as spikes of many g"
262        };
263        return (
264            None,
265            Reading::withheld(Reason::NoAccelerometer, detail),
266            fallback(None),
267        );
268    }
269    let Some((channel, stated)) = accelerometers
270        .iter()
271        .find_map(|channel| family(log.format, &channel.column).map(|axial| (*channel, axial)))
272    else {
273        let columns: Vec<String> = accelerometers
274            .iter()
275            .map(|channel| format!("`{}`", channel.column))
276            .collect();
277        return withheld(
278            Reason::AxisUnstated,
279            format!(
280                "the log's accelerometers ({}) don't say which lies along the rocket's axis",
281                columns.join(", ")
282            ),
283        );
284    };
285    let (time, raw) = match clocked(&first_at_each_time(channel)) {
286        Ok(clocked) => clocked,
287        Err((reason, detail)) => return withheld(reason, detail),
288    };
289    // A sample that isn't a number is no reading: it is left out, the samples beside it kept.
290    let (time, raw): (Vec<f64>, Vec<f64>) = time
291        .iter()
292        .zip(&raw)
293        .filter(|(_, value)| value.is_finite())
294        .map(|(t, value)| (*t, *value))
295        .unzip();
296    let apogee_s = match &heights.apogee {
297        Reading::Read(apogee) => apogee.time_s,
298        Reading::Withheld(Withheld { reason, detail }) => {
299            return withheld(
300                *reason,
301                format!(
302                    "the top acceleration is searched up to apogee, which is withheld: {detail}"
303                ),
304            );
305        }
306    };
307    let boost: Vec<usize> = (0..time.len()).filter(|&k| time[k] <= apogee_s).collect();
308    if boost.len() < 3 {
309        return withheld(
310            Reason::TooShort,
311            format!(
312                "the accelerometer has {} samples before apogee, too few to take a reading from",
313                boost.len()
314            ),
315        );
316    }
317    // The climb's interval: a logger may sample its pad or its descent at another rate.
318    let mut steps: Vec<f64> = boost
319        .windows(2)
320        .map(|pair| time[pair[1]] - time[pair[0]])
321        .collect();
322    let interval = median(&mut steps).unwrap_or(0.0);
323    if interval < MIN_INTERVAL_S * (1.0 - 1e-3) {
324        return withheld(
325            Reason::SampledTooFast,
326            format!(
327                "the accelerometer's samples come every {interval:.3e} s, faster than the \
328                 {MIN_INTERVAL_S} s its readings were checked at"
329            ),
330        );
331    }
332    // The trace with its spikes taken out, to find the thrust's start and end and burnout on: a
333    // charge's shock or one bad sample would otherwise turn the trace over or end the thrust.
334    let clean = hampel(&raw, half_window(SPIKE_WINDOW_S, interval), SPIKE_THRESHOLD);
335    // The thrust is searched from liftoff's earliest time by the heights, or the log's start
336    // where liftoff is withheld: a rocket at rest reads 1 g, so anything more before it moves is
337    // the pad's, a knock or a bump.
338    let end = boost.last().copied().unwrap_or(0);
339    let earliest_s = heights
340        .liftoff
341        .value()
342        .map(|liftoff| liftoff.time_s - liftoff.bound_s);
343    let from = earliest_s.map_or(0, |earliest_s| {
344        time[..=end].partition_point(|t| *t < earliest_s).min(end)
345    });
346    let half_mean = half_window(BURNOUT_MEAN_S, interval);
347    // Which way up the part reads, by three witnesses on the trace as written, before it is
348    // turned: the pad, the coast to apogee and the thrust ([`direction`]). The pad ends where
349    // the trace first moves from it either way. The coast is read only where one was flown:
350    // after liftoff's latest time by the heights and after the trace first moves from its pad,
351    // as a coast follows the thrust, and before an apogee the log doesn't end at, as a log that
352    // ends in the climb shows no coast; otherwise the second before apogee's earliest time may
353    // be the pad's or the thrust's.
354    let either_way = |moved: f64| moved.abs() > 0.5 * LIFTOFF_ACCELERATION_M_S2;
355    let moved = first_move(&raw, &clean, either_way);
356    // Where liftoff is withheld, as a log that starts in the climb has it, the log's start
357    // stands for liftoff's latest time.
358    let flown = match &heights.apogee {
359        Reading::Read(apogee) => {
360            let start_s = apogee.time_s - apogee.time_bound_s - COAST_SPAN_S;
361            let lifted_s = heights
362                .liftoff
363                .value()
364                .map_or(time[0], |liftoff| liftoff.time_s + liftoff.bound_s);
365            !apogee.is_floor
366                && start_s >= lifted_s
367                && moved.is_some_and(|moved| time[moved] <= start_s)
368        }
369        _ => false,
370    };
371    // Gravity's coast isn't held to liftoff's latest time, as the direction's is: coarse heights
372    // put that time late, past a coast that was flown, and the family's word then settled alone
373    // where the coast would have disagreed (#806). What it guards against here is the pad, where
374    // the trace hasn't moved.
375    let coasted = match &heights.apogee {
376        Reading::Read(apogee) => {
377            let start_s = apogee.time_s - apogee.time_bound_s - COAST_SPAN_S;
378            !apogee.is_floor && moved.is_some_and(|moved| time[moved] <= start_s)
379        }
380        _ => false,
381    };
382    let (way, said_by) = match direction(
383        pad_level(&time, &raw, &clean, &heights.liftoff, either_way),
384        coast_level(&time, &raw, &boost, &heights.apogee).filter(|_| flown),
385        &thrust_witness(
386            &time,
387            &clean,
388            from,
389            end,
390            half_mean,
391            interval,
392            heights.liftoff.value().map_or(
393                (
394                    time[0] + BURN_LEAST_S,
395                    "the log's start by 0.5 s, liftoff withheld",
396                    false,
397                ),
398                |liftoff| {
399                    (
400                        liftoff.time_s + liftoff.bound_s,
401                        "liftoff's latest time",
402                        true,
403                    )
404                },
405            ),
406        ),
407    ) {
408        Ok(settled) => settled,
409        Err(detail) => {
410            return withheld(
411                Reason::DirectionUnstated,
412                format!("the accelerometer `{}`: {detail}", channel.column),
413            );
414        }
415    };
416    let sign = way.sign();
417    let turned: Vec<f64> = raw.iter().map(|v| sign * v).collect();
418    let turned_clean: Vec<f64> = clean.iter().map(|v| sign * v).collect();
419    let g = STANDARD_GRAVITY_MPS2;
420    let tolerance = GRAVITY_TOLERANCE_G * g;
421    // The pad, on the accelerometer's own trace turned: a rocket at rest reads a steady level,
422    // which the thrust lifts by [`LIFTOFF_ACCELERATION_M_S2`] or more once the rocket moves. So
423    // the pad is the samples from the start until the first that reads half that above the
424    // start's level, if that comes no later than liftoff's latest time by the heights.
425    let pad = pad_level(&time, &turned, &turned_clean, &heights.liftoff, |moved| {
426        moved > 0.5 * LIFTOFF_ACCELERATION_M_S2
427    });
428    // A pad within the tolerance of 1 g holds gravity, of 0 doesn't; one that reads neither,
429    // such as a log that starts in the thrust, says nothing.
430    let by_pad = pad.and_then(|pad| {
431        if (pad - g).abs() <= tolerance {
432            Some(Gravity::In)
433        } else if pad.abs() <= tolerance {
434            Some(Gravity::Out)
435        } else {
436            None
437        }
438    });
439    // The coast's last [`COAST_SPAN_S`] before apogee's earliest time, read only after the trace
440    // first moves and before an apogee the log doesn't end at (#806): about 0 holds gravity,
441    // about −1 g doesn't; still under thrust, or anything else, it says nothing.
442    let coast = coast_level(&time, &turned, &boost, &heights.apogee).filter(|_| coasted);
443    let by_coast = coast.and_then(|coast| {
444        if coast.abs() <= tolerance {
445            Some(Gravity::In)
446        } else if (coast + g).abs() <= tolerance {
447            Some(Gravity::Out)
448        } else {
449            None
450        }
451    });
452    let witnesses = [
453        (stated.gravity, GravityBy::Family),
454        (by_pad, GravityBy::Pad),
455        (by_coast, GravityBy::Coast),
456    ];
457    let said: Vec<(Gravity, GravityBy)> = witnesses
458        .iter()
459        .filter_map(|(word, by)| word.map(|word| (word, *by)))
460        .collect();
461    // A coast at about −1 g says gravity is out only beside another witness (#806). A part that
462    // holds gravity reads its drag there, `−D/m`, and a rocket still fast at apogee, arcing over,
463    // can drag about 1 g. Its about 0 stands alone, as before: without gravity a coasting part
464    // reads `−D/m − g`, drag only pushing it further below −1 g, so reading within the tolerance
465    // of 0 takes a net forward push (thrust less drag) of between about 0.75 and 1.25 g. A thrust
466    // still burning in that second gives one, a risk left open and untested (#1131): on a part
467    // that takes gravity out, with no family word and no pad, it reads gravity in and the top
468    // 1 g low.
469    let lone_coast_out = matches!(said.as_slice(), [(Gravity::Out, GravityBy::Coast)]);
470    let gravity = match said.first() {
471        Some(&first) if !lone_coast_out && said.iter().all(|(word, _)| *word == first.0) => first,
472        _ => {
473            let family = match stated.gravity {
474                Some(Gravity::In) => "says its readings hold gravity",
475                Some(Gravity::Out) => "says gravity is taken out of its readings",
476                None => "doesn't say whether its readings hold gravity",
477            };
478            let level = |name: &str, level: Option<f64>, held: &str, out: &str| {
479                level.map_or_else(
480                    || format!("no {name} is read to tell by"),
481                    |level| {
482                        format!(
483                            "its {name} reads {:.2} g ({held} holds gravity, {out} doesn't)",
484                            level / g
485                        )
486                    },
487                )
488            };
489            let verdict = if lone_coast_out {
490                "only the coast says, and a coast at −1 g says gravity is out only beside \
491                 another witness: a part that holds gravity reads its drag there, and a rocket \
492                 still fast at apogee, arcing over, can drag about 1 g"
493            } else {
494                "they don't settle it, or disagree"
495            };
496            return withheld(
497                Reason::GravityUnstated,
498                format!(
499                    "the accelerometer `{}`'s family {family}; {}; {}: within \
500                     {GRAVITY_TOLERANCE_G} g, {verdict}",
501                    channel.column,
502                    level("pad", pad, "1 g", "0"),
503                    level("coast to apogee", coast, "0", "−1 g"),
504                ),
505            );
506        }
507    };
508    let gravity_m_s2 = match gravity.0 {
509        Gravity::In => 0.0,
510        Gravity::Out => g,
511    };
512    let f: Vec<f64> = turned.iter().map(|v| v + gravity_m_s2).collect();
513    let f_clean: Vec<f64> = turned_clean.iter().map(|v| v + gravity_m_s2).collect();
514    let step = smallest_step(&raw);
515    let accelerometer = Accelerometer {
516        column: channel.column.clone(),
517        gravity: gravity.0,
518        gravity_by: gravity.1,
519        turned_over: sign < 0.0,
520        sample_interval_s: interval,
521        step_m_s2: step,
522    };
523    // The burns: each a span of the cleaned trace past [`LIFTOFF_ACCELERATION_M_S2`] ([`spans`])
524    // that holds past there for [`BURN_LEAST_S`], as a canopy's or a charge's shock doesn't, or
525    // the first such span where none does, searched from liftoff's earliest time. The top is
526    // searched over the burns, so a shock in a coast isn't taken for it, nor a bump on the pad.
527    let mean = running_mean(&f_clean, half_mean);
528    let spans = spans(&f_clean, &mean, from, end, interval);
529    // A trace so turned, gravity put back, that never passes [`LIFTOFF_ACCELERATION_M_S2`]
530    // shows no thrust, as a rocket leaving the pad does, and no top to read: which way up the
531    // witnesses settled is then borne out by nothing.
532    if spans.is_empty() {
533        let by: Vec<&str> = said_by.iter().map(|by| by.words()).collect();
534        return withheld(
535            Reason::DirectionUnstated,
536            format!(
537                "the accelerometer `{}`, read {} as its {} say{} and with gravity put back. It \
538                 never reads past {:.0} g from liftoff's earliest time to apogee, as a rocket \
539                 leaving the pad does. The earliest time is the log's start where liftoff is \
540                 withheld. The accelerometer shows no thrust to read the top or burnout from",
541                channel.column,
542                way.words(),
543                match by.split_last() {
544                    Some((last, rest)) if !rest.is_empty() => {
545                        format!("{} and {last}", rest.join(", "))
546                    }
547                    _ => by.join(""),
548                },
549                if by.len() == 1 { "s" } else { "" },
550                LIFTOFF_ACCELERATION_M_S2 / g
551            ),
552        );
553    }
554    let mut burns: Vec<Span> = spans
555        .iter()
556        .copied()
557        .filter(|span| span.held_s >= BURN_LEAST_S)
558        .collect();
559    // A motor that holds past there for less, a short burn's, is the first such span.
560    if burns.is_empty() {
561        burns.extend(spans.first());
562    }
563    // Whether the thrust ends on the channel: the last burn's mean falls through zero before
564    // apogee. Where it doesn't, the accelerometer ends in the thrust, or the thrust runs on to
565    // apogee, so the top may lie past the samples.
566    let ended = burns.last().is_some_and(|burn| burn.falls);
567    // Whether the thrust begins on the channel: the sample before the first burn's rise reads
568    // under 2 g. Where it doesn't, the log starts in the thrust, or the search for it does, so
569    // the top may have come before the samples searched, as an ignition spike before a log that
570    // starts in the climb would.
571    let began = burns
572        .first()
573        .is_none_or(|burn| burn.rise > 0 && f_clean[burn.rise - 1] < LIFTOFF_ACCELERATION_M_S2);
574    let thrust: Vec<usize> = burns
575        .iter()
576        .flat_map(|burn| burn.rise..=burn.fall)
577        .collect();
578    let top_index = thrust
579        .iter()
580        .copied()
581        .max_by(|a, b| f[*a].total_cmp(&f[*b]).then(b.cmp(a)))
582        .unwrap_or(from);
583    let top = f[top_index];
584    let around: Vec<f64> = boost
585        .iter()
586        .copied()
587        .filter(|&k| (time[k] - time[top_index]).abs() <= NOISE_SPAN_S)
588        .map(|k| f[k])
589        .collect();
590    let jump = [top_index.wrapping_sub(1), top_index + 1]
591        .iter()
592        .filter_map(|&k| f.get(k))
593        .filter(|v| v.is_finite())
594        .map(|v| (top - v).abs())
595        .fold(0.0, f64::max);
596    let zeroed_m_s2 = match gravity.0 {
597        Gravity::In => 0.0,
598        Gravity::Out => g * (1.0 - RAIL_TILT_DEG.to_radians().cos()),
599    };
600    let noise_m_s2 = noise(&around);
601    // How far the pad strays from the level it witnessed: a tilt or the part's own offset.
602    let strayed_m_s2 = match (by_pad, pad) {
603        (Some(Gravity::In), Some(pad)) => (pad - g).abs(),
604        (Some(Gravity::Out), Some(pad)) => pad.abs(),
605        _ => 0.0,
606    };
607    let bound_m_s2 = ACCEL_SCALE_SHARE * top.abs()
608        + ACCEL_BIAS_M_S2
609        + strayed_m_s2
610        + zeroed_m_s2
611        + ACCEL_NOISE_SIGMAS * noise_m_s2
612        + step
613        + jump;
614    let range_m_s2 = stated.range_g.map(|range| range * g);
615    // Clipped at the stated range, or held flat at the top short of it or with no range stated:
616    // two causes, kept apart, as the first says the part read no more and the second only that
617    // it may have clipped.
618    let clip = if range_m_s2.is_some_and(|range| top >= range - 2.0 * step - tolerance) {
619        Some(Clip::Range)
620    } else if flat_top(&f, &thrust, top, interval, noise_m_s2, step) {
621        Some(Clip::Flat)
622    } else {
623        None
624    };
625    let is_floor = clip.is_some() || !ended || !began;
626    let max_acceleration = Reading::Read(MaxAcceleration {
627        acceleration_m_s2: top,
628        bound_m_s2,
629        interval_m_s2: (!is_floor)
630            .then(|| interval::TOP_ACCELERATION_SHARES.interval(top, bound_m_s2))
631            .flatten(),
632        // Only a clipped top: one whose burn the log ends in is a floor by another cause, its
633        // errors a whole top's, and no set tests its lower end (#1071).
634        lower_end_m_s2: clip
635            .is_some()
636            .then(|| interval::TOP_ACCELERATION_FLOOR_SHARES.lower_end(top, bound_m_s2))
637            .flatten(),
638        time_s: time[top_index],
639        range_m_s2,
640        is_floor,
641        clip,
642        source: Source::Accelerometer,
643        provenance: if clip.is_some() {
644            Provenance::Clipped
645        } else {
646            Provenance::Measured
647        },
648        method: Method::HighestReading,
649    });
650    // Burnout is the thrust's end. After more than one burn the tuning set, whose flights burn
651    // once, holds no bound for it; burnout from the speed's peak, which comes no later than the
652    // last burn's end, stands instead. Nor is it read where the thrust doesn't end on the
653    // channel, or where it would come before liftoff's earliest time.
654    let read = match burns.as_slice() {
655        [_, .., last] => Err(format!(
656            "the accelerometer shows {} burns, the last rising past {:.0} g at {:.2} s: burnout \
657             is read from a flight that burns once",
658            burns.len(),
659            LIFTOFF_ACCELERATION_M_S2 / g,
660            time[last.rise]
661        )),
662        _ if !ended => Err(format!(
663            "the accelerometer's thrust, past {:.0} g from {:.2} s, never falls through zero \
664             before {}. The thrust doesn't end on the channel, so it shows no burnout",
665            LIFTOFF_ACCELERATION_M_S2 / g,
666            burns.first().map_or(time[from], |burn| time[burn.rise]),
667            if end + 1 == time.len() {
668                "the accelerometer's last sample"
669            } else {
670                "apogee"
671            }
672        )),
673        _ => burnout(&time, &f, &mean, end, top_index, step, interval).and_then(
674            |(time_s, bound_s)| match earliest_s {
675                Some(earliest_s) if time_s < earliest_s => Err(format!(
676                    "the accelerometer's burnout, {time_s:.2} s, would come before liftoff's \
677                     earliest time by the heights, {earliest_s:.2} s"
678                )),
679                _ => Ok((time_s, bound_s)),
680            },
681        ),
682    };
683    let burnout = match read {
684        Ok((time_s, bound_s)) => Reading::Read(Burnout {
685            time_s,
686            bound_s,
687            interval_s: interval::BURNOUT_SHARES.interval(time_s, bound_s),
688            lower_end_s: None,
689            time_after_liftoff_s: heights.liftoff.value().map(|l| time_s - l.time_s),
690            is_floor: false,
691            source: Source::Accelerometer,
692            provenance: Provenance::Measured,
693            method: Method::LeastAfterThrust,
694        }),
695        Err(detail) => fallback(Some(detail)),
696    };
697    (Some(accelerometer), max_acceleration, burnout)
698}
699
700/// Whether the top holds flat over [`FLAT_TOP_SAMPLES`] samples, or [`FLAT_TOP_S`] if that is
701/// more: Debrief's sign of a part held at its range. Flat is within [`FLAT_TOP_SHARE`] of the top
702/// or [`FLAT_TOP_M_S2`] if that is more, as Debrief has it, or within half the part's noise
703/// `noise_m_s2` where that is less, and never less than half a step `step_m_s2`: a part at its
704/// range writes one value, while a thrust's plateau or crest read by a quiet part still scatters
705/// by its noise. On the tuning flights' quietest part, Debrief's tolerance alone is several times
706/// the noise at the top, and called thrust plateaus clipped that weren't. A part quieter than half
707/// its step writes a plateau as one value too, so on it a plateau as long as the run reads as
708/// clipped: the reading is then a floor, which can't flatter the top.
709fn flat_top(
710    f: &[f64],
711    boost: &[usize],
712    top: f64,
713    interval: f64,
714    noise_m_s2: f64,
715    step_m_s2: f64,
716) -> bool {
717    let near = (FLAT_TOP_SHARE * top.abs())
718        .max(FLAT_TOP_M_S2)
719        .min(0.5 * noise_m_s2)
720        .max(0.5 * step_m_s2);
721    #[expect(
722        clippy::cast_possible_truncation,
723        clippy::cast_sign_loss,
724        reason = "a positive count of samples, rounded"
725    )]
726    let least = if interval > 0.0 {
727        ((FLAT_TOP_S / interval).round() as usize).max(FLAT_TOP_SAMPLES)
728    } else {
729        FLAT_TOP_SAMPLES
730    };
731    let mut run = 0;
732    let mut longest = 0;
733    let mut last = None;
734    for &k in boost {
735        // A run is of neighboring samples.
736        let next = last.is_some_and(|previous| k == previous + 1);
737        run = if f[k] >= top - near {
738            if next { run + 1 } else { 1 }
739        } else {
740            0
741        };
742        longest = longest.max(run);
743        last = Some(k);
744    }
745    longest >= least
746}
747
748/// How far above a tie a count of intervals is lifted before it is rounded: a median interval
749/// read off a clock's float times can fall a few parts in 10¹⁶ short, as 0.05 s does at 20 Hz,
750/// and would round 0.5 to 0, not 1.
751const TIE_SHARE: f64 = 1e-9;
752
753/// The samples either side of a window `span_s` long holds, at `interval`: half the span in
754/// intervals, rounded, a tie up, at an interval no shorter than [`MIN_INTERVAL_S`].
755fn half_window(span_s: f64, interval: f64) -> usize {
756    #[expect(
757        clippy::cast_possible_truncation,
758        clippy::cast_sign_loss,
759        reason = "a positive count of samples, rounded: at MIN_INTERVAL_S a span of a second holds \
760                  250 either side"
761    )]
762    let half = (0.5 * span_s / interval.max(MIN_INTERVAL_S) * (1.0 + TIE_SHARE)).round() as usize;
763    half
764}
765
766/// The mean of `values` over `half` samples either side of each, the window cut short at the ends.
767fn running_mean(values: &[f64], half: usize) -> Vec<f64> {
768    let last = values.len().saturating_sub(1);
769    (0..values.len())
770        .map(|k| {
771            let window = &values[k.saturating_sub(half)..=k.saturating_add(half).min(last)];
772            #[expect(
773                clippy::cast_precision_loss,
774                reason = "a window of a few samples converts exactly"
775            )]
776            let count = window.len() as f64;
777            window.iter().sum::<f64>() / count
778        })
779        .collect()
780}
781
782/// A span of a trace past [`LIFTOFF_ACCELERATION_M_S2`]: from the sample `rise` past it to the
783/// sample `fall` where the trace's running mean next falls through zero, or the search's end if
784/// it doesn't.
785#[derive(Debug, Clone, Copy, PartialEq)]
786struct Span {
787    /// The first sample past [`LIFTOFF_ACCELERATION_M_S2`].
788    rise: usize,
789    /// Where the mean next falls through zero, or the search's end.
790    fall: usize,
791    /// Whether the mean falls through zero before the search's end.
792    falls: bool,
793    /// How long the trace holds past [`LIFTOFF_ACCELERATION_M_S2`] over the span, s: its samples
794    /// there, an interval each.
795    held_s: f64,
796}
797
798/// The spans of `values` past [`LIFTOFF_ACCELERATION_M_S2`] from sample `from` to `end`, each
799/// ending where `mean`, the trace's running mean, next falls through zero, the next searched
800/// from after it; at `interval`.
801fn spans(values: &[f64], mean: &[f64], from: usize, end: usize, interval: f64) -> Vec<Span> {
802    let mut spans = Vec::new();
803    let mut next = from;
804    while let Some(rise) = (next..=end).find(|&k| values[k] >= LIFTOFF_ACCELERATION_M_S2) {
805        let fall = (rise + 1..=end).find(|&k| mean[k] <= 0.0);
806        let to = fall.unwrap_or(end);
807        #[expect(
808            clippy::cast_precision_loss,
809            reason = "a count of samples converts exactly"
810        )]
811        let held_s = (rise..=to)
812            .filter(|&k| values[k] >= LIFTOFF_ACCELERATION_M_S2)
813            .count() as f64
814            * interval;
815        spans.push(Span {
816            rise,
817            fall: to,
818            falls: fall.is_some(),
819            held_s,
820        });
821        match fall {
822            Some(fall) => next = fall + 1,
823            None => break,
824        }
825    }
826    spans
827}
828
829/// Which way up an accelerometer reads: nose up, as the rocket's axis points in the climb, or
830/// nose down, as a part mounted the other way writes it.
831#[derive(Debug, Clone, Copy, PartialEq, Eq)]
832enum Way {
833    Up,
834    Down,
835}
836
837impl Way {
838    /// The sign that turns a reading written this way up to nose up.
839    fn sign(self) -> f64 {
840        match self {
841            Self::Up => 1.0,
842            Self::Down => -1.0,
843        }
844    }
845
846    /// The other way up.
847    fn other(self) -> Self {
848        match self {
849            Self::Up => Self::Down,
850            Self::Down => Self::Up,
851        }
852    }
853
854    fn words(self) -> &'static str {
855        match self {
856            Self::Up => "nose up",
857            Self::Down => "nose down",
858        }
859    }
860}
861
862/// A witness to which way up an accelerometer reads.
863#[derive(Debug, Clone, Copy, PartialEq, Eq)]
864enum WayBy {
865    Pad,
866    Coast,
867    Thrust,
868}
869
870impl WayBy {
871    fn words(self) -> &'static str {
872        match self {
873            Self::Pad => "pad",
874            Self::Coast => "coast to apogee",
875            Self::Thrust => "thrust",
876        }
877    }
878}
879
880/// What the thrust says of which way up the part reads, `None` for nothing, and the words that
881/// say why; `alone` where it can settle the way alone: where its span rises by liftoff's latest
882/// time, not at the start of a log whose liftoff is withheld, which may start after burnout,
883/// with a drag there.
884#[derive(Debug, Clone, PartialEq)]
885struct ThrustWitness {
886    way: Option<Way>,
887    words: String,
888    alone: bool,
889}
890
891/// The first sample of `clean`, the cleaned twin of `values`, that `moved` says has left the
892/// start's level, the median of the first [`PAD_MIN_SAMPLES`] of `values`, by how far it lies
893/// from it; `None` if none does.
894fn first_move(values: &[f64], clean: &[f64], moved: impl Fn(f64) -> bool) -> Option<usize> {
895    let mut start: Vec<f64> = values.iter().take(PAD_MIN_SAMPLES).copied().collect();
896    let level = median(&mut start).unwrap_or(f64::NAN);
897    (0..clean.len()).find(|&k| moved(clean[k] - level))
898}
899
900/// The steady level of `values` on the pad, as the median of the samples from the start to the
901/// [`first_move`] that `moved` says, if that sample is the [`PAD_MIN_SAMPLES`]th or later and
902/// comes no later than liftoff's latest time by the heights; `None` otherwise, or where liftoff
903/// is withheld. A log that starts in the thrust has no pad before its latest time.
904fn pad_level(
905    time: &[f64],
906    values: &[f64],
907    clean: &[f64],
908    liftoff: &Reading<Liftoff>,
909    moved: impl Fn(f64) -> bool,
910) -> Option<f64> {
911    let Reading::Read(liftoff) = liftoff else {
912        return None;
913    };
914    let rise = first_move(values, clean, moved)?;
915    if rise >= PAD_MIN_SAMPLES && time[rise] <= liftoff.time_s + liftoff.bound_s {
916        median(&mut values[..rise].to_vec())
917    } else {
918        None
919    }
920}
921
922/// The median of `values` over the climb's samples `boost` in the last [`COAST_SPAN_S`] before
923/// apogee's earliest time, if [`PAD_MIN_SAMPLES`] or more lie there; `None` where apogee is
924/// withheld.
925fn coast_level(
926    time: &[f64],
927    values: &[f64],
928    boost: &[usize],
929    apogee: &Reading<Apogee>,
930) -> Option<f64> {
931    let Reading::Read(apogee) = apogee else {
932        return None;
933    };
934    let end = apogee.time_s - apogee.time_bound_s;
935    let mut readings: Vec<f64> = boost
936        .iter()
937        .filter(|&&k| time[k] >= end - COAST_SPAN_S && time[k] <= end)
938        .map(|&k| values[k])
939        .collect();
940    if readings.len() >= PAD_MIN_SAMPLES {
941        median(&mut readings)
942    } else {
943        None
944    }
945}
946
947/// The thrust's witness to which way up the accelerometer reads, from its cleaned trace `clean`
948/// as written, its samples `from` (liftoff's earliest time) to `end` (apogee) at `interval`,
949/// averaged over `half` samples either side to end a span, its times `time`. The first span,
950/// either way up, that holds past [`LIFTOFF_ACCELERATION_M_S2`] for [`BURN_LEAST_S`], as a
951/// thrust does and a knock on the pad doesn't, says its way, unless a span the other way comes
952/// before it, as a short burn before a heavy drag or a knock's rebound does: then it says
953/// nothing. Where no span holds that long, the way every span shares says, a short burn's; spans
954/// both ways, or none, say nothing. The thrust is what lifts the rocket, so the span that says
955/// must rise by `lifted`'s time: liftoff's latest time by the heights, or, where liftoff is
956/// withheld as a log that starts in the climb has it, [`BURN_LEAST_S`] after the log's start,
957/// `lifted`'s words naming which. A span that rises later is a drag after a thrust too weak to
958/// pass 2 g as written, or a second burn, and says nothing. A log whose liftoff is withheld may
959/// start after burnout, its drag at its start, so a span there says, but not `alone`. Read as
960/// written, a thrust under 3 g on a part that takes gravity out reads under 2 g, and says
961/// nothing: the pad must say.
962fn thrust_witness(
963    time: &[f64],
964    clean: &[f64],
965    from: usize,
966    end: usize,
967    half: usize,
968    interval: f64,
969    lifted: (f64, &str, bool),
970) -> ThrustWitness {
971    let walk = |way: Way| {
972        let values: Vec<f64> = clean.iter().map(|v| way.sign() * v).collect();
973        let mean = running_mean(&values, half);
974        spans(&values, &mean, from, end, interval)
975    };
976    let (up, down) = (walk(Way::Up), walk(Way::Down));
977    let held = |spans: &[Span]| {
978        spans
979            .iter()
980            .find(|span| span.held_s >= BURN_LEAST_S)
981            .map(|span| span.rise)
982    };
983    let first_held = match (held(&up), held(&down)) {
984        (Some(up), Some(down)) if down < up => Some((Way::Down, down)),
985        (Some(up), _) => Some((Way::Up, up)),
986        (None, Some(down)) => Some((Way::Down, down)),
987        (None, None) => None,
988    };
989    let past = format!("{:.0} g", LIFTOFF_ACCELERATION_M_S2 / STANDARD_GRAVITY_MPS2);
990    let (lifted_s, lifted_by, alone) = lifted;
991    let says = |way: Way, words: String| ThrustWitness {
992        way: Some(way),
993        words: format!("its thrust says {}: {words}", way.words()),
994        alone,
995    };
996    let neither = |words: String| ThrustWitness {
997        way: None,
998        words: format!("its thrust says neither: {words}"),
999        alone,
1000    };
1001    // The span that would say rises by liftoff's latest time, as the thrust that lifts the
1002    // rocket does, or says nothing.
1003    let lifts = |way: Way, rise: usize, words: String| {
1004        if time[rise] <= lifted_s {
1005            says(way, words)
1006        } else {
1007            neither(format!(
1008                "its span that would say {}, from {:.2} s, rises after {lifted_by}, \
1009                 {lifted_s:.2} s. A drag after a thrust too weak to read past {past} or a \
1010                 second burn does so. That span is not the thrust that lifts the rocket",
1011                way.words(),
1012                time[rise]
1013            ))
1014        }
1015    };
1016    if let Some((way, rise)) = first_held {
1017        let other = match way {
1018            Way::Up => &down,
1019            Way::Down => &up,
1020        };
1021        return match other.first().filter(|span| span.rise < rise) {
1022            Some(before) => neither(format!(
1023                "the first span past {past} to hold there for {BURN_LEAST_S} s, {} from {:.2} s, \
1024                 comes after one {} from {:.2} s. A drag after a short burn or a knock's \
1025                 rebound may do so",
1026                way.words(),
1027                time[rise],
1028                way.other().words(),
1029                time[before.rise]
1030            )),
1031            None => lifts(
1032                way,
1033                rise,
1034                format!(
1035                    "the first span past {past} to hold there for {BURN_LEAST_S} s, from {:.2} s",
1036                    time[rise]
1037                ),
1038            ),
1039        };
1040    }
1041    let count = |spans: usize| match spans {
1042        1 => "1 span".to_owned(),
1043        spans => format!("{spans} spans"),
1044    };
1045    match (up.len(), down.len()) {
1046        (0, 0) => neither(format!(
1047            "as written, it never reads past {past} either way up from liftoff's earliest time \
1048             (the log's start where liftoff is withheld) to apogee"
1049        )),
1050        (spans, 0) | (0, spans) => {
1051            let (way, first) = if down.is_empty() {
1052                (Way::Up, &up[0])
1053            } else {
1054                (Way::Down, &down[0])
1055            };
1056            lifts(
1057                way,
1058                first.rise,
1059                format!(
1060                    "no span past {past} holds there for {BURN_LEAST_S} s, and its {} {}, as a \
1061                     short burn's does",
1062                    count(spans),
1063                    if spans == 1 {
1064                        "reads so"
1065                    } else {
1066                        "all read so"
1067                    }
1068                ),
1069            )
1070        }
1071        (up, down) => neither(format!(
1072            "it reads past {past} both ways up, in {} nose up and {} nose down, and never for \
1073             {BURN_LEAST_S} s, as a thrust holds",
1074            count(up),
1075            count(down)
1076        )),
1077    }
1078}
1079
1080/// Which way up the accelerometer reads, by three witnesses, each on its trace as written and
1081/// each from physics that holds whether or not the part takes gravity out:
1082/// - the pad, its steady level `pad` before the thrust: at rest a part reads 1 g nose up and
1083///   −1 g nose down where it holds gravity, and 0 either way where it doesn't, so a pad within
1084///   [`GRAVITY_TOLERANCE_G`] of 1 g says nose up, of −1 g nose down, and of 0 nothing;
1085/// - the coast's last [`COAST_SPAN_S`] before apogee's earliest time, its median `coast`, where
1086///   one was flown: in a coast a part reads `−D/m` nose up where it holds gravity and
1087///   `−D/m − g` where it doesn't, never above 0 while it coasts with its thrust ended and no
1088///   canopy open, and the mirror nose down, so a coast at 1 g
1089///   less the tolerance or more below 0 says nose up, as far above 0 nose down, a drag only
1090///   pushing it further, and one nearer 0 nothing;
1091/// - the thrust ([`thrust_witness`]).
1092///
1093/// Settled when the pad or the thrust says and no witness disagrees: the way and the witnesses
1094/// that said it, or the words that say what each said. The coast can only disagree: its second
1095/// can hold a weak thrust still burning or a canopy opened early, either of which reads the
1096/// other way, so a coast alone settles nothing.
1097fn direction(
1098    pad: Option<f64>,
1099    coast: Option<f64>,
1100    thrust: &ThrustWitness,
1101) -> Result<(Way, Vec<WayBy>), String> {
1102    let g = STANDARD_GRAVITY_MPS2;
1103    let tolerance = GRAVITY_TOLERANCE_G * g;
1104    let by_pad = pad.and_then(|pad| {
1105        if (pad - g).abs() <= tolerance {
1106            Some(Way::Up)
1107        } else if (pad + g).abs() <= tolerance {
1108            Some(Way::Down)
1109        } else {
1110            None
1111        }
1112    });
1113    let by_coast = coast.and_then(|coast| {
1114        if coast <= -(g - tolerance) {
1115            Some(Way::Up)
1116        } else if coast >= g - tolerance {
1117            Some(Way::Down)
1118        } else {
1119            None
1120        }
1121    });
1122    let said: Vec<(Way, WayBy)> = [
1123        (by_pad, WayBy::Pad),
1124        (by_coast, WayBy::Coast),
1125        (thrust.way, WayBy::Thrust),
1126    ]
1127    .iter()
1128    .filter_map(|(way, by)| way.map(|way| (way, *by)))
1129    .collect();
1130    // A coast alone settles nothing, nor a thrust at the start of a log whose liftoff is
1131    // withheld: the pad can, the thrust where it rises by liftoff's latest time, or a thrust
1132    // at a log's start with the coast beside it.
1133    let settles =
1134        by_pad.is_some() || (thrust.way.is_some() && (thrust.alone || by_coast.is_some()));
1135    match said.first() {
1136        Some(&(way, _)) if settles && said.iter().all(|(each, _)| *each == way) => {
1137            Ok((way, said.iter().map(|(_, by)| *by).collect()))
1138        }
1139        _ => {
1140            let level = |name: &str, level: Option<f64>, said: Option<Way>, marks: &str| {
1141                level.map_or_else(
1142                    || format!("no {name} is read to tell by"),
1143                    |level| {
1144                        format!(
1145                            "its {name} reads {:.2} g as written, which says {} ({marks})",
1146                            level / g,
1147                            said.map_or("neither", Way::words)
1148                        )
1149                    },
1150                )
1151            };
1152            let near = 1.0 - GRAVITY_TOLERANCE_G;
1153            Err(format!(
1154                "{}; {}; {}: {}",
1155                level(
1156                    "pad",
1157                    pad,
1158                    by_pad,
1159                    "about 1 g says nose up, about −1 g nose down"
1160                ),
1161                level(
1162                    "coast to apogee",
1163                    coast,
1164                    by_coast,
1165                    &format!("−{near} g or less says nose up, {near} g or more nose down")
1166                ),
1167                thrust.words,
1168                if said.is_empty() {
1169                    "none of them says which way up it reads"
1170                } else if !settles && thrust.way.is_none() {
1171                    "the coast alone says. A coast's second can hold a weak thrust still \
1172                     burning or a canopy opened early. So the coast doesn't settle which way up it \
1173                     reads on its own"
1174                } else if !settles {
1175                    "the thrust alone says, at the start of a log whose liftoff is withheld, which \
1176                     may start after burnout with a drag there. So the thrust doesn't settle which way \
1177                     up it reads without the coast beside it"
1178                } else {
1179                    "they disagree on which way up it reads"
1180                }
1181            ))
1182        }
1183    }
1184}
1185
1186/// Burnout from the accelerometer: its time and bound, or why the accelerometer gives none. `f`
1187/// is the trace, `mean` its cleaned twin averaged over [`BURNOUT_MEAN_S`] at `interval`, `end` the
1188/// last sample before apogee and `top_index` the top acceleration's.
1189fn burnout(
1190    time: &[f64],
1191    f: &[f64],
1192    mean: &[f64],
1193    end: usize,
1194    top_index: usize,
1195    step: f64,
1196    interval: f64,
1197) -> Result<(f64, f64), String> {
1198    // The trace averaged over [`BURNOUT_MEAN_S`], `2h + 1` samples, which cuts its noise by
1199    // √(2h + 1) and spreads burnout over the window.
1200    let h = half_window(BURNOUT_MEAN_S, interval);
1201    let Some(crossing) = (top_index + 1..=end).find(|&k| mean[k] <= 0.0) else {
1202        return Err(
1203            "the accelerometer never reads below zero between its top and apogee, so it shows \
1204             no burnout"
1205                .to_owned(),
1206        );
1207    };
1208    let noise_end = time
1209        .partition_point(|t| *t <= time[crossing] + 1.0)
1210        .min(end + 1);
1211    #[expect(
1212        clippy::cast_precision_loss,
1213        reason = "a window of a few samples converts exactly"
1214    )]
1215    let averaged = ((2 * h + 1) as f64).sqrt();
1216    let n =
1217        ACCEL_NOISE_SIGMAS * noise(&f[top_index..noise_end.max(top_index + 1)]) / averaged + step;
1218    let mut least = (f64::INFINITY, crossing);
1219    let mut stop = None;
1220    for (k, value) in mean.iter().enumerate().take(end + 1).skip(crossing) {
1221        if *value < least.0 {
1222            least = (*value, k);
1223        } else if *value > least.0 + 4.0 * n {
1224            stop = Some(k);
1225            break;
1226        }
1227    }
1228    let Some(stop) = stop else {
1229        return Err(format!(
1230            "the accelerometer's reading doesn't climb {:.2} m/s² back from its least, four times \
1231             its noise and step, before apogee. Burnout can't be told from the coast",
1232            4.0 * n
1233        ));
1234    };
1235    if least.0 > -3.0 * n {
1236        return Err(format!(
1237            "the accelerometer's least reading after the thrust, {:.2} m/s², lies within {:.2} \
1238             m/s², three times its noise and step, of zero. That is too little drag to tell \
1239             burnout by",
1240            least.0,
1241            3.0 * n
1242        ));
1243    }
1244    let near: Vec<usize> = (crossing..stop)
1245        .filter(|&k| mean[k] <= least.0 + 2.0 * n)
1246        .collect();
1247    // Never empty: the least's own sample lies in `crossing..stop` and within `2N` of itself.
1248    let (Some(&first), Some(&last)) = (near.first(), near.last()) else {
1249        return Err(
1250            "the accelerometer's least reading after the thrust can't be placed".to_owned(),
1251        );
1252    };
1253    // The averaged trace's least lies from two intervals before the first such sample, one for
1254    // the sample next to it and one for the part's filter, which spreads a thrust cut off at once
1255    // over about a sample, to an interval after the last; burnout lies within half the average's
1256    // window, `w/2`, of it. The thrust falls steeply and the coast's drag eases slowly, so it lies
1257    // near the first, where the average, reaching the coast's level only once its window has
1258    // passed a thrust cut off at once, reads it late by `w/2`: the reading is the first less
1259    // `w/2`, and the bound reaches back two intervals and on to the last, an interval and `w/2`.
1260    let interval = local_interval(time, first).max(local_interval(time, last));
1261    #[expect(
1262        clippy::cast_precision_loss,
1263        reason = "a window of a few samples converts exactly"
1264    )]
1265    let half_window_s = h as f64 * interval;
1266    let bound_s = (time[last] - time[first] + interval + 2.0 * half_window_s).max(2.0 * interval);
1267    Ok((time[first] - half_window_s, bound_s))
1268}
1269
1270/// Burnout from the top speed's peak, a floor; or why it is withheld. `why` says why the
1271/// accelerometer gave none, where it has one.
1272fn from_speed(heights: &Readings, why: Option<String>) -> Reading<Burnout> {
1273    match &heights.max_speed {
1274        Reading::Read(speed) => {
1275            let bound_s = 2.0 * SPEED_NOISE_M_S / STANDARD_GRAVITY_MPS2
1276                + 0.5 * SPEED_WINDOW_S
1277                + heights.sample_interval_s.unwrap_or(0.0);
1278            Reading::Read(Burnout {
1279                time_s: speed.time_s,
1280                bound_s,
1281                interval_s: None,
1282                lower_end_s: interval::BURNOUT_FLOOR_SHARES.lower_end(speed.time_s, bound_s),
1283                time_after_liftoff_s: heights.liftoff.value().map(|l| speed.time_s - l.time_s),
1284                is_floor: true,
1285                source: speed.source,
1286                provenance: Provenance::Derived,
1287                method: Method::SpeedPeak,
1288            })
1289        }
1290        Reading::Withheld(Withheld { reason, detail }) => Reading::withheld(
1291            *reason,
1292            match why {
1293                Some(why) => format!(
1294                    "{why}; and burnout from the speed's peak needs the top speed, which is \
1295                     withheld: {detail}"
1296                ),
1297                None => format!(
1298                    "burnout from the speed's peak needs the top speed, which is withheld: \
1299                     {detail}"
1300                ),
1301            },
1302        ),
1303    }
1304}
1305
1306#[cfg(test)]
1307mod tests {
1308    use super::super::read as read_all;
1309    use super::*;
1310    use crate::log::{Channel, Stated};
1311
1312    const G: f64 = STANDARD_GRAVITY_MPS2;
1313
1314    /// Uniform noise in ±`amplitude`/2, the same on every run: σ is `amplitude`/√12.
1315    fn jitter(k: usize, amplitude: f64) -> f64 {
1316        #[expect(
1317            clippy::cast_precision_loss,
1318            reason = "a sample's index converts exactly"
1319        )]
1320        let x = (k as f64 * 12.9898).sin() * 43_758.545_3;
1321        amplitude * (x - x.floor() - 0.5)
1322    }
1323
1324    /// The pad to 3 s, a climb at 4 g to 4 s, a vacuum coast to apogee at 8 s (98.1 m), then
1325    /// down at 10 m/s: the height track the accelerometer's readings are searched against.
1326    fn height(t: f64) -> f64 {
1327        let c = t - 3.0;
1328        if c <= 0.0 {
1329            0.0
1330        } else if c < 1.0 {
1331            2.0 * G * c * c
1332        } else if c < 5.0 {
1333            let d = c - 1.0;
1334            2.0 * G + 4.0 * G * d - 0.5 * G * d * d
1335        } else {
1336            (10.0 * G - 10.0 * (c - 5.0)).max(0.0)
1337        }
1338    }
1339
1340    /// The specific force along the axis, gravity in: 1 g on the pad, a thrust rising to 6 g at
1341    /// 3.5 s, falling through zero to −0.6 g at burnout, 4.1 s, as the drag pulls back, the
1342    /// drag's pull easing to nothing at apogee, then 1 g again under a canopy.
1343    fn specific_force(t: f64) -> f64 {
1344        if t < 3.0 {
1345            G
1346        } else if t < 4.0 {
1347            5.0 * G + G * (std::f64::consts::PI * (t - 3.0)).sin()
1348        } else if t < 4.1 {
1349            5.0 * G - 5.6 * G * (t - 4.0) / 0.1
1350        } else if t < 8.0 {
1351            -0.6 * G * (8.0 - t) / 3.9
1352        } else {
1353            G
1354        }
1355    }
1356
1357    /// A log of [`height`] every 0.05 s and an accelerometer under `column`, read as `format`,
1358    /// sampled every `dt` s, writing `value` of each sample's index and time.
1359    fn log(
1360        format: LogFormat,
1361        column: &str,
1362        dt: f64,
1363        value: impl Fn(usize, f64) -> f64,
1364    ) -> FlightLog {
1365        let clock = |dt: f64| -> Vec<f64> {
1366            (0..)
1367                .map(|i| f64::from(i) * dt)
1368                .take_while(|t| *t <= 30.0 + 1e-9)
1369                .collect()
1370        };
1371        let time_s = clock(0.05);
1372        let accel_s = clock(dt);
1373        let values = accel_s
1374            .iter()
1375            .enumerate()
1376            .map(|(k, t)| value(k, *t))
1377            .collect();
1378        let mut log = FlightLog {
1379            format,
1380            logger: "test".to_owned(),
1381            serial_number: None,
1382            firmware: None,
1383            flight_number: None,
1384            stated: Stated::default(),
1385            altitude_m: time_s.iter().map(|t| height(*t)).collect(),
1386            time_s,
1387            vertical_speed_m_s: None,
1388            temperature_k: None,
1389            battery_v: None,
1390            channels: vec![Channel::new(
1391                column,
1392                Quantity::Acceleration,
1393                accel_s,
1394                values,
1395            )],
1396            events: Vec::new(),
1397            notes: Vec::new(),
1398        };
1399        // An AltOS log is a TeleMetrum's: its GPS receiver's column beside the accelerometer.
1400        if format == LogFormat::AltosCsv {
1401            let time_s = log.time_s.clone();
1402            let latitude = vec![40.0; time_s.len()];
1403            log.channels.push(Channel::new(
1404                "latitude",
1405                Quantity::Latitude,
1406                time_s,
1407                latitude,
1408            ));
1409        }
1410        log
1411    }
1412
1413    /// A noisy axial trace reads its top and burnout within their bounds, measured; gravity is
1414    /// settled by the pad, as a column that only names the axis can't say.
1415    #[test]
1416    fn an_axial_trace_reads_its_top_and_burnout() {
1417        let readings = read_all(&log(
1418            LogFormat::GenericTable,
1419            "Axial accel",
1420            0.01,
1421            |k, t| specific_force(t) + jitter(k, 0.3),
1422        ));
1423        let accelerometer = readings.accelerometer.unwrap();
1424        assert_eq!(accelerometer.gravity, Gravity::In);
1425        assert_eq!(accelerometer.gravity_by, GravityBy::Pad);
1426        assert!(!accelerometer.turned_over);
1427        let top = readings.max_acceleration.value().unwrap();
1428        assert!(
1429            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1430            "{top:?}"
1431        );
1432        assert!((top.time_s - 3.5).abs() < 0.1, "{top:?}");
1433        assert_eq!(top.provenance, Provenance::Measured);
1434        assert_eq!(top.method, Method::HighestReading);
1435        // Whole, each states its 90% interval by its own shares, and no lower end.
1436        assert_eq!(
1437            top.interval_m_s2,
1438            interval::TOP_ACCELERATION_SHARES.interval(top.acceleration_m_s2, top.bound_m_s2)
1439        );
1440        assert!(top.interval_m_s2.is_some() && top.lower_end_m_s2.is_none());
1441        let stated = readings.burnout.value().unwrap();
1442        assert_eq!(
1443            stated.interval_s,
1444            interval::BURNOUT_SHARES.interval(stated.time_s, stated.bound_s)
1445        );
1446        assert!(stated.interval_s.is_some() && stated.lower_end_s.is_none());
1447        assert_eq!(top.range_m_s2, None);
1448        let burnout = readings.burnout.value().unwrap();
1449        assert!(!burnout.is_floor);
1450        assert_eq!(burnout.method, Method::LeastAfterThrust);
1451        assert!(
1452            (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1453            "{burnout:?}"
1454        );
1455        // The least lies at the thrust's end, to a sample.
1456        assert!((burnout.time_s - 4.1).abs() <= 0.01, "{burnout:?}");
1457        // The bound is the samples within 2N of the least: N is 5σ over √7 samples averaged and
1458        // a step, 0.16 m/s², and the coast's drag eases 1.5 m/s² a second, so they span about
1459        // 0.22 s; with an interval and the 0.07 s window, 0.30 s.
1460        let sigma = 0.3 / 12.0_f64.sqrt();
1461        let n = ACCEL_NOISE_SIGMAS * sigma / 7.0_f64.sqrt();
1462        let span = 2.0 * n / (0.6 * G / 3.9);
1463        assert!(
1464            (burnout.bound_s - (span + 0.01 + 0.07)).abs() < 0.03,
1465            "{burnout:?}, span {span}"
1466        );
1467    }
1468
1469    /// A part mounted nose down, gravity taken out, reads the same: turned over and put back.
1470    #[test]
1471    fn a_turned_over_part_without_gravity_reads_alike() {
1472        let readings = read_all(&log(
1473            LogFormat::GenericTable,
1474            "Axial accel",
1475            0.01,
1476            |k, t| -(specific_force(t) - G) + jitter(k, 0.3),
1477        ));
1478        let accelerometer = readings.accelerometer.unwrap();
1479        assert!(accelerometer.turned_over);
1480        assert_eq!(accelerometer.gravity, Gravity::Out);
1481        let top = readings.max_acceleration.value().unwrap();
1482        assert!(
1483            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1484            "{top:?}"
1485        );
1486        let burnout = readings.burnout.value().unwrap();
1487        assert!(
1488            (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1489            "{burnout:?}"
1490        );
1491    }
1492
1493    /// A part held at its range is clipped: by the range its family states, or, with none, by a
1494    /// top held flat. The true top lies above the reading less its bound, as a floor states.
1495    #[test]
1496    fn a_top_held_at_the_range_is_clipped() {
1497        // Fluctus states a ±200 g part; the trace scaled to peak at 240 g reads 200 g.
1498        let scale = 40.0;
1499        let readings = read_all(&log(
1500            LogFormat::FluctusCsv,
1501            "vert-accel (m/s2)",
1502            0.01,
1503            |_, t| {
1504                if t < 3.0 {
1505                    G
1506                } else {
1507                    (scale * (specific_force(t) - G) + G).min(200.0 * G)
1508                }
1509            },
1510        ));
1511        let top = readings.max_acceleration.value().unwrap();
1512        assert_eq!(top.provenance, Provenance::Clipped, "{top:?}");
1513        assert_eq!(top.range_m_s2, Some(200.0 * G));
1514        assert!(top.acceleration_m_s2 - top.bound_m_s2 <= scale * 5.0 * G + G);
1515        // A clipped top states its lower end by the floor's shares, inside its bound, and no
1516        // interval.
1517        assert_eq!(
1518            top.lower_end_m_s2,
1519            Some(top.acceleration_m_s2 - 0.259 * top.bound_m_s2)
1520        );
1521        assert!(top.interval_m_s2.is_none());
1522        // Below the range, the same family's part reads its top, measured.
1523        let readings = read_all(&log(
1524            LogFormat::FluctusCsv,
1525            "vert-accel (m/s2)",
1526            0.01,
1527            |k, t| {
1528                if t < 3.0 {
1529                    G + jitter(k, 0.3)
1530                } else {
1531                    20.0 * (specific_force(t) - G) + G + jitter(k, 0.3)
1532                }
1533            },
1534        ));
1535        let top = readings.max_acceleration.value().unwrap();
1536        assert_eq!(top.provenance, Provenance::Measured, "{top:?}");
1537        // No range stated: flat at 5.5 g for 0.6 s, where the thrust peaks at 6 g.
1538        let readings = read_all(&log(
1539            LogFormat::GenericTable,
1540            "Axial accel",
1541            0.01,
1542            |k, t| (specific_force(t) + jitter(k, 0.3)).min(5.5 * G),
1543        ));
1544        let top = readings.max_acceleration.value().unwrap();
1545        assert_eq!(top.provenance, Provenance::Clipped, "{top:?}");
1546        assert_eq!(top.range_m_s2, None);
1547        assert!((top.acceleration_m_s2 - 5.5 * G).abs() < 1e-9);
1548    }
1549
1550    /// A quiet part's plateau isn't a clip: within Debrief's tolerance, 0.25 m/s² at 5 g, it holds
1551    /// for the whole plateau, but it still scatters by its noise, 0.03 m/s² here.
1552    #[test]
1553    fn a_quiet_plateau_is_not_clipped() {
1554        let plateau = |t: f64| {
1555            if (3.0..4.0).contains(&t) {
1556                5.0 * G
1557            } else {
1558                specific_force(t)
1559            }
1560        };
1561        let readings = read_all(&log(
1562            LogFormat::GenericTable,
1563            "Axial accel",
1564            0.002,
1565            |k, t| plateau(t) + jitter(k, 0.1),
1566        ));
1567        let top = readings.max_acceleration.value().unwrap();
1568        assert!((top.acceleration_m_s2 - 5.0 * G).abs() <= top.bound_m_s2);
1569        assert_eq!(top.provenance, Provenance::Measured, "{top:?}");
1570    }
1571
1572    /// A family's word that its readings hold no gravity, against a pad that reads 1 g, settles
1573    /// nothing; nor does a family that doesn't say, over a pad that reads neither.
1574    #[test]
1575    fn gravity_unsettled_withholds_the_top_and_burnout_falls_back() {
1576        let readings = read_all(&log(LogFormat::Marsa, "acceleration", 0.01, |_, t| {
1577            specific_force(t)
1578        }));
1579        assert_eq!(
1580            readings.max_acceleration.reason(),
1581            Some(Reason::GravityUnstated)
1582        );
1583        assert!(readings.accelerometer.is_none());
1584        let readings = read_all(&log(
1585            LogFormat::GenericTable,
1586            "Axial accel",
1587            0.01,
1588            |_, t| specific_force(t) - 0.5 * G,
1589        ));
1590        assert_eq!(
1591            readings.max_acceleration.reason(),
1592            Some(Reason::GravityUnstated)
1593        );
1594        // Burnout falls back to the speed's peak, a floor.
1595        let burnout = readings.burnout.value().unwrap();
1596        assert!(burnout.is_floor);
1597        assert_eq!(burnout.method, Method::SpeedPeak);
1598        // A floor states its lower end by the floor's shares, and no interval.
1599        assert_eq!(
1600            burnout.lower_end_s,
1601            interval::BURNOUT_FLOOR_SHARES.lower_end(burnout.time_s, burnout.bound_s)
1602        );
1603        assert_eq!(
1604            burnout.lower_end_s,
1605            Some(burnout.time_s + 0.0335 * burnout.bound_s)
1606        );
1607        assert!(burnout.interval_s.is_none());
1608    }
1609
1610    /// A log that starts in the thrust has no pad to tell gravity by; its coast to apogee still
1611    /// does where it reads about 0, gravity in. About −1 g, gravity out, it doesn't settle alone,
1612    /// as a drag of about 1 g reads so too (#806). The drag here eases as the square of a speed
1613    /// that falls off in the coast, under 0.04 g in the last second.
1614    #[test]
1615    fn the_coast_settles_gravity_where_there_is_no_pad() {
1616        let eased = |t: f64| {
1617            if (4.1..8.0).contains(&t) {
1618                -0.6 * G * ((8.0 - t) / 3.9).powi(2)
1619            } else {
1620                specific_force(t)
1621            }
1622        };
1623        let late = |gravity_out: bool| {
1624            let mut log = log(LogFormat::GenericTable, "Axial accel", 0.01, |k, t| {
1625                eased(t) - if gravity_out { G } else { 0.0 } + jitter(k, 0.3)
1626            });
1627            // The accelerometer starts at 3.2 s, its thrust already 5.6 g.
1628            let channel = &mut log.channels[0];
1629            let first = channel.time_s.iter().position(|t| *t >= 3.2).unwrap();
1630            channel.time_s.drain(..first);
1631            channel.values.drain(..first);
1632            read_all(&log)
1633        };
1634        let readings = late(false);
1635        let accelerometer = readings.accelerometer.unwrap();
1636        assert_eq!(accelerometer.gravity, Gravity::In);
1637        assert_eq!(accelerometer.gravity_by, GravityBy::Coast);
1638        let top = readings.max_acceleration.value().unwrap();
1639        assert!(
1640            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1641            "{top:?}"
1642        );
1643        let readings = late(true);
1644        assert!(readings.accelerometer.is_none());
1645        let Reading::Withheld(withheld) = &readings.max_acceleration else {
1646            panic!("{:?}", readings.max_acceleration);
1647        };
1648        assert_eq!(withheld.reason, Reason::GravityUnstated);
1649        assert!(
1650            withheld.detail.contains("only the coast says"),
1651            "{withheld:?}"
1652        );
1653        // A family that says gravity is out, over a coast that reads 0, disagrees.
1654        let mut log = log(LogFormat::Marsa, "acceleration", 0.01, |_, t| eased(t));
1655        let channel = &mut log.channels[0];
1656        let first = channel.time_s.iter().position(|t| *t >= 3.2).unwrap();
1657        channel.time_s.drain(..first);
1658        channel.values.drain(..first);
1659        let readings = read_all(&log);
1660        assert_eq!(
1661            readings.max_acceleration.reason(),
1662            Some(Reason::GravityUnstated)
1663        );
1664    }
1665
1666    /// A rocket still fast at apogee, arcing over, drags about 1 g in the coast's last second.
1667    /// With gravity in, its part reads about −1 g there, as one without gravity and little drag
1668    /// would. On a log with no family word and no pad, the coast alone said gravity was out, and
1669    /// 1 g was put back on a top already holding it (#806). Now it is withheld.
1670    #[test]
1671    fn a_fast_arc_over_doesnt_settle_gravity_out_alone() {
1672        let arcing = |t: f64| {
1673            if (4.1..8.0).contains(&t) {
1674                -G
1675            } else {
1676                specific_force(t)
1677            }
1678        };
1679        // The accelerometer starts at 3.2 s, its thrust already 5.6 g: no pad.
1680        let late = |format, column| {
1681            let mut log = log(format, column, 0.01, |k, t| arcing(t) + jitter(k, 0.3));
1682            let channel = &mut log.channels[0];
1683            let first = channel.time_s.iter().position(|t| *t >= 3.2).unwrap();
1684            channel.time_s.drain(..first);
1685            channel.values.drain(..first);
1686            read_all(&log)
1687        };
1688        let readings = late(LogFormat::GenericTable, "Axial accel");
1689        assert!(
1690            readings.accelerometer.is_none(),
1691            "{:?}",
1692            readings.accelerometer
1693        );
1694        let Reading::Withheld(withheld) = &readings.max_acceleration else {
1695            panic!("{:?}", readings.max_acceleration);
1696        };
1697        assert_eq!(withheld.reason, Reason::GravityUnstated);
1698        // The coast was read, and said gravity is out: withheld for standing alone, not unread.
1699        assert!(
1700            withheld.detail.contains("only the coast says"),
1701            "{withheld:?}"
1702        );
1703        // Beside a family that says gravity is in, the AIM XTRA's, the coast disagrees and the
1704        // top is withheld still, as before.
1705        assert_eq!(
1706            late(LogFormat::EntacoreAimCsv, "acceleration")
1707                .max_acceleration
1708                .reason(),
1709            Some(Reason::GravityUnstated)
1710        );
1711    }
1712
1713    /// Gravity's coast is read only where a coast was flown (#806). Here
1714    /// the heights put apogee's earliest time 0.1 s after the thrust starts, so the second before
1715    /// it lies on the pad. On a part that takes gravity out the pad reads 0, which as a coast says
1716    /// gravity is in, against the family's word and the pad: the top was withheld. Not read as a
1717    /// coast, the family and the pad settle it.
1718    #[test]
1719    fn gravitys_coast_is_read_only_where_one_was_flown() {
1720        let log = log(LogFormat::Marsa, "acceleration", 0.01, |k, t| {
1721            specific_force(t) - G + jitter(k, 0.3)
1722        });
1723        let mut heights = super::super::heights(&log);
1724        let Reading::Read(apogee) = &mut heights.apogee else {
1725            panic!("{:?}", heights.apogee);
1726        };
1727        apogee.time_bound_s = apogee.time_s - 3.1;
1728        let (accelerometer, top, _) = read(&log, &heights);
1729        let accelerometer = accelerometer.unwrap_or_else(|| panic!("{top:?}"));
1730        assert_eq!(accelerometer.gravity, Gravity::Out);
1731        assert_eq!(accelerometer.gravity_by, GravityBy::Family);
1732        let top = top.value().unwrap();
1733        assert!(
1734            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1735            "{top:?}"
1736        );
1737    }
1738
1739    /// A sample that repeats the time before it is left out, the first kept, as AltOS's primary
1740    /// track keeps it; a clock that runs back is still refused.
1741    #[test]
1742    fn a_repeated_time_keeps_the_first_sample() {
1743        let mut log = log(LogFormat::GenericTable, "Axial accel", 0.01, |k, t| {
1744            specific_force(t) + jitter(k, 0.3)
1745        });
1746        let channel = &mut log.channels[0];
1747        let k = channel.time_s.iter().position(|t| *t >= 3.5).unwrap();
1748        channel.time_s.insert(k + 1, channel.time_s[k]);
1749        channel.values.insert(k + 1, 100.0 * G);
1750        let readings = read_all(&log);
1751        let top = readings.max_acceleration.value().unwrap();
1752        assert!(
1753            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1754            "{top:?}"
1755        );
1756        let channel = &mut log.channels[0];
1757        channel.time_s[k + 1] = channel.time_s[k] - 0.005;
1758        assert_eq!(
1759            read_all(&log).max_acceleration.reason(),
1760            Some(Reason::ClockOutOfOrder)
1761        );
1762    }
1763
1764    /// With no drag to pull the reading below zero, the accelerometer shows no burnout, and the
1765    /// speed's peak gives a floor: burnout, 4.0 s here, comes no sooner than it less its bound.
1766    #[test]
1767    fn no_fall_below_zero_is_a_floor_from_the_speed() {
1768        let readings = read_all(&log(
1769            LogFormat::GenericTable,
1770            "Axial accel",
1771            0.01,
1772            |_, t| {
1773                if (4.0..8.0).contains(&t) {
1774                    0.0
1775                } else {
1776                    specific_force(t)
1777                }
1778            },
1779        ));
1780        assert!(readings.max_acceleration.value().is_some());
1781        let burnout = readings.burnout.value().unwrap();
1782        assert!(burnout.is_floor);
1783        assert_eq!(burnout.provenance, Provenance::Derived);
1784        assert!(burnout.time_s - 4.0 <= burnout.bound_s, "{burnout:?}");
1785    }
1786
1787    /// A charge's shock in the coast, larger than the thrust, isn't taken for the top, and one
1788    /// sample of −60 g in the thrust neither turns the trace over nor moves burnout.
1789    #[test]
1790    fn a_spike_neither_tops_nor_turns_the_trace() {
1791        let base = |k: usize, t: f64| specific_force(t) + jitter(k, 0.3);
1792        // A 12 g shock for 30 ms at 7.5 s, half a second before apogee.
1793        let readings = read_all(&log(
1794            LogFormat::GenericTable,
1795            "Axial accel",
1796            0.01,
1797            |k, t| {
1798                if (7.5..7.53).contains(&t) {
1799                    12.0 * G
1800                } else {
1801                    base(k, t)
1802                }
1803            },
1804        ));
1805        let top = readings.max_acceleration.value().unwrap();
1806        assert!(
1807            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1808            "{top:?}"
1809        );
1810        assert!(top.time_s < 4.1, "{top:?}");
1811        assert!(!readings.accelerometer.as_ref().unwrap().turned_over);
1812        // A canopy's shock of −20 g for 0.2 s at 7 s, too long for the filter: the thrust's 6 g
1813        // still comes first, so the trace isn't turned over.
1814        let readings = read_all(&log(
1815            LogFormat::GenericTable,
1816            "Axial accel",
1817            0.01,
1818            |k, t| {
1819                if (7.0..7.2).contains(&t) {
1820                    -20.0 * G
1821                } else {
1822                    base(k, t)
1823                }
1824            },
1825        ));
1826        assert!(!readings.accelerometer.as_ref().unwrap().turned_over);
1827        let top = readings.max_acceleration.value().unwrap();
1828        assert!(
1829            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1830            "{top:?}"
1831        );
1832        // One sample of −60 g at 3.3 s, in the thrust.
1833        let readings = read_all(&log(
1834            LogFormat::GenericTable,
1835            "Axial accel",
1836            0.01,
1837            |k, t| {
1838                if (t - 3.3).abs() < 1e-9 {
1839                    -60.0 * G
1840                } else {
1841                    base(k, t)
1842                }
1843            },
1844        ));
1845        assert!(!readings.accelerometer.as_ref().unwrap().turned_over);
1846        let top = readings.max_acceleration.value().unwrap();
1847        assert!(
1848            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1849            "{top:?}"
1850        );
1851        let burnout = readings.burnout.value().unwrap();
1852        assert!(!burnout.is_floor, "{burnout:?}");
1853        assert!(
1854            (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1855            "{burnout:?}"
1856        );
1857    }
1858
1859    /// A sample that isn't a number is left out, and the readings stand without it.
1860    #[test]
1861    fn a_sample_that_is_no_number_is_left_out() {
1862        for bad in [f64::NAN, f64::NEG_INFINITY, f64::INFINITY] {
1863            let readings = read_all(&log(
1864                LogFormat::GenericTable,
1865                "Axial accel",
1866                0.01,
1867                |k, t| {
1868                    if (t - 3.8).abs() < 1e-9 {
1869                        bad
1870                    } else {
1871                        specific_force(t) + jitter(k, 0.3)
1872                    }
1873                },
1874            ));
1875            let top = readings.max_acceleration.value().unwrap();
1876            assert!(
1877                (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1878                "{bad}: {top:?}"
1879            );
1880            let burnout = readings.burnout.value().unwrap();
1881            assert!(!burnout.is_floor, "{bad}: {burnout:?}");
1882            assert!(
1883                (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1884                "{bad}: {burnout:?}"
1885            );
1886        }
1887    }
1888
1889    /// An accelerometer sampled faster than its readings were checked at is withheld, as a height
1890    /// track is, and burnout falls back to the top speed.
1891    #[test]
1892    fn an_accelerometer_sampled_too_fast_is_withheld() {
1893        let readings = read_all(&log(
1894            LogFormat::GenericTable,
1895            "Axial accel",
1896            0.001,
1897            |_, t| specific_force(t),
1898        ));
1899        assert_eq!(
1900            readings.max_acceleration.reason(),
1901            Some(Reason::SampledTooFast)
1902        );
1903        assert!(readings.accelerometer.is_none());
1904        assert!(readings.burnout.value().unwrap().is_floor);
1905        // 160,000 samples 1e-7 s apart, a clock that once overflowed the burnout window's count
1906        // and averaged for seconds: refused before either.
1907        let mut fast = log(LogFormat::GenericTable, "Axial accel", 0.01, |_, t| {
1908            specific_force(t)
1909        });
1910        let time_s: Vec<f64> = (0..160_000).map(|i| 3.0 + f64::from(i) * 1e-7).collect();
1911        let values = time_s.iter().map(|t| specific_force(*t)).collect();
1912        fast.channels = vec![Channel::new(
1913            "Axial accel",
1914            Quantity::Acceleration,
1915            time_s,
1916            values,
1917        )];
1918        assert_eq!(
1919            read_all(&fast).max_acceleration.reason(),
1920            Some(Reason::SampledTooFast)
1921        );
1922    }
1923
1924    /// A second burn, an air start's or a sustainer's, is searched for the top, and as the tuning
1925    /// set's flights burn once, the accelerometer gives no burnout: the speed's peak, no later
1926    /// than the last burn's end, gives it as a floor. A pulse in the coast that holds past 2 g for
1927    /// less than [`BURN_LEAST_S`], as a canopy's shock does, is no burn.
1928    #[test]
1929    fn a_second_burn_is_searched_for_the_top_and_leaves_burnout_to_the_speed() {
1930        let with = |from: f64, to: f64, peak_g: f64| {
1931            read_all(&log(
1932                LogFormat::GenericTable,
1933                "Axial accel",
1934                0.01,
1935                |k, t| {
1936                    let value = if (from..to).contains(&t) {
1937                        peak_g * G * ((t - from) / 0.05).min((to - t) / 0.05).min(1.0)
1938                    } else {
1939                        specific_force(t)
1940                    };
1941                    value + jitter(k, 0.3)
1942                },
1943            ))
1944        };
1945        // A sustainer's burn at 8 g from 5 s to 6.5 s, in the coast.
1946        let readings = with(5.0, 6.5, 8.0);
1947        let top = readings.max_acceleration.value().unwrap();
1948        assert!(
1949            (top.acceleration_m_s2 - 8.0 * G).abs() <= top.bound_m_s2,
1950            "{top:?}"
1951        );
1952        assert!((5.0..6.5).contains(&top.time_s), "{top:?}");
1953        let burnout = readings.burnout.value().unwrap();
1954        assert!(burnout.is_floor, "{burnout:?}");
1955        assert_eq!(burnout.method, Method::SpeedPeak);
1956        // A canopy's shock at 10 g for 0.4 s, from 7 s: the top and burnout are the burn's.
1957        let readings = with(7.0, 7.4, 10.0);
1958        let top = readings.max_acceleration.value().unwrap();
1959        assert!(
1960            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1961            "{top:?}"
1962        );
1963        let burnout = readings.burnout.value().unwrap();
1964        assert!(!burnout.is_floor, "{burnout:?}");
1965        assert!(
1966            (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1967            "{burnout:?}"
1968        );
1969    }
1970
1971    /// A span past 2 g that holds there for less than [`BURN_LEAST_S`] is no burn, as a knock on
1972    /// the pad with its rebound isn't, unless no span holds that long: then the first is the
1973    /// burn, a short motor's.
1974    #[test]
1975    fn a_burn_holds_past_two_g_or_is_the_only_one() {
1976        // A knock to 4 g and its rebound to −2 g, 0.15 s each, at 2.5 s, before the thrust.
1977        let readings = read_all(&log(
1978            LogFormat::GenericTable,
1979            "Axial accel",
1980            0.01,
1981            |k, t| {
1982                let value = if (2.5..2.65).contains(&t) {
1983                    4.0 * G
1984                } else if (2.65..2.8).contains(&t) {
1985                    -2.0 * G
1986                } else {
1987                    specific_force(t)
1988                };
1989                value + jitter(k, 0.3)
1990            },
1991        ));
1992        let burnout = readings.burnout.value().unwrap();
1993        assert!(!burnout.is_floor, "{burnout:?}");
1994        assert!(
1995            (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1996            "{burnout:?}"
1997        );
1998        // A motor that burns 0.3 s at 6 g, and a canopy's shock at 10 g for 0.4 s at 7 s.
1999        let readings = read_all(&log(
2000            LogFormat::GenericTable,
2001            "Axial accel",
2002            0.01,
2003            |k, t| {
2004                let value = if t < 3.0 {
2005                    G
2006                } else if t < 3.3 {
2007                    6.0 * G
2008                } else if t < 3.4 {
2009                    6.0 * G - 6.6 * G * (t - 3.3) / 0.1
2010                } else if (7.0..7.4).contains(&t) {
2011                    10.0 * G
2012                } else if t < 8.0 {
2013                    -0.6 * G * (8.0 - t) / 4.6
2014                } else {
2015                    G
2016                };
2017                value + jitter(k, 0.3)
2018            },
2019        ));
2020        let top = readings.max_acceleration.value().unwrap();
2021        assert!(
2022            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
2023            "{top:?}"
2024        );
2025        assert!(top.time_s < 3.4, "{top:?}");
2026    }
2027
2028    /// A bump on the pad, wider than the cleaning takes out and higher than the thrust, comes
2029    /// before liftoff's earliest time and isn't the top: a rocket at rest reads 1 g.
2030    #[test]
2031    fn a_bump_on_the_pad_isnt_the_top() {
2032        // A knock to 7 g over 0.3 s at 1 s, two seconds before liftoff.
2033        let readings = read_all(&log(
2034            LogFormat::GenericTable,
2035            "Axial accel",
2036            0.01,
2037            |k, t| {
2038                let value = if (1.0..1.3).contains(&t) {
2039                    G + 6.0 * G * (std::f64::consts::PI * (t - 1.0) / 0.3).sin()
2040                } else {
2041                    specific_force(t)
2042                };
2043                value + jitter(k, 0.3)
2044            },
2045        ));
2046        let top = readings.max_acceleration.value().unwrap();
2047        assert!(
2048            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
2049            "{top:?}"
2050        );
2051        assert!(top.time_s >= 3.0, "{top:?}");
2052        let burnout = readings.burnout.value().unwrap();
2053        assert!(!burnout.is_floor, "{burnout:?}");
2054        assert!(
2055            (burnout.time_s - 4.1).abs() <= burnout.bound_s,
2056            "{burnout:?}"
2057        );
2058    }
2059
2060    /// A count of intervals a few parts in 10¹⁶ short of a tie, as a median interval of 20 Hz
2061    /// float times can be, rounds up as the tie itself does.
2062    #[test]
2063    fn a_window_on_a_tie_rounds_up() {
2064        assert_eq!(half_window(BURNOUT_MEAN_S, 0.05), 1);
2065        assert_eq!(half_window(BURNOUT_MEAN_S, 0.050_000_000_000_000_71), 1);
2066        assert_eq!(half_window(BURNOUT_MEAN_S, 0.01), 3);
2067        assert_eq!(half_window(BURNOUT_MEAN_S, 0.010_000_000_000_000_2), 3);
2068        assert_eq!(half_window(BURNOUT_MEAN_S, 0.002), 13);
2069        assert_eq!(half_window(BURNOUT_MEAN_S, 0.002_000_000_000_000_002), 13);
2070    }
2071
2072    /// A top that reaches the part's range in one sample, with no flat run, is clipped by the
2073    /// range alone: the same trace with no range stated is measured.
2074    #[test]
2075    fn a_top_reaching_the_range_in_one_sample_is_clipped() {
2076        // Peaking at 200 g at 3.5 s, Fluctus's stated range.
2077        let peak = |t: f64| {
2078            if t < 3.0 {
2079                G
2080            } else {
2081                39.8 * (specific_force(t) - G) + G
2082            }
2083        };
2084        let fluctus = read_all(&log(
2085            LogFormat::FluctusCsv,
2086            "vert-accel (m/s2)",
2087            0.01,
2088            |_, t| peak(t),
2089        ));
2090        let top = fluctus.max_acceleration.value().unwrap();
2091        assert_eq!(top.provenance, Provenance::Clipped, "{top:?}");
2092        let unstated = read_all(&log(
2093            LogFormat::GenericTable,
2094            "Axial accel",
2095            0.01,
2096            |_, t| peak(t),
2097        ));
2098        let top = unstated.max_acceleration.value().unwrap();
2099        assert_eq!(top.provenance, Provenance::Measured, "{top:?}");
2100    }
2101
2102    /// Burnout's refusals, each by its own words: a coast that never climbs back from its least
2103    /// before apogee, and a least too near zero to tell from the noise.
2104    #[test]
2105    fn burnout_refuses_a_coast_it_cant_tell() {
2106        let dt = 0.01;
2107        let time: Vec<f64> = (0..=790).map(|i| f64::from(i) * dt).collect();
2108        let try_burnout = |drag_g: f64, back: bool| {
2109            let f: Vec<f64> = time
2110                .iter()
2111                .enumerate()
2112                .map(|(k, &t)| {
2113                    let coast = if back && t >= 7.5 { G } else { -drag_g * G };
2114                    (if t < 4.0 { specific_force(t) } else { coast }) + jitter(k, 0.3)
2115                })
2116                .collect();
2117            let mean = running_mean(&f, half_window(BURNOUT_MEAN_S, dt));
2118            let top = (0..f.len()).max_by(|a, b| f[*a].total_cmp(&f[*b])).unwrap();
2119            burnout(&time, &f, &mean, time.len() - 1, top, 0.0, dt)
2120        };
2121        // A steady drag to the log's end: no climb back.
2122        let error = try_burnout(0.6, false).unwrap_err();
2123        assert!(error.contains("doesn't climb"), "{error}");
2124        // A drag of 0.02 g, then the canopy's 1 g: back, but the least is within 3N of zero.
2125        let error = try_burnout(0.02, true).unwrap_err();
2126        assert!(error.contains("too little drag"), "{error}");
2127        // The same at 0.6 g reads.
2128        assert!(try_burnout(0.6, true).is_ok());
2129    }
2130
2131    /// Three traces that show no thrust, each withheld as [`Reason::DirectionUnstated`], burnout
2132    /// falling back to the top speed's floor, the words saying why. One reads 1 g throughout: it
2133    /// never moves from its pad, so neither the pad nor the coast after a thrust says, and nor
2134    /// does the thrust. One passes 2 g both ways up and never holds there for [`BURN_LEAST_S`],
2135    /// so the thrust says nothing, and its pad's 1 g, nose up, and its coast's 1 g, nose down,
2136    /// disagree. One dips on the pad, so its pad's 1 g says nose up, then pushes at 1.8 g: so
2137    /// turned, the trace never passes 2 g, as a rocket leaving the pad does.
2138    #[test]
2139    fn a_trace_that_shows_no_thrust_either_way_up_is_withheld() {
2140        let pulse = |t: f64, at: f64| {
2141            if (at..at + 0.2).contains(&t) {
2142                4.0 * G
2143            } else {
2144                0.0
2145            }
2146        };
2147        let weak = |t: f64| {
2148            if (1.0..1.3).contains(&t) {
2149                -3.0 * G
2150            } else if t < 3.0 {
2151                G
2152            } else if t < 4.5 {
2153                1.8 * G
2154            } else if t < 8.0 {
2155                -0.2 * G * (8.0 - t) / 3.5
2156            } else {
2157                G
2158            }
2159        };
2160        for (case, words, trace) in [
2161            (
2162                "flat",
2163                "none of them says",
2164                Box::new(|_: f64| G) as Box<dyn Fn(f64) -> f64>,
2165            ),
2166            (
2167                "both ways",
2168                "which says nose down",
2169                // 5 g for 0.2 s in the thrust, then −5 g for 0.2 s in the coast.
2170                Box::new(move |t: f64| G + pulse(t, 3.4) - 1.5 * pulse(t, 5.0)),
2171            ),
2172            ("weak", "shows no thrust", Box::new(weak)),
2173        ] {
2174            let readings = read_all(&log(
2175                LogFormat::GenericTable,
2176                "Axial accel",
2177                0.01,
2178                |k, t| trace(t) + jitter(k, 0.3),
2179            ));
2180            let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2181                panic!("{case}: {:?}", readings.max_acceleration);
2182            };
2183            assert_eq!(*reason, Reason::DirectionUnstated, "{case}");
2184            assert!(detail.contains(words), "{case}: {detail}");
2185            let burnout = readings.burnout.value().unwrap();
2186            assert_eq!(burnout.method, Method::SpeedPeak, "{case}");
2187            assert!(burnout.is_floor, "{case}");
2188        }
2189    }
2190
2191    /// A dip on the pad, to −3 g over 0.3 s at 1 s, doesn't turn the trace over: it comes before
2192    /// liftoff's earliest time, so the thrust, which holds past 2 g for [`BURN_LEAST_S`], says
2193    /// nose up, as the pad's 1 g does on a column that holds gravity and the coast's −1 g on
2194    /// AltOS's, which takes it out. The top and burnout are the thrust's.
2195    #[test]
2196    fn a_dip_on_the_pad_doesnt_turn_the_trace_over() {
2197        let dipped = |t: f64| {
2198            if (1.0..1.3).contains(&t) {
2199                G - 4.0 * G * (std::f64::consts::PI * (t - 1.0) / 0.3).sin()
2200            } else {
2201                specific_force(t)
2202            }
2203        };
2204        for (format, column, out_m_s2) in [
2205            (LogFormat::GenericTable, "Axial accel", 0.0),
2206            (LogFormat::AltosCsv, "acceleration", G),
2207        ] {
2208            let readings = read_all(&log(format, column, 0.01, |k, t| {
2209                dipped(t) - out_m_s2 + jitter(k, 0.3)
2210            }));
2211            let accelerometer = readings.accelerometer.as_ref().unwrap();
2212            assert!(!accelerometer.turned_over, "{column}: {accelerometer:?}");
2213            let top = readings.max_acceleration.value().unwrap();
2214            assert!(
2215                (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
2216                "{column}: {top:?}"
2217            );
2218            assert!((top.time_s - 3.5).abs() < 0.1, "{column}: {top:?}");
2219            let burnout = readings.burnout.value().unwrap();
2220            assert_eq!(burnout.method, Method::LeastAfterThrust, "{column}");
2221            assert!(
2222                (burnout.time_s - 4.1).abs() <= burnout.bound_s,
2223                "{column}: {burnout:?}"
2224            );
2225        }
2226    }
2227
2228    /// A knock on the pad with its rebound first, −2.5 g for 0.15 s at 2.5 s and then 4 g for
2229    /// 0.15 s, inside liftoff's bound: the rebound comes before the thrust's span, so the thrust
2230    /// says nothing, and the pad's 1 g says nose up. The trace isn't turned over, and the top and
2231    /// burnout are the thrust's, neither before liftoff's earliest time.
2232    #[test]
2233    fn a_knock_with_its_rebound_first_doesnt_turn_the_trace_over() {
2234        let readings = read_all(&log(
2235            LogFormat::GenericTable,
2236            "Axial accel",
2237            0.01,
2238            |k, t| {
2239                let value = if (2.5..2.65).contains(&t) {
2240                    -2.5 * G
2241                } else if (2.65..2.8).contains(&t) {
2242                    4.0 * G
2243                } else {
2244                    specific_force(t)
2245                };
2246                value + jitter(k, 0.3)
2247            },
2248        ));
2249        assert!(!readings.accelerometer.as_ref().unwrap().turned_over);
2250        let liftoff = readings.liftoff.value().unwrap();
2251        let earliest = liftoff.time_s - liftoff.bound_s;
2252        let top = readings.max_acceleration.value().unwrap();
2253        assert!(
2254            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
2255            "{top:?}"
2256        );
2257        assert!(top.time_s >= earliest.max(3.0), "{top:?}, {liftoff:?}");
2258        let burnout = readings.burnout.value().unwrap();
2259        assert_eq!(burnout.method, Method::LeastAfterThrust, "{burnout:?}");
2260        assert!(
2261            (burnout.time_s - 4.1).abs() <= burnout.bound_s,
2262            "{burnout:?}"
2263        );
2264        assert!(burnout.time_s >= earliest, "{burnout:?}, {liftoff:?}");
2265        assert!(
2266            burnout
2267                .time_after_liftoff_s
2268                .is_some_and(|after| after > 0.0),
2269            "{burnout:?}"
2270        );
2271    }
2272
2273    /// A short burn, 40 g from 3.0 s to 3.3 s, then a heavy drag, −8 g easing to −2.9 g by 4.5 s
2274    /// and to nothing by 6 s, gravity in: the specific force along the axis, nose up.
2275    fn short_burn(t: f64) -> f64 {
2276        if t < 3.0 {
2277            G
2278        } else if t < 3.3 {
2279            40.0 * G
2280        } else if t < 4.5 {
2281            -8.0 * G + 5.1 * G * (t - 3.3) / 1.2
2282        } else if t < 6.0 {
2283            -2.9 * G * (6.0 - t) / 1.5
2284        } else if t < 8.0 {
2285            0.0
2286        } else {
2287            G
2288        }
2289    }
2290
2291    /// A short burn before a heavy drag ([`short_burn`]): the drag's span holds past 2 g for
2292    /// [`BURN_LEAST_S`] and the burn's doesn't, but the burn's comes first, so the thrust says
2293    /// nothing; the pad, at 1 g, says nose up where gravity is in, and the top is the burn's
2294    /// 40 g, not the drag's. Where AltOS takes gravity out, its pad's 0 says nothing and the
2295    /// coast's −1 g alone settles nothing: withheld, never turned over.
2296    #[test]
2297    fn a_short_burn_before_a_heavy_drag_reads_nose_up() {
2298        let without = read_all(&log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2299            short_burn(t) - G + jitter(k, 0.3)
2300        }));
2301        let Reading::Withheld(Withheld { reason, detail }) = &without.max_acceleration else {
2302            panic!("{:?}", without.max_acceleration);
2303        };
2304        assert_eq!(*reason, Reason::DirectionUnstated);
2305        assert!(detail.contains("the coast alone says"), "{detail}");
2306        let (format, column, out_m_s2) = (LogFormat::GenericTable, "Axial accel", 0.0);
2307        let readings = read_all(&log(format, column, 0.01, |k, t| {
2308            short_burn(t) - out_m_s2 + jitter(k, 0.3)
2309        }));
2310        let accelerometer = readings.accelerometer.as_ref();
2311        assert!(
2312            accelerometer.is_some_and(|a| !a.turned_over),
2313            "{column}: {accelerometer:?}, {:?}",
2314            readings.max_acceleration
2315        );
2316        let top = readings.max_acceleration.value().unwrap();
2317        assert!(
2318            (top.acceleration_m_s2 - 40.0 * G).abs() <= top.bound_m_s2,
2319            "{column}: {top:?}"
2320        );
2321        assert!((3.0..3.3).contains(&top.time_s), "{column}: {top:?}");
2322        assert_eq!(top.provenance, Provenance::Measured, "{column}");
2323        assert!(!top.is_floor, "{column}: {top:?}");
2324        let burnout = readings.burnout.value().unwrap();
2325        assert!(
2326            (burnout.time_s - 3.3).abs() <= burnout.bound_s,
2327            "{column}: {burnout:?}"
2328        );
2329    }
2330
2331    /// The same short burn and drag on a part mounted nose down: the pad's −1 g says so where
2332    /// gravity is in, and the top is the burn's 40 g. Where gravity is out, the coast's +1 g
2333    /// alone settles nothing: withheld.
2334    #[test]
2335    fn a_short_burn_read_nose_down_reads_alike() {
2336        let without = read_all(&log(
2337            LogFormat::GenericTable,
2338            "Axial accel",
2339            0.01,
2340            |k, t| -(short_burn(t) - G) + jitter(k, 0.3),
2341        ));
2342        assert_eq!(
2343            without.max_acceleration.reason(),
2344            Some(Reason::DirectionUnstated)
2345        );
2346        let out_m_s2 = 0.0;
2347        let readings = read_all(&log(
2348            LogFormat::GenericTable,
2349            "Axial accel",
2350            0.01,
2351            |k, t| -(short_burn(t) - out_m_s2) + jitter(k, 0.3),
2352        ));
2353        let accelerometer = readings.accelerometer.as_ref();
2354        assert!(
2355            accelerometer.is_some_and(|a| a.turned_over),
2356            "out {out_m_s2}: {accelerometer:?}, {:?}",
2357            readings.max_acceleration
2358        );
2359        let top = readings.max_acceleration.value().unwrap();
2360        assert!(
2361            (top.acceleration_m_s2 - 40.0 * G).abs() <= top.bound_m_s2,
2362            "out {out_m_s2}: {top:?}"
2363        );
2364        assert!(!top.is_floor, "out {out_m_s2}: {top:?}");
2365    }
2366
2367    /// A pad that reads 1 g, nose up with gravity in, before a thrust that reads −6 g, nose
2368    /// down: the witnesses disagree, so the top and the accelerometer's burnout are withheld,
2369    /// the words naming each witness, and burnout comes from the top speed.
2370    #[test]
2371    fn a_pad_that_disagrees_with_the_thrust_is_withheld() {
2372        let readings = read_all(&log(
2373            LogFormat::GenericTable,
2374            "Axial accel",
2375            0.01,
2376            |k, t| if t < 3.0 { G } else { -specific_force(t) } + jitter(k, 0.3),
2377        ));
2378        let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2379            panic!("{:?}", readings.max_acceleration);
2380        };
2381        assert_eq!(*reason, Reason::DirectionUnstated);
2382        for words in [
2383            "its pad reads 1.00 g as written, which says nose up",
2384            "its coast to apogee reads",
2385            "its thrust says nose down",
2386            "they disagree",
2387        ] {
2388            assert!(detail.contains(words), "{words}: {detail}");
2389        }
2390        assert!(readings.accelerometer.is_none());
2391        let burnout = readings.burnout.value().unwrap();
2392        assert_eq!(burnout.method, Method::SpeedPeak);
2393        assert!(burnout.is_floor);
2394    }
2395
2396    /// A thrust of 2.5 g, a thrust-to-weight of about 2.5, on AltOS, which takes gravity out:
2397    /// as written it reads 1.5 g, under 2 g, so the thrust says nothing, and the pad's 0 says
2398    /// nothing either; the coast's −1 g, less the drag, says nose up, but a coast alone settles
2399    /// nothing: withheld. Where the drag after burnout is heavy, −1.5 g, it reads past −2 g for
2400    /// over [`BURN_LEAST_S`] as written, but rises after liftoff's latest time, so it isn't the
2401    /// thrust and says nothing: withheld again. Never turned over.
2402    #[test]
2403    fn a_weak_thrust_without_gravity_is_withheld_not_turned() {
2404        let weak = |drag_g: f64| {
2405            move |t: f64| {
2406                if t < 3.0 {
2407                    G
2408                } else if t < 4.5 {
2409                    2.5 * G
2410                } else if t < 8.0 {
2411                    -drag_g * G * (8.0 - t) / 3.5
2412                } else {
2413                    G
2414                }
2415            }
2416        };
2417        let light = weak(0.4);
2418        let readings = read_all(&log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2419            light(t) - G + jitter(k, 0.3)
2420        }));
2421        let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2422            panic!("{:?}", readings.max_acceleration);
2423        };
2424        assert_eq!(*reason, Reason::DirectionUnstated);
2425        assert!(detail.contains("which says nose up"), "{detail}");
2426        assert!(detail.contains("the coast alone says"), "{detail}");
2427        let burnout = readings.burnout.value().unwrap();
2428        assert_eq!(burnout.method, Method::SpeedPeak, "{burnout:?}");
2429        assert!(burnout.is_floor);
2430        let heavy = weak(1.5);
2431        let readings = read_all(&log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2432            heavy(t) - G + jitter(k, 0.3)
2433        }));
2434        let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2435            panic!("{:?}", readings.max_acceleration);
2436        };
2437        assert_eq!(*reason, Reason::DirectionUnstated);
2438        assert!(detail.contains("which says nose up"), "{detail}");
2439        assert!(
2440            detail.contains("rises after liftoff's latest time"),
2441            "{detail}"
2442        );
2443        assert!(detail.contains("the coast alone says"), "{detail}");
2444    }
2445
2446    /// A thrust of 2.5 g on AltOS, which takes gravity out, reads 1.5 g as written, under 2 g;
2447    /// the drag after it, 1.5 g easing to apogee, reads past −2 g as written for over
2448    /// [`BURN_LEAST_S`]. With the log cut short of apogee no coast is read, and the pad's 0 says
2449    /// nothing, so were the drag taken for the thrust the trace would be turned over and the
2450    /// drag read as a 3.5 g top: its span rises after liftoff's latest time, so it says
2451    /// nothing, and the top is withheld at every cut, never turned over.
2452    #[test]
2453    fn a_drag_after_a_weak_thrust_isnt_the_thrust() {
2454        let weak = |t: f64| {
2455            if t < 3.0 {
2456                G
2457            } else if t < 4.5 {
2458                2.5 * G
2459            } else if t < 8.0 {
2460                -1.5 * G * (8.0 - t) / 3.5
2461            } else {
2462                G
2463            }
2464        };
2465        for end_s in [5.6, 6.5, 7.0, 7.5] {
2466            let mut log = log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2467                weak(t) - G + jitter(k, 0.3)
2468            });
2469            let cut = |time_s: &[f64]| time_s.partition_point(|t| *t <= end_s + 1e-9);
2470            let channel = &mut log.channels[0];
2471            let kept = cut(&channel.time_s);
2472            channel.time_s.truncate(kept);
2473            channel.values.truncate(kept);
2474            let kept = cut(&log.time_s);
2475            log.time_s.truncate(kept);
2476            log.altitude_m.truncate(kept);
2477            let readings = read_all(&log);
2478            assert_eq!(
2479                readings.max_acceleration.reason(),
2480                Some(Reason::DirectionUnstated),
2481                "to {end_s} s: {:?}",
2482                readings.max_acceleration
2483            );
2484        }
2485    }
2486
2487    /// AltOS's `acceleration` from a board with no accelerometer, an EasyMini's, is its
2488    /// barometer's estimate: with neither a GPS receiver's column nor an inertial unit's beside
2489    /// it, no top or burnout is read from it, and burnout comes from the top speed. Either column
2490    /// makes it a sensor's.
2491    #[test]
2492    fn altos_acceleration_without_an_accelerometer_board_isnt_read() {
2493        let sensor = log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2494            specific_force(t) - G + jitter(k, 0.3)
2495        });
2496        assert!(read_all(&sensor).max_acceleration.value().is_some());
2497        let mut barometer = sensor.clone();
2498        barometer
2499            .channels
2500            .retain(|channel| channel.column != "latitude");
2501        let readings = read_all(&barometer);
2502        let Reading::Withheld(withheld) = &readings.max_acceleration else {
2503            panic!("{:?}", readings.max_acceleration);
2504        };
2505        assert_eq!(withheld.reason, Reason::NoAccelerometer);
2506        assert!(
2507            withheld.detail.contains("estimate from its barometer"),
2508            "{withheld:?}"
2509        );
2510        assert!(readings.accelerometer.is_none());
2511        let burnout = readings.burnout.value().expect("from the top speed");
2512        assert_eq!(burnout.method, Method::SpeedPeak, "{burnout:?}");
2513        let mut inertial = barometer.clone();
2514        let (time_s, values) = (inertial.time_s.clone(), vec![9.8; inertial.time_s.len()]);
2515        inertial.channels.push(Channel::new(
2516            "accel_x",
2517            Quantity::Acceleration,
2518            time_s,
2519            values,
2520        ));
2521        assert!(read_all(&inertial).max_acceleration.value().is_some());
2522        // A receiver with no fix leaves its column all gaps: still a TeleMetrum's.
2523        let mut unfixed = sensor.clone();
2524        for channel in &mut unfixed.channels {
2525            if channel.column == "latitude" {
2526                channel.values.fill(f64::NAN);
2527            }
2528        }
2529        assert!(read_all(&unfixed).max_acceleration.value().is_some());
2530    }
2531
2532    /// A log that starts in the thrust, past its 6 g top at 3.5 s: from 3.6 s the trace is
2533    /// already past 2 g at its first sample, so the thrust began before the log and its top may
2534    /// have come earlier, as it did: the top read is a floor, the truth no lower than it less
2535    /// its bound. So on AltOS with the whole log cut, liftoff withheld, and on a column that
2536    /// holds gravity with only the accelerometer cut, liftoff read by the heights.
2537    #[test]
2538    fn a_log_that_starts_in_the_thrust_gives_its_top_as_a_floor() {
2539        for (format, column, out_m_s2, whole) in [
2540            (LogFormat::AltosCsv, "acceleration", G, true),
2541            (LogFormat::GenericTable, "Axial accel", 0.0, false),
2542        ] {
2543            let mut log = log(format, column, 0.01, |k, t| {
2544                specific_force(t) - out_m_s2 + jitter(k, 0.3)
2545            });
2546            let from = |time_s: &[f64]| time_s.partition_point(|t| *t < 3.6);
2547            let channel = &mut log.channels[0];
2548            let cut = from(&channel.time_s);
2549            channel.time_s.drain(..cut);
2550            channel.values.drain(..cut);
2551            if whole {
2552                let cut = from(&log.time_s);
2553                log.time_s.drain(..cut);
2554                log.altitude_m.drain(..cut);
2555            }
2556            let readings = read_all(&log);
2557            let top = readings.max_acceleration.value();
2558            let top = top.unwrap_or_else(|| panic!("{column}: {:?}", readings.max_acceleration));
2559            assert!(top.is_floor, "{column}: {top:?}");
2560            assert_eq!(top.clip, None, "{column}");
2561            assert!(
2562                top.acceleration_m_s2 - top.bound_m_s2 <= 6.0 * G,
2563                "{column}: {top:?}"
2564            );
2565            // Not clipped, so no set tests a lower end on it: it states neither.
2566            assert!(top.lower_end_m_s2.is_none(), "{column}");
2567            assert!(top.interval_m_s2.is_none(), "{column}");
2568        }
2569    }
2570
2571    /// A log whose liftoff is withheld, as one that starts in the climb has it: its thrust's
2572    /// span, at its start, may be a drag where the log starts after burnout, so it settles the
2573    /// way only with the coast beside it. On AltOS, which takes gravity out, a log from 3.35 s,
2574    /// after liftoff, reads its 6 g top at 3.5 s nose up, its coast agreeing; logs that
2575    /// start at 4.6 s, after burnout, their drag at their start (a 2.5 g thrust's to apogee, or
2576    /// a 6 g thrust's cut at 7 s), are withheld, never turned over.
2577    #[test]
2578    fn a_thrust_at_a_log_start_settles_only_beside_the_coast() {
2579        let trimmed = |trace: &dyn Fn(f64) -> f64, dt: f64, from_s: f64, to_s: f64| {
2580            let mut log = log(LogFormat::AltosCsv, "acceleration", dt, |k, t| {
2581                trace(t) - G + jitter(k, 0.3)
2582            });
2583            let keep = |time_s: &[f64]| {
2584                (
2585                    time_s.partition_point(|t| *t < from_s - 1e-9),
2586                    time_s.partition_point(|t| *t <= to_s + 1e-9),
2587                )
2588            };
2589            let channel = &mut log.channels[0];
2590            let (a, b) = keep(&channel.time_s);
2591            channel.time_s = channel.time_s[a..b].to_vec();
2592            channel.values = channel.values[a..b].to_vec();
2593            let (a, b) = keep(&log.time_s);
2594            log.time_s = log.time_s[a..b].to_vec();
2595            log.altitude_m = log.altitude_m[a..b].to_vec();
2596            read_all(&log)
2597        };
2598        let started = trimmed(&specific_force, 0.01, 3.35, f64::INFINITY);
2599        assert!(started.liftoff.reason().is_some(), "{:?}", started.liftoff);
2600        let accelerometer = started.accelerometer.as_ref();
2601        assert!(
2602            accelerometer.is_some_and(|a| !a.turned_over),
2603            "{accelerometer:?}, {:?}",
2604            started.max_acceleration
2605        );
2606        let top = started.max_acceleration.value().unwrap();
2607        assert!(
2608            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
2609            "{top:?}"
2610        );
2611        let weak = |t: f64| {
2612            if t < 3.0 {
2613                G
2614            } else if t < 4.5 {
2615                2.5 * G
2616            } else if t < 8.0 {
2617                -1.5 * G * (8.0 - t) / 3.5
2618            } else {
2619                G
2620            }
2621        };
2622        let strong = |t: f64| {
2623            if t < 3.0 {
2624                G
2625            } else if t < 4.5 {
2626                6.0 * G
2627            } else if t < 8.0 {
2628                -3.0 * G * (8.0 - t) / 3.5
2629            } else {
2630                G
2631            }
2632        };
2633        for (case, readings) in [
2634            ("weak, 0.01 s", trimmed(&weak, 0.01, 4.6, f64::INFINITY)),
2635            ("weak, 0.02 s", trimmed(&weak, 0.02, 4.6, f64::INFINITY)),
2636            ("weak, 0.05 s", trimmed(&weak, 0.05, 4.6, f64::INFINITY)),
2637            ("weak, to 6.5 s", trimmed(&weak, 0.01, 4.6, 6.5)),
2638            ("strong, to 7 s", trimmed(&strong, 0.01, 4.6, 7.0)),
2639        ] {
2640            assert!(
2641                readings.max_acceleration.value().is_none()
2642                    && readings
2643                        .accelerometer
2644                        .as_ref()
2645                        .is_none_or(|a| !a.turned_over),
2646                "{case}: {:?}, {:?}",
2647                readings.accelerometer,
2648                readings.max_acceleration
2649            );
2650        }
2651    }
2652
2653    /// A coast alone settles nothing, as its second can hold what reads the other way: on a
2654    /// part that holds gravity, nose up on a pad tilted to read 0.5 g, which says nothing, a
2655    /// 40 g burn of 0.3 s before a heavy drag leaves the thrust saying nothing, and a canopy
2656    /// opened early reads 1 g through the coast's second; on AltOS, which takes gravity out, a
2657    /// 2.5 g thrust, under 2 g as written, still burns into that second. Either coast says nose
2658    /// down; both are withheld, never turned over.
2659    #[test]
2660    fn a_lone_coast_settles_nothing() {
2661        let canopy = |t: f64| {
2662            if t < 3.0 {
2663                0.5 * G
2664            } else if t < 3.3 {
2665                40.0 * G
2666            } else if t < 4.5 {
2667                -8.0 * G + 5.1 * G * (t - 3.3) / 1.2
2668            } else if t < 6.0 {
2669                -2.9 * G * (6.0 - t) / 1.5
2670            } else {
2671                G
2672            }
2673        };
2674        let burning = |t: f64| {
2675            if t < 3.0 {
2676                G
2677            } else if t < 7.5 {
2678                2.5 * G
2679            } else if t < 8.0 {
2680                -0.3 * G
2681            } else {
2682                G
2683            }
2684        };
2685        for (case, readings) in [
2686            (
2687                "a canopy opened early",
2688                read_all(&log(
2689                    LogFormat::GenericTable,
2690                    "Axial accel",
2691                    0.01,
2692                    |k, t| canopy(t) + jitter(k, 0.3),
2693                )),
2694            ),
2695            (
2696                "a thrust still burning",
2697                read_all(&log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2698                    burning(t) - G + jitter(k, 0.3)
2699                })),
2700            ),
2701        ] {
2702            let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2703                panic!("{case}: {:?}", readings.max_acceleration);
2704            };
2705            assert_eq!(*reason, Reason::DirectionUnstated, "{case}");
2706            assert!(detail.contains("the coast alone says"), "{case}: {detail}");
2707        }
2708    }
2709
2710    /// An accelerometer whose clock runs late against the heights', its thrust starting at 7.6 s
2711    /// where the heights put apogee at 8 s: the second before apogee's earliest time is still its
2712    /// pad, at 1 g, and comes before the trace first moves, so it isn't read as a coast, which
2713    /// would say nose down. Its thrust rises after liftoff's latest time by the heights, so it
2714    /// isn't the thrust that lifted the rocket on their clock and says nothing either: withheld,
2715    /// never turned over.
2716    #[test]
2717    fn a_coast_before_the_trace_moves_says_nothing() {
2718        let readings = read_all(&log(
2719            LogFormat::EntacoreAimCsv,
2720            "acceleration",
2721            0.01,
2722            |k, t| if t < 7.6 { G } else { 6.0 * G } + jitter(k, 0.3),
2723        ));
2724        let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2725            panic!("{:?}", readings.max_acceleration);
2726        };
2727        assert_eq!(*reason, Reason::DirectionUnstated);
2728        assert!(detail.contains("no coast to apogee is read"), "{detail}");
2729        assert!(
2730            detail.contains("rises after liftoff's latest time"),
2731            "{detail}"
2732        );
2733    }
2734
2735    /// The thrust's witness, each way it says or doesn't, on traces sampled every 0.01 s: a held
2736    /// span with nothing the other way before it says its way; one after a span the other way
2737    /// says nothing; with none held, spans one way say it and spans both ways or none nothing;
2738    /// a span before liftoff's earliest time isn't searched.
2739    #[test]
2740    fn the_thrust_witness_says_its_way_or_nothing() {
2741        let dt = 0.01;
2742        let time: Vec<f64> = (0..=600).map(|i| f64::from(i) * dt).collect();
2743        let witness = |from_s: f64, trace: &dyn Fn(f64) -> f64| {
2744            let clean: Vec<f64> = time.iter().map(|t| trace(*t)).collect();
2745            let from = time.partition_point(|t| *t < from_s);
2746            thrust_witness(
2747                &time,
2748                &clean,
2749                from,
2750                time.len() - 1,
2751                half_window(BURNOUT_MEAN_S, dt),
2752                dt,
2753                (1.2, "liftoff's latest time", true),
2754            )
2755        };
2756        // A pulse of `g` g from `at` s for `long` s.
2757        let pulse = |t: f64, at: f64, long: f64, g: f64| {
2758            if (at..at + long).contains(&t) {
2759                g * G
2760            } else {
2761                0.0
2762            }
2763        };
2764        let thrust = move |t: f64| G + pulse(t, 1.0, 1.0, 4.0) - pulse(t, 2.0, 2.0, 1.5);
2765        let short_then_drag = move |t: f64| pulse(t, 1.0, 0.3, 40.0) - pulse(t, 1.3, 1.0, 8.0);
2766        let short = move |t: f64| pulse(t, 1.0, 0.3, 6.0) - pulse(t, 1.3, 2.0, 0.5);
2767        let both = move |t: f64| pulse(t, 1.0, 0.2, 5.0) - pulse(t, 3.0, 0.2, 5.0);
2768        let knocked = move |t: f64| -pulse(t, 0.5, 0.15, 3.5) + thrust(t);
2769        // A case's name, liftoff's earliest time, its trace, the way it says and its words.
2770        type Case<'a> = (&'a str, f64, &'a dyn Fn(f64) -> f64, Option<Way>, &'a str);
2771        let cases: [Case; 9] = [
2772            ("held", 0.0, &thrust, Some(Way::Up), "to hold there"),
2773            (
2774                "held, down",
2775                0.0,
2776                &|t| -thrust(t),
2777                Some(Way::Down),
2778                "to hold",
2779            ),
2780            (
2781                "drag after a short burn",
2782                0.0,
2783                &short_then_drag,
2784                None,
2785                "comes after one nose up",
2786            ),
2787            (
2788                "mirrored",
2789                0.0,
2790                &|t| -short_then_drag(t),
2791                None,
2792                "comes after one nose down",
2793            ),
2794            ("short only", 0.0, &short, Some(Way::Up), "1 span reads so"),
2795            (
2796                "short, down",
2797                0.0,
2798                &|t| -short(t),
2799                Some(Way::Down),
2800                "1 span reads so",
2801            ),
2802            ("both ways", 0.0, &both, None, "both ways up"),
2803            ("flat", 0.0, &|_| G, None, "never reads past"),
2804            (
2805                "knock before the search",
2806                0.8,
2807                &knocked,
2808                Some(Way::Up),
2809                "from 1.00 s",
2810            ),
2811        ];
2812        for (case, from_s, trace, way, words) in cases {
2813            let said = witness(from_s, trace);
2814            assert_eq!(said.way, way, "{case}: {said:?}");
2815            assert!(said.words.contains(words), "{case}: {said:?}");
2816        }
2817        // The knock searched: its rebound comes before the thrust, which then says nothing.
2818        assert_eq!(witness(0.0, &knocked).way, None);
2819        // A thrust under 2 g as written, then a drag that holds past 2 g the other way: the
2820        // drag's span rises after liftoff's latest time, 1.2 s here, so it says nothing.
2821        let weak_then_drag = move |t: f64| pulse(t, 1.0, 1.5, 1.5) - pulse(t, 2.5, 1.5, 2.5);
2822        let said = witness(0.0, &weak_then_drag);
2823        assert_eq!(said.way, None, "{said:?}");
2824        assert!(
2825            said.words
2826                .contains("from 2.50 s, rises after liftoff's latest time, 1.20 s"),
2827            "{said:?}"
2828        );
2829        // With liftoff withheld, as a log that starts in the climb has it, the thrust's span
2830        // rises within 0.5 s of the log's start or says nothing.
2831        let started = |at_s: f64| {
2832            let clean: Vec<f64> = time.iter().map(|t| thrust(*t + 1.0 - at_s)).collect();
2833            thrust_witness(
2834                &time,
2835                &clean,
2836                0,
2837                time.len() - 1,
2838                half_window(BURNOUT_MEAN_S, dt),
2839                dt,
2840                (
2841                    BURN_LEAST_S,
2842                    "the log's start by 0.5 s, liftoff withheld",
2843                    false,
2844                ),
2845            )
2846        };
2847        assert_eq!(started(0.2).way, Some(Way::Up), "{:?}", started(0.2));
2848        let late = started(1.0);
2849        assert_eq!(late.way, None, "{late:?}");
2850        assert!(
2851            late.words
2852                .contains("rises after the log's start by 0.5 s, liftoff withheld"),
2853            "{late:?}"
2854        );
2855    }
2856
2857    /// The pad and the coast say by their levels as written, each within 0.25 g: the pad 1 g
2858    /// nose up, −1 g nose down, 0 nothing; the coast −0.75 g or less nose up, 0.75 g or more
2859    /// nose down, a drag only pushing it further. Settled when the pad or the thrust says and
2860    /// none disagrees; the coast alone settles nothing, but can disagree.
2861    #[test]
2862    fn the_pad_and_the_coast_say_by_their_levels() {
2863        let silent = ThrustWitness {
2864            way: None,
2865            words: "its thrust says neither".to_owned(),
2866            alone: true,
2867        };
2868        let up = ThrustWitness {
2869            way: Some(Way::Up),
2870            words: "its thrust says nose up".to_owned(),
2871            alone: true,
2872        };
2873        let down = ThrustWitness {
2874            way: Some(Way::Down),
2875            words: "its thrust says nose down".to_owned(),
2876            alone: true,
2877        };
2878        let way = |pad: Option<f64>, coast: Option<f64>, thrust: &ThrustWitness| {
2879            direction(pad.map(|g| g * G), coast.map(|g| g * G), thrust).map(|(way, _)| way)
2880        };
2881        assert_eq!(way(Some(1.0), None, &silent), Ok(Way::Up));
2882        assert_eq!(way(Some(1.24), None, &silent), Ok(Way::Up));
2883        assert_eq!(way(Some(-1.0), None, &silent), Ok(Way::Down));
2884        assert!(way(Some(1.26), None, &silent).is_err());
2885        assert!(way(Some(0.0), None, &silent).is_err());
2886        for coast in [-1.0, -0.76, -3.0, 1.3, -0.74, 0.0] {
2887            assert!(way(None, Some(coast), &silent).is_err(), "{coast}");
2888        }
2889        assert!(
2890            direction(None, Some(-G), &silent)
2891                .unwrap_err()
2892                .ends_with("So the coast doesn't settle which way up it reads on its own"),
2893        );
2894        assert_eq!(way(None, Some(-1.0), &up), Ok(Way::Up));
2895        assert_eq!(way(None, Some(-0.76), &up), Ok(Way::Up));
2896        assert_eq!(way(None, Some(-3.0), &up), Ok(Way::Up));
2897        assert!(way(None, Some(-0.76), &down).is_err());
2898        assert_eq!(way(None, Some(-0.74), &down), Ok(Way::Down));
2899        assert_eq!(way(None, Some(1.3), &down), Ok(Way::Down));
2900        assert!(way(None, Some(0.76), &up).is_err());
2901        assert_eq!(way(None, Some(0.74), &up), Ok(Way::Up));
2902        assert_eq!(way(Some(1.0), Some(-1.0), &silent), Ok(Way::Up));
2903        // A thrust at the start of a log whose liftoff is withheld settles only beside the
2904        // coast, or the pad.
2905        let at_start = ThrustWitness {
2906            way: Some(Way::Up),
2907            words: "its thrust says nose up".to_owned(),
2908            alone: false,
2909        };
2910        assert!(
2911            direction(None, None, &at_start)
2912                .unwrap_err()
2913                .ends_with("without the coast beside it")
2914        );
2915        assert_eq!(way(None, Some(-1.0), &at_start), Ok(Way::Up));
2916        assert!(way(None, Some(1.0), &at_start).is_err());
2917        assert_eq!(way(Some(-1.0), Some(1.0), &silent), Ok(Way::Down));
2918        assert!(way(None, None, &silent).is_err());
2919        assert_eq!(way(None, None, &down), Ok(Way::Down));
2920        assert_eq!(
2921            direction(Some(G), Some(-G), &up),
2922            Ok((Way::Up, vec![WayBy::Pad, WayBy::Coast, WayBy::Thrust]))
2923        );
2924        assert!(way(Some(1.0), Some(1.0), &silent).is_err());
2925        assert!(way(Some(1.0), None, &down).is_err());
2926        assert!(way(None, Some(-1.0), &down).is_err());
2927        // The words say what each witness said, and whether none said or two disagree.
2928        let none = direction(None, None, &silent).unwrap_err();
2929        assert!(none.starts_with("no pad is read to tell by"), "{none}");
2930        assert!(
2931            none.ends_with("none of them says which way up it reads"),
2932            "{none}"
2933        );
2934        let split = direction(Some(G), Some(G), &silent).unwrap_err();
2935        for words in [
2936            "its pad reads 1.00 g as written, which says nose up",
2937            "its coast to apogee reads 1.00 g as written, which says nose down",
2938            "they disagree on which way up it reads",
2939        ] {
2940            assert!(split.contains(words), "{words}: {split}");
2941        }
2942    }
2943
2944    /// An accelerometer that ends in the thrust, still rising from 3 g to 6 g, gives its top as a
2945    /// floor: the thrust never falls through zero on the channel, so the top may have been
2946    /// higher, and burnout isn't read off it. So whether the whole log ends at 3.7 s or only the
2947    /// accelerometer does; and where the whole log ends at 6 s, at 12 g, its apogee a floor at
2948    /// its end: the second before that apogee's earliest time is the thrust's, not a coast, and
2949    /// would say nose down.
2950    #[test]
2951    fn an_accelerometer_that_ends_in_the_thrust_gives_its_top_as_a_floor() {
2952        let rising = |t: f64| {
2953            if t < 3.0 {
2954                G
2955            } else {
2956                3.0 * G + 3.0 * G * (t - 3.0)
2957            }
2958        };
2959        for (end_s, whole) in [(3.7, true), (3.7, false), (6.0, true)] {
2960            let mut log = log(LogFormat::GenericTable, "Axial accel", 0.01, |k, t| {
2961                rising(t) + jitter(k, 0.3)
2962            });
2963            let cut = |time_s: &[f64]| time_s.partition_point(|t| *t <= end_s + 1e-9);
2964            let channel = &mut log.channels[0];
2965            let kept = cut(&channel.time_s);
2966            channel.time_s.truncate(kept);
2967            channel.values.truncate(kept);
2968            if whole {
2969                let kept = cut(&log.time_s);
2970                log.time_s.truncate(kept);
2971                log.altitude_m.truncate(kept);
2972            }
2973            let readings = read_all(&log);
2974            let case = format!("to {end_s} s, whole {whole}");
2975            let top = readings.max_acceleration.value();
2976            let top = top.unwrap_or_else(|| panic!("{case}: {:?}", readings.max_acceleration));
2977            assert!(top.is_floor, "{case}: {top:?}");
2978            assert_eq!(top.provenance, Provenance::Measured, "{case}");
2979            // The reading less its bound lies below the thrust where the channel ends.
2980            assert!(
2981                top.acceleration_m_s2 - top.bound_m_s2 <= rising(end_s),
2982                "{case}: {top:?}"
2983            );
2984            assert!(
2985                readings
2986                    .burnout
2987                    .value()
2988                    .is_none_or(|burnout| burnout.method != Method::LeastAfterThrust),
2989                "{case}: {:?}",
2990                readings.burnout
2991            );
2992        }
2993    }
2994
2995    /// The top's bound holds the jump to the next sample either side: a peak of 10 g, 0.1 s wide,
2996    /// between two samples 0.05 s apart that read 7 g, is within the bound of the reading.
2997    #[test]
2998    fn a_peak_between_two_samples_is_within_the_jump() {
2999        let peaked = |t: f64| {
3000            if (3.0..4.0).contains(&t) {
3001                4.0 * G + 6.0 * G * (1.0 - (t - 3.525).abs() / 0.05).max(0.0)
3002            } else if (4.0..4.1).contains(&t) {
3003                4.0 * G - 4.6 * G * (t - 4.0) / 0.1
3004            } else {
3005                specific_force(t)
3006            }
3007        };
3008        let readings = read_all(&log(
3009            LogFormat::GenericTable,
3010            "Axial accel",
3011            0.05,
3012            |k, t| peaked(t) + jitter(k, 0.3),
3013        ));
3014        let top = readings.max_acceleration.value().unwrap();
3015        assert!(top.acceleration_m_s2 < 7.1 * G, "{top:?}");
3016        assert!(
3017            (top.acceleration_m_s2 - 10.0 * G).abs() <= top.bound_m_s2,
3018            "{top:?}"
3019        );
3020    }
3021
3022    /// A sample with no time, then one that repeats the time before it: the sample with no time
3023    /// is left out, and the repeat with it, as the time it repeats is the last kept.
3024    #[test]
3025    fn a_repeat_after_a_sample_with_no_time_is_left_out() {
3026        let mut log = log(LogFormat::GenericTable, "Axial accel", 0.01, |k, t| {
3027            specific_force(t) + jitter(k, 0.3)
3028        });
3029        let channel = &mut log.channels[0];
3030        let k = channel.time_s.iter().position(|t| *t >= 3.5).unwrap();
3031        let repeated = channel.time_s[k];
3032        channel.time_s.splice(k + 1..k + 1, [f64::NAN, repeated]);
3033        channel.values.splice(k + 1..k + 1, [100.0 * G, 100.0 * G]);
3034        let kept = first_at_each_time(&log.channels[0]);
3035        assert_eq!(kept.time_s.len(), log.channels[0].time_s.len() - 2);
3036        assert!(kept.time_s.iter().all(|t| t.is_finite()));
3037        let readings = read_all(&log);
3038        let top = readings.max_acceleration.value().unwrap();
3039        assert!(
3040            (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
3041            "{top:?}"
3042        );
3043    }
3044
3045    /// The noise of a straight line is 0; of uniform noise, its σ within a few percent.
3046    #[test]
3047    fn the_noise_is_the_scatter_about_the_curve() {
3048        let line: Vec<f64> = (0..100).map(|k| f64::from(k) * 0.5).collect();
3049        assert!(noise(&line).abs() < 1e-12);
3050        let scattered: Vec<f64> = (0..20_000).map(|k| jitter(k, 1.0)).collect();
3051        let sigma = 1.0 / 12.0_f64.sqrt();
3052        // The robust estimate assumes a normal spread; a uniform one's reads 10% under.
3053        assert!(
3054            (noise(&scattered) / sigma - 1.0).abs() < 0.15,
3055            "{}",
3056            noise(&scattered)
3057        );
3058    }
3059}