Skip to main content

hpr_flightdata/
arts2.rs

1//! Ozark Aerospace's ARTS2 flight computer's interpreted data, as its software exports a flight:
2//! a `# MET Acc Vel iAlt pAlt` header, then comma-separated rows.
3//!
4//! The ARTS2 records an accelerometer and a barometer, each read by a 10-bit converter, at a rate
5//! its owner sets, until its memory is full (*ARTS2 User Manual*, V1.0.0, Ozark Aerospace, 2007,
6//! p9, p16). Its PC software, DataAnalyzer, downloads the flight and works out what it shows:
7//! against the mission elapsed time (MET), a barometric altitude, an "accelerometer altitude",
8//! the velocity and the acceleration (p11–12). *Flight → Export → Interpreted Data* writes them as
9//! a CSV file (p14). The manual describes neither the file's columns nor their units, and its
10//! screens show feet, ft/s and ft/s² (p10–11), but the files among the project's sample logs are
11//! not all in those units, as below. Each holds about 16,000 rows, the logger's memory, one every
12//! 0.02 s (50 Hz), from launch:
13//!
14//! ```text
15//! # MET Acc Vel iAlt pAlt
16//! 0.000,0.00,0.00,0.00,0.00
17//! 0.020,61.00,0.61,0.01,0.00
18//! ```
19//!
20//! **Recognition.** The first line that isn't blank is `#` and then the five names `MET`, `Acc`,
21//! `Vel`, `iAlt` and `pAlt`, in that order and nothing else, parted by spaces, tabs or commas and
22//! compared without regard to case. The ARTS2's raw data (`MET,Acc(HI),Acc/Baro(LO),Baro(HI),State`)
23//! and AltOS's CSV, whose header also opens with `#` (`#version,serial,…`), name other columns.
24//!
25//! **Columns.** Nothing in the file says whether the software was set to English or metric units,
26//! and the sample logs hold both, so every unit is decided from the file itself, by the checks
27//! below, each of which the reader runs; a note on the record gives each decision and its numbers.
28//!
29//! | Column | Quantity | Unit, and from where |
30//! |---|---|---|
31//! | `MET` | the clock: seconds from launch | the name (mission elapsed time) and the apogee check (below), which a clock in another unit fails |
32//! | `Acc` | [`Quantity::Acceleration`], along the logger's axis, gravity taken out | standard gravity (× 9.806 65 m/s²) or `Vel`'s unit per second, from the boost check (below) |
33//! | `Vel` | [`Quantity::Speed`]: the logger's integral of `Acc` | m/s or ft/s, from the apogee check and the step check (below), which must agree |
34//! | `iAlt` | [`Quantity::InertialAltitude`]: the logger's integral of `Vel` | `Vel`'s length unit, from the inertial check (below) |
35//! | `pAlt` | [`Quantity::AltitudeAboveGround`]: the barometric altitude, the primary track | `Vel`'s length unit, from the step check and the barometric check (below) |
36//!
37//! The length unit, of `Vel` and `pAlt`, rests on two pieces of evidence that don't depend on each
38//! other: how fast `Vel` falls at the apogee, and how far `pAlt` moves for one count of the
39//! barometer. A file is read only where both give the same unit.
40//!
41//! *The apogee check* decides `Vel`'s unit, and with it that `MET` is in seconds. `Vel` is the
42//! logger's integral of `Acc`: over the boost, `Vel` rises by `Acc`'s integral times one factor in
43//! every sample file (the boost check). At the apogee the rocket is slowest, so its drag is least,
44//! and the accelerometer reads near zero; with gravity taken out, `Acc` then reads −1 g, and `Vel`
45//! falls at g in its own unit: 9.81 m/s² or 32.17 ft/s². The reader finds the first sample after
46//! `Vel`'s highest where it reaches zero, fits a straight line to `Vel` over the second of coast
47//! before that zero, to the first sample at or below it, and takes the unit in which the line's
48//! slope is within 25% of −g; m and ft are 3.28 times apart, so at most one unit can be. A clock
49//! in milliseconds or minutes would put the slope 1,000 or 60 times off, so the same fit pins
50//! `MET` in seconds. The second after the zero is left out: there the ejection's jolt can come, as
51//! it does in the sample files 1 to 4.5 s after it.
52//!
53//! A parachute out before the zero adds its drag to the second before it: one out at 25 m/s on the
54//! way up can make `Vel` fall at 3.7 g in m/s, which is 1.13 g in ft/s, within 25% of g in the
55//! wrong unit. So the window is the *coast's* last second: where `Acc` jumps in the 2 s before the
56//! zero, the line is fitted to the second before the first jump instead, and a jump earlier in
57//! that second starts it after the jump. A row is a jump where it and the row after it are both
58//! further from the median of the 3 rows before than half that median, about half a g near the
59//! apogee, where `Acc` reads about −1 g in its unit; one row's spike is no jump, and the sample
60//! files hold single-row spikes of a few g. A canopy out more than 2 s before the zero can make
61//! `Vel` fall at no more than 1.28 g over its last second, so it can't pass for the other unit: a
62//! canopy whose drag grows as the speed squared stops a rising rocket within `(v_t / g) π/2`, `v_t`
63//! its descent rate, so taking over 2 s means `v_t` over `4g/π`, 12.49 m/s, and then the last
64//! second's fall, `v_t tan(g · 1 s / v_t)` a second, is at most 1.28 g. As of 2026-10-13, no jump
65//! ends the window in the 4 interpreted-data files among the project's sample logs, and every
66//! one's slope is within 4% of g in the unit its step gives. A file whose `Vel` never reaches its
67//! zero after its highest, whose window holds fewer than 3 samples, or whose slope is within 25%
68//! of neither unit, is refused ([`LogError::Unit`]).
69//!
70//! *The step check* decides the length unit apart from `Vel`. `pAlt` is written to a hundredth but
71//! moves by its barometer's count, a fixed step of pressure. The ARTS2 reads a Motorola MPXA4100A
72//! sensor with a 10-bit converter (manual, p16); the sensor's output is its supply voltage times
73//! `0.010 59 P − 0.1518`, `P` in kPa (*MPXAZ4100A Series* data sheet, Freescale, Rev 1, 2005, p4),
74//! so a count, 1/1,024 of the supply, is `1 / (1,024 × 0.010 59)` kPa, 92.2 Pa, where the
75//! converter is read against the sensor's supply (the manual doesn't say). Near the ground that is
76//! `Δh = Δp / (ρ g)`: the reader takes the count as 92.2 Pa ± 15% and the ground's air from sea
77//! level at 5% over standard pressure and −20 °C, 1.46 kg/m³, to a 3,000 m site at 5% under its
78//! standard pressure (U.S. Standard Atmosphere, 1976) and 45 °C, 0.73 kg/m³, so a count is 5.46
79//! to 14.83 m: written as 5.46 to 14.83 in meters, 17.91 to 48.64 in feet. The two bands don't
80//! meet, so a step falls in one unit's at most. The step is `pAlt`'s smallest change between two
81//! written values in a row, gaps passed over, that at least 3 changes come within 0.02 of: a
82//! single smaller change, as a closing row of zeros makes, isn't a count. As of 2026-10-13, every
83//! sample file's step is between 8.5 and 9 m, in the band of the unit its slope gives. A `pAlt`
84//! with no step written 3 times, a step in neither band, or a step whose unit isn't the slope's,
85//! is refused ([`LogError::Unit`]). The step is larger aloft, where the air is thinner, so a
86//! record whose single counts all lie high above a high site can fall outside the band, and is
87//! refused.
88//!
89//! *The boost check* decides `Acc`'s unit. From the first sample to `Vel`'s highest, the reader
90//! sums `Vel`'s rise and `Acc`'s integral (trapezoids) over the steps where both are written: the
91//! ratio is `Vel`'s unit over `Acc`'s, about 1 when `Acc` is in `Vel`'s unit per second and about
92//! g in `Vel`'s unit when `Acc` is in standard gravities. Within 10% of one of them, that unit is
93//! taken; otherwise `Acc` is kept as written, [`Quantity::Unrecognized`]. The software's own
94//! arithmetic sets the ratio, so only the rounding of the written values moves it: as of
95//! 2026-10-13 every sample file's ratio is within 0.3% of the one its unit gives.
96//!
97//! *The inertial check* decides `iAlt`'s unit, as the boost check does `Acc`'s: from the first
98//! sample to the apogee, `iAlt`'s rise over `Vel`'s integral is 1 when they share a length unit.
99//! Within 10% of 1, `iAlt` is read in `Vel`'s; otherwise it is kept as written. The sample files'
100//! ratios are 1.000 to 4 digits.
101//!
102//! *The barometric check* holds `pAlt` to `Vel`. `pAlt` is the barometer's altitude, not an
103//! integral, so it can't match `Vel`'s to the digit; but its highest value must be near the
104//! climb `Vel` integrates to by the apogee, which the reader requires within 25% in the length
105//! unit. 25% allows for a day's air that isn't the standard atmosphere (a few percent), the
106//! integration's drift and the barometer's step, and is narrow enough that m and ft can't both be
107//! within it. The sample files' highest `pAlt` is 0.95 to 0.99 times the climb. A climb under 176
108//! m (20 of the barometer's steps, below), where one step would use a fifth of the margin, or a
109//! `pAlt` outside the margin, is refused ([`LogError::Unit`]).
110//!
111//! **The primary track.** [`FlightLog::time_s`] is `MET` and [`FlightLog::altitude_m`] is `pAlt`:
112//! the barometer's altitude above the ground. The file starts at launch, `MET` 0, and holds no
113//! samples from the pad, so the zero of `pAlt` is the logger's own ground reference, not in the
114//! file: the average of 16 pressure samples it takes as it enters flight mode on the pad, its
115//! "Zero Altitude baseline" (p17). In every sample file `pAlt` reads 0.00 on the first row; where
116//! it reads more than one barometer step (below) off zero there, a note says so. `iAlt` is kept as
117//! a channel: an integral of a single-axis accelerometer drifts, and in every sample file it falls
118//! to zero, and stays there, a minute or more before the barometer's descent ends, while `Vel`
119//! reads hundreds to thousands below zero by the end of the file. So `Vel` is no vertical speed
120//! either: [`FlightLog::vertical_speed_m_s`] is `None`, as for the Blue Raven's inertial velocity.
121//!
122//! **The closing zeros.** In every sample file the last row, or the last two, write `Vel` as
123//! 0.00 where the row before reads hundreds to thousands below zero: they aren't an integral of
124//! `Acc`, which moves `Vel` by under 1 a row there. A closing run of exactly 0 in `Vel` or `iAlt`
125//! is a gap, with a note, where the value before it lies further from 0 than twice what its rate
126//! (`Acc` times the boost check's ratio for `Vel`; `Vel` for `iAlt`), held at its largest over the
127//! run, changes it by in the run's time, plus a hundredth for the rounding. Where `Acc` is kept as
128//! written, it sets no rate, and `Vel`'s closing zeros are kept. In two of the sample files the
129//! last row writes 0.00 in every column; its `Acc` and `pAlt` are kept as written. The first row's
130//! `Acc` is 0.00 in every sample file too, also kept.
131//!
132//! **The barometer's step.** The format's resolution ([`LogFormat::altitude_resolution_m`]) is
133//! the coarsest of the sample files' smallest `pAlt` steps near the ground, 28.89 ft (8.81 m);
134//! all of them are between 8.5 and 9 m. A count is a fixed step of pressure, so the step is larger
135//! aloft and at a higher launch site.
136//!
137//! **Cells.** Every row must hold five cells, and its `MET` a number greater than the row
138//! before's; otherwise the file is refused, naming the line. Any other cell that is empty or isn't
139//! a number is a gap (`NaN`), counted in a note. A value finite as written that its unit makes
140//! infinite, such as `1e308` g, is refused, naming its line, as every reader refuses one. Lines may
141//! end in CR, LF or both, blank lines are skipped, and a byte-order mark is dropped. As every row must be five cells wide, the record
142//! never holds more values than the file has cells, and a row is read no further than its sixth
143//! cell before it is refused.
144
145use hpr_atmos::ussa76::{DRY_AIR_GAS_CONSTANT_J_PER_KG_K, SEA_LEVEL_PRESSURE_PA, Ussa76};
146use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
147
148use crate::error::LogError;
149use crate::log::{Channel, FlightLog, LogFormat, Quantity, Stated};
150use crate::perfectflite::FOOT_M;
151use crate::table::{finite, number, numbered_lines, short};
152
153/// The format's name in messages.
154const FORMAT: &str = "ARTS2 CSV";
155
156/// The logger's name on the record.
157const LOGGER: &str = "Ozark Aerospace ARTS2";
158
159/// The header's names after its `#`, in order.
160const NAMES: [&str; 5] = ["MET", "Acc", "Vel", "iAlt", "pAlt"];
161
162/// The coarsest of the sample files' smallest `pAlt` steps near the ground, in feet (module docs,
163/// *The barometer's step*).
164const COARSEST_STEP_FT: f64 = 28.89;
165
166/// The step between two altitudes the format can tell apart near the ground, m
167/// ([`crate::log::LogFormat::altitude_resolution_m`]): the coarsest of the smallest steps `pAlt`
168/// moves by in the 4 interpreted-data files among the project's sample logs as of 2026-10-13,
169/// 28.89 ft; every one of them is between 8.5 and 9 m. `pAlt` is written to a hundredth, but moves
170/// by its barometer's count, a fixed step of pressure ([`COUNT_PA`]), so the step is larger aloft
171/// and at a higher site.
172pub(crate) const ALTITUDE_STEP_M: f64 = COARSEST_STEP_FT * FOOT_M;
173
174/// One count of the ARTS2's barometer, Pa, nominal. The ARTS2 reads a Motorola MPXA4100A pressure
175/// sensor with its processor's 10-bit converter (*ARTS2 User Manual*, V1.0.0, p16). The sensor's
176/// output is `V_S (0.010 59 P − 0.1518)`, `P` in kPa, ratiometric to its supply `V_S` (*MPXAZ4100A
177/// Series* data sheet, Freescale, Rev 1, 2005: Table 2 and its note 2, p2; the transfer function,
178/// p4). Read against that supply, one of the converter's 1,024 counts is `1 / (1,024 × 0.010 59)`
179/// kPa, 92.2 Pa.
180const COUNT_PA: f64 = 1_000.0 / (1_024.0 * 0.010_59);
181
182/// How far, as a share, a count may be from [`COUNT_PA`]: the manual doesn't say what the
183/// converter's reference is, and the sensor's supply may be 4.85 to 5.35 V (±5% of its 5.1 V, the
184/// data sheet's Table 2), so a fixed reference beside it moves the count by that much; the rest
185/// allows for the sensor's span off nominal (its accuracy is ±1.8% of the span) and the software's
186/// conversion to altitude.
187const COUNT_TOLERANCE: f64 = 0.15;
188
189/// The highest launch site, m above sea level, whose ground step the band allows.
190const HIGHEST_SITE_M: f64 = 3_000.0;
191
192/// How far, as a share, a day's ground pressure may be from the standard atmosphere's at its site.
193const WEATHER_SPREAD: f64 = 0.05;
194
195/// The coldest and the hottest air at the ground, K, that the band allows: −20 °C and 45 °C.
196const COLDEST_K: f64 = 253.15;
197const HOTTEST_K: f64 = 318.15;
198
199/// How often `pAlt`'s smallest step must be written, to within [`STEP_SPREAD`], to count: once
200/// could be a placeholder, as a closing row of zeros is.
201const STEP_REPEATS: usize = 3;
202
203/// How far apart, in the written unit, two of `pAlt`'s steps may be and count as one: two
204/// hundredths, the rounding of the two values each step is the difference of.
205const STEP_SPREAD: f64 = 2.0 * ROUNDING;
206
207/// How long before `Vel`'s zero at the apogee, s, the samples its slope is fitted to start: the
208/// coast's last second, before any ejection's jolt.
209const APOGEE_WINDOW_S: f64 = 1.0;
210
211/// How long before `Vel`'s zero, s, a jump in `Acc` ends the window early (module docs, *The
212/// apogee check*). A canopy whose drag grows as the speed squared, `g (v / v_t)²` for a descent
213/// rate `v_t`, stops a rising rocket within `(v_t / g) atan(v₀ / v_t)`, under `(v_t / g) π/2`; so
214/// one out more than 2 s before the zero has `v_t` over `4g/π`, 12.49 m/s, and makes `Vel` fall
215/// over the zero's last second by `v_t tan(g · 1 s / v_t)` a second, at most 1.28 g, read in the
216/// other unit 0.39 or 4.2 g: far from g ([`GRAVITY_MARGIN`]). A parachute out later is found by
217/// its jump.
218const DEPLOYMENT_SEARCH_S: f64 = 2.0;
219
220/// How many rows before a row its `Acc` is compared with, through their median.
221const JUMP_REFERENCE_ROWS: usize = 3;
222
223/// How far, as a share of the level before it, `Acc` must move, on a row and the row after it, for
224/// the row to be a jump: about half a g near the apogee, where `Acc` reads about −1 g.
225const JUMP_SHARE: f64 = 0.5;
226
227/// The fewest samples the apogee's line is fitted to.
228const APOGEE_SAMPLES: usize = 3;
229
230/// How far, as a share, the slope of `Vel` through the apogee may be from −g in a unit for `Vel`
231/// to be read in it: the drag at the apogee is small, and m and ft are 3.28 times apart, so at
232/// most one unit can be within 25%.
233const GRAVITY_MARGIN: f64 = 0.25;
234
235/// How far, as a share, a ratio the software's own integration sets (the boost and inertial
236/// checks) may be from the one a unit gives: the written values' rounding moves them by at most
237/// 0.3% in the sample files.
238const INTEGRAL_MARGIN: f64 = 0.10;
239
240/// How far, as a share, `pAlt`'s highest value may be from the climb `Vel` integrates to: a day's
241/// air off the standard atmosphere, the integration's drift and the barometer's step; m and ft
242/// can't both be within it.
243const BAROMETRIC_MARGIN: f64 = 0.25;
244
245/// The least climb, m, from which `pAlt`'s unit is decided: 20 of the barometer's steps, so that
246/// one step is 5% of the climb, a fifth of [`BAROMETRIC_MARGIN`].
247const SETTLING_CLIMB_M: f64 = 20.0 * ALTITUDE_STEP_M;
248
249/// The most a written value may be off its true one, in its unit: the export writes hundredths.
250const ROUNDING: f64 = 0.01;
251
252/// A length unit, of the velocity and the altitudes.
253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254enum Length {
255    Meter,
256    Foot,
257}
258
259impl Length {
260    const BOTH: [Self; 2] = [Self::Meter, Self::Foot];
261
262    /// Meters in the unit.
263    fn meters(self) -> f64 {
264        match self {
265            Self::Meter => 1.0,
266            Self::Foot => FOOT_M,
267        }
268    }
269
270    /// Standard gravity in the unit per second squared.
271    fn gravity(self) -> f64 {
272        STANDARD_GRAVITY_MPS2 / self.meters()
273    }
274
275    /// The unit's name.
276    fn name(self) -> &'static str {
277        match self {
278            Self::Meter => "meters",
279            Self::Foot => "feet",
280        }
281    }
282
283    /// The unit's symbol.
284    fn symbol(self) -> &'static str {
285        match self {
286            Self::Meter => "m",
287            Self::Foot => "ft",
288        }
289    }
290}
291
292/// The first line of the text that isn't blank, any byte-order mark dropped.
293fn first_line(text: &str) -> Option<&str> {
294    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
295    text.split(['\r', '\n'])
296        .map(str::trim)
297        .find(|line| !line.is_empty())
298}
299
300/// Whether a line is the export's header: `#`, then [`NAMES`] and nothing else.
301fn is_header(line: &str) -> bool {
302    let Some(rest) = line.trim().strip_prefix('#') else {
303        return false;
304    };
305    let mut names = rest.split([' ', '\t', ',']).filter(|name| !name.is_empty());
306    NAMES.iter().all(|expected| {
307        names
308            .next()
309            .is_some_and(|name| name.eq_ignore_ascii_case(expected))
310    }) && names.next().is_none()
311}
312
313/// Whether a file's text is in this layout: its first line that isn't blank is the export's
314/// header, `# MET Acc Vel iAlt pAlt`.
315pub fn recognizes(text: &str) -> bool {
316    first_line(text).is_some_and(is_header)
317}
318
319/// The file's rows, as written.
320struct Rows {
321    /// `MET`, s.
322    time_s: Vec<f64>,
323    /// `Acc`, `Vel`, `iAlt` and `pAlt` as written, `NaN` for a gap.
324    values: [Vec<f64>; 4],
325    /// Each row's line in the file.
326    lines: Vec<usize>,
327    /// Each column's gaps, and the line of the first.
328    gaps: [(usize, usize); 4],
329}
330
331/// The columns' places in [`Rows::values`].
332const ACC: usize = 0;
333const VEL: usize = 1;
334const IALT: usize = 2;
335const PALT: usize = 3;
336
337/// Reads a log in this layout.
338///
339/// # Errors
340///
341/// - [`LogError::NotThisFormat`] if the first line that isn't blank isn't the export's header.
342/// - [`LogError::NoData`] without a row.
343/// - [`LogError::Syntax`] for a row not five cells wide, or whose `MET` isn't a number greater
344///   than the row before's, or a value too large to convert to SI.
345/// - [`LogError::Unit`] where the file's evidence settles no unit for `Vel` or `pAlt` (module
346///   docs): the primary track would have no unit.
347pub fn read(text: &str) -> Result<FlightLog, LogError> {
348    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
349    let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
350    let Some((header_line, header)) = lines.next() else {
351        return Err(LogError::NotThisFormat {
352            format: FORMAT,
353            message: "the file is empty".to_owned(),
354        });
355    };
356    if !is_header(header) {
357        return Err(LogError::NotThisFormat {
358            format: FORMAT,
359            message: format!(
360                "its first line, {:?}, isn't the ARTS2's interpreted-data header, \
361                 `# MET Acc Vel iAlt pAlt`",
362                short(header)
363            ),
364        });
365    }
366    let rows = rows(lines)?;
367    if rows.time_s.is_empty() {
368        return Err(LogError::NoData { format: FORMAT });
369    }
370    let units = decide(&rows, header_line)?;
371    let mut notes = units.notes.clone();
372    let mut values = rows.values.clone();
373    closing_zeros(&rows, &units, &mut values, &mut notes);
374    for (index, (count, line)) in rows.gaps.iter().enumerate() {
375        if *count > 0 {
376            notes.push(format!(
377                "`{}` has {count} cells that are empty or aren't a number, the first on line \
378                 {line}: gaps",
379                NAMES[index + 1]
380            ));
381        }
382    }
383    let length = units.length.meters();
384    let acc_scale = units.acceleration.unwrap_or(1.0);
385    let ialt_scale = if units.inertial { length } else { 1.0 };
386    let convert_column = |column: usize, scale: f64| {
387        let column_values = values.get(column).map_or(&[][..], Vec::as_slice);
388        convert(column_values, scale, &rows.lines, NAMES[column + 1])
389    };
390    let acc = convert_column(ACC, acc_scale)?;
391    let vel = convert_column(VEL, length)?;
392    let ialt = convert_column(IALT, ialt_scale)?;
393    let altitude_m = convert_column(PALT, length)?;
394    if let Some(first) = altitude_m.first()
395        && first.is_finite()
396        && first.abs() > ALTITUDE_STEP_M
397    {
398        notes.push(format!(
399            "`pAlt` reads {first:.2} m on the first row, more than one barometer step from zero: \
400             the logger's ground isn't where the record starts"
401        ));
402    }
403    let channel = |index: usize, quantity: Quantity, values: Vec<f64>| Channel {
404        column: NAMES[index + 1].to_owned(),
405        quantity,
406        time_s: rows.time_s.clone(),
407        values,
408    };
409    let acc_quantity = if units.acceleration.is_some() {
410        Quantity::Acceleration
411    } else {
412        Quantity::Unrecognized
413    };
414    let ialt_quantity = if units.inertial {
415        Quantity::InertialAltitude
416    } else {
417        Quantity::Unrecognized
418    };
419    let channels = vec![
420        channel(ACC, acc_quantity, acc),
421        channel(VEL, Quantity::Speed, vel),
422        channel(IALT, ialt_quantity, ialt),
423        channel(PALT, Quantity::AltitudeAboveGround, altitude_m.clone()),
424    ];
425    Ok(FlightLog {
426        format: LogFormat::Arts2Csv,
427        logger: LOGGER.to_owned(),
428        serial_number: None,
429        firmware: None,
430        flight_number: None,
431        stated: Stated::default(),
432        time_s: rows.time_s,
433        altitude_m,
434        vertical_speed_m_s: None,
435        temperature_k: None,
436        battery_v: None,
437        channels,
438        events: Vec::new(),
439        notes,
440    })
441}
442
443/// A column's values times `scale`, each row's on its line in `lines` (the rows keep a line for
444/// every value).
445///
446/// # Errors
447///
448/// [`LogError::Syntax`] for a value finite as written that `scale` makes infinite, such as
449/// `1e308` g, on its row's line ([ADR-258] §3).
450///
451/// [ADR-258]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0258-aerospacenus-board-and-a-phone-apps-csv-before-the-rest.md
452fn convert(
453    values: &[f64],
454    scale: f64,
455    lines: &[usize],
456    column: &str,
457) -> Result<Vec<f64>, LogError> {
458    values
459        .iter()
460        .zip(lines)
461        .map(|(value, &line)| finite(value * scale, FORMAT, line, column))
462        .collect()
463}
464
465/// The data rows below the header.
466fn rows<'a>(lines: impl Iterator<Item = (usize, &'a str)>) -> Result<Rows, LogError> {
467    let mut rows = Rows {
468        time_s: Vec::new(),
469        values: Default::default(),
470        lines: Vec::new(),
471        gaps: [(0, 0); 4],
472    };
473    for (line, text) in lines {
474        // One more than the header names, so that a wider row is told apart without holding all
475        // of its cells.
476        let cells: Vec<&str> = text.split(',').take(NAMES.len() + 1).collect();
477        if cells.len() != NAMES.len() {
478            return Err(LogError::Syntax {
479                format: FORMAT,
480                line,
481                message: format!(
482                    "a row of {} cells, where the header names {}: {:?}",
483                    if cells.len() > NAMES.len() {
484                        format!("more than {}", NAMES.len())
485                    } else {
486                        cells.len().to_string()
487                    },
488                    NAMES.len(),
489                    short(text)
490                ),
491            });
492        }
493        let Some(time) = cells.first().and_then(|cell| number(cell, false)) else {
494            return Err(LogError::Syntax {
495                format: FORMAT,
496                line,
497                message: format!("`MET` isn't a number: {:?}", short(text)),
498            });
499        };
500        if let Some(previous) = rows.time_s.last()
501            && time <= *previous
502        {
503            return Err(LogError::Syntax {
504                format: FORMAT,
505                line,
506                message: format!(
507                    "`MET` {time} doesn't come after the row before's, {previous}: the clock must \
508                     increase"
509                ),
510            });
511        }
512        rows.time_s.push(time);
513        rows.lines.push(line);
514        for (index, cell) in cells.iter().skip(1).enumerate() {
515            let value = number(cell, false).unwrap_or(f64::NAN);
516            if value.is_nan() {
517                let (count, first) = &mut rows.gaps[index];
518                if *count == 0 {
519                    *first = line;
520                }
521                *count += 1;
522            }
523            rows.values[index].push(value);
524        }
525    }
526    Ok(rows)
527}
528
529/// The units the checks decided (module docs), and a note on each.
530#[derive(Debug, Clone)]
531struct Units {
532    /// The length unit of `Vel` and `pAlt`.
533    length: Length,
534    /// `Acc`'s factor to m/s², `None` if kept as written.
535    acceleration: Option<f64>,
536    /// Whether `iAlt` is in [`Self::length`]; kept as written if not.
537    inertial: bool,
538    /// `Vel`'s rise over `Acc`'s integral on the boost (the boost check), if measured.
539    boost_ratio: Option<f64>,
540    notes: Vec<String>,
541}
542
543/// Where `Vel` crosses zero at the apogee.
544struct Apogee {
545    /// The row of `Vel`'s highest value.
546    peak: usize,
547    /// The first row after it whose `Vel` is zero or below.
548    row: usize,
549    /// The time of the zero, on the line between that row and the one before written.
550    time_s: f64,
551}
552
553/// `Vel`'s highest value and its first zero after it (module docs, *The apogee check*).
554fn apogee(time_s: &[f64], vel: &[f64]) -> Option<Apogee> {
555    let peak = vel
556        .iter()
557        .enumerate()
558        .filter(|(_, value)| value.is_finite())
559        .fold(
560            None,
561            |best: Option<(usize, f64)>, (row, value)| match best {
562                Some((_, top)) if top >= *value => best,
563                _ => Some((row, *value)),
564            },
565        )
566        .filter(|(_, top)| *top > 0.0)?
567        .0;
568    let mut before = (peak, *vel.get(peak)?);
569    for (row, value) in vel.iter().enumerate().skip(peak + 1) {
570        if !value.is_finite() {
571            continue;
572        }
573        if *value <= 0.0 {
574            let (t0, t1) = (*time_s.get(before.0)?, *time_s.get(row)?);
575            let share = before.1 / (before.1 - value);
576            return Some(Apogee {
577                peak,
578                row,
579                time_s: t0 + share * (t1 - t0),
580            });
581        }
582        before = (row, *value);
583    }
584    None
585}
586
587/// Whether `Acc` jumps on a row: it and the row after it are both further from the median of the
588/// [`JUMP_REFERENCE_ROWS`] rows before than [`JUMP_SHARE`] of that median, so that one row's spike
589/// is no jump. A row without as many written rows before it, or whose own or next value isn't
590/// written, counts as a jump: the coast can't be shown to go on through it.
591fn acc_jumps(acc: &[f64], row: usize) -> bool {
592    let Some(before) = row
593        .checked_sub(JUMP_REFERENCE_ROWS)
594        .and_then(|start| acc.get(start..row))
595    else {
596        return true;
597    };
598    let mut before = before.to_vec();
599    if before.iter().any(|value| !value.is_finite()) {
600        return true;
601    }
602    before.sort_by(f64::total_cmp);
603    let Some(&level) = before.get(JUMP_REFERENCE_ROWS / 2) else {
604        return true;
605    };
606    // Written so that a value that isn't a number is off the level.
607    let off = |row: usize| {
608        acc.get(row).is_none_or(|value| {
609            let close = (value - level).abs() <= JUMP_SHARE * level.abs();
610            !close
611        })
612    };
613    off(row) && off(row + 1)
614}
615
616/// The stretch of coast `Vel`'s slope is fitted over, and the fit.
617struct Coast {
618    /// The least-squares slope of `Vel`, its unit a second.
619    slope: f64,
620    /// How many samples it is fitted to.
621    points: usize,
622    /// Where a jump in `Acc` ends the stretch before `Vel`'s zero, s, if one does.
623    jump_s: Option<f64>,
624}
625
626/// Why no slope could be fitted: the time the stretch ends at, a jump's if one ended it, and how
627/// many samples it holds.
628struct NoCoast {
629    jump_s: Option<f64>,
630    points: usize,
631}
632
633/// The least-squares slope of `Vel` over the coast's last [`APOGEE_WINDOW_S`] before its zero
634/// (module docs, *The apogee check*): the samples from that long before its zero, but not before
635/// its highest, to the first at or below the zero; or, where `Acc` jumps in the
636/// [`DEPLOYMENT_SEARCH_S`] before the zero, the samples of that long before the first jump, to the
637/// row before it. A jump earlier in the window starts it after the jump.
638fn coast_slope(
639    time_s: &[f64],
640    vel: &[f64],
641    acc: &[f64],
642    apogee: &Apogee,
643) -> Result<Coast, NoCoast> {
644    let time = |row: usize| time_s.get(row).copied().unwrap_or(f64::NAN);
645    let scan_from_s = apogee.time_s - DEPLOYMENT_SEARCH_S - APOGEE_WINDOW_S;
646    let jumps: Vec<usize> = (apogee.peak + 1..=apogee.row)
647        .filter(|row| time(*row) >= scan_from_s && acc_jumps(acc, *row))
648        .collect();
649    let first = jumps
650        .iter()
651        .copied()
652        .find(|row| time(*row) >= apogee.time_s - DEPLOYMENT_SEARCH_S);
653    let (end, to_s, jump_s) = match first {
654        Some(row) => (row, time(row), Some(time(row))),
655        None => (apogee.row + 1, apogee.time_s, None),
656    };
657    let start = jumps
658        .iter()
659        .copied()
660        .filter(|row| *row < end)
661        .fold(apogee.peak, usize::max);
662    let points: Vec<(f64, f64)> = (start..end)
663        .filter_map(|row| Some((*time_s.get(row)?, *vel.get(row)?)))
664        .filter(|(time, value)| value.is_finite() && *time >= to_s - APOGEE_WINDOW_S)
665        .collect();
666    let fit = fitted_slope(&points);
667    match fit {
668        Some(slope) if points.len() >= APOGEE_SAMPLES => Ok(Coast {
669            slope,
670            points: points.len(),
671            jump_s,
672        }),
673        _ => Err(NoCoast {
674            jump_s,
675            points: points.len(),
676        }),
677    }
678}
679
680/// The least-squares slope through points `(t, v)`, if one is defined.
681fn fitted_slope(points: &[(f64, f64)]) -> Option<f64> {
682    let count = points.len() as f64;
683    let mean_t = points.iter().map(|p| p.0).sum::<f64>() / count;
684    let mean_v = points.iter().map(|p| p.1).sum::<f64>() / count;
685    let spread: f64 = points.iter().map(|p| (p.0 - mean_t).powi(2)).sum();
686    let slope = points
687        .iter()
688        .map(|p| (p.0 - mean_t) * (p.1 - mean_v))
689        .sum::<f64>()
690        / spread;
691    slope.is_finite().then_some(slope)
692}
693
694/// The air's density at the ground, kg/m³, densest and thinnest, that the barometer's step band
695/// allows (module docs, *The barometer's step*): sea level's standard pressure 5% high in the
696/// coldest air, and the standard pressure at the highest site (U.S. Standard Atmosphere, 1976,
697/// [`Ussa76`]) 5% low in the hottest, by the ideal gas law `ρ = p / (R T)`.
698fn ground_densities_kg_m3() -> (f64, f64) {
699    let gas = DRY_AIR_GAS_CONSTANT_J_PER_KG_K;
700    let densest = SEA_LEVEL_PRESSURE_PA * (1.0 + WEATHER_SPREAD) / (gas * COLDEST_K);
701    let highest_pa = Ussa76::standard()
702        .sample(HIGHEST_SITE_M)
703        .map_or(f64::NAN, |sample| sample.air.pressure_pa);
704    let thinnest = highest_pa * (1.0 - WEATHER_SPREAD) / (gas * HOTTEST_K);
705    (densest, thinnest)
706}
707
708/// The least and the most, m, one barometer count is in altitude at the ground: the hydrostatic
709/// `Δh = Δp / (ρ g)`, [`COUNT_PA`] within [`COUNT_TOLERANCE`], in the densest and the thinnest
710/// air of [`ground_densities_kg_m3`].
711fn step_band_m() -> (f64, f64) {
712    let (densest, thinnest) = ground_densities_kg_m3();
713    (
714        COUNT_PA * (1.0 - COUNT_TOLERANCE) / (densest * STANDARD_GRAVITY_MPS2),
715        COUNT_PA * (1.0 + COUNT_TOLERANCE) / (thinnest * STANDARD_GRAVITY_MPS2),
716    )
717}
718
719/// The band [`step_band_m`] in a unit, as the file would write it.
720fn step_band(unit: Length) -> (f64, f64) {
721    let (least, most) = step_band_m();
722    (least / unit.meters(), most / unit.meters())
723}
724
725/// `pAlt`'s smallest step, in its written unit, and how many of its steps lie within
726/// [`STEP_SPREAD`] above it: the least change between two written values in a row, gaps passed
727/// over, that at least [`STEP_REPEATS`] changes come within [`STEP_SPREAD`] of. `None` if none
728/// does.
729fn smallest_step(palt: &[f64]) -> Option<(f64, usize)> {
730    let written: Vec<f64> = palt.iter().copied().filter(|v| v.is_finite()).collect();
731    // In hundredths, as written; a change that isn't finite or is under a hundredth is no step.
732    let mut steps: Vec<f64> = written
733        .windows(2)
734        .filter_map(|pair| match pair {
735            [a, b] => Some(((b - a).abs() * 100.0).round()),
736            _ => None,
737        })
738        .filter(|step| step.is_finite() && *step >= 1.0)
739        .collect();
740    steps.sort_by(f64::total_cmp);
741    let spread = (STEP_SPREAD * 100.0).round();
742    steps.iter().enumerate().find_map(|(at, step)| {
743        let within = steps
744            .get(at..)
745            .unwrap_or_default()
746            .iter()
747            .take_while(|other| **other <= step + spread)
748            .count();
749        (within >= STEP_REPEATS).then_some((step / 100.0, within))
750    })
751}
752
753/// Over the steps from the first row to `end` where both columns are written, the rise of `of`
754/// and the trapezoid integral of `rate`.
755fn rise_and_integral(time_s: &[f64], of: &[f64], rate: &[f64], end: usize) -> (f64, f64) {
756    let mut rise = 0.0;
757    let mut integral = 0.0;
758    for row in 1..=end.min(time_s.len().saturating_sub(1)) {
759        let (Some(&[t0, t1]), Some(&[a0, a1]), Some(&[r0, r1])) = (
760            time_s
761                .get(row - 1..=row)
762                .and_then(|s| <&[f64; 2]>::try_from(s).ok()),
763            of.get(row - 1..=row)
764                .and_then(|s| <&[f64; 2]>::try_from(s).ok()),
765            rate.get(row - 1..=row)
766                .and_then(|s| <&[f64; 2]>::try_from(s).ok()),
767        ) else {
768            continue;
769        };
770        if [a0, a1, r0, r1].iter().all(|value| value.is_finite()) {
771            rise += a1 - a0;
772            integral += 0.5 * (r0 + r1) * (t1 - t0);
773        }
774    }
775    (rise, integral)
776}
777
778/// Whether `value` is within `margin`, as a share, of `target`.
779fn near(value: f64, target: f64, margin: f64) -> bool {
780    value.is_finite() && (value - target).abs() <= margin * target.abs()
781}
782
783/// Decides each column's unit from the file (module docs, *Columns*).
784fn decide(rows: &Rows, header_line: usize) -> Result<Units, LogError> {
785    let [acc, vel, ialt, palt] = &rows.values;
786    let time_s = &rows.time_s;
787    let line_of = |row: usize| rows.lines.get(row).copied().unwrap_or(header_line);
788    let refuse = |line: usize, message: String| LogError::Unit {
789        format: FORMAT,
790        line,
791        message,
792    };
793
794    // The apogee check: `Vel`'s unit.
795    let Some(apogee) = apogee(time_s, vel) else {
796        return Err(refuse(
797            header_line,
798            "`Vel` never comes back to zero after its highest value: without the apogee, no \
799             unit for it, nor for `pAlt`, can be decided"
800                .to_owned(),
801        ));
802    };
803    let apogee_line = line_of(apogee.row);
804    let window = |jump_s: Option<f64>| {
805        jump_s.map_or_else(
806            || format!("the {APOGEE_WINDOW_S} s before"),
807            |at| format!("the {APOGEE_WINDOW_S} s of coast before `Acc` jumps at {at:.2} s"),
808        )
809    };
810    let coast = match coast_slope(time_s, vel, acc, &apogee) {
811        Ok(coast) => coast,
812        Err(none) => {
813            return Err(refuse(
814                apogee_line,
815                format!(
816                    "into its zero at {:.2} s, `Vel` has {} samples, fewer than {APOGEE_SAMPLES}, \
817                     in {}. Its slope at the apogee decides its unit, and it can't be fitted",
818                    apogee.time_s,
819                    none.points,
820                    window(none.jump_s)
821                ),
822            ));
823        }
824    };
825    let slope = coast.slope;
826    let by_slope: Vec<Length> = Length::BOTH
827        .into_iter()
828        .filter(|unit| near(-slope, unit.gravity(), GRAVITY_MARGIN))
829        .collect();
830    let [length] = by_slope[..] else {
831        return Err(refuse(
832            apogee_line,
833            format!(
834                "into its zero at {:.2} s, over {}, `Vel` changes by {slope:.3} a second. That is \
835                 not within {:.0}% of standard gravity in either m/s² (−9.807) or ft/s² \
836                 (−32.174). No unit for it, nor for `pAlt`, can be decided",
837                apogee.time_s,
838                window(coast.jump_s),
839                GRAVITY_MARGIN * 100.0
840            ),
841        ));
842    };
843
844    // The step check: the barometer's count, apart from `Vel`.
845    let (_, climb) = rise_and_integral(time_s, vel, vel, apogee.row);
846    let climb_m = climb * length.meters();
847    // A climb that isn't a number fails too.
848    let settles = climb_m >= SETTLING_CLIMB_M;
849    if !settles {
850        return Err(refuse(
851            apogee_line,
852            format!(
853                "`Vel` integrates to a climb of {climb_m:.1} m by the apogee. That is under the \
854                 {SETTLING_CLIMB_M:.0} m from which the barometer's step lets `pAlt`'s unit be \
855                 decided"
856            ),
857        ));
858    }
859    let bands = Length::BOTH.map(|unit| {
860        let (least, most) = step_band(unit);
861        format!("{least:.2} to {most:.2} {}", unit.symbol())
862    });
863    let Some((step, repeats)) = smallest_step(palt) else {
864        return Err(refuse(
865            header_line,
866            format!(
867                "`pAlt` has no step written {STEP_REPEATS} times, to within {STEP_SPREAD:.2}. The \
868                 barometer's count can't be measured, and it must bear out the unit `Vel`'s \
869                 slope gives"
870            ),
871        ));
872    };
873    let by_step: Vec<Length> = Length::BOTH
874        .into_iter()
875        .filter(|unit| {
876            let (least, most) = step_band(*unit);
877            step >= least && step <= most
878        })
879        .collect();
880    let [stepped] = by_step[..] else {
881        return Err(refuse(
882            header_line,
883            format!(
884                "`pAlt`'s smallest step, {step:.2}, is one count of the barometer near the ground \
885                 in neither meters ({}) nor feet ({}). No unit for it, nor for `Vel`, can be \
886                 decided",
887                bands[0], bands[1]
888            ),
889        ));
890    };
891    if stepped != length {
892        return Err(refuse(
893            apogee_line,
894            format!(
895                "`Vel`'s slope into its zero at {:.2} s, {slope:.3} a second, is standard gravity \
896                 in {} per second squared. `pAlt`'s smallest step, {step:.2}, is one count of \
897                 the barometer in {}. The two disagree, and no unit is decided",
898                apogee.time_s,
899                length.name(),
900                stepped.name()
901            ),
902        ));
903    }
904    let gravities = -slope / length.gravity();
905    let mut notes = vec![format!(
906        "`Vel` read in {} per second, from the apogee and the barometer's step: its line falls \
907         at {:.3} a second. That line runs through its {} samples of {}, into its zero at \
908         {:.2} s. The line's fall is {gravities:.3} of standard gravity's {:.3} {}/s², within \
909         {:.0}%, and `pAlt`'s step is a count in {} too",
910        length.name(),
911        -slope,
912        coast.points,
913        window(coast.jump_s),
914        apogee.time_s,
915        length.gravity(),
916        length.symbol(),
917        GRAVITY_MARGIN * 100.0,
918        length.name()
919    )];
920
921    // The barometric check: `pAlt`'s highest value against `Vel`'s climb.
922    let highest = palt
923        .iter()
924        .filter(|value| value.is_finite())
925        .fold(f64::NEG_INFINITY, |top, value| top.max(*value));
926    let share = highest / climb;
927    if !near(share, 1.0, BAROMETRIC_MARGIN) {
928        return Err(refuse(
929            apogee_line,
930            format!(
931                "`pAlt`'s highest value, {highest:.2}, is {share:.3} times the climb `Vel` \
932                 integrates to by the apogee, {climb:.2} {}, not within {:.0}%. No unit for the \
933                 barometric altitude can be decided",
934                length.symbol(),
935                BAROMETRIC_MARGIN * 100.0
936            ),
937        ));
938    }
939    let band = match length {
940        Length::Meter => &bands[0],
941        Length::Foot => &bands[1],
942    };
943    notes.push(format!(
944        "`pAlt` read in {}, from its step and `Vel`: its smallest step is {step:.2}. {repeats} of \
945         its steps are within {STEP_SPREAD:.2} of it. The smallest step is one count of the \
946         barometer near the ground in {} ({band}). `pAlt`'s highest value, {highest:.2}, is \
947         {share:.3} times the climb `Vel` integrates to by the apogee, {climb:.2} {}, within \
948         {:.0}%",
949        length.name(),
950        length.name(),
951        length.symbol(),
952        BAROMETRIC_MARGIN * 100.0
953    ));
954    let met_note = format!(
955        "`MET` read in seconds, from the apogee: `Vel` is in {} per second, as the barometer's \
956         step has it. `Vel` falls into its zero at {gravities:.3} of standard gravity a second. A \
957         clock in milliseconds or minutes would put that fall 1,000 or 60 times off",
958        length.name()
959    );
960
961    // The boost check: `Acc`'s unit.
962    let (rise, integral) = rise_and_integral(time_s, vel, acc, apogee.peak);
963    let ratio = rise / integral;
964    let boost_ratio = ratio.is_finite().then_some(ratio);
965    let acceleration = if near(ratio, 1.0, INTEGRAL_MARGIN) {
966        notes.push(format!(
967            "`Acc` read in {} per second squared, from `Vel`: over the boost, `Vel` rises \
968             {ratio:.3} times `Acc`'s integral, within {:.0}% of 1",
969            length.name(),
970            INTEGRAL_MARGIN * 100.0
971        ));
972        Some(length.meters())
973    } else if near(ratio, length.gravity(), INTEGRAL_MARGIN) {
974        notes.push(format!(
975            "`Acc` read in standard gravities, 9.806 65 m/s², from `Vel`: over the boost, `Vel` \
976             rises {ratio:.3} times `Acc`'s integral. That is within {:.0}% of standard \
977             gravity's {:.3} {}/s²",
978            INTEGRAL_MARGIN * 100.0,
979            length.gravity(),
980            length.symbol()
981        ));
982        Some(STANDARD_GRAVITY_MPS2)
983    } else {
984        notes.push(format!(
985            "`Acc` kept as written: over the boost, `Vel` rises {ratio:.3} times `Acc`'s \
986             integral. That is within {:.0}% of neither 1 nor standard gravity in {} per second \
987             squared",
988            INTEGRAL_MARGIN * 100.0,
989            length.name()
990        ));
991        None
992    };
993
994    // The inertial check: `iAlt`'s unit.
995    let (rise, integral) = rise_and_integral(time_s, ialt, vel, apogee.row);
996    let ratio = rise / integral;
997    let inertial = near(ratio, 1.0, INTEGRAL_MARGIN);
998    notes.push(if inertial {
999        format!(
1000            "`iAlt` read in {}, from `Vel`: to the apogee it rises {ratio:.4} times `Vel`'s \
1001             integral, within {:.0}% of 1",
1002            length.name(),
1003            INTEGRAL_MARGIN * 100.0
1004        )
1005    } else {
1006        format!(
1007            "`iAlt` kept as written: to the apogee it rises {ratio:.4} times `Vel`'s integral, \
1008             not within {:.0}% of 1",
1009            INTEGRAL_MARGIN * 100.0
1010        )
1011    });
1012    notes.push(met_note);
1013    Ok(Units {
1014        length,
1015        acceleration,
1016        inertial,
1017        boost_ratio,
1018        notes,
1019    })
1020}
1021
1022/// Marks the closing run of `Vel` and `iAlt` zeros gaps where it is a placeholder (module docs,
1023/// *The closing zeros*).
1024fn closing_zeros(rows: &Rows, units: &Units, values: &mut [Vec<f64>; 4], notes: &mut Vec<String>) {
1025    let count = rows.time_s.len();
1026    let at = |column: usize, row: usize| rows.values[column].get(row).copied().unwrap_or(f64::NAN);
1027    // `Acc`'s rate moves `Vel` by the boost check's ratio only where that check bore `Acc` out;
1028    // kept as written, `Acc` sets no reach, and `Vel`'s zeros are kept.
1029    let vel_scale = units.acceleration.and(units.boost_ratio).map(f64::abs);
1030    for (column, rate, scale) in [(VEL, ACC, vel_scale), (IALT, VEL, Some(1.0))] {
1031        let run = (0..count)
1032            .rev()
1033            .take_while(|row| at(column, *row) == 0.0)
1034            .count();
1035        let Some(before) = count.checked_sub(run + 1) else {
1036            continue;
1037        };
1038        let (Some(scale), Some(last), Some(&start)) =
1039            (scale, count.checked_sub(1), rows.time_s.get(before))
1040        else {
1041            continue;
1042        };
1043        let span = rows.time_s.get(last).map_or(f64::NAN, |end| end - start);
1044        // The most the rate can move the column over the run, its largest written value held
1045        // throughout.
1046        let fastest = (before..count)
1047            .map(|row| at(rate, row).abs())
1048            .filter(|value| value.is_finite())
1049            .fold(0.0, f64::max);
1050        let reach = fastest * scale * span;
1051        let previous = at(column, before);
1052        if run > 0
1053            && previous.is_finite()
1054            && reach.is_finite()
1055            && previous.abs() > 2.0 * reach + ROUNDING
1056        {
1057            for row in before + 1..count {
1058                if let Some(cell) = values[column].get_mut(row) {
1059                    *cell = f64::NAN;
1060                }
1061            }
1062            notes.push(format!(
1063                "the last {run} rows, from line {}, write `{}` as 0, where the row before reads \
1064                 {previous:.2}. That is more than twice what `{}` can change it by in {span:.2} s. \
1065                 So they aren't its integral, and they are gaps",
1066                rows.lines.get(before + 1).copied().unwrap_or_default(),
1067                NAMES[column + 1],
1068                NAMES[rate + 1],
1069            ));
1070        }
1071    }
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076    use super::*;
1077
1078    /// An invented flight as the export writes it, a row every 0.1 s: a boost of `boost_s` at
1079    /// `boost_m_s2` net, a coast at −g less a drag of 0.0004 v² a meter, and 5 s of descent with
1080    /// the accelerometer reading −0.3 m/s²; `Vel` and `iAlt` the trapezoid integrals of the
1081    /// written `Acc` and `Vel`, `pAlt` 0.97 of the climb then falling at 20 m/s, in steps of 9 m.
1082    /// `Vel`, `iAlt` and `pAlt` are written in units of `length_m` meters and `Acc` in units of
1083    /// `acc_m_s2`.
1084    fn flight(boost_s: f64, boost_m_s2: f64, length_m: f64, acc_m_s2: f64) -> String {
1085        flight_deploying(boost_s, boost_m_s2, length_m, acc_m_s2, None, 0.1)
1086    }
1087
1088    /// [`flight`], with a parachute out once the rocket has slowed to `deploy_m_s` on its way up,
1089    /// if given: from then on to the apogee, the accelerometer reads its drag besides the
1090    /// rocket's, g (v / 5 m/s)², the drag of a canopy that would bring the rocket down at 5 m/s;
1091    /// a row every `dt` seconds.
1092    fn flight_deploying(
1093        boost_s: f64,
1094        boost_m_s2: f64,
1095        length_m: f64,
1096        acc_m_s2: f64,
1097        deploy_m_s: Option<f64>,
1098        dt: f64,
1099    ) -> String {
1100        let mut deployed = false;
1101        let mut text = String::from("# MET Acc Vel iAlt pAlt \n");
1102        let (mut vel, mut ialt, mut previous) = (0.0_f64, 0.0_f64, None::<f64>);
1103        let mut apogee: Option<(f64, f64)> = None;
1104        for row in 0..10_000 {
1105            let time = f64::from(row) * dt;
1106            let acc_si = if row == 0 {
1107                0.0
1108            } else if time <= boost_s + 1e-9 {
1109                boost_m_s2
1110            } else if apogee.is_none() {
1111                deployed |= deploy_m_s.is_some_and(|speed| vel <= speed);
1112                let chute = if deployed {
1113                    STANDARD_GRAVITY_MPS2 * (vel / 5.0).powi(2)
1114                } else {
1115                    0.0
1116                };
1117                -STANDARD_GRAVITY_MPS2 - 0.0004 * vel * vel.abs() - chute
1118            } else {
1119                -0.3
1120            };
1121            let acc = (acc_si / acc_m_s2 * 100.0).round() / 100.0;
1122            if let Some(before) = previous {
1123                let next = vel + 0.5 * (before + acc) * acc_m_s2 * dt;
1124                ialt = (ialt + 0.5 * (vel + next) * dt).max(0.0);
1125                if apogee.is_none() && vel > 0.0 && next <= 0.0 {
1126                    apogee = Some((time, 0.97 * ialt));
1127                }
1128                vel = next;
1129            }
1130            previous = Some(acc);
1131            let baro = apogee.map_or(0.97 * ialt, |(at, top)| (top - 20.0 * (time - at)).max(0.0));
1132            let palt = (baro / 9.0).round() * 9.0;
1133            text.push_str(&format!(
1134                "{time:.3},{acc:.2},{:.2},{:.2},{:.2}\n",
1135                vel / length_m,
1136                ialt / length_m,
1137                palt / length_m
1138            ));
1139            if apogee.is_some_and(|(at, _)| time > at + 5.0) {
1140                break;
1141            }
1142        }
1143        text
1144    }
1145
1146    /// The metric flight: 2 s at 70 m/s², about 830 m up.
1147    fn metric() -> String {
1148        flight(2.0, 70.0, 1.0, 1.0)
1149    }
1150
1151    /// The same flight as the English files write it: feet, ft/s, and `Acc` in g.
1152    fn english() -> String {
1153        flight(2.0, 70.0, FOOT_M, STANDARD_GRAVITY_MPS2)
1154    }
1155
1156    /// The text with one column's values, past the header, multiplied by `factor`.
1157    fn scaled(text: &str, column: usize, factor: f64) -> String {
1158        text.lines()
1159            .map(|line| {
1160                if line.starts_with('#') {
1161                    return format!("{line}\n");
1162                }
1163                let cells: Vec<String> = line
1164                    .split(',')
1165                    .enumerate()
1166                    .map(|(index, cell)| {
1167                        if index == column + 1 {
1168                            format!("{:.2}", cell.parse::<f64>().unwrap() * factor)
1169                        } else {
1170                            cell.to_owned()
1171                        }
1172                    })
1173                    .collect();
1174                format!("{}\n", cells.join(","))
1175            })
1176            .collect()
1177    }
1178
1179    fn highest(values: &[f64]) -> f64 {
1180        values
1181            .iter()
1182            .filter(|value| value.is_finite())
1183            .fold(f64::NEG_INFINITY, |top, value| top.max(*value))
1184    }
1185
1186    fn unit_message(result: Result<FlightLog, LogError>) -> String {
1187        match result {
1188            Err(LogError::Unit { message, .. }) => message,
1189            other => panic!("expected a unit error, got {other:?}"),
1190        }
1191    }
1192
1193    #[test]
1194    fn the_header_is_recognized_and_others_are_not() {
1195        assert!(recognizes(
1196            "# MET Acc Vel iAlt pAlt \n0.000,0.00,0.00,0.00,0.00\n"
1197        ));
1198        assert!(recognizes("\u{feff}\r\n#MET,Acc,Vel,iAlt,pAlt\r\n"));
1199        assert!(recognizes("# met acc vel ialt palt\n"));
1200        for other in [
1201            "MET,Acc(HI),Acc/Baro(LO),Baro(HI),State\n0.000,512,4,777,64\n",
1202            "#version,serial,flight,call,time,clock,rssi,lqi\n",
1203            "# Comments\n# MET Acc Vel iAlt pAlt\n",
1204            "# MET Acc Vel iAlt\n",
1205            "# MET Acc Vel iAlt pAlt State\n",
1206            "# MET Acc Vel pAlt iAlt\n",
1207            "MET Acc Vel iAlt pAlt\n",
1208            "",
1209        ] {
1210            assert!(!recognizes(other), "{other:?}");
1211        }
1212    }
1213
1214    /// The two unit systems of the sample files, each read from its own evidence, and the same
1215    /// flight in each: reading feet as meters, or g as m/s², would put the two 3.28 or 9.81
1216    /// times apart.
1217    #[test]
1218    fn metric_and_english_files_read_to_the_same_flight() {
1219        let metric = read(&metric()).unwrap();
1220        let english = read(&english()).unwrap();
1221        let top_m = highest(&metric.altitude_m);
1222        let top_e = highest(&english.altitude_m);
1223        assert!(top_m > 700.0 && top_m < 1_000.0, "{top_m}");
1224        // `pAlt` is written to a hundredth of a foot, 0.003 m.
1225        assert!((top_m - top_e).abs() < 0.01, "{top_m} m against {top_e} m");
1226        // `Acc` written to a hundredth of a g is within 0.05 m/s² of its value; `Vel` and `iAlt`
1227        // integrate the written `Acc`, so they drift apart by a little more, and `pAlt`, worked
1228        // out from `iAlt`, can round to the next of its 9 m steps.
1229        for (column, allowed) in [(0, 0.06), (1, 3.0), (2, 3.0), (3, 9.01)] {
1230            let (a, b) = (&metric.channels[column], &english.channels[column]);
1231            assert_eq!(a.quantity, b.quantity, "{}", a.column);
1232            let worst = a
1233                .values
1234                .iter()
1235                .zip(&b.values)
1236                .filter(|(x, y)| x.is_finite() && y.is_finite())
1237                .map(|(x, y)| (x - y).abs())
1238                .fold(0.0, f64::max);
1239            assert!(worst < allowed, "{}: {worst}", a.column);
1240        }
1241        let quantities: Vec<Quantity> = metric.channels.iter().map(|c| c.quantity).collect();
1242        assert_eq!(
1243            quantities,
1244            [
1245                Quantity::Acceleration,
1246                Quantity::Speed,
1247                Quantity::InertialAltitude,
1248                Quantity::AltitudeAboveGround
1249            ]
1250        );
1251        let from = "per second, from the apogee and the barometer's step: ";
1252        assert!(metric.notes[0].starts_with(&format!("`Vel` read in meters {from}")));
1253        assert!(english.notes[0].starts_with(&format!("`Vel` read in feet {from}")));
1254        assert!(metric.notes[1].starts_with("`pAlt` read in meters, from its step and `Vel`: "));
1255        assert!(english.notes[1].starts_with("`pAlt` read in feet, from its step and `Vel`: "));
1256        assert!(english.notes[2].starts_with("`Acc` read in standard gravities, "));
1257        assert!(metric.notes[2].starts_with("`Acc` read in meters per second squared, "));
1258        for log in [&metric, &english] {
1259            assert!(log.notes[4].starts_with("`MET` read in seconds, from the apogee: "));
1260        }
1261        assert!(metric.vertical_speed_m_s.is_none());
1262    }
1263
1264    /// A velocity whose slope at the apogee is g in neither unit settles no unit for the primary
1265    /// track: the file is refused, not read in a guessed unit.
1266    #[test]
1267    fn a_velocity_that_falls_at_no_gravity_is_refused() {
1268        for factor in [2.0, 0.5, 1.6 / FOOT_M] {
1269            let message = unit_message(read(&scaled(&metric(), VEL, factor)));
1270            assert!(
1271                message.contains("not within 25% of standard gravity in either"),
1272                "{factor}: {message}"
1273            );
1274        }
1275    }
1276
1277    /// The barometric altitude in feet beside a velocity in m/s, or in meters beside one in ft/s:
1278    /// the barometer's step and the velocity's slope disagree, and the file is refused. A step
1279    /// that is a count in both units' bands but a highest value half again the climb is refused
1280    /// by the barometric check.
1281    #[test]
1282    fn a_barometric_altitude_in_another_unit_is_refused() {
1283        for (text, slope, step) in [
1284            (scaled(&metric(), PALT, 1.0 / FOOT_M), "meters", "feet"),
1285            (scaled(&english(), PALT, FOOT_M), "feet", "meters"),
1286        ] {
1287            let message = unit_message(read(&text));
1288            assert!(
1289                message.contains(&format!(
1290                    "is standard gravity in {slope} per second squared"
1291                )) && message.contains(&format!(
1292                    "one count of the barometer in {step}. The two disagree"
1293                )),
1294                "{message}"
1295            );
1296        }
1297        for text in [metric(), english()] {
1298            let message = unit_message(read(&scaled(&text, PALT, 1.5)));
1299            assert!(message.starts_with("`pAlt`'s highest value, "), "{message}");
1300        }
1301    }
1302
1303    /// The barometer's step settles a unit only inside one unit's band: a step of a third of a
1304    /// count, or one between the bands, is refused, and so is a `pAlt` with no step written
1305    /// three times.
1306    #[test]
1307    fn a_step_in_neither_band_is_refused() {
1308        let (least_m, most_m) = step_band(Length::Meter);
1309        let (least_ft, most_ft) = step_band(Length::Foot);
1310        // The bands are apart: the most a count is in meters is under the least in feet.
1311        assert!(most_m < least_ft, "{most_m} m against {least_ft} ft");
1312        // 1 / (1,024 × 0.010 59) kPa; the densest air 1.464 kg/m³, the thinnest 0.729.
1313        assert!((COUNT_PA - 92.216).abs() < 1e-3, "{COUNT_PA}");
1314        let (densest, thinnest) = ground_densities_kg_m3();
1315        assert!((densest - 1.4640).abs() < 1e-3, "{densest}");
1316        assert!((thinnest - 0.7294).abs() < 1e-3, "{thinnest}");
1317        assert!((least_m - 5.460).abs() < 1e-3 && (most_m - 14.83).abs() < 1e-2);
1318        assert!((least_ft - 17.91).abs() < 1e-2 && (most_ft - 48.64).abs() < 1e-2);
1319        // Each scale moves the 9 m step and the highest value together, so only the step's band
1320        // decides: 9 × 0.5 = 4.5 m is below the metric band, 9 × 1.8 = 16.2 between the bands.
1321        for factor in [0.5, 1.8] {
1322            let message = unit_message(read(&scaled(&metric(), PALT, factor)));
1323            assert!(
1324                message.contains("in neither meters ("),
1325                "{factor}: {message}"
1326            );
1327        }
1328        // A `pAlt` that steps by 9 once, and by more each other time, has no step to measure; a
1329        // single smaller step, as a closing zero can make, isn't taken for the count.
1330        assert_eq!(smallest_step(&[0.0, 9.0, 29.0, 70.0, 153.0]), None);
1331        let steps = [0.0, 9.0, 18.01, f64::NAN, 27.02, 36.02, 30.0];
1332        assert_eq!(smallest_step(&steps), Some((9.0, 4)));
1333        // The metric flight with `pAlt` stepping by 0.37 more on each row than the row before.
1334        let text: String = metric()
1335            .lines()
1336            .enumerate()
1337            .map(|(row, line)| match line.rsplit_once(',') {
1338                Some((head, _)) if row > 0 => {
1339                    let row = row as f64;
1340                    format!("{head},{:.2}\n", 0.37 * row * (row + 1.0) / 2.0)
1341                }
1342                _ => format!("{line}\n"),
1343            })
1344            .collect();
1345        let message = unit_message(read(&text));
1346        assert!(
1347            message.starts_with("`pAlt` has no step written 3 times"),
1348            "{message}"
1349        );
1350    }
1351
1352    /// The bound [`DEPLOYMENT_SEARCH_S`] rests on: a canopy that takes more than 2 s to stop the
1353    /// rocket has a descent rate over `4g/π`, and then makes `Vel` fall at no more than 1.28 g
1354    /// over the zero's last second, outside the other unit's 25% of g either way.
1355    #[test]
1356    fn a_parachute_out_more_than_2_s_early_slows_vel_little() {
1357        let g = STANDARD_GRAVITY_MPS2;
1358        // The time to stop from any speed is under (v_t / g) π/2: 2 s at v_t = 4g/π.
1359        let least = 4.0 * g / std::f64::consts::PI;
1360        assert!((least * std::f64::consts::FRAC_PI_2 / g - DEPLOYMENT_SEARCH_S).abs() < 1e-12);
1361        // The mean fall over the last second, v_t tan(g / v_t), falls toward g as v_t grows.
1362        let fall = |rate: f64| rate * (g / rate).tan() / g;
1363        let mut before = fall(least);
1364        assert!(before < 1.28 && before > 1.27, "{before}");
1365        for rate in (1..=100).map(|step| least + f64::from(step)) {
1366            let now = fall(rate);
1367            assert!(now < before && now > 1.0, "{rate}: {now}");
1368            before = now;
1369        }
1370        // Read in the other unit, 1.28 g is 0.39 g or 4.2 g.
1371        assert!(!near(1.28 * FOOT_M, 1.0, GRAVITY_MARGIN));
1372        assert!(!near(1.28 / FOOT_M, 1.0, GRAVITY_MARGIN));
1373    }
1374
1375    /// `Acc` and `iAlt` that no check bears out are kept as written, the file still read.
1376    #[test]
1377    fn columns_no_check_bears_out_are_kept_as_written() {
1378        let log = read(&scaled(&metric(), ACC, 3.0)).unwrap();
1379        assert_eq!(log.channels[0].quantity, Quantity::Unrecognized);
1380        assert!(
1381            log.notes
1382                .iter()
1383                .any(|n| n.starts_with("`Acc` kept as written: "))
1384        );
1385        let log = read(&scaled(&metric(), IALT, 1.0 / FOOT_M)).unwrap();
1386        assert_eq!(log.channels[2].quantity, Quantity::Unrecognized);
1387        assert!(
1388            log.notes
1389                .iter()
1390                .any(|n| n.starts_with("`iAlt` kept as written: "))
1391        );
1392        // `Acc` in g beside m/s, a pairing no sample file has, is read so from its own check.
1393        let log = read(&scaled(&metric(), ACC, 1.0 / STANDARD_GRAVITY_MPS2)).unwrap();
1394        assert_eq!(log.channels[0].quantity, Quantity::Acceleration);
1395        assert!(log.notes[2].starts_with("`Acc` read in standard gravities"));
1396    }
1397
1398    /// The edges of the apogee check, each side of 25% of g: a slope of 1.22 g reads, 1.28 g
1399    /// doesn't; 0.78 g reads, 0.72 g doesn't. Every column is scaled together, so the other
1400    /// checks hold and only the slope moves.
1401    #[test]
1402    fn the_apogee_margin_is_25_percent() {
1403        for (factor, reads) in [(1.22, true), (1.28, false), (0.78, true), (0.72, false)] {
1404            let text = [ACC, VEL, IALT, PALT]
1405                .into_iter()
1406                .fold(metric(), |text, column| scaled(&text, column, factor));
1407            let result = read(&text);
1408            if reads {
1409                let log = result.unwrap();
1410                assert!(log.notes[0].starts_with("`Vel` read in meters per second"));
1411            } else {
1412                assert!(matches!(result, Err(LogError::Unit { .. })), "{factor}");
1413            }
1414        }
1415    }
1416
1417    /// A flight too low for the barometer's step to settle `pAlt`'s unit, and a file cut before
1418    /// its apogee, are refused.
1419    #[test]
1420    fn low_and_unfinished_flights_are_refused() {
1421        // 1 s at 40 m/s², about 100 m up after a 4 s coast.
1422        let message = unit_message(read(&flight(1.0, 40.0, 1.0, 1.0)));
1423        assert!(message.contains("under the 176 m"), "{message}");
1424        // 0.3 s at 30 m/s²: under a second of coast, too little to fit `Vel`'s slope to.
1425        let message = unit_message(read(&flight(0.3, 30.0, 1.0, 1.0)));
1426        assert!(
1427            message.contains("`Vel` has 1 samples, fewer than 3, in the 1 s of coast before"),
1428            "{message}"
1429        );
1430        let cut: String = metric()
1431            .lines()
1432            .take(60)
1433            .map(|l| format!("{l}\n"))
1434            .collect();
1435        let message = unit_message(read(&cut));
1436        assert!(
1437            message.starts_with("`Vel` never comes back to zero"),
1438            "{message}"
1439        );
1440        let message = unit_message(read("# MET Acc Vel iAlt pAlt\n0,,,,\n0.02,,,,\n"));
1441        assert!(
1442            message.starts_with("`Vel` never comes back to zero"),
1443            "{message}"
1444        );
1445    }
1446
1447    /// The closing zeros of `Vel` are gaps; a zero `Vel` its rate could reach is kept.
1448    #[test]
1449    fn closing_zeros_beyond_reach_are_gaps() {
1450        let mut text = metric();
1451        let last = text.trim_end().rsplit_once('\n').unwrap().1.to_owned();
1452        let cells: Vec<&str> = last.split(',').collect();
1453        let time: f64 = cells[0].parse().unwrap();
1454        text.push_str(&format!(
1455            "{:.3},{},0.00,{},{}\n",
1456            time + 0.1,
1457            cells[1],
1458            cells[3],
1459            cells[4]
1460        ));
1461        text.push_str(&format!("{:.3},0.00,0.00,0.00,0.00\n", time + 0.2));
1462        let log = read(&text).unwrap();
1463        let vel = &log.channels[1].values;
1464        assert!(vel[vel.len() - 2..].iter().all(|v| v.is_nan()));
1465        assert!(vel[vel.len() - 3].is_finite());
1466        assert!(
1467            log.notes
1468                .iter()
1469                .any(|n| n.starts_with("the last 2 rows, from line "))
1470        );
1471        // `pAlt` and `Acc` keep their zeros.
1472        assert_eq!(log.altitude_m.last(), Some(&0.0));
1473        assert_eq!(log.channels[0].values.last(), Some(&0.0));
1474        // A small velocity coming to zero in one step of a large `Acc` is no placeholder.
1475        let text = "# MET Acc Vel iAlt pAlt\n0,0,0,0,0\n0.02,50,0.5,0,0\n0.04,-50,0,0.01,0\n";
1476        let rows = rows(numbered_lines(text).skip(1)).unwrap();
1477        let units = Units {
1478            length: Length::Meter,
1479            acceleration: Some(1.0),
1480            inertial: true,
1481            boost_ratio: Some(1.0),
1482            notes: Vec::new(),
1483        };
1484        let mut values = rows.values.clone();
1485        let mut notes = Vec::new();
1486        closing_zeros(&rows, &units, &mut values, &mut notes);
1487        assert_eq!(values[VEL][2], 0.0);
1488        assert!(notes.is_empty(), "{notes:?}");
1489    }
1490
1491    /// Rows not five cells wide, and clocks that don't increase, are refused by line; other cells
1492    /// that aren't numbers are gaps.
1493    #[test]
1494    fn rows_are_checked_and_bad_cells_are_gaps() {
1495        let header = "# MET Acc Vel iAlt pAlt\n";
1496        for (body, line) in [
1497            ("0,0,0,0,0\n0.1,0,0,0\n", 3),
1498            ("0,0,0,0,0\n0,0,0,0,0\n", 3),
1499            ("0,0,0,0,0\n,0,0,0,0\n", 3),
1500            ("0,0,0,0,0,\n", 2),
1501        ] {
1502            match read(&format!("{header}{body}")) {
1503                Err(LogError::Syntax { line: at, .. }) => assert_eq!(at, line, "{body:?}"),
1504                other => panic!("{body:?}: {other:?}"),
1505            }
1506        }
1507        assert_eq!(read(header), Err(LogError::NoData { format: FORMAT }));
1508        let text = metric().replacen("\n1.000,", "\n1.000,x", 1);
1509        let log = read(&text).unwrap();
1510        assert!(log.channels[0].values[10].is_nan());
1511        assert!(
1512            log.notes
1513                .iter()
1514                .any(|n| n.starts_with("`Acc` has 1 cells that are empty or aren't a number"))
1515        );
1516        // A row wider than five cells is refused without reading past its sixth.
1517        match read(&format!("{header}0,0,0,0,0{}\n", ",0".repeat(1_000))) {
1518            Err(LogError::Syntax {
1519                line: 2, message, ..
1520            }) => {
1521                assert!(
1522                    message.starts_with("a row of more than 5 cells, "),
1523                    "{message}"
1524                );
1525            }
1526            other => panic!("{other:?}"),
1527        }
1528    }
1529
1530    /// An `Acc` in g finite as written and infinite in m/s² is refused on its line (ADR-258 §3).
1531    #[test]
1532    fn a_value_its_conversion_makes_infinite_is_refused() {
1533        let text = english();
1534        let at = text.find("\n17.000,").unwrap() + 1;
1535        let end = at + text[at..].find(',').unwrap();
1536        let next = end + 1 + text[end + 1..].find(',').unwrap();
1537        let text = format!("{}1e308{}", &text[..=end], &text[next..]);
1538        assert_eq!(
1539            read(&text).unwrap_err().to_string(),
1540            "ARTS2 CSV line 172: the column Acc holds a value too large for its unit's \
1541             conversion to SI"
1542        );
1543        // `1e308` is finite as written, and as written it is kept when `Acc` has no unit.
1544        let values = convert(&[1e308, f64::NAN, 2.0], 1.0, &[2, 3, 4], "Acc").unwrap();
1545        assert!(values[0] == 1e308 && values[1].is_nan() && values[2] == 2.0);
1546        // The first value the scale makes infinite is refused, on its own line.
1547        assert_eq!(
1548            convert(&[2.0, -1e308, 1e308], 10.0, &[2, 3, 4], "Acc")
1549                .unwrap_err()
1550                .to_string(),
1551            "ARTS2 CSV line 3: the column Acc holds a value too large for its unit's conversion \
1552             to SI"
1553        );
1554    }
1555
1556    /// `Vel`'s closing zeros are judged against `Acc`'s reach only where the boost check read
1557    /// `Acc` in a unit: kept as written, `Acc` sets no reach, and the zeros are kept.
1558    #[test]
1559    fn closing_zeros_need_an_acceleration_in_a_unit() {
1560        let text = "# MET Acc Vel iAlt pAlt\n0,0,0,0,0\n0.02,1,100,0,0\n0.04,1,0,2,0\n";
1561        let rows = rows(numbered_lines(text).skip(1)).unwrap();
1562        for (acceleration, kept) in [(Some(1.0), false), (None, true)] {
1563            let units = Units {
1564                length: Length::Meter,
1565                acceleration,
1566                inertial: true,
1567                boost_ratio: Some(1.0),
1568                notes: Vec::new(),
1569            };
1570            let mut values = rows.values.clone();
1571            let mut notes = Vec::new();
1572            closing_zeros(&rows, &units, &mut values, &mut notes);
1573            assert_eq!(values[VEL][2] == 0.0, kept, "{acceleration:?}");
1574            assert_eq!(notes.is_empty(), kept, "{notes:?}");
1575        }
1576    }
1577
1578    /// A barometric altitude more than a step off zero on the first row gets a note.
1579    #[test]
1580    fn a_ground_off_zero_is_noted() {
1581        let text = metric().replacen(
1582            "\n0.000,0.00,0.00,0.00,0.00\n",
1583            "\n0.000,0.00,0.00,0.00,27.00\n",
1584            1,
1585        );
1586        let log = read(&text).unwrap();
1587        assert!(
1588            log.notes
1589                .iter()
1590                .any(|n| n.starts_with("`pAlt` reads 27.00 m on the first row"))
1591        );
1592        let log = read(&metric()).unwrap();
1593        assert!(!log.notes.iter().any(|n| n.contains("first row")));
1594    }
1595
1596    /// A metric flight, a row every 0.02 s as the logger's 50 Hz, whose parachute comes out at
1597    /// 25 m/s on the way up, 0.62 s before `Vel`'s zero. Over the second before the zero, the
1598    /// chute's drag makes `Vel` fall at 3.7 g in m/s, 1.13 g in ft/s, within 25% of g in feet:
1599    /// fitted there, as the reader once did, the file would be read in feet, its heights 3.28
1600    /// times too low. The jump in `Acc` ends the window at the deployment, where `Vel` falls at
1601    /// 1.04 g in m/s, and the barometer's step agrees: it is read in meters.
1602    #[test]
1603    fn a_parachute_out_before_the_apogee_does_not_flip_the_unit() {
1604        let text = flight_deploying(2.0, 70.0, 1.0, 1.0, Some(25.0), 0.02);
1605        let rows = rows(numbered_lines(&text).skip(1)).unwrap();
1606        let [acc, vel, _, palt] = &rows.values;
1607        let apogee = apogee(&rows.time_s, vel).unwrap();
1608        // The fit over the second before the zero, as the reader made it before the jump check.
1609        let old: Vec<(f64, f64)> = (apogee.peak..=apogee.row)
1610            .map(|row| (rows.time_s[row], vel[row]))
1611            .filter(|(time, _)| *time >= apogee.time_s - APOGEE_WINDOW_S)
1612            .collect();
1613        let old_slope = fitted_slope(&old).unwrap();
1614        assert!(
1615            near(-old_slope, Length::Foot.gravity(), GRAVITY_MARGIN),
1616            "{old_slope}"
1617        );
1618        assert!(!near(-old_slope, Length::Meter.gravity(), GRAVITY_MARGIN));
1619        // The coast before the jump falls at g in m/s, and the step is a count in meters.
1620        let Ok(coast) = coast_slope(&rows.time_s, vel, acc, &apogee) else {
1621            panic!("no coast");
1622        };
1623        let jump = coast.jump_s.unwrap();
1624        assert!(
1625            jump < apogee.time_s - 0.5 && jump > apogee.time_s - 1.0,
1626            "{jump}"
1627        );
1628        assert!(
1629            near(-coast.slope, Length::Meter.gravity(), 0.1),
1630            "{}",
1631            coast.slope
1632        );
1633        assert_eq!(smallest_step(palt).map(|(step, _)| step), Some(9.0));
1634        let log = read(&text).unwrap();
1635        let note = &log.notes[0];
1636        assert!(
1637            note.starts_with(
1638                "`Vel` read in meters per second, from the apogee and the barometer's step: "
1639            ) && note.contains(&format!("of coast before `Acc` jumps at {jump:.2} s")),
1640            "{note}"
1641        );
1642        let top = highest(&log.altitude_m);
1643        assert!(top > 700.0 && top < 1_000.0, "{top}");
1644    }
1645
1646    #[test]
1647    fn the_step_is_the_coarsest_of_the_sample_files() {
1648        assert!((ALTITUDE_STEP_M - 8.805_672).abs() < 1e-9);
1649    }
1650}