hpr_flightdata/readings.rs
1//! The readings taken from a flight log on its own: liftoff, apogee, the top speed, the top
2//! acceleration, burnout, landing, the flight time and the descent under each canopy, with no
3//! design file and no simulation.
4//!
5//! Each is a [`Reading`]: a value with where it came from, how it was read and the bound its error
6//! stays within, or [`Reading::Withheld`] with the reason the log can't support it. A reading is
7//! never guessed at; one the log can't support is left out and says why.
8//!
9//! **The track.** Every reading of a height or a time but the accelerometer's comes from one
10//! height track, the first of
11//! these the log holds ([`Source`]): the logger's own barometric altitude (the record's primary
12//! track); a pressure, turned into a height by the 1976 standard atmosphere, as every logger
13//! documented does it (`docs/research/altimeter-height-formulas.md`); a barometric altitude kept
14//! in a channel, above the pad or above sea level; or a GNSS receiver's altitude. A GNSS track
15//! gives no reading: a receiver's filter lags a climb and overshoots its top, and its fix drops
16//! out at liftoff ([`Reason::ReceiverLag`], [`Reason::ReceiverDropout`]).
17//!
18//! **Method.** The track is first filtered by a running median over [`MEDIAN_WINDOW_S`]
19//! ([`crate::filter::running_median`]), which takes out the pressure pulse an ejection charge
20//! punches into a barometric trace. Then:
21//!
22//! - the **climb** is the first filtered sample twice [`LIFTOFF_ALLOWANCE_M`] and the track's step
23//! above where the log starts: the allowance is the most the pad's noise lifts the filtered
24//! track, from below at the start or from above at the climb. One or two of the log's first three
25//! samples that stand more than that rise and three times the noise above the second lowest of
26//! the samples after them are bad, unless the track stays at their level again before a top well above it,
27//! and the readings leave them out;
28//! - the **pad** is the median of the samples to the last within half that of the start before the
29//! climb, or of the last rest before the climb where the track falls to it and it lies more than
30//! the rise from the start, the gap entering the pad's error (#1158). A rocket that leaves the pad
31//! at [`LIFTOFF_ACCELERATION_M_S2`] or more, moving at `v` when the log starts, climbs
32//! `v t + A t²/2` while the track stays near its start, so its samples bound `v`, and with it
33//! how far up the rocket may already be, `v²/(2A)`: that much enters the bounds. Where it could
34//! pass the allowance, the pad is short ([`Reason::ShortPad`]): a track on a zero, the logger's
35//! own or one only a mapping's or a column's word vouches for, reads its heights from that zero,
36//! the zero's possible error entering the bounds, and any other withholds them. A track that is
37//! above the pad only by a word must start within [`PAD_ZERO_M`] of its zero;
38//! - **liftoff** is the last sample before apogee within the pad's allowance: how far the filtered
39//! pad strays from its median, at least [`LIFTOFF_ALLOWANCE_M`], and a step;
40//! - **apogee** is the filtered track's highest value, at the middle of the run of samples that
41//! hold it (the track's step leaves a peak flat for a few samples), unless that top isn't a
42//! coast's ([`Reason::DisturbedTop`]): the track falls below a peak in the last
43//! [`COAST_CHECK_S`] and climbs back to it, or climbs into the top faster than a coast slowing
44//! at twice gravity and falls from it faster than a body at rest there ([`SPIKE_CHECK_S`]), as a
45//! charge's transient does;
46//! - the **top speed** is the highest least-squares slope of the filtered track over
47//! [`SPEED_WINDOW_S`] from liftoff to apogee: a speed HPR Sim derives, withheld where the
48//! barometer's port may read the transonic flow ([`TRANSONIC_SPEED_M_S`]) and refused as
49//! Debrief refuses one ([`IMPLAUSIBLE_SPEED_M_S`], [`ASCENT_NOISE_FRACTION`]);
50//! - **landing** is the first sample after apogee back within the pad's allowance, at least
51//! [`LANDING_HEIGHT_M`], that stays under it and [`LANDED_CEILING_M`]'s margin for
52//! [`LANDED_FOR_S`], and no sooner, give or take a sample, than a fall from rest in vacuum would
53//! lose that height, `√(2h/g)`: drag only slows a fall;
54//! - the **flight time** is landing's time less liftoff's;
55//! - the **descent under each canopy** is read back from landing, as Debrief reads it: the main's
56//! rate near the ground, the run of samples back from landing that stays near it, and its first
57//! sample the main's opening; the drogue's leg from apogee to there, if the descent before it
58//! fell fast enough to tell it apart ([`Descent`], [`Opening`], [M7.2c][m7-2c]);
59//! - the **top acceleration** and **burnout** come from an accelerometer along the rocket's axis
60//! ([`MaxAcceleration`], [`Burnout`]), burnout as a floor from the top speed's time where the
61//! log has none; a log with no accelerometer gives no top acceleration, as differencing a height
62//! twice turns its step into spikes of many g.
63//!
64//! Before any reading, a log must be sampled no slower than [`MAX_INTERVAL_S`] and in steps no
65//! coarser than [`MAX_STEP_M`] (or [`MAX_PRESSURE_STEP_PA`]), the range the bounds were checked
66//! over, on a clock that increases ([`Reason::ClockOutOfOrder`]); and its climb must lose more than
67//! its noise and step in the [`COAST_CHECK_S`] before its top, as a coast does and as a clock in
68//! the wrong unit, such as milliseconds read as seconds, can't.
69//!
70//! **Bounds.** Each reading states the bound its error stays within: the sum of the terms
71//! [`docs/physics/log-readings.md`][page] lists, each from the noise model of HPR Sim's synthetic
72//! flights ([ADR-280] §3) or measured on the log itself. Most of an apogee's bound is the day's
73//! air: a logger converts pressure by the standard atmosphere, so a day [`AIR_TEMPERATURE_SPREAD_K`]
74//! off standard moves its heights by up to [`TEMPERATURE_SHARE`] of themselves. On the synthetic
75//! flights' tuning set, logged at every rate and step from 500 to half a sample a second and from
76//! no step to 100 Pa, their accelerometers at 500, 100 and 20 Hz, and started as loggers that
77//! record from launch start, from 0.3 s before liftoff to 0.5 s after it, every reading given
78//! stayed within its bound (`cargo xtask synthetic`).
79//!
80//! The landing's thresholds and the least climb, [`LIFTOFF_HEIGHT_M`], are Debrief's
81//! (`lib/analyze/index.ts`, MIT, the project owner's own), set on its corpus of flight logs rather
82//! than taken from a published source; the running median in place of Debrief's Hampel filter,
83//! the climb's mark, the pad and its error, the liftoff allowance, the derived speed and the
84//! bounds are HPR Sim's ([ADR-281]); so are burnout's method and the canopies' and the top
85//! acceleration's bounds ([ADR-283]).
86//!
87//! [page]: https://hpr.fusionspace.co/physics/log-readings.html
88//! [ADR-280]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0280-m7-2-in-seven-the-synthetic-flights-first.md
89//! [ADR-281]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0281-readings-on-every-logger.md
90//! [ADR-283]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0283-the-rest-of-the-readings.md
91//! [m7-2c]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m7-2c
92
93use hpr_atmos::Ussa76;
94use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
95use serde::{Deserialize, Serialize};
96use std::collections::VecDeque;
97use std::iter::StepBy;
98use std::ops::Range;
99
100use crate::filter::{median, running_median};
101use crate::log::{Channel, FlightLog, LogFormat, Quantity};
102
103mod accelerometer;
104mod canopies;
105pub mod interval;
106
107pub use accelerometer::{SYNTHETIC_COLUMN, SYNTHETIC_LOWER_RANGE_COLUMN};
108pub use interval::Interval;
109
110/// The running median's span, s: 0.3 s, Debrief's despiking window. Debrief runs a Hampel filter
111/// over it ([`crate::filter::hampel`], threshold 4); HPR Sim takes the plain median (threshold 0). On
112/// the public Pnut log Debrief ships, the ejection charge's pulse peaks at 1,028 ft, against the
113/// 1,009 ft apogee the logger states. The samples around the pulse, a dip before it and a lasting
114/// drop after it, widen its window's spread until the Hampel filter keeps it, and an apogee read
115/// after it is the pulse. After the median it reads 1,010 ft. The median removes any pulse up to
116/// half its window wide, and reads a noise-free peak bent by gravity alone no more than
117/// [`peak_bound_m`] low, 0.077 m at 20 Hz. The Pnut numbers are checked only where the log has been
118/// fetched into `refs/` (it isn't committed); CI checks an invented log of the same shape.
119pub const MEDIAN_WINDOW_S: f64 = 0.3;
120/// The most samples either side of its center the running median takes: the [`MEDIAN_WINDOW_S`]
121/// window at over 6 kHz, far faster than [`MIN_INTERVAL_S`] lets a log be read.
122pub const MAX_MEDIAN_HALF_WINDOW: usize = 1000;
123/// The fastest a log may be sampled, s: the fastest rate the bounds were checked at on the
124/// synthetic flights' tuning set, 500 samples a second, above which the readings are withheld
125/// ([`Reason::SampledTooFast`]). A clock a part in a thousand faster, as a logger's rounding of
126/// its own clock may be, still reads.
127pub const MIN_INTERVAL_S: f64 = 0.002;
128/// The slowest a log may be sampled, s: the slowest rate the bounds were checked at on the
129/// synthetic flights' tuning set, half a sample a second, below which the readings are withheld
130/// ([`Reason::SampledTooSlowly`]). It is about twice a radio's telemetry interval, and a
131/// millisecond clock read as seconds is slower at any rate under 500 samples a second.
132pub const MAX_INTERVAL_S: f64 = 2.0;
133/// The coarsest step a height track may have, m: the coarsest checked on the tuning set, above
134/// the 8.8 m steps of the coarsest altitude track the readers read (MARSA's).
135pub const MAX_STEP_M: f64 = 10.0;
136/// The coarsest step a pressure track may have, Pa: the coarsest checked on the tuning set, above
137/// the 92 Pa steps of the coarsest pressure track the readers read (an ARTS2's raw counts).
138pub const MAX_PRESSURE_STEP_PA: f64 = 100.0;
139/// The climb above the pad that marks a flight, m (Debrief's 3 m).
140pub const LIFTOFF_HEIGHT_M: f64 = 3.0;
141/// The least the filtered track may sit above the pad and still be on it, m: four times the
142/// synthetic flights' fast correlated barometer noise (0.5 m, [ADR-280] §3), HPR Sim's choice.
143/// Where the pad's own samples reach further, the allowance is their reach. Liftoff read at half a
144/// foot above the pad, as before the readings were taken on every logger, came up to 6 s early on a
145/// noisy 500 Hz barometer, the noise lifting the pad's last samples above it; with the pad's reach
146/// measured but the allowance at 1 m, 6.8 s early at half a sample a second on one tuning flight,
147/// against a 4.5 s bound, the noise moving the pad's last sample past the reach of the two before;
148/// at 2 m, never.
149///
150/// [ADR-280]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0280-m7-2-in-seven-the-synthetic-flights-first.md
151pub const LIFTOFF_ALLOWANCE_M: f64 = 2.0;
152/// The least mean acceleration a rocket leaves the pad with over its first meters, m/s², which
153/// sets how long it takes to climb out of the pad's noise and so how late liftoff can be read:
154/// twice gravity, as the safety codes' 3:1 thrust to weight leaves on the motor's average thrust
155/// (NAR's high-power code: liftoff weight no more than a third of the certified average thrust;
156/// Tripoli's: below 3:1 only with an active stability system). The tuning set's slowest rocket
157/// averages 30 m/s² over its first 5 m. A rocket slower off the pad is read later than the bound,
158/// and may already be further up, when a log starts, than its pad's error allows.
159pub const LIFTOFF_ACCELERATION_M_S2: f64 = 2.0 * STANDARD_GRAVITY_MPS2;
160/// How close to the pad the altitude must come to mark landing, m (Debrief's 2 m).
161pub const LANDING_HEIGHT_M: f64 = 2.0;
162/// The height above the pad the altitude must then stay under, m (Debrief's 5 m)…
163pub const LANDED_CEILING_M: f64 = 5.0;
164/// …and for how long, s (Debrief's 1 s).
165pub const LANDED_FOR_S: f64 = 1.0;
166/// How far above the ground the logger may sit on the pad, m: it lands lower than it started by
167/// as much, so its landing is read early by the time that height takes. HPR Sim's choice, a tall
168/// rocket's electronics bay on a rail.
169pub const PAD_ABOVE_GROUND_M: f64 = 3.0;
170/// A top speed above this is refused, m/s (Debrief's ceiling).
171pub const IMPLAUSIBLE_SPEED_M_S: f64 = 4000.0;
172/// A top speed is refused when the climb's most negative speed is more than this share of it: a
173/// trace swinging that far has no usable sign (Debrief's 20%).
174pub const ASCENT_NOISE_FRACTION: f64 = 0.2;
175/// The span of the least-squares fit the top speed is the slope of, s: HPR Sim's choice, long
176/// enough to average the barometer's correlated noise down to a few meters a second, short enough
177/// to keep most of the speed's peak.
178pub const SPEED_WINDOW_S: f64 = 0.5;
179/// The fewest samples the fit may take: the top speed is withheld on a log sampled slower than
180/// [`SPEED_WINDOW_S`] over this less one.
181pub const SPEED_MIN_SAMPLES: usize = 5;
182/// The Mach number from which a barometer's port may read the transonic flow over the nose: the
183/// ogive-cylinder's pressure coefficient behind its shoulder jumps between Mach 0.9 and 1.0
184/// (`docs/research/altimeter-mach-error.md` §1–2), and on the tuning set a speed derived from it
185/// was off by up to 850 m/s from Mach 0.9. HPR Sim's margin below it.
186pub const TRANSONIC_MACH: f64 = 0.8;
187/// The top speed at or above which it is withheld ([`Reason::Transonic`]), m/s:
188/// [`TRANSONIC_MACH`] times the speed of sound in the coldest air the bounds allow below 20 km, the
189/// standard atmosphere's 216.65 K less [`AIR_TEMPERATURE_SPREAD_K`]: `0.8 √(1.4 · 287.05 ·
190/// 201.65)` = 227.7 m/s.
191pub const TRANSONIC_SPEED_M_S: f64 = 227.736_107_633_374_67;
192/// The pressure coefficient a port one caliber behind the nose's shoulder reads below Mach 0.9,
193/// its size: the ogive-cylinder's measured −0.02 (`altimeter-mach-error.md` §1–2), the largest
194/// the synthetic flights draw. A climb's dynamic pressure rises with its speed, so the port's
195/// error lifts a speed derived while the rocket accelerates.
196pub const PORT_PRESSURE_COEFFICIENT: f64 = 0.02;
197/// How far the day's air may be from the 1976 standard atmosphere for the bounds to hold, K: the
198/// synthetic flights' range ([ADR-280] §2). Where the log's temperature at the pad lies further
199/// off and the log gives the pad's height above sea level, [`Readings::day_air`] says so, with the
200/// share the day may move a reading by (#1259).
201///
202/// [ADR-280]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0280-m7-2-in-seven-the-synthetic-flights-first.md
203pub const AIR_TEMPERATURE_SPREAD_K: f64 = 15.0;
204/// The share of a barometric height its error from the day's air can reach: a height read by the
205/// standard atmosphere is `T_std/T` of the true one over the layer it spans (the hypsometric
206/// equation), so off by `ΔT/T_std` at most, `T_std` no colder than the standard atmosphere's
207/// 216.65 K below 20 km: 15/216.65 = 6.9%. About 0.35% a kelvin near the ground.
208pub const TEMPERATURE_SHARE: f64 = AIR_TEMPERATURE_SPREAD_K / 216.65;
209/// The share of a height a barometer's gain can be off after its pad zero: an MS5607's ±1.0 mbar
210/// over the 400 mbar its datasheet states it on (an inference), the widest of the synthetic
211/// flights' parts ([ADR-280] §3).
212///
213/// [ADR-280]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0280-m7-2-in-seven-the-synthetic-flights-first.md
214pub const BAROMETER_GAIN: f64 = 0.0025;
215/// The barometer's noise at a reading, m: what the fast and slow correlated noise, the part's
216/// white noise, the pad's own median and the port's error at apogee's sideways speed add to a
217/// height read off the filtered track, tuned on the tuning set.
218pub const NOISE_M: f64 = 3.0;
219/// The most a barometer's drift moves a height in a second, m: the synthetic flights' fastest
220/// drift, 3 Pa in 30 s ([ADR-280] §3), at the density of air 5 km up (0.74 kg/m³).
221///
222/// [ADR-280]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0280-m7-2-in-seven-the-synthetic-flights-first.md
223pub const DRIFT_M_PER_S: f64 = 0.015;
224/// What the barometer's noise adds to a derived speed, m/s, tuned on the tuning set.
225pub const SPEED_NOISE_M_S: f64 = 5.0;
226/// How long before its top the track is checked, s. A coast loses `g t²/2` in the last `t` before
227/// its top, 78 m in 4 s, gravity slowing it and drag only adding, and a flight whose motor burns
228/// into those 4 s less; a track on a clock read a thousand times too slow, as milliseconds read as
229/// seconds, loses about 80 µm, so a track must lose more than twice its noise and step. And a
230/// coast doesn't fall and rise again: a track that falls more than that after a peak in those 4 s
231/// and then climbs to its top has a top that isn't the coast's ([`Reason::DisturbedTop`]).
232pub const COAST_CHECK_S: f64 = 4.0;
233/// How long either side of its top the track is checked for a spike, s: a second, or two samples
234/// of a slower track. A coast slowing at gravity and drag climbs no more than `g Δ²` in its last
235/// Δ, and nothing falls from its top faster than gravity pulls it, so a track that climbs into
236/// its top and falls from it faster than both holds a spike there ([`Reason::DisturbedTop`]), as
237/// a breakup's in a public Blue Raven log does, 1.2 km over the coast. A parachute open before
238/// apogee breaks only the first, a charge that lifts the bay's pressure at the top only the
239/// second, and their tops are read.
240pub const SPIKE_CHECK_S: f64 = 1.0;
241/// The fastest the day's pressure changes in the ordinary run of weather, Pa an hour: the
242/// National Weather Service's *pressure rising (falling) rapidly*, 0.06 inHg an hour or more
243/// (its glossary; the threshold of METAR's `PRESRR` and `PRESFR` remarks).
244pub const RAPID_PRESSURE_CHANGE_PA_PER_H: f64 = 0.06 * 3386.389;
245/// How far from its zero a track whose heights are above the pad only by a mapping's or a column's
246/// word may start and still be taken as a height above the pad, m: a logger zeroes on the pad, and
247/// its zero moves by the weather and its noise before launch. An hour on the pad at
248/// [`RAPID_PRESSURE_CHANGE_PA_PER_H`], at sea level's standard density, then [`NOISE_M`]: `203.2 /
249/// (1.225 · 9.807) + 3` = 19.9 m. The hour is HPR Sim's choice. A track that starts further off is
250/// withheld as [`Reason::StartsOffThePad`], as an altitude above sea level a column mapping calls
251/// one above the ground reads (#646).
252pub const PAD_ZERO_M: f64 =
253 RAPID_PRESSURE_CHANGE_PA_PER_H / (1.225 * STANDARD_GRAVITY_MPS2) + NOISE_M;
254
255/// The axial accelerometer's scale error, a share of its reading: the ADXL375's ±10% sensitivity
256/// ([ADR-280] §3, the datasheet's p. 3), the widest of the parts the synthetic flights' loggers
257/// model.
258///
259/// [ADR-280]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0280-m7-2-in-seven-the-synthetic-flights-first.md
260pub const ACCEL_SCALE_SHARE: f64 = 0.10;
261/// Its residual bias after the pad's zero, m/s²: the synthetic flights' 0.05 g, the top of the
262/// 10–50 mg the sensor-noise note calls a guess, as no source states one.
263pub const ACCEL_BIAS_M_S2: f64 = 0.05 * STANDARD_GRAVITY_MPS2;
264/// The most a rail stands from vertical, degrees: the NAR's and Tripoli's high-power safety
265/// codes allow 20° (the NAR's model rocket code allows 30°). A logger that zeroes its
266/// accelerometer on the pad takes out `g cos θ`, so standard gravity put back is off by up to
267/// `g (1 − cos 20°)`, 0.06 g.
268pub const RAIL_TILT_DEG: f64 = 20.0;
269/// How near 1 g, or 0, an accelerometer's pad must read, or its coast to apogee 0 or −1 g, to
270/// settle whether gravity is in its readings, g: a 20° rail's 0.06 g, a part's zero offset and the
271/// small drag near apogee, HPR Sim's choice. Also how far below its part's range a top
272/// acceleration is taken as clipped, with two steps.
273pub const GRAVITY_TOLERANCE_G: f64 = 0.25;
274/// The noise bound on one accelerometer sample, in its measured σ: five, which a normal noise
275/// passes, either way, about once in 1.7 million samples.
276pub const ACCEL_NOISE_SIGMAS: f64 = 5.0;
277/// The span the accelerometer's trace is averaged over to find burnout, s: `2h + 1` samples, `h`
278/// half the span in intervals, rounded half away from zero, a tie that a clock's float times leave
279/// a hair short included, so 27 at 500 Hz, 7 at 100 Hz and 3 at 20 Hz.
280pub const BURNOUT_MEAN_S: f64 = 0.05;
281/// The span either side of the top acceleration its noise is measured over, s.
282pub const NOISE_SPAN_S: f64 = 0.5;
283/// The window of the Hampel filter the accelerometer's trace is cleaned with before the thrust's
284/// start and end and burnout are found on it, s: a spike narrower than half of it, a charge's
285/// shock or one bad sample, is taken out, while a step or a steady run, as the thrust's rise and
286/// fall are, is kept as it was. HPR Sim's choice; the top is still read off the samples.
287pub const SPIKE_WINDOW_S: f64 = 0.1;
288/// The Hampel filter's threshold, in robust standard deviations of its window (R. K. Pearson et
289/// al., *The Class of Generalized Hampel Filters*, EUSIPCO 2015, §2, `t`): five, as
290/// [`ACCEL_NOISE_SIGMAS`] holds the noise, so it takes out what noise alone reaches about once
291/// in 1.7 million samples. HPR Sim's choice.
292pub const SPIKE_THRESHOLD: f64 = 5.0;
293/// The least time a burn holds the cleaned accelerometer trace past
294/// [`LIFTOFF_ACCELERATION_M_S2`], s: a span that holds there for less is taken for a shock, a
295/// canopy's or a charge's, or a knock, not a burn, unless no span holds that long, when the first
296/// is the burn, a short one. Measured once, when the rule was chosen, on the sample logs: of the
297/// spans after the first, every one that started within 3 s of apogee held for at most 0.47 s,
298/// and every longer one started more than 3 s before it; nothing beside those logs says which of
299/// the longer ones are burns. HPR Sim's choice
300/// ([#789](https://github.com/nrdptel/fusionspace-eridanus/issues/789)).
301pub const BURN_LEAST_S: f64 = 0.5;
302/// The least samples of an accelerometer's pad, or its coast, that settle its gravity.
303pub const PAD_MIN_SAMPLES: usize = 3;
304/// The span of the coast before apogee's earliest time whose median reading settles an
305/// accelerometer's gravity, s: near apogee a rocket falls freely but for a drag its slow speed
306/// makes small, so a part that holds gravity reads about 0 and one that takes it out about −1 g.
307pub const COAST_SPAN_S: f64 = 1.0;
308/// A top acceleration held flat over this many samples is clipped: Debrief's.
309pub const FLAT_TOP_SAMPLES: usize = 4;
310/// Or over this long, s, if that is more samples: Debrief's.
311pub const FLAT_TOP_S: f64 = 0.05;
312/// Flat: within this share of the top, Debrief's.
313pub const FLAT_TOP_SHARE: f64 = 0.003;
314/// Or within this, m/s², if that is more: Debrief's.
315pub const FLAT_TOP_M_S2: f64 = 0.25;
316/// The span of the least-squares fit of the descent's rate, s: a canopy's rate changes slowly,
317/// so a fit twice the climb's averages the noise down; it needs [`SPEED_MIN_SAMPLES`], so a log
318/// sampled slower than every 0.25 s gives no canopy's rate.
319pub const DESCENT_WINDOW_S: f64 = 1.0;
320/// The steps of the track a fit of the descent's rate holds at the least: a fit across one step
321/// reads a spike, and one across four is off by about a quarter of the rate, which the run's
322/// [`MAIN_TOLERANCE_SHARE`] leaves room for. HPR Sim's choice.
323pub const DESCENT_FIT_STEPS: f64 = 4.0;
324/// The longest fit of the descent's rate, s: a track whose steps need more is too coarse to tell
325/// the main's opening by. HPR Sim's choice.
326pub const DESCENT_WINDOW_MAX_S: f64 = 10.0;
327/// The main's rate is the median over this long before landing, or the fit's span if that is
328/// longer, s: Debrief's.
329pub const DESCENT_TAIL_S: f64 = 2.0;
330/// Its last half is left out, s; and a main opening sooner than this after apogee is none:
331/// Debrief's.
332pub const DESCENT_GUARD_S: f64 = 0.5;
333/// The run back from landing stays within this share of the main's rate: Debrief's.
334pub const MAIN_TOLERANCE_SHARE: f64 = 1.6;
335/// Or within this much more, m/s, if that is more: Debrief's.
336pub const MAIN_TOLERANCE_M_S: f64 = 3.0;
337/// A drogue's leg falls faster than this many times the main's rate, by its median: Debrief's.
338pub const DROGUE_RATIO: f64 = 1.4;
339/// A leg of the descent loses more than this, m: Debrief's.
340pub const LEG_LEAST_M: f64 = 3.0;
341/// And more than this share of its top's height: Debrief's.
342pub const LEG_LEAST_SHARE: f64 = 0.1;
343/// The least density scale height of the troposphere, m: the 1976 standard atmosphere's
344/// `R T/(g − R L)`, with its 6.5 K/km lapse `L`, at its coldest, the tropopause's 216.65 K less
345/// [`AIR_TEMPERATURE_SPREAD_K`], is 7,289 m, taken down to 7,000 m. A canopy's rate goes as the
346/// density to the −½, so it grows by no more than `exp(h/2H)` over `h` of height in the
347/// troposphere.
348pub const DENSITY_SCALE_HEIGHT_M: f64 = 7_000.0;
349
350/// A reading, or why the log can't support it.
351///
352/// Serialized, the status goes in beside the reading's own fields (`"status": "read"`), so `T`
353/// must serialize as a map, as the reading structs here do.
354#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
355#[serde(tag = "status", rename_all = "snake_case")]
356pub enum Reading<T> {
357 /// The reading, with where it came from.
358 Read(T),
359 /// The log can't support the reading.
360 Withheld(Withheld),
361}
362
363impl<T> Reading<T> {
364 /// The reading, if it wasn't withheld.
365 pub fn value(&self) -> Option<&T> {
366 match self {
367 Self::Read(value) => Some(value),
368 Self::Withheld(_) => None,
369 }
370 }
371
372 /// Why it was withheld, if it was.
373 pub fn reason(&self) -> Option<Reason> {
374 match self {
375 Self::Read(_) => None,
376 Self::Withheld(withheld) => Some(withheld.reason),
377 }
378 }
379
380 fn withheld(reason: Reason, detail: impl Into<String>) -> Self {
381 Self::Withheld(Withheld {
382 reason,
383 detail: detail.into(),
384 })
385 }
386}
387
388/// Why a reading was withheld.
389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
390pub struct Withheld {
391 /// The reason, as a code.
392 pub reason: Reason,
393 /// The reason in words, with the log's own numbers.
394 pub detail: String,
395}
396
397/// Declares a fieldless enum and its `ALL`, every variant in the order declared, from one list,
398/// so that a new variant can't be left out of `ALL`.
399macro_rules! with_all {
400 ($(#[$meta:meta])* pub enum $name:ident { $($(#[$variant_meta:meta])* $variant:ident,)* }) => {
401 $(#[$meta])*
402 pub enum $name {
403 $($(#[$variant_meta])* $variant,)*
404 }
405
406 impl $name {
407 /// Every variant, in the order declared: what a program that maps them, as the
408 /// command line does, checks itself against.
409 pub const ALL: &'static [Self] = &[$(Self::$variant),*];
410 }
411 };
412}
413
414mod day_air;
415
416pub(crate) use day_air::standard_temperature_k;
417pub use day_air::{
418 COLDEST_STANDARD_K, DayAir, LOGGED_AIR_RANGE_K, PadHeightFrom, UNIT_ZERO_TOLERANCE_K,
419 UNIT_ZEROS_K,
420};
421
422with_all! {
423/// The reason a reading was withheld.
424#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
425#[serde(rename_all = "snake_case")]
426#[non_exhaustive]
427pub enum Reason {
428 /// The track has fewer than three samples.
429 TooShort,
430 /// The altitude never climbs twice [`LIFTOFF_ALLOWANCE_M`] and the step above where the log
431 /// starts, or [`LIFTOFF_HEIGHT_M`] above the pad, or the pad's allowance and a step if that is
432 /// higher; or, for landing, falls too little past its step and noise for the descent's rate to
433 /// be measured.
434 NoClimb,
435 /// A track whose heights are above the pad only by a mapping's or a column's word starts more
436 /// than [`PAD_ZERO_M`] from its zero: the log didn't start on the pad, or its heights aren't
437 /// above the pad, such as an altitude above sea level a column mapping calls one above the
438 /// ground.
439 StartsOffThePad,
440 /// The log ends before the rocket is seen to land.
441 EndsBeforeLanding,
442 /// The altitude reaches the ground sooner than a fall from rest at apogee in vacuum could.
443 FasterThanFreeFall,
444 /// The top speed is above [`IMPLAUSIBLE_SPEED_M_S`].
445 ImplausibleSpeed,
446 /// The climb's speed swings negative by more than [`ASCENT_NOISE_FRACTION`] of its top.
447 NoisySpeed,
448 /// The log has no accelerometer.
449 NoAccelerometer,
450 /// The reading needs another, which was withheld.
451 Needs,
452 /// The record breaks what every reader guarantees: a primary track as long as its clock, on
453 /// finite times that increase, and channels as long as their clocks. Only a record built by
454 /// hand can.
455 BadRecord,
456 /// The samples come more often than [`MIN_INTERVAL_S`], faster than the bounds were checked
457 /// at.
458 SampledTooFast,
459 /// The log holds no altitude, pressure or GNSS track.
460 NoHeightTrack,
461 /// The log's only height is an altitude whose sensor it doesn't state, such as a table's
462 /// `Altitude` column read by its header: a barometer's bounds can't be stated for it.
463 UnstatedSensor,
464 /// The samples come further apart than [`MAX_INTERVAL_S`], or than the top speed's fit needs.
465 SampledTooSlowly,
466 /// The track's step is coarser than [`MAX_STEP_M`] or [`MAX_PRESSURE_STEP_PA`].
467 StepTooCoarse,
468 /// The top speed reaches [`TRANSONIC_SPEED_M_S`], where the barometer's port may read the
469 /// transonic flow over the nose.
470 Transonic,
471 /// The only height is a GNSS receiver's, whose filter lags a climb and overshoots its top.
472 ReceiverLag,
473 /// The only height is a GNSS receiver's, whose fix drops out or lags at liftoff.
474 ReceiverDropout,
475 /// The track loses no more than twice its noise and step in the [`COAST_CHECK_S`] before its
476 /// top: its clock is in another unit, such as milliseconds read as seconds, its top isn't a
477 /// coast's, or it isn't a height.
478 SlowerThanFreeCoast,
479 /// The log's first samples can't rule out a rocket already more than [`LIFTOFF_ALLOWANCE_M`]
480 /// up when it starts: it starts after liftoff, as a logger that records from launch writes
481 /// its zero and then the climb, or holds too little of the pad to tell liftoff by. A track on
482 /// the logger's own zero, or one a mapping or a header calls above the ground, still gives its
483 /// heights from that zero, with the zero's possible error in their bounds, and withholds
484 /// liftoff unless a sample sits within the allowance of it.
485 ShortPad,
486 /// The height track's clock doesn't increase, so no time can be read off it.
487 ClockOutOfOrder,
488 /// The track's top isn't a coast's: it falls more than twice its noise and step below a peak
489 /// in the last [`COAST_CHECK_S`] before its top, then climbs to it, or climbs into it faster
490 /// than a coast can and falls from it faster than gravity pulls a body at rest there
491 /// ([`SPIKE_CHECK_S`]). A transient after apogee
492 /// does either, such as a charge's that lasts longer than the median takes out and stands
493 /// above the true top. Which is the apogee can't be told, so the apogee, the top speed and
494 /// landing are withheld; liftoff is not.
495 DisturbedTop,
496 /// The track falls more than the climb's rise below its start before the climb, then climbs
497 /// from the fall without resting again: a disturbance on the pad, such as a pressure pulse at
498 /// the barometer at ignition (#1101). The pad is read from before the fall, or from the
499 /// logger's zero when too little of it comes before. The top speed is withheld; so is liftoff
500 /// when no sample before the fall is on the pad, its bound otherwise reaching back over the
501 /// fall; and every reading is withheld when the track has no zero and too little pad before
502 /// the fall.
503 DisturbedPad,
504 /// The log's accelerometers don't say which of them lies along the rocket's axis, such as a
505 /// board's three axes, a phone's or a table's column read by its header: the top
506 /// acceleration and a burnout from the accelerometer need the axial one.
507 AxisUnstated,
508 /// The axial accelerometer's readings may or may not hold gravity's 1 g, and nothing settles
509 /// which: its family doesn't say, and neither its pad (about 1 g or 0) nor its coast to
510 /// apogee (about 0 or −1 g) reads either level, or what they say disagrees.
511 GravityUnstated,
512 /// Which way up the axial accelerometer reads, nose up or nose down, isn't settled, or its
513 /// trace shows no thrust. Of its three witnesses, each on the trace as written, none says or
514 /// two disagree: the pad (about 1 g nose up, about −1 g nose down), the coast to apogee
515 /// (−0.75 g or less nose up, 0.75 g or more nose down) and the thrust (its first span past
516 /// [`LIFTOFF_ACCELERATION_M_S2`] to hold there for [`BURN_LEAST_S`], unless a span the other
517 /// way comes first). Or, turned as they settle and gravity put back, the trace never passes
518 /// [`LIFTOFF_ACCELERATION_M_S2`] from liftoff's earliest time to apogee.
519 DirectionUnstated,
520 /// The descent shows no drogue's leg. Walked back from landing, its rate at the ground's
521 /// density never passes the main's mark, [`MAIN_TOLERANCE_SHARE`] times the rate near the
522 /// ground or [`MAIN_TOLERANCE_M_S`] more if that is more, in the [`DESCENT_TAIL_S`] before
523 /// the main's leg, or the descent before that leg isn't, on median, [`DROGUE_RATIO`] times
524 /// that rate. The rocket came down under one canopy, or under a drogue no faster than the
525 /// mark, which reads as one: the main's descent is then the whole descent's, from apogee to
526 /// landing, and there is no drogue's.
527 OneCanopy,
528 /// A leg of the descent loses too little height, under [`LEG_LEAST_M`] or
529 /// [`LEG_LEAST_SHARE`] of its top's height, or lasts too little, for its rate to be read.
530 ShortLeg,
531}
532}
533
534with_all! {
535/// The track a reading was read from.
536#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
537#[serde(rename_all = "snake_case")]
538#[non_exhaustive]
539pub enum Source {
540 /// The logger's barometric altitude, the record's primary track, above the logger's zero.
541 Barometer,
542 /// A pressure channel, turned into a height by the 1976 standard atmosphere and zeroed on
543 /// the pad.
544 Pressure,
545 /// A barometric altitude channel, above the ground or above sea level, zeroed on the pad.
546 AltitudeChannel,
547 /// A GNSS receiver's altitude.
548 Gnss,
549 /// The accelerometer along the rocket's axis.
550 Accelerometer,
551}
552}
553
554with_all! {
555/// Whether a reading was measured or derived.
556#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
557#[serde(rename_all = "snake_case")]
558#[non_exhaustive]
559pub enum Provenance {
560 /// Read straight off the track: a height or a time it holds.
561 Measured,
562 /// Worked out from the track, such as a speed from the slope of its heights.
563 Derived,
564 /// Measured, but at the sensor's range, so the true value may lie beyond it: a top
565 /// acceleration at the part's stated range, or held flat at its top as a part that clipped
566 /// holds it.
567 Clipped,
568}
569}
570
571with_all! {
572/// How a reading was taken from its track.
573#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
574#[serde(rename_all = "snake_case")]
575#[non_exhaustive]
576pub enum Method {
577 /// The last sample before apogee within the pad's allowance: [`LIFTOFF_ALLOWANCE_M`], or the
578 /// filtered pad's own reach if that is more, and a step.
579 LastOnThePad,
580 /// The filtered track's highest value, at the middle of its flat run.
581 HighestFiltered,
582 /// The highest least-squares slope of the filtered track over [`SPEED_WINDOW_S`].
583 SteepestSlope,
584 /// The first sample after apogee back within the pad's allowance, as liftoff's, that stays
585 /// down for [`LANDED_FOR_S`].
586 BackOnThePad,
587 /// The axial accelerometer's highest reading before apogee.
588 HighestReading,
589 /// The first sample next to the axial accelerometer's least reading after it falls below
590 /// zero: the end of the thrust's fall, where the coast's drag begins to ease.
591 LeastAfterThrust,
592 /// The top speed's time, a floor: burnout came no sooner than it less its bound.
593 SpeedPeak,
594 /// Landing's time less liftoff's.
595 LiftoffToLanding,
596 /// The height a leg of the descent loses over the time it takes, the main's leg found back
597 /// from landing as the run of samples descending near the main's rate.
598 LegChord,
599}
600}
601
602/// Liftoff.
603#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
604pub struct Liftoff {
605 /// The last sample on the pad, s on the track's clock: the filtered track was within the
606 /// pad's allowance then, and never again before apogee.
607 pub time_s: f64,
608 /// The bound on its error, s: the time to climb twice the allowance at
609 /// [`LIFTOFF_ACCELERATION_M_S2`], `√(4a/A)`, and the longer interval either side of the
610 /// sample, twice.
611 pub bound_s: f64,
612 /// Its 90% interval, s on the track's clock ([`interval::LIFTOFF_SHARES`]); `None` on a
613 /// disturbed pad ([`Reason::DisturbedPad`]), whose bound reaches back over the fall.
614 pub interval_s: Option<Interval>,
615 /// The track it came from.
616 pub source: Source,
617 /// Measured.
618 pub provenance: Provenance,
619 /// How it was read.
620 pub method: Method,
621}
622
623/// The highest point.
624#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
625pub struct Apogee {
626 /// When, s on the track's clock: the middle of the run of samples at the filtered track's
627 /// highest value.
628 pub time_s: f64,
629 /// When, s after liftoff; `None` when liftoff is withheld.
630 pub time_after_liftoff_s: Option<f64>,
631 /// The bound on the time's error, s: the time the top of a coast takes to fall by the
632 /// height's noise and step there, `√(2 (noise + step)/g)`, and the longest interval either
633 /// side of the peak's flat run.
634 pub time_bound_s: f64,
635 /// The time's 90% interval, s on the track's clock ([`interval::APOGEE_TIME_SHARES`]);
636 /// `None` when the height is a floor.
637 pub time_interval_s: Option<Interval>,
638 /// The filtered track there, m above the pad, or on a short pad above the track's zero, whose
639 /// possible error the bound holds.
640 pub height_m: f64,
641 /// The bound on the height's error, m: the day's air ([`TEMPERATURE_SHARE`]) and the
642 /// barometer's gain ([`BAROMETER_GAIN`]) as shares of the height, then its noise
643 /// ([`NOISE_M`]), drift ([`DRIFT_M_PER_S`]) since the log began, a step at the pad and one
644 /// at the peak, and the median's [`peak_bound_m`].
645 pub bound_m: f64,
646 /// The height's 90% interval, m above the pad ([`interval::APOGEE_HEIGHT_SHARES`]); `None`
647 /// when the height is a floor.
648 pub height_interval_m: Option<Interval>,
649 /// The filtered track there, m above the track's own zero: the logger's, for its own
650 /// altitude; for a channel's, as the channel or the standard atmosphere gives it.
651 pub altitude_m: f64,
652 /// Whether the peak lies within half the median's window of the log's end, so the log may
653 /// have stopped before the rocket did: the height is then a floor.
654 pub is_floor: bool,
655 /// The highest sample the track holds before the filter: above the apogee when the median
656 /// set a pulse aside.
657 pub highest_sample: Sample,
658 /// The track it came from.
659 pub source: Source,
660 /// Measured.
661 pub provenance: Provenance,
662 /// How it was read.
663 pub method: Method,
664}
665
666/// One sample of the track.
667#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
668pub struct Sample {
669 /// When, s on the track's clock.
670 pub time_s: f64,
671 /// The height, m above the track's own zero.
672 pub altitude_m: f64,
673}
674
675/// The top vertical speed in the climb.
676#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
677pub struct MaxSpeed {
678 /// The speed, m/s, up.
679 pub speed_m_s: f64,
680 /// The bound on its error, m/s: the day's air and the barometer's gain as shares of it; the
681 /// port's error while the rocket accelerates, [`PORT_PRESSURE_COEFFICIENT`] `v a/g`; the fit
682 /// cutting the peak, `(a₁ + a₂) w/4`, the climb's change of speed before and after it
683 /// measured on the fits; and [`SPEED_NOISE_M_S`].
684 pub bound_m_s: f64,
685 /// Its 90% interval, m/s ([`interval::TOP_SPEED_SHARES`]); `None` on a floor.
686 pub interval_m_s: Option<Interval>,
687 /// Whether the top is a floor, as the apogee's height is: the log ends on the climb, so the
688 /// rocket may have gone faster after its last sample, by any amount.
689 pub is_floor: bool,
690 /// When, s on the track's clock: the middle of the fit.
691 pub time_s: f64,
692 /// The filtered track then, m above the pad, or on a short pad above the track's zero, which
693 /// may be off the pad by as much as the apogee's bound allows for; no bound is given on it.
694 pub height_m: f64,
695 /// The track it came from.
696 pub source: Source,
697 /// Derived.
698 pub provenance: Provenance,
699 /// How it was read.
700 pub method: Method,
701}
702
703/// The top acceleration in the climb, as the axial accelerometer reads it.
704#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
705pub struct MaxAcceleration {
706 /// The acceleration, m/s², along the rocket's axis, nose up positive, gravity's reaction in it
707 /// as an accelerometer reads it: +1 g standing on the pad, the thrust less the drag over the
708 /// mass in the climb. Less 9.81 m/s² it is the rocket's own acceleration up on a vertical
709 /// climb. A channel written with gravity taken out has it put back.
710 pub acceleration_m_s2: f64,
711 /// The bound on its error, m/s²: the part's scale ([`ACCEL_SCALE_SHARE`]) as a share of it,
712 /// its residual bias ([`ACCEL_BIAS_M_S2`]), gravity's share a tilted rail takes from a channel
713 /// zeroed on the pad ([`RAIL_TILT_DEG`]), five times the noise measured around the top, a
714 /// step, and the change to the next sample either side, which a peak between them can hide.
715 /// When it is clipped, the true top is no lower than the reading less the bound, and may be
716 /// higher by any amount.
717 pub bound_m_s2: f64,
718 /// Its 90% interval, m/s² ([`interval::TOP_ACCELERATION_SHARES`]); `None` on a floor.
719 pub interval_m_s2: Option<Interval>,
720 /// A clipped top's lower end, m/s² ([`interval::TOP_ACCELERATION_FLOOR_SHARES`]); `None` where
721 /// it isn't clipped, as on a floor whose burn the log ends in, which no set tests.
722 pub lower_end_m_s2: Option<f64>,
723 /// When, s on the accelerometer's clock.
724 pub time_s: f64,
725 /// The range of the part its family states, m/s², `None` where it doesn't.
726 pub range_m_s2: Option<f64>,
727 /// Whether the top is a floor: no lower than the reading less its bound, and maybe higher by
728 /// any amount. A clipped top is ([`clip`](Self::clip)), and so is one whose burn the
729 /// accelerometer ends in, its thrust never falling through zero on the channel before apogee:
730 /// that one is measured, its [`clip`](Self::clip) `None`.
731 pub is_floor: bool,
732 /// Why it is clipped, where it is: at the part's stated range, or held flat at its top below
733 /// it or with no range stated; `None` where it isn't.
734 pub clip: Option<Clip>,
735 /// The accelerometer.
736 pub source: Source,
737 /// Clipped where [`clip`](Self::clip) says why; otherwise measured.
738 pub provenance: Provenance,
739 /// How it was read.
740 pub method: Method,
741}
742
743with_all! {
744/// Why a top acceleration is clipped.
745#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
746#[serde(rename_all = "snake_case")]
747#[non_exhaustive]
748pub enum Clip {
749 /// It reaches the part's range as its family states it, less two steps and
750 /// [`GRAVITY_TOLERANCE_G`]: the part read no more.
751 Range,
752 /// It holds flat at its top for [`FLAT_TOP_SAMPLES`] samples or [`FLAT_TOP_S`], as Debrief
753 /// tells a part that clipped, short of any range the family states or with none stated: the
754 /// part may have clipped, at a range other than the one stated.
755 Flat,
756}
757}
758
759/// Burnout: when the motor stopped pushing.
760#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
761pub struct Burnout {
762 /// When, s on the clock of the track it came from.
763 pub time_s: f64,
764 /// The bound on its error, s. From the accelerometer: the span of the samples within twice
765 /// the noise of the least reading and an interval, or two intervals if that is more. From the
766 /// speed's peak, a floor:
767 /// the time a coast slowing at g takes to lose twice [`SPEED_NOISE_M_S`], half the speed's
768 /// fit and an interval, by which the peak can read late.
769 pub bound_s: f64,
770 /// Its 90% interval, s on the same clock ([`interval::BURNOUT_SHARES`]); `None` on a floor.
771 pub interval_s: Option<Interval>,
772 /// A floor's lower end, s on the same clock ([`interval::BURNOUT_FLOOR_SHARES`]); `None` where
773 /// it isn't a floor.
774 pub lower_end_s: Option<f64>,
775 /// When, s after liftoff: the burn's length; `None` when liftoff is withheld.
776 pub time_after_liftoff_s: Option<f64>,
777 /// Whether the time is a floor: burnout came no sooner than it, less its bound, and may have
778 /// come later by any amount, as a motor whose thrust tails off below the drag and the weight
779 /// keeps burning after the rocket stops gaining speed.
780 pub is_floor: bool,
781 /// The accelerometer, or the height track the speed came from.
782 pub source: Source,
783 /// Measured from the accelerometer; derived from the speed's peak.
784 pub provenance: Provenance,
785 /// How it was read.
786 pub method: Method,
787}
788
789/// The flight time, liftoff to landing.
790#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
791pub struct FlightTime {
792 /// From liftoff to landing, s.
793 pub time_s: f64,
794 /// The bound on its error, s: liftoff's and landing's.
795 pub bound_s: f64,
796 /// Its 90% interval, s ([`interval::FLIGHT_TIME_SHARES`]).
797 pub interval_s: Option<Interval>,
798 /// The track it came from.
799 pub source: Source,
800 /// Measured: two times on the track.
801 pub provenance: Provenance,
802 /// How it was read.
803 pub method: Method,
804}
805
806/// The descent under one canopy: a leg of the descent, from apogee or the main's opening to the
807/// main's opening or landing.
808#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
809pub struct Descent {
810 /// The mean rate of descent over the leg, m/s, down positive: the filtered height lost over
811 /// the time taken.
812 pub rate_m_s: f64,
813 /// The bound on the rate's error, m/s: the day's air and the barometer's gain as shares of
814 /// the height lost, the noise and a step at either end, the drift over the leg, and from
815 /// apogee the median's [`peak_bound_m`], over the leg's time.
816 pub bound_m_s: f64,
817 /// Its 90% interval, m/s ([`interval::DROGUE_RATE_SHARES`] on a drogue's leg,
818 /// [`interval::MAIN_RATE_SHARES`] on the main's).
819 pub interval_m_s: Option<Interval>,
820 /// Where the leg starts, s on the track's clock: apogee, or the main's opening.
821 pub from_s: f64,
822 /// Where it ends: the main's opening, or landing.
823 pub to_s: f64,
824 /// The filtered track's height at its start, m above the pad.
825 pub from_height_m: f64,
826 /// At its end.
827 pub to_height_m: f64,
828 /// The main's opening, found back from landing, for the main's leg after a drogue's; `None`
829 /// for a drogue's leg or a descent under one canopy.
830 pub opening: Option<Opening>,
831 /// The track it came from.
832 pub source: Source,
833 /// Derived from the heights.
834 pub provenance: Provenance,
835 /// How it was read.
836 pub method: Method,
837}
838
839/// The main's opening, found back from landing.
840#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
841pub struct Opening {
842 /// The first sample of the run back from landing whose rate of descent stays near the main's,
843 /// s on the track's clock.
844 pub time_s: f64,
845 /// The bound on its error, s: the time the main takes to slow the drogue's descent to the
846 /// run's mark, worked out from the rate the main settles to; half the rate's fit; and two
847 /// intervals.
848 pub bound_s: f64,
849 /// Its 90% interval, s on the track's clock ([`interval::MAIN_OPENING_SHARES`]).
850 pub interval_s: Option<Interval>,
851 /// The filtered track's height then, m above the pad.
852 pub height_m: f64,
853}
854
855/// The axial accelerometer the top acceleration and burnout came from, and how its readings were
856/// taken.
857#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
858pub struct Accelerometer {
859 /// The channel's column, as the file writes it.
860 pub column: String,
861 /// Whether its readings hold gravity's 1 g, as an accelerometer's do, or were written with it
862 /// taken out; it is put back for the readings.
863 pub gravity: Gravity,
864 /// How that was settled.
865 pub gravity_by: GravityBy,
866 /// Whether its readings were turned over, as a part mounted nose down writes the climb's
867 /// thrust negative: its largest reading before apogee is negative.
868 pub turned_over: bool,
869 /// The median interval between its samples, s.
870 pub sample_interval_s: f64,
871 /// Its step, m/s²: the smallest gap between two of its values.
872 pub step_m_s2: f64,
873}
874
875with_all! {
876/// Whether an accelerometer's readings hold gravity.
877#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
878#[serde(rename_all = "snake_case")]
879#[non_exhaustive]
880pub enum Gravity {
881 /// They hold it, as the part reads: +1 g on the pad.
882 In,
883 /// The logger took it out, as its reading on the pad: 0 there.
884 Out,
885}
886}
887
888with_all! {
889/// How an accelerometer's [`Gravity`] was settled.
890#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
891#[serde(rename_all = "snake_case")]
892#[non_exhaustive]
893pub enum GravityBy {
894 /// Its family says so, and its pad and its coast, where they say, agree.
895 Family,
896 /// Its pad: about 1 g, or about 0, where its family doesn't say; its coast, where it says,
897 /// agrees.
898 Pad,
899 /// Its coast to apogee: about 0, or about −1 g, where neither its family nor its pad says.
900 Coast,
901}
902}
903
904/// Landing, and the descent before it.
905#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
906pub struct Landing {
907 /// The first sample after apogee back within the pad's allowance, at least
908 /// [`LANDING_HEIGHT_M`], s on the track's clock: before touchdown by the time the last meters
909 /// took.
910 pub time_s: f64,
911 /// The bound on its error, s: the time the descent takes to fall the pad's allowance, the
912 /// barometer's noise and drift, a step and the logger's height on the pad
913 /// ([`PAD_ABOVE_GROUND_M`]), at its rate near the ground taken slow by its step and noise,
914 /// and the longer interval either side of the sample, twice.
915 pub bound_s: f64,
916 /// Its 90% interval, s on the track's clock ([`interval::LANDING_SHARES`]).
917 pub interval_s: Option<Interval>,
918 /// From apogee to landing, s.
919 pub descent_time_s: f64,
920 /// The mean rate of descent from apogee to landing, m/s: the height lost over the time taken,
921 /// drogue and main together.
922 pub mean_descent_rate_m_s: f64,
923 /// The bound on the rate's error, m/s: the apogee's height bound and the height landing is
924 /// read at, then the rate times the apogee's and landing's time bounds, over the descent time.
925 pub mean_descent_rate_bound_m_s: f64,
926 /// The rate's 90% interval, m/s ([`interval::DESCENT_RATE_SHARES`]).
927 pub mean_descent_rate_interval_m_s: Option<Interval>,
928 /// The track it came from.
929 pub source: Source,
930 /// Measured: the time. The rate is derived from it and apogee.
931 pub provenance: Provenance,
932 /// How it was read.
933 pub method: Method,
934}
935
936/// What was read from a flight log.
937#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
938pub struct Readings {
939 /// The track the readings came from; `None` if the log has none, or is withheld whole as
940 /// [`Reason::BadRecord`].
941 pub source: Option<Source>,
942 /// The median interval between the track's samples, s; `None` for a log too short to read.
943 pub sample_interval_s: Option<f64>,
944 /// The track's step, m: the reader's for the logger's own altitude, else the smallest gap
945 /// between two of its values, a pressure's at the pad.
946 pub step_m: Option<f64>,
947 /// The running median's span, s, whole samples of the interval: [`MEDIAN_WINDOW_S`] rounded.
948 pub median_window_s: Option<f64>,
949 /// How far below its true peak the running median can read a peak bent by gravity alone, m
950 /// ([`peak_bound_m`]).
951 pub peak_bound_m: Option<f64>,
952 /// The pad, m on the track's own scale: the median of the samples surely before liftoff, or,
953 /// in a log that starts after liftoff, the logger's zero; `None` when every reading is
954 /// withheld before it is found. After a fall to a second level, the last rest's (#1158): the
955 /// start's level may have been the pad, and the gap enters the bounds, not this value.
956 pub pad_altitude_m: Option<f64>,
957 /// Whether the track's top lies at the log's end, within half the filter's window, so the log
958 /// may have stopped before the rocket did: the apogee and the top speed are then floors, and
959 /// the smoother's apogee too. It holds where the apogee is withheld as well.
960 pub ends_on_the_climb: bool,
961 /// Liftoff.
962 pub liftoff: Reading<Liftoff>,
963 /// The highest point.
964 pub apogee: Reading<Apogee>,
965 /// The top vertical speed from liftoff to apogee.
966 pub max_speed: Reading<MaxSpeed>,
967 /// The top acceleration, from the axial accelerometer.
968 pub max_acceleration: Reading<MaxAcceleration>,
969 /// Burnout, from the axial accelerometer or the speed's peak.
970 pub burnout: Reading<Burnout>,
971 /// Landing, and the descent before it.
972 pub landing: Reading<Landing>,
973 /// The flight time, liftoff to landing.
974 pub flight_time: Reading<FlightTime>,
975 /// The descent under the drogue: from apogee to the main's opening.
976 pub drogue_descent: Reading<Descent>,
977 /// The descent under the main, the canopy the rocket landed under: from the main's opening,
978 /// or from apogee when the descent shows one canopy, to landing.
979 pub main_descent: Reading<Descent>,
980 /// The axial accelerometer the top acceleration and burnout came from; `None` when the log
981 /// has none, or none settled.
982 pub accelerometer: Option<Accelerometer>,
983 /// The day's air at the pad, from the log's own temperature against the standard
984 /// atmosphere's, and whether the bounds' allowance for it, [`AIR_TEMPERATURE_SPREAD_K`],
985 /// covers it; `None` where the log has no temperature, no height above sea level for the pad,
986 /// a temperature outside −100 to 100 °C ([`LOGGED_AIR_RANGE_K`]), a column of one value at a
987 /// unit's zero ([`UNIT_ZEROS_K`]: 0 K, 0 °C or 0 °F), or the pad isn't found. Left out of a
988 /// record written before the field was.
989 #[serde(default)]
990 pub day_air: Option<DayAir>,
991}
992
993/// The height track the readings take.
994pub(crate) struct Track {
995 pub(crate) source: Source,
996 pub(crate) time_s: Vec<f64>,
997 /// Heights, m: above the logger's zero for its own altitude, else as the channel or the
998 /// standard atmosphere gives them; the readings measure from the pad.
999 pub(crate) height_m: Vec<f64>,
1000 /// The step, m: at the pad's pressure for a pressure track.
1001 pub(crate) step_m: f64,
1002 /// A pressure track's step, Pa.
1003 pub(crate) pressure_step_pa: Option<f64>,
1004 /// Whether its heights stand on a zero set on the pad: the logger's own altitude, which a
1005 /// [`FlightLog`] holds above the logger's zero, or a channel named as above the ground. A
1006 /// log that starts after liftoff reads its heights from that zero.
1007 pub(crate) zeroed: bool,
1008}
1009
1010impl Track {
1011 /// The step at a height of the track, m: a pressure track's step in height grows as the air
1012 /// thins, `Δh = Δp/(ρ g)`, the density from the standard atmosphere at that height.
1013 fn step_at(&self, height_m: f64) -> f64 {
1014 match self.pressure_step_pa {
1015 Some(step_pa) => step_pa / (standard_density(height_m) * STANDARD_GRAVITY_MPS2),
1016 None => self.step_m,
1017 }
1018 }
1019}
1020
1021/// The 1976 standard atmosphere's density at a pressure altitude, kg/m³, its sea-level 1.225
1022/// outside the model's range.
1023fn standard_density(height_m: f64) -> f64 {
1024 Ussa76::standard()
1025 .sample(height_m)
1026 .map_or(1.225, |sample| sample.air.density_kg_m3)
1027}
1028
1029/// Takes the readings from a flight log.
1030pub fn read(log: &FlightLog) -> Readings {
1031 let mut readings = heights(log);
1032 // A canopy's descent is read once landing is; withheld, it is withheld as landing is.
1033 if let Reading::Withheld(withheld) = &readings.landing {
1034 readings.drogue_descent = Reading::Withheld(withheld.clone());
1035 readings.main_descent = Reading::Withheld(withheld.clone());
1036 }
1037 readings.flight_time = flight_time(&readings);
1038 // An apogee that is only a floor may lie below the top: the share stays at the coldest
1039 // standard air's, the larger, rather than taken at a height the rocket may have passed.
1040 if let (Some(air), Reading::Read(apogee)) = (&mut readings.day_air, &readings.apogee)
1041 && !apogee.is_floor
1042 {
1043 air.set_top(apogee.height_m);
1044 }
1045 let (accelerometer, max_acceleration, burnout) = accelerometer::read(log, &readings);
1046 readings.accelerometer = accelerometer;
1047 readings.max_acceleration = max_acceleration;
1048 readings.burnout = burnout;
1049 readings
1050}
1051
1052/// The flight time, from liftoff and landing; withheld as the first of them withheld is.
1053fn flight_time(readings: &Readings) -> Reading<FlightTime> {
1054 match (&readings.liftoff, &readings.landing) {
1055 (Reading::Read(liftoff), Reading::Read(landing)) => {
1056 let (time_s, bound_s) = (
1057 landing.time_s - liftoff.time_s,
1058 liftoff.bound_s + landing.bound_s,
1059 );
1060 Reading::Read(FlightTime {
1061 time_s,
1062 bound_s,
1063 interval_s: interval::FLIGHT_TIME_SHARES.interval(time_s, bound_s),
1064 source: landing.source,
1065 provenance: Provenance::Measured,
1066 method: Method::LiftoffToLanding,
1067 })
1068 }
1069 (Reading::Withheld(withheld), _) => Reading::withheld(
1070 withheld.reason,
1071 format!(
1072 "the flight time needs liftoff, which is withheld: {}",
1073 withheld.detail
1074 ),
1075 ),
1076 (_, Reading::Withheld(withheld)) => Reading::withheld(
1077 withheld.reason,
1078 format!(
1079 "the flight time needs landing, which is withheld: {}",
1080 withheld.detail
1081 ),
1082 ),
1083 }
1084}
1085
1086/// The readings of the height track: liftoff, apogee, the top speed, landing and the descent
1087/// under each canopy. The top acceleration, burnout and the flight time are left for [`read`].
1088fn heights(log: &FlightLog) -> Readings {
1089 let every = |source: Option<Source>, reason: Reason, detail: &str| Readings {
1090 source,
1091 sample_interval_s: None,
1092 step_m: None,
1093 median_window_s: None,
1094 peak_bound_m: None,
1095 pad_altitude_m: None,
1096 ends_on_the_climb: false,
1097 liftoff: Reading::withheld(reason, detail),
1098 apogee: Reading::withheld(reason, detail),
1099 max_speed: Reading::withheld(reason, detail),
1100 max_acceleration: Reading::withheld(reason, detail),
1101 burnout: Reading::withheld(reason, detail),
1102 landing: Reading::withheld(reason, detail),
1103 flight_time: Reading::withheld(reason, detail),
1104 drogue_descent: Reading::withheld(reason, detail),
1105 main_descent: Reading::withheld(reason, detail),
1106 accelerometer: None,
1107 day_air: None,
1108 };
1109 if let Err(detail) = check_record(log) {
1110 return every(None, Reason::BadRecord, &detail);
1111 }
1112 let track = match track(log) {
1113 Ok(track) => track,
1114 Err((reason, detail)) => return every(None, reason, &detail),
1115 };
1116 let source = Some(track.source);
1117 if track.source == Source::Gnss {
1118 let mut readings = every(
1119 source,
1120 Reason::ReceiverLag,
1121 "the log's only height is a GNSS receiver's, whose navigation filter lags a climb and \
1122 overshoots its top by more than a barometer's bounds allow",
1123 );
1124 readings.liftoff = Reading::withheld(
1125 Reason::ReceiverDropout,
1126 "the log's only height is a GNSS receiver's, whose fix drops out or lags at liftoff",
1127 );
1128 readings.landing = Reading::withheld(
1129 Reason::Needs,
1130 "landing is found against the pad after apogee, and liftoff and apogee were withheld",
1131 );
1132 return readings;
1133 }
1134 let time = &track.time_s;
1135 let n = time.len();
1136 let mut steps: Vec<f64> = time.windows(2).map(|pair| pair[1] - pair[0]).collect();
1137 let (Some(interval), true) = (median(&mut steps), n >= 3) else {
1138 return every(
1139 source,
1140 Reason::TooShort,
1141 &format!("the track has {n} samples, too few to take a reading from"),
1142 );
1143 };
1144 if interval > MAX_INTERVAL_S {
1145 let mut readings = every(
1146 source,
1147 Reason::SampledTooSlowly,
1148 &format!(
1149 "the track's samples come every {interval:.3} s, slower than the {MAX_INTERVAL_S} s \
1150 the readings were checked at. A clock in milliseconds read as seconds looks so"
1151 ),
1152 );
1153 readings.sample_interval_s = Some(interval);
1154 return readings;
1155 }
1156 if interval < MIN_INTERVAL_S * (1.0 - 1e-3) {
1157 let mut readings = every(
1158 source,
1159 Reason::SampledTooFast,
1160 &format!(
1161 "the track's samples come every {interval:.3e} s, faster than the {MIN_INTERVAL_S} \
1162 s, 500 samples a second, the readings were checked at"
1163 ),
1164 );
1165 readings.sample_interval_s = Some(interval);
1166 return readings;
1167 }
1168 let half = half_window(interval);
1169 // Invariant: at MIN_INTERVAL_S the window holds 75 samples either side, far under the cap.
1170 debug_assert!(half <= MAX_MEDIAN_HALF_WINDOW, "{half}");
1171 let coarse = match track.pressure_step_pa {
1172 Some(step) if step > MAX_PRESSURE_STEP_PA => Some(format!(
1173 "the track's pressure moves in steps of {step:.1} Pa, coarser than the \
1174 {MAX_PRESSURE_STEP_PA} Pa the readings were checked at"
1175 )),
1176 None if track.step_m > MAX_STEP_M => Some(format!(
1177 "the track moves in steps of {:.2} m, coarser than the {MAX_STEP_M} m the readings \
1178 were checked at",
1179 track.step_m
1180 )),
1181 _ => None,
1182 };
1183 if let Some(detail) = coarse {
1184 let mut readings = every(source, Reason::StepTooCoarse, &detail);
1185 readings.sample_interval_s = Some(interval);
1186 readings.step_m = Some(track.step_m);
1187 return readings;
1188 }
1189 let step = track.step_m;
1190 let bound = peak_bound_m(half, interval);
1191 #[expect(
1192 clippy::cast_precision_loss,
1193 reason = "a window of a few samples converts exactly"
1194 )]
1195 let window_s = 2.0 * half as f64 * interval;
1196 let mut readings = every(source, Reason::TooShort, "");
1197 readings.sample_interval_s = Some(interval);
1198 readings.step_m = Some(step);
1199 readings.median_window_s = Some(window_s);
1200 readings.peak_bound_m = Some(bound);
1201
1202 // The climb: where the filtered track first rises `rise` above where the log starts, twice
1203 // the pad's allowance and step, which the pad's noise doesn't reach (the allowance is the
1204 // most it lifts the filtered pad), from below at the start or from above at the climb.
1205 let rise = 2.0 * (LIFTOFF_ALLOWANCE_M + step);
1206 // The log starts for the readings after any bad first samples, or they would take them for
1207 // the pad.
1208 let kept = without_bad_start(&track.height_m, time, half, rise);
1209 let heights = kept.as_deref().unwrap_or(&track.height_m);
1210 let head = kept
1211 .as_ref()
1212 .map_or(0, |kept| kept.iter().take_while(|h| h.is_nan()).count());
1213 let filtered = running_median(heights, half);
1214 let start = filtered[head..]
1215 .iter()
1216 .copied()
1217 .find(|h| h.is_finite())
1218 .unwrap_or(f64::NAN);
1219 let Some(apogee_index) = arg_max(&filtered[head..]).map(|index| index + head) else {
1220 return no_climb(readings, rise);
1221 };
1222 let Some(climb) = filtered[head..=apogee_index]
1223 .iter()
1224 .position(|h| *h >= start + rise)
1225 .map(|index| index + head)
1226 else {
1227 return no_climb(readings, rise);
1228 };
1229 let before_climb = before_climb(&filtered, time, (head, climb), start, rise);
1230 // After a fall to a level the track rests at: the medians of the stay at the start and of the
1231 // last rest. Within the rise of each other they are one level, the start's pad: a noisy pad's
1232 // lowest filtered heights can stand the rise below its first. Further apart, the last rest is
1233 // the pad, and the other may have been it (#1158): a logger carried down to the pad and a
1234 // level the pressure moved to before liftoff look alike, so the gap enters the pad's error.
1235 let (before_climb, level_gap_m) = match before_climb {
1236 BeforeClimb::Rests {
1237 from,
1238 last,
1239 level_m,
1240 before_end,
1241 ..
1242 } => {
1243 let (pad_from, on_pad) = last_rest_samples(&filtered, (from, last), level_m, rise);
1244 let level = |range: &[f64]| {
1245 let mut finite: Vec<f64> =
1246 range.iter().copied().filter(|h| h.is_finite()).collect();
1247 median(&mut finite)
1248 };
1249 match (
1250 level(&heights[pad_from..on_pad]),
1251 level(&heights[head..before_end]),
1252 ) {
1253 (Some(last_m), Some(start_m)) if (last_m - start_m).abs() > rise => {
1254 (before_climb, (last_m - start_m).abs())
1255 }
1256 _ => (BeforeClimb::AtStart, 0.0),
1257 }
1258 }
1259 other => (other, 0.0),
1260 };
1261 let pad_fall = match before_climb {
1262 BeforeClimb::Falls(fall) => Some(fall),
1263 BeforeClimb::Rests { then_falls, .. } => then_falls,
1264 BeforeClimb::AtStart => None,
1265 };
1266 // The pad: the median of the samples to the last within half the rise of the start before
1267 // the climb, the allowance and a step, so that the pad's noise doesn't end it early and the
1268 // climb lends it few samples; before a fall into the climb, those before the fall; after a
1269 // fall to a level the track rests at, the last rest before the climb (#1158): back from its
1270 // last sample within half the rise of where it ends, for as long as the samples rest.
1271 let (pad_from, on_pad) = match before_climb {
1272 BeforeClimb::Falls(fall) => (head, fall.begin.max(head + 1)),
1273 BeforeClimb::AtStart => (
1274 head,
1275 filtered[head..climb]
1276 .iter()
1277 .rposition(|h| *h <= start + 0.5 * rise)
1278 .map_or(head + 1, |last| head + last + 1),
1279 ),
1280 BeforeClimb::Rests {
1281 from,
1282 last,
1283 level_m,
1284 ..
1285 } => last_rest_samples(&filtered, (from, last), level_m, rise),
1286 };
1287 // How high the rocket may already be when the log starts. The track stays within half the rise
1288 // of its start, or rests at the last rest's level, for `stay_s`; a rocket that left the pad at
1289 // [`LIFTOFF_ACCELERATION_M_S2`] or more, moving at `v` at the start, climbs `v t + A t²/2` in
1290 // that time, no more than the rise with the noise at either end, so
1291 // `v ≤ (rise − A stay²/2)/stay`, and it had climbed `v²/(2A)`. A log that may start further up
1292 // than the allowance has no pad to tell liftoff by: a logger that records from launch writes
1293 // its zero, then climbs.
1294 let stay_s = time[on_pad - 1] - time[pad_from];
1295 let start_speed = if stay_s > 0.0 {
1296 ((rise - 0.5 * LIFTOFF_ACCELERATION_M_S2 * stay_s * stay_s) / stay_s).max(0.0)
1297 } else {
1298 f64::INFINITY
1299 };
1300 let pad_error_m = start_speed * start_speed / (2.0 * LIFTOFF_ACCELERATION_M_S2);
1301 // Before a fall into the climb, the samples are the pad only if they rest there.
1302 let short_pad = pad_error_m > LIFTOFF_ALLOWANCE_M
1303 || pad_fall
1304 .as_ref()
1305 .is_some_and(|fall| stay_s < fall.resting_s);
1306 // With no pad, the log's first sample stands for it: the zero a logger that records from
1307 // launch writes first, or the climb's first height in one that writes none.
1308 let measured_pad = if short_pad {
1309 heights
1310 .iter()
1311 .copied()
1312 .find(|h| h.is_finite())
1313 .unwrap_or(start)
1314 } else {
1315 let mut before: Vec<f64> = heights[pad_from..on_pad]
1316 .iter()
1317 .copied()
1318 .filter(|h| h.is_finite())
1319 .collect();
1320 median(&mut before).unwrap_or(start)
1321 };
1322 let by_word = zero_by_word(log, &track);
1323 if by_word && measured_pad.abs() > PAD_ZERO_M {
1324 let detail = format!(
1325 "the log starts {measured_pad:.2} m from the logger's zero. That is more than the \
1326 {PAD_ZERO_M:.1} m the weather and the noise move a zero on the pad. It didn't \
1327 start on the pad, or its heights aren't above the pad. An altitude above sea \
1328 level mapped as one above the ground reads so: map it as altitude_msl"
1329 );
1330 readings.liftoff = Reading::withheld(Reason::StartsOffThePad, detail.clone());
1331 readings.apogee = Reading::withheld(Reason::StartsOffThePad, detail.clone());
1332 readings.max_speed = Reading::withheld(Reason::StartsOffThePad, detail.clone());
1333 readings.landing = Reading::withheld(Reason::StartsOffThePad, detail);
1334 return readings;
1335 }
1336 let short_detail = format!(
1337 "the track stays within {:.1} m of its start for {stay_s:.2} s, so the rocket may have \
1338 climbed {pad_error_m:.1} m before the log starts. That is more than the pad's {:.0} m \
1339 allowance. Either the log starts after liftoff, as a logger recording from launch \
1340 does, or it holds too little of the pad to tell liftoff",
1341 0.5 * rise,
1342 LIFTOFF_ALLOWANCE_M
1343 );
1344 let fall_detail = pad_fall.as_ref().map(|fall| {
1345 let below = if fall.after_rest {
1346 "the level it rests at last"
1347 } else {
1348 "its start"
1349 };
1350 format!(
1351 "the track falls {:.1} m below {below} before the climb, and climbs from the fall \
1352 without resting again for {:.2} s: a disturbance on the pad, such as a pressure \
1353 pulse at ignition",
1354 fall.depth_m, fall.resting_s
1355 )
1356 });
1357 // With no pad, a track whose heights stand on a zero reads from that zero; one with no such
1358 // zero, as a pressure track, can't place the pad.
1359 if short_pad && !track.zeroed {
1360 let (reason, detail) = match &fall_detail {
1361 Some(detail) => (
1362 Reason::DisturbedPad,
1363 format!(
1364 "{detail}; and before the fall the track stays within {:.1} m of its start \
1365 for only {stay_s:.2} s, with no zero to place the pad by",
1366 0.5 * rise
1367 ),
1368 ),
1369 None => (Reason::ShortPad, short_detail.clone()),
1370 };
1371 let mut withheld = every(source, reason, &detail);
1372 withheld.sample_interval_s = readings.sample_interval_s;
1373 withheld.step_m = readings.step_m;
1374 withheld.median_window_s = readings.median_window_s;
1375 withheld.peak_bound_m = readings.peak_bound_m;
1376 return withheld;
1377 }
1378 // A short pad read from a zero is as far off as the zero. A zero the logger set on the pad is
1379 // the pad's. A word's zero (#646) sits within `PAD_ZERO_M` of the pad, as a zero set on the
1380 // pad drifts, and the first sample reads `s` above it after a climb `c` of up to `pad_error_m`,
1381 // so the zero stands `c − s` above the pad: as far as `s` below it, or, the rocket having
1382 // climbed before the log, up to `pad_error_m − s` above it, no more than `PAD_ZERO_M`. A pad
1383 // of samples is as far off as the rocket may have climbed before them.
1384 let (pad, pad_error_m) = if short_pad {
1385 let zero_error_m = if by_word {
1386 measured_pad
1387 .abs()
1388 .max((pad_error_m - measured_pad).min(PAD_ZERO_M))
1389 } else {
1390 0.0
1391 };
1392 (0.0, zero_error_m)
1393 } else {
1394 (measured_pad, pad_error_m)
1395 };
1396 let pad_error_m = pad_error_m + level_gap_m;
1397 readings.pad_altitude_m = Some(pad);
1398 // The day's air over the span the pad was taken from; a short pad's, at the log's start.
1399 let pad_span_s = if short_pad {
1400 (time[head], time[head])
1401 } else {
1402 (time[pad_from], time[on_pad - 1])
1403 };
1404 readings.day_air = day_air::day_air(log, pad_span_s);
1405 // How far the filtered pad reaches from its median, at least the allowance, which is all a
1406 // short pad, with no samples of it, has; liftoff is the last sample before apogee within that
1407 // and a step of the pad.
1408 let pad_samples = if short_pad {
1409 &[][..]
1410 } else {
1411 &filtered[pad_from..on_pad]
1412 };
1413 let reach = pad_samples
1414 .iter()
1415 .filter(|h| h.is_finite())
1416 .map(|h| (h - pad).abs())
1417 .fold(LIFTOFF_ALLOWANCE_M, f64::max);
1418 let allowance = reach + step;
1419 let climb_height = LIFTOFF_HEIGHT_M.max(allowance + step);
1420 let top = filtered[apogee_index];
1421 if top < pad + climb_height {
1422 return no_climb(readings, climb_height);
1423 }
1424 // Liftoff: the last sample before apogee within the pad's allowance. A log with none, its
1425 // pad short, starts above its zero's allowance: after liftoff, and its climb is searched from
1426 // its start.
1427 let level = pad + allowance;
1428 let on_the_pad = filtered[..apogee_index].iter().rposition(|h| *h <= level);
1429 let first = on_the_pad.unwrap_or(head);
1430
1431 // The track's step leaves the peak flat over a run of samples: the apogee is the run's
1432 // middle.
1433 let run_end = apogee_index
1434 + filtered[apogee_index..]
1435 .iter()
1436 .take_while(|h| **h == top)
1437 .count()
1438 - 1;
1439 let is_floor = run_end + half >= n - 1;
1440 readings.ends_on_the_climb = is_floor;
1441 let apogee_s = 0.5 * (time[apogee_index] + time[run_end]);
1442 let height = top - pad;
1443
1444 // A coast loses g t²/2 in the last t before its top, and a track on a clock a thousand times
1445 // too slow next to nothing: a track must lose more than twice its noise and step.
1446 let before_top = time[apogee_index] - COAST_CHECK_S;
1447 let least = 2.0 * (NOISE_M + track.step_at(top));
1448 if before_top > time[first] {
1449 let index = time.partition_point(|t| *t <= before_top).saturating_sub(1);
1450 let lost = top - filtered[index];
1451 if lost <= least {
1452 let coast = 0.5 * STANDARD_GRAVITY_MPS2 * COAST_CHECK_S * COAST_CHECK_S;
1453 let detail = format!(
1454 "the track loses {lost:.2} m in the {COAST_CHECK_S} s before its top. That is no \
1455 more than twice its noise and step ({least:.1} m), where a coast loses \
1456 {coast:.0} m. So either the track's clock is in another unit, such as \
1457 milliseconds read as seconds, or it isn't a height"
1458 );
1459 let mut withheld = every(source, Reason::SlowerThanFreeCoast, &detail);
1460 withheld.sample_interval_s = readings.sample_interval_s;
1461 withheld.step_m = readings.step_m;
1462 withheld.median_window_s = readings.median_window_s;
1463 withheld.peak_bound_m = readings.peak_bound_m;
1464 withheld.pad_altitude_m = readings.pad_altitude_m;
1465 return withheld;
1466 }
1467 }
1468 // A coast doesn't fall and rise again: a track that falls more than twice its noise and step
1469 // below a peak in the last [`COAST_CHECK_S`] before its top, then climbs to it, holds a top
1470 // that isn't the coast's, as a deployment's disturbance after apogee does when it lasts longer
1471 // than the median takes out. Which is the apogee can't be told.
1472 let window = time
1473 .partition_point(|t| *t < before_top)
1474 .max(first)
1475 .min(apogee_index);
1476 let mut peak = (f64::NEG_INFINITY, window);
1477 let mut fall = (0.0, window, window);
1478 for (index, height) in filtered.iter().enumerate().take(apogee_index).skip(window) {
1479 if *height > peak.0 {
1480 peak = (*height, index);
1481 }
1482 if peak.0 - height > fall.0 {
1483 fall = (peak.0 - height, peak.1, index);
1484 }
1485 }
1486 // Nor does a coast climb into its top as fast as a spike does and fall from it as fast. Slowing
1487 // at `a`, gravity and drag's upward share, a coast climbs `a Δ²/2` in its last Δ, and `a < 2g`
1488 // while that share, `ρ |v| v_z / (2β)`, is under g: over the last second at sea level, for a
1489 // ballistic coefficient β = m/(C_D A) over 24 kg/m² on a vertical coast and over 150 kg/m² at
1490 // 120 m/s across, where a 29 mm rocket of 0.3 kg has about 800. And nothing falls from its top
1491 // faster than gravity pulls it. The filtered top can trail the true one, but only while the
1492 // track falls less than its noise and step twice over and the median's window, `w`, lets it:
1493 // a fall from rest gathers at most `v = √(2g (2(N + s) + g w²/8))` by then, and from the
1494 // windows' first sample to their last, `L`, falls no more than `v L + g L²/2`. A parachute
1495 // open before apogee slows the climb harder than that, but not the fall; a charge that lifts
1496 // the bay's pressure at the top drops the track faster, after the coast's own climb. A track
1497 // that climbs and falls faster than both, past twice its noise and step, holds a spike at its
1498 // top, and which is the apogee can't be told. Checked over [`SPIKE_CHECK_S`] either side of
1499 // the top, or two samples.
1500 let span_s = SPIKE_CHECK_S.max(2.0 * interval);
1501 let back = time
1502 .partition_point(|t| *t <= time[apogee_index] - span_s)
1503 .saturating_sub(1);
1504 let climbed = top - filtered[back];
1505 let climb_s = time[apogee_index] - time[back];
1506 let climb_most = STANDARD_GRAVITY_MPS2 * climb_s * climb_s + least;
1507 let window_at =
1508 |index: usize| time[(index + half).min(n - 1)] - time[index.saturating_sub(half)];
1509 let held_m = least + STANDARD_GRAVITY_MPS2 * window_at(apogee_index).powi(2) / 8.0;
1510 let gathered_m_s = (2.0 * STANDARD_GRAVITY_MPS2 * held_m).sqrt();
1511 let falling = (run_end + 1..n)
1512 .take_while(|&index| time[index] - time[run_end] <= span_s)
1513 .find_map(|index| {
1514 let fallen = top - filtered[index];
1515 let over_s = time[(index + half).min(n - 1)] - time[apogee_index.saturating_sub(half)];
1516 let most =
1517 gathered_m_s * over_s + 0.5 * STANDARD_GRAVITY_MPS2 * over_s * over_s + least;
1518 (fallen > most).then_some((fallen, index, most))
1519 });
1520 let spike = falling
1521 .filter(|_| back >= first && climbed > climb_most)
1522 .map(|(fallen, index, most)| {
1523 format!(
1524 "the track climbs {climbed:.1} m into its top at {:.2} s in {climb_s:.2} s. That is \
1525 more than the {climb_most:.1} m a coast slowing at twice gravity climbs. The \
1526 track falls {fallen:.1} m from it by {:.2} s, more than the {most:.1} m a body at rest \
1527 there can fall. Each is past twice its noise and step. Its top is a spike, such \
1528 as a charge's, so which is the apogee can't be told",
1529 time[apogee_index], time[index]
1530 )
1531 });
1532 let disturbed = spike.or_else(|| {
1533 (fall.0 > least).then(|| {
1534 let (fallen, from, to) = fall;
1535 format!(
1536 "the track falls {fallen:.1} m from a peak at {:.2} s to {:.2} s. That is more than \
1537 twice its noise and step ({least:.1} m). The track then climbs to its top at {:.2} s. \
1538 A coast doesn't fall and then climb, and a disturbance after apogee, such as the \
1539 deployment's, does, so which is the apogee can't be told",
1540 time[from], time[to], time[apogee_index]
1541 )
1542 })
1543 });
1544
1545 // Liftoff is read late by the time the rocket takes to climb out of the pad's reach, once
1546 // above it and once below, at the least acceleration off the pad, and by a sample either side.
1547 // Before a fall into the climb, the rocket may have left the pad at any time from the last
1548 // sample within the pad's allowance before the fall, read so, to the climb's: the bound
1549 // reaches back over the fall. A log with no such sample may have started off the pad.
1550 let lifted = on_the_pad.and_then(|liftoff| {
1551 let bound_s = (4.0 * (allowance + pad_error_m) / LIFTOFF_ACCELERATION_M_S2).sqrt()
1552 + 2.0 * local_interval(time, liftoff);
1553 match &pad_fall {
1554 None => Some((liftoff, bound_s)),
1555 Some(fall) => filtered[head..fall.begin]
1556 .iter()
1557 .rposition(|h| (h - pad).abs() <= allowance)
1558 .map(|rested| (liftoff, bound_s + time[liftoff] - time[head + rested])),
1559 }
1560 });
1561 readings.liftoff = match lifted {
1562 None if fall_detail.is_some() => Reading::withheld(
1563 Reason::DisturbedPad,
1564 format!(
1565 "{}, and no sample before the fall is within the pad's {allowance:.1} m \
1566 allowance, so the rocket may have left the pad before the log starts",
1567 fall_detail.clone().unwrap_or_default()
1568 ),
1569 ),
1570 Some((liftoff, bound_s)) => Reading::Read(Liftoff {
1571 time_s: time[liftoff],
1572 bound_s,
1573 // The shares were fitted on liftoffs off a resting pad, not on a bound reaching back
1574 // over a fall, where the truth can lie at its far end.
1575 interval_s: pad_fall
1576 .is_none()
1577 .then(|| interval::LIFTOFF_SHARES.interval(time[liftoff], bound_s))
1578 .flatten(),
1579 source: track.source,
1580 provenance: Provenance::Measured,
1581 method: Method::LastOnThePad,
1582 }),
1583 None => Reading::withheld(
1584 Reason::ShortPad,
1585 format!(
1586 "{short_detail}; the track starts {:.2} m above the logger's zero, past the \
1587 pad's {allowance:.1} m allowance",
1588 start - pad
1589 ),
1590 ),
1591 };
1592 if let Some(detail) = disturbed {
1593 readings.apogee = Reading::withheld(Reason::DisturbedTop, detail.clone());
1594 readings.max_speed = Reading::withheld(Reason::DisturbedTop, detail.clone());
1595 readings.landing = Reading::withheld(Reason::DisturbedTop, detail);
1596 return readings;
1597 }
1598 let highest = arg_max(heights).unwrap_or(apogee_index);
1599 let top_step = track.step_at(top);
1600 let height_bound = (TEMPERATURE_SHARE + BAROMETER_GAIN) * height.abs()
1601 + NOISE_M
1602 + pad_error_m
1603 + DRIFT_M_PER_S * (apogee_s - time[0])
1604 + step
1605 + top_step
1606 + bound;
1607 let time_bound = (2.0 * (NOISE_M + top_step) / STANDARD_GRAVITY_MPS2).sqrt()
1608 + local_interval(time, apogee_index).max(local_interval(time, run_end));
1609 // A floor's truth may lie any amount above it: it states no interval.
1610 let stated = |shares: interval::Shares, value: f64, bound: f64| {
1611 (!is_floor).then(|| shares.interval(value, bound)).flatten()
1612 };
1613 readings.apogee = Reading::Read(Apogee {
1614 time_s: apogee_s,
1615 time_after_liftoff_s: lifted.map(|(index, _)| apogee_s - time[index]),
1616 time_bound_s: time_bound,
1617 time_interval_s: stated(interval::APOGEE_TIME_SHARES, apogee_s, time_bound),
1618 height_m: height,
1619 bound_m: height_bound,
1620 height_interval_m: stated(interval::APOGEE_HEIGHT_SHARES, height, height_bound),
1621 altitude_m: top,
1622 is_floor,
1623 highest_sample: Sample {
1624 time_s: time[highest],
1625 altitude_m: heights[highest],
1626 },
1627 source: track.source,
1628 provenance: Provenance::Measured,
1629 method: Method::HighestFiltered,
1630 });
1631 readings.max_speed = max_speed(
1632 time,
1633 &filtered,
1634 (first, apogee_index),
1635 pad,
1636 interval,
1637 track.source,
1638 is_floor,
1639 );
1640 // A log that starts after liftoff may have missed a faster climb before its first samples.
1641 if let (None, Some(speed)) = (lifted, readings.max_speed.value())
1642 && speed.time_s - time[0] < SPEED_WINDOW_S
1643 {
1644 readings.max_speed = Reading::withheld(
1645 Reason::ShortPad,
1646 format!(
1647 "the climb's speed peaks within {SPEED_WINDOW_S} s of the log's start, and the log \
1648 holds no pad. The rocket may have climbed faster before the log's first sample"
1649 ),
1650 );
1651 }
1652 if let Some(detail) = &fall_detail {
1653 readings.max_speed = Reading::withheld(
1654 Reason::DisturbedPad,
1655 format!("{detail}. The climb's first speeds may be the disturbance's"),
1656 );
1657 }
1658 let apex = Apex {
1659 index: apogee_index,
1660 time_s: apogee_s,
1661 height_bound_m: height_bound,
1662 time_bound_s: time_bound,
1663 };
1664 readings.landing = landing(&track, &filtered, pad, &apex, (allowance, pad_error_m));
1665 if let Reading::Read(landed) = &readings.landing {
1666 let index = time.partition_point(|t| *t < landed.time_s);
1667 (readings.drogue_descent, readings.main_descent) =
1668 canopies::read(&track, &filtered, pad, &apex, index, bound);
1669 }
1670 readings
1671}
1672
1673/// The readings of a track that never climbs `climb_height` above the pad.
1674fn no_climb(mut readings: Readings, climb_height: f64) -> Readings {
1675 let detail = format!("the altitude never climbs {climb_height:.1} m above the pad");
1676 readings.liftoff = Reading::withheld(Reason::NoClimb, detail.clone());
1677 readings.apogee = Reading::withheld(Reason::NoClimb, detail.clone());
1678 readings.max_speed = Reading::withheld(Reason::NoClimb, detail.clone());
1679 readings.landing = Reading::withheld(Reason::NoClimb, detail);
1680 readings
1681}
1682
1683/// The longer of the two intervals either side of sample `index`: a logger that samples the pad
1684/// slowly and the flight fast leaves its liftoff sample a pad's interval from the next.
1685fn local_interval(time: &[f64], index: usize) -> f64 {
1686 let gap = |a: usize, b: usize| match (time.get(a), time.get(b)) {
1687 (Some(a), Some(b)) => b - a,
1688 _ => 0.0,
1689 };
1690 gap(index.wrapping_sub(1), index).max(gap(index, index + 1))
1691}
1692
1693/// Whether the track's zero is the pad's only by a word: a mapped table's primary track is a height
1694/// above the pad only by the mapping's word (#646), and a channel above the ground only by its
1695/// column's; a reader's own altitude is by its format's.
1696pub(crate) fn zero_by_word(log: &FlightLog, track: &Track) -> bool {
1697 let mapped = matches!(
1698 log.format,
1699 LogFormat::GenericTable | LogFormat::BinaryRecords | LogFormat::ConsoleCapture
1700 );
1701 match track.source {
1702 Source::Barometer => mapped,
1703 Source::AltitudeChannel => track.zeroed,
1704 Source::Pressure | Source::Gnss | Source::Accelerometer => false,
1705 }
1706}
1707
1708/// The heights the readings take, on the scale of [`Readings::pad_altitude_m`], and their times, s
1709/// on the log's clock; `None` if the log holds no track. A channel-only log's `altitude_m` is empty,
1710/// so a caller after the log's height takes it from here.
1711#[must_use]
1712pub fn height_track(log: &FlightLog) -> Option<(Vec<f64>, Vec<f64>)> {
1713 track(log).ok().map(|track| (track.time_s, track.height_m))
1714}
1715
1716/// Which sensor the readings' height track comes from, as [`height_track`] takes it; `None` if
1717/// the log holds no track.
1718#[must_use]
1719pub fn height_track_source(log: &FlightLog) -> Option<Source> {
1720 track(log).ok().map(|track| track.source)
1721}
1722
1723/// The track the readings take, the first the log holds: the logger's own altitude, a pressure,
1724/// a barometric altitude channel, a GNSS altitude; or why there is none.
1725pub(crate) fn track(log: &FlightLog) -> Result<Track, (Reason, String)> {
1726 if !log.time_s.is_empty() {
1727 let declared = log.format.altitude_resolution_m();
1728 let step = if declared > 0.0 {
1729 declared
1730 } else {
1731 smallest_step(&log.altitude_m)
1732 };
1733 return Ok(Track {
1734 source: Source::Barometer,
1735 time_s: log.time_s.clone(),
1736 height_m: log.altitude_m.clone(),
1737 step_m: step,
1738 pressure_step_pa: None,
1739 zeroed: true,
1740 });
1741 }
1742 let first = |quantity: Quantity| log.channels_of(quantity).next();
1743 if let Some(channel) = first(Quantity::Pressure) {
1744 let (time_s, values) = clocked(channel)?;
1745 let air = Ussa76::standard();
1746 let height_m: Vec<f64> = values
1747 .iter()
1748 .map(|p| air.pressure_altitude_m(*p).unwrap_or(f64::NAN))
1749 .collect();
1750 let step_pa = smallest_step(&values);
1751 // The step in height at the pad's pressure, dh/dp = −1/(ρg), the pad's density from the
1752 // standard atmosphere at the track's first height.
1753 let pad_m = height_m
1754 .iter()
1755 .copied()
1756 .find(|h| h.is_finite())
1757 .unwrap_or(0.0);
1758 return Ok(Track {
1759 source: Source::Pressure,
1760 time_s,
1761 height_m,
1762 step_m: step_pa / (standard_density(pad_m) * STANDARD_GRAVITY_MPS2),
1763 pressure_step_pa: Some(step_pa),
1764 zeroed: false,
1765 });
1766 }
1767 let channel_track = |channel: &Channel, source: Source| Track {
1768 source,
1769 time_s: channel.time_s.clone(),
1770 height_m: channel.values.clone(),
1771 step_m: smallest_step(&channel.values),
1772 pressure_step_pa: None,
1773 zeroed: false,
1774 };
1775 if let Some(channel) =
1776 first(Quantity::AltitudeAboveGround).or_else(|| first(Quantity::AltitudeMsl))
1777 {
1778 let (time_s, height_m) = clocked(channel)?;
1779 return Ok(Track {
1780 source: Source::AltitudeChannel,
1781 step_m: smallest_step(&height_m),
1782 time_s,
1783 height_m,
1784 pressure_step_pa: None,
1785 zeroed: channel.quantity == Quantity::AltitudeAboveGround,
1786 });
1787 }
1788 if let Some(channel) = first(Quantity::GnssAltitude) {
1789 return Ok(channel_track(channel, Source::Gnss));
1790 }
1791 if let Some(channel) = first(Quantity::Altitude) {
1792 // A GPX track's elevation is its receiver's: the format carries GNSS tracks.
1793 if log.format == LogFormat::Gpx {
1794 return Ok(channel_track(channel, Source::Gnss));
1795 }
1796 return Err((
1797 Reason::UnstatedSensor,
1798 format!(
1799 "the log's only height, `{}`, doesn't say whether a barometer or a GNSS receiver \
1800 measured it. A column mapping can mark it as the barometer's primary track",
1801 channel.column
1802 ),
1803 ));
1804 }
1805 Err((
1806 Reason::NoHeightTrack,
1807 "the log holds no altitude, pressure or GNSS track".to_owned(),
1808 ))
1809}
1810
1811/// The smallest gap between two of the track's distinct finite values, or 0 if it holds fewer
1812/// than two: a track's step, as a track in steps passes every level between its lowest and its
1813/// highest. Successive changes would miss it on a track sampled so slowly that every sample moves
1814/// several steps.
1815fn smallest_step(values: &[f64]) -> f64 {
1816 let mut sorted: Vec<f64> = values.iter().copied().filter(|v| v.is_finite()).collect();
1817 sorted.sort_by(f64::total_cmp);
1818 sorted.dedup();
1819 let smallest = sorted
1820 .windows(2)
1821 .map(|pair| pair[1] - pair[0])
1822 .fold(f64::INFINITY, f64::min);
1823 if smallest.is_finite() { smallest } else { 0.0 }
1824}
1825
1826/// Whole samples either side of the running median's center: [`MEDIAN_WINDOW_S`] over two
1827/// intervals, rounded half up, at least one. At 20 Hz it is 3. A log's intervals are written to a
1828/// few decimals, so a rounding tie, such as 1.5 at 10 Hz, must not turn on the last bit of the
1829/// interval's median: a part in 10⁹ settles it upwards.
1830fn half_window(interval: f64) -> usize {
1831 let exact = MEDIAN_WINDOW_S / (2.0 * interval);
1832 #[expect(
1833 clippy::cast_possible_truncation,
1834 clippy::cast_sign_loss,
1835 reason = "a positive, finite count of samples, rounded, clamped to at least one"
1836 )]
1837 let half = (exact * (1.0 + 1e-9)).round().max(1.0) as usize;
1838 half
1839}
1840
1841/// How far below its true peak the running median of `half` samples either side can read a trace
1842/// sampled every `interval` s and bent by gravity alone near its peak, m:
1843/// `g ((⌈half/2⌉ + ½) Δt)² / 2`. At the highest sample, `half + 1` of the window's samples lie
1844/// within `⌈half/2⌉` places of it, so the median is no lower than they are, and the true peak lies
1845/// within half a sample of the highest sample. At 20 Hz, 0.077 m.
1846pub fn peak_bound_m(half: usize, interval: f64) -> f64 {
1847 #[expect(
1848 clippy::cast_precision_loss,
1849 reason = "a window of a few samples converts exactly"
1850 )]
1851 let reach = (half.div_ceil(2) as f64 + 0.5) * interval;
1852 0.5 * STANDARD_GRAVITY_MPS2 * reach * reach
1853}
1854
1855/// Whether the record holds to what every reader guarantees: one time per altitude, each channel
1856/// as long as its clock, and finite times that increase on the record's clock.
1857fn check_record(log: &FlightLog) -> Result<(), String> {
1858 let n = log.time_s.len();
1859 let channels = [
1860 ("altitude", Some(log.altitude_m.len())),
1861 ("speed", log.vertical_speed_m_s.as_ref().map(Vec::len)),
1862 ("temperature", log.temperature_k.as_ref().map(Vec::len)),
1863 ("battery", log.battery_v.as_ref().map(Vec::len)),
1864 ];
1865 for (name, len) in channels {
1866 if let Some(len) = len
1867 && len != n
1868 {
1869 return Err(format!(
1870 "the record has {n} times and {len} {name} samples: a reader gives each channel \
1871 one sample per time"
1872 ));
1873 }
1874 }
1875 increasing("the record's", &log.time_s)?;
1876 for channel in &log.channels {
1877 if channel.values.len() != channel.time_s.len() {
1878 return Err(format!(
1879 "channel `{}` has {} times and {} values: a reader gives a channel one value per \
1880 time",
1881 channel.column,
1882 channel.time_s.len(),
1883 channel.values.len()
1884 ));
1885 }
1886 }
1887 Ok(())
1888}
1889
1890/// A channel's samples on its clock, those with no time dropped, as a track takes them; or, if
1891/// its clock doesn't increase, why not. A reader keeps a channel's clock as the file writes it,
1892/// which can repeat or run back, as a GNSS receiver's fixes or a team's merged table do.
1893fn clocked(channel: &Channel) -> Result<(Vec<f64>, Vec<f64>), (Reason, String)> {
1894 let (time_s, values): (Vec<f64>, Vec<f64>) = channel
1895 .time_s
1896 .iter()
1897 .zip(&channel.values)
1898 .filter(|(t, _)| t.is_finite())
1899 .map(|(t, v)| (*t, *v))
1900 .unzip();
1901 increasing(&format!("channel `{}`'s", channel.column), &time_s)
1902 .map_err(|detail| (Reason::ClockOutOfOrder, detail))?;
1903 Ok((time_s, values))
1904}
1905
1906/// Whether `times` are finite and increase.
1907fn increasing(whose: &str, times: &[f64]) -> Result<(), String> {
1908 match times
1909 .windows(2)
1910 .position(|pair| !(pair[0].is_finite() && pair[1].is_finite() && pair[1] > pair[0]))
1911 {
1912 Some(index) => Err(format!(
1913 "{whose} times don't increase at sample {}: {} s, then {} s",
1914 index + 1,
1915 times[index],
1916 times[index + 1]
1917 )),
1918 None => Ok(()),
1919 }
1920}
1921
1922/// The index of the first greatest finite value.
1923fn arg_max(values: &[f64]) -> Option<usize> {
1924 values
1925 .iter()
1926 .enumerate()
1927 .filter(|(_, value)| value.is_finite())
1928 .fold(
1929 None,
1930 |best: Option<(usize, f64)>, (index, value)| match best {
1931 Some((_, top)) if *value <= top => best,
1932 _ => Some((index, *value)),
1933 },
1934 )
1935 .map(|(index, _)| index)
1936}
1937
1938/// The least-squares slope of `heights` against `times` over the samples within half of
1939/// [`SPEED_WINDOW_S`] of `times[center]`, skipping gaps; `None` with fewer than
1940/// [`SPEED_MIN_SAMPLES`].
1941fn slope(times: &[f64], heights: &[f64], center: usize) -> Option<f64> {
1942 slope_over(times, heights, center, SPEED_WINDOW_S)
1943}
1944
1945/// The most samples a slope's window of `window_s` is read at: twice the window's steps at the
1946/// fastest rate the readings were checked at, one every [`MIN_INTERVAL_S`], plus one (501 for the
1947/// 0.5 s speed window, which holds 251 at that rate; a clock a part in a thousand faster still
1948/// reads, and its window holds the same 251). A log sampled no faster is read whole; a
1949/// burst of samples close together, which the median interval doesn't see, costs each of them at
1950/// most this many steps, not a walk over the burst, so that the slopes over a climb or a descent
1951/// take time linear in its samples, but for a binary search's logarithm (#1250).
1952fn slope_samples(window_s: f64) -> usize {
1953 #[expect(
1954 clippy::cast_possible_truncation,
1955 clippy::cast_sign_loss,
1956 reason = "a window of at most DESCENT_WINDOW_MAX_S is at most 10,000 steps, positive"
1957 )]
1958 let steps = (2.0 * window_s / MIN_INTERVAL_S).ceil() as usize;
1959 steps + 1
1960}
1961
1962/// The samples a slope's window of `window_s` about `times[center]` is read at: those within half
1963/// of it, at every n-th sample where the window holds more than [`slope_samples`], n the least
1964/// whole number that brings the count within it; a window of no more is read whole.
1965fn slope_indices(times: &[f64], center: usize, window_s: f64) -> StepBy<Range<usize>> {
1966 let t0 = times[center];
1967 let reach = 0.5 * window_s;
1968 let from = times.partition_point(|t| *t < t0 - reach);
1969 let to = times.partition_point(|t| *t <= t0 + reach);
1970 let stride = (to - from).div_ceil(slope_samples(window_s)).max(1);
1971 (from..to).step_by(stride)
1972}
1973
1974/// The least-squares slope of `heights` against `times` over the samples within half of
1975/// `window_s` of `times[center]`, skipping gaps; `None` with fewer than [`SPEED_MIN_SAMPLES`].
1976/// The window is read at [`slope_indices`].
1977fn slope_over(times: &[f64], heights: &[f64], center: usize, window_s: f64) -> Option<f64> {
1978 let t0 = times[center];
1979 let indices = slope_indices(times, center, window_s);
1980 let window = || {
1981 indices
1982 .clone()
1983 .map(|k| (times[k], heights[k]))
1984 .filter(|(_, h)| h.is_finite())
1985 .map(|(t, h)| (t - t0, h))
1986 };
1987 let (count, sum_t, sum_h) = window().fold((0_usize, 0.0, 0.0), |(c, st, sh), (t, h)| {
1988 (c + 1, st + t, sh + h)
1989 });
1990 if count < SPEED_MIN_SAMPLES {
1991 return None;
1992 }
1993 #[expect(
1994 clippy::cast_precision_loss,
1995 reason = "a window of at most a few thousand samples converts exactly"
1996 )]
1997 let count_f = count as f64;
1998 let (mean_t, mean_h) = (sum_t / count_f, sum_h / count_f);
1999 let (num, den) = window().fold((0.0, 0.0), |(num, den), (t, h)| {
2000 (
2001 num + (t - mean_t) * (h - mean_h),
2002 den + (t - mean_t) * (t - mean_t),
2003 )
2004 });
2005 (den > 0.0).then(|| num / den)
2006}
2007
2008/// The top vertical speed from liftoff to apogee, or why it is withheld.
2009fn max_speed(
2010 time: &[f64],
2011 filtered: &[f64],
2012 (liftoff, apogee): (usize, usize),
2013 pad: f64,
2014 interval: f64,
2015 source: Source,
2016 is_floor: bool,
2017) -> Reading<MaxSpeed> {
2018 #[expect(
2019 clippy::cast_precision_loss,
2020 reason = "a handful of samples converts exactly"
2021 )]
2022 let slowest = SPEED_WINDOW_S / (SPEED_MIN_SAMPLES - 1) as f64;
2023 if interval > slowest {
2024 return Reading::withheld(
2025 Reason::SampledTooSlowly,
2026 format!(
2027 "the track's samples come every {interval:.3} s, too far apart for a \
2028 {SPEED_WINDOW_S} s fit of {SPEED_MIN_SAMPLES} samples. That fit needs them at most \
2029 {slowest} s apart"
2030 ),
2031 );
2032 }
2033 let speeds: Vec<(usize, f64)> = (liftoff..=apogee)
2034 .filter_map(|index| slope(time, filtered, index).map(|v| (index, v)))
2035 .collect();
2036 let Some(&(index, top)) = speeds
2037 .iter()
2038 .fold(None, |best: Option<&(usize, f64)>, item| match best {
2039 Some(b) if item.1 <= b.1 => best,
2040 _ => Some(item),
2041 })
2042 else {
2043 return Reading::withheld(
2044 Reason::SampledTooSlowly,
2045 "the climb is too short for a single fit of the speed",
2046 );
2047 };
2048 let worst = speeds.iter().map(|(_, v)| *v).fold(f64::INFINITY, f64::min);
2049 if top > IMPLAUSIBLE_SPEED_M_S {
2050 return Reading::withheld(
2051 Reason::ImplausibleSpeed,
2052 format!("the climb's speed peaks at {top:.1} m/s, above {IMPLAUSIBLE_SPEED_M_S} m/s"),
2053 );
2054 }
2055 if top >= TRANSONIC_SPEED_M_S {
2056 return Reading::withheld(
2057 Reason::Transonic,
2058 format!(
2059 "the climb's speed reaches {top:.1} m/s, at or above {TRANSONIC_SPEED_M_S:.1} m/s, \
2060 where the barometer's port may read the transonic flow over the nose"
2061 ),
2062 );
2063 }
2064 if top <= 0.0 || -worst > ASCENT_NOISE_FRACTION * top {
2065 return Reading::withheld(
2066 Reason::NoisySpeed,
2067 format!(
2068 "the speed from liftoff to apogee swings from {worst:.1} to {top:.1} m/s: a \
2069 negative swing over {:.0}% of the top has no usable sign",
2070 ASCENT_NOISE_FRACTION * 100.0
2071 ),
2072 );
2073 }
2074 // The climb's change of speed either side of the top, from the fits a window away: a fit
2075 // cuts a peak by about (a₁ + a₂) w/8; twice that is allowed.
2076 let at = |t: f64| {
2077 let target = time.partition_point(|s| *s < t).clamp(liftoff, apogee);
2078 speeds
2079 .iter()
2080 .min_by_key(|(i, _)| (i.abs_diff(target), *i))
2081 .map_or(top, |(_, v)| *v)
2082 };
2083 let rising = ((top - at(time[index] - SPEED_WINDOW_S)) / SPEED_WINDOW_S).max(0.0);
2084 let falling = ((top - at(time[index] + SPEED_WINDOW_S)) / SPEED_WINDOW_S).max(0.0);
2085 let bound_m_s = (TEMPERATURE_SHARE + BAROMETER_GAIN) * top
2086 + PORT_PRESSURE_COEFFICIENT * top * rising / STANDARD_GRAVITY_MPS2
2087 + 0.25 * (rising + falling) * SPEED_WINDOW_S
2088 + SPEED_NOISE_M_S;
2089 Reading::Read(MaxSpeed {
2090 speed_m_s: top,
2091 bound_m_s,
2092 interval_m_s: (!is_floor)
2093 .then(|| interval::TOP_SPEED_SHARES.interval(top, bound_m_s))
2094 .flatten(),
2095 is_floor,
2096 time_s: time[index],
2097 height_m: filtered[index] - pad,
2098 source,
2099 provenance: Provenance::Derived,
2100 method: Method::SteepestSlope,
2101 })
2102}
2103
2104/// A fall before the climb: where it leaves the start's band, how deep it goes, and the rest it
2105/// lacks.
2106#[derive(Clone, Copy)]
2107struct Fall {
2108 /// The sample after the last at or above the start's band before the fall's lowest point.
2109 begin: usize,
2110 /// How far below the start the filtered track falls, m.
2111 depth_m: f64,
2112 /// The time the track would have to stay within the band to rest, s.
2113 resting_s: f64,
2114 /// Whether it falls from the last rest before the climb (#1158), not from the log's start.
2115 after_rest: bool,
2116}
2117
2118/// What the track does before the climb, for reading the pad.
2119#[derive(Clone, Copy)]
2120enum BeforeClimb {
2121 /// It falls no further below its start than the rise and the drift, or (as the caller decides)
2122 /// rests last at a level whose median lies within the rise of the start's: the pad is read
2123 /// from its start.
2124 AtStart,
2125 /// It falls further, to a level it rests at: the pad is the last rest before the climb
2126 /// (#1158).
2127 Rests {
2128 /// The first sample of the last rest before the climb.
2129 from: usize,
2130 /// The last sample whose window rested in it.
2131 last: usize,
2132 /// The lowest filtered height of that last window, m: where the rest ends.
2133 level_m: f64,
2134 /// The sample after the track's last at or above half the rise below its start, before the
2135 /// fall's lowest point.
2136 before_end: usize,
2137 /// A fall from the rest into the climb, deeper than the rise below `level_m`: a pulse at
2138 /// ignition after the rest (#1101).
2139 then_falls: Option<Fall>,
2140 },
2141 /// It falls further and goes into the climb without resting (#1101).
2142 Falls(Fall),
2143}
2144
2145/// The samples of the last rest before the climb, as a range `pad_from..on_pad` of `filtered`
2146/// (#1158): from its last sample within half the rise of `level_m`, where it ends, back while the
2147/// samples rest, their highest and lowest within the rise. `from..=last` is the rest's run of
2148/// resting windows.
2149fn last_rest_samples(
2150 filtered: &[f64],
2151 (from, last): (usize, usize),
2152 level_m: f64,
2153 rise: f64,
2154) -> (usize, usize) {
2155 let on_pad = filtered[from..=last]
2156 .iter()
2157 .rposition(|h| *h <= level_m + 0.5 * rise)
2158 .map_or(from + 1, |found| from + found + 1);
2159 let (mut lowest, mut highest) = (f64::INFINITY, f64::NEG_INFINITY);
2160 let mut pad_from = on_pad - 1;
2161 for index in (from..on_pad).rev() {
2162 let h = filtered[index];
2163 lowest = lowest.min(h);
2164 highest = highest.max(h);
2165 if !h.is_finite() || highest - lowest > rise {
2166 break;
2167 }
2168 pad_from = index;
2169 }
2170 (pad_from, on_pad)
2171}
2172
2173/// What the track does before the climb: stays near its start, falls to a level it rests at
2174/// (the last such rest is the pad, #1158), or falls into the climb without resting (#1101).
2175///
2176/// A rocket on the pad doesn't sink below it. A filtered track that falls more than `rise` and the
2177/// drift ([`DRIFT_M_PER_S`]) below its start before the climb, then goes into the climb without
2178/// resting anywhere on the way down or up, isn't the pad: by its look it is a pressure pulse at
2179/// the barometer at ignition. Resting is staying within half the rise of one height for as long
2180/// as a rocket leaving the pad at [`LIFTOFF_ACCELERATION_M_S2`] takes to cross the rise, with no
2181/// sample that isn't a number among them,
2182/// `√(2 rise/A)`, so a fall to a level the track then holds, as a logger carried down to the pad
2183/// or the weather moving the pressure, is no disturbance. The pad is then the level the track
2184/// rests at last before the climb: a logger switched on above the pad and carried down to it
2185/// reads from the pad. The caller widens the pad's error by the gap to the start's level, as
2186/// either may be the pad. A rest is a run of windows that each rest, every one ending on the
2187/// sample after the one before. Its level is where it ends, the lowest filtered height of its
2188/// last window: the climb only rises from it, and the weather may have moved the pad's reading
2189/// while it rested. A fall from it deeper than the rise before the climb is a pulse at ignition,
2190/// as a fall from the start is. The samples before a fall into the climb are the pad only if they
2191/// rest too; else the pad is the logger's zero, or can't be placed.
2192fn before_climb(
2193 filtered: &[f64],
2194 time: &[f64],
2195 (head, climb): (usize, usize),
2196 start: f64,
2197 rise: f64,
2198) -> BeforeClimb {
2199 let Some(low) = (head..climb)
2200 .filter(|index| filtered[*index].is_finite())
2201 .min_by(|a, b| filtered[*a].total_cmp(&filtered[*b]))
2202 else {
2203 return BeforeClimb::AtStart;
2204 };
2205 let depth_m = start - filtered[low];
2206 if depth_m <= rise + DRIFT_M_PER_S * (time[low] - time[head]) {
2207 return BeforeClimb::AtStart;
2208 }
2209 let band = 0.5 * rise;
2210 let begin = filtered[head..low]
2211 .iter()
2212 .rposition(|h| *h >= start - band)
2213 .map_or(head, |last| head + last + 1);
2214 let resting_s = (2.0 * rise / LIFTOFF_ACCELERATION_M_S2).sqrt();
2215 // A rest is a run of finite samples whose highest and lowest lie within the rise, so all
2216 // within half of it of their middle, for `resting_s`: the window's least and most are kept in
2217 // two queues of indexes, each sample entering and leaving each once.
2218 let mut from = begin;
2219 let mut lows: VecDeque<usize> = VecDeque::new();
2220 let mut highs: VecDeque<usize> = VecDeque::new();
2221 // The last rest so far: its first sample, its last window's lowest height, and the last
2222 // sample whose window rested.
2223 let mut last_rest: Option<(usize, f64, usize)> = None;
2224 for index in begin..climb {
2225 let h = filtered[index];
2226 if !h.is_finite() {
2227 lows.clear();
2228 highs.clear();
2229 from = index + 1;
2230 continue;
2231 }
2232 while lows.back().is_some_and(|&k| filtered[k] >= h) {
2233 lows.pop_back();
2234 }
2235 lows.push_back(index);
2236 while highs.back().is_some_and(|&k| filtered[k] <= h) {
2237 highs.pop_back();
2238 }
2239 highs.push_back(index);
2240 while let (Some(&low), Some(&high)) = (lows.front(), highs.front())
2241 && filtered[high] - filtered[low] > 2.0 * band
2242 {
2243 from = low.min(high) + 1;
2244 while lows.front().is_some_and(|&k| k < from) {
2245 lows.pop_front();
2246 }
2247 while highs.front().is_some_and(|&k| k < from) {
2248 highs.pop_front();
2249 }
2250 }
2251 if time[index] - time[from] >= resting_s {
2252 // The window's lowest is at the front of `lows`, which holds `index` at least.
2253 let level_m = lows.front().map_or(h, |&k| filtered[k]);
2254 last_rest = match last_rest {
2255 Some((first, _, last)) if last + 1 == index => Some((first, level_m, index)),
2256 _ => Some((from, level_m, index)),
2257 };
2258 }
2259 }
2260 let Some((from, level_m, last)) = last_rest else {
2261 return BeforeClimb::Falls(Fall {
2262 begin,
2263 depth_m,
2264 resting_s,
2265 after_rest: false,
2266 });
2267 };
2268 let then_falls = (last + 1..climb)
2269 .filter(|index| filtered[*index].is_finite())
2270 .map(|index| filtered[index])
2271 .min_by(f64::total_cmp)
2272 .map(|lowest| level_m - lowest)
2273 .filter(|depth_m| *depth_m > rise)
2274 .map(|depth_m| Fall {
2275 begin: last + 1,
2276 depth_m,
2277 resting_s,
2278 after_rest: true,
2279 });
2280 BeforeClimb::Rests {
2281 from,
2282 last,
2283 level_m,
2284 before_end: begin,
2285 then_falls,
2286 }
2287}
2288
2289/// How many of a log's first samples are looked at for being bad.
2290const FIRST_SAMPLES: usize = 3;
2291
2292/// The log's heights with its bad first samples taken out, or `None` if it starts well (#1076).
2293///
2294/// One of the first three is bad if it stands more than `rise` and three times the barometer's
2295/// noise above the second lowest of the samples after them. A raw sample carries the noise the
2296/// filtered track doesn't, and the second lowest leaves out a low sample among them, the second of
2297/// two bad ones. Those samples span the median's window, and at least five, so that the slowest
2298/// logs' short window sees past two bad samples. A sample low on the start is left: a logger that
2299/// writes its zero and then the climb from some meters up looks the same (#1103).
2300///
2301/// All three standing apart is a fall of the track's own, a pressure pulse on the pad at ignition
2302/// by its look (#1101), and Juno III's dip of 8.5 m stays under the margin. A level the filtered
2303/// track returns to and stays at is the pad, and the low stretch after the first samples is the
2304/// disturbance: from rest at [`LIFTOFF_ACCELERATION_M_S2`] a rocket leaves that band sooner than
2305/// the stay asked for. Crossing it slower still, in `T` seconds with no thrust in the band's upper
2306/// part, it is within `b + (2 b / T)² / (2 g)` of its top, `b` the band's half width: its speed at
2307/// the band's upper edge is at most its mean through the band, and it slows at `g` or more. So a
2308/// level that near the top is no pad.
2309fn without_bad_start(heights: &[f64], time: &[f64], half: usize, rise: f64) -> Option<Vec<f64>> {
2310 let span = (2 * half + 1).max(5);
2311 let mut after: Vec<f64> = heights
2312 .get(FIRST_SAMPLES..FIRST_SAMPLES + span)?
2313 .iter()
2314 .copied()
2315 .filter(|h| h.is_finite())
2316 .collect();
2317 if after.len() < 3 {
2318 return None;
2319 }
2320 after.sort_by(f64::total_cmp);
2321 let above = after[1] + rise + 3.0 * NOISE_M;
2322 let bad: Vec<usize> = (0..FIRST_SAMPLES).filter(|k| heights[*k] > above).collect();
2323 let first = *bad.first()?;
2324 if bad.len() == FIRST_SAMPLES {
2325 return None;
2326 }
2327 let mut kept = heights.to_vec();
2328 for &k in &bad {
2329 kept[k] = f64::NAN;
2330 }
2331 let filtered = running_median(&kept, half);
2332 let top = arg_max(&filtered)?;
2333 let start_level = heights[first];
2334 let mut stay_from = None;
2335 let mut longest_s: f64 = 0.0;
2336 for (h, t) in filtered[..top].iter().zip(time) {
2337 if (h - start_level).abs() <= rise {
2338 let from = *stay_from.get_or_insert(*t);
2339 longest_s = longest_s.max(t - from);
2340 } else {
2341 stay_from = None;
2342 }
2343 }
2344 let leaving_s = (4.0 * rise / LIFTOFF_ACCELERATION_M_S2).sqrt();
2345 let is_pad = longest_s > 0.0 && longest_s >= leaving_s && {
2346 let crossing_m_s = 2.0 * rise / longest_s;
2347 filtered[top]
2348 > start_level + rise + crossing_m_s * crossing_m_s / (2.0 * STANDARD_GRAVITY_MPS2)
2349 };
2350 (!is_pad).then_some(kept)
2351}
2352
2353/// The first sample from `from` on whose height is under `mark` and from which the heights stay
2354/// under `ceiling` (a gap is not under it) for `span_s`, the span ending by the record's last
2355/// sample; `heights` and `time` are as long as each other or `time` longer, `time` increasing.
2356///
2357/// `high` is the first sample from the candidate on that isn't under the ceiling; it only moves
2358/// forward, so the scan is linear in the samples, but for a binary search's logarithm at each
2359/// candidate, where checking each candidate's span sample by sample costs a burst's square
2360/// (#1250).
2361fn first_settled(
2362 heights: &[f64],
2363 time: &[f64],
2364 from: usize,
2365 (mark, ceiling): (f64, f64),
2366 span_s: f64,
2367) -> Option<usize> {
2368 let n = heights.len();
2369 let end = time[n.checked_sub(1)?];
2370 let mut high = from;
2371 (from..n).find(|&index| {
2372 high = high.max(index);
2373 if !(heights[index] < mark && time[index] + span_s <= end) {
2374 return false;
2375 }
2376 while high < n && heights[high] < ceiling {
2377 high += 1;
2378 }
2379 let span_end = index + time[index..n].partition_point(|t| *t <= time[index] + span_s);
2380 high >= span_end
2381 })
2382}
2383
2384/// Apogee, as landing needs it.
2385struct Apex {
2386 index: usize,
2387 time_s: f64,
2388 height_bound_m: f64,
2389 time_bound_s: f64,
2390}
2391
2392/// Landing and the descent, or why they are withheld.
2393fn landing(
2394 track: &Track,
2395 filtered: &[f64],
2396 pad: f64,
2397 apex: &Apex,
2398 (allowance, pad_error_m): (f64, f64),
2399) -> Reading<Landing> {
2400 let time = &track.time_s;
2401 let end = time[filtered.len() - 1];
2402 // Debrief's marks, raised to the pad's own reach and step where those are more, as the
2403 // liftoff's is, so a coarse or noisy track flickering on the ground doesn't hold landing off.
2404 let level = LANDING_HEIGHT_M.max(allowance);
2405 let ceiling = level + (LANDED_CEILING_M - LANDING_HEIGHT_M) + track.step_m;
2406 let landed = first_settled(
2407 filtered,
2408 time,
2409 apex.index + 1,
2410 (pad + level, pad + ceiling),
2411 LANDED_FOR_S,
2412 );
2413 let Some(index) = landed else {
2414 return Reading::withheld(
2415 Reason::EndsBeforeLanding,
2416 format!(
2417 "the log ends at {end:.2} s, {:.1} m above the pad. It ends before the altitude \
2418 comes within {level:.1} m of the pad and stays under {ceiling:.1} m for \
2419 {LANDED_FOR_S} s",
2420 filtered[filtered.len() - 1] - pad
2421 ),
2422 );
2423 };
2424 let descent_time_s = time[index] - apex.time_s;
2425 let drop = filtered[apex.index] - filtered[index];
2426 // The quickest any fall from rest at apogee can lose that height: in vacuum. Both heights
2427 // are stepped, so the drop can read up to one step long; and the apogee's time, the middle
2428 // of its flat run, can sit about half a sample from the true one, so a sample is allowed. A
2429 // test passes a vacuum fall in feet at 10 to 100 samples a second, wherever its apogee falls
2430 // within a foot and its liftoff between samples, and fails without either.
2431 let quickest = (2.0 * (drop - track.step_m).max(0.0) / STANDARD_GRAVITY_MPS2).sqrt();
2432 if descent_time_s + local_interval(time, index) < quickest {
2433 return Reading::withheld(
2434 Reason::FasterThanFreeFall,
2435 format!(
2436 "the altitude reaches the pad {descent_time_s:.2} s after apogee, sooner than a \
2437 fall from rest in vacuum could ({quickest:.2} s). The trace isn't a height there"
2438 ),
2439 );
2440 }
2441 // The descent's rate near the ground, which sets how early the landing mark and the logger's
2442 // height on the pad put it: over the last 5 s before landing, or back to where the track was
2443 // four times its step and noise higher if that is longer, and taken a step and the noise at
2444 // either end slow, as a stepped, noisy drop can read that much long.
2445 let margin_m = track.step_m + 2.0 * NOISE_M;
2446 let back = time
2447 .partition_point(|t| *t < time[index] - 5.0)
2448 .min(
2449 (apex.index..index)
2450 .rev()
2451 .find(|&back| filtered[back] - filtered[index] >= 4.0 * margin_m)
2452 .unwrap_or(apex.index),
2453 )
2454 .max(apex.index);
2455 let rate = (filtered[back] - filtered[index] - margin_m) / (time[index] - time[back]);
2456 if rate.is_nan() || rate <= 0.0 {
2457 return Reading::withheld(
2458 Reason::NoClimb,
2459 format!(
2460 "the track falls {drop:.1} m from apogee to landing, too little past its step and \
2461 noise ({margin_m:.1} m) to time the descent"
2462 ),
2463 );
2464 }
2465 let mean_rate = drop / descent_time_s;
2466 let early_m = level
2467 + NOISE_M
2468 + pad_error_m
2469 + PAD_ABOVE_GROUND_M
2470 + track.step_m
2471 + DRIFT_M_PER_S * (time[index] - time[0]);
2472 let bound_s = early_m / rate + 2.0 * local_interval(time, index);
2473 let rate_bound = (apex.height_bound_m + early_m + mean_rate * (apex.time_bound_s + bound_s))
2474 / descent_time_s;
2475 Reading::Read(Landing {
2476 time_s: time[index],
2477 bound_s,
2478 interval_s: interval::LANDING_SHARES.interval(time[index], bound_s),
2479 descent_time_s,
2480 mean_descent_rate_m_s: mean_rate,
2481 mean_descent_rate_bound_m_s: rate_bound,
2482 mean_descent_rate_interval_m_s: interval::DESCENT_RATE_SHARES
2483 .interval(mean_rate, rate_bound),
2484 source: track.source,
2485 provenance: Provenance::Measured,
2486 method: Method::BackOnThePad,
2487 })
2488}
2489
2490#[cfg(test)]
2491mod tests {
2492 use super::*;
2493 use crate::log::Stated;
2494
2495 const DT: f64 = 0.05;
2496
2497 /// A log sampled every 0.05 s to `end_s`, its height from `flight`.
2498 fn log(end_s: f64, flight: impl Fn(f64) -> f64) -> FlightLog {
2499 log_every(DT, end_s, flight)
2500 }
2501
2502 /// A log sampled every `dt` s to `end_s`, its height from `flight`.
2503 fn log_every(dt: f64, end_s: f64, flight: impl Fn(f64) -> f64) -> FlightLog {
2504 let times: Vec<f64> = (0..)
2505 .map(|i| f64::from(i) * dt)
2506 .take_while(|t| *t <= end_s + 1e-9)
2507 .collect();
2508 let altitude_m: Vec<f64> = times.iter().map(|t| flight(*t)).collect();
2509 FlightLog {
2510 format: LogFormat::PerfectFlitePf2,
2511 logger: "PerfectFlite Pnut".to_owned(),
2512 serial_number: None,
2513 firmware: None,
2514 flight_number: None,
2515 stated: Stated::default(),
2516 time_s: times,
2517 altitude_m,
2518 vertical_speed_m_s: None,
2519 temperature_k: None,
2520 battery_v: None,
2521 channels: Vec::new(),
2522 events: Vec::new(),
2523 notes: Vec::new(),
2524 }
2525 }
2526
2527 /// The same log with its track moved to a channel of `quantity`, the record's own emptied,
2528 /// each height turned by `value`.
2529 fn as_channel(log: &FlightLog, quantity: Quantity, value: impl Fn(f64) -> f64) -> FlightLog {
2530 let mut moved = log.clone();
2531 moved.format = LogFormat::GenericTable;
2532 moved.channels = vec![Channel::new(
2533 "track",
2534 quantity,
2535 log.time_s.clone(),
2536 log.altitude_m.iter().map(|h| value(*h)).collect(),
2537 )];
2538 moved.time_s.clear();
2539 moved.altitude_m.clear();
2540 moved
2541 }
2542
2543 /// A climb at 4 g from 1 s to 2 s (19.6 m, 39.2 m/s), a vacuum coast to apogee at 6 s
2544 /// (98.1 m, `10 g` in meters), then down at `descent` m/s to the pad.
2545 fn flight(descent: f64) -> impl Fn(f64) -> f64 {
2546 let g = STANDARD_GRAVITY_MPS2;
2547 move |t| {
2548 if t <= 1.0 {
2549 0.0
2550 } else if t < 2.0 {
2551 2.0 * g * (t - 1.0).powi(2)
2552 } else if t < 6.0 {
2553 let c = t - 2.0;
2554 2.0 * g + 4.0 * g * c - 0.5 * g * c * c
2555 } else {
2556 let h = 10.0 * g - descent * (t - 6.0);
2557 h.max(0.0)
2558 }
2559 }
2560 }
2561
2562 /// One or two bad samples among the first three; three apart is a fall of the track's own; a
2563 /// level held again is the pad (#1076).
2564 #[test]
2565 fn bad_first_samples_are_told_from_a_fall_on_the_pad() {
2566 let rise = 5.0;
2567 let out = |heights: &[f64], half: usize| -> Vec<usize> {
2568 let time: Vec<f64> = (0..heights.len()).map(|k| 0.05 * k as f64).collect();
2569 without_bad_start(heights, &time, half, rise).map_or(Vec::new(), |kept| {
2570 (0..kept.len()).filter(|k| kept[*k].is_nan()).collect()
2571 })
2572 };
2573 let climbing =
2574 |from: f64| -> Vec<f64> { (0..40).map(|k| from + 9.0 * f64::from(k)).collect() };
2575 let pad_then_climb = || -> Vec<f64> {
2576 let mut heights = vec![0.0; 20];
2577 heights.extend(climbing(0.0));
2578 heights
2579 };
2580 // A clean climb, and noise on a flat pad.
2581 assert_eq!(out(&climbing(0.0), 3), [0_usize; 0]);
2582 let noise: Vec<f64> = (0..40)
2583 .map(|k| f64::from(k % 3))
2584 .chain(climbing(0.0))
2585 .collect();
2586 assert_eq!(out(&noise, 3), [0_usize; 0]);
2587 // Bad samples first, one or two of the three, high on a climb or on a pad, at both ends of
2588 // the median's reach.
2589 for half in [1, 3] {
2590 for bad in [&[0_usize][..], &[1], &[2], &[0, 1], &[0, 2], &[1, 2]] {
2591 let mut high = climbing(0.0);
2592 let mut up = pad_then_climb();
2593 for &k in bad {
2594 high[k] += 1_000.0;
2595 up[k] += 1_000.0;
2596 }
2597 assert_eq!(out(&high, half), bad, "high {half}");
2598 assert_eq!(out(&up, half), bad, "up {half}");
2599 }
2600 // Low on a pad: a logger's zero before the climb looks the same, and they stay.
2601 for bad in [&[0_usize][..], &[1], &[2], &[0, 1], &[0, 2], &[1, 2]] {
2602 let mut low = pad_then_climb();
2603 for &k in bad {
2604 low[k] -= 1_000.0;
2605 }
2606 assert_eq!(out(&low, half), [0_usize; 0], "low {half}");
2607 }
2608 }
2609 // Three: the track's own.
2610 let mut heights = climbing(0.0);
2611 for sample in &mut heights[..3] {
2612 *sample += 1_000.0;
2613 }
2614 assert_eq!(out(&heights, 3), [0_usize; 0]);
2615 // Juno III's first rows, then the climb, with no bad sample among them; a far larger fall.
2616 for first in [
2617 &[0.0, 0.0, 0.0, -0.9, -2.8, -7.6, -8.5, -8.5, -7.6, -2.8, 0.0][..],
2618 &[
2619 0.0, 0.0, 0.0, -28.0, -30.0, -44.0, -92.0, -193.0, -348.0, -500.0, -900.0,
2620 ],
2621 ] {
2622 let mut heights = first.to_vec();
2623 heights.extend(climbing(2.0));
2624 assert_eq!(out(&heights, 3), [0_usize; 0], "{first:?}");
2625 }
2626 // Good samples, a low stretch, and the pad held again: nothing taken out, though two of
2627 // them stand above it.
2628 let mut held: Vec<f64> = vec![0.0, 0.0];
2629 held.extend(vec![-1_000.0; 8]);
2630 held.extend(vec![0.0; 40]);
2631 held.extend(climbing(0.0));
2632 assert_eq!(out(&held, 3), [0_usize; 0]);
2633 // At the margin exactly nothing stands apart. Too short a log to tell.
2634 let mut at_rise = pad_then_climb();
2635 at_rise[0] = rise + 3.0 * NOISE_M;
2636 assert_eq!(out(&at_rise, 3), [0_usize; 0]);
2637 assert_eq!(out(&[1_000.0, 0.0, 1.0], 3), [0_usize; 0]);
2638 // A bad level the track reaches only near its top is no pad: the arc lingers there.
2639 let arc: Vec<f64> = (0..200)
2640 .map(|k| 500.0 - 0.5 * STANDARD_GRAVITY_MPS2 * (0.05 * (f64::from(k) - 100.0)).powi(2))
2641 .collect();
2642 let mut near_top = arc.clone();
2643 near_top[0] = 498.0;
2644 near_top[1] = 498.0;
2645 assert_eq!(out(&near_top, 3), [0, 1]);
2646 // Nothing after the first samples to judge them by: good ones stay.
2647 assert_eq!(out(&[f64::NAN; 40], 3), [0_usize; 0]);
2648 let mut dropout = vec![f64::NAN; 40];
2649 dropout[0] = 5.0;
2650 dropout[1] = 6.0;
2651 assert_eq!(out(&dropout, 3), [0_usize; 0]);
2652 // One high sample and one low among those after: the low one isn't what the high is judged by.
2653 // Too few samples after them to judge them by.
2654 let mut few = vec![f64::NAN; 40];
2655 few[0] = 300.0;
2656 few[1] = 300.0;
2657 few[3] = 0.0;
2658 assert_eq!(out(&few, 3), [0_usize; 0]);
2659 few[4] = 0.0;
2660 assert_eq!(out(&few, 3), [0_usize; 0]);
2661 // A boost at the least the readings take stays at a level longer than the median's span,
2662 // and leaves it sooner than a pad.
2663 let mut slow_boost: Vec<f64> = (0..200)
2664 .map(|k| 0.5 * LIFTOFF_ACCELERATION_M_S2 * (0.05 * f64::from(k)).powi(2))
2665 .collect();
2666 slow_boost[0] = 20.0;
2667 slow_boost[1] = 20.0;
2668 assert_eq!(out(&slow_boost, 3), [0, 1]);
2669 let mut mixed = pad_then_climb();
2670 mixed[0] += 300.0;
2671 mixed[3] -= 1_000.0;
2672 assert_eq!(out(&mixed, 3), [0]);
2673 // A low sample just after the three doesn't make good ones bad, at either end of the
2674 // median's reach, nor one low among the three and one after.
2675 for half in [1, 3] {
2676 let mut third = pad_then_climb();
2677 third[3] -= 100.0;
2678 assert_eq!(out(&third, half), [0_usize; 0]);
2679 third[2] -= 100.0;
2680 assert_eq!(out(&third, half), [0_usize; 0]);
2681 }
2682 }
2683
2684 /// A log cut on the climb holds neither the rocket's top height nor, for all it knows, its top
2685 /// speed: both are floors with no interval (#1089). The whole flight's top speed states one.
2686 #[test]
2687 fn a_log_cut_on_the_climb_states_its_top_speed_as_a_floor() {
2688 let whole = log(30.0, flight(10.0));
2689 let read_whole = read(&whole);
2690 let top = read_whole.max_speed.value().unwrap();
2691 assert!(!top.is_floor, "{top:?}");
2692 assert!(top.interval_m_s.is_some(), "{top:?}");
2693 let apogee_s = read_whole.apogee.value().unwrap().time_s;
2694 let mut cut = whole.clone();
2695 // Halfway to apogee: the track's top is at the log's end.
2696 let keep = cut.time_s.iter().position(|t| *t > apogee_s / 2.0).unwrap();
2697 cut.time_s.truncate(keep);
2698 cut.altitude_m.truncate(keep);
2699 let read_cut = read(&cut);
2700 assert!(read_cut.apogee.value().unwrap().is_floor);
2701 let top = read_cut.max_speed.value().unwrap();
2702 assert!(top.is_floor, "{top:?}");
2703 assert_eq!(top.interval_m_s, None, "{top:?}");
2704 }
2705
2706 /// Each reading of the height track states the 90% interval its own shares make of its own
2707 /// value and bound, no other's ([ADR-308](https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0308-m7-2e-in-four-the-intervals-by-reading-then-the-surfaces.md)).
2708 #[test]
2709 fn each_reading_states_the_interval_its_own_shares_make() {
2710 use interval::*;
2711 let readings = read(&log(30.0, flight(10.0)));
2712 let liftoff = readings.liftoff.value().unwrap();
2713 let apogee = readings.apogee.value().unwrap();
2714 let speed = readings.max_speed.value().unwrap();
2715 let landing = readings.landing.value().unwrap();
2716 let flight_time = readings.flight_time.value().unwrap();
2717 let stated = [
2718 (
2719 liftoff.interval_s,
2720 LIFTOFF_SHARES,
2721 liftoff.time_s,
2722 liftoff.bound_s,
2723 ),
2724 (
2725 apogee.height_interval_m,
2726 APOGEE_HEIGHT_SHARES,
2727 apogee.height_m,
2728 apogee.bound_m,
2729 ),
2730 (
2731 apogee.time_interval_s,
2732 APOGEE_TIME_SHARES,
2733 apogee.time_s,
2734 apogee.time_bound_s,
2735 ),
2736 (
2737 speed.interval_m_s,
2738 TOP_SPEED_SHARES,
2739 speed.speed_m_s,
2740 speed.bound_m_s,
2741 ),
2742 (
2743 landing.interval_s,
2744 LANDING_SHARES,
2745 landing.time_s,
2746 landing.bound_s,
2747 ),
2748 (
2749 flight_time.interval_s,
2750 FLIGHT_TIME_SHARES,
2751 flight_time.time_s,
2752 flight_time.bound_s,
2753 ),
2754 (
2755 landing.mean_descent_rate_interval_m_s,
2756 DESCENT_RATE_SHARES,
2757 landing.mean_descent_rate_m_s,
2758 landing.mean_descent_rate_bound_m_s,
2759 ),
2760 ];
2761 for (k, (interval, shares, value, bound)) in stated.into_iter().enumerate() {
2762 let interval = interval.unwrap();
2763 assert_eq!(Some(interval), shares.interval(value, bound), "reading {k}");
2764 assert_eq!(interval.low, value - shares.high * bound, "reading {k}");
2765 assert_eq!(interval.high, value - shares.low * bound, "reading {k}");
2766 }
2767 // No two readings share their shares, so a reading wired to another's would fail above.
2768 let all = [
2769 LIFTOFF_SHARES,
2770 APOGEE_HEIGHT_SHARES,
2771 APOGEE_TIME_SHARES,
2772 TOP_SPEED_SHARES,
2773 LANDING_SHARES,
2774 FLIGHT_TIME_SHARES,
2775 DESCENT_RATE_SHARES,
2776 ];
2777 for (i, a) in all.iter().enumerate() {
2778 for b in &all[i + 1..] {
2779 assert_ne!(a, b);
2780 }
2781 }
2782 // Liftoff is read late and the flight time short, so their intervals lie wholly before
2783 // and wholly after the reading.
2784 assert!(liftoff.interval_s.unwrap().high < liftoff.time_s);
2785 assert!(flight_time.interval_s.unwrap().low > flight_time.time_s);
2786 }
2787
2788 /// The test flight reads: liftoff by the allowance's climb after 1 s, apogee at 6 s, the top
2789 /// speed at 2 s, landing below 2 m, each within its bound.
2790 #[test]
2791 fn a_plain_flight_reads() {
2792 let readings = read(&log(30.0, flight(10.0)));
2793 assert_eq!(readings.source, Some(Source::Barometer));
2794 let liftoff = readings.liftoff.value().unwrap();
2795 // 2 m above the pad at 1 + √(1/g) = 1.32 s: the last sample at or below it.
2796 assert!((liftoff.time_s - 1.3).abs() < 1e-9, "{}", liftoff.time_s);
2797 assert!(liftoff.time_s - 1.0 <= liftoff.bound_s);
2798 let apogee = readings.apogee.value().unwrap();
2799 let g = STANDARD_GRAVITY_MPS2;
2800 assert!((apogee.time_s - 6.0).abs() <= apogee.time_bound_s);
2801 assert!((apogee.height_m - 10.0 * g).abs() <= apogee.bound_m);
2802 // The peak is a corner, the descent starting at once: the median takes 0.36 m off it.
2803 assert!(
2804 (apogee.height_m - 10.0 * g).abs() < 0.5,
2805 "{}",
2806 apogee.height_m
2807 );
2808 assert_eq!(apogee.provenance, Provenance::Measured);
2809 let speed = readings.max_speed.value().unwrap();
2810 assert!((speed.speed_m_s - 4.0 * g).abs() <= speed.bound_m_s);
2811 assert!(
2812 (speed.time_s - 2.0).abs() <= 0.5 * SPEED_WINDOW_S,
2813 "{}",
2814 speed.time_s
2815 );
2816 assert_eq!(speed.provenance, Provenance::Derived);
2817 assert_eq!(speed.method, Method::SteepestSlope);
2818 let landing = readings.landing.value().unwrap();
2819 // 98.1 m at 10 m/s from 6 s: down at 15.81 s.
2820 let touchdown = 6.0 + g;
2821 assert!((landing.time_s - touchdown).abs() <= landing.bound_s);
2822 assert!(landing.time_s < touchdown);
2823 let rate = 10.0 * g / (touchdown - 6.0);
2824 assert!(
2825 (landing.mean_descent_rate_m_s - rate).abs() <= landing.mean_descent_rate_bound_m_s
2826 );
2827 assert_eq!(
2828 readings.max_acceleration.reason(),
2829 Some(Reason::NoAccelerometer)
2830 );
2831 }
2832
2833 /// The same flight reads alike from a pressure channel, a barometric altitude channel above
2834 /// sea level and a primary track; a GNSS altitude gives no reading, by name.
2835 #[test]
2836 fn every_track_reads_but_gnss() {
2837 let primary = log(30.0, flight(10.0));
2838 let air = Ussa76::standard();
2839 let site = 1200.0;
2840 let pressure = as_channel(&primary, Quantity::Pressure, |h| {
2841 air.sample(site + h).unwrap().air.pressure_pa
2842 });
2843 let msl = as_channel(&primary, Quantity::AltitudeMsl, |h| site + h);
2844 let base = read(&primary);
2845 let height = base.apogee.value().unwrap().height_m;
2846 for (record, source) in [
2847 (&pressure, Source::Pressure),
2848 (&msl, Source::AltitudeChannel),
2849 ] {
2850 let readings = read(record);
2851 assert_eq!(readings.source, Some(source));
2852 let apogee = readings.apogee.value().unwrap();
2853 assert_eq!(apogee.source, source);
2854 // Geometric and geopotential heights differ by 0.02% here.
2855 assert!(
2856 (apogee.height_m - height).abs() < 0.05,
2857 "{source:?}: {}",
2858 apogee.height_m
2859 );
2860 assert!(readings.landing.value().is_some(), "{source:?}");
2861 assert!(readings.liftoff.value().is_some(), "{source:?}");
2862 }
2863 let gnss = read(&as_channel(&primary, Quantity::GnssAltitude, |h| site + h));
2864 assert_eq!(gnss.source, Some(Source::Gnss));
2865 assert_eq!(gnss.liftoff.reason(), Some(Reason::ReceiverDropout));
2866 assert_eq!(gnss.apogee.reason(), Some(Reason::ReceiverLag));
2867 assert_eq!(gnss.max_speed.reason(), Some(Reason::ReceiverLag));
2868 assert_eq!(gnss.landing.reason(), Some(Reason::Needs));
2869 let mut gpx = as_channel(&primary, Quantity::Altitude, |h| site + h);
2870 assert_eq!(read(&gpx).apogee.reason(), Some(Reason::UnstatedSensor));
2871 gpx.format = LogFormat::Gpx;
2872 assert_eq!(read(&gpx).apogee.reason(), Some(Reason::ReceiverLag));
2873 let mut nothing = as_channel(&primary, Quantity::Temperature, |h| h);
2874 assert_eq!(read(¬hing).apogee.reason(), Some(Reason::NoHeightTrack));
2875 nothing.channels.clear();
2876 assert_eq!(read(¬hing).landing.reason(), Some(Reason::NoHeightTrack));
2877 }
2878
2879 /// Each withheld reading names the reason that fired, and only the readings that need it go.
2880 #[test]
2881 fn each_refusal_names_its_reason() {
2882 let short = read(&log(0.05, flight(10.0)));
2883 for reason_of in [
2884 short.liftoff.reason(),
2885 short.apogee.reason(),
2886 short.max_speed.reason(),
2887 short.landing.reason(),
2888 ] {
2889 assert_eq!(reason_of, Some(Reason::TooShort));
2890 }
2891
2892 let flat = read(&log(10.0, |_| 0.5));
2893 assert_eq!(flat.apogee.reason(), Some(Reason::NoClimb));
2894 assert_eq!(flat.landing.reason(), Some(Reason::NoClimb));
2895
2896 // Starting 19.6 m up and climbing, as a log that starts after liftoff: no pad. A reader's
2897 // altitude stands on the logger's zero, so the apogee reads from it; liftoff, before the
2898 // log, and the top speed, at its start, are withheld.
2899 let aloft = read(&log(30.0, |t| flight(10.0)(t + 2.0)));
2900 assert_eq!(aloft.pad_altitude_m, Some(0.0));
2901 assert_eq!(aloft.liftoff.reason(), Some(Reason::ShortPad));
2902 assert_eq!(aloft.max_speed.reason(), Some(Reason::ShortPad));
2903 // The median reads the sharp top, where the descent starts at 10 m/s, 0.11 m low.
2904 let apogee = aloft.apogee.value().unwrap();
2905 assert!(
2906 (apogee.height_m - 10.0 * STANDARD_GRAVITY_MPS2).abs() < 0.2,
2907 "{}",
2908 apogee.height_m
2909 );
2910 assert_eq!(apogee.time_after_liftoff_s, None);
2911 assert!(aloft.landing.value().is_some());
2912 assert_eq!(aloft.flight_time.reason(), Some(Reason::ShortPad));
2913 // A mapped table that writes its zero, then the climb from 23.5 m up, as a logger that
2914 // records from launch does: its first sample says its heights stand on the pad, which
2915 // the median, lifted into the climb at the start, wouldn't.
2916 let mut zero_first = log(30.0, |t| flight(10.0)(t + 2.1));
2917 zero_first.format = LogFormat::GenericTable;
2918 zero_first.altitude_m[0] = 0.0;
2919 let zero_first = read(&zero_first);
2920 assert_eq!(zero_first.pad_altitude_m, Some(0.0));
2921 assert_eq!(zero_first.liftoff.reason(), Some(Reason::ShortPad));
2922 assert!(zero_first.apogee.value().is_some());
2923 // A track with no zero on the pad, as a pressure track, can't place it: every height
2924 // reading is withheld.
2925 let pressure = as_channel(
2926 &log(30.0, |t| flight(10.0)(t + 2.0)),
2927 Quantity::Pressure,
2928 |h| 101_325.0 - 12.0 * h,
2929 );
2930 let pressure = read(&pressure);
2931 for reason_of in [
2932 pressure.liftoff.reason(),
2933 pressure.apogee.reason(),
2934 pressure.max_speed.reason(),
2935 pressure.landing.reason(),
2936 ] {
2937 assert_eq!(reason_of, Some(Reason::ShortPad));
2938 }
2939
2940 // A record a reader would never give: refused whole, and saying why.
2941 let mut short_speed = log(20.0, flight(10.0));
2942 short_speed.vertical_speed_m_s = Some(vec![0.0; 3]);
2943 let refused = read(&short_speed);
2944 assert_eq!(refused.apogee.reason(), Some(Reason::BadRecord));
2945 assert_eq!(refused.landing.reason(), Some(Reason::BadRecord));
2946 let mut repeated = log(20.0, flight(10.0));
2947 repeated.time_s[10] = repeated.time_s[9];
2948 assert_eq!(read(&repeated).liftoff.reason(), Some(Reason::BadRecord));
2949 // A channel's clock is the file's: one that runs back can't be read off, and one with a
2950 // time that isn't a number drops that sample.
2951 let pressure = as_channel(&log(20.0, flight(10.0)), Quantity::Pressure, |h| {
2952 101_325.0 - 12.0 * h
2953 });
2954 let mut channel_back = pressure.clone();
2955 channel_back.channels[0].time_s[10] = 0.0;
2956 assert_eq!(
2957 read(&channel_back).apogee.reason(),
2958 Some(Reason::ClockOutOfOrder)
2959 );
2960 let mut channel_gap = pressure;
2961 channel_gap.channels[0].time_s[10] = f64::NAN;
2962 assert!(read(&channel_gap).apogee.value().is_some());
2963
2964 let cut = read(&log(8.0, flight(10.0)));
2965 assert_eq!(cut.landing.reason(), Some(Reason::EndsBeforeLanding));
2966 assert!(cut.apogee.value().is_some());
2967
2968 // 98.1 m in 2.5 s: a vacuum fall from rest takes √(2 · 98.1/g) = 4.5 s.
2969 let dropped = read(&log(20.0, flight(4.0 * STANDARD_GRAVITY_MPS2)));
2970 assert_eq!(dropped.landing.reason(), Some(Reason::FasterThanFreeFall));
2971
2972 // Still climbing at the end: the apogee is a floor.
2973 let climbing = read(&log(4.0, flight(10.0)));
2974 let floor = climbing.apogee.value().unwrap();
2975 assert!(floor.is_floor);
2976 // A floor's truth may lie any amount above it, so it states no 90% interval; the same
2977 // flight read whole states both.
2978 assert!(floor.height_interval_m.is_none() && floor.time_interval_s.is_none());
2979 let whole = cut.apogee.value().unwrap();
2980 assert!(!whole.is_floor);
2981 assert!(whole.height_interval_m.is_some() && whole.time_interval_s.is_some());
2982 assert_eq!(climbing.landing.reason(), Some(Reason::EndsBeforeLanding));
2983
2984 // An accelerometer that doesn't say it lies along the axis gives no top acceleration.
2985 let mut accelerometer = log(30.0, flight(10.0));
2986 accelerometer.channels.push(Channel::new(
2987 "accel",
2988 Quantity::Acceleration,
2989 accelerometer.time_s.clone(),
2990 vec![0.0; accelerometer.time_s.len()],
2991 ));
2992 assert_eq!(
2993 read(&accelerometer).max_acceleration.reason(),
2994 Some(Reason::AxisUnstated)
2995 );
2996 }
2997
2998 /// The pad is the median of everything before the climb: a jitter in the first samples
2999 /// doesn't move liftoff to the start of the log.
3000 #[test]
3001 fn early_jitter_leaves_the_pad_where_it_is() {
3002 let foot = crate::perfectflite::FOOT_M;
3003 let mut log = log(30.0, |t| flight(10.0)(t - 2.0));
3004 for (index, feet) in [0.0, -1.0, -1.0, 0.0].into_iter().enumerate() {
3005 log.altitude_m[index] = feet * foot;
3006 }
3007 let read = read(&log);
3008 assert_eq!(read.pad_altitude_m, Some(0.0));
3009 assert!((read.liftoff.value().unwrap().time_s - 3.3).abs() < 1e-9);
3010 }
3011
3012 /// Noise on the pad up to the allowance doesn't move liftoff earlier: at half a foot, the
3013 /// rule before the readings were taken on every logger, it read at the pad's last low sample,
3014 /// two seconds early.
3015 #[test]
3016 fn pad_noise_within_the_allowance_leaves_liftoff() {
3017 let mut noisy = log(40.0, |t| flight(10.0)(t - 5.0));
3018 // The pad from 0 to 6 s, its last two seconds 1.5 m up, below the 2 m allowance.
3019 for (time, height) in noisy.time_s.iter().zip(noisy.altitude_m.iter_mut()) {
3020 if (4.0..=6.0).contains(time) {
3021 *height = 1.5;
3022 }
3023 }
3024 let readings = read(&noisy);
3025 let liftoff = readings.liftoff.value().unwrap();
3026 assert!((liftoff.time_s - 6.3).abs() < 1e-9, "{}", liftoff.time_s);
3027 assert!(liftoff.time_s - 6.0 <= liftoff.bound_s);
3028 }
3029
3030 /// A vacuum hop from `t0` to `apogee_m`, falling back at `fall_g` times gravity, its heights
3031 /// rounded to whole feet as a PerfectFlite writes them; and when it is back on the pad.
3032 fn hop(apogee_m: f64, t0: f64, fall_g: f64) -> (impl Fn(f64) -> f64, f64) {
3033 let g = STANDARD_GRAVITY_MPS2;
3034 let foot = crate::perfectflite::FOOT_M;
3035 let v0 = (2.0 * g * apogee_m).sqrt();
3036 let top = t0 + v0 / g;
3037 let fall = fall_g * g;
3038 let down = top + (2.0 * apogee_m / fall).sqrt();
3039 let flight = move |t: f64| {
3040 let h = if t <= t0 {
3041 0.0
3042 } else if t <= top {
3043 v0 * (t - t0) - 0.5 * g * (t - t0).powi(2)
3044 } else if t < down {
3045 apogee_m - 0.5 * fall * (t - top).powi(2)
3046 } else {
3047 0.0
3048 };
3049 (h / foot).round() * foot
3050 };
3051 (flight, down)
3052 }
3053
3054 /// The free-fall check passes a fall in vacuum wherever it falls between samples, with the
3055 /// heights rounded to feet, at 10 to 100 samples a second, and refuses one at 1.3 g. A low hop,
3056 /// just past the climb's mark of twice the allowance and the step, passes it and is then withheld,
3057 /// as it falls too little past its step and the noise for the descent's rate to be measured;
3058 /// the higher ones land. One below the mark never climbs.
3059 #[test]
3060 fn a_vacuum_fall_lands_and_a_faster_one_is_refused() {
3061 let foot = crate::perfectflite::FOOT_M;
3062 // Low hops, their apogees a fiftieth of a foot apart, where the rounding matters most,
3063 // just past the 4.6 m mark; and higher ones.
3064 let mark = 2.0 * (LIFTOFF_ALLOWANCE_M + foot);
3065 assert!(16.0 * foot > mark && 15.0 * foot < mark);
3066 let apogees: Vec<f64> = (0..50)
3067 .map(|k| (16.0 + f64::from(k) / 50.0) * foot)
3068 .chain([30.0, 300.0, 3000.0])
3069 .collect();
3070 for dt in [0.01, 0.05, 0.1] {
3071 for &apogee_m in &apogees {
3072 for step in 0..13 {
3073 let t0 = 1.0 + f64::from(step) * dt / 13.0;
3074 let (flight, down) = hop(apogee_m, t0, 1.0);
3075 let read = read(&log_every(dt, down + 3.0, flight));
3076 let low = apogee_m < 30.0;
3077 let lands = match &read.landing {
3078 Reading::Read(_) => !low,
3079 Reading::Withheld(withheld) => {
3080 low && withheld.reason == Reason::NoClimb
3081 && withheld.detail.contains("to time the descent")
3082 }
3083 };
3084 assert!(
3085 lands,
3086 "{dt} s, {apogee_m} m, from {t0} s: {:?}",
3087 read.landing
3088 );
3089 }
3090 }
3091 }
3092 let (below, down) = hop(15.0 * foot, 1.0, 1.0);
3093 assert_eq!(
3094 read(&log(down + 3.0, below)).apogee.reason(),
3095 Some(Reason::NoClimb)
3096 );
3097 for apogee_m in [100.0, 1000.0] {
3098 let (flight, down) = hop(apogee_m, 1.0, 1.3);
3099 let read = read(&log(down + 3.0, flight));
3100 assert_eq!(
3101 read.landing.reason(),
3102 Some(Reason::FasterThanFreeFall),
3103 "{apogee_m} m"
3104 );
3105 }
3106 }
3107
3108 /// The climb of [`flight`] lifting off at `t0`, read through a pulse at the barometer from
3109 /// `t0` that reads the track `depth` m low at `t0 + 0.4` s and is gone by `t0 + 0.8` s, as a
3110 /// pressure pulse on the pad at ignition might (#1101).
3111 fn pulsed(t0: f64, depth: f64) -> impl Fn(f64) -> f64 {
3112 let climb = flight(10.0);
3113 move |t| {
3114 let k = t - t0;
3115 let pulse = if (0.0..0.8).contains(&k) {
3116 depth * (1.0 - (k - 0.4).abs() / 0.4)
3117 } else {
3118 0.0
3119 };
3120 climb(k + 1.0) - pulse
3121 }
3122 }
3123
3124 /// A fall into the climb isn't the pad (#1101): the pad is read from before it, or from the
3125 /// logger's zero when too little comes before it, so the apogee holds its bound of the truth.
3126 /// The top speed is withheld; liftoff holds its bound, which reaches back over the fall, or is
3127 /// withheld where the log starts in the fall. With no zero and too little pad, every reading
3128 /// is withheld. A fall to a level the track then holds is no disturbance, and the last level
3129 /// it holds before the climb is the pad (#1158).
3130 #[test]
3131 fn a_pulse_at_ignition_isnt_the_pad() {
3132 let truth_m = 10.0 * STANDARD_GRAVITY_MPS2;
3133 let holds = |read: &Readings, liftoff_s: Option<f64>, case: &str| {
3134 let apogee = read.apogee.value().unwrap();
3135 assert!(
3136 (apogee.height_m - truth_m).abs() <= apogee.bound_m,
3137 "{case}: {} m, bound {} m",
3138 apogee.height_m,
3139 apogee.bound_m
3140 );
3141 assert_eq!(
3142 read.max_speed.reason(),
3143 Some(Reason::DisturbedPad),
3144 "{case}"
3145 );
3146 match liftoff_s {
3147 Some(truth_s) => {
3148 let liftoff = read.liftoff.value().unwrap();
3149 assert!(liftoff.interval_s.is_none(), "{case}");
3150 assert!(
3151 (liftoff.time_s - truth_s).abs() <= liftoff.bound_s,
3152 "{case}: liftoff {} s, bound {} s",
3153 liftoff.time_s,
3154 liftoff.bound_s
3155 );
3156 }
3157 None => {
3158 assert_eq!(read.liftoff.reason(), Some(Reason::DisturbedPad), "{case}");
3159 assert!(apogee.time_after_liftoff_s.is_none(), "{case}");
3160 }
3161 }
3162 };
3163 // On the logger's zero: a few samples of pad, a long pad, or none, the log starting in
3164 // the fall after a liftoff before it.
3165 for (t0, depth, lifted) in [
3166 (0.25, 300.0, true),
3167 (0.25, 30.0, true),
3168 (3.0, 300.0, true),
3169 (-0.2, 300.0, false),
3170 ] {
3171 let read = read(&log(t0 + 30.0, pulsed(t0, depth)));
3172 let case = format!("zero, liftoff at {t0} s, fall {depth} m");
3173 holds(&read, lifted.then_some(t0), &case);
3174 assert_eq!(read.pad_altitude_m, Some(0.0), "{case}");
3175 }
3176 // A pressure track has no zero: a long pad before the pulse places it, a short one can't.
3177 let on_pressure = |t0: f64| {
3178 let pressure = as_channel(
3179 &log(t0 + 30.0, pulsed(t0, 300.0)),
3180 Quantity::Pressure,
3181 |h| 101_325.0 - 12.0 * h,
3182 );
3183 read(&pressure)
3184 };
3185 holds(&on_pressure(3.0), Some(3.0), "pressure, pad 3 s");
3186 let short = on_pressure(0.25);
3187 for reason in [
3188 short.liftoff.reason(),
3189 short.apogee.reason(),
3190 short.max_speed.reason(),
3191 short.landing.reason(),
3192 ] {
3193 assert_eq!(reason, Some(Reason::DisturbedPad));
3194 }
3195 // Carried 30 m down to the pad and set there for 4 s: the pad is where it rests, its
3196 // filtered heights spread over more than half the rise from any one of them, though
3197 // within the rise (4.61 m on a PerfectFlite).
3198 let climb = flight(10.0);
3199 for spread_m in [0.0, 1.6] {
3200 let walked = read(&log(40.0, |t| {
3201 let noise = if (t / DT).round() % 2.0 == 0.0 {
3202 spread_m
3203 } else {
3204 -spread_m
3205 };
3206 if t < 2.0 {
3207 30.0
3208 } else if t < 6.0 {
3209 noise
3210 } else {
3211 climb(t - 5.0)
3212 }
3213 }));
3214 assert!(
3215 walked.liftoff.value().is_some(),
3216 "{spread_m}: {:?}",
3217 walked.liftoff
3218 );
3219 assert!(
3220 walked.max_speed.reason() != Some(Reason::DisturbedPad),
3221 "{spread_m}"
3222 );
3223 assert!(
3224 walked.pad_altitude_m.unwrap().abs() <= spread_m,
3225 "{spread_m}"
3226 );
3227 let apogee = walked.apogee.value().unwrap();
3228 assert!(
3229 (apogee.height_m - truth_m).abs() <= apogee.bound_m,
3230 "{spread_m}"
3231 );
3232 }
3233 // A gap in the samples during the fall isn't a rest: the fall is still found.
3234 let mut gapped = log(33.0, pulsed(3.0, 300.0));
3235 for h in &mut gapped.altitude_m[63..76] {
3236 *h = f64::NAN;
3237 }
3238 assert_eq!(read(&gapped).max_speed.reason(), Some(Reason::DisturbedPad));
3239 }
3240
3241 /// A log that rests at a higher level, then on the pad before the climb (#1158). The median of
3242 /// every sample near the log's start took the higher level for the pad, and the apogee read low
3243 /// by the drop, outside its bound. Now the last rest before the climb is the pad, and the gap
3244 /// to the start's level enters the pad's error, as a logger carried down to the pad and a level
3245 /// the pressure moved to before liftoff look alike. So the apogee holds its bound, or is
3246 /// withheld, on every shape here: carried down, sunk to a plateau and stepped or walked back
3247 /// up, a stretch far below, a pulse after the rest. Each runs on the logger's zero and on a
3248 /// pressure track, most quiet and with heights alternating 3.2 m apart, more than half the rise
3249 /// (2.30 m on a PerfectFlite) though within it (4.61 m).
3250 #[test]
3251 fn the_pad_is_the_last_rest_before_the_climb() {
3252 let truth_m = 10.0 * STANDARD_GRAVITY_MPS2;
3253 let climb = flight(10.0);
3254 // The log's height from `before` until `liftoff_s`, then the climb from `from_m`; read on
3255 // both tracks.
3256 let both = |liftoff_s: f64, from_m: f64, spread_m: f64, before: &dyn Fn(f64) -> f64| {
3257 let carried = log(liftoff_s + 30.0, |t| {
3258 let noise = if (t / DT).round() % 2.0 == 0.0 {
3259 spread_m
3260 } else {
3261 -spread_m
3262 };
3263 if t < liftoff_s {
3264 before(t) + noise
3265 } else {
3266 from_m + climb(t - liftoff_s + 1.0)
3267 }
3268 });
3269 let pressure = as_channel(&carried, Quantity::Pressure, |h| 101_325.0 - 12.0 * h);
3270 [("zero", read(&carried)), ("pressure", read(&pressure))]
3271 };
3272 // The apogee holds its bound of the truth, or is withheld.
3273 let holds = |read: &Readings, case: &str| {
3274 if let Some(apogee) = read.apogee.value() {
3275 assert!(
3276 (apogee.height_m - truth_m).abs() <= apogee.bound_m,
3277 "{case}: {} m, bound {} m",
3278 apogee.height_m,
3279 apogee.bound_m
3280 );
3281 }
3282 };
3283 // Read from the pad: its level, the apogee and liftoff within their bounds.
3284 let reads = |read: &Readings, liftoff_s: f64, pad_m: f64, case: &str| {
3285 if let Some(pad) = read.pad_altitude_m.filter(|_| case.starts_with("zero")) {
3286 assert!((pad - pad_m).abs() <= 1.6, "{case}: pad {pad} m");
3287 }
3288 assert!(read.apogee.value().is_some(), "{case}: {:?}", read.apogee);
3289 holds(read, case);
3290 let liftoff = read.liftoff.value().unwrap();
3291 assert!(
3292 (liftoff.time_s - liftoff_s).abs() <= liftoff.bound_s,
3293 "{case}: liftoff {} s, bound {} s",
3294 liftoff.time_s,
3295 liftoff.bound_s
3296 );
3297 };
3298 // Carried 30 or 60 m down: the issue's three cases, a stay on the pad a little over the
3299 // 0.69 s a rest takes, and longer stays on the pad. Read from the pad.
3300 for (above_s, high_m, pad_s) in [
3301 (5.0, 30.0, 3.0),
3302 (20.0, 30.0, 10.0),
3303 (2.0, 30.0, 4.0),
3304 (10.0, 30.0, 0.8),
3305 (3.0, 30.0, 5.0),
3306 (2.0, 60.0, 4.0),
3307 ] {
3308 for spread_m in [0.0, 1.6] {
3309 let liftoff_s = above_s + pad_s;
3310 let before = |t: f64| if t < above_s { high_m } else { 0.0 };
3311 for (track, read) in both(liftoff_s, 0.0, spread_m, &before) {
3312 let case = format!(
3313 "{track}: {above_s} s at {high_m} m, {pad_s} s on the pad, spread {spread_m} m"
3314 );
3315 reads(&read, liftoff_s, 0.0, &case);
3316 assert!(
3317 read.max_speed.reason() != Some(Reason::DisturbedPad),
3318 "{case}"
3319 );
3320 }
3321 }
3322 }
3323 // Above the apogee, the track never climbs from its start: withheld.
3324 let before = |t: f64| if t < 5.0 { 300.0 } else { 0.0 };
3325 for (track, read) in both(8.0, 0.0, 0.0, &before) {
3326 assert_eq!(read.apogee.reason(), Some(Reason::NoClimb), "{track}");
3327 }
3328 // Carried down slowly, at 1 m/s, then 2 s on the pad: the pad is read back from the climb,
3329 // not from where the walk down began to count as a rest.
3330 let before = |t: f64| (30.0 - (t - 2.0).max(0.0)).max(0.0);
3331 for (track, read) in both(34.0, 0.0, 0.0, &before) {
3332 reads(&read, 34.0, 0.0, &format!("{track}: carried down slowly"));
3333 }
3334 // Carried down, resting 5 s on the pad, then a pulse at ignition: read from the rest, the
3335 // top speed withheld as for a pulse from the start (#1101).
3336 let pulse = pulsed(7.0, 30.0);
3337 let carried = log(37.0, |t| {
3338 if t < 2.0 {
3339 30.0
3340 } else if t < 7.0 {
3341 0.0
3342 } else {
3343 pulse(t)
3344 }
3345 });
3346 let pressure = as_channel(&carried, Quantity::Pressure, |h| 101_325.0 - 12.0 * h);
3347 for (track, read) in [("zero", read(&carried)), ("pressure", read(&pressure))] {
3348 let case = format!("{track}: carried down, then a pulse");
3349 assert!(read.apogee.value().is_some(), "{case}: {:?}", read.apogee);
3350 holds(&read, &case);
3351 assert_eq!(
3352 read.max_speed.reason(),
3353 Some(Reason::DisturbedPad),
3354 "{case}"
3355 );
3356 }
3357 // Sunk 30, 60 or 100 m below the start for 1 to 5 s after 3 s there, then back up to the
3358 // start's level in a step or over 0.3 s, and the climb from there; or climbed from the
3359 // plateau, a level the pressure moved to. Quiet and noisy.
3360 for (low_m, plateau_s) in [
3361 (30.0, 1.0),
3362 (30.0, 3.0),
3363 (30.0, 5.0),
3364 (60.0, 3.0),
3365 (100.0, 3.0),
3366 (100.0, 5.0),
3367 ] {
3368 for spread_m in [0.0, 1.6] {
3369 for (back_s, from_m) in [(0.0, 0.0), (0.3, 0.0), (0.0, -low_m)] {
3370 let sunk_s = 3.0 + plateau_s;
3371 let before = |t: f64| {
3372 if t < 3.0 {
3373 0.0
3374 } else if t < sunk_s {
3375 -low_m
3376 } else {
3377 -low_m * (1.0 - (t - sunk_s) / back_s)
3378 }
3379 };
3380 for (track, read) in both(sunk_s + back_s, from_m, spread_m, &before) {
3381 holds(
3382 &read,
3383 &format!(
3384 "{track}: {plateau_s} s at -{low_m} m, back over {back_s} s, \
3385 climbing from {from_m} m, spread {spread_m} m"
3386 ),
3387 );
3388 }
3389 }
3390 }
3391 }
3392 // A stretch 30 or 1,000 m below for 1 s with a short return to the pad before liftoff.
3393 for (low_m, back_s) in [(30.0, 0.1), (1_000.0, 0.1), (1_000.0, 0.2)] {
3394 let before = |t: f64| if (3.0..4.0).contains(&t) { -low_m } else { 0.0 };
3395 for (track, read) in both(4.0 + back_s, 0.0, 0.0, &before) {
3396 holds(
3397 &read,
3398 &format!("{track}: 1 s at -{low_m} m, back {back_s} s"),
3399 );
3400 }
3401 }
3402 }
3403
3404 /// A log that starts 0.1 s before a fast liftoff, as a logger that records from launch writes
3405 /// its pad: its samples can't rule out that the rocket had climbed 52 m before the log, so the
3406 /// pad is the logger's zero, and liftoff is read at the last sample within its allowance.
3407 #[test]
3408 fn a_short_pad_is_the_loggers_zero() {
3409 let (flight, down) = hop(300.0, 0.1, 1.0);
3410 let read = read(&log(down + 3.0, flight));
3411 assert_eq!(read.pad_altitude_m, Some(0.0));
3412 let liftoff = read.liftoff.value().unwrap();
3413 assert!((liftoff.time_s - 0.1).abs() < 1e-9, "{}", liftoff.time_s);
3414 let apogee = read.apogee.value().unwrap();
3415 assert!(apogee.time_after_liftoff_s.is_some());
3416
3417 // A mapped table's track is above the pad only by the mapping's word (#646). Its zero sits
3418 // within 19.9 m of the pad, and with no pad to place, the first sample stands on it after
3419 // a climb of up to the pad's error: each bound takes the most the zero can then be off. So
3420 // the apogee, and liftoff and landing where given, hold whatever the zero's offset, from a
3421 // log that starts on the pad, or up the climb with its zero set there. A 60 m hop keeps
3422 // the bound's share for the day's air under the offsets, so each is seen.
3423 let foot = crate::perfectflite::FOOT_M;
3424 let truth_m = (60.0 / foot).round() * foot;
3425 for (t0, offset_m) in [
3426 (0.1, Some(0.0)),
3427 (0.1, Some(1.5)),
3428 (0.1, Some(15.0)),
3429 (0.1, Some(-10.0)),
3430 (-0.25, None),
3431 (-0.5, None),
3432 ] {
3433 let (flight, down) = hop(60.0, t0, 1.0);
3434 // With no offset given, the zero is where the log starts, up the climb.
3435 let offset_m = offset_m.unwrap_or(-flight(0.0));
3436 let mut mapped = log(down + 3.0, move |t| offset_m + flight(t));
3437 mapped.format = LogFormat::GenericTable;
3438 let got = super::read(&mapped);
3439 let apogee = got.apogee.value().unwrap();
3440 assert!(
3441 (apogee.height_m - truth_m).abs() <= apogee.bound_m,
3442 "{t0} {offset_m}: {} against {}",
3443 apogee.height_m - truth_m,
3444 apogee.bound_m
3445 );
3446 if let Some(liftoff) = got.liftoff.value() {
3447 assert!(
3448 (liftoff.time_s - t0).abs() <= liftoff.bound_s,
3449 "{t0} {offset_m}"
3450 );
3451 }
3452 if let Some(landing) = got.landing.value() {
3453 assert!(
3454 (landing.time_s - down).abs() <= landing.bound_s,
3455 "{t0} {offset_m}"
3456 );
3457 }
3458 }
3459 // Taking the zero's error as the first sample's distance from it alone fails the zero set
3460 // up the climb: the bound must allow for the climb before the log.
3461 let (flight, down) = hop(60.0, -0.5, 1.0);
3462 let start_m = flight(0.0);
3463 let mut mapped = log(down + 3.0, |t| flight(t) - start_m);
3464 mapped.format = LogFormat::GenericTable;
3465 let apogee_bound = super::read(&mapped).apogee.value().unwrap().bound_m;
3466 assert!(apogee_bound > start_m + NOISE_M, "{apogee_bound} {start_m}");
3467 // Sampled at 5 Hz, the track leaves its start at once, so the rocket may have climbed any
3468 // height before the log: the zero's error is the 19.9 m cap, and the bound stays finite.
3469 let mut coarse = log_every(0.2, down + 3.0, move |t| flight(t) - start_m);
3470 coarse.format = LogFormat::GenericTable;
3471 let coarse_bound = super::read(&coarse).apogee.value().unwrap().bound_m;
3472 assert!(
3473 coarse_bound > PAD_ZERO_M && coarse_bound < truth_m,
3474 "{coarse_bound}"
3475 );
3476 }
3477
3478 /// The pad is short where its samples can't rule out a rocket already past the allowance: a
3479 /// PerfectFlite's track 1 m off its zero, on the pad for `pad_s`, then climbing at 10 g for a
3480 /// second and coasting at gravity, sampled at 500 Hz, stays within half the 4.61 m rise of its
3481 /// start until 0.216 s after liftoff. A rocket at 2 g moving at `v` at the start would climb the rise in that time unless
3482 /// `v ≤ (rise − g stay²)/stay`, so it may have climbed `v²/(4g)`: 1.70 m after a 0.17 s pad,
3483 /// within the 2 m allowance, so the pad is its samples' and the apogee's bound grows by that;
3484 /// 2.51 m after 0.13 s, past it, so the pad is the zero. The climb's first samples lend the
3485 /// median 26 mm, within the eighth of the rise a constant acceleration can lend it.
3486 #[test]
3487 fn the_pad_is_short_where_the_rocket_may_have_left_it() {
3488 let g = STANDARD_GRAVITY_MPS2;
3489 let climb = |pad_s: f64| {
3490 move |t: f64| {
3491 let c = (t - pad_s).clamp(0.0, 1.0);
3492 let coast = (t - pad_s - 1.0).max(0.0);
3493 1.0 + 5.0 * g * c * c + 10.0 * g * coast - 0.5 * g * coast * coast
3494 }
3495 };
3496 let after = read(&log_every(MIN_INTERVAL_S, 14.0, climb(0.17)));
3497 let step = after.step_m.unwrap();
3498 let rise = 2.0 * (LIFTOFF_ALLOWANCE_M + step);
3499 let lent = after.pad_altitude_m.unwrap() - 1.0;
3500 assert!(lent > 0.0 && lent <= rise / 8.0, "{lent}");
3501 let before = read(&log_every(MIN_INTERVAL_S, 14.0, climb(0.13)));
3502 assert_eq!(before.pad_altitude_m, Some(0.0));
3503
3504 // The bound's share, against the same flight after a 2 s pad, whose samples rule it out;
3505 // the lent pad shortens the height, and its share of the bound, by under 3 mm.
3506 let long = read(&log_every(MIN_INTERVAL_S, 16.0, climb(2.0)));
3507 // The stay ends at the last sample within half the rise: the median of a rising track
3508 // is its sample.
3509 let stay = (0..)
3510 .map(|k| f64::from(k) * MIN_INTERVAL_S)
3511 .take_while(|t| climb(0.17)(*t) <= 1.0 + 0.5 * rise)
3512 .last()
3513 .unwrap();
3514 let speed = (rise - g * stay * stay) / stay;
3515 let pad_error = speed * speed / (4.0 * g);
3516 assert!(
3517 (pad_error - 1.70).abs() < 0.01,
3518 "pad error {pad_error}, stay {stay}"
3519 );
3520 let bound = |read: &Readings| read.apogee.value().unwrap().bound_m;
3521 let drift = DRIFT_M_PER_S * (0.17 - 2.0);
3522 assert!(
3523 (bound(&after) - bound(&long) - (pad_error + drift)).abs() < 3e-3,
3524 "{} against {}",
3525 bound(&after) - bound(&long),
3526 pad_error + drift
3527 );
3528 }
3529
3530 /// A noisy pad sampled slowly is still a pad: its first samples wobble by more than a meter,
3531 /// which the pad's start doesn't take for a climb, as a 1 m rise from the first sample did.
3532 #[test]
3533 fn a_noisy_slow_pad_is_still_a_pad() {
3534 let wobble = [
3535 -0.19, -2.42, -0.06, -1.71, -0.9, -1.3, -0.4, -2.0, -1.1, -0.7,
3536 ];
3537 let mut noisy = log_every(0.2, 40.0, |t| flight(10.0)(t - 2.0));
3538 for (height, noise) in noisy.altitude_m.iter_mut().zip(wobble.iter().cycle()) {
3539 *height += noise;
3540 }
3541 let read = read(&noisy);
3542 let liftoff = read.liftoff.value().unwrap();
3543 assert!(
3544 (liftoff.time_s - 3.0).abs() <= liftoff.bound_s,
3545 "{} within {}",
3546 liftoff.time_s,
3547 liftoff.bound_s
3548 );
3549 let pad = read.pad_altitude_m.unwrap();
3550 assert!((-2.42..=-0.06).contains(&pad), "{pad}");
3551 }
3552
3553 /// #646, both ways: a mapped altitude above sea level is refused as starting off the pad,
3554 /// and a millisecond clock read as seconds as sampled too slowly, or, from a logger fast
3555 /// enough to pass that, as slower than a coast; the same flights in their right units read.
3556 #[test]
3557 fn a_track_in_the_wrong_unit_is_refused() {
3558 let right = log(30.0, flight(10.0));
3559 assert!(read(&right).apogee.value().is_some());
3560 let mut msl = right.clone();
3561 msl.format = LogFormat::GenericTable;
3562 for height in &mut msl.altitude_m {
3563 *height += 1188.7;
3564 }
3565 let readings = read(&msl);
3566 assert_eq!(readings.apogee.reason(), Some(Reason::StartsOffThePad));
3567 let detail = match &readings.apogee {
3568 Reading::Withheld(withheld) => withheld.detail.clone(),
3569 Reading::Read(_) => String::new(),
3570 };
3571 assert!(detail.contains("above sea level"), "{detail}");
3572 // At the edge of a zero's hour of weather: just inside it reads, from the pad; just
3573 // outside, refused. A reader's altitude is above the pad by its format, so the same offset
3574 // in a PerfectFlite's log reads.
3575 let offset = |format: LogFormat, by: f64| {
3576 let mut moved = right.clone();
3577 moved.format = format;
3578 for height in &mut moved.altitude_m {
3579 *height += by;
3580 }
3581 read(&moved)
3582 };
3583 let inside = offset(LogFormat::GenericTable, PAD_ZERO_M - 0.01);
3584 assert_eq!(inside.pad_altitude_m, Some(PAD_ZERO_M - 0.01));
3585 assert!(inside.apogee.value().is_some());
3586 let outside = offset(LogFormat::GenericTable, PAD_ZERO_M + 0.01);
3587 assert_eq!(outside.apogee.reason(), Some(Reason::StartsOffThePad));
3588 assert_eq!(outside.liftoff.reason(), Some(Reason::StartsOffThePad));
3589 let reader = offset(LogFormat::PerfectFlitePf2, PAD_ZERO_M + 0.01);
3590 assert!(reader.apogee.value().is_some());
3591 assert!(reader.liftoff.value().is_some());
3592 // A channel's column says the same: above the ground, refused; above sea level, read
3593 // from its pad.
3594 let agl = as_channel(&right, Quantity::AltitudeAboveGround, |h| h + 1188.7);
3595 assert_eq!(read(&agl).apogee.reason(), Some(Reason::StartsOffThePad));
3596 let msl = read(&as_channel(&right, Quantity::AltitudeMsl, |h| h + 1188.7));
3597 assert!((msl.pad_altitude_m.unwrap() - 1188.7).abs() < 1e-9);
3598 assert!(msl.apogee.value().is_some());
3599
3600 // 20 Hz in milliseconds read as seconds: samples 50 s apart.
3601 let mut millis = right.clone();
3602 for time in &mut millis.time_s {
3603 *time *= 1000.0;
3604 }
3605 assert_eq!(
3606 read(&millis).apogee.reason(),
3607 Some(Reason::SampledTooSlowly)
3608 );
3609 // 500 Hz, the fastest the readings take, so 2 s apart when misread, the slowest they
3610 // take: the climb takes 1,000 times as long, and loses nothing in the last 4 s before its
3611 // top.
3612 let fast = log_every(MIN_INTERVAL_S, 30.0, flight(10.0));
3613 assert!(read(&fast).apogee.value().is_some());
3614 let mut fast_millis = fast;
3615 for (index, time) in fast_millis.time_s.iter_mut().enumerate() {
3616 *time = f64::from(u32::try_from(index).unwrap()) * 2.0;
3617 }
3618 let readings = read(&fast_millis);
3619 assert_eq!(readings.apogee.reason(), Some(Reason::SlowerThanFreeCoast));
3620 assert_eq!(readings.liftoff.reason(), Some(Reason::SlowerThanFreeCoast));
3621 }
3622
3623 /// A track whose step is coarser than the bounds were checked at is withheld, at the edge.
3624 #[test]
3625 fn a_coarse_step_is_withheld() {
3626 // The flight ten times as high and √10 times as long, so it coasts at gravity still.
3627 let stepped = |step: f64| {
3628 let tall = |t: f64| 10.0 * flight(10.0)(t / 10f64.sqrt());
3629 let mut log = log(60.0, |t| (tall(t) / step).round() * step);
3630 log.format = LogFormat::GenericTable;
3631 read(&log)
3632 };
3633 assert!(stepped(MAX_STEP_M).apogee.value().is_some());
3634 assert_eq!(
3635 stepped(MAX_STEP_M * 1.01).apogee.reason(),
3636 Some(Reason::StepTooCoarse)
3637 );
3638 }
3639
3640 /// A clock faster than the bounds were checked at is withheld whole, saying so, at the edge:
3641 /// 500 samples a second, and a part in a thousand faster, reads; 800 a second, as one sample
3642 /// log's is, and two parts in a thousand faster than 500, don't.
3643 #[test]
3644 fn a_clock_too_fine_for_the_window_is_withheld() {
3645 let with_interval = |interval: f64| {
3646 let mut log = log(30.0, flight(10.0));
3647 for (index, time) in log.time_s.iter_mut().enumerate() {
3648 *time = f64::from(u32::try_from(index).unwrap()) * interval;
3649 }
3650 read(&log)
3651 };
3652 for interval in [1e-30, 1e-6, 0.001_25, MIN_INTERVAL_S * (1.0 - 2e-3)] {
3653 let read = with_interval(interval);
3654 assert_eq!(
3655 read.apogee.reason(),
3656 Some(Reason::SampledTooFast),
3657 "{interval}"
3658 );
3659 assert_eq!(read.landing.reason(), Some(Reason::SampledTooFast));
3660 assert_eq!(read.sample_interval_s.map(|s| s > 0.0), Some(true));
3661 }
3662 for interval in [MIN_INTERVAL_S, MIN_INTERVAL_S * (1.0 - 5e-4)] {
3663 let read = with_interval(interval);
3664 assert_ne!(
3665 read.apogee.reason(),
3666 Some(Reason::SampledTooFast),
3667 "{interval}"
3668 );
3669 let window_s = read.median_window_s.unwrap();
3670 assert!((window_s - 0.3).abs() < 1e-3, "{window_s}");
3671 }
3672 }
3673
3674 /// The window's half-width at a rounding tie doesn't turn on the interval's last bit.
3675 #[test]
3676 fn the_window_settles_ties_upwards() {
3677 assert_eq!(half_window(0.05), 3);
3678 for interval in [0.1, 0.1 + 1e-15, 0.1 - 1e-15, 0.2 - 0.1] {
3679 assert_eq!(half_window(interval), 2, "{interval}");
3680 }
3681 assert_eq!(half_window(1.0), 1);
3682 assert!((peak_bound_m(3, 0.05) - 0.076_614).abs() < 1e-6);
3683 }
3684
3685 /// The constants worked out from others say so.
3686 #[test]
3687 fn derived_constants_follow_their_formulas() {
3688 let sound = (1.4 * 287.05 * (216.65 - AIR_TEMPERATURE_SPREAD_K)).sqrt();
3689 assert!((TRANSONIC_SPEED_M_S - TRANSONIC_MACH * sound).abs() < 1e-9);
3690 assert!((TEMPERATURE_SHARE - 0.069_236).abs() < 1e-6);
3691 }
3692
3693 proptest::proptest! {
3694 /// The median's peak bound holds wherever the true peak falls between samples, at any
3695 /// half-width, and the median never reads above the peak.
3696 #[test]
3697 fn the_peak_bound_holds(phase in 0.0..1.0_f64, half in 1_usize..7, dt in 0.01..0.2_f64) {
3698 let trace: Vec<f64> = (-60..=60)
3699 .map(|i| {
3700 let t = (f64::from(i) - phase) * dt;
3701 -0.5 * STANDARD_GRAVITY_MPS2 * t * t
3702 })
3703 .collect();
3704 let top = running_median(&trace, half)
3705 .into_iter()
3706 .fold(f64::NEG_INFINITY, f64::max);
3707 proptest::prop_assert!(top <= 0.0);
3708 proptest::prop_assert!(-top <= peak_bound_m(half, dt) * (1.0 + 1e-12));
3709 }
3710 }
3711
3712 /// A coast doesn't fall and rise again, and nothing falls from its top faster than gravity
3713 /// pulls it: a transient that stands above the coast's top, as a charge's does, holds the
3714 /// apogee, the top speed and landing back, by name; liftoff is read. A step 20 m above the
3715 /// top, 0.6 s wide, 0.3 s after apogee, before the track has fallen past twice its noise and
3716 /// step (6.6 m), falls 29.0 m from its top in a sample, where a body at rest there falls at
3717 /// most 20.9 m past the median's window and the noise; a climb at 12 m/s from 10 m below the
3718 /// top to 26 m above it, then down at 10 m/s, falls no faster than that, but follows a fall of
3719 /// 8.9 m. Each is caught by its own rule, and the same flight with neither reads its apogee at
3720 /// the coast's top.
3721 #[test]
3722 fn a_transient_top_is_withheld() {
3723 let g = STANDARD_GRAVITY_MPS2;
3724 let plain = read(&log(30.0, flight(10.0)));
3725 let apogee = plain.apogee.value().unwrap();
3726 assert!((apogee.time_s - 6.0).abs() <= apogee.time_bound_s);
3727
3728 fn by<T: std::fmt::Debug>(reading: &Reading<T>, rule: &str) {
3729 let Reading::Withheld(withheld) = reading else {
3730 panic!("{reading:?}");
3731 };
3732 assert_eq!(withheld.reason, Reason::DisturbedTop);
3733 assert!(withheld.detail.contains(rule), "{}", withheld.detail);
3734 }
3735 let withheld = |read: &Readings, rule: &str| {
3736 assert!(read.liftoff.value().is_some());
3737 by(&read.apogee, rule);
3738 by(&read.max_speed, rule);
3739 by(&read.landing, rule);
3740 };
3741 let stepped = |t: f64| {
3742 if (6.3..6.9).contains(&t) {
3743 10.0 * g + 20.0
3744 } else {
3745 flight(10.0)(t)
3746 }
3747 };
3748 withheld(&read(&log(30.0, stepped)), "a body at rest there can fall");
3749 let returning = |t: f64| {
3750 if t < 7.0 {
3751 flight(10.0)(t)
3752 } else if t < 10.0 {
3753 10.0 * g - 10.0 + 12.0 * (t - 7.0)
3754 } else {
3755 (10.0 * g + 26.0 - 10.0 * (t - 10.0)).max(0.0)
3756 }
3757 };
3758 withheld(&read(&log(30.0, returning)), "then climbs to its top");
3759 }
3760
3761 /// A top that is the vehicle's is read, whichever half of a spike follows it. A parachute open
3762 /// before apogee slows the climb into the top, not the fall from it: a coast that opens its
3763 /// chute at 40 m/s and stops at 40 m/s² climbs 20 m in its last second, more than a coast
3764 /// slowing at twice gravity could, then falls at gravity to 8 m/s. A charge that lifts the
3765 /// bay's pressure at the top drops the track after the coast's own climb: 50 m for half a
3766 /// second from 0.4 s after the top.
3767 #[test]
3768 fn a_top_that_isnt_a_spike_is_read() {
3769 let g = STANDARD_GRAVITY_MPS2;
3770 // Off the pad at 1 s at 40 m/s² for 3 s (180 m, 120 m/s), a vacuum coast to 40 m/s, then
3771 // 40 m/s² to the top 20 m higher, and down at gravity to 8 m/s.
3772 let coast_s = 80.0 / g;
3773 let opened_m = 180.0 + 120.0 * coast_s - 0.5 * g * coast_s * coast_s;
3774 let (top_s, top_m) = (4.0 + coast_s + 1.0, opened_m + 20.0);
3775 let chuted = move |t: f64| {
3776 if t <= 1.0 {
3777 0.0
3778 } else if t < 4.0 {
3779 20.0 * (t - 1.0).powi(2)
3780 } else if t < 4.0 + coast_s {
3781 let c = t - 4.0;
3782 180.0 + 120.0 * c - 0.5 * g * c * c
3783 } else if t < top_s {
3784 let c = top_s - t;
3785 top_m - 20.0 * c * c
3786 } else {
3787 let d = t - top_s;
3788 let speeding = (8.0 / g).min(d);
3789 (top_m - 0.5 * g * speeding * speeding - 8.0 * (d - speeding)).max(0.0)
3790 }
3791 };
3792 let chute = read(&log(140.0, chuted));
3793 let apogee = chute.apogee.value().unwrap();
3794 assert!(
3795 (apogee.height_m - top_m).abs() <= apogee.bound_m,
3796 "{apogee:?}"
3797 );
3798 assert!(
3799 (apogee.time_s - top_s).abs() <= apogee.time_bound_s,
3800 "{apogee:?}"
3801 );
3802 assert!(chute.landing.value().is_some(), "{:?}", chute.landing);
3803
3804 let charged = read(&log(30.0, |t| {
3805 let dropped = if (6.4..6.9).contains(&t) { 50.0 } else { 0.0 };
3806 flight(10.0)(t) - dropped
3807 }));
3808 let apogee = charged.apogee.value().unwrap();
3809 assert!(
3810 (apogee.height_m - 10.0 * g).abs() <= apogee.bound_m,
3811 "{apogee:?}"
3812 );
3813 assert!(
3814 (apogee.time_s - 6.0).abs() <= apogee.time_bound_s,
3815 "{apogee:?}"
3816 );
3817 }
3818
3819 /// A charge's transient, in the shapes of two public logs whose licenses keep them out of
3820 /// the repository, with invented numbers: a telemetry logger that sends a sample a second on
3821 /// the pad and after its charge and ten a second between, its charge at the top of a 914 m
3822 /// coast, then one sample 130 m under the top and the next 150 m over it, reads the coast's
3823 /// top, the spike taken out by the median; a breakup that reads a climb to 40% over the
3824 /// coast's top within a second, mid-coast, and back in half a second, is withheld by name: it
3825 /// falls 50.0 m in a sample from its top, where a body at rest there falls at most 13.6 m.
3826 #[test]
3827 fn a_charges_transient_reads_the_coast_or_is_withheld() {
3828 let g = STANDARD_GRAVITY_MPS2;
3829 // Off the pad at 300 s at 40 m/s² for 3 s (180 m, 120 m/s), a vacuum coast to the top
3830 // at 315.23 s (913.9 m), then down at 30 m/s.
3831 let (top_s, top_m) = (303.0 + 120.0 / g, 180.0 + 120.0 * 120.0 / (2.0 * g));
3832 let flight = move |t: f64| {
3833 if t <= 300.0 {
3834 0.0
3835 } else if t < 303.0 {
3836 20.0 * (t - 300.0).powi(2)
3837 } else if t < top_s {
3838 let c = t - 303.0;
3839 180.0 + 120.0 * c - 0.5 * g * c * c
3840 } else {
3841 (top_m - 30.0 * (t - top_s)).max(0.0)
3842 }
3843 };
3844 let made = |time_s: Vec<f64>, height: &dyn Fn(usize, f64) -> f64| {
3845 let mut made = log_every(1.0, 0.0, |_| 0.0);
3846 made.altitude_m = time_s
3847 .iter()
3848 .enumerate()
3849 .map(|(i, t)| height(i, *t))
3850 .collect();
3851 made.time_s = time_s;
3852 made
3853 };
3854
3855 let mut time_s: Vec<f64> = (0..=300).map(f64::from).collect();
3856 time_s.extend((1..=153).map(|k| 300.0 + 0.1 * f64::from(k)));
3857 let charge = time_s.len();
3858 time_s.extend((1..=37).map(|k| 315.3 + f64::from(k)));
3859 let telemetry = read(&made(time_s, &|i, t| match i.checked_sub(charge) {
3860 Some(0) => top_m - 130.0,
3861 Some(1) => top_m + 150.0,
3862 _ => flight(t),
3863 }));
3864 let apogee = telemetry.apogee.value().unwrap();
3865 assert!(
3866 (apogee.height_m - top_m).abs() <= apogee.bound_m,
3867 "{apogee:?}"
3868 );
3869 assert!(
3870 (apogee.time_s - top_s).abs() <= apogee.time_bound_s,
3871 "{apogee:?}"
3872 );
3873
3874 let time_s: Vec<f64> = (0..=1200).map(|k| 295.0 + 0.05 * f64::from(k)).collect();
3875 let breakup = read(&made(time_s, &|_, t| {
3876 let over = 1.4 * top_m - flight(308.0);
3877 let lift = if (308.0..309.0).contains(&t) {
3878 over * (t - 308.0)
3879 } else if (309.0..309.5).contains(&t) {
3880 over * (1.0 - 2.0 * (t - 309.0))
3881 } else {
3882 0.0
3883 };
3884 flight(t) + lift
3885 }));
3886 assert!(breakup.liftoff.value().is_some());
3887 for reason in [
3888 breakup.apogee.reason(),
3889 breakup.max_speed.reason(),
3890 breakup.landing.reason(),
3891 ] {
3892 assert_eq!(reason, Some(Reason::DisturbedTop));
3893 }
3894 }
3895
3896 /// The top speed's guards, each on its own.
3897 #[test]
3898 fn a_top_speed_is_refused_by_name() {
3899 let g = STANDARD_GRAVITY_MPS2;
3900 // A climb at `a` m/s² for 3 s from 1 s, then a vacuum coast and a 30 m/s descent.
3901 let boost = |a: f64| {
3902 move |t: f64| {
3903 let v = a * 3.0;
3904 let coast = v / g;
3905 let top = 4.5 * a + 0.5 * v * coast;
3906 if t <= 1.0 {
3907 0.0
3908 } else if t < 4.0 {
3909 0.5 * a * (t - 1.0).powi(2)
3910 } else if t < 4.0 + coast {
3911 let c = t - 4.0;
3912 4.5 * a + v * c - 0.5 * g * c * c
3913 } else {
3914 (top - 30.0 * (t - 4.0 - coast)).max(0.0)
3915 }
3916 }
3917 };
3918 // 3 s at 70 m/s² is 210 m/s, under the transonic mark; at 80 m/s², 240 m/s, over it.
3919 let below = read(&log(300.0, boost(70.0)));
3920 let speed = below.max_speed.value().unwrap();
3921 assert!((speed.speed_m_s - 210.0).abs() <= speed.bound_m_s);
3922 assert!(speed.speed_m_s < TRANSONIC_SPEED_M_S);
3923 let over = read(&log(300.0, boost(80.0)));
3924 assert_eq!(over.max_speed.reason(), Some(Reason::Transonic));
3925 assert!(over.apogee.value().is_some());
3926 // 1,400 m/s² for 3 s: implausible, refused ahead of the transonic mark.
3927 let absurd = read(&log(2000.0, boost(1400.0)));
3928 assert_eq!(absurd.max_speed.reason(), Some(Reason::ImplausibleSpeed));
3929 // A 60 m dip in the coast 4.4 s before the top, down and back at 200 m/s, where the
3930 // coast climbs at 43 m/s: the climb's speed swings past −42 m/s, 20% of its top.
3931 let dipped = read(&log(300.0, |t| {
3932 let dip = if (21.0..21.3).contains(&t) {
3933 200.0 * (t - 21.0)
3934 } else if (21.3..21.6).contains(&t) {
3935 200.0 * (21.6 - t)
3936 } else {
3937 0.0
3938 };
3939 boost(70.0)(t) - dip
3940 }));
3941 assert_eq!(dipped.max_speed.reason(), Some(Reason::NoisySpeed));
3942 // Logged at 10 Hz the 0.5 s fit has 5 or 6 samples; at 8 Hz 5; at 7.7 Hz, too few.
3943 let slow = |dt: f64| read(&log_every(dt, 30.0, flight(10.0))).max_speed;
3944 assert!(slow(0.1).value().is_some());
3945 assert!(slow(0.125).value().is_some());
3946 assert_eq!(slow(0.13).reason(), Some(Reason::SampledTooSlowly));
3947 }
3948
3949 /// `ALL` is built from the enum's own list, so it can't miss a variant; each is listed once,
3950 /// with its own code.
3951 #[test]
3952 fn all_lists_every_variant_once() {
3953 fn codes<T: Serialize>(all: &[T]) -> (usize, usize) {
3954 let mut codes: Vec<String> = all
3955 .iter()
3956 .map(|value| serde_json::json!(value).to_string())
3957 .collect();
3958 let listed = codes.len();
3959 codes.sort();
3960 codes.dedup();
3961 (listed, codes.len())
3962 }
3963 assert_eq!(codes(Reason::ALL), (28, 28));
3964 assert_eq!(codes(Source::ALL), (5, 5));
3965 assert_eq!(codes(Provenance::ALL), (3, 3));
3966 assert_eq!(codes(Method::ALL), (9, 9));
3967 assert_eq!(codes(Gravity::ALL), (2, 2));
3968 assert_eq!(codes(GravityBy::ALL), (3, 3));
3969 assert_eq!(codes(Clip::ALL), (2, 2));
3970 }
3971
3972 /// Serialized, a reading carries its status beside its fields.
3973 #[test]
3974 fn a_reading_serializes_with_its_status() {
3975 let read = read(&log(30.0, flight(10.0)));
3976 let json = serde_json::to_value(&read).unwrap();
3977 assert_eq!(json["apogee"]["status"], "read");
3978 assert_eq!(json["apogee"]["source"], "barometer");
3979 assert_eq!(json["apogee"]["provenance"], "measured");
3980 assert_eq!(json["max_speed"]["provenance"], "derived");
3981 assert_eq!(json["max_acceleration"]["status"], "withheld");
3982 assert_eq!(json["max_acceleration"]["reason"], "no_accelerometer");
3983 let back: Readings = serde_json::from_value(json).unwrap();
3984 assert_eq!(back, read);
3985 }
3986
3987 /// A window of exactly [`slope_samples`] is read whole, every sample in the sums as a fit
3988 /// over them all takes them; one sample more is read at every second.
3989 #[test]
3990 fn a_window_of_the_cap_is_read_whole_and_one_more_is_not() {
3991 // Twice the steps at the fastest rate the readings were checked at, plus one.
3992 assert_eq!(slope_samples(SPEED_WINDOW_S), 501);
3993 assert_eq!(slope_samples(DESCENT_WINDOW_S), 1_001);
3994 assert_eq!(slope_samples(DESCENT_WINDOW_MAX_S), 10_001);
3995 let window_s = SPEED_WINDOW_S;
3996 let cap = slope_samples(window_s);
3997 let fit = |times: &[f64], heights: &[f64], center: usize| {
3998 let t0 = times[center];
3999 let count = times.len() as f64;
4000 let mean_t = times.iter().map(|t| t - t0).sum::<f64>() / count;
4001 let mean_h = heights.iter().sum::<f64>() / count;
4002 let (num, den) = times
4003 .iter()
4004 .zip(heights)
4005 .fold((0.0, 0.0), |(n, d), (t, h)| {
4006 let dt = t - t0 - mean_t;
4007 (n + dt * (h - mean_h), d + dt * dt)
4008 });
4009 num / den
4010 };
4011 for samples in [cap, cap + 1] {
4012 // All within the window, 0.9 of it end to end.
4013 let step = 0.9 * window_s / (samples - 1) as f64;
4014 let times: Vec<f64> = (0..samples).map(|k| 10.0 + step * k as f64).collect();
4015 let heights: Vec<f64> = times
4016 .iter()
4017 .enumerate()
4018 .map(|(k, t)| 40.0 * t + (k % 3) as f64)
4019 .collect();
4020 let center = samples / 2;
4021 let slope = slope_over(×, &heights, center, window_s).unwrap();
4022 let whole = fit(×, &heights, center);
4023 if samples == cap {
4024 assert_eq!(slope.to_bits(), whole.to_bits(), "{slope} against {whole}");
4025 } else {
4026 assert_ne!(slope.to_bits(), whole.to_bits(), "{slope}");
4027 }
4028 }
4029 }
4030
4031 /// A burst of samples close together, which the median interval doesn't see, is read by a
4032 /// slope's fit at no more than [`slope_samples`] of them, for the top speed's window and the
4033 /// descent's alike, rather than every sample of the burst for each of them (#1250).
4034 #[test]
4035 fn a_burst_is_read_at_no_more_than_the_cap() {
4036 let burst: u32 = 1_000_000;
4037 let times: Vec<f64> = (0..500)
4038 .map(|k| 0.002 * f64::from(k))
4039 .chain((0..burst).map(|k| 1.0 + 0.4 * f64::from(k) / f64::from(burst)))
4040 .chain((0..500).map(|k| 1.4 + 0.002 * f64::from(k)))
4041 .collect();
4042 let center = 500 + 500_000;
4043 for window_s in [SPEED_WINDOW_S, DESCENT_WINDOW_S, DESCENT_WINDOW_MAX_S] {
4044 let cap = slope_samples(window_s);
4045 let read = slope_indices(×, center, window_s).len();
4046 assert!(
4047 read <= cap && 2 * read >= cap,
4048 "{window_s} s: {read} of {cap}"
4049 );
4050 }
4051 }
4052
4053 /// The landing's scan finds the sample the rule names, checking each candidate's span sample
4054 /// by sample, on tracks with gaps, dips and bursts.
4055 #[test]
4056 fn the_settled_scan_is_the_rule_written_out() {
4057 let rule = |heights: &[f64],
4058 time: &[f64],
4059 from: usize,
4060 (mark, ceiling): (f64, f64),
4061 span_s: f64| {
4062 let end = time[heights.len() - 1];
4063 (from..heights.len()).find(|&index| {
4064 heights[index] < mark
4065 && time[index] + span_s <= end
4066 && heights[index..]
4067 .iter()
4068 .zip(&time[index..])
4069 .take_while(|(_, t)| **t <= time[index] + span_s)
4070 .all(|(h, _)| *h < ceiling)
4071 })
4072 };
4073 // A linear congruential generator, so the tracks are the same on every run.
4074 let mut state: u64 = 0x2545_f491_4f6c_dd1d;
4075 let mut next = move || {
4076 state = state
4077 .wrapping_mul(6_364_136_223_846_793_005)
4078 .wrapping_add(1_442_695_040_888_963_407);
4079 f64::from(u32::try_from(state >> 40).unwrap_or(0)) / f64::from(1_u32 << 24)
4080 };
4081 let mut found = 0;
4082 for _ in 0..2_000 {
4083 let n = 2 + (next() * 300.0) as usize;
4084 let mut t = 0.0;
4085 let (mut time, mut heights) = (Vec::new(), Vec::new());
4086 for _ in 0..n {
4087 t += if next() < 0.2 {
4088 1e-4
4089 } else {
4090 0.05 + 0.2 * next()
4091 };
4092 time.push(t);
4093 let u = next();
4094 heights.push(if u < 0.05 {
4095 f64::NAN
4096 } else if u < 0.5 {
4097 3.0 * next()
4098 } else {
4099 12.0 * next()
4100 });
4101 }
4102 let from = (next() * n as f64) as usize;
4103 let span_s = 0.2 + 2.0 * next();
4104 let want = rule(&heights, &time, from, (2.0, 7.0), span_s);
4105 assert_eq!(
4106 first_settled(&heights, &time, from, (2.0, 7.0), span_s),
4107 want
4108 );
4109 found += usize::from(want.is_some());
4110 }
4111 assert!(found > 200, "{found}");
4112 }
4113
4114 /// Landing over a burst under the mark that rises past the ceiling at its end, as a descent's
4115 /// track might dip and recover, takes time in proportion to the burst, to within a binary
4116 /// search's logarithm: checking each candidate's span sample by sample, as `landing` did before
4117 /// [`first_settled`], took 47 s on this burst of 600,000 samples on a fast desktop, and grows
4118 /// as the square of the burst (#1250). The clock times `landing` alone, and nothing it reads
4119 /// reaches a result.
4120 #[test]
4121 #[allow(clippy::disallowed_types, reason = "the clock times landing alone")]
4122 fn landing_over_a_burst_is_not_walked_for_each_sample() {
4123 let burst: u32 = 600_000;
4124 // Down at 10 m/s from 100 m at apogee, a dip to the pad in 0.4 s at 8 s that rises past
4125 // the ceiling at its end, the rest of the descent, and 3 s on the ground.
4126 let (mut time_s, mut height_m) = (Vec::new(), Vec::new());
4127 for k in 0..160 {
4128 let t = 0.05 * f64::from(k);
4129 time_s.push(t);
4130 height_m.push(100.0 - 10.0 * t);
4131 }
4132 for k in 0..burst {
4133 time_s.push(8.0 + 0.4 * f64::from(k) / f64::from(burst));
4134 height_m.push(if k + 5_000 < burst { 0.0 } else { 50.0 });
4135 }
4136 for k in 0..92 {
4137 let t = 8.4 + 0.05 * f64::from(k);
4138 time_s.push(t);
4139 height_m.push((16.0 - 10.0 * (t - 8.4)).max(0.0));
4140 }
4141 let track = Track {
4142 source: Source::Barometer,
4143 time_s,
4144 height_m,
4145 step_m: 0.0,
4146 pressure_step_pa: None,
4147 zeroed: true,
4148 };
4149 let apex = Apex {
4150 index: 0,
4151 time_s: 0.0,
4152 height_bound_m: 1.0,
4153 time_bound_s: 0.1,
4154 };
4155 let began = std::time::Instant::now();
4156 let landed = landing(&track, &track.height_m, 0.0, &apex, (1.0, 0.5));
4157 let elapsed = began.elapsed();
4158 let landed_s = landed.value().map(|l| l.time_s);
4159 assert!(landed_s.is_some_and(|t| t > 9.5 && t < 10.5), "{landed:?}");
4160 assert!(elapsed.as_secs_f64() < 5.0, "{elapsed:?}");
4161 }
4162
4163 /// A descent under a drogue, then a main, whose main leg holds a burst of samples that makes
4164 /// most of the descent's, still reads both legs, the main's opening where it reads without the
4165 /// burst: the descent rates' median is sized at no faster than the readings accept. Sized at
4166 /// the burst's interval, its window would span the whole descent, and the walk back from
4167 /// landing would find no drogue's leg (#1250).
4168 #[test]
4169 fn a_burst_in_the_main_leg_keeps_the_drogues_leg() {
4170 let g = STANDARD_GRAVITY_MPS2;
4171 // A climb at 4 g for 3 s from 1 s, a vacuum coast to 883 m at 16 s, 25 m/s under the
4172 // drogue to 200 m at 43.3 s, then 6 m/s under the main to the pad at 76.6 s.
4173 let fly = move |t: f64| {
4174 if t <= 1.0 {
4175 0.0
4176 } else if t < 4.0 {
4177 2.0 * g * (t - 1.0).powi(2)
4178 } else if t < 16.0 {
4179 let c = t - 4.0;
4180 18.0 * g + 12.0 * g * c - 0.5 * g * c * c
4181 } else {
4182 let top = 18.0 * g + 72.0 * g;
4183 let main_s = 16.0 + (top - 200.0) / 25.0;
4184 if t < main_s {
4185 top - 25.0 * (t - 16.0)
4186 } else {
4187 (200.0 - 6.0 * (t - main_s)).max(0.0)
4188 }
4189 }
4190 };
4191 let pad_s = 200.0;
4192 // Every 2 ms, with `burst` samples in 0.4 s from 55 s after the pad.
4193 let log_of = |burst: u32| {
4194 let (mut time_s, mut altitude_m) = (Vec::new(), Vec::new());
4195 let mut t: f64 = 0.0;
4196 while t <= pad_s + 90.0 {
4197 let since = t - pad_s;
4198 if burst > 0 && (since - 55.0).abs() < 1e-9 {
4199 for k in 0..burst {
4200 let at = 55.0 + 0.4 * f64::from(k) / f64::from(burst);
4201 time_s.push(pad_s + at);
4202 altitude_m.push(fly(at));
4203 }
4204 t += 0.4;
4205 continue;
4206 }
4207 time_s.push(t);
4208 altitude_m.push(fly(since.max(0.0)));
4209 t = (t * 500.0 + 1.0).round() / 500.0;
4210 }
4211 let mut log = log_every(DT, 0.0, |_| 0.0);
4212 log.time_s = time_s;
4213 log.altitude_m = altitude_m;
4214 log
4215 };
4216 let opening = |log: &FlightLog| {
4217 let readings = read(log);
4218 let drogue = readings.drogue_descent.value().copied();
4219 assert!(drogue.is_some(), "{:?}", readings.drogue_descent);
4220 readings.main_descent.value().map(|d| d.from_s)
4221 };
4222 let clean_log = log_of(0);
4223 let burst_log = log_of(60_000);
4224 // The burst's 60,000 samples, in place of the 200 its 0.4 s holds at 500 a second.
4225 assert_eq!(burst_log.time_s.len(), clean_log.time_s.len() + 59_800);
4226 let clean = opening(&clean_log).unwrap();
4227 // 60,000 samples in the burst against about 30,000 in the rest of the descent.
4228 let burst = opening(&burst_log).unwrap();
4229 assert!((burst - clean).abs() < 0.5, "{burst} against {clean}");
4230 }
4231
4232 /// Logs with a burst of samples in the climb, in the descent's last seconds, or just before
4233 /// landing, where the track dips to the pad and rises past the landed ceiling and the
4234 /// descent's median interval falls into the burst, still give the reading each stresses, and
4235 /// read well within the smoother's burst bound, 60 s (#1250). A pad at 500 samples a second,
4236 /// 10% longer than the burst's samples need, holds the median at 2 ms. The clock times each
4237 /// read alone, and nothing it reads reaches a result.
4238 #[test]
4239 #[allow(clippy::disallowed_types, reason = "the clock times each read alone")]
4240 fn a_burst_of_samples_still_gives_the_readings() {
4241 let fly = flight(10.0);
4242 // A log with a burst from `start` s after the pad, its height at each time, and its pad.
4243 let with_burst = |start: f64, burst: u32, height: &dyn Fn(u32, f64) -> f64| {
4244 let pad_s = (1.1 * f64::from(burst) * MIN_INTERVAL_S).ceil();
4245 let (mut time_s, mut altitude_m) = (Vec::new(), Vec::new());
4246 let mut t: f64 = 0.0;
4247 while t <= pad_s + 45.0 {
4248 let since = t - pad_s;
4249 if (since - start).abs() < 1e-9 {
4250 for k in 0..burst {
4251 let at = start + 0.4 * f64::from(k) / f64::from(burst);
4252 time_s.push(pad_s + at);
4253 altitude_m.push(height(k, at));
4254 }
4255 t += 0.4;
4256 continue;
4257 }
4258 time_s.push(t);
4259 altitude_m.push(fly(since.max(0.0)));
4260 t = (t * 500.0 + 1.0).round() / 500.0;
4261 }
4262 let mut log = log_every(DT, 0.0, |_| 0.0);
4263 log.time_s = time_s;
4264 log.altitude_m = altitude_m;
4265 (log, pad_s)
4266 };
4267 let timed = |log: &FlightLog| {
4268 let began = std::time::Instant::now();
4269 let readings = read(log);
4270 (readings, began.elapsed().as_secs_f64())
4271 };
4272 let (log, _) = with_burst(1.2, 200_000, &|_, at| fly(at));
4273 let (climb, elapsed) = timed(&log);
4274 assert!(climb.max_speed.value().is_some(), "{:?}", climb.max_speed);
4275 assert!(elapsed < 60.0, "climb: {elapsed} s");
4276 let (log, _) = with_burst(14.0, 200_000, &|_, at| fly(at));
4277 let (tail, elapsed) = timed(&log);
4278 assert!(
4279 tail.main_descent.value().is_some(),
4280 "{:?}",
4281 tail.main_descent
4282 );
4283 assert!(elapsed < 60.0, "descent: {elapsed} s");
4284 let dip = |k: u32, _: f64| if k + 5_000 < 300_000 { 0.0 } else { 50.0 };
4285 let (log, pad_s) = with_burst(13.0, 300_000, &dip);
4286 let (dipped, elapsed) = timed(&log);
4287 let landing = dipped.landing.value().map(|l| l.time_s - pad_s);
4288 assert!(landing.is_some_and(|t| t > 13.4), "{:?}", dipped.landing);
4289 assert!(elapsed < 60.0, "landing: {elapsed} s");
4290 }
4291}