Skip to main content

hpr_flightdata/
sillygoose.rs

1//! AerospaceNU's SillyGoose flight computer's logs, as the board writes them: text under a
2//! `timestampMs` header, one row per sample.
3//!
4//! The SillyGoose is a flight computer of Northeastern University's rocketry club, AerospaceNU,
5//! that logs its barometer, its accelerometer and gyroscope, its own altitude and vertical-speed
6//! estimates and its pyro channels' state. The club publishes its flights' logs with a README
7//! that names each file after its flight and tags it, among others, `pre reboot` and `post
8//! reboot` where the board restarted in flight and its log is in two files, and `doctored` where
9//! the file was altered after it was offloaded (AerospaceNU, *rocket-flight-data*, `README.md`,
10//! read 2026-10-12). No published document describes the columns, so each unit here comes from
11//! the column's name or from a check the reader runs on the file's values, as below. Three
12//! layouts are among the project's sample logs, all read alike:
13//!
14//! - *The board's log*: tab-separated, 20 columns, about 100 samples a second in flight and one
15//!   every 5 s on the pad (here with the tabs shown as spaces):
16//!
17//!   ```text
18//!   timestampMs  pressurePa  tempK  accelX  accelY  accelZ  gyroX  gyroY  gyroZ  imuTemp  …
19//!   1000  97716.500000  290.15  0.012000  -0.020000  9.810000  0.001064  …
20//!   ```
21//!
22//! - *With its settings*: a `CONFIG` line of `KEY=VALUE` settings, then the same header with 8
23//!   more columns, `tiltMagnitudeDeg`, `angularVelRadS_x` … `_z` and `quaternion_a` … `_d`. The one
24//!   such sample file looks like replayed output, not a recording: after a few samples on the pad
25//!   it jumps into the boost, it ends still climbing, and its temperature holds one value
26//!   throughout (a note says so; below).
27//! - *Space-separated*: the 20 columns' header with single spaces between the names, at 50
28//!   samples a second, whose values don't all agree with the units the names state; the checks
29//!   below find which do.
30//!
31//! **Recognition.** The first line that isn't blank, or the one after it if that first line opens
32//! with `CONFIG`, is a header whose first name is `timestampMs` and which names `pressurePa` and
33//! `altitudeM`, compared without regard to case. A header with a tab has its names and its rows'
34//! cells split at tabs; one without, at runs of spaces. The club's ground station's conversion
35//! of a downlink, a `CONFIG` line and then comma-separated rows with no header, is not this
36//! layout and isn't read.
37//!
38//! **Columns.** Each name the reader knows, what it is read as, and where its unit comes from;
39//! the column keeps the file's name. A column the reader doesn't know is kept as written,
40//! [`Quantity::Unrecognized`], with a note (the first 20 such notes kept, the rest counted); a
41//! header naming a column twice, with an empty name, or with more than [`MAX_COLUMNS`] names is
42//! refused:
43//!
44//! | Column | Quantity | Unit, and from where |
45//! |---|---|---|
46//! | `timestampMs` | the clock | milliseconds, from its name; the board's own zero, before its first sample |
47//! | `pressurePa` | [`Quantity::Pressure`] | Pa, from its name, if its first value is a pressure near the ground in pascals |
48//! | `tempK` | [`Quantity::Temperature`]: [`FlightLog::temperature_k`] | K, from its name, if every value is one an electronics bay can have in kelvin |
49//! | `accelX`, `accelY`, `accelZ` | [`Quantity::Acceleration`] | m/s² or standard gravities, from the pad's gravity (below) |
50//! | `gyroX`, `gyroY`, `gyroZ` | [`Quantity::AngularRate`] | radians or degrees per second, from the board's turning (below) |
51//! | `imuTemp` | [`Quantity::Temperature`] | K, from the values (below) |
52//! | `battV` | [`Quantity::Voltage`]: [`FlightLog::battery_v`] | V, from its name, if every value lies within 0 to 20 V |
53//! | `altitudeM` | [`Quantity::AltitudeAboveGround`]: the primary track | m, from its name, checked against the pressure (below) |
54//! | `velocityMS` | [`Quantity::Speed`], up positive: [`FlightLog::vertical_speed_m_s`] | m/s, from its name, checked against the altitude (below) |
55//! | `accelerationMSS` | [`Quantity::Acceleration`] | m/s², from its name: the board's own estimate, along an axis the file doesn't state |
56//! | `unfiltAlt` | [`Quantity::AltitudeAboveGround`] | m, from the pressure (below); the zero is the board's, and not stated |
57//! | `flightState` | [`Quantity::Number`] | the board's state code, as written: no published source gives the codes' meanings |
58//! | `drogueCont`, `mainCont` | [`Quantity::Number`] | 0 or 1, as written: the pyro channels' continuity, by their names |
59//! | `drogueFired`, `mainFired` | [`Quantity::Number`] | 0 or 1, as written; each rise from 0 to 1 is an event (below) |
60//! | `tiltMagnitudeDeg` | [`Quantity::Angle`] | degrees, from its name, if every value lies within 0 to 180° |
61//! | `angularVelRadS_x`, `_y`, `_z` | [`Quantity::AngularRate`] | radians per second, from their names, if no value is beyond what a gyroscope measures (below) |
62//! | `quaternion_a` … `_d` | [`Quantity::Number`] | the parts of an attitude quaternion, which have no unit |
63//!
64//! A column whose values refute the unit its name states is kept as written,
65//! [`Quantity::Unrecognized`], with a note saying why; a column whose unit the values decide gets
66//! a note saying on what evidence. The checks:
67//!
68//! - *The pressure* is read in pascals if its first value lies within 50,000 to 110,000 Pa (the
69//!   bounds [`crate::rrc3`] argues for a pad's pressure). Every sample file's does.
70//! - *The temperatures.* An electronics bay's temperature lies within −40 to 60 °C, 233.15 to
71//!   333.15 K. `tempK` is read in kelvin, as its name says, if every value lies within that range;
72//!   `imuTemp`'s name states no unit, and it is read in kelvin on the same evidence: in degrees
73//!   Celsius or Fahrenheit the same values would be hotter than any bay survives. Otherwise each is
74//!   kept as written. In the space-separated sample `tempK` reads below zero, which no temperature
75//!   in kelvin can, and nothing in the file says in which unit it is; there and in the file with
76//!   its settings `imuTemp` is 0 at every sample, a placeholder rather than a reading.
77//! - *The pad's gravity.* A board at rest, or hanging under a parachute, reads 1 g: 9.806 65 in
78//!   m/s², 1 in standard gravities. The reader adds up the time the three axes' magnitude lies
79//!   within 10% of each of the two, every sample counting until the next, but for at most 5 s,
80//!   the board's longest regular step: past it the logging paused, and a sample says nothing of
81//!   the time after, so a coast sample before a jump of the clock can't count for minutes. The
82//!   unit whose 1 g lasts at least 1 s and at least twice as long as the other's is taken;
83//!   otherwise the axes are kept as written. In the board's sample logs the magnitude reads 9.8
84//!   for minutes on the pad and under the parachutes, against at most 1 s near 1 m/s² in the
85//!   coast; in the space-separated one it reads 1 for 46 s and never 9.8, so its axes are read in
86//!   g, × 9.806 65. One step in the sample logs passes 5.04 s, an 8 s one, and the limit changes
87//!   neither unit's time in any of them by as much as 0.05 s.
88//! - *The board's turning.* With the board at about 1 g (within 15%), the direction the
89//!   accelerometer reads is gravity's, so as the board turns, that direction turns by as much as
90//!   the gyroscope's rates across it say. Over stretches of 10 steps at most 0.05 s apart, the
91//!   reader adds up the angle between the accelerometer's direction at each stretch's ends and the
92//!   gyroscope's turn across that direction, |ω × â| dt, with ω read in radians per second. The
93//!   unit, radians or degrees per second, in which the gyroscope's turn lies within a quarter to 4
94//!   times the accelerometer's is taken, given at least 3 stretches and 0.2 rad of turning; as the
95//!   units are 57.3 times apart, at most one can be. Otherwise the gyroscope is kept as written.
96//!   Swinging under a parachute turns the accelerometer's direction without turning the board, so
97//!   the ratio often runs below 1: in radians per second it is 0.40 to 1.6 in the 11 of the board's
98//!   own logs with stretches to check, and in degrees per second 1.3 in the other two, whose rates
99//!   reach about 1,000; the 42-sample log, all on the pad, has none, and its gyroscope is kept as
100//!   written.
101//! - *`angularVelRadS_*`* are read in radians per second, as their names say, if no value's
102//!   magnitude passes 349 rad/s, the 20,000 °/s full scale of Analog Devices' ADXRS649, a
103//!   gyroscope made for very high rates (*ADXRS649* data sheet). In the file with its settings they
104//!   pass it, so they are kept as written.
105//! - *`altitudeM`* is checked against the pressure: from the first sample to the one of lowest
106//!   pressure, the climb in the U.S. Standard Atmosphere, 1976 ([`hpr_atmos::ussa76`]), against
107//!   the column's. Within 25%, meters are borne out; beyond, the file is refused
108//!   ([`LogError::Unit`]): the primary track has no unit to be read in. Under 10 m of climb, or
109//!   without a pressure in pascals, the check can't be made and a note says so. `unfiltAlt`,
110//!   whose name states no unit, is read in meters on the same check, and otherwise kept as
111//!   written.
112//! - *`velocityMS`* is checked against `altitudeM`: over the steps at most 0.05 s long, the least
113//!   squares slope of the altitude's change on the speed times the step must lie within 25% of 1;
114//!   a slope that can't be computed, as when the sums overflow, isn't within it.
115//!   This ties the clock, the speed and the altitude together: a speed in feet per second, or a
116//!   clock in seconds, would be 3.28 or 1,000 times off. Under 10 m of movement the check can't be
117//!   made and a note says so; a slope beyond is kept as written. In the sample files it is 0.86 to
118//!   1.08.
119//!
120//! **The primary track.** The record's altitude is `altitudeM`, the board's own altitude above its
121//! zero, the pad: in the sample files that start on the pad it reads within 2.1 m of zero at the
122//! first sample, but for the replayed file's 5 m. It is a filtered estimate, smoother than the
123//! pressure; `unfiltAlt`, the board's altitude before filtering, is on a zero the file doesn't
124//! state (in the board's logs
125//! within 150 m of the standard atmosphere's altitude of the pressure, in the space-separated file
126//! the same as `altitudeM`'s), so it isn't the track. The vertical speed is `velocityMS`, the
127//! temperature `tempK` and the battery `battV`, where they are read in their units. The track
128//! takes the samples in time order, the first at each time, leaving out any sample without a time;
129//! a note counts those put in order or left out, and the channels keep every one in the file's
130//! order. Where the altitude reads more than 100 m off zero at the track's first sample, as in the
131//! file after a restart in flight, a note says so: each of the two files is its own record.
132//!
133//! **Events.** Each time `drogueFired` or `mainFired` goes from 0 to 1 is an [`Event`] named by its
134//! column, at the sample's time, in time order: the names say the board fired that channel. A flag
135//! already 1 at its first sample is no event. `flightState` changes are no events: the codes'
136//! meanings aren't published.
137//!
138//! **The settings.** In a `CONFIG` line, `BOARD_NAME` names the logger and `FIRMWARE_VERSION` the
139//! firmware; the other settings are left out, counted in a note, as no source gives their units.
140//! Without a `BOARD_NAME` the logger is `AerospaceNU SillyGoose`.
141//!
142//! **Cells.** An empty cell, or one that isn't a number, is a gap (`NaN`), counted in a note. A
143//! value too large to hold once converted to its unit, such as an accelerometer's 10³⁰⁸ g in m/s²
144//! or a gyroscope's 10³⁰⁸ rad/s in °/s, is refused, naming its line and column
145//! ([ADR-258][adr-258] §3). A row with fewer cells than the header names has the rest as gaps,
146//! counted in a note; a row with more is refused, naming its line, as is a file whose rows hold
147//! under a quarter of the cells the header names (past the first 65,536), so that a short file
148//! can't make the reader store far more gaps than it writes cells. Lines may end in CR, LF or both, blank lines are skipped, and a byte-order
149//! mark is dropped.
150//!
151//! [adr-258]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0258-aerospacenus-board-and-a-phone-apps-csv-before-the-rest.md
152
153use std::collections::BTreeSet;
154use std::f64::consts::PI;
155
156use hpr_atmos::ussa76::Ussa76;
157use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
158
159use crate::error::LogError;
160use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
161use crate::table::{Notes, finite, number, numbered_lines, short};
162
163/// The format's name in messages.
164const FORMAT: &str = "SillyGoose text";
165
166/// The logger's name where the file states none.
167const LOGGER: &str = "AerospaceNU SillyGoose";
168
169/// The clock's name, the header's first.
170const CLOCK: &str = "timestampMs";
171
172/// The names a header must hold besides the clock to be recognized.
173const MARKS: [&str; 2] = ["pressurePa", "altitudeM"];
174
175/// The opening word of the settings line.
176const CONFIG: &str = "CONFIG";
177
178/// The step between two altitudes the format can tell apart near the ground, m
179/// ([`crate::log::LogFormat::altitude_resolution_m`]): the board writes `altitudeM` to the
180/// centimeter, and it steps by that, 0.01 m, near the ground in every one of the 12 board's logs
181/// among the project's sample logs (2026-10-13), as in the file with its settings. The
182/// space-separated file writes four decimals but steps by at least 0.08 m, its pressure being in
183/// whole pascals; the step the board's own layout writes is taken, so that a tolerance built on it
184/// stays tight.
185pub(crate) const ALTITUDE_STEP_M: f64 = 0.01;
186
187/// A pressure near the ground in pascals, the bounds [`crate::rrc3`] argues for a pad's.
188const PAD_PA: (f64, f64) = (50_000.0, 110_000.0);
189
190/// An electronics bay's temperatures, K: −40 to 60 °C, a winter launch to a bay in the desert sun.
191const BAY_K: (f64, f64) = (233.15, 333.15);
192
193/// The most a battery may read, V, to be read in volts: a board's battery is a few volts, and
194/// millivolts would be thousands.
195const VOLTS_MAX: f64 = 20.0;
196
197/// How far, as a share, the accelerometer's magnitude may lie from 1 g to count as reading it.
198const GRAVITY_MARGIN: f64 = 0.1;
199
200/// The least time, s, the file must read 1 g in a unit for that unit to be taken.
201const GRAVITY_LEAST_S: f64 = 1.0;
202
203/// How many times longer the taken unit's 1 g must last than the other's.
204const GRAVITY_LEAD: f64 = 2.0;
205
206/// The most time, s, one sample counts for in the pad's gravity: the board's longest regular step,
207/// one sample every 5 s on the pad. A longer step is a pause in the logging, and the sample before
208/// it says nothing of the time past those 5 s.
209const GRAVITY_STEP_MAX_S: f64 = 5.0;
210
211/// The most names a header may have: the board writes 20, or 28 with its settings.
212pub const MAX_COLUMNS: usize = 256;
213
214/// The longest step, s, of the board's fast logging that the turning and speed checks use: 10 ms
215/// or 20 ms in the sample files, where the pad's are 5 s.
216const FAST_STEP_S: f64 = 0.05;
217
218/// The steps a stretch of the turning check spans.
219const TURN_STEPS: usize = 10;
220
221/// How far, as a share, the accelerometer may read from 1 g in a stretch of the turning check.
222const TURN_GRAVITY_MARGIN: f64 = 0.15;
223
224/// The least the accelerometer's direction must turn, rad, over the stretches for the check to
225/// decide.
226const TURN_LEAST_RAD: f64 = 0.2;
227
228/// The fewest stretches for the turning check to decide.
229const TURN_LEAST_STRETCHES: usize = 3;
230
231/// How many times off, either way, the gyroscope's turn may be from the accelerometer's for a
232/// unit to be taken: degrees and radians are 57.3 times apart, so at most one unit is within it.
233const TURN_FACTOR: f64 = 4.0;
234
235/// The fastest rate a gyroscope measures, rad/s: 20,000 °/s, the full scale of Analog Devices'
236/// ADXRS649 (*ADXRS649* data sheet), a gyroscope made for very high rates.
237const RATE_MAX_RAD_S: f64 = 20_000.0 * PI / 180.0;
238
239/// The least climb, m, from which the pressure checks an altitude's unit: twice the 5 m of noise
240/// and drift a board's altitude has on the pad, and enough for meters and feet, 3.28 times apart,
241/// to be told apart within [`CLIMB_MARGIN`].
242const CHECK_CLIMB_M: f64 = 10.0;
243
244/// How far, as a share, an altitude's climb may be from the pressure's for meters to be borne
245/// out.
246const CLIMB_MARGIN: f64 = 0.25;
247
248/// How far the speed check's slope may lie from 1.
249const SPEED_MARGIN: f64 = 0.25;
250
251/// The least movement, m, the speed integrates over the fast steps for the speed check to decide.
252const SPEED_LEAST_M: f64 = 10.0;
253
254/// How far, m, the altitude may read from zero at the track's first sample before a note says the
255/// record doesn't start at the board's zero.
256const GROUND_OFF_M: f64 = 100.0;
257
258/// The least climb, m, over which a temperature that never changes gets a note.
259const STILL_CLIMB_M: f64 = 100.0;
260
261/// The most events a log keeps; past it, a note counts the rest.
262const MAX_EVENTS: usize = 1_000;
263
264/// What a column is.
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266enum Role {
267    Pressure,
268    /// `tempK`.
269    Temperature,
270    /// One axis of the accelerometer: 0 for x, 1 for y, 2 for z.
271    Accel(usize),
272    /// One axis of the gyroscope.
273    Gyro(usize),
274    /// `imuTemp`.
275    ImuTemperature,
276    Battery,
277    /// `altitudeM`.
278    Altitude,
279    /// `velocityMS`.
280    Speed,
281    /// `accelerationMSS`, the board's estimate.
282    Estimate,
283    /// `unfiltAlt`.
284    Unfiltered,
285    /// `flightState`.
286    State,
287    /// A pyro channel's continuity.
288    Continuity,
289    /// A pyro channel's fired flag: its rises are events.
290    Fired,
291    Tilt,
292    AngularVelocity,
293    Quaternion,
294    Unknown,
295}
296
297/// The names the reader knows, but the clock, and what each is.
298const KNOWN: [(&str, Role); 27] = [
299    ("pressurePa", Role::Pressure),
300    ("tempK", Role::Temperature),
301    ("accelX", Role::Accel(0)),
302    ("accelY", Role::Accel(1)),
303    ("accelZ", Role::Accel(2)),
304    ("gyroX", Role::Gyro(0)),
305    ("gyroY", Role::Gyro(1)),
306    ("gyroZ", Role::Gyro(2)),
307    ("imuTemp", Role::ImuTemperature),
308    ("battV", Role::Battery),
309    ("altitudeM", Role::Altitude),
310    ("velocityMS", Role::Speed),
311    ("accelerationMSS", Role::Estimate),
312    ("unfiltAlt", Role::Unfiltered),
313    ("flightState", Role::State),
314    ("drogueCont", Role::Continuity),
315    ("mainCont", Role::Continuity),
316    ("drogueFired", Role::Fired),
317    ("mainFired", Role::Fired),
318    ("tiltMagnitudeDeg", Role::Tilt),
319    ("angularVelRadS_x", Role::AngularVelocity),
320    ("angularVelRadS_y", Role::AngularVelocity),
321    ("angularVelRadS_z", Role::AngularVelocity),
322    ("quaternion_a", Role::Quaternion),
323    ("quaternion_b", Role::Quaternion),
324    ("quaternion_c", Role::Quaternion),
325    ("quaternion_d", Role::Quaternion),
326];
327
328/// What a column is, by its name, compared without regard to case.
329fn role_of(name: &str) -> Role {
330    KNOWN
331        .iter()
332        .find(|(known, _)| known.eq_ignore_ascii_case(name))
333        .map_or(Role::Unknown, |(_, role)| *role)
334}
335
336/// A line's cells: split at tabs, trimmed, if `tabs`; else at runs of spaces.
337fn cells(line: &str, tabs: bool) -> Box<dyn Iterator<Item = &str> + '_> {
338    if tabs {
339        Box::new(line.split('\t').map(str::trim))
340    } else {
341        Box::new(line.split_whitespace())
342    }
343}
344
345/// Whether a line, trimmed, is a header of this layout: `timestampMs` first, and [`MARKS`]. The
346/// walk stops once both are seen, and copies nothing.
347fn is_header(line: &str) -> bool {
348    let mut names = cells(line, line.contains('\t'));
349    if !names
350        .next()
351        .is_some_and(|first| first.eq_ignore_ascii_case(CLOCK))
352    {
353        return false;
354    }
355    let mut seen = [false; MARKS.len()];
356    for name in names {
357        for (mark, seen) in MARKS.iter().zip(&mut seen) {
358            *seen |= name.eq_ignore_ascii_case(mark);
359        }
360        if seen.iter().all(|seen| *seen) {
361            return true;
362        }
363    }
364    false
365}
366
367/// Whether a line, trimmed, is the settings line: `CONFIG`, then its settings.
368fn is_config(line: &str) -> bool {
369    cells(line, line.contains('\t')).next() == Some(CONFIG)
370}
371
372/// Whether the text is this layout: its first line that isn't blank is a header (module docs), or
373/// a `CONFIG` line with a header after it.
374pub fn recognizes(text: &str) -> bool {
375    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
376    let mut lines = text
377        .split(['\r', '\n'])
378        .map(str::trim)
379        .filter(|line| !line.is_empty());
380    match lines.next() {
381        Some(first) if is_config(first) => lines.next().is_some_and(is_header),
382        Some(first) => is_header(first),
383        None => false,
384    }
385}
386
387/// One data column.
388struct Column {
389    name: String,
390    role: Role,
391    /// The values as written, `NaN` for a gap.
392    values: Vec<f64>,
393    /// What the column is read as.
394    quantity: Quantity,
395    /// The factor from the values as written to the quantity's unit.
396    scale: f64,
397}
398
399impl Column {
400    /// The column, read as its role's quantity in its name's unit until a check decides otherwise.
401    fn new(name: &str) -> Self {
402        let role = role_of(name);
403        let (quantity, scale) = match role {
404            Role::Pressure => (Quantity::Pressure, 1.0),
405            Role::Temperature | Role::ImuTemperature => (Quantity::Temperature, 1.0),
406            Role::Accel(_) | Role::Estimate => (Quantity::Acceleration, 1.0),
407            Role::Gyro(_) => (Quantity::AngularRate, 1.0),
408            Role::AngularVelocity => (Quantity::AngularRate, 180.0 / PI),
409            Role::Battery => (Quantity::Voltage, 1.0),
410            Role::Altitude | Role::Unfiltered => (Quantity::AltitudeAboveGround, 1.0),
411            Role::Speed => (Quantity::Speed, 1.0),
412            Role::Tilt => (Quantity::Angle, 1.0),
413            Role::State | Role::Continuity | Role::Fired | Role::Quaternion => {
414                (Quantity::Number, 1.0)
415            }
416            Role::Unknown => (Quantity::Unrecognized, 1.0),
417        };
418        Self {
419            name: name.to_owned(),
420            role,
421            values: Vec::new(),
422            quantity,
423            scale,
424        }
425    }
426
427    /// Keeps the column as written.
428    fn keep(&mut self) {
429        self.quantity = Quantity::Unrecognized;
430        self.scale = 1.0;
431    }
432
433    /// The column's name, cut short, in backticks.
434    fn quoted(&self) -> String {
435        format!("`{}`", short(&self.name))
436    }
437
438    /// The lowest and highest of the values, if any is a number.
439    fn range(&self) -> Option<(f64, f64)> {
440        let mut finite = self.values.iter().copied().filter(|v| v.is_finite());
441        let first = finite.next()?;
442        Some(finite.fold((first, first), |(lo, hi), v| (lo.min(v), hi.max(v))))
443    }
444}
445
446/// Reads a SillyGoose log from its text.
447///
448/// # Errors
449///
450/// [`LogError::NotThisFormat`] if the first line that isn't blank, or the one after a `CONFIG`
451/// line, isn't this layout's header; [`LogError::Syntax`] for a header with an empty name or a
452/// name given twice, a row with more cells than the header names, a file whose rows hold too
453/// few of the cells its header names, or a value its unit's conversion makes too large for an
454/// `f64`; [`LogError::NoData`] if no row has a time;
455/// [`LogError::Unit`] if `altitudeM`'s climb is more than 25% off the pressure's (module docs).
456pub fn read(text: &str) -> Result<FlightLog, LogError> {
457    let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
458    let Some(first) = lines.next() else {
459        return Err(not_this("the file is empty".to_owned()));
460    };
461    let (config, (header_line, header)) = if is_config(first.1.trim()) {
462        let Some(next) = lines.next() else {
463            return Err(not_this(
464                "the file holds a `CONFIG` line and nothing after it".to_owned(),
465            ));
466        };
467        (Some(first.1.trim()), next)
468    } else {
469        (None, first)
470    };
471    let header = header.trim();
472    if !is_header(header) {
473        return Err(not_this(format!(
474            "its header, {:?}, isn't a SillyGoose log's: `timestampMs` first, then names such as \
475             `pressurePa` and `altitudeM`",
476            short(header)
477        )));
478    }
479    let tabs = header.contains('\t');
480
481    let mut columns: Vec<Column> = Vec::new();
482    let mut seen: BTreeSet<String> = BTreeSet::new();
483    for (index, name) in cells(header, tabs).enumerate() {
484        if index >= MAX_COLUMNS {
485            return Err(syntax(
486                header_line,
487                format!("the header names more than {MAX_COLUMNS} columns"),
488            ));
489        }
490        if name.is_empty() {
491            return Err(syntax(
492                header_line,
493                format!("the header's column {} has no name", index + 1),
494            ));
495        }
496        if !seen.insert(name.to_ascii_lowercase()) {
497            return Err(syntax(
498                header_line,
499                format!("the header names {:?} twice", short(name)),
500            ));
501        }
502        if index > 0 {
503            columns.push(Column::new(name));
504        }
505    }
506    let width = columns.len() + 1;
507
508    let mut times: Vec<f64> = Vec::new();
509    // Each row's line in the file, for a refusal that names it.
510    let mut row_lines: Vec<usize> = Vec::new();
511    let mut gaps = 0usize;
512    let mut first_gap = None;
513    let mut short_rows = 0usize;
514    let mut first_short = None;
515    let mut cells_written = 0usize;
516    for (number_of_line, line) in lines {
517        // One more than the header names, so that a wider row is told apart without collecting
518        // the whole of a long line.
519        let row: Vec<&str> = cells(line.trim_end(), tabs).take(width + 1).collect();
520        if row.len() > width {
521            return Err(syntax(
522                number_of_line,
523                format!("the row has more than {width} cells, where the header names {width}"),
524            ));
525        }
526        if row.len() < width {
527            short_rows += 1;
528            first_short.get_or_insert(number_of_line);
529        }
530        cells_written = cells_written.saturating_add(row.len());
531        let mut value_at = |index: usize| match row.get(index) {
532            Some(cell) => number(cell, false).unwrap_or_else(|| {
533                gaps += 1;
534                first_gap.get_or_insert(number_of_line);
535                f64::NAN
536            }),
537            None => f64::NAN,
538        };
539        times.push(value_at(0) / 1_000.0);
540        row_lines.push(number_of_line);
541        for (index, column) in columns.iter_mut().enumerate() {
542            column.values.push(value_at(index + 1));
543        }
544        if crate::log::too_sparse(width, times.len(), cells_written) {
545            return Err(syntax(
546                number_of_line,
547                format!(
548                    "{} rows hold {cells_written} of the {} cells the header's {width} columns \
549                     name: too few for the header to be this file's",
550                    times.len(),
551                    times.len().saturating_mul(width)
552                ),
553            ));
554        }
555    }
556    if !times.iter().any(|time| time.is_finite()) {
557        return Err(LogError::NoData { format: FORMAT });
558    }
559    let Some(primary) = columns.iter().position(|c| c.role == Role::Altitude) else {
560        // Invariant: the header was recognized, so it names `altitudeM`.
561        return Err(syntax(
562            header_line,
563            "the file has no `altitudeM`".to_owned(),
564        ));
565    };
566
567    let mut decisions: Vec<String> = Vec::new();
568    let pressure_pa = decide_pressure(&mut columns, &mut decisions);
569    decide_temperatures(&mut columns, &mut decisions);
570    let gravity = decide_accelerometer(&mut columns, &times, &mut decisions);
571    decide_gyroscope(&mut columns, &times, gravity, &mut decisions);
572    decide_by_range(&mut columns, &mut decisions);
573    decide_altitudes(&mut columns, pressure_pa, header_line, &mut decisions)?;
574    decide_speed(&mut columns, &times, &mut decisions);
575    // Kept few, as a header may name many columns the reader doesn't know.
576    let mut unknown_notes = Notes::default();
577    for column in &columns {
578        if column.role == Role::Unknown {
579            unknown_notes.push(format!(
580                "the column {} isn't one this reader knows; its values are kept as written",
581                column.quoted()
582            ));
583        }
584    }
585    decisions.extend(unknown_notes.into_vec());
586
587    let (logger, firmware, config_note) = settings(config);
588
589    // Every channel, in its unit. A value that its factor makes infinite, such as 10³⁰⁸ g in
590    // m/s², is refused on its row's line (ADR-258 §3).
591    let mut channels: Vec<Channel> = Vec::with_capacity(columns.len());
592    for column in &columns {
593        let mut values = Vec::with_capacity(column.values.len());
594        for (line, value) in row_lines.iter().zip(&column.values) {
595            values.push(finite(value * column.scale, FORMAT, *line, &column.name)?);
596        }
597        channels.push(Channel {
598            column: column.name.clone(),
599            quantity: column.quantity,
600            time_s: times.clone(),
601            values,
602        });
603    }
604
605    // The events: the fired flags' rises.
606    let mut events = Vec::new();
607    let mut events_left_out = 0usize;
608    for column in columns.iter().filter(|c| c.role == Role::Fired) {
609        let mut before: Option<f64> = None;
610        for (value, time) in column.values.iter().zip(&times) {
611            if !value.is_finite() {
612                continue;
613            }
614            if before == Some(0.0) && *value == 1.0 && time.is_finite() {
615                if events.len() < MAX_EVENTS {
616                    events.push(Event {
617                        time_s: *time,
618                        name: column.name.clone(),
619                    });
620                } else {
621                    events_left_out += 1;
622                }
623            }
624            before = Some(*value);
625        }
626    }
627    events.sort_by(|a, b| a.time_s.total_cmp(&b.time_s));
628
629    // The primary track: the samples in time order, the first at each time.
630    let mut order: Vec<usize> = (0..times.len()).filter(|&i| times[i].is_finite()).collect();
631    let untimed = times.len() - order.len();
632    let backwards = order
633        .windows(2)
634        .filter(|pair| times[pair[1]] < times[pair[0]])
635        .count();
636    order.sort_by(|&a, &b| times[a].total_cmp(&times[b]));
637    let before = order.len();
638    order.dedup_by(|later, earlier| times[*later] == times[*earlier]);
639    let repeats = before - order.len();
640    let on_track = |index: usize| -> Vec<f64> {
641        order
642            .iter()
643            .map(|&row| channels[index].values[row])
644            .collect()
645    };
646    let time_s: Vec<f64> = order.iter().map(|&row| times[row]).collect();
647    let altitude_m = on_track(primary);
648    let track_of = |role: Role, quantity: Quantity| {
649        columns
650            .iter()
651            .position(|c| c.role == role && c.quantity == quantity)
652            .map(on_track)
653    };
654    let vertical_speed_m_s = track_of(Role::Speed, Quantity::Speed);
655    let temperature_k = track_of(Role::Temperature, Quantity::Temperature);
656    let battery_v = track_of(Role::Battery, Quantity::Voltage);
657
658    let mut notes = decisions;
659    notes.extend(config_note);
660    if backwards > 0 || repeats > 0 || untimed > 0 {
661        notes.push(format!(
662            "the clock goes back {backwards} times and repeats a time {repeats} times, and \
663             {untimed} samples have no time. The record's track takes the samples in time order, \
664             the first at each time, and leaves out those without one. The channels keep them all"
665        ));
666    }
667    if let Some(ground) = altitude_m.iter().copied().find(|v| v.is_finite())
668        && ground.abs() > GROUND_OFF_M
669    {
670        notes.push(format!(
671            "`{}` reads {ground:.2} m at the track's first sample, not near zero. The record \
672             starts away from the board's zero, as a log after a restart in flight does",
673            short(&columns[primary].name)
674        ));
675    }
676    notes.extend(still_temperature(&columns, primary));
677    let mut line_notes = Notes::default();
678    if gaps > 0 {
679        line_notes.push(format!(
680            "{gaps} cells, the first on line {}, are empty or not numbers: each is a gap",
681            first_gap.unwrap_or(header_line)
682        ));
683    }
684    if short_rows > 0 {
685        line_notes.push(format!(
686            "{short_rows} rows, the first on line {}, hold fewer cells than the header names: the \
687             cells they leave out are gaps",
688            first_short.unwrap_or(header_line)
689        ));
690    }
691    if events_left_out > 0 {
692        line_notes.push(format!(
693            "and {events_left_out} more rises of the fired flags, left out of the events so that \
694             the list stays short"
695        ));
696    }
697    notes.extend(line_notes.into_vec());
698
699    Ok(FlightLog {
700        format: LogFormat::SillyGooseText,
701        logger,
702        serial_number: None,
703        firmware,
704        flight_number: None,
705        stated: Stated::default(),
706        time_s,
707        altitude_m,
708        vertical_speed_m_s,
709        temperature_k,
710        battery_v,
711        channels,
712        events,
713        notes,
714    })
715}
716
717/// The column with a role, if the file has it.
718fn find(columns: &[Column], role: Role) -> Option<usize> {
719    columns.iter().position(|c| c.role == role)
720}
721
722/// Reads the pressure in pascals if its first value is a pressure near the ground in them; whether
723/// it is.
724fn decide_pressure(columns: &mut [Column], decisions: &mut Vec<String>) -> bool {
725    let Some(at) = find(columns, Role::Pressure) else {
726        return false;
727    };
728    let column = &mut columns[at];
729    match column.values.iter().copied().find(|v| v.is_finite()) {
730        Some(first) if (PAD_PA.0..=PAD_PA.1).contains(&first) => true,
731        first => {
732            let why = first.map_or_else(
733                || "it holds no number".to_owned(),
734                |first| {
735                    format!(
736                        "its first value, {first}, is no pressure near the ground in them \
737                         (50,000 to 110,000 Pa)"
738                    )
739                },
740            );
741            decisions.push(format!(
742                "{} kept as written: its name says pascals, but {why}",
743                column.quoted()
744            ));
745            column.keep();
746            false
747        }
748    }
749}
750
751/// Whether every value of a column is a temperature an electronics bay can have in kelvin, and at
752/// least one is a number.
753fn bay_kelvin(column: &Column) -> bool {
754    column
755        .range()
756        .is_some_and(|(lo, hi)| lo >= BAY_K.0 && hi <= BAY_K.1)
757}
758
759/// Why a column's values aren't a bay's temperatures in kelvin.
760fn not_kelvin(column: &Column) -> String {
761    match column.range() {
762        None => "it holds no number".to_owned(),
763        Some((lo, hi)) if lo == 0.0 && hi == 0.0 => {
764            "every value is exactly 0, no temperature in kelvin, and a placeholder rather than a \
765             reading in any unit"
766                .to_owned()
767        }
768        Some((lo, hi)) => format!(
769            "its values run from {lo} to {hi}, outside the 233.15 to 333.15 K (−40 to 60 °C) an \
770             electronics bay can have{}",
771            if lo < 0.0 {
772                ", and below 0 no temperature in kelvin can be"
773            } else {
774                ""
775            }
776        ),
777    }
778}
779
780/// Reads `tempK` in kelvin, as its name says, and `imuTemp`, by its values, if they are a bay's;
781/// otherwise keeps each as written.
782fn decide_temperatures(columns: &mut [Column], decisions: &mut Vec<String>) {
783    for column in columns.iter_mut() {
784        match column.role {
785            Role::Temperature if !bay_kelvin(column) => {
786                decisions.push(format!(
787                    "{} kept as written: its name says kelvin, but {}; nothing in the file says \
788                     which unit it is in",
789                    column.quoted(),
790                    not_kelvin(column)
791                ));
792                column.keep();
793            }
794            Role::ImuTemperature => {
795                if let (true, Some((lo, hi))) = (bay_kelvin(column), column.range()) {
796                    decisions.push(format!(
797                        "{} read in kelvin, from the values: they run from {lo} to {hi}. That is within \
798                         the 233.15 to 333.15 K an electronics bay can have. In degrees \
799                         Celsius or Fahrenheit they would be hotter than any bay survives",
800                        column.quoted()
801                    ));
802                } else {
803                    decisions.push(format!(
804                        "{} kept as written: its name states no unit, and {}",
805                        column.quoted(),
806                        not_kelvin(column)
807                    ));
808                    column.keep();
809                }
810            }
811            _ => {}
812        }
813    }
814}
815
816/// The three axes of a sensor, by role, if the file has all three.
817fn axes(columns: &[Column], role: fn(usize) -> Role) -> Option<[usize; 3]> {
818    Some([
819        find(columns, role(0))?,
820        find(columns, role(1))?,
821        find(columns, role(2))?,
822    ])
823}
824
825/// A sample of three axes, as written.
826fn vector(columns: &[Column], axes: [usize; 3], row: usize) -> [f64; 3] {
827    axes.map(|at| columns[at].values[row])
828}
829
830fn magnitude(v: [f64; 3]) -> f64 {
831    (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
832}
833
834/// The names of the columns at some places, as a sentence.
835fn listed_at(columns: &[Column], at: &[usize]) -> String {
836    let quoted: Vec<String> = at.iter().map(|&i| columns[i].quoted()).collect();
837    match quoted.as_slice() {
838        [] => String::new(),
839        [one] => one.clone(),
840        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
841    }
842}
843
844/// Decides the accelerometer's unit from the pad's gravity (module docs): the value 1 g reads as,
845/// 9.806 65 or 1, if decided.
846fn decide_accelerometer(
847    columns: &mut [Column],
848    times: &[f64],
849    decisions: &mut Vec<String>,
850) -> Option<f64> {
851    let axes = axes(columns, Role::Accel)?;
852    let mut in_ms2 = 0.0;
853    let mut in_g = 0.0;
854    for row in 0..times.len().saturating_sub(1) {
855        let step = times[row + 1] - times[row];
856        let reading = magnitude(vector(columns, axes, row));
857        if !(step > 0.0 && step.is_finite() && reading.is_finite()) {
858            continue;
859        }
860        let weight = step.min(GRAVITY_STEP_MAX_S);
861        if (reading - STANDARD_GRAVITY_MPS2).abs() <= GRAVITY_MARGIN * STANDARD_GRAVITY_MPS2 {
862            in_ms2 += weight;
863        }
864        if (reading - 1.0).abs() <= GRAVITY_MARGIN {
865            in_g += weight;
866        }
867    }
868    let names = listed_at(columns, &axes);
869    let evidence = format!(
870        "the three axes' magnitude reads within 10% of 9.806 65 for {in_ms2:.1} s of the file's \
871         time. It reads within 10% of 1 for {in_g:.1} s. A board at rest or under a parachute \
872         reads 1 g. The unit whose 1 g lasts at least 1 s and twice as long as the other's is \
873         taken"
874    );
875    let decided = if in_ms2 >= GRAVITY_LEAST_S && in_ms2 >= GRAVITY_LEAD * in_g {
876        decisions.push(format!(
877            "{names} read in meters per second squared, from the pad's gravity: {evidence}"
878        ));
879        Some((STANDARD_GRAVITY_MPS2, 1.0))
880    } else if in_g >= GRAVITY_LEAST_S && in_g >= GRAVITY_LEAD * in_ms2 {
881        decisions.push(format!(
882            "{names} read in standard gravities, × 9.806 65 m/s², from the pad's gravity: \
883             {evidence}"
884        ));
885        Some((1.0, STANDARD_GRAVITY_MPS2))
886    } else {
887        decisions.push(format!(
888            "{names} kept as written: the pad's gravity doesn't settle their unit: {evidence}"
889        ));
890        None
891    };
892    for at in axes {
893        match decided {
894            Some((_, scale)) => columns[at].scale = scale,
895            None => columns[at].keep(),
896        }
897    }
898    decided.map(|(one_g, _)| one_g)
899}
900
901/// What the turning check found.
902#[derive(Debug, Clone, Copy, PartialEq)]
903struct Turning {
904    /// The stretches it used.
905    stretches: usize,
906    /// The accelerometer's direction's turn over them, rad.
907    accelerometer_rad: f64,
908    /// The gyroscope's turn across that direction, its rates read in rad/s, rad.
909    gyroscope_rad: f64,
910}
911
912/// The turning check (module docs): over stretches of [`TURN_STEPS`] fast steps where the
913/// accelerometer reads about `one_g`, the accelerometer's direction's turn and the gyroscope's.
914fn turning(
915    columns: &[Column],
916    times: &[f64],
917    accel: [usize; 3],
918    gyro: [usize; 3],
919    one_g: f64,
920) -> Turning {
921    let mut found = Turning {
922        stretches: 0,
923        accelerometer_rad: 0.0,
924        gyroscope_rad: 0.0,
925    };
926    let near_g = |row: usize| {
927        let reading = magnitude(vector(columns, accel, row));
928        reading.is_finite() && (reading - one_g).abs() <= TURN_GRAVITY_MARGIN * one_g
929    };
930    let fast = |row: usize| {
931        let step = times[row + 1] - times[row];
932        step > 0.0
933            && step <= FAST_STEP_S
934            && vector(columns, gyro, row).iter().all(|v| v.is_finite())
935    };
936    let direction = |row: usize| {
937        let a = vector(columns, accel, row);
938        let m = magnitude(a);
939        a.map(|v| v / m)
940    };
941    let mut start = 0;
942    while start + TURN_STEPS < times.len() {
943        let end = start + TURN_STEPS;
944        if !((start..end).all(fast) && (start..=end).all(near_g)) {
945            start += 1;
946            continue;
947        }
948        let (from, to) = (direction(start), direction(end));
949        let cosine = (from[0] * to[0] + from[1] * to[1] + from[2] * to[2]).clamp(-1.0, 1.0);
950        let mut gyroscope = 0.0;
951        for row in start..end {
952            let w = vector(columns, gyro, row);
953            let a = direction(row);
954            let across = [
955                w[1] * a[2] - w[2] * a[1],
956                w[2] * a[0] - w[0] * a[2],
957                w[0] * a[1] - w[1] * a[0],
958            ];
959            gyroscope += magnitude(across) * (times[row + 1] - times[row]);
960        }
961        found.stretches += 1;
962        found.accelerometer_rad += cosine.acos();
963        found.gyroscope_rad += gyroscope;
964        start = end;
965    }
966    found
967}
968
969/// Decides the gyroscope's unit from the board's turning (module docs).
970fn decide_gyroscope(
971    columns: &mut [Column],
972    times: &[f64],
973    one_g: Option<f64>,
974    decisions: &mut Vec<String>,
975) {
976    let Some(gyro) = axes(columns, Role::Gyro) else {
977        return;
978    };
979    let names = listed_at(columns, &gyro);
980    let accel = axes(columns, Role::Accel);
981    let (Some(accel), Some(one_g)) = (accel, one_g) else {
982        decisions.push(format!(
983            "{names} kept as written: their unit is decided from the accelerometer's gravity as \
984             the board turns. The file has no accelerometer read in a known unit"
985        ));
986        for at in gyro {
987            columns[at].keep();
988        }
989        return;
990    };
991    let found = turning(columns, times, accel, gyro, one_g);
992    let ratio = found.gyroscope_rad / found.accelerometer_rad;
993    let degrees = PI / 180.0;
994    let evidence = format!(
995        "over {} stretches of {TURN_STEPS} steps at most {FAST_STEP_S} s apart with the \
996         accelerometer within 15% of 1 g, its direction turns {:.3} rad. A board at rest or \
997         under a parachute reads so. Over the same stretches, the gyroscope's rates turn the \
998         board across that direction {:.3} rad read in radians per second, {:.3} rad read in \
999         degrees",
1000        found.stretches,
1001        found.accelerometer_rad,
1002        found.gyroscope_rad,
1003        found.gyroscope_rad * degrees
1004    );
1005    let within = |ratio: f64| (1.0 / TURN_FACTOR..=TURN_FACTOR).contains(&ratio);
1006    let enough =
1007        found.stretches >= TURN_LEAST_STRETCHES && found.accelerometer_rad >= TURN_LEAST_RAD;
1008    let scale = if enough && within(ratio) {
1009        decisions.push(format!(
1010            "{names} read in radians per second, from the board's turning: {evidence}. The unit \
1011             whose turn is within a quarter to 4 times the accelerometer's is taken"
1012        ));
1013        Some(180.0 / PI)
1014    } else if enough && within(ratio * degrees) {
1015        decisions.push(format!(
1016            "{names} read in degrees per second, from the board's turning: {evidence}. The unit \
1017             whose turn is within a quarter to 4 times the accelerometer's is taken"
1018        ));
1019        Some(1.0)
1020    } else {
1021        let why = if enough {
1022            "in neither unit is the gyroscope's turn within a quarter to 4 times the \
1023             accelerometer's"
1024        } else {
1025            "too little turning to tell, under 3 stretches or 0.2 rad"
1026        };
1027        decisions.push(format!(
1028            "{names} kept as written: the board's turning doesn't settle their unit, {why}: \
1029             {evidence}"
1030        ));
1031        None
1032    };
1033    for at in gyro {
1034        match scale {
1035            Some(scale) => columns[at].scale = scale,
1036            None => columns[at].keep(),
1037        }
1038    }
1039}
1040
1041/// Checks the battery's, the tilt's and the angular velocities' values against their names' units,
1042/// keeping as written a column they refute.
1043fn decide_by_range(columns: &mut [Column], decisions: &mut Vec<String>) {
1044    let mut rates = Vec::new();
1045    let mut rates_beyond = None;
1046    for (at, column) in columns.iter_mut().enumerate() {
1047        let range = column.range();
1048        match column.role {
1049            Role::Battery => {
1050                if let Some((lo, hi)) = range.filter(|(lo, hi)| *lo < 0.0 || *hi > VOLTS_MAX) {
1051                    decisions.push(format!(
1052                        "{} kept as written: its name says volts, but its values run from {lo} \
1053                         to {hi}. That is outside the 0 to 20 V a board's battery reads",
1054                        column.quoted()
1055                    ));
1056                    column.keep();
1057                }
1058            }
1059            Role::Tilt => {
1060                if let Some((lo, hi)) = range.filter(|(lo, hi)| *lo < 0.0 || *hi > 180.0) {
1061                    decisions.push(format!(
1062                        "{} kept as written: its name says degrees, but its values run from {lo} \
1063                         to {hi}, where a tilt's size lies within 0 to 180°",
1064                        column.quoted()
1065                    ));
1066                    column.keep();
1067                }
1068            }
1069            Role::AngularVelocity => {
1070                rates.push(at);
1071                if let Some((lo, hi)) = range {
1072                    let largest = lo.abs().max(hi.abs());
1073                    if largest > RATE_MAX_RAD_S {
1074                        rates_beyond = Some(rates_beyond.map_or(largest, |l: f64| l.max(largest)));
1075                    }
1076                }
1077            }
1078            _ => {}
1079        }
1080    }
1081    if let Some(largest) = rates_beyond {
1082        decisions.push(format!(
1083            "{} kept as written: their names say radians per second, but they reach {largest}. \
1084             That is beyond the 20,000 °/s (349 rad/s) full scale of Analog Devices' ADXRS649. \
1085             That gyroscope is made for very high rates",
1086            listed_at(columns, &rates)
1087        ));
1088        for at in rates {
1089            columns[at].keep();
1090        }
1091    }
1092}
1093
1094/// What the altitude check found for a column.
1095#[derive(Debug, Clone, Copy, PartialEq)]
1096enum Climb {
1097    /// The pressure climbs too little, or has no unit, to check by; the climb, if any.
1098    Unchecked(Option<f64>),
1099    /// The pressure's climb in the standard atmosphere, m, and the column's, as written.
1100    Checked { pressure_m: f64, column: f64 },
1101}
1102
1103/// The altitude check (module docs): from the first sample to the one of lowest pressure, the
1104/// pressure's climb in the standard atmosphere and the column's.
1105fn climb(columns: &[Column], pressure: Option<usize>, altitude: usize) -> Climb {
1106    let Some(pressure) = pressure else {
1107        return Climb::Unchecked(None);
1108    };
1109    let pairs = columns[pressure]
1110        .values
1111        .iter()
1112        .zip(&columns[altitude].values)
1113        .filter(|(p, a)| p.is_finite() && **p > 0.0 && a.is_finite());
1114    let mut first = None;
1115    let mut lowest: Option<(f64, f64)> = None;
1116    for (p, a) in pairs {
1117        first.get_or_insert((*p, *a));
1118        if lowest.is_none_or(|(low, _)| *p < low) {
1119            lowest = Some((*p, *a));
1120        }
1121    }
1122    let (Some(first), Some(lowest)) = (first, lowest) else {
1123        return Climb::Unchecked(None);
1124    };
1125    let atmosphere = Ussa76::standard();
1126    let Ok(pressure_m) = atmosphere
1127        .pressure_altitude_m(lowest.0)
1128        .and_then(|low| atmosphere.pressure_altitude_m(first.0).map(|pad| low - pad))
1129    else {
1130        return Climb::Unchecked(None);
1131    };
1132    if pressure_m < CHECK_CLIMB_M {
1133        return Climb::Unchecked(Some(pressure_m));
1134    }
1135    Climb::Checked {
1136        pressure_m,
1137        column: lowest.1 - first.1,
1138    }
1139}
1140
1141/// Checks `altitudeM` against the pressure, refusing the file if its climb is off, and reads
1142/// `unfiltAlt` in meters if the pressure bears them out.
1143fn decide_altitudes(
1144    columns: &mut [Column],
1145    pressure_pa: bool,
1146    header_line: usize,
1147    decisions: &mut Vec<String>,
1148) -> Result<(), LogError> {
1149    let pressure = find(columns, Role::Pressure).filter(|_| pressure_pa);
1150    let within = |pressure_m: f64, column: f64| (column / pressure_m - 1.0).abs() <= CLIMB_MARGIN;
1151    let unchecked = |climb: Option<f64>| match climb {
1152        Some(climb) => format!(
1153            "the pressure climbs {climb:.2} m in the standard atmosphere, under the \
1154             {CHECK_CLIMB_M} m from which it checks an altitude's unit"
1155        ),
1156        None => "the file has no pressure in pascals to check it by".to_owned(),
1157    };
1158    if let Some(at) = find(columns, Role::Altitude) {
1159        match climb(columns, pressure, at) {
1160            Climb::Checked { pressure_m, column } if !within(pressure_m, column) => {
1161                return Err(LogError::Unit {
1162                    format: FORMAT,
1163                    line: header_line,
1164                    message: format!(
1165                        "{} climbs {column:.1} from the first sample to the one of lowest \
1166                         pressure. The pressure's climb in the standard atmosphere is \
1167                         {pressure_m:.1} m. The column's name says meters, but the two aren't within 25%",
1168                        columns[at].quoted()
1169                    ),
1170                });
1171            }
1172            Climb::Checked { .. } => {}
1173            Climb::Unchecked(climb) => decisions.push(format!(
1174                "{} read in meters, from its name: {}",
1175                columns[at].quoted(),
1176                unchecked(climb)
1177            )),
1178        }
1179    }
1180    if let Some(at) = find(columns, Role::Unfiltered) {
1181        match climb(columns, pressure, at) {
1182            Climb::Checked { pressure_m, column } if within(pressure_m, column) => {
1183                decisions.push(format!(
1184                    "{} read in meters, from the pressure: from the first sample to the one of \
1185                     lowest pressure it climbs {column:.1}. The standard atmosphere climbs \
1186                     {pressure_m:.1} m, and the two are within 25%",
1187                    columns[at].quoted()
1188                ));
1189            }
1190            Climb::Checked { pressure_m, column } => {
1191                decisions.push(format!(
1192                    "{} kept as written: from the first sample to the one of lowest pressure it \
1193                     climbs {column:.1}. The standard atmosphere climbs {pressure_m:.1} m, and \
1194                     the two aren't within 25%",
1195                    columns[at].quoted()
1196                ));
1197                columns[at].keep();
1198            }
1199            Climb::Unchecked(climb) => {
1200                decisions.push(format!(
1201                    "{} kept as written: its name states no unit, and {}",
1202                    columns[at].quoted(),
1203                    unchecked(climb)
1204                ));
1205                columns[at].keep();
1206            }
1207        }
1208    }
1209    Ok(())
1210}
1211
1212/// Checks `velocityMS` against `altitudeM` (module docs), keeping it as written if the slope is
1213/// off.
1214fn decide_speed(columns: &mut [Column], times: &[f64], decisions: &mut Vec<String>) {
1215    let (Some(speed), Some(altitude)) = (find(columns, Role::Speed), find(columns, Role::Altitude))
1216    else {
1217        return;
1218    };
1219    let v = &columns[speed].values;
1220    let z = &columns[altitude].values;
1221    let (mut cross, mut square, mut moved) = (0.0, 0.0, 0.0);
1222    for row in 0..times.len().saturating_sub(1) {
1223        let step = times[row + 1] - times[row];
1224        let traveled = 0.5 * (v[row] + v[row + 1]) * step;
1225        let risen = z[row + 1] - z[row];
1226        if !(step > 0.0 && step <= FAST_STEP_S && traveled.is_finite() && risen.is_finite()) {
1227            continue;
1228        }
1229        cross += traveled * risen;
1230        square += traveled * traveled;
1231        moved += traveled.abs();
1232    }
1233    let name = columns[speed].quoted();
1234    if moved < SPEED_LEAST_M {
1235        decisions.push(format!(
1236            "{name} read in meters per second, from its name: over the steps at most \
1237             {FAST_STEP_S} s long it moves {moved:.1} m. That is under the {SPEED_LEAST_M} m from which \
1238             the altitude checks it"
1239        ));
1240        return;
1241    }
1242    let slope = cross / square;
1243    // Written to fail closed: a slope that is `NaN`, as when the sums overflow, isn't within it.
1244    let within = (slope - 1.0).abs() <= SPEED_MARGIN;
1245    if !within {
1246        let found = if slope.is_finite() {
1247            format!("the altitude changes {slope:.3} times what it integrates to")
1248        } else {
1249            "the slope of the altitude's change on what it integrates to can't be computed, the \
1250             sums being too large to hold"
1251                .to_owned()
1252        };
1253        decisions.push(format!(
1254            "{name} kept as written: its name says meters per second, but over the steps at most \
1255             {FAST_STEP_S} s long {found}, not within 25% of once"
1256        ));
1257        columns[speed].keep();
1258    }
1259}
1260
1261/// A note if `tempK`, read in kelvin, holds one value at every sample while the altitude climbs
1262/// more than [`STILL_CLIMB_M`].
1263fn still_temperature(columns: &[Column], primary: usize) -> Option<String> {
1264    let at = find(columns, Role::Temperature)?;
1265    let column = &columns[at];
1266    if column.quantity != Quantity::Temperature {
1267        return None;
1268    }
1269    let (lo, hi) = column.range()?;
1270    let samples = column.values.iter().filter(|v| v.is_finite()).count();
1271    let (low, high) = columns[primary].range()?;
1272    (lo == hi && samples >= 2 && high - low > STILL_CLIMB_M).then(|| {
1273        format!(
1274            "{} reads {lo} at every one of its {samples} samples while the altitude spans \
1275             {:.0} m. A board's sensor warms or cools in flight. So the file may be a replay of \
1276             recorded or made-up values rather than the board's own log",
1277            column.quoted(),
1278            high - low
1279        )
1280    })
1281}
1282
1283/// The logger, the firmware and a note on the settings left out, from a `CONFIG` line.
1284fn settings(config: Option<&str>) -> (String, Option<String>, Option<String>) {
1285    let mut logger = LOGGER.to_owned();
1286    let mut firmware = None;
1287    let Some(config) = config else {
1288        return (logger, firmware, None);
1289    };
1290    let mut others = 0usize;
1291    let mut first_other = None;
1292    for setting in cells(config, config.contains('\t')).skip(1) {
1293        let Some((key, value)) = setting.split_once('=') else {
1294            others += 1;
1295            continue;
1296        };
1297        let value = value.trim();
1298        match key.trim() {
1299            "BOARD_NAME" if !value.is_empty() => logger = short(value),
1300            "FIRMWARE_VERSION" if !value.is_empty() => firmware = Some(short(value)),
1301            key => {
1302                others += 1;
1303                first_other.get_or_insert_with(|| short(key));
1304            }
1305        }
1306    }
1307    let note = (others > 0).then(|| {
1308        format!(
1309            "the `CONFIG` line's {others} other settings{} are left out: no source gives their \
1310             meanings or units",
1311            first_other.map_or_else(String::new, |key| format!(", such as `{key}`,"))
1312        )
1313    });
1314    (logger, firmware, note)
1315}
1316
1317fn not_this(message: String) -> LogError {
1318    LogError::NotThisFormat {
1319        format: FORMAT,
1320        message,
1321    }
1322}
1323
1324fn syntax(line: usize, message: String) -> LogError {
1325    LogError::Syntax {
1326        format: FORMAT,
1327        line,
1328        message,
1329    }
1330}
1331
1332#[cfg(test)]
1333mod tests {
1334    use super::*;
1335
1336    const G: f64 = STANDARD_GRAVITY_MPS2;
1337    const FOOT_M: f64 = 0.3048;
1338
1339    const HEADER: &str = "timestampMs\tpressurePa\ttempK\taccelX\taccelY\taccelZ\tgyroX\tgyroY\t\
1340                          gyroZ\timuTemp\tbattV\taltitudeM\tvelocityMS\taccelerationMSS\t\
1341                          unfiltAlt\tflightState\tdrogueCont\tdrogueFired\tmainCont\tmainFired";
1342
1343    /// The pressure, Pa, at an altitude above a pad 300 m up in the standard atmosphere's
1344    /// troposphere: the altimeter formula inverted.
1345    fn pressure_at(altitude_m: f64) -> f64 {
1346        101_325.0 * (1.0 - (300.0 + altitude_m) / 44_330.8).powf(1.0 / 0.190_263)
1347    }
1348
1349    /// How an invented flight is written: each quantity's value per SI unit, and the bay's
1350    /// temperatures as written.
1351    #[derive(Debug, Clone, Copy)]
1352    struct Written {
1353        accel: f64,
1354        gyro: f64,
1355        altitude: f64,
1356        unfiltered: f64,
1357        speed: f64,
1358        pressure: f64,
1359        temp: f64,
1360        imu_temp: f64,
1361        battery: f64,
1362        turning: bool,
1363    }
1364
1365    impl Default for Written {
1366        fn default() -> Self {
1367            Self {
1368                accel: 1.0,
1369                gyro: 1.0,
1370                altitude: 1.0,
1371                unfiltered: 1.0,
1372                speed: 1.0,
1373                pressure: 1.0,
1374                temp: 290.15,
1375                imu_temp: 293.15,
1376                battery: 4.0,
1377                turning: true,
1378            }
1379        }
1380    }
1381
1382    /// One sample of the invented flight, in SI and rad/s.
1383    struct Sample {
1384        t_ms: f64,
1385        altitude_m: f64,
1386        speed_m_s: f64,
1387        accel: [f64; 3],
1388        gyro: [f64; 3],
1389        drogue: u8,
1390        main: u8,
1391    }
1392
1393    /// An invented flight: 4 samples on the pad 5 s apart; a boost at 7 g, 20 samples 50 ms
1394    /// apart; 60 samples 20 ms apart under a parachute from 300 m, the board turning about x at
1395    /// 1 rad/s if `turning`, the drogue fired; 3 samples landed 5 s apart, the main fired.
1396    fn samples(turning: bool) -> Vec<Sample> {
1397        let mut out = Vec::new();
1398        for k in 0..4 {
1399            out.push(Sample {
1400                t_ms: 1_000.0 + 5_000.0 * f64::from(k),
1401                altitude_m: 0.0,
1402                speed_m_s: 0.0,
1403                accel: [0.0, 0.0, G],
1404                gyro: [0.0; 3],
1405                drogue: 0,
1406                main: 0,
1407            });
1408        }
1409        for k in 1..=20 {
1410            let tau = 0.05 * f64::from(k);
1411            out.push(Sample {
1412                t_ms: 16_000.0 + 50.0 * f64::from(k),
1413                altitude_m: 40.0 * tau * tau,
1414                speed_m_s: 80.0 * tau,
1415                accel: [0.0, 0.0, 7.0 * G],
1416                gyro: [0.0; 3],
1417                drogue: 0,
1418                main: 0,
1419            });
1420        }
1421        let rate = if turning { 1.0 } else { 0.0 };
1422        for k in 0..60 {
1423            let tau = 0.02 * f64::from(k);
1424            let angle = rate * tau;
1425            out.push(Sample {
1426                t_ms: 21_000.0 + 20.0 * f64::from(k),
1427                altitude_m: 300.0 - 15.0 * tau,
1428                speed_m_s: -15.0,
1429                accel: [0.0, G * angle.sin(), G * angle.cos()],
1430                gyro: [rate, 0.0, 0.0],
1431                drogue: 1,
1432                main: 0,
1433            });
1434        }
1435        for k in 0..3 {
1436            out.push(Sample {
1437                t_ms: 60_000.0 + 5_000.0 * f64::from(k),
1438                altitude_m: 0.4,
1439                speed_m_s: 0.0,
1440                accel: [0.0, G, 0.0],
1441                gyro: [0.0; 3],
1442                drogue: 1,
1443                main: 1,
1444            });
1445        }
1446        out
1447    }
1448
1449    /// The invented flight as the board's tab-separated log, written as asked.
1450    fn text(w: Written) -> String {
1451        let mut text = format!("{HEADER}\n");
1452        for (k, s) in samples(w.turning).into_iter().enumerate() {
1453            let a = s.accel.map(|v| v * w.accel);
1454            let g = s.gyro.map(|v| v * w.gyro);
1455            text.push_str(&format!(
1456                "{}\t{:.4}\t{:.3}\t{:.6}\t{:.6}\t{:.6}\t{:.6}\t{:.6}\t{:.6}\t{}\t{}\t{:.3}\t{:.3}\t\
1457                 0.00\t{:.3}\t0\t1\t{}\t1\t{}\n",
1458                s.t_ms,
1459                pressure_at(s.altitude_m) * w.pressure,
1460                w.temp + 0.001 * k as f64,
1461                a[0],
1462                a[1],
1463                a[2],
1464                g[0],
1465                g[1],
1466                g[2],
1467                w.imu_temp,
1468                w.battery,
1469                s.altitude_m * w.altitude,
1470                s.speed_m_s * w.speed,
1471                (300.0 + s.altitude_m) * w.unfiltered,
1472                s.drogue,
1473                s.main
1474            ));
1475        }
1476        text
1477    }
1478
1479    /// The invented flight with its temperature, row by row, as given.
1480    fn text_with_temperature(temperature: impl Fn(usize) -> f64) -> String {
1481        let text = text(Written::default());
1482        let mut lines = text.lines();
1483        let mut out = format!("{}\n", lines.next().unwrap_or_default());
1484        for (k, line) in lines.enumerate() {
1485            let mut cells: Vec<String> = line.split('\t').map(str::to_owned).collect();
1486            cells[2] = format!("{}", temperature(k));
1487            out.push_str(&cells.join("\t"));
1488            out.push('\n');
1489        }
1490        out
1491    }
1492
1493    fn channel<'a>(log: &'a FlightLog, column: &str) -> &'a Channel {
1494        log.channels
1495            .iter()
1496            .find(|c| c.column == column)
1497            .unwrap_or_else(|| panic!("no {column}"))
1498    }
1499
1500    fn values<'a>(log: &'a FlightLog, column: &str) -> &'a [f64] {
1501        &channel(log, column).values
1502    }
1503
1504    fn quantity(log: &FlightLog, column: &str) -> Quantity {
1505        channel(log, column).quantity
1506    }
1507
1508    fn note<'a>(log: &'a FlightLog, start: &str) -> &'a str {
1509        let matching: Vec<&String> = log.notes.iter().filter(|n| n.starts_with(start)).collect();
1510        assert_eq!(matching.len(), 1, "{start}: {:?}", log.notes);
1511        matching[0]
1512    }
1513
1514    fn has_note(log: &FlightLog, start: &str) -> bool {
1515        log.notes.iter().any(|n| n.starts_with(start))
1516    }
1517
1518    /// The survey's reading of a note (`xtask logs`' `unit_decision`): the text before the first
1519    /// `: ` of a note opening with a name in backticks that is `read in` or `kept as written`.
1520    fn counted(note: &str) -> Option<&str> {
1521        let (decision, _) = note.split_once(": ")?;
1522        (decision.starts_with('`')
1523            && (decision.contains("` read in ") || decision.contains("` kept as written")))
1524        .then_some(decision)
1525    }
1526
1527    fn close(a: f64, b: f64) -> bool {
1528        (a - b).abs() <= 1e-9 * b.abs().max(1.0)
1529    }
1530
1531    #[test]
1532    fn recognizes_the_header_and_nothing_like_it() {
1533        assert!(recognizes(&format!("\u{feff}\r\n{HEADER}\r\n1\t2\n")));
1534        assert!(recognizes(&HEADER.replace('\t', " ")));
1535        assert!(recognizes("TIMESTAMPMS altitudeM PRESSUREPA\n"));
1536        assert!(recognizes(&format!("CONFIG\tBOARD_NAME=x\n\n{HEADER}\n")));
1537        for other in [
1538            "",
1539            "timestampMs\tpressurePa\n",
1540            "timestampMs,pressurePa,altitudeM\n",
1541            "time\tpressurePa\taltitudeM\n",
1542            "timestamp_ms,pressurePa,altitudeM\n",
1543            "CONFIG\tconverted_from=x\n6098809,0,302.7,-2.8\n",
1544            "CONFIG\tBOARD_NAME=x\n",
1545            "time,pressure,Pressure AGL,time,launch detect\n",
1546            "# MET Acc Vel iAlt pAlt\n",
1547        ] {
1548            assert!(!recognizes(other), "{other:?}");
1549        }
1550        // The header must come first, or straight after the settings line.
1551        assert!(!recognizes(&format!("a note\n{HEADER}\n")));
1552    }
1553
1554    #[test]
1555    fn reads_an_invented_flight_in_si() {
1556        let log = read(&text(Written::default())).unwrap();
1557        assert_eq!(log.format, LogFormat::SillyGooseText);
1558        assert_eq!(log.logger, LOGGER);
1559        assert_eq!(log.time_s.len(), 87);
1560        assert_eq!(log.time_s[0], 1.0);
1561        assert_eq!(log.channels.len(), 19);
1562        assert!(log.channels.iter().all(|c| c.time_s.len() == 87));
1563        assert_eq!(quantity(&log, "pressurePa"), Quantity::Pressure);
1564        assert_eq!(quantity(&log, "accelZ"), Quantity::Acceleration);
1565        assert_eq!(quantity(&log, "gyroX"), Quantity::AngularRate);
1566        assert_eq!(quantity(&log, "flightState"), Quantity::Number);
1567        assert!(close(values(&log, "accelZ")[0], G));
1568        // 1 rad/s, in °/s.
1569        assert!(close(values(&log, "gyroX")[30], 180.0 / PI));
1570        let top = log.altitude_m.iter().copied().fold(f64::MIN, f64::max);
1571        assert_eq!(top, 300.0);
1572        assert_eq!(log.vertical_speed_m_s.as_ref().unwrap()[10], 28.0);
1573        assert_eq!(log.temperature_k.as_ref().unwrap()[0], 290.15);
1574        assert_eq!(log.battery_v.as_ref().unwrap()[0], 4.0);
1575        let events: Vec<(f64, &str)> = log
1576            .events
1577            .iter()
1578            .map(|e| (e.time_s, e.name.as_str()))
1579            .collect();
1580        assert_eq!(events, [(21.0, "drogueFired"), (60.0, "mainFired")]);
1581        // Every unit decision is one the survey counts.
1582        for note in log.notes.iter().filter(|n| n.starts_with('`')) {
1583            assert!(counted(note).is_some(), "{note}");
1584        }
1585        assert!(log.notes.iter().all(|n| !n.contains("assum")));
1586    }
1587
1588    /// The accelerometer's unit both ways: a file in g reads the same in SI as one in m/s², and
1589    /// neither is taken for the other. Flipping the rule would read the g file's pad as 1 m/s².
1590    #[test]
1591    fn the_accelerometer_s_unit_is_decided_by_the_pad_s_gravity_both_ways() {
1592        let in_ms2 = read(&text(Written::default())).unwrap();
1593        let in_g = read(&text(Written {
1594            accel: 1.0 / G,
1595            ..Written::default()
1596        }))
1597        .unwrap();
1598        note(
1599            &in_ms2,
1600            "`accelX`, `accelY` and `accelZ` read in meters per second squared, from the pad's \
1601             gravity: ",
1602        );
1603        note(
1604            &in_g,
1605            "`accelX`, `accelY` and `accelZ` read in standard gravities, × 9.806 65 m/s², from \
1606             the pad's gravity: ",
1607        );
1608        for (a, b) in values(&in_g, "accelZ")
1609            .iter()
1610            .zip(values(&in_ms2, "accelZ"))
1611        {
1612            assert!((a - b).abs() < 1e-5, "{a} {b}");
1613        }
1614        assert!(close(values(&in_g, "accelZ")[0], G));
1615        // The gyroscope's check runs on either.
1616        assert_eq!(quantity(&in_g, "gyroX"), Quantity::AngularRate);
1617
1618        // A magnitude near neither 1 g settles nothing: the axes, and the gyroscope that needs
1619        // them, are kept as written.
1620        let neither = read(&text(Written {
1621            accel: 0.5,
1622            ..Written::default()
1623        }))
1624        .unwrap();
1625        assert_eq!(quantity(&neither, "accelX"), Quantity::Unrecognized);
1626        assert!(close(values(&neither, "accelZ")[0], 0.5 * G));
1627        note(
1628            &neither,
1629            "`accelX`, `accelY` and `accelZ` kept as written: ",
1630        );
1631        assert!(
1632            note(&neither, "`gyroX`, `gyroY` and `gyroZ` kept as written: ")
1633                .contains("no accelerometer read in a known unit")
1634        );
1635    }
1636
1637    /// The pad's gravity counts time, not samples: a fast run of 300 readings of 1 m/s² in a
1638    /// coast doesn't outweigh 25 readings of 9.8 over 2 minutes at rest.
1639    #[test]
1640    fn the_pad_s_gravity_weighs_each_reading_by_its_time() {
1641        let mut text = format!("{HEADER}\n");
1642        for t in (0..=24).map(|k| 5_000.0 * f64::from(k)) {
1643            text.push_str(&format!(
1644                "{t}\t97772\t290\t0\t0\t{G}\t0\t0\t0\t293\t4\t0\t0\t0\t300\t0\t0\t0\t0\t0\n"
1645            ));
1646        }
1647        for k in 1..=300 {
1648            let t = 120_000.0 + 10.0 * f64::from(k);
1649            text.push_str(&format!(
1650                "{t}\t97772\t290\t0\t0\t1.0\t0\t0\t0\t293\t4\t0\t0\t0\t300\t0\t0\t0\t0\t0\n"
1651            ));
1652        }
1653        let log = read(&text).unwrap();
1654        assert!(
1655            note(
1656                &log,
1657                "`accelX`, `accelY` and `accelZ` read in meters per second squared"
1658            )
1659            .contains("within 10% of 9.806 65 for 120.0 s of the file's time. It reads within 10% of 1 for 3.0 s"),
1660            "{:?}",
1661            log.notes
1662        );
1663    }
1664
1665    /// A sample counts for at most 5 s: a coast reading of 1.0 before the clock jumps 10 minutes
1666    /// doesn't outweigh 35 s of 9.8 on the pad and landed. Counting the whole jump would read the
1667    /// file in g, its accelerations 9.8 times too high.
1668    #[test]
1669    fn a_jump_of_the_clock_counts_for_at_most_5_s_of_gravity() {
1670        let mut text = format!("{HEADER}\n");
1671        let row = |t: f64, z: f64| {
1672            format!("{t}\t97772\t290\t0\t0\t{z}\t0\t0\t0\t293\t4\t0\t0\t0\t300\t0\t0\t0\t0\t0\n")
1673        };
1674        for k in 0..6 {
1675            text.push_str(&row(5_000.0 * f64::from(k), G));
1676        }
1677        text.push_str(&row(30_000.0, 1.0));
1678        text.push_str(&row(630_000.0, G));
1679        text.push_str(&row(635_000.0, G));
1680        let log = read(&text).unwrap();
1681        assert!(
1682            note(
1683                &log,
1684                "`accelX`, `accelY` and `accelZ` read in meters per second squared"
1685            )
1686            .contains(
1687                "within 10% of 9.806 65 for 35.0 s of the file's time. It reads within 10% of 1 for 5.0 s"
1688            ),
1689            "{:?}",
1690            log.notes
1691        );
1692        assert!(close(values(&log, "accelZ")[0], G));
1693    }
1694
1695    /// The gyroscope's unit both ways, and kept where the turning doesn't settle it. Flipping the
1696    /// rule would read the radian file's 1 rad/s as 1 °/s.
1697    #[test]
1698    fn the_gyroscope_s_unit_is_decided_by_the_board_s_turning_both_ways() {
1699        let radians = read(&text(Written::default())).unwrap();
1700        let degrees = read(&text(Written {
1701            gyro: 180.0 / PI,
1702            ..Written::default()
1703        }))
1704        .unwrap();
1705        assert!(
1706            note(
1707                &radians,
1708                "`gyroX`, `gyroY` and `gyroZ` read in radians per second, from the board's \
1709                 turning: "
1710            )
1711            .contains("over 5 stretches")
1712        );
1713        note(
1714            &degrees,
1715            "`gyroX`, `gyroY` and `gyroZ` read in degrees per second, from the board's turning: ",
1716        );
1717        for (a, b) in values(&radians, "gyroX")
1718            .iter()
1719            .zip(values(&degrees, "gyroX"))
1720        {
1721            assert!((a - b).abs() < 1e-4, "{a} {b}");
1722        }
1723        assert!(close(values(&radians, "gyroX")[30], 180.0 / PI));
1724
1725        // No turning: too little to tell.
1726        let still = read(&text(Written {
1727            turning: false,
1728            ..Written::default()
1729        }))
1730        .unwrap();
1731        assert_eq!(quantity(&still, "gyroX"), Quantity::Unrecognized);
1732        assert!(
1733            note(&still, "`gyroX`, `gyroY` and `gyroZ` kept as written: ")
1734                .contains("too little turning to tell")
1735        );
1736
1737        // Rates 10 times the turning's in rad/s, 0.17 times in °/s: in neither unit within a
1738        // factor of 4.
1739        let off = read(&text(Written {
1740            gyro: 10.0,
1741            ..Written::default()
1742        }))
1743        .unwrap();
1744        assert_eq!(quantity(&off, "gyroX"), Quantity::Unrecognized);
1745        assert!(
1746            note(&off, "`gyroX`, `gyroY` and `gyroZ` kept as written: ")
1747                .contains("in neither unit")
1748        );
1749    }
1750
1751    #[test]
1752    fn the_turning_check_measures_a_known_turn() {
1753        let log_text = text(Written::default());
1754        let mut lines = numbered_lines(&log_text);
1755        let _ = lines.next();
1756        let mut columns: Vec<Column> = HEADER.split('\t').skip(1).map(Column::new).collect();
1757        let mut times = Vec::new();
1758        for (_, line) in lines {
1759            let mut cells = line
1760                .split('\t')
1761                .map(|c| c.parse::<f64>().unwrap_or(f64::NAN));
1762            times.push(cells.next().unwrap_or(f64::NAN) / 1_000.0);
1763            for (column, value) in columns.iter_mut().zip(cells) {
1764                column.values.push(value);
1765            }
1766        }
1767        let accel = axes(&columns, Role::Accel).unwrap();
1768        let gyro = axes(&columns, Role::Gyro).unwrap();
1769        let found = turning(&columns, &times, accel, gyro, G);
1770        // 59 steps of 20 ms at 1 rad/s under the parachute: 5 whole stretches of 0.2 rad.
1771        assert_eq!(found.stretches, 5);
1772        assert!((found.accelerometer_rad - 1.0).abs() < 1e-5, "{found:?}");
1773        assert!((found.gyroscope_rad - 1.0).abs() < 1e-5, "{found:?}");
1774    }
1775
1776    #[test]
1777    fn temperatures_are_kelvin_only_where_the_values_bear_it_out() {
1778        let log = read(&text(Written::default())).unwrap();
1779        assert_eq!(quantity(&log, "tempK"), Quantity::Temperature);
1780        assert_eq!(quantity(&log, "imuTemp"), Quantity::Temperature);
1781        note(&log, "`imuTemp` read in kelvin, from the values: ");
1782        assert!(!has_note(&log, "`tempK`"), "{:?}", log.notes);
1783
1784        let refuted = read(&text(Written {
1785            temp: -9.0,
1786            imu_temp: 0.0,
1787            ..Written::default()
1788        }))
1789        .unwrap();
1790        assert_eq!(quantity(&refuted, "tempK"), Quantity::Unrecognized);
1791        assert!(refuted.temperature_k.is_none());
1792        assert_eq!(values(&refuted, "tempK")[0], -9.0);
1793        assert!(
1794            note(
1795                &refuted,
1796                "`tempK` kept as written: its name says kelvin, but "
1797            )
1798            .contains("below 0 no temperature in kelvin can be")
1799        );
1800        assert!(
1801            note(
1802                &refuted,
1803                "`imuTemp` kept as written: its name states no unit, and "
1804            )
1805            .contains("every value is exactly 0")
1806        );
1807
1808        // Degrees Celsius aren't kelvin, and nothing says they are Celsius.
1809        let celsius = read(&text(Written {
1810            temp: 20.0,
1811            imu_temp: 22.5,
1812            ..Written::default()
1813        }))
1814        .unwrap();
1815        assert_eq!(quantity(&celsius, "tempK"), Quantity::Unrecognized);
1816        assert_eq!(quantity(&celsius, "imuTemp"), Quantity::Unrecognized);
1817        assert!(
1818            note(&celsius, "`tempK` kept as written: ")
1819                .contains("run from 20 to 20.086, outside the 233.15 to 333.15 K")
1820        );
1821    }
1822
1823    /// `altitudeM` in feet is refused: the primary track would be 3.28 times off. `unfiltAlt` in
1824    /// feet is kept as written.
1825    #[test]
1826    fn altitudes_are_checked_against_the_pressure() {
1827        match read(&text(Written {
1828            altitude: 1.0 / FOOT_M,
1829            ..Written::default()
1830        })) {
1831            Err(LogError::Unit {
1832                line: 1, message, ..
1833            }) => {
1834                assert!(message.contains("`altitudeM` climbs 984.3"), "{message}");
1835                assert!(message.contains("aren't within 25%"), "{message}");
1836            }
1837            other => panic!("{other:?}"),
1838        }
1839        let unfiltered = read(&text(Written {
1840            unfiltered: 1.0 / FOOT_M,
1841            ..Written::default()
1842        }))
1843        .unwrap();
1844        assert_eq!(quantity(&unfiltered, "unfiltAlt"), Quantity::Unrecognized);
1845        assert!(
1846            note(&unfiltered, "`unfiltAlt` kept as written: ")
1847                .contains("climbs 984.3. The standard atmosphere climbs 300.0 m")
1848        );
1849        let meters = read(&text(Written::default())).unwrap();
1850        assert_eq!(
1851            quantity(&meters, "unfiltAlt"),
1852            Quantity::AltitudeAboveGround
1853        );
1854        note(&meters, "`unfiltAlt` read in meters, from the pressure: ");
1855        assert!(!has_note(&meters, "`altitudeM`"));
1856    }
1857
1858    #[test]
1859    fn a_pressure_that_is_no_pad_s_in_pascals_is_kept_and_the_altitude_unchecked() {
1860        let hectopascals = read(&text(Written {
1861            pressure: 0.01,
1862            ..Written::default()
1863        }))
1864        .unwrap();
1865        assert_eq!(
1866            quantity(&hectopascals, "pressurePa"),
1867            Quantity::Unrecognized
1868        );
1869        assert!(
1870            note(
1871                &hectopascals,
1872                "`pressurePa` kept as written: its name says pascals, but "
1873            )
1874            .contains("(50,000 to 110,000 Pa)")
1875        );
1876        assert!(
1877            note(&hectopascals, "`altitudeM` read in meters, from its name: ")
1878                .contains("no pressure in pascals")
1879        );
1880        note(&hectopascals, "`unfiltAlt` kept as written: ");
1881    }
1882
1883    /// A speed in feet per second is 3.28 times what the altitude climbs: kept as written, and
1884    /// no vertical speed. In m/s it is borne out without a note.
1885    #[test]
1886    fn the_speed_is_checked_against_the_altitude() {
1887        let log = read(&text(Written::default())).unwrap();
1888        assert_eq!(quantity(&log, "velocityMS"), Quantity::Speed);
1889        assert!(!has_note(&log, "`velocityMS`"));
1890        let feet = read(&text(Written {
1891            speed: 1.0 / FOOT_M,
1892            ..Written::default()
1893        }))
1894        .unwrap();
1895        assert_eq!(quantity(&feet, "velocityMS"), Quantity::Unrecognized);
1896        assert!(feet.vertical_speed_m_s.is_none());
1897        assert!(note(&feet, "`velocityMS` kept as written: ").contains("0.305 times"));
1898    }
1899
1900    /// Sums too large to hold make the slope `NaN`, which no comparison bears out: the speed is
1901    /// kept as written, not read in m/s unchecked.
1902    #[test]
1903    fn a_speed_whose_slope_cannot_be_computed_is_kept() {
1904        let mut text = "timestampMs\tpressurePa\taltitudeM\tvelocityMS\n".to_owned();
1905        for k in 0..50 {
1906            let (altitude, speed) = match k {
1907                20 => ("1e160", "1e160"),
1908                21 => ("0", "1e160"),
1909                _ => ("0", "0"),
1910            };
1911            text.push_str(&format!("{}\t0\t{altitude}\t{speed}\n", 10 * k));
1912        }
1913        let log = read(&text).unwrap();
1914        assert_eq!(quantity(&log, "velocityMS"), Quantity::Unrecognized);
1915        assert!(log.vertical_speed_m_s.is_none());
1916        let kept = note(&log, "`velocityMS` kept as written: ");
1917        assert!(kept.contains("can't be computed"), "{kept}");
1918        assert!(!kept.contains("NaN"), "{kept}");
1919        assert!(counted(kept).is_some());
1920    }
1921
1922    /// The invented flight in g, with one cell of its second sample replaced.
1923    fn text_in_g_with(cell: usize, value: &str) -> String {
1924        let text = text(Written {
1925            accel: 1.0 / G,
1926            ..Written::default()
1927        });
1928        let mut lines = text.lines();
1929        let mut out = format!("{}\n", lines.next().unwrap_or_default());
1930        for (k, line) in lines.enumerate() {
1931            let mut cells: Vec<String> = line.split('\t').map(str::to_owned).collect();
1932            if k == 1 {
1933                cells[cell] = value.to_owned();
1934            }
1935            out.push_str(&cells.join("\t"));
1936            out.push('\n');
1937        }
1938        out
1939    }
1940
1941    /// A value in g near the largest `f64` is finite as written and infinite in m/s²: refused on
1942    /// its line, the file's third (ADR-258 §3).
1943    #[test]
1944    fn a_value_its_conversion_makes_infinite_is_refused() {
1945        assert_eq!(
1946            read(&text_in_g_with(3, "-1.7e308"))
1947                .unwrap_err()
1948                .to_string(),
1949            "SillyGoose text line 3: the column accelX holds a value too large for its unit's \
1950             conversion to SI"
1951        );
1952        // Just below the overflow, the value is read, in m/s².
1953        let log = read(&text_in_g_with(3, "1e307")).unwrap();
1954        assert_eq!(quantity(&log, "accelX"), Quantity::Acceleration);
1955        assert!(close(values(&log, "accelX")[1], 1e307 * G));
1956    }
1957
1958    /// A gyroscope's rate in rad/s near the largest `f64` is infinite in °/s: refused on its line
1959    /// (ADR-258 §3).
1960    #[test]
1961    fn a_value_its_conversion_makes_infinite_is_refused_for_the_gyroscope() {
1962        assert_eq!(
1963            read(&text_in_g_with(7, "1.7e308")).unwrap_err().to_string(),
1964            "SillyGoose text line 3: the column gyroY holds a value too large for its unit's \
1965             conversion to SI"
1966        );
1967    }
1968
1969    /// Unknown columns are kept, each with a note, but the notes stop at 20 and count the rest; a
1970    /// header of [`MAX_COLUMNS`] names is read.
1971    #[test]
1972    fn an_unknown_column_is_kept_and_its_notes_stay_few() {
1973        let names: Vec<String> = (0..30).map(|k| format!("extra_{k}")).collect();
1974        let text = format!(
1975            "timestampMs\tpressurePa\taltitudeM\t{}\n1000\t97772\t0\t{}\n",
1976            names.join("\t"),
1977            ["7"; 30].join("\t")
1978        );
1979        let log = read(&text).unwrap();
1980        assert_eq!(log.channels.len(), 32);
1981        assert_eq!(quantity(&log, "extra_29"), Quantity::Unrecognized);
1982        assert_eq!(values(&log, "extra_29"), [7.0]);
1983        let kept = log
1984            .notes
1985            .iter()
1986            .filter(|n| n.starts_with("the column `extra_"))
1987            .count();
1988        assert_eq!(kept, 20);
1989        note(&log, "and 10 more notes");
1990
1991        let names: Vec<String> = (0..MAX_COLUMNS - 3).map(|k| format!("c{k}")).collect();
1992        let widest = read(&format!(
1993            "timestampMs\tpressurePa\taltitudeM\t{}\n1000\t97772\t0\n",
1994            names.join("\t")
1995        ))
1996        .unwrap();
1997        assert_eq!(widest.channels.len(), MAX_COLUMNS - 1);
1998        assert!(widest.notes.len() <= 30, "{}", widest.notes.len());
1999    }
2000
2001    /// A log all on the pad: too little climb or movement to check the altitude's and the speed's
2002    /// units, so they are read from their names, and `unfiltAlt` is kept.
2003    #[test]
2004    fn a_log_on_the_pad_reads_its_units_from_their_names() {
2005        let mut text = format!("{HEADER}\n");
2006        for k in 0..6 {
2007            let t = 1_000 + 5_000 * k;
2008            text.push_str(&format!(
2009                "{t}\t97772.5\t290.2\t0.01\t0.02\t9.79\t0.001\t0\t0\t293\t4.1\t0.{k}\t0.0\t0\t\
2010                 300.{k}\t0\t0\t0\t0\t0\n"
2011            ));
2012        }
2013        let log = read(&text).unwrap();
2014        assert!(
2015            note(&log, "`altitudeM` read in meters, from its name: ")
2016                .contains("the pressure climbs 0.00 m")
2017        );
2018        note(
2019            &log,
2020            "`velocityMS` read in meters per second, from its name: ",
2021        );
2022        note(
2023            &log,
2024            "`unfiltAlt` kept as written: its name states no unit, and ",
2025        );
2026        note(&log, "`gyroX`, `gyroY` and `gyroZ` kept as written: ");
2027        assert!(log.events.is_empty());
2028    }
2029
2030    #[test]
2031    fn the_settings_line_names_the_board_and_the_extra_columns_are_checked() {
2032        let header = format!(
2033            "{HEADER}\ttiltMagnitudeDeg\tangularVelRadS_x\tangularVelRadS_y\tangularVelRadS_z\t\
2034             quaternion_a\tquaternion_b\tquaternion_c\tquaternion_d"
2035        );
2036        let file = |config: &str, tilt: f64, rate: f64, battery: f64| {
2037            let mut text = format!("{config}\n{header}\n");
2038            for k in 0..3 {
2039                text.push_str(&format!(
2040                    "{}\t97772\t290\t0\t0\t9.8\t0\t0\t0\t293\t{battery}\t0\t0\t0\t300\t0\t0\t0\t\
2041                     0\t0\t{tilt}\t{rate}\t0\t0\t1\t0\t0\t0\n",
2042                    1_000 + 5_000 * k
2043                ));
2044            }
2045            text
2046        };
2047        let log = read(&file(
2048            "CONFIG\tBOARD_NAME=Bench\tFIRMWARE_VERSION=2.1\tA=1\tNOVALUE",
2049            12.5,
2050            3.0,
2051            4.0,
2052        ))
2053        .unwrap();
2054        assert_eq!(log.logger, "Bench");
2055        assert_eq!(log.firmware.as_deref(), Some("2.1"));
2056        note(
2057            &log,
2058            "the `CONFIG` line's 2 other settings, such as `A`, are left out: ",
2059        );
2060        assert_eq!(quantity(&log, "tiltMagnitudeDeg"), Quantity::Angle);
2061        assert_eq!(quantity(&log, "quaternion_a"), Quantity::Number);
2062        assert_eq!(quantity(&log, "angularVelRadS_x"), Quantity::AngularRate);
2063        assert!(close(values(&log, "angularVelRadS_x")[0], 3.0 * 180.0 / PI));
2064
2065        // Past what a gyroscope measures, beyond a tilt's range, and beyond a battery's volts.
2066        let refuted = read(&file("CONFIG\tBOARD_NAME=", 190.0, 400.0, 3_700.0)).unwrap();
2067        assert_eq!(refuted.logger, LOGGER);
2068        assert!(refuted.firmware.is_none());
2069        for column in [
2070            "angularVelRadS_x",
2071            "angularVelRadS_y",
2072            "tiltMagnitudeDeg",
2073            "battV",
2074        ] {
2075            assert_eq!(
2076                quantity(&refuted, column),
2077                Quantity::Unrecognized,
2078                "{column}"
2079            );
2080        }
2081        assert!(refuted.battery_v.is_none());
2082        assert!(
2083            note(
2084                &refuted,
2085                "`angularVelRadS_x`, `angularVelRadS_y` and `angularVelRadS_z` kept as written: "
2086            )
2087            .contains("reach 400")
2088        );
2089        note(&refuted, "`tiltMagnitudeDeg` kept as written: ");
2090        note(&refuted, "`battV` kept as written: ");
2091        // A rate just inside 20,000 °/s is read.
2092        let inside = read(&file("CONFIG", 10.0, 349.0, 4.0)).unwrap();
2093        assert_eq!(quantity(&inside, "angularVelRadS_x"), Quantity::AngularRate);
2094    }
2095
2096    #[test]
2097    fn malformed_files_are_refused_naming_the_line() {
2098        let syntax_line = |text: &str| match read(text) {
2099            Err(LogError::Syntax { line, message, .. }) => (line, message),
2100            other => panic!("{other:?}"),
2101        };
2102        let wide = format!("{HEADER}\n{}\t1\n", ["0"; 20].join("\t"));
2103        let (line, message) = syntax_line(&wide);
2104        assert_eq!(line, 2);
2105        assert!(
2106            message.contains("more than 20 cells, where the header names 20"),
2107            "{message}"
2108        );
2109        // A long row is refused alike, read no further than one cell past the header's width.
2110        let long = format!("{HEADER}\n{}\n", ["0"; 100_000].join("\t"));
2111        let (line, message) = syntax_line(&long);
2112        assert_eq!(line, 2);
2113        assert!(message.contains("more than 20 cells"), "{message}");
2114        // A header of more names than the board ever writes.
2115        let names: Vec<String> = (0..MAX_COLUMNS).map(|k| format!("c{k}")).collect();
2116        let (line, message) = syntax_line(&format!(
2117            "timestampMs\tpressurePa\taltitudeM\t{}\n0\t0\t0\n",
2118            names.join("\t")
2119        ));
2120        assert_eq!(line, 1);
2121        assert!(
2122            message.contains("the header names more than 256 columns"),
2123            "{message}"
2124        );
2125        let (line, message) = syntax_line("timestampMs pressurePa altitudeM altitudeM\n1 2 3 4\n");
2126        assert_eq!(line, 1);
2127        assert!(message.contains("names \"altitudeM\" twice"), "{message}");
2128        let (_, message) = syntax_line("timestampMs\tpressurePa\t\taltitudeM\n");
2129        assert!(message.contains("column 3 has no name"), "{message}");
2130        for text in ["", "\n\n", "CONFIG\tA=1\n", "hello\n"] {
2131            assert!(
2132                matches!(read(text), Err(LogError::NotThisFormat { .. })),
2133                "{text:?}"
2134            );
2135        }
2136        assert!(matches!(
2137            read("timestampMs pressurePa altitudeM\n"),
2138            Err(LogError::NoData { .. })
2139        ));
2140        assert!(matches!(
2141            read("timestampMs pressurePa altitudeM\nx 97000 0\n"),
2142            Err(LogError::NoData { .. })
2143        ));
2144        // A wide header over short rows can't make the reader store far more than the file holds:
2145        // 253 names over rows of one cell pass the bound at the 264th row.
2146        let names: Vec<String> = (0..250).map(|k| format!("c{k}")).collect();
2147        let mut sparse = format!("timestampMs\tpressurePa\taltitudeM\t{}\n", names.join("\t"));
2148        for k in 0..300 {
2149            sparse.push_str(&format!("{k}\n"));
2150        }
2151        let (_, message) = syntax_line(&sparse);
2152        assert!(message.contains("too few for the header"), "{message}");
2153    }
2154
2155    #[test]
2156    fn empty_and_unreadable_cells_and_short_rows_are_gaps() {
2157        let text = "timestampMs pressurePa altitudeM extra\n\
2158                    1000 97772 0 1\n\
2159                    2000 x 1 2\n\
2160                    3000 97760 2\n";
2161        let log = read(text).unwrap();
2162        assert!(values(&log, "pressurePa")[1].is_nan());
2163        assert!(values(&log, "extra")[2].is_nan());
2164        assert_eq!(quantity(&log, "extra"), Quantity::Unrecognized);
2165        note(
2166            &log,
2167            "1 cells, the first on line 3, are empty or not numbers: ",
2168        );
2169        note(
2170            &log,
2171            "1 rows, the first on line 4, hold fewer cells than the header names: ",
2172        );
2173        note(&log, "the column `extra` isn't one this reader knows");
2174        let tabbed = read("timestampMs\tpressurePa\taltitudeM\n1000\t\t0\n").unwrap();
2175        assert!(tabbed.channels[0].values[0].is_nan());
2176        note(
2177            &tabbed,
2178            "1 cells, the first on line 2, are empty or not numbers: ",
2179        );
2180    }
2181
2182    #[test]
2183    fn the_track_is_put_in_time_order_and_the_channels_kept_as_written() {
2184        let text = "timestampMs pressurePa altitudeM\n\
2185                    1000 97772 0\n\
2186                    3000 97749 2\n\
2187                    2000 97760 1\n\
2188                    3000 97668 9\n\
2189                    - 97714 5\n";
2190        let log = read(text).unwrap();
2191        assert_eq!(log.time_s, [1.0, 2.0, 3.0]);
2192        assert_eq!(log.altitude_m, [0.0, 1.0, 2.0]);
2193        assert_eq!(values(&log, "altitudeM"), [0.0, 2.0, 1.0, 9.0, 5.0]);
2194        note(
2195            &log,
2196            "the clock goes back 1 times and repeats a time 1 times, and 1 samples have no time",
2197        );
2198    }
2199
2200    #[test]
2201    fn a_log_starting_aloft_and_a_temperature_that_never_changes_are_noted() {
2202        let text = "timestampMs pressurePa tempK altitudeM\n\
2203                    100 96000 290.15 150\n\
2204                    200 96010 290.15 149\n";
2205        let log = read(text).unwrap();
2206        note(
2207            &log,
2208            "`altitudeM` reads 150.00 m at the track's first sample, not near zero",
2209        );
2210        // 150 m to 149 m isn't a climb of over 100 m: no note on the temperature.
2211        assert!(!has_note(&log, "`tempK` reads"));
2212
2213        let replay = read(&text_with_temperature(|_| 300.0)).unwrap();
2214        assert!(
2215            note(
2216                &replay,
2217                "`tempK` reads 300 at every one of its 87 samples while the altitude spans 300 m"
2218            )
2219            .contains("replay")
2220        );
2221        let recording = read(&text_with_temperature(|k| 300.0 + 0.01 * k as f64)).unwrap();
2222        assert!(!has_note(&recording, "`tempK` reads"));
2223    }
2224
2225    #[test]
2226    fn a_fired_flag_s_rises_are_events_and_one_already_set_is_not() {
2227        let text = "timestampMs pressurePa altitudeM drogueFired mainFired drogueCont flightState\n\
2228                    1000 97772 0 0 1 1 0\n\
2229                    2000 97770 0 1 1 0 1\n\
2230                    3000 97770 0 - 0 1 2\n\
2231                    4000 97770 0 1 1 0 3\n\
2232                    5000 97770 0 0 0 1 4\n\
2233                    6000 97770 0 1 0 1 4\n";
2234        let log = read(text).unwrap();
2235        let events: Vec<(f64, &str)> = log
2236            .events
2237            .iter()
2238            .map(|e| (e.time_s, e.name.as_str()))
2239            .collect();
2240        // `mainFired` set at its first sample is no rise; it rises again at 4 s. A gap between
2241        // two 1s is no rise, nor are the continuity flag's and the state's changes.
2242        assert_eq!(
2243            events,
2244            [
2245                (2.0, "drogueFired"),
2246                (4.0, "mainFired"),
2247                (6.0, "drogueFired")
2248            ]
2249        );
2250        assert_eq!(quantity(&log, "drogueCont"), Quantity::Number);
2251        assert_eq!(quantity(&log, "flightState"), Quantity::Number);
2252    }
2253
2254    #[test]
2255    fn listed_names_read_as_a_sentence() {
2256        let columns: Vec<Column> = ["a", "b", "c"].into_iter().map(Column::new).collect();
2257        assert_eq!(listed_at(&columns, &[0]), "`a`");
2258        assert_eq!(listed_at(&columns, &[0, 1]), "`a` and `b`");
2259        assert_eq!(listed_at(&columns, &[0, 1, 2]), "`a`, `b` and `c`");
2260    }
2261
2262    proptest::proptest! {
2263        /// Any text is read or refused, never a panic; what is read has a strictly increasing
2264        /// primary track, and every channel as many times as values.
2265        #[test]
2266        fn any_text_is_read_or_refused(
2267            text in "(CONFIG\tBOARD_NAME=[a-z]{0,4}\n)?timestampMs[ \t]pressurePa[ \t]altitudeM\
2268                     ([ \t](accelX|accelY|accelZ|gyroX|gyroY|gyroZ|tempK|velocityMS|mainFired)){0,6}\n\
2269                     ([-0-9. \t]{0,30}\n){0,16}"
2270        ) {
2271            if let Ok(log) = read(&text) {
2272                proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
2273                proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
2274                for channel in &log.channels {
2275                    proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
2276                }
2277            }
2278        }
2279    }
2280}