Skip to main content

hpr_flightdata/
altos.rs

1//! AltOS's CSV flight logs, as AltosUI exports a TeleMetrum's, TeleMega's, EasyMega's or
2//! EasyMini's flight.
3//!
4//! The file is text: perhaps a few comment lines starting with `#`, then one header line naming
5//! the columns, then one row per sample, the cells separated by a comma and spaces:
6//!
7//! ```text
8//! #version,serial,flight,call,time,rssi,lqi,state,state_name,acceleration,pressure,altitude,height,speed,temperature,…
9//! 6, 1234, 3,N0CALL,    -1.00, -80,  40, 2,     pad,    0.10,  98000.00,  250.00,    0.00,    0.00, 21.0,…
10//! ```
11//!
12//! The columns differ by device and by AltosUI's version: the header says which there are, and
13//! this reader maps them by name. `call` is there when the flight came in by radio, and `rssi`
14//! and `lqi` when it was received as telemetry; a GPS-equipped unit adds `latitude`, `longitude`,
15//! a second `altitude`, the time of day, the distance and bearing to the pad and the receiver's
16//! satellite columns `sat01`…`sat32`; a TeleMega or EasyMega adds its inertial and magnetic
17//! sensors. One of the files read has no `pressure` or barometric `altitude` column at all.
18//!
19//! **Units.** The AltOS manual says the file holds "all of the sensor values … converted to
20//! standard units, with the barometric data reported in both pressure, altitude and height above
21//! pad units", and that its header and comment lines start with `#` (Altus Metrum, *AltOS*
22//! manual, §12.5.1 "Comma Separated Value Format"). It names no column's unit; these are each
23//! one's reading, and where it comes from:
24//!
25//! | columns | read as | from |
26//! |---|---|---|
27//! | `time` | the clock, s, from the logger's zero at boost: negative on the pad | Debrief's reader |
28//! | `height` | [`Quantity::AltitudeAboveGround`], m above the pad | Debrief's reader; the manual's "height above pad" |
29//! | `altitude` (the first) | [`Quantity::AltitudeMsl`], m, the barometric altitude | the manual; Debrief's reader |
30//! | `altitude` after `longitude` | [`Quantity::GnssAltitude`], m, the GPS receiver's | Debrief's reader, which finds it by its place |
31//! | `pressure` | [`Quantity::Pressure`], Pa; hPa if the column never reaches 1,200 (below) | the files read: about 98,000 on a pad |
32//! | `acceleration`, `accel_x`/`_y`/`_z` | [`Quantity::Acceleration`], m/s² | Debrief's reader and its proof from the data (below) |
33//! | `speed`, `accel_speed`, `baro_speed` | [`Quantity::Speed`], m/s, up positive | Debrief's reader |
34//! | `temperature` | [`Quantity::Temperature`], °C in the file, K here | Debrief's reader |
35//! | `battery_voltage`, `drogue_voltage`, `main_voltage`, `pyro`, `igniter_*` | [`Quantity::Voltage`], V | Debrief's reader (battery); the manual's §13.9 states the igniter and battery readings in volts |
36//! | `latitude`, `longitude` | [`Quantity::Latitude`], [`Quantity::Longitude`], degrees | Debrief's reader |
37//! | `tilt`, `pad_az`, `pad_el` | [`Quantity::Angle`], degrees | the manual (its pyro condition's "angle from vertical", in degrees; §13.10's bearing "in degrees"); the files read stay within 0–180 and 0–360 |
38//! | `pad_dist`, `pad_range` | [`Quantity::Distance`], m | only the manual's "standard units": no document states their unit |
39//! | `version`, `serial`, `flight`, `rssi`, `lqi`, `state`, `connected`, `locked`, `nsat`, `year`…`second`, `pdop`, `hdop`, `vdop`, `sat01`…`sat32` | [`Quantity::Number`], as written | counts, codes, flags, signal strengths and dilutions of precision |
40//! | `gyro_roll`/`_pitch`/`_yaw`, `mag_x`/`_y`/`_z` | [`Quantity::Unrecognized`], as written | the record has no quantity for a rotation rate or a magnetic field, and no document states their unit |
41//!
42//! Every other column is kept as written, [`Quantity::Unrecognized`], with a note. `call` (the
43//! radio call sign) and `state_name` (the flight computer's state in words) are text, not
44//! channels: each state the file changes to is an [`Event`] instead, at the time of the row that
45//! changes it, the first row's state included. The numeric `state` column is kept as a channel.
46//!
47//! **The primary track.** [`FlightLog::altitude_m`] is `height`; the vertical speed is
48//! `baro_speed`, the barometer's, and absent without it: `accel_speed` integrates the
49//! accelerometer and `speed` is the flight computer's own estimate, which leans on the
50//! accelerometer on the way up, so both stay channels only (Debrief's reader took `accel_speed`
51//! first). The temperature is `temperature` and the battery `battery_voltage`. `time` is
52//! required. A header with no `height` gives the record no primary track, only its channels,
53//! with a note.
54//!
55//! **Quirks, and what this reader does about them.**
56//!
57//! - *Repeated times.* AltosUI writes rows that share a time with the row before, hundreds in a
58//!   flight; in every one of the files read, such rows also repeat the height. The primary track
59//!   must have strictly increasing times, so it keeps the first row at each time, and the rows it
60//!   leaves out are counted in a note. Rows out of time order (none in the files read) are put in
61//!   order on the primary track, again with a note. This is what Debrief does (its
62//!   `lib/flight/build.ts`: sort by time, keep the first row at each time). The channels keep
63//!   every row, in the file's order, each on its own time.
64//! - *Acceleration net of gravity.* AltOS writes `acceleration` along the rocket's axis with
65//!   gravity taken out: it reads about 0 at rest, not 1 g, while the TeleMega's body-axis
66//!   `accel_x` on the same row reads about 9.8 m/s² (Debrief's reader, from the data). The
67//!   channel is kept as written, and a note says so. The pad's reading of 1 g along the axis is
68//!   what comes out, so the channel is the rocket's own acceleration only while it points
69//!   straight up; tilted, it is off by the difference between g and g's share along the axis.
70//! - *GPS before a fix.* AltOS writes a position of exactly (0, 0) before its receiver has a fix
71//!   (Debrief's reader). A row with latitude and longitude both 0 has its latitude, longitude and
72//!   GPS altitude read as gaps, counted in a note. None of the files read has such a row; the
73//!   rule is Debrief's, kept so that a track can't run to the equator.
74//! - *Pressure in hectopascals.* Debrief's own sample file writes pressure in hPa (about 983 on
75//!   its pad), where AltosUI's exports write Pa. No launch site's pressure is below 10 kPa nor
76//!   above 120 kPa, and the two units are a hundredfold apart, so the column's highest value
77//!   settles it: from 10,000 to 120,000, Pa; from 100 to 1,200, hPa, converted with a note;
78//!   anything else is kept as written, [`Quantity::Unrecognized`], with a note.
79//! - *Gaps.* AltosUI writes `NaN` where it has no value (a TeleMega's `tilt` before it has an
80//!   attitude). A cell that is empty or not a finite number is a gap, `NaN`, counted per column
81//!   in a note.
82//! - *Short and long rows.* A row with fewer cells than the header (a file cut off mid-row) has
83//!   the rest as gaps, with a note; a row with more cells is refused, naming its line, unless the
84//!   extra cells are empty (a trailing comma). A row whose time isn't a number can't be placed on
85//!   the clock and is left out, with a note.
86//!
87//! **The states.** AltosUI's exports number the flight's states and name them on each row: 2
88//! `pad`, 3 `boost`, 4 `fast`, 5 `coast`, 6 `drogue`, 7 `main` and 8 `landed`. A row whose
89//! `state` and `state_name` are one of these numbers named as another, or a name numbered as
90//! another, is counted in a note, the first such line quoted, and the events take the names as
91//! written: Debrief's own sample export names state 1 `pad`. (A table cut from an export is
92//! stricter, below.)
93//!
94//! **A spreadsheet's re-save.** A flyer may open an export in a spreadsheet and save it again. The
95//! reader reads three things a spreadsheet leaves:
96//!
97//! - *A unit after a name.* A header may write a unit after a column's name in parentheses, `height
98//!   (m)`. The column is read by its name. Where the unit is the one this reader reads the column
99//!   in (the table above: `s`; `m`; `m/s^2`, `m/s²` or `m/s/s`; `m/s`; `V`; `degrees`, `deg` or
100//!   `°`; `C` or `°C`; `Pa`), it is read as AltOS's, the columns named in one note. Any other
101//!   unit, such as `altitude (ft)` or `accel_x (m/s)`, keeps the column as written,
102//!   [`Quantity::Unrecognized`], with a note: the reader can't tell how its values were made. A
103//!   pressure written `Pa` whose values settle as hPa is kept as written too. A unit after `time`
104//!   other than `s` is refused, as the clock can't be placed.
105//! - *Formulas.* A cell may hold the spreadsheet's formula, such as `=3.28084*J2`, not a value.
106//!   The formulas aren't worked out. A column of formulas alone isn't a channel; a column with
107//!   some has those cells as gaps. Either way the column's formulas are kept as text in a note,
108//!   run by run: a run is rows on consecutive lines whose formula is the same once each reference
109//!   to the cell's own row is written `{row}`, so `=3.28084*J2` on line 2 and `=3.28084*J3` on
110//!   line 3 are one run, `` `=3.28084*J{row}` on lines 2–3 ``, and each cell the note gives can
111//!   be rebuilt from it. A reference is one to three capital letters, an optional `$` and the
112//!   row's number; a CSV a spreadsheet saves writes its row *n* on line *n*. A note gives at most 8 runs a
113//!   column, counting the cells past them, and quotes at most 200 characters of a formula; at
114//!   most 64 columns' formulas are noted, one more note counting the rest.
115//! - *A deleted column.* `height` may be gone, as above.
116//!
117//! **A table cut from an export.** A file may hold AltOS's columns alone: a header of AltOS's own
118//! names with no `#version,serial,flight` before them and no unit after them, naming `time`,
119//! `state` and `state_name`, such as `time,state,state_name,acceleration,pressure,altitude,height`.
120//! Such names alone don't show the file is AltOS's, so its states must: of its first 100 rows, at
121//! least one must give a `state` and a `state_name` that are one of AltOS's pairs, and none may
122//! give a pair that contradicts them ([`recognizes_table`]); a row further on that contradicts
123//! them is refused at its line. Each row is then read as an export's, with a note that the header
124//! was found this way.
125//!
126//! **What the file says about itself.** The serial number and flight number come from the comment
127//! lines `# serial …` and `# flight …` when the file has them, and from the first row's `serial`
128//! and `flight` cells otherwise; `# product …` names the device, as in `AltOS TeleMetrum`. The
129//! file states no firmware version (its `version` column is the data's, kept as a channel), no
130//! apogee and no sample count.
131//!
132//! **Where this comes from.** Ported from Debrief's reader (`lib/parsers/altusmetrum.ts`, MIT, the
133//! project owner's own; see `THIRD-PARTY-NOTICES.md`), which was written from exported files, and
134//! the AltOS manual's description of the export. No AltOS or AltosUI source code was read. Where
135//! this reader departs from Debrief's: it keeps every column as a channel where Debrief keeps a
136//! chosen few; it keeps the file's clock, where Debrief moves the zero to the first row; it reads a
137//! hectopascal pressure as such; it refuses a long row; it requires the header first (after
138//! comment lines), where Debrief searches the first 60 lines for it. The units after names, the
139//! formulas, the record with no `height` and the table cut from an export are this reader's own,
140//! written from the collection's files ([ADR-274][adr-274]). AltOS's radio telemetry is other
141//! files: its log of packets, `.telem` ([`crate::altos_telem`]), and the packets decoded to a
142//! table, `serial,tick,ptype,…` ([`crate::altos_telem_csv`]).
143//!
144//! [adr-274]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0274-the-rest-of-the-importers-planned-teensy-logger-first.md
145
146use crate::error::LogError;
147use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
148use crate::table::finite;
149
150/// The format's name in errors.
151const FORMAT: &str = "AltOS CSV";
152
153/// The most notes about single lines a log keeps; past it, one more note counts the rest.
154const MAX_NOTES: usize = 20;
155
156/// The most characters of the file an error or note quotes.
157const QUOTED_CHARS: usize = 80;
158
159/// What a column of the file is to this reader.
160#[derive(Debug, Clone, Copy, PartialEq)]
161enum Role {
162    /// The `time` column: the clock.
163    Clock,
164    /// Text, not a channel: `call` and `state_name`.
165    Text,
166    /// A channel of this quantity, the file's values as SI.
167    Value(Quantity),
168    /// A temperature in °C, a channel in K.
169    Celsius,
170    /// A pressure, Pa or hPa as the column's values settle.
171    Pressure,
172}
173
174/// A column's role from its name, and whether the reader knows the name. `after_longitude` says
175/// whether a `longitude` column comes before it, which makes an `altitude` the GPS receiver's.
176fn role(name: &str, after_longitude: bool) -> (Role, bool) {
177    use Quantity as Q;
178    let lower = name.to_ascii_lowercase();
179    let value = |quantity| (Role::Value(quantity), true);
180    match lower.as_str() {
181        "time" => (Role::Clock, true),
182        "call" | "state_name" => (Role::Text, true),
183        "height" => value(Q::AltitudeAboveGround),
184        "altitude" if after_longitude => value(Q::GnssAltitude),
185        "altitude" => value(Q::AltitudeMsl),
186        "pressure" => (Role::Pressure, true),
187        "acceleration" | "accel_x" | "accel_y" | "accel_z" => value(Q::Acceleration),
188        "speed" | "accel_speed" | "baro_speed" => value(Q::Speed),
189        "temperature" => (Role::Celsius, true),
190        "battery_voltage" | "drogue_voltage" | "main_voltage" | "pyro" => value(Q::Voltage),
191        "latitude" => value(Q::Latitude),
192        "longitude" => value(Q::Longitude),
193        "tilt" | "pad_az" | "pad_el" => value(Q::Angle),
194        "pad_dist" | "pad_range" => value(Q::Distance),
195        "version" | "serial" | "flight" | "rssi" | "lqi" | "state" | "connected" | "locked"
196        | "nsat" | "year" | "month" | "day" | "hour" | "minute" | "second" | "pdop" | "hdop"
197        | "vdop" => value(Q::Number),
198        "gyro_roll" | "gyro_pitch" | "gyro_yaw" | "mag_x" | "mag_y" | "mag_z" => {
199            value(Q::Unrecognized)
200        }
201        _ if lower.starts_with("igniter_") => value(Q::Voltage),
202        _ if is_satellite(&lower) => value(Q::Number),
203        _ => (Role::Value(Q::Unrecognized), false),
204    }
205}
206
207/// A header cell split into its name and the unit written after it in parentheses, as a
208/// spreadsheet's user wrote `acceleration (m/s^2)`: the unit `None` for a name with none, such as
209/// AltosUI writes.
210fn split_unit(cell: &str) -> (&str, Option<&str>) {
211    match cell
212        .strip_suffix(')')
213        .and_then(|rest| rest.rsplit_once(" ("))
214    {
215        Some((name, unit)) if !name.trim().is_empty() => (name.trim(), Some(unit.trim())),
216        _ => (cell, None),
217    }
218}
219
220/// Whether a unit written after a column's name is the one this reader reads the column's role
221/// in ([`split_unit`]). A pressure's `Pa` must also be the unit its values settle.
222fn unit_agrees(role: Role, unit: &str) -> bool {
223    use Quantity as Q;
224    let units: &[&str] = match role {
225        Role::Clock => &["s"],
226        Role::Value(Q::AltitudeAboveGround | Q::AltitudeMsl | Q::GnssAltitude | Q::Distance) => {
227            &["m"]
228        }
229        Role::Value(Q::Acceleration) => &["m/s^2", "m/s²", "m/s/s"],
230        Role::Value(Q::Speed) => &["m/s"],
231        Role::Value(Q::Voltage) => &["V"],
232        Role::Value(Q::Latitude | Q::Longitude | Q::Angle) => &["degrees", "deg", "°"],
233        Role::Celsius => &["C", "°C"],
234        Role::Pressure => &["Pa"],
235        _ => &[],
236    };
237    units.contains(&unit)
238}
239
240/// The unit a header writes after a column's name, against the one this reader reads it in.
241#[derive(Debug, Clone, Copy, PartialEq)]
242enum Unit {
243    /// None written, as AltosUI writes its header.
244    Unwritten,
245    /// The one this reader reads the column in: the column is read as AltOS's.
246    Agrees,
247    /// Another: the column is kept as written.
248    Differs,
249}
250
251/// Whether a column is one of the receiver's satellite columns, `sat01` to `sat32`.
252fn is_satellite(lower: &str) -> bool {
253    lower
254        .strip_prefix("sat")
255        .is_some_and(|digits| digits.len() == 2 && digits.bytes().all(|b| b.is_ascii_digit()))
256}
257
258/// Notes about single lines as the reader meets them: the first [`MAX_NOTES`] kept, the rest
259/// only counted, so a file of many broken lines can't fill memory with them.
260#[derive(Default)]
261struct Notes {
262    kept: Vec<String>,
263    left_out: usize,
264}
265
266impl Notes {
267    fn push(&mut self, note: String) {
268        if self.kept.len() < MAX_NOTES {
269            self.kept.push(note);
270        } else {
271            self.left_out += 1;
272        }
273    }
274}
275
276/// What the comment lines before the header state.
277#[derive(Default)]
278struct Preamble {
279    product: Option<String>,
280    serial: Option<String>,
281    flight: Option<String>,
282}
283
284/// Reads an AltOS CSV flight log from its text.
285///
286/// # Errors
287///
288/// [`LogError::NotThisFormat`] if the first line that isn't a `#` comment isn't AltOS's header
289/// (`version,serial,flight,…`, with or without a leading `#`) or a header of AltOS's own names
290/// that names `time`, `state` and `state_name`; [`LogError::Syntax`] for a header without a
291/// `time` column, a row with more cells than the header names, a row whose `state` and
292/// `state_name` aren't the number and the name AltOS gives one state, a header-only table none of
293/// whose rows gives a state AltOS's exports name, or a pressure in hPa too large to convert to
294/// pascals; [`LogError::NoData`] if no row has a time.
295pub fn read(text: &str) -> Result<FlightLog, LogError> {
296    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
297    let text = text.replace("\r\n", "\n").replace('\r', "\n");
298    let mut lines = text
299        .lines()
300        .enumerate()
301        .map(|(index, line)| (index + 1, line.trim()));
302
303    let mut preamble = Preamble::default();
304    let mut comments = false;
305    let (header_line, header, bare_table) = loop {
306        match lines.next() {
307            Some((_, "")) => {}
308            Some((number, line)) => {
309                let bare = line.trim_start_matches('#').trim();
310                if is_header(bare) {
311                    break (number, bare, false);
312                }
313                if !comments && is_table_header(line) {
314                    break (number, line, true);
315                }
316                if line.starts_with('#') {
317                    comments = true;
318                    preamble.read(bare);
319                    continue;
320                }
321                return Err(LogError::NotThisFormat {
322                    format: FORMAT,
323                    message: format!(
324                        "line {number}, {:?}, isn't AltOS's header, `version,serial,flight,…`",
325                        short(line)
326                    ),
327                });
328            }
329            None => {
330                return Err(LogError::NotThisFormat {
331                    format: FORMAT,
332                    message: "the file has no `version,serial,flight,…` header".to_owned(),
333                });
334            }
335        }
336    };
337    let names: Vec<String> = header
338        .split(',')
339        .map(|cell| cell.trim().to_owned())
340        .collect();
341    let columns = header_columns(&names, header_line)?;
342
343    let mut notes = Notes::default();
344    let mut table = Table::new(&names, &columns, bare_table);
345    for (number, line) in lines {
346        if line.is_empty() {
347            continue;
348        }
349        if line.starts_with('#') {
350            notes.push(format!(
351                "line {number}, a `#` line among the rows, was skipped"
352            ));
353            continue;
354        }
355        table.row(&columns, line, number, &mut notes)?;
356    }
357    if table.time_s.is_empty() {
358        return Err(LogError::NoData { format: FORMAT });
359    }
360    if bare_table && table.states_checked == 0 {
361        return Err(LogError::Syntax {
362            format: FORMAT,
363            line: header_line,
364            message: "a table of AltOS's columns with no `version,serial,flight` header is read \
365                      by its states. No row's `state` and `state_name` are a state AltOS's \
366                      exports name"
367                .to_owned(),
368        });
369    }
370    assemble(&names, &columns, table, &preamble, notes, bare_table)
371}
372
373/// Whether a line, its `#` taken off, is AltOS's header.
374fn is_header(bare: &str) -> bool {
375    let mut cells = bare.split(',').map(str::trim);
376    ["version", "serial", "flight"].iter().all(|expected| {
377        cells
378            .next()
379            .is_some_and(|cell| cell.eq_ignore_ascii_case(expected))
380    })
381}
382
383/// Whether a line is a header of AltOS's own column names only, as AltosUI writes them, with no
384/// `version,serial,flight` before them and no unit after them, naming `time`, `state` and
385/// `state_name`: a table cut from an AltOS export.
386fn is_table_header(line: &str) -> bool {
387    let names: Vec<&str> = line.split(',').map(str::trim).collect();
388    let mut after_longitude = false;
389    let all_known = names.iter().all(|name| {
390        let known = role(name, after_longitude).1;
391        after_longitude |= name.eq_ignore_ascii_case("longitude");
392        known
393    });
394    all_known
395        && ["time", "state", "state_name"]
396            .iter()
397            .all(|wanted| names.iter().any(|name| name.eq_ignore_ascii_case(wanted)))
398}
399
400/// Whether a text is a table cut from an AltOS export, its header AltOS's own names with no
401/// `version,serial,flight` before them, naming `time`, `state` and `state_name`, and AltOS's
402/// states its proof: of its first 100 rows, at least one gives a `state` and a `state_name` that
403/// AltOS's exports write for one state ([`crate::altos_telem`]), and none gives a pair they
404/// contradict.
405pub fn recognizes_table(text: &str) -> bool {
406    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
407    let mut lines = text
408        .split(['\r', '\n'])
409        .map(str::trim)
410        .filter(|line| !line.is_empty());
411    let Some(header) = lines.next().filter(|line| is_table_header(line)) else {
412        return false;
413    };
414    let names: Vec<&str> = header.split(',').map(str::trim).collect();
415    let find = |wanted: &str| {
416        names
417            .iter()
418            .position(|name| name.eq_ignore_ascii_case(wanted))
419    };
420    let (Some(state), Some(state_name)) = (find("state"), find("state_name")) else {
421        return false;
422    };
423    let mut checked = 0;
424    for line in lines.take(100) {
425        let cells: Vec<&str> = line.split(',').map(str::trim).collect();
426        if let (Some(number), Some(name)) = (cells.get(state), cells.get(state_name)) {
427            match state_pair(number, name) {
428                Ok(true) => checked += 1,
429                Ok(false) => {}
430                Err(_) => return false,
431            }
432        }
433    }
434    checked > 0
435}
436
437/// Whether a row's `state` and `state_name` are a pair AltOS's exports write ([`crate::altos_telem`]):
438/// `Ok(true)` if they are, `Ok(false)` if neither is a state they name, so nothing is checked,
439/// and why not if one is and the other isn't its partner.
440fn state_pair(number: &str, name: &str) -> Result<bool, String> {
441    use crate::altos_telem::STATES;
442    // A number a spreadsheet rewrote, `3.0` for `3`, is the same state.
443    let by_number = number
444        .parse::<f64>()
445        .ok()
446        .and_then(|number| STATES.iter().find(|(known, _)| f64::from(*known) == number));
447    let by_name = STATES
448        .iter()
449        .find(|(_, known)| known.eq_ignore_ascii_case(name));
450    match (by_number, by_name) {
451        (None, None) => Ok(false),
452        (Some(a), Some(b)) if a == b => Ok(true),
453        (Some((known, partner)), _) => Err(format!(
454            "the row's state {known} is named {:?}, where AltOS names {known} `{partner}`",
455            short(name)
456        )),
457        (None, Some((partner, known))) => Err(format!(
458            "the row's state {:?} is named `{known}`, where AltOS numbers `{known}` {partner}",
459            short(number)
460        )),
461    }
462}
463
464impl Preamble {
465    /// Reads a comment line such as `product TeleMetrum`, keeping what names the logger and the
466    /// flight; the rest (`call`, a title) is passed over.
467    fn read(&mut self, bare: &str) {
468        let Some((key, value)) = bare.split_once(char::is_whitespace) else {
469            return;
470        };
471        let value = value.trim();
472        if value.is_empty() {
473            return;
474        }
475        let slot = match key.to_ascii_lowercase().as_str() {
476            "product" => &mut self.product,
477            "serial" => &mut self.serial,
478            "flight" => &mut self.flight,
479            _ => return,
480        };
481        slot.get_or_insert_with(|| short(value));
482    }
483}
484
485/// A column of the header: its role, whether the reader knows its name, and the unit written
486/// after the name.
487#[derive(Debug, Clone, Copy)]
488struct Column {
489    role: Role,
490    known: bool,
491    unit: Unit,
492}
493
494/// The index of the first header cell whose name, less any unit after it, is the one wanted.
495fn named(names: &[String], wanted: &str) -> Option<usize> {
496    names
497        .iter()
498        .position(|name| split_unit(name).0.eq_ignore_ascii_case(wanted))
499}
500
501/// Each header cell's column; refuses a header without `time`.
502fn header_columns(names: &[String], number: usize) -> Result<Vec<Column>, LogError> {
503    let mut after_longitude = false;
504    let mut altitudes = 0;
505    let columns: Vec<Column> = names
506        .iter()
507        .map(|cell| {
508            let (name, unit) = split_unit(cell);
509            let lower = name.to_ascii_lowercase();
510            // A second `altitude` is the GPS receiver's even if no `longitude` precedes it.
511            let gnss = after_longitude || (lower == "altitude" && altitudes > 0);
512            if lower == "altitude" {
513                altitudes += 1;
514            }
515            if lower == "longitude" {
516                after_longitude = true;
517            }
518            let (role, known) = role(name, gnss);
519            match unit {
520                None => Column {
521                    role,
522                    known,
523                    unit: Unit::Unwritten,
524                },
525                Some(unit) if known && unit_agrees(role, unit) => Column {
526                    role,
527                    known,
528                    unit: Unit::Agrees,
529                },
530                Some(_) => Column {
531                    role: if known && role != Role::Text {
532                        Role::Value(Quantity::Unrecognized)
533                    } else {
534                        role
535                    },
536                    known,
537                    unit: Unit::Differs,
538                },
539            }
540        })
541        .collect();
542    match named(names, "time") {
543        Some(index) if columns[index].role == Role::Clock => Ok(columns),
544        Some(_) => Err(LogError::Syntax {
545            format: FORMAT,
546            line: number,
547            message: "the header writes a unit after `time` other than s".to_owned(),
548        }),
549        None => Err(LogError::Syntax {
550            format: FORMAT,
551            line: number,
552            message: "the header names no `time` column".to_owned(),
553        }),
554    }
555}
556
557/// The most runs of formulas a column's note gives one by one ([`Formulas`]); past them the
558/// rest are counted.
559const MAX_FORMULA_RUNS: usize = 8;
560
561/// A run of rows on consecutive lines whose cells in a column hold one formula, its cell
562/// references to its own row written `{row}`: the formula, and the first and last lines of the
563/// run.
564#[derive(Debug, Clone)]
565struct Run {
566    formula: String,
567    first: usize,
568    last: usize,
569}
570
571/// The most characters of a formula a note quotes.
572const FORMULA_CHARS: usize = 200;
573
574/// The most columns of formulas the notes give, apart from the other notes' bound, so that a
575/// note about a column or a line can't push a formula out; past them one note counts the rest.
576const MAX_FORMULA_COLUMNS: usize = 64;
577
578/// A column's formula cells, the runs of them kept as text.
579#[derive(Debug, Clone, Default)]
580struct Formulas {
581    /// The cells that hold a formula.
582    cells: usize,
583    /// The first [`MAX_FORMULA_RUNS`] runs, in the file's order.
584    runs: Vec<Run>,
585    /// The cells of the runs past them.
586    left_out: usize,
587}
588
589impl Formulas {
590    /// Adds a formula cell on a line, the line being the cell's row in the spreadsheet, as a CSV
591    /// a spreadsheet saves writes its row 1 on line 1.
592    fn add(&mut self, cell: &str, line: usize) {
593        self.cells += 1;
594        let formula = cut(&own_row(cell, line), FORMULA_CHARS);
595        if let Some(run) = self.runs.last_mut()
596            && self.left_out == 0
597            && run.formula == formula
598            && line == run.last + 1
599        {
600            run.last = line;
601        } else if self.runs.len() < MAX_FORMULA_RUNS && self.left_out == 0 {
602            self.runs.push(Run {
603                formula,
604                first: line,
605                last: line,
606            });
607        } else {
608            self.left_out += 1;
609        }
610    }
611}
612
613/// A formula with each cell reference to its own row, such as `J2` in row 2's `=3.28*J2`, written
614/// `J{row}`: a reference is one to three letters, an optional `$`, and the row's number, with no
615/// letter or digit before it and none, nor a `(`, after it, so a function such as `LOG10(` isn't
616/// one.
617fn own_row(formula: &str, row: usize) -> String {
618    let row = row.to_string();
619    let bytes = formula.as_bytes();
620    let mut out = String::with_capacity(formula.len());
621    let mut at = 0;
622    while at < bytes.len() {
623        let letters = bytes[at..]
624            .iter()
625            .take_while(|b| b.is_ascii_uppercase())
626            .count();
627        let starts = at == 0 || !bytes[at - 1].is_ascii_alphanumeric();
628        if letters == 0 {
629            // Copies one character, whole.
630            let next = formula[at..].chars().next().map_or(1, char::len_utf8);
631            out.push_str(&formula[at..at + next]);
632            at += next;
633            continue;
634        }
635        if !starts {
636            // Copies the run of capitals whole: none of them starts a reference, as each follows
637            // a letter or digit. Stepping one at a time would count the run's rest again at each,
638            // in time growing as the square of its length.
639            out.push_str(&formula[at..at + letters]);
640            at += letters;
641            continue;
642        }
643        let mut end = at + letters;
644        let dollar = bytes.get(end) == Some(&b'$');
645        if dollar {
646            end += 1;
647        }
648        let digits = bytes[end..]
649            .iter()
650            .take_while(|b| b.is_ascii_digit())
651            .count();
652        let after = bytes.get(end + digits);
653        let ends = after.is_none_or(|b| !b.is_ascii_alphanumeric() && *b != b'(');
654        if letters <= 3 && digits > 0 && ends && formula[end..end + digits] == row {
655            out.push_str(&formula[at..end]);
656            out.push_str("{row}");
657        } else {
658            out.push_str(&formula[at..end + digits]);
659        }
660        at = end + digits;
661    }
662    out
663}
664
665/// The rows read so far, column by column.
666struct Table {
667    /// Each kept row's time, in the file's order.
668    time_s: Vec<f64>,
669    /// Each kept row's line in the file.
670    lines: Vec<usize>,
671    /// Each column's values, row by row, as written (no unit converted yet); empty for the clock
672    /// and text columns.
673    values: Vec<Vec<f64>>,
674    /// Each column's count of cells that were empty or not a finite number, formulas apart.
675    gaps: Vec<usize>,
676    /// Each column's formula cells.
677    formulas: Vec<Formulas>,
678    /// Each kept row's `state_name`, if the file has the column.
679    states: Vec<String>,
680    /// The index of the `time` column.
681    clock: usize,
682    /// The indices of the `state` and `state_name` columns.
683    state: Option<usize>,
684    state_name: Option<usize>,
685    /// The rows whose `state` and `state_name` are a pair AltOS's exports write.
686    states_checked: usize,
687    /// Whether the header is a table's with no `version,serial,flight` ([`is_table_header`]),
688    /// whose states are the proof that it is AltOS's: a row contradicting them is refused.
689    bare: bool,
690    /// Otherwise, the rows whose `state` and `state_name` contradict AltOS's pair, and the first
691    /// of them, its line and why.
692    states_differing: usize,
693    first_differing: Option<String>,
694    /// The indices of the `serial` and `flight` columns.
695    serial: Option<usize>,
696    flight: Option<usize>,
697    /// The first kept row's `serial` and `flight` cells, as written.
698    first_serial: Option<String>,
699    first_flight: Option<String>,
700    /// The rows read so far, and the cells they wrote, for [`crate::log::too_sparse`].
701    rows: usize,
702    cells_written: usize,
703}
704
705impl Table {
706    fn new(names: &[String], columns: &[Column], bare: bool) -> Self {
707        Self {
708            time_s: Vec::new(),
709            lines: Vec::new(),
710            values: vec![Vec::new(); columns.len()],
711            gaps: vec![0; columns.len()],
712            formulas: vec![Formulas::default(); columns.len()],
713            states: Vec::new(),
714            // `header_columns` has refused a header without a `time` column.
715            clock: named(names, "time").unwrap_or(0),
716            state: named(names, "state"),
717            state_name: named(names, "state_name"),
718            states_checked: 0,
719            bare,
720            states_differing: 0,
721            first_differing: None,
722            serial: named(names, "serial"),
723            flight: named(names, "flight"),
724            first_serial: None,
725            first_flight: None,
726            rows: 0,
727            cells_written: 0,
728        }
729    }
730
731    /// Reads one data row.
732    fn row(
733        &mut self,
734        columns: &[Column],
735        line: &str,
736        number: usize,
737        notes: &mut Notes,
738    ) -> Result<(), LogError> {
739        let cells: Vec<&str> = line.split(',').map(str::trim).collect();
740        if cells.len() > columns.len() && cells[columns.len()..].iter().any(|c| !c.is_empty()) {
741            return Err(LogError::Syntax {
742                format: FORMAT,
743                line: number,
744                message: format!(
745                    "the row has {} cells and the header names {}",
746                    cells.len(),
747                    columns.len()
748                ),
749            });
750        }
751        let cell = |index: Option<usize>| index.and_then(|index| cells.get(index).copied());
752        let Some(time) = cell(Some(self.clock)).and_then(number_in) else {
753            notes.push(format!(
754                "line {number} has no time and was left out: {:?}",
755                short(line)
756            ));
757            return Ok(());
758        };
759        if let (Some(state), Some(name)) = (cell(self.state), cell(self.state_name)) {
760            match state_pair(state, name) {
761                Ok(checked) => self.states_checked += usize::from(checked),
762                Err(message) if self.bare => {
763                    return Err(LogError::Syntax {
764                        format: FORMAT,
765                        line: number,
766                        message,
767                    });
768                }
769                Err(message) => {
770                    self.states_differing += 1;
771                    self.first_differing
772                        .get_or_insert_with(|| format!("line {number}: {message}"));
773                }
774            }
775        }
776        self.rows += 1;
777        self.cells_written += cells.len().min(columns.len());
778        if crate::log::too_sparse(columns.len(), self.rows, self.cells_written) {
779            return Err(LogError::Syntax {
780                format: FORMAT,
781                line: number,
782                message: format!(
783                    "{} rows hold {} of the {} cells the header's {} columns name: too few for \
784                     the header to be this file's",
785                    self.rows,
786                    self.cells_written,
787                    self.rows.saturating_mul(columns.len()),
788                    columns.len()
789                ),
790            });
791        }
792        if cells.len() < columns.len() {
793            notes.push(format!(
794                "line {number} has {} cells of the header's {}; the rest read as gaps",
795                cells.len(),
796                columns.len()
797            ));
798        }
799        if self.time_s.is_empty() {
800            self.first_serial = cell(self.serial).filter(|s| !s.is_empty()).map(short);
801            self.first_flight = cell(self.flight).filter(|s| !s.is_empty()).map(short);
802        }
803        self.time_s.push(time);
804        self.lines.push(number);
805        for (index, column) in columns.iter().enumerate() {
806            if matches!(column.role, Role::Clock | Role::Text) {
807                continue;
808            }
809            // A cell a short row leaves out is a gap its row's note counts, not the column's; a
810            // formula is text, kept in its column's note.
811            let value = match cells.get(index) {
812                Some(cell) if cell.starts_with('=') => {
813                    self.formulas[index].add(cell, number);
814                    f64::NAN
815                }
816                Some(cell) => number_in(cell).unwrap_or_else(|| {
817                    self.gaps[index] += 1;
818                    f64::NAN
819                }),
820                None => f64::NAN,
821            };
822            self.values[index].push(value);
823        }
824        if self.state_name.is_some() {
825            self.states
826                .push(cell(self.state_name).map(short).unwrap_or_default());
827        }
828        Ok(())
829    }
830}
831
832/// A cell's value: a finite number, or `None`.
833fn number_in(cell: &str) -> Option<f64> {
834    cell.parse::<f64>().ok().filter(|value| value.is_finite())
835}
836
837/// The lowest of a pad's pressures, Pa, that this reader takes a column for: below any launch
838/// site, and a hundred times the highest pressure in hPa below.
839const PASCAL_LOW: f64 = 10_000.0;
840/// The highest pressure, Pa, that this reader takes a column for: above any on Earth's surface.
841const PASCAL_HIGH: f64 = 120_000.0;
842
843/// How a pressure column's values read, from its highest: Pa (a factor of 1), hPa (100), or
844/// neither (`None`).
845fn pressure_factor(values: &[f64]) -> Option<f64> {
846    let highest = values
847        .iter()
848        .copied()
849        .filter(|value| value.is_finite())
850        .fold(f64::NEG_INFINITY, f64::max);
851    if (PASCAL_LOW..=PASCAL_HIGH).contains(&highest) {
852        Some(1.0)
853    } else if (PASCAL_LOW / 100.0..=PASCAL_HIGH / 100.0).contains(&highest) {
854        Some(100.0)
855    } else {
856        None
857    }
858}
859
860/// A column's formulas as a note gives them: each run's formula and its lines, then any cells
861/// past the runs given.
862fn formula_runs(formulas: &Formulas) -> String {
863    let mut runs: Vec<String> = formulas
864        .runs
865        .iter()
866        .map(|run| {
867            let cells = run.last - run.first + 1;
868            let lines = if cells == 1 {
869                format!("line {}", run.first)
870            } else {
871                format!("lines {}–{}", run.first, run.last)
872            };
873            format!("`{}` on {lines}", run.formula)
874        })
875        .collect();
876    if formulas.left_out > 0 {
877        runs.push(format!(
878            "{} more past them",
879            count(formulas.left_out, "cell")
880        ));
881    }
882    runs.join("; ")
883}
884
885/// Builds the log from the rows.
886///
887/// # Errors
888///
889/// [`LogError::Syntax`] for a pressure in hPa that the factor of 100 makes infinite.
890fn assemble(
891    names: &[String],
892    columns: &[Column],
893    mut table: Table,
894    preamble: &Preamble,
895    line_notes: Notes,
896    bare_table: bool,
897) -> Result<FlightLog, LogError> {
898    let mut notes: Vec<String> = Vec::new();
899    let mut column_notes = Notes::default();
900    let n = table.time_s.len();
901    // A column by its name, and its role: a unit written after the name that differs from this
902    // reader's makes the column another's.
903    let find = |wanted: &str, role: Role| {
904        named(names, wanted).filter(|&index| columns[index].role == role)
905    };
906    if let Some(first) = &table.first_differing {
907        notes.push(format!(
908            "{} a `state` and a `state_name` that aren't the pair AltOS's exports write, the \
909             first at {first}; the events take the names as written",
910            match table.states_differing {
911                1 => "1 row gives".to_owned(),
912                n => format!("{n} rows give"),
913            }
914        ));
915    }
916    if bare_table {
917        notes.push(format!(
918            "the header names AltOS's columns with no `version,serial,flight` before them. The \
919             table is read as AltOS's, as {} give a `state` and a `state_name` that AltOS's exports \
920             write for one state, and none contradicts them",
921            count(table.states_checked, "row")
922        ));
923    }
924
925    // GPS positions of exactly (0, 0) are the receiver's before a fix.
926    if let (Some(lat), Some(lon)) = (
927        find("latitude", Role::Value(Quantity::Latitude)),
928        find("longitude", Role::Value(Quantity::Longitude)),
929    ) {
930        let gnss: Vec<usize> = (0..columns.len())
931            .filter(|&index| columns[index].role == Role::Value(Quantity::GnssAltitude))
932            .collect();
933        let mut blanked = 0;
934        for row in 0..n {
935            if table.values[lat][row] == 0.0 && table.values[lon][row] == 0.0 {
936                blanked += 1;
937                for &index in gnss.iter().chain([&lat, &lon]) {
938                    table.values[index][row] = f64::NAN;
939                }
940            }
941        }
942        if blanked > 0 {
943            notes.push(format!(
944                "{} placing the GPS at latitude 0, longitude 0 (AltOS's position before its \
945                 receiver has a fix). Their latitude, longitude and GPS altitude read as gaps",
946                count(blanked, "row")
947            ));
948        }
949    }
950
951    let mut channels = Vec::with_capacity(columns.len());
952    let mut converted: Vec<Option<Vec<f64>>> = vec![None; columns.len()];
953    let mut units_agreeing = Vec::new();
954    let mut formula_notes: Vec<String> = Vec::new();
955    let mut formula_columns_left_out = 0;
956    let mut formula_note = |note: String| {
957        if formula_notes.len() < MAX_FORMULA_COLUMNS {
958            formula_notes.push(note);
959        } else {
960            formula_columns_left_out += 1;
961        }
962    };
963    for (index, column) in columns.iter().enumerate() {
964        let name = &names[index];
965        let mut values = std::mem::take(&mut table.values[index]);
966        let formulas = &table.formulas[index];
967        if formulas.cells > 0 && formulas.cells == n {
968            // Every cell a formula: text, not a channel.
969            formula_note(format!(
970                "the `{}` column's {} a spreadsheet's {}, not {}. The column is not a channel. \
971                 Each formula is kept here as text, not worked out. `{{row}}` stands for each \
972                 cell's own row: {}",
973                short(name),
974                match formulas.cells {
975                    1 => "1 cell is".to_owned(),
976                    cells => format!("{cells} cells are"),
977                },
978                if formulas.cells == 1 {
979                    "formula"
980                } else {
981                    "formulas"
982                },
983                if formulas.cells == 1 {
984                    "a value"
985                } else {
986                    "values"
987                },
988                formula_runs(formulas)
989            ));
990            continue;
991        }
992        if formulas.cells > 0 {
993            formula_note(format!(
994                "the `{}` column has {} holding a spreadsheet's formula, not a value. The cells \
995                 read as gaps, and the formulas are kept here as text. `{{row}}` stands for \
996                 each cell's own row: {}",
997                short(name),
998                count(formulas.cells, "cell"),
999                formula_runs(formulas)
1000            ));
1001        }
1002        let quantity = match column.role {
1003            Role::Clock | Role::Text => continue,
1004            Role::Value(quantity) => quantity,
1005            Role::Celsius => {
1006                for value in &mut values {
1007                    *value += 273.15;
1008                }
1009                Quantity::Temperature
1010            }
1011            Role::Pressure => match pressure_factor(&values) {
1012                Some(factor) if factor != 1.0 && column.unit == Unit::Agrees => {
1013                    notes.push(format!(
1014                        "the `{}` column states Pa, but its highest value is a pad's pressure \
1015                         in hPa; it is kept as written",
1016                        short(name)
1017                    ));
1018                    Quantity::Unrecognized
1019                }
1020                Some(factor) => {
1021                    if factor != 1.0 {
1022                        // A finite cell that the factor makes infinite, such as `-1.7e308` hPa,
1023                        // is refused on its row's line (ADR-258 §3).
1024                        for (value, &line) in values.iter_mut().zip(&table.lines) {
1025                            *value = finite(*value * factor, FORMAT, line, name)?;
1026                        }
1027                        notes.push(format!(
1028                            "the `{}` column never reaches 1,200 and was read as hPa, not Pa",
1029                            short(name)
1030                        ));
1031                    }
1032                    Quantity::Pressure
1033                }
1034                None => {
1035                    notes.push(format!(
1036                        "the `{}` column's highest value isn't a pad's pressure in Pa or hPa; it \
1037                         is kept as written",
1038                        short(name)
1039                    ));
1040                    Quantity::Unrecognized
1041                }
1042            },
1043        };
1044        match column.unit {
1045            Unit::Unwritten => {}
1046            Unit::Agrees => units_agreeing.push(format!("`{}`", short(name))),
1047            Unit::Differs if column.known => column_notes.push(format!(
1048                "the header writes `{}`, a unit after AltOS's `{}` that isn't the one this \
1049                 reader reads it in; its values are kept as written",
1050                short(name),
1051                short(split_unit(name).0)
1052            )),
1053            Unit::Differs => {}
1054        }
1055        if !column.known {
1056            column_notes.push(format!(
1057                "the column `{}` isn't one this reader knows; its values are kept as written",
1058                short(name)
1059            ));
1060        }
1061        if table.gaps[index] > 0 {
1062            column_notes.push(format!(
1063                "the `{}` column has {} empty or not a number (AltosUI writes `NaN` where it \
1064                 has no value), read as gaps",
1065                short(name),
1066                count(table.gaps[index], "cell")
1067            ));
1068        }
1069        converted[index] = Some(values.clone());
1070        channels.push(Channel {
1071            column: name.clone(),
1072            quantity,
1073            time_s: table.time_s.clone(),
1074            values,
1075        });
1076    }
1077    if !units_agreeing.is_empty() {
1078        notes.push(format!(
1079            "the header writes a unit after AltOS's name of {}: each the unit this reader reads \
1080             the column in, so read as AltOS's",
1081            units_agreeing.join(", ")
1082        ));
1083    }
1084    if find("acceleration", Role::Value(Quantity::Acceleration)).is_some() {
1085        notes.push(
1086            "AltOS writes `acceleration` with gravity taken out: it reads about 0 at rest, not \
1087             1 g; the channel is kept as written"
1088                .to_owned(),
1089        );
1090    }
1091
1092    // The primary track: in time order, the first row at each time; none without a `height`, or
1093    // with one of formulas alone, which isn't a channel.
1094    let named_height = find("height", Role::Value(Quantity::AltitudeAboveGround));
1095    let height = named_height.filter(|&index| converted[index].is_some());
1096    let mut order: Vec<usize> = (0..n).collect();
1097    order.sort_by(|&a, &b| table.time_s[a].total_cmp(&table.time_s[b]));
1098    let mut latest = f64::NEG_INFINITY;
1099    let out_of_order = table
1100        .time_s
1101        .iter()
1102        .filter(|&&time| {
1103            let early = time < latest;
1104            latest = latest.max(time);
1105            early
1106        })
1107        .count();
1108    let mut kept: Vec<usize> = Vec::with_capacity(n);
1109    for row in order {
1110        match kept.last() {
1111            Some(&last) if table.time_s[last] == table.time_s[row] => {}
1112            _ => kept.push(row),
1113        }
1114    }
1115    if height.is_none() {
1116        kept.clear();
1117        notes.push(if named_height.is_some() {
1118            "the `height` column, AltOS's height above the pad, holds a spreadsheet's formulas \
1119             alone: the record has no primary track, only its channels"
1120                .to_owned()
1121        } else {
1122            "the header names no `height`, AltOS's height above the pad: the record has no \
1123             primary track, only its channels"
1124                .to_owned()
1125        });
1126    } else {
1127        if out_of_order > 0 {
1128            notes.push(format!(
1129                "{} coming before an earlier row's time: the primary track takes the rows in \
1130                 time order; the channels keep the file's",
1131                count(out_of_order, "row")
1132            ));
1133        }
1134        if kept.len() < n {
1135            notes.push(format!(
1136                "{} repeating an earlier row's time: the primary track keeps the first row at \
1137                 each time; the channels keep every row",
1138                count(n - kept.len(), "row")
1139            ));
1140        }
1141    }
1142    let primary = |index: Option<usize>| {
1143        index
1144            .filter(|_| height.is_some())
1145            .and_then(|index| converted[index].as_ref())
1146            .map(|values| kept.iter().map(|&row| values[row]).collect::<Vec<f64>>())
1147    };
1148    // The primary track is barometric: `accel_speed` integrates the accelerometer, and `speed`
1149    // is the flight computer's own estimate, which uses its accelerometer on the way up.
1150    let speed = find("baro_speed", Role::Value(Quantity::Speed));
1151
1152    let mut events: Vec<Event> = Vec::new();
1153    let mut state: Option<&str> = None;
1154    for (row, name) in table.states.iter().enumerate() {
1155        if !name.is_empty() && state != Some(name.as_str()) {
1156            events.push(Event {
1157                time_s: table.time_s[row],
1158                name: name.clone(),
1159            });
1160            state = Some(name.as_str());
1161        }
1162    }
1163
1164    let serial_number = preamble
1165        .serial
1166        .clone()
1167        .or_else(|| table.first_serial.clone());
1168    if let (Some(stated), Some(written)) = (&preamble.serial, &table.first_serial)
1169        && stated != written
1170    {
1171        notes.push(format!(
1172            "the comment lines give the serial number as {stated:?} and the rows as {written:?}; \
1173             the comment lines' is kept"
1174        ));
1175    }
1176    let flight = preamble.flight.as_ref().or(table.first_flight.as_ref());
1177    let flight_number = flight.and_then(|flight| flight.parse().ok());
1178    if flight.is_some() && flight_number.is_none() {
1179        notes.push(format!(
1180            "the flight number {:?} isn't a whole number and was left out",
1181            flight.map(String::as_str).unwrap_or_default()
1182        ));
1183    }
1184
1185    notes.extend(formula_notes);
1186    if formula_columns_left_out > 0 {
1187        notes.push(format!(
1188            "and {} holding formulas, past the {MAX_FORMULA_COLUMNS} whose formulas are given",
1189            count(formula_columns_left_out, "more column")
1190        ));
1191    }
1192    notes.extend(column_notes.kept);
1193    notes.extend(line_notes.kept);
1194    let left_out = column_notes.left_out + line_notes.left_out;
1195    if left_out > 0 {
1196        notes.push(format!(
1197            "and {left_out} more notes about single columns and lines, left out so that a \
1198             broken file's list stays short"
1199        ));
1200    }
1201
1202    Ok(FlightLog {
1203        format: LogFormat::AltosCsv,
1204        logger: match &preamble.product {
1205            Some(product) => format!("AltOS {product}"),
1206            None => "AltOS".to_owned(),
1207        },
1208        serial_number,
1209        firmware: None,
1210        flight_number,
1211        stated: Stated::default(),
1212        time_s: kept.iter().map(|&row| table.time_s[row]).collect(),
1213        altitude_m: primary(height).unwrap_or_default(),
1214        vertical_speed_m_s: primary(speed),
1215        temperature_k: primary(find("temperature", Role::Celsius)),
1216        battery_v: primary(find("battery_voltage", Role::Value(Quantity::Voltage))),
1217        channels,
1218        events,
1219        notes,
1220    })
1221}
1222
1223/// A count and its noun, such as `1 row` or `3 rows`.
1224fn count(n: usize, noun: &str) -> String {
1225    if n == 1 {
1226        format!("1 {noun}")
1227    } else {
1228        format!("{n} {noun}s")
1229    }
1230}
1231
1232/// Text from the file as an error or note quotes it: cut to [`QUOTED_CHARS`] characters, so a
1233/// binary file's "first line" doesn't fill the message.
1234fn short(text: &str) -> String {
1235    cut(text, QUOTED_CHARS)
1236}
1237
1238/// Text cut to a number of characters, its last a `…` where it is cut.
1239fn cut(text: &str, chars: usize) -> String {
1240    if text.chars().count() <= chars {
1241        text.to_owned()
1242    } else {
1243        let mut cut: String = text.chars().take(chars - 1).collect();
1244        cut.push('…');
1245        cut
1246    }
1247}
1248
1249#[cfg(test)]
1250mod tests {
1251    use super::*;
1252
1253    const HEAD: &str = "#version,serial,flight,call,time,rssi,lqi,state,state_name,acceleration,\
1254                        pressure,altitude,height,baro_speed,temperature,battery_voltage\n";
1255
1256    /// A row, its state's number the one AltOS's exports give its name.
1257    fn row(time: f64, state: &str, height: f64) -> String {
1258        let number = crate::altos_telem::STATES
1259            .iter()
1260            .find(|(_, name)| *name == state)
1261            .map_or(2, |(number, _)| *number);
1262        format!(
1263            "6, 77, 4,N0CALL, {time:8.2}, -80, 40, {number}, {state:>7}, 0.10, 98000.00, \
1264             {:.2}, {height:.2}, 1.50, 20.0, 3.90\n",
1265            250.0 + height
1266        )
1267    }
1268
1269    /// Every column a channel in the file's order, but the clock and the text; the primary
1270    /// track from `height`, `baro_speed`, `temperature` and `battery_voltage`, in SI.
1271    #[test]
1272    fn reads_columns_and_the_primary_track() {
1273        let text = format!("{HEAD}{}{}", row(-0.5, "pad", 0.0), row(0.0, "boost", 1.25));
1274        let log = read(&text).unwrap();
1275        assert_eq!(log.format, LogFormat::AltosCsv);
1276        assert_eq!(log.logger, "AltOS");
1277        assert_eq!(log.serial_number.as_deref(), Some("77"));
1278        assert_eq!(log.flight_number, Some(4));
1279        assert_eq!(log.firmware, None);
1280        assert_eq!(log.time_s, [-0.5, 0.0]);
1281        assert_eq!(log.altitude_m, [0.0, 1.25]);
1282        assert_eq!(log.vertical_speed_m_s.as_deref(), Some(&[1.5, 1.5][..]));
1283        assert_eq!(log.temperature_k.as_deref(), Some(&[293.15, 293.15][..]));
1284        assert_eq!(log.battery_v.as_deref(), Some(&[3.9, 3.9][..]));
1285        let names: Vec<&str> = log.channels.iter().map(|c| c.column.as_str()).collect();
1286        assert_eq!(
1287            names,
1288            [
1289                "version",
1290                "serial",
1291                "flight",
1292                "rssi",
1293                "lqi",
1294                "state",
1295                "acceleration",
1296                "pressure",
1297                "altitude",
1298                "height",
1299                "baro_speed",
1300                "temperature",
1301                "battery_voltage"
1302            ]
1303        );
1304        let pressure = log.channels_of(Quantity::Pressure).next().unwrap();
1305        assert_eq!(pressure.values, [98000.0, 98000.0]);
1306        assert_eq!(log.channels_of(Quantity::AltitudeMsl).count(), 1);
1307        assert_eq!(
1308            log.events,
1309            [
1310                Event {
1311                    time_s: -0.5,
1312                    name: "pad".to_owned()
1313                },
1314                Event {
1315                    time_s: 0.0,
1316                    name: "boost".to_owned()
1317                }
1318            ]
1319        );
1320        assert_eq!(log.notes.len(), 1, "{:?}", log.notes);
1321        assert!(log.notes[0].contains("gravity taken out"));
1322    }
1323
1324    /// The second `altitude`, after `longitude`, is the GPS receiver's; a (0, 0) position is
1325    /// no fix, and its row's latitude, longitude and GPS altitude are gaps.
1326    #[test]
1327    fn the_second_altitude_is_the_gps_and_zero_zero_is_no_fix() {
1328        let text = "#version,serial,flight,time,state_name,altitude,height,latitude,longitude,\
1329                    altitude,nsat,sat01,pad_dist,pad_az,tilt,gyro_roll\n\
1330                    6,1,1,0.0,pad,250,0,0,0,0,0,0,0,0,NaN,1\n\
1331                    6,1,1,0.5,pad,250,0,40.5,-105.25,251.5,7,31,3,90,2.5,1\n";
1332        let log = read(text).unwrap();
1333        let quantities: Vec<Quantity> = log.channels.iter().map(|c| c.quantity).collect();
1334        use Quantity as Q;
1335        assert_eq!(
1336            quantities,
1337            [
1338                Q::Number,
1339                Q::Number,
1340                Q::Number,
1341                Q::AltitudeMsl,
1342                Q::AltitudeAboveGround,
1343                Q::Latitude,
1344                Q::Longitude,
1345                Q::GnssAltitude,
1346                Q::Number,
1347                Q::Number,
1348                Q::Distance,
1349                Q::Angle,
1350                Q::Angle,
1351                Q::Unrecognized
1352            ]
1353        );
1354        let gnss = log.channels_of(Q::GnssAltitude).next().unwrap();
1355        assert_eq!(gnss.column, "altitude");
1356        assert!(gnss.values[0].is_nan());
1357        assert_eq!(gnss.values[1], 251.5);
1358        let latitude = log.channels_of(Q::Latitude).next().unwrap();
1359        assert!(latitude.values[0].is_nan());
1360        assert_eq!(latitude.values[1], 40.5);
1361        // The barometric altitude on the same row is untouched.
1362        let baro = log.channels_of(Q::AltitudeMsl).next().unwrap();
1363        assert_eq!(baro.values, [250.0, 250.0]);
1364        assert!(
1365            log.notes
1366                .iter()
1367                .any(|n| n.starts_with("1 row placing the GPS")),
1368            "{:?}",
1369            log.notes
1370        );
1371        assert!(
1372            log.notes
1373                .iter()
1374                .any(|n| n.contains("`tilt` column has 1 cell empty")),
1375            "{:?}",
1376            log.notes
1377        );
1378        // No speed, temperature or battery column: none on the primary track.
1379        assert!(log.vertical_speed_m_s.is_none() && log.temperature_k.is_none());
1380        assert!(log.battery_v.is_none());
1381    }
1382
1383    /// Repeated times: the primary track keeps the first row at each, the channels every row.
1384    /// Rows out of order are put in order on the primary track, and both are noted.
1385    #[test]
1386    fn repeated_and_reordered_times() {
1387        let text = format!(
1388            "{HEAD}{}{}{}{}",
1389            row(0.0, "pad", 0.0),
1390            row(0.5, "boost", 5.0),
1391            row(0.5, "boost", 6.0),
1392            row(0.25, "boost", 2.0)
1393        );
1394        let log = read(&text).unwrap();
1395        assert_eq!(log.time_s, [0.0, 0.25, 0.5]);
1396        assert_eq!(log.altitude_m, [0.0, 2.0, 5.0]);
1397        let height = log
1398            .channels_of(Quantity::AltitudeAboveGround)
1399            .next()
1400            .unwrap();
1401        assert_eq!(height.time_s, [0.0, 0.5, 0.5, 0.25]);
1402        assert_eq!(height.values, [0.0, 5.0, 6.0, 2.0]);
1403        assert!(
1404            log.notes
1405                .iter()
1406                .any(|n| n.starts_with("1 row coming before")),
1407            "{:?}",
1408            log.notes
1409        );
1410        assert!(
1411            log.notes.iter().any(|n| n.starts_with("1 row repeating")),
1412            "{:?}",
1413            log.notes
1414        );
1415        // One event per change of state, in the file's order.
1416        let names: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
1417        assert_eq!(names, ["pad", "boost"]);
1418    }
1419
1420    /// Comment lines before a header without `#`: product, serial and flight from them.
1421    #[test]
1422    fn comment_lines_name_the_logger() {
1423        let text = "\u{feff}# Altus Metrum flight log\r\n# product TeleMetrum\r\n# serial 2001\r\n\
1424                    # flight 3\r\n# call N0CALL\r\nversion,serial,flight,time,state_name,height\r\n\
1425                    5,2002,3,0.00,pad,0.0\r\n";
1426        let log = read(text).unwrap();
1427        assert_eq!(log.logger, "AltOS TeleMetrum");
1428        assert_eq!(log.serial_number.as_deref(), Some("2001"));
1429        assert_eq!(log.flight_number, Some(3));
1430        assert!(
1431            log.notes
1432                .iter()
1433                .any(|n| n.contains("\"2001\" and the rows as \"2002\"")),
1434            "{:?}",
1435            log.notes
1436        );
1437    }
1438
1439    /// A pressure near the lowest `f64`, in a column read as hPa, is finite as written and
1440    /// infinite in pascals: refused on its line (ADR-258 §3).
1441    #[test]
1442    fn a_value_its_conversion_makes_infinite_is_refused() {
1443        let head = "#version,serial,flight,time,state_name,pressure,height\n";
1444        let text = format!("{head}5,1,1,0,pad,983.25,0\n5,1,1,1,pad,-1.7e308,10\n");
1445        assert_eq!(
1446            read(&text).unwrap_err().to_string(),
1447            "AltOS CSV line 3: the column pressure holds a value too large for its unit's \
1448             conversion to SI"
1449        );
1450    }
1451
1452    /// A pressure column in hPa is converted; one that is neither Pa nor hPa is kept as written.
1453    #[test]
1454    fn pressure_unit_from_its_highest_value() {
1455        let head = "#version,serial,flight,time,state_name,pressure,height\n";
1456        let log = read(&format!(
1457            "{head}5,1,1,0,pad,983.25,0\n5,1,1,1,pad,950.5,10\n"
1458        ))
1459        .unwrap();
1460        let pressure = log.channels_of(Quantity::Pressure).next().unwrap();
1461        assert_eq!(pressure.values, [98325.0, 95050.0]);
1462        assert!(
1463            log.notes.iter().any(|n| n.contains("read as hPa")),
1464            "{:?}",
1465            log.notes
1466        );
1467
1468        let log = read(&format!("{head}5,1,1,0,pad,98.3,0\n")).unwrap();
1469        assert_eq!(log.channels_of(Quantity::Pressure).count(), 0);
1470        let kept = log
1471            .channels
1472            .iter()
1473            .find(|c| c.column == "pressure")
1474            .unwrap();
1475        assert_eq!(
1476            (kept.quantity, kept.values[0]),
1477            (Quantity::Unrecognized, 98.3)
1478        );
1479
1480        // The boundaries: 1,200 hPa and 10,000 Pa are each still their unit.
1481        assert_eq!(pressure_factor(&[1200.0, f64::NAN]), Some(100.0));
1482        assert_eq!(pressure_factor(&[10_000.0]), Some(1.0));
1483        assert_eq!(pressure_factor(&[120_000.0]), Some(1.0));
1484        assert_eq!(pressure_factor(&[1200.5]), None);
1485        assert_eq!(pressure_factor(&[120_000.5]), None);
1486        assert_eq!(pressure_factor(&[f64::NAN]), None);
1487    }
1488
1489    /// Short rows have gaps; a long row of empty cells is a trailing comma; a row with no time
1490    /// is left out; an unknown column is kept and noted.
1491    #[test]
1492    fn odd_rows_and_columns() {
1493        let text = "#version,serial,flight,time,state_name,height,widget\n\
1494                    6,1,1,0.0,pad,0,5,,\n\
1495                    6,1,1,,pad,0,5\n\
1496                    6,1,1,1.0,boost,3\n";
1497        let log = read(text).unwrap();
1498        assert_eq!(log.time_s, [0.0, 1.0]);
1499        let widget = log.channels.iter().find(|c| c.column == "widget").unwrap();
1500        assert_eq!(widget.quantity, Quantity::Unrecognized);
1501        assert_eq!(widget.values[0], 5.0);
1502        assert!(widget.values[1].is_nan());
1503        let expected = [
1504            "the column `widget` isn't one this reader knows",
1505            "line 3 has no time and was left out",
1506            "line 4 has 6 cells of the header's 7",
1507        ];
1508        for text in expected {
1509            assert!(
1510                log.notes.iter().any(|n| n.starts_with(text)),
1511                "{text}: {:?}",
1512                log.notes
1513            );
1514        }
1515        // The short row's missing cell is counted by its line's note, not as the column's gap.
1516        assert_eq!(log.notes.len(), expected.len(), "{:?}", log.notes);
1517    }
1518
1519    /// A file of many broken rows keeps a short list of notes and counts the rest.
1520    #[test]
1521    fn notes_stay_few() {
1522        let text = format!(
1523            "#version,serial,flight,time,height\n{}0,1,1,0,0\n",
1524            "0,1,1,x,0\n".repeat(1000)
1525        );
1526        let log = read(&text).unwrap();
1527        assert_eq!(log.notes.len(), MAX_NOTES + 1);
1528        assert!(
1529            log.notes[MAX_NOTES].starts_with("and 980 more notes"),
1530            "{:?}",
1531            log.notes
1532        );
1533    }
1534
1535    /// Each refusal says what is wrong, and where.
1536    #[test]
1537    fn malformed_files_are_refused() {
1538        let cases = [
1539            ("", "not read as AltOS CSV: the file has no"),
1540            ("# just a comment\n", "has no `version,serial,flight"),
1541            (
1542                "time,height\n0,0\n",
1543                "line 1, \"time,height\", isn't AltOS's header",
1544            ),
1545            ("PerfectFlite Pnut\n", "isn't AltOS's header"),
1546            (
1547                "#version,serial,flight,time (ms)\n0,0,0,0\n",
1548                "line 1: the header writes a unit after `time` other than s",
1549            ),
1550            (
1551                "#version,serial,flight,height\n0,0,0,0\n",
1552                "line 1: the header names no `time`",
1553            ),
1554            ("#version,serial,flight,time,height\n", "no data rows"),
1555            (
1556                "#version,serial,flight,time,height\n0,0,0,x,0\n",
1557                "no data rows",
1558            ),
1559            (
1560                "#version,serial,flight,time,height\n0,0,0,0,0,7\n",
1561                "line 2: the row has 6 cells and the header names 5",
1562            ),
1563        ];
1564        for (text, expected) in cases {
1565            let error = read(text).unwrap_err().to_string();
1566            assert!(error.contains(expected), "{text:?}: {error}");
1567        }
1568        let junk = "\u{fffd}".repeat(100_000);
1569        let error = read(&junk).unwrap_err().to_string();
1570        assert!(error.len() < 400 && error.contains('…'), "{error}");
1571    }
1572
1573    /// A header without `height` reads, with no primary track and every column a channel.
1574    #[test]
1575    fn no_height_no_primary_track() {
1576        let log = read("#version,serial,flight,time,altitude\n6,77,4,0.5,250\n").unwrap();
1577        assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
1578        assert!(log.temperature_k.is_none() && log.battery_v.is_none());
1579        let altitude = log
1580            .channels
1581            .iter()
1582            .find(|c| c.column == "altitude")
1583            .unwrap();
1584        assert_eq!(
1585            (altitude.quantity, altitude.values.as_slice()),
1586            (Quantity::AltitudeMsl, &[250.0][..])
1587        );
1588        assert!(log.notes.iter().any(|n| n.contains("no primary track")));
1589    }
1590
1591    /// A unit after AltOS's name that is this reader's reads the column as AltOS's; another
1592    /// keeps it as written; a pressure stated in Pa whose values are hPa is kept as written.
1593    #[test]
1594    fn units_after_the_names() {
1595        let text = "#version,serial,flight,time,height (m),acceleration (m/s^2),accel_x (m/s),\
1596                    pressure (Pa)\n6,77,4,0.5,10,1.5,9.8,980\n";
1597        let log = read(text).unwrap();
1598        let quantity = |column: &str| {
1599            log.channels
1600                .iter()
1601                .find(|c| c.column == column)
1602                .map(|c| c.quantity)
1603        };
1604        assert_eq!(log.altitude_m, [10.0]);
1605        assert_eq!(
1606            quantity("acceleration (m/s^2)"),
1607            Some(Quantity::Acceleration)
1608        );
1609        assert_eq!(quantity("accel_x (m/s)"), Some(Quantity::Unrecognized));
1610        assert_eq!(quantity("pressure (Pa)"), Some(Quantity::Unrecognized));
1611        assert!(
1612            log.notes
1613                .iter()
1614                .any(|n| n.contains("`accel_x (m/s)`, a unit"))
1615        );
1616        let feet = read("#version,serial,flight,time,height (ft)\n6,77,4,0.5,10\n").unwrap();
1617        assert!(
1618            feet.altitude_m.is_empty(),
1619            "a height in feet isn't AltOS's height"
1620        );
1621    }
1622
1623    /// A `height` of formulas alone isn't a channel, so the record has no primary track, as with
1624    /// none: the clock and the track stay the same length.
1625    #[test]
1626    fn a_height_of_formulas_alone_is_no_primary_track() {
1627        let text = "#version,serial,flight,time,height,altitude\n\
1628                    6,77,4,0.5,=F2-F$2,250\n\
1629                    6,77,4,0.6,=F3-F$2,251\n";
1630        let log = read(text).unwrap();
1631        assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
1632        assert!(log.channels.iter().all(|c| c.column != "height"));
1633        assert!(
1634            log.notes.iter().any(|n| n.starts_with(
1635                "the `height` column, AltOS's height above the pad, holds a spreadsheet's \
1636                 formulas alone"
1637            )),
1638            "{:#?}",
1639            log.notes
1640        );
1641    }
1642
1643    /// One formula cell is written of in the singular.
1644    #[test]
1645    fn one_formula_cell_reads_in_the_singular() {
1646        let log = read("#version,serial,flight,time,height,x\n6,77,4,0.5,0,=E2*2\n").unwrap();
1647        assert!(
1648            log.notes.iter().any(|n| n.starts_with(
1649                "the `x` column's 1 cell is a spreadsheet's formula, not a value. The column"
1650            )),
1651            "{:#?}",
1652            log.notes
1653        );
1654    }
1655
1656    /// The formula notes' bounds hold at their limits and count what is past them: at most
1657    /// [`MAX_FORMULA_RUNS`] runs a column and [`MAX_FORMULA_COLUMNS`] columns.
1658    #[test]
1659    fn the_formula_bounds_hold_at_their_limits() {
1660        let runs = |extra: usize| {
1661            let mut text = String::from("#version,serial,flight,time,height,x\n");
1662            for k in 0..MAX_FORMULA_RUNS + extra {
1663                text += &format!("6,77,4,{k}.0,{k},=E{}*{k}\n", k + 2);
1664            }
1665            let log = read(&text).unwrap();
1666            log.notes
1667                .into_iter()
1668                .find(|n| n.starts_with("the `x` column's"))
1669                .unwrap()
1670        };
1671        let at = runs(0);
1672        assert_eq!(at.matches("` on line ").count(), MAX_FORMULA_RUNS, "{at}");
1673        assert!(!at.contains("past them"), "{at}");
1674        let past = runs(2);
1675        assert_eq!(
1676            past.matches("` on line ").count(),
1677            MAX_FORMULA_RUNS,
1678            "{past}"
1679        );
1680        assert!(past.ends_with("; 2 cells more past them"), "{past}");
1681
1682        let columns = |n: usize| {
1683            let names: Vec<String> = (0..n).map(|k| format!("x{k}")).collect();
1684            let cells: Vec<String> = (0..n).map(|k| format!("={k}")).collect();
1685            let text = format!(
1686                "#version,serial,flight,time,height,{}\n6,77,4,0.0,0,{}\n",
1687                names.join(","),
1688                cells.join(",")
1689            );
1690            read(&text).unwrap().notes
1691        };
1692        let given = |notes: &[String]| notes.iter().filter(|n| n.starts_with("the `x")).count();
1693        assert_eq!(given(&columns(MAX_FORMULA_COLUMNS)), MAX_FORMULA_COLUMNS);
1694        let past = columns(MAX_FORMULA_COLUMNS + 3);
1695        assert_eq!(given(&past), MAX_FORMULA_COLUMNS);
1696        assert!(
1697            past.iter()
1698                .any(|n| n.contains("past the 64 whose formulas are given")),
1699            "{past:#?}"
1700        );
1701    }
1702
1703    /// A state a spreadsheet rewrote, `3.0`, is AltOS's `3`; and a table opening with a
1704    /// byte-order mark is still recognized.
1705    #[test]
1706    fn a_rewritten_state_and_a_byte_order_mark_still_read() {
1707        let text = "\u{feff}time,state,state_name,height\n0.0,3.0,boost,0\n0.1,5.0,coast,2\n";
1708        assert!(recognizes_table(text));
1709        let log = read(text).unwrap();
1710        let events: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
1711        assert_eq!(events, ["boost", "coast"]);
1712    }
1713
1714    /// A formula is text: a column of them isn't a channel, and its note gives every formula,
1715    /// each cell's own row as `{row}`, run by run; a formula among numbers is a gap.
1716    #[test]
1717    fn formulas_are_kept_as_text() {
1718        let text = "#version,serial,flight,time,height,altitude (ft),(ft/s)\n\
1719                    6,77,4,0.0,0,=3.28084*E2,=3.28*E2\n\
1720                    6,77,4,0.5,10,=3.28*E3,1.5\n\
1721                    6,77,4,1.0,20,=3.28*E4,=3.28*E4\n\
1722                    6,77,4,1.5,30,=3.28*E5,=3.28*E5\n";
1723        let log = read(text).unwrap();
1724        assert_eq!(log.altitude_m, [0.0, 10.0, 20.0, 30.0]);
1725        assert!(log.channels.iter().all(|c| c.column != "altitude (ft)"));
1726        let note = |start: &str| {
1727            log.notes
1728                .iter()
1729                .find(|n| n.starts_with(start))
1730                .unwrap_or_else(|| panic!("{start}: {:#?}", log.notes))
1731        };
1732        let all = note("the `altitude (ft)` column's 4 cells are a spreadsheet's formulas");
1733        assert!(
1734            all.ends_with("`=3.28084*E{row}` on line 2; `=3.28*E{row}` on lines 3–5"),
1735            "{all}"
1736        );
1737        let mixed = note("the `(ft/s)` column has 3 cells holding");
1738        assert!(
1739            mixed.ends_with("`=3.28*E{row}` on line 2; `=3.28*E{row}` on lines 4–5"),
1740            "{mixed}"
1741        );
1742        let speed = log.channels.iter().find(|c| c.column == "(ft/s)").unwrap();
1743        assert_eq!(speed.values[1], 1.5);
1744        assert!(speed.values[0].is_nan() && speed.values[3].is_nan());
1745    }
1746
1747    /// A formula cell holding a long run of capitals after a digit reads in time linear in its
1748    /// length: stepping through the run one letter at a time, recounting the rest at each, grows
1749    /// as the square of its length, and took 50 s to read this cell of 600,000 letters on a fast
1750    /// desktop (#1250). The clock times the read alone, and nothing it reads reaches a result.
1751    #[test]
1752    #[allow(clippy::disallowed_types, reason = "the clock times the read alone")]
1753    fn a_long_run_of_capitals_in_a_formula_reads_in_linear_time() {
1754        let letters = "A".repeat(600_000);
1755        let text = format!(
1756            "#version,serial,flight,time,height,altitude (ft)\n\
1757             6,77,4,0.0,0,=1{letters}\n\
1758             6,77,4,0.5,10,1\n"
1759        );
1760        let began = std::time::Instant::now();
1761        let log = read(&text).unwrap();
1762        let elapsed = began.elapsed();
1763        assert_eq!(log.altitude_m, [0.0, 10.0]);
1764        // The run is copied as written.
1765        let short = "A".repeat(1_000);
1766        assert_eq!(
1767            own_row(&format!("=1{short}+J2"), 2),
1768            format!("=1{short}+J{{row}}")
1769        );
1770        assert!(elapsed.as_secs_f64() < 5.0, "{elapsed:?}");
1771    }
1772
1773    /// Only a reference to the cell's own row becomes `{row}`.
1774    #[test]
1775    fn own_row_rewrites_references_to_the_row_only() {
1776        assert_eq!(own_row("=3.28*J2", 2), "=3.28*J{row}");
1777        assert_eq!(own_row("=AL12-AL$2+J$12", 12), "=AL{row}-AL$2+J${row}");
1778        assert_eq!(own_row("=LOG10(J10)", 10), "=LOG10(J{row})");
1779        assert_eq!(own_row("=ABCD7+A7B", 7), "=ABCD7+A7B");
1780        assert_eq!(own_row("=J22*2", 2), "=J22*2");
1781        assert_eq!(own_row("=é+J3", 3), "=é+J{row}");
1782    }
1783
1784    /// In a table with no `version` header, a row whose state number and name aren't AltOS's
1785    /// pair is refused at its line; a state AltOS's exports don't name passes unchecked.
1786    #[test]
1787    fn a_state_unlike_altoss_is_refused() {
1788        let head = "time,state,state_name,height\n-0.5,2,pad,0\n";
1789        let error = read(&format!("{head}0.0,3,ignition,0\n"))
1790            .unwrap_err()
1791            .to_string();
1792        assert!(
1793            error.contains(
1794                "line 3: the row's state 3 is named \"ignition\", where AltOS names 3 `boost`"
1795            ),
1796            "{error}"
1797        );
1798        let error = read(&format!("{head}0.0,4,boost,0\n"))
1799            .unwrap_err()
1800            .to_string();
1801        assert!(
1802            error.contains("line 3: the row's state 4 is named"),
1803            "{error}"
1804        );
1805        let error = read(&format!("{head}0.0,12,boost,0\n"))
1806            .unwrap_err()
1807            .to_string();
1808        assert!(error.contains("where AltOS numbers `boost` 3"), "{error}");
1809        assert!(read(&format!("{head}0.0,9,invalid,0\n")).is_ok());
1810    }
1811
1812    /// In an export with AltOS's `version,serial,flight` header, a state unlike AltOS's is
1813    /// counted in a note, its name kept for the events: one sample file numbers `pad` 1.
1814    #[test]
1815    fn an_exports_state_unlike_altoss_is_noted() {
1816        let text = format!(
1817            "{HEAD}{}{}",
1818            row(-0.5, "pad", 0.0).replacen(", 2,", ", 1,", 1),
1819            row(0.0, "boost", 1.25)
1820        );
1821        let log = read(&text).unwrap();
1822        let note = log
1823            .notes
1824            .iter()
1825            .find(|n| n.starts_with("1 row gives a `state`"))
1826            .unwrap_or_else(|| panic!("{:#?}", log.notes));
1827        assert!(
1828            note.contains("the first at line 2: the row's state \"1\" is named `pad`"),
1829            "{note}"
1830        );
1831        let events: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
1832        assert_eq!(events, ["pad", "boost"]);
1833    }
1834
1835    /// A table cut from an export, AltOS's names with no `version` header, is read by its
1836    /// states; one with no state AltOS names, a unit after a name, a name AltOS doesn't write or
1837    /// comments before it, isn't.
1838    #[test]
1839    fn a_table_of_altoss_columns_reads_by_its_states() {
1840        let text = "time,state,state_name,acceleration,pressure,altitude,height,speed,temperature\n\
1841                    -0.10,3,boost,9.1,95300,512.7,5.2,15.8,23.7\n\
1842                    0.00,3,boost,10.0,95290,513.5,6.0,16.8,23.7\n\
1843                    0.10,5,coast,-9.8,95200,521.6,14.1,15.0,23.7\n";
1844        assert!(recognizes_table(text));
1845        assert_eq!(
1846            crate::import::detect(text.as_bytes()),
1847            Some(LogFormat::AltosCsv)
1848        );
1849        let log = read(text).unwrap();
1850        assert_eq!(log.altitude_m, [5.2, 6.0, 14.1]);
1851        assert_eq!(log.serial_number, None);
1852        let events: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
1853        assert_eq!(events, ["boost", "coast"]);
1854        assert!(
1855            log.notes
1856                .iter()
1857                .any(|n| n.starts_with("the header names AltOS's columns"))
1858        );
1859        let unknown = text
1860            .replace("3,boost", "1,idle")
1861            .replace("5,coast", "0,startup");
1862        assert!(!recognizes_table(&unknown));
1863        assert!(
1864            read(&unknown)
1865                .unwrap_err()
1866                .to_string()
1867                .contains("by its states")
1868        );
1869        assert!(!recognizes_table(&text.replace("speed,", "speed (m/s),")));
1870        assert!(!recognizes_table(&text.replace("speed,", "source,")));
1871        assert!(!recognizes_table(&text.replace("5,coast", "5,boost")));
1872        assert!(read(&format!("# product EasyMini\n{text}")).is_err());
1873    }
1874
1875    proptest::proptest! {
1876        /// Any text is read or refused, never a panic; what is read has a strictly increasing
1877        /// primary track, and every channel as many times as values.
1878        #[test]
1879        fn any_text_is_read_or_refused(
1880            text in "(#version,serial,flight,time,height,state_name,altitude,longitude,altitude\n)?\
1881                     ([-0-9., NaN#a-z]{0,24}\n){0,12}"
1882        ) {
1883            if let Ok(log) = read(&text) {
1884                proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
1885                proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
1886                for channel in &log.channels {
1887                    proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
1888                }
1889            }
1890        }
1891    }
1892}