Skip to main content

hpr_flightdata/
fwgps.rs

1//! Featherweight's GPS tracker logs, as the tracker's app and its ground station write them to
2//! comma-separated files: positions from a GPS receiver, with no barometer.
3//!
4//! Featherweight's GPS tracker radios its fixes to a ground station, which passes them to a phone
5//! app over Bluetooth; the tracker also keeps its own "flight data logging" (Featherweight,
6//! *Featherweight GPS Tracker User's Manual*, February 20, 2025, p17). As of 2026-10-12, among the
7//! project's sample logs, 40 distinct files hold one of four layouts, each a header line naming the
8//! columns, then one row per fix:
9//!
10//! | Layout | Files | Header |
11//! |---|---|---|
12//! | The tracker's log, older | 7 | `UTCTIME,UNIXTIME,ALT,LAT,LON,#SATS,FIX,HORZV,VERTV,HEAD,FLAGS,>40,>32,>24,RSSI,BATT` |
13//! | The tracker's log, newer | 21 | the same 16, then `Altitude AGL,Launch detection,Apogee detection,Landing detection,Distance (feet)` |
14//! | The ground station's log | 8 | `TRACKER,DATE,TIME,LAT,LON,ALT,FIX,HORZV,VERTV,HEAD,FLAGS,#TOT,>40,>32,>24,RSSI,BATT` |
15//! | The ground station's log with its radio's figures | 4 | `TRACKER,DATE,TIME,GS Lat,GS Lon,GS Alt asl,TRACKER Lat,TRACKER Lon,TRACKER Alt asl,…` (40 columns) |
16//!
17//! ```text
18//! UTCTIME,UNIXTIME,ALT,LAT,LON,#SATS,FIX,HORZV,VERTV,HEAD,FLAGS,>40,>32,>24,RSSI,BATT
19//! Jun 3 2024 15:20:00.100 UTC,1717446000.100,4000,40.1234567,-105.1234567,18,3,0,0,90,0x03,4,9,3,-40,4.010
20//! ```
21//!
22//! A file is one of these when its first line that isn't blank opens with `UTCTIME,UNIXTIME` and
23//! names `LAT` and `LON`, or opens with `TRACKER,DATE,TIME` and names `LAT` and `LON` or `TRACKER
24//! Lat` and `TRACKER Lon`. Columns are then mapped by name, not by place; a name is matched as
25//! written, its spaces at either end trimmed.
26//!
27//! **No barometer.** The files hold a GPS receiver's positions only, so the record's primary track
28//! is empty, as for a Blue Raven's high-rate file ([ADR-253][adr-253] §6, on the RRC3, Eggtimer
29//! and Blue Raven readers) and as [ADR-254][adr-254] §2 decided for GPS logs, and every column is
30//! a channel, with a note saying so. The readings withhold on such a log.
31//!
32//! [adr-253]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0253-rrc3-eggtimer-and-blue-raven-csv-first.md
33//! [adr-254]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0254-gps-tracks-first-among-the-other-importers.md
34//! [adr-258]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0258-aerospacenus-board-and-a-phone-apps-csv-before-the-rest.md
35//!
36//! **Channels.** Every column but the clock's parts, the tracker's name and `Found rocket ID` is a
37//! channel, in the file's order, in the record's SI unit ([`Quantity::unit`]):
38//!
39//! | Column | Quantity | Unit from |
40//! |---|---|---|
41//! | `UTCTIME`; `TIME` | [`Quantity::TimeOfDay`]: UTC; the ground station's clock | the clock (below) |
42//! | `UNIXTIME` | [`Quantity::Unrecognized`], as written | a note gives its offset from `UTCTIME` (below) |
43//! | `ALT`, `TRACKER Alt asl`, `GS Alt asl`, `Found rocket altitude` | [`Quantity::GnssAltitude`] | feet: the manual and the data (below) |
44//! | `Altitude AGL`, `GS_ASL_offset` | [`Quantity::Distance`]: a height, not above sea level | feet, with the altitude |
45//! | `LAT`, `LON` and each `… Lat`, `… Lon`, `… lat`, `… lon` | [`Quantity::Latitude`], [`Quantity::Longitude`] | degrees |
46//! | `HORZV`, `VERTV` | [`Quantity::Speed`] | ft/s: the manual and the data (below) |
47//! | `HEAD` | [`Quantity::Angle`] | degrees: the manual and the data (below) |
48//! | `BATT` | [`Quantity::Voltage`] | volts: the data (below) |
49//! | `GS_batt_v`, `Found rocket batt_v` | [`Quantity::Voltage`] | the header's `v` |
50//! | `Distance (feet)`, `Alt AGL (ft)`, `Horizontal range (ft)`, `Total range (ft)` | [`Quantity::Distance`] | the header's feet |
51//! | `LoRa Max Range (kft)` | [`Quantity::Distance`] | the header's thousands of feet |
52//! | `#SATS`, `#TOT`, `FIX`, `FLAGS`, `>40`, `>32`, `>24`, `RSSI`, `RSSI Down`, `RSSI Up`, `Found RSSI`, `Found rocket fix`, the radio's packet counts | [`Quantity::Number`], as written | no unit |
53//! | `LoRa Success Rate` | [`Quantity::Number`], in percent | written `67%`, "the packet success rate, expressed as a percentage, based on the last 50 packets" (*Featherweight Swift User's Manual*, April 10 2026, p10) |
54//! | `Launch detection`, `Apogee detection`, `Landing detection` | [`Quantity::Number`], 1 for `TRUE` and 0 for `FALSE` | the manual's "flag"s (p17) |
55//!
56//! `>40`, `>32` and `>24` are, in the manual's words, the "Number of GPS satellites with > 40
57//! signal strength" and so on (p17), its color table giving signal strengths in dB-Hz (p10). `FLAGS` is written in hexadecimal (`0x03`) in the
58//! older tracker log and both ground-station logs, and in decimal in the newer tracker log; either
59//! is read as the number it writes. A column the reader doesn't know is kept as written,
60//! [`Quantity::Unrecognized`], with a note.
61//!
62//! **Units no header states.** The manual lists the tracker's log as "Altitude (ASL, Feet)",
63//! "Horizontal velocity (feet/second)", "Vertical velocity (feet/second)", "Heading (degrees from
64//! North)" and "Tracker battery voltage" (p17), in the order of the tracker log's columns, and the
65//! ground station's serial packet gives the same units (Appendix A, p21). Each is checked against
66//! the file's own rows, and each file's record carries one note per kind: the decision and what
67//! decided it, the same words for every file decided alike, then after the colon this file's
68//! evidence, such as `` `ALT` read in feet, from the manual and the horizontal speed: … ``. The
69//! checks, and what they found as of 2026-10-12, among the project's 40 sample files:
70//!
71//! - *The file's length unit.* One rule decides it for every length and speed the manual gives
72//!   in feet: the heights, `HORZV` and `VERTV`. Only `HORZV` can be checked against an absolute
73//!   length, the great-circle distance between two fixes. Taking each tracker's rows in time
74//!   order, and each pair of rows more than 0.5 s and at most 2.5 s apart (from the last row whose
75//!   position differed, as the ground station repeats a fix it hasn't heard anew) at a speed of at
76//!   least 20 as written, the distance in feet a second over `HORZV` has a median between 0.95 and
77//!   1.32 in the 37 files with 10 such pairs or more (1.32 in one ground-station log, the rest
78//!   below 1.08); meters per second would give 3.28, knots 1.69, miles per hour 1.47. A median
79//!   inside 0.7 to 1.4 keeps the manual's feet (`from the manual and the distance between fixes`,
80//!   and for the heights `from the manual and the horizontal speed`); with fewer than 10 pairs, as
81//!   in 3 files, the manual decides alone (`from the manual alone`); a median outside the band
82//!   keeps every one of those columns as written, with a note. The band's upper edge sits 6% above
83//!   the highest sample median and 4.5% below miles per hour's 1.467, so a file in miles per hour
84//!   whose fixes ran 4.5% or more short of its speeds would be read in feet per second: the band
85//!   errs toward the manual's unit, not away from it. Kilometers per hour would give 0.91, inside
86//!   the band: the manual, not the check, rules them out. Pairs a tenth of a second apart are left
87//!   out: in one of the older tracker logs, whose rows step back and repeat, the distance over
88//!   such pairs runs 1.6 times `HORZV`, where over pairs a second apart it runs 1.02 times.
89//! - *Vertical speed.* `VERTV` against the change of the altitude a second, over the same pairs,
90//!   shows only that the two share a length unit, not which: a file all in meters agrees as well
91//!   as one all in feet. It decides only whether `VERTV` is in the altitude's unit a second
92//!   (`` `VERTV` read in feet per second, in the altitude's unit, from the change of altitude ``,
93//!   or `from the manual alone` with fewer than 10 pairs); where its median falls outside 0.7 to
94//!   1.4, `VERTV` and the heights are kept as written. The medians fall between 0.94 and 1.03 in
95//!   the 38 files with 10 such pairs or more.
96//! - *Heights.* In the 40-column ground-station log, `Alt AGL (ft)`, whose header says feet, is
97//!   `TRACKER Alt asl` less `GS Alt asl` and `GS_ASL_offset` to 0.15 ft on every row with a fix of
98//!   all 4 files, which ties those three to feet too: the heights there are kept as written if it
99//!   holds on under half the rows, and its note says `` and `Alt AGL (ft)` `` among what decided.
100//!   In the newer tracker log, `Altitude AGL` is `ALT` less one height, the pad's, to 0.05 ft (in
101//!   all 21 files, on all but one row), which shows the two share a unit but not which.
102//!   `Distance (feet)` is, by a median of 1.000 to 1.002 times, the great-circle distance from the
103//!   first row's position in the 21 newer tracker logs.
104//! - *Heading.* `HEAD` stays within −179 to 180 in every file: degrees, as the manual says. A file
105//!   with a value past ±360 keeps it as written.
106//! - *Battery.* `BATT` stays between 0 and 4.16 in every file, as one lithium cell's volts do
107//!   (the ground station's serial packet writes millivolts, p21, which would be thousands), and
108//!   reads 0 on every row of the 8 shorter ground-station logs. A value outside 0 to 5 keeps it as
109//!   written.
110//!
111//! The speeds' and heights' unit is also what fw2kml's KML of the same flights shows (the GPS
112//! logs' decision, [ADR-254][adr-254] §5), a check across files the reader can't make.
113//!
114//! **The clock.** The tracker's clock is `UTCTIME`, written `Jul 14 2031 17:04:31.250 UTC`: an
115//! English month's first three letters, the day, the year, the time of day and `UTC`. Read as UTC,
116//! it puts the first fix between 6.8 h and 15.4 h of local mean solar time at the fix's longitude
117//! in the 28 tracker files. `UNIXTIME` is a Unix time, but a whole number of hours, 4 to 8, ahead
118//! of `UTCTIME` on every row of every tracker file, as if the site's offset from UTC had been
119//! added where it should have been taken away: read as UTC, it would put a fix at up to 22.9 h of
120//! solar time. It is kept as a channel as written, with a note giving its offset. The ground
121//! station's clock is `DATE` (`2031-07-14`) and `TIME` (`14:27:09.375`), in a zone the file
122//! doesn't state. At the first fix, `TIME` falls between 6.6 h and 13.5 h in 11 of the 12
123//! ground-station files, as a clock on the site's zone would on a launch day, and read as UTC it
124//! would put 8 of them between 22.8 h and 4.0 h of local mean solar time, at night; in the
125//! twelfth, `TIME` is 0.2 h, 16.2 h of solar time read as UTC, as a clock on UTC would be. The
126//! times are kept on that clock as written, with a note, `` `DATE` and `TIME` kept as written, in a
127//! time zone the file doesn't state: … ``, giving this file's figures after the colon.
128//!
129//! The log's zero is the first row's time, in the file's order. Channels keep every row in the
130//! file's order, so a time may go back: in each of the 7 older tracker logs, rows step back 1 to
131//! 11 times, by 0.9 s to 9 s, and in two of them once by about 847 s and 4,407 s; 1 to 76 rows of
132//! each repeat a time already written. A note counts how often and how far times go back, and how
133//! many rows repeat a time. The rows of the ground-station logs and of the newer tracker logs run
134//! forward, but for one repeated time in 4 of the newer. A clock cell that isn't a time is
135//! refused, naming its line.
136//!
137//! **Trackers.** A ground station logs every tracker it hears; 3 of the 8 shorter ground-station
138//! logs and 1 of the 4 longer hold several (up to 5). Each tracker has its own set of channels, in
139//! the order the trackers first appear, each named with the tracker's trimmed name in brackets,
140//! such as `LAT [Rocket-1]`, when the file holds more than one; a file of one tracker keeps the
141//! header's names. Past [`MAX_TRACKERS`] trackers, or [`MAX_CHANNELS`] channels in all, a further
142//! tracker's rows are left out, counted in a note, so a file of many names can't make the reader
143//! hold a set of channels for each.
144//!
145//! **No fix.** Before it has a fix, a tracker writes 0 for its latitude, longitude and altitude:
146//! 372 rows of 6 shorter ground-station logs and 74 of a longer one do. A row whose latitude and
147//! longitude are both exactly 0 has them and the altitude beside them read as gaps, counted in a
148//! note, for the tracker's, the ground station's and the found rocket's positions alike, as
149//! [`crate::altos`] does for AltOS's (0, 0). A latitude beyond ±90° or a longitude beyond ±180° is
150//! a gap too, counted per column in a note, as [`crate::kml`] and [`crate::nmea`] read theirs; no
151//! sample file has one.
152//!
153//! **Cells and rows.** A cell is a decimal number, hexadecimal digits after `0x`, `TRUE` or
154//! `FALSE` (1 or 0), or a number followed by `%`. A cell that is empty or none of these, such as
155//! the literal `NaN` in `Distance (feet)` (27 cells over the 21 newer tracker logs), is a gap,
156//! counted per column in a note. A row with fewer cells than the header has the rest as gaps; a
157//! row with more is refused, as is a value its unit's factor makes too large for an `f64`, such
158//! as `LoRa Max Range (kft)` near 10³⁰⁸, naming its line ([the rule for infinite values][adr-258],
159//! §3). A file whose rows, down to
160//! any row, hold under a quarter of the cells its header names (past the first 65,536) is refused
161//! at that row. Blank lines are skipped; lines may end in CR, LF or both (2 of the shorter
162//! ground-station logs end in CR LF); a byte-order mark is dropped.
163//!
164//! **What the file says about itself.** The logger is a `Featherweight GPS tracker` or a
165//! `Featherweight GPS ground station`; the files state no serial number, firmware, flight number,
166//! apogee or ground elevation.
167//!
168//! **Where this comes from.** The layouts and their quirks, from the sample files; the units,
169//! from the manual as cited and the files; the tracker log's clock, columns and feet, following
170//! Debrief's `lib/parsers/featherweightGps.ts` (MIT, the project owner's own; see
171//! `THIRD-PARTY-NOTICES.md`). Where this reader departs from Debrief's: it keeps every row in the
172//! file's order on `UTCTIME`, where Debrief sorts by `UNIXTIME` and drops repeated times; it reads
173//! the shorter ground-station log, which Debrief doesn't, and keeps each tracker apart, where
174//! Debrief reads every row as one tracker's; it keeps every column, where Debrief keeps a chosen
175//! few; and it reads a position's no-fix zeros as gaps by the zeros themselves, where Debrief reads
176//! them by the `FIX` column.
177
178use std::collections::HashMap;
179
180use crate::error::LogError;
181use crate::log::{Channel, FlightLog, LogFormat, Quantity, Stated, too_sparse};
182use crate::perfectflite::FOOT_M;
183use crate::table::{Notes, finite, number, numbered_lines, short};
184
185/// The format's name in errors.
186const FORMAT: &str = "Featherweight GPS CSV";
187
188/// The most trackers one file's channels are kept for; past it, a tracker's rows are left out.
189/// The sample files hold at most 5.
190pub const MAX_TRACKERS: usize = 64;
191
192/// The most channels a file's trackers may have in all; past it, a further tracker's rows are left
193/// out. Two trackers of the 40-column log hold 74.
194pub const MAX_CHANNELS: usize = 4_096;
195
196/// The shortest step between two fixes a speed is checked over, s: over a tenth of a second, the
197/// older tracker log's rows, which step back and repeat, can pair fixes that weren't a tenth of a
198/// second apart.
199const MIN_STEP_S: f64 = 0.5;
200
201/// The longest step between two fixes a speed is checked over, s: the ground station logs about a
202/// fix a second, the tracker up to ten.
203const MAX_STEP_S: f64 = 2.5;
204
205/// The slowest speed, as written, a speed is checked at: below it a GPS receiver's noise is a
206/// large part of the change.
207const MIN_SPEED: f64 = 20.0;
208
209/// The fewest pairs of rows a speed check needs to overrule the manual.
210const MIN_PAIRS: usize = 10;
211
212/// The band a speed check's median ratio must fall in to agree with the manual: wide enough for
213/// the 0.94 to 1.32 seen in the samples, narrow enough to refuse miles per hour (1.47), knots
214/// (1.69) and meters per second (3.28). The upper edge is 4.5% below miles per hour's 1.467, so a
215/// file in miles per hour whose fixes run that much short of its speeds would read in feet per
216/// second: the band errs toward the manual's unit (the module's docs say more).
217const AGREES: (f64, f64) = (0.7, 1.4);
218
219/// The most a battery reads in volts: one lithium cell is full at about 4.2 V.
220const MAX_CELL_V: f64 = 5.0;
221
222/// The mean radius of the Earth, m: R₁ = 6,371,008.8 m of the Geodetic Reference System 1980
223/// (Moritz, *Geodetic Reference System 1980*, Journal of Geodesy 74, 2000). A great circle on this
224/// sphere is within half a percent of the ellipsoid's distance anywhere.
225const EARTH_RADIUS_M: f64 = 6_371_008.8;
226
227/// Nanoseconds in a second and in a day.
228const NS_PER_S: i64 = 1_000_000_000;
229const NS_PER_DAY: i64 = 86_400 * NS_PER_S;
230
231/// The years a clock cell may name: a GPS receiver's dates fall well inside, and the span keeps a
232/// difference of two times, in nanoseconds, inside an `i64`.
233const YEARS: std::ops::RangeInclusive<i64> = 1970..=2199;
234
235/// Whether the text is in this reader's layout, judged from its header, never the file's name.
236pub(crate) fn recognizes(text: &str) -> bool {
237    numbered_lines(text)
238        .map(|(_, line)| line)
239        .find(|line| !line.trim().is_empty())
240        .and_then(layout)
241        .is_some()
242}
243
244/// Which of Featherweight's logs a file is.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246enum Layout {
247    /// The tracker's own log, timed by `UTCTIME`.
248    Tracker,
249    /// The ground station's log, timed by `DATE` and `TIME`, one tracker's rows or several.
250    GroundStation,
251}
252
253/// A header line's layout, `None` if it is neither.
254///
255/// The opening names are checked first, one at a time, and the rest are walked without being
256/// collected, so that a long line of other text is turned away without a list of its names.
257fn layout(header: &str) -> Option<Layout> {
258    let mut names = header.split(',').map(str::trim);
259    let layout = match (names.next()?, names.next()?) {
260        ("UTCTIME", "UNIXTIME") => Layout::Tracker,
261        ("TRACKER", "DATE") if names.next()? == "TIME" => Layout::GroundStation,
262        _ => return None,
263    };
264    let (mut lat, mut lon, mut tracker_lat, mut tracker_lon) = (false, false, false, false);
265    for name in names {
266        match name {
267            "LAT" => lat = true,
268            "LON" => lon = true,
269            "TRACKER Lat" => tracker_lat = true,
270            "TRACKER Lon" => tracker_lon = true,
271            _ => {}
272        }
273    }
274    let position = (lat && lon) || (layout == Layout::GroundStation && tracker_lat && tracker_lon);
275    position.then_some(layout)
276}
277
278/// What a column is to this reader.
279#[derive(Debug, Clone, Copy, PartialEq)]
280enum Role {
281    /// `UTCTIME`: the tracker's clock, and a time-of-day channel.
282    Clock,
283    /// `DATE`: the ground station's clock's date.
284    Date,
285    /// `TIME`: the ground station's clock's time of day, and a time-of-day channel.
286    Time,
287    /// `TRACKER`: whose row it is.
288    Tracker,
289    /// Text that names, such as `Found rocket ID`: no channel.
290    Label,
291    /// A value of some kind.
292    Value(Kind),
293}
294
295/// The kinds of value column, each with how its unit is decided.
296#[derive(Debug, Clone, Copy, PartialEq)]
297enum Kind {
298    /// A height in feet by the manual, checked against the file: above sea level, or not.
299    Height { above_sea_level: bool },
300    /// `VERTV`.
301    VerticalSpeed,
302    /// `HORZV`.
303    HorizontalSpeed,
304    /// `HEAD`.
305    Heading,
306    /// `BATT`.
307    Battery,
308    /// `UNIXTIME`.
309    UnixTime,
310    /// A quantity whose unit the header states, or that has none, made SI by a factor.
311    Stated(Quantity, f64),
312    /// A name the reader doesn't know.
313    Unknown,
314}
315
316/// What a column is, by its trimmed name.
317fn role(name: &str) -> Role {
318    use Quantity as Q;
319    let value = |kind| Role::Value(kind);
320    let stated = |quantity, factor| Role::Value(Kind::Stated(quantity, factor));
321    match name {
322        "UTCTIME" => Role::Clock,
323        "DATE" => Role::Date,
324        "TIME" => Role::Time,
325        "TRACKER" => Role::Tracker,
326        "Found rocket ID" => Role::Label,
327        "UNIXTIME" => value(Kind::UnixTime),
328        "ALT" | "TRACKER Alt asl" | "GS Alt asl" | "Found rocket altitude" => value(Kind::Height {
329            above_sea_level: true,
330        }),
331        "Altitude AGL" | "GS_ASL_offset" => value(Kind::Height {
332            above_sea_level: false,
333        }),
334        "LAT" | "TRACKER Lat" | "GS Lat" | "Found rocket lat" => stated(Q::Latitude, 1.0),
335        "LON" | "TRACKER Lon" | "GS Lon" | "Found rocket lon" => stated(Q::Longitude, 1.0),
336        "HORZV" => value(Kind::HorizontalSpeed),
337        "VERTV" => value(Kind::VerticalSpeed),
338        "HEAD" => value(Kind::Heading),
339        "BATT" => value(Kind::Battery),
340        "GS_batt_v" | "Found rocket batt_v" => stated(Q::Voltage, 1.0),
341        "Distance (feet)" | "Alt AGL (ft)" | "Horizontal range (ft)" | "Total range (ft)" => {
342            stated(Q::Distance, FOOT_M)
343        }
344        "LoRa Max Range (kft)" => stated(Q::Distance, 1_000.0 * FOOT_M),
345        "#SATS" | "#TOT" | "FIX" | "FLAGS" | ">40" | ">32" | ">24" | "RSSI" | "RSSI Down"
346        | "RSSI Up" | "Found RSSI" | "Found rocket fix" | "Down Sent" | "Down Rcvd"
347        | "Found Sent" | "Up Sent" | "Up Rccvd" | "LoRa Success Rate" | "Launch detection"
348        | "Apogee detection" | "Landing detection" => stated(Q::Number, 1.0),
349        _ => value(Kind::Unknown),
350    }
351}
352
353/// One column of the header.
354struct Column {
355    name: String,
356    role: Role,
357    /// Cells that were empty or not a value, and the first of them as written.
358    gaps: usize,
359    gap_example: Option<String>,
360    /// Latitudes beyond ±90° or longitudes beyond ±180°, read as gaps.
361    out_of_range: usize,
362}
363
364/// One tracker's rows: their times and each column's values as written, the clock's columns
365/// holding the time of day.
366struct Set {
367    name: String,
368    times_ns: Vec<i64>,
369    /// Each row's line in the file.
370    lines: Vec<usize>,
371    values: Vec<Vec<f64>>,
372}
373
374/// A position's three columns, the altitude's if the file has it.
375#[derive(Debug, Clone, Copy)]
376struct Position {
377    lat: usize,
378    lon: usize,
379    alt: Option<usize>,
380    /// Rows read with the latitude and longitude both 0.
381    zeros: usize,
382}
383
384/// Reads a Featherweight GPS tracker's or ground station's CSV.
385///
386/// # Errors
387///
388/// [`LogError::NotThisFormat`] if the first line isn't one of the four headers;
389/// [`LogError::Syntax`] for a header column with no name, a row with more cells than the header,
390/// a row whose clock is missing or isn't a time, rows holding under a quarter of the cells the
391/// header names, or a value its unit's factor makes too large for an `f64`; [`LogError::NoData`]
392/// if no row follows the header.
393pub fn read(text: &str) -> Result<FlightLog, LogError> {
394    let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
395    let Some((header_line, header)) = lines.next() else {
396        return Err(LogError::NotThisFormat {
397            format: FORMAT,
398            message: "the file is empty".to_owned(),
399        });
400    };
401    let Some(layout) = layout(header) else {
402        return Err(LogError::NotThisFormat {
403            format: FORMAT,
404            message: format!(
405                "its first line, {:?}, isn't a Featherweight GPS header, which opens \
406                 `UTCTIME,UNIXTIME` or `TRACKER,DATE,TIME`",
407                short(header)
408            ),
409        });
410    };
411    let mut notes = Notes::default();
412    let mut columns = Vec::new();
413    for (index, name) in header.split(',').map(str::trim).enumerate() {
414        if name.is_empty() {
415            return Err(syntax(
416                header_line,
417                format!("the header's column {} has no name", index + 1),
418            ));
419        }
420        let role = role(name);
421        if role == Role::Value(Kind::Unknown) {
422            notes.push(format!(
423                "the column {:?} isn't one this reader knows, and was kept as written",
424                short(name)
425            ));
426        }
427        columns.push(Column {
428            name: name.to_owned(),
429            role,
430            gaps: 0,
431            gap_example: None,
432            out_of_range: 0,
433        });
434    }
435    let find = |role: Role| columns.iter().position(|c| c.role == role);
436    // The layout's header check names these columns' places, so each is found.
437    let clock = match layout {
438        Layout::Tracker => Clock::Utc(find(Role::Clock).unwrap_or(0)),
439        Layout::GroundStation => Clock::DateTime {
440            date: find(Role::Date).unwrap_or(1),
441            time: find(Role::Time).unwrap_or(2),
442            tracker: find(Role::Tracker).unwrap_or(0),
443        },
444    };
445    let mut positions = positions(&columns);
446    let channels_per_set = columns
447        .iter()
448        .filter(|c| matches!(c.role, Role::Clock | Role::Time | Role::Value(_)))
449        .count();
450
451    let mut sets: Vec<Set> = Vec::new();
452    let mut set_of: HashMap<String, usize> = HashMap::new();
453    let mut left_out = LeftOut::default();
454    let (mut rows, mut cells_written) = (0usize, 0usize);
455    let (mut short_rows, mut first_short_row) = (0usize, 0usize);
456    let mut first_row: Option<(String, i64)> = None;
457    for (line_number, line) in lines {
458        let cells: Vec<&str> = line.split(',').map(str::trim).collect();
459        if cells.len() > columns.len() {
460            return Err(syntax(
461                line_number,
462                format!(
463                    "the row has {} cells, more than the header's {}",
464                    cells.len(),
465                    columns.len()
466                ),
467            ));
468        }
469        rows += 1;
470        cells_written += cells.len();
471        // Checked row by row, so that a wide header over short rows is refused before the gaps
472        // it would leave grow past a quarter more than the cells the file holds.
473        if too_sparse(columns.len(), rows, cells_written) {
474            return Err(syntax(
475                line_number,
476                format!(
477                    "the header names {} columns, and the {rows} rows down to this one hold only \
478                     {cells_written} cells",
479                    columns.len()
480                ),
481            ));
482        }
483        if cells.len() < columns.len() {
484            if short_rows == 0 {
485                first_short_row = line_number;
486            }
487            short_rows += 1;
488        }
489        let instant = clock.read(&cells, &columns, line_number)?;
490        if first_row.is_none() {
491            first_row = Some((clock.as_written(&cells), instant));
492        }
493        let tracker = clock.tracker(&cells);
494        let index = match set_of.get(tracker) {
495            Some(&index) => index,
496            None if sets.is_empty()
497                || (sets.len() < MAX_TRACKERS
498                    && (sets.len() + 1).saturating_mul(channels_per_set) <= MAX_CHANNELS) =>
499            {
500                set_of.insert(tracker.to_owned(), sets.len());
501                sets.push(Set {
502                    name: tracker.to_owned(),
503                    times_ns: Vec::new(),
504                    lines: Vec::new(),
505                    values: vec![Vec::new(); columns.len()],
506                });
507                sets.len() - 1
508            }
509            None => {
510                left_out.row(tracker);
511                continue;
512            }
513        };
514        let set = &mut sets[index];
515        set.times_ns.push(instant);
516        set.lines.push(line_number);
517        read_cells(set, &mut columns, &cells, instant);
518        for position in &mut positions {
519            no_fix(set, position);
520        }
521    }
522    let Some(first_row) = first_row else {
523        return Err(LogError::NoData { format: FORMAT });
524    };
525    let mut file_notes = Vec::new();
526    if short_rows > 0 {
527        file_notes.push(format!(
528            "{short_rows} rows, the first on line {first_short_row}, have fewer cells than the \
529             header's {}: the cells they leave out are gaps",
530            columns.len()
531        ));
532    }
533    if let Some(note) = left_out.note() {
534        file_notes.push(note);
535    }
536    build(
537        layout, &columns, sets, &positions, &first_row, notes, file_notes,
538    )
539}
540
541/// Where a layout's clock is.
542#[derive(Debug, Clone, Copy)]
543enum Clock {
544    /// `UTCTIME`'s place.
545    Utc(usize),
546    /// `DATE`'s, `TIME`'s and `TRACKER`'s places.
547    DateTime {
548        date: usize,
549        time: usize,
550        tracker: usize,
551    },
552}
553
554impl Clock {
555    /// A row's time, ns from 1970-01-01 00:00 on the file's clock; a missing cell or one that
556    /// isn't a time is refused.
557    fn read(self, cells: &[&str], columns: &[Column], line: usize) -> Result<i64, LogError> {
558        let cell = |index: usize| {
559            cells.get(index).copied().ok_or_else(|| {
560                syntax(
561                    line,
562                    format!(
563                        "the row ends after {} cells, before its {:?}",
564                        cells.len(),
565                        short(&columns[index].name)
566                    ),
567                )
568            })
569        };
570        let refuse = |what: &str, cell: &str, index: usize| {
571            syntax(
572                line,
573                format!(
574                    "the {what} {:?} in cell {} isn't one",
575                    short(cell),
576                    index + 1
577                ),
578            )
579        };
580        match self {
581            Self::Utc(index) => {
582                let text = cell(index)?;
583                utc_time(text).ok_or_else(|| refuse("time", text, index))
584            }
585            Self::DateTime { date, time, .. } => {
586                let (date_text, time_text) = (cell(date)?, cell(time)?);
587                let day = civil_date(date_text).ok_or_else(|| refuse("date", date_text, date))?;
588                let of_day =
589                    time_of_day_ns(time_text).ok_or_else(|| refuse("time", time_text, time))?;
590                Ok(day * NS_PER_DAY + of_day)
591            }
592        }
593    }
594
595    /// The row's tracker: the trimmed `TRACKER`, or none for the tracker's own log.
596    fn tracker<'a>(self, cells: &[&'a str]) -> &'a str {
597        match self {
598            Self::Utc(_) => "",
599            Self::DateTime { tracker, .. } => cells.get(tracker).copied().unwrap_or_default(),
600        }
601    }
602
603    /// The clock's cells as the file writes them, cut short.
604    fn as_written(self, cells: &[&str]) -> String {
605        match self {
606            Self::Utc(index) => short(cells.get(index).copied().unwrap_or_default()),
607            Self::DateTime { date, time, .. } => short(&format!(
608                "{} {}",
609                cells.get(date).copied().unwrap_or_default(),
610                cells.get(time).copied().unwrap_or_default()
611            )),
612        }
613    }
614}
615
616/// Rows of trackers past the caps, counted.
617#[derive(Default)]
618struct LeftOut {
619    names: Vec<String>,
620    rows: usize,
621}
622
623impl LeftOut {
624    fn row(&mut self, tracker: &str) {
625        self.rows += 1;
626        // Counting names stops at the cap's size, so a file of many can't fill memory with them.
627        if self.names.len() < MAX_TRACKERS && !self.names.iter().any(|name| name == tracker) {
628            self.names.push(tracker.to_owned());
629        }
630    }
631
632    fn note(&self) -> Option<String> {
633        (self.rows > 0).then(|| {
634            let trackers = if self.names.len() < MAX_TRACKERS {
635                format!("{} more trackers", self.names.len())
636            } else {
637                format!("{MAX_TRACKERS} or more further trackers")
638            };
639            format!(
640                "{} rows of {trackers} were left out, past the first {MAX_TRACKERS} trackers or \
641                 {MAX_CHANNELS} channels. This keeps a file of many tracker names from making the \
642                 reader hold a set of channels for each",
643                self.rows
644            )
645        })
646    }
647}
648
649/// Reads a row's cells into its tracker's columns as written: the clock's columns as the time of
650/// day, s, a value column as its cell's value or a gap.
651fn read_cells(set: &mut Set, columns: &mut [Column], cells: &[&str], instant: i64) {
652    for (index, column) in columns.iter_mut().enumerate() {
653        let value = match column.role {
654            Role::Date | Role::Tracker | Role::Label => continue,
655            Role::Clock => seconds_of_day(instant),
656            Role::Time => cells
657                .get(index)
658                .and_then(|cell| time_of_day_ns(cell))
659                .map_or(f64::NAN, |ns| ns as f64 / NS_PER_S as f64),
660            Role::Value(kind) => match cells.get(index) {
661                None => f64::NAN,
662                Some(cell) => match value(cell) {
663                    Some(value) if value.abs() > most_degrees(kind) => {
664                        column.out_of_range += 1;
665                        f64::NAN
666                    }
667                    Some(value) => value,
668                    None => {
669                        column.gaps += 1;
670                        if column.gap_example.is_none() {
671                            column.gap_example = Some(short(cell));
672                        }
673                        f64::NAN
674                    }
675                },
676            },
677        };
678        set.values[index].push(value);
679    }
680}
681
682/// The largest a value of a kind may be either side of 0: 90° for a latitude, 180° for a
683/// longitude, as kml.rs and nmea.rs read them; no bound for the rest.
684fn most_degrees(kind: Kind) -> f64 {
685    match kind {
686        Kind::Stated(Quantity::Latitude, _) => 90.0,
687        Kind::Stated(Quantity::Longitude, _) => 180.0,
688        _ => f64::INFINITY,
689    }
690}
691
692/// A cell's value as written: a decimal number, hexadecimal digits after `0x`, `TRUE` or `FALSE`
693/// as 1 or 0, or a number followed by `%`; `None` for anything else, `NaN` included.
694fn value(cell: &str) -> Option<f64> {
695    if let Some(value) = number(cell, false) {
696        return Some(value);
697    }
698    match cell {
699        "TRUE" => return Some(1.0),
700        "FALSE" => return Some(0.0),
701        _ => {}
702    }
703    if let Some(digits) = cell.strip_prefix("0x").or_else(|| cell.strip_prefix("0X")) {
704        if digits.is_empty() || digits.len() > 13 || !digits.bytes().all(|b| b.is_ascii_hexdigit())
705        {
706            return None;
707        }
708        // At most 13 hexadecimal digits, 52 bits, so the value is below 2⁵² and exact as an f64.
709        return u64::from_str_radix(digits, 16).ok().map(|bits| bits as f64);
710    }
711    cell.strip_suffix('%')
712        .filter(|rest| !rest.ends_with(char::is_whitespace))
713        .and_then(|rest| number(rest, false))
714}
715
716/// The positions the header holds: the tracker's, and in the longer ground-station log the ground
717/// station's and the found rocket's, each its latitude, longitude and altitude.
718fn positions(columns: &[Column]) -> Vec<Position> {
719    let place = |name: &str| columns.iter().position(|c| c.name == name);
720    [
721        ("LAT", "LON", "ALT"),
722        ("TRACKER Lat", "TRACKER Lon", "TRACKER Alt asl"),
723        ("GS Lat", "GS Lon", "GS Alt asl"),
724        (
725            "Found rocket lat",
726            "Found rocket lon",
727            "Found rocket altitude",
728        ),
729    ]
730    .into_iter()
731    .filter_map(|(lat, lon, alt)| {
732        Some(Position {
733            lat: place(lat)?,
734            lon: place(lon)?,
735            alt: place(alt),
736            zeros: 0,
737        })
738    })
739    .collect()
740}
741
742/// A no-fix row's position, its latitude and longitude both 0, read as gaps, and counted.
743fn no_fix(set: &mut Set, position: &mut Position) {
744    let last = |column: usize| set.values[column].last().copied();
745    if last(position.lat) == Some(0.0) && last(position.lon) == Some(0.0) {
746        position.zeros += 1;
747        for column in [Some(position.lat), Some(position.lon), position.alt]
748            .into_iter()
749            .flatten()
750        {
751            if let Some(value) = set.values[column].last_mut() {
752                *value = f64::NAN;
753            }
754        }
755    }
756}
757
758/// A tracker log's `UTCTIME`, such as `Jul 14 2031 17:04:31.250 UTC`, as ns from 1970-01-01 00:00
759/// UTC; `None` for anything else.
760fn utc_time(cell: &str) -> Option<i64> {
761    let mut parts = cell.split_whitespace();
762    let (month, day, year, time, zone) = (
763        parts.next()?,
764        parts.next()?,
765        parts.next()?,
766        parts.next()?,
767        parts.next()?,
768    );
769    if parts.next().is_some() || zone != "UTC" {
770        return None;
771    }
772    const MONTHS: [&str; 12] = [
773        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
774    ];
775    let month = MONTHS
776        .iter()
777        .position(|name| name.eq_ignore_ascii_case(month))?;
778    let day = days(year, u32::try_from(month).ok()? + 1, day)?;
779    Some(day * NS_PER_DAY + time_of_day_ns(time)?)
780}
781
782/// A ground station's `DATE`, `YYYY-MM-DD`, as days from 1970-01-01; `None` for anything else.
783fn civil_date(cell: &str) -> Option<i64> {
784    let mut parts = cell.split('-');
785    let (year, month, day) = (parts.next()?, parts.next()?, parts.next()?);
786    if parts.next().is_some() || year.len() != 4 || !digits(month, 1..=2) {
787        return None;
788    }
789    days(year, month.parse().ok()?, day)
790}
791
792/// Whether text is all ASCII digits, as many as the range allows.
793fn digits(text: &str, count: std::ops::RangeInclusive<usize>) -> bool {
794    count.contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit())
795}
796
797/// A date's days from 1970-01-01, the year four digits within [`YEARS`] and the day one or two
798/// digits within the month (leap years by the Gregorian rule).
799fn days(year: &str, month: u32, day: &str) -> Option<i64> {
800    if !digits(year, 4..=4) || !digits(day, 1..=2) {
801        return None;
802    }
803    let year: i64 = year.parse().ok()?;
804    let day: u32 = day.parse().ok()?;
805    let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
806    let length = match month {
807        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
808        4 | 6 | 9 | 11 => 30,
809        2 if leap => 29,
810        2 => 28,
811        _ => return None,
812    };
813    (YEARS.contains(&year) && (1..=length).contains(&day))
814        .then(|| days_from_civil(year, month, day))
815}
816
817/// Days from 1970-01-01 to a date of the proleptic Gregorian calendar, by Howard Hinnant's
818/// `days_from_civil` ("chrono-Compatible Low-Level Date Algorithms", 2013, public domain): the
819/// year counted from March, so that February's leap day falls at its end.
820fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
821    let year = if month <= 2 { year - 1 } else { year };
822    let era = year.div_euclid(400);
823    let year_of_era = year - era * 400;
824    let day_of_year = (153 * i64::from((month + 9) % 12) + 2) / 5 + i64::from(day) - 1;
825    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
826    era * 146_097 + day_of_era - 719_468
827}
828
829/// A time of day, `H:MM:SS` or `HH:MM:SS` with up to nine decimals, as ns after midnight; `None`
830/// for anything else, or a time past 23:59:60.999 999 999 (a leap second's).
831fn time_of_day_ns(cell: &str) -> Option<i64> {
832    let mut parts = cell.split(':');
833    let (hours, minutes, seconds) = (parts.next()?, parts.next()?, parts.next()?);
834    if parts.next().is_some() {
835        return None;
836    }
837    let (whole, fraction) = seconds.split_once('.').unwrap_or((seconds, ""));
838    if !digits(hours, 1..=2)
839        || !digits(minutes, 2..=2)
840        || !digits(whole, 2..=2)
841        || !(fraction.is_empty() || digits(fraction, 1..=9))
842        || (seconds.contains('.') && fraction.is_empty())
843    {
844        return None;
845    }
846    let (hours, minutes, whole): (i64, i64, i64) = (
847        hours.parse().ok()?,
848        minutes.parse().ok()?,
849        whole.parse().ok()?,
850    );
851    if hours >= 24 || minutes >= 60 || whole > 60 {
852        return None;
853    }
854    let mut nanos: i64 = 0;
855    for (place, digit) in fraction.bytes().enumerate() {
856        // At most nine digits, each place a tenth of the one before, from 10⁸ ns.
857        nanos += i64::from(digit - b'0') * 10_i64.pow(8 - u32::try_from(place).ok()?);
858    }
859    Some(((hours * 60 + minutes) * 60 + whole) * NS_PER_S + nanos)
860}
861
862/// A time's seconds after its midnight.
863fn seconds_of_day(instant: i64) -> f64 {
864    instant.rem_euclid(NS_PER_DAY) as f64 / NS_PER_S as f64
865}
866
867/// Seconds from one time to another, both ns on one clock.
868fn seconds_between(from: i64, to: i64) -> f64 {
869    // Both times lie within YEARS, so their difference fits an i64 of nanoseconds.
870    (to - from) as f64 / NS_PER_S as f64
871}
872
873/// The record: every tracker's channels, the decided units, and the notes.
874fn build(
875    layout: Layout,
876    columns: &[Column],
877    sets: Vec<Set>,
878    positions: &[Position],
879    first_row: &(String, i64),
880    notes: Notes,
881    file_notes: Vec<String>,
882) -> Result<FlightLog, LogError> {
883    let decisions = Decisions::from_file(columns, &sets);
884    let mut log = FlightLog {
885        format: LogFormat::FeatherweightGpsCsv,
886        logger: match layout {
887            Layout::Tracker => "Featherweight GPS tracker",
888            Layout::GroundStation => "Featherweight GPS ground station",
889        }
890        .to_owned(),
891        serial_number: None,
892        firmware: None,
893        flight_number: None,
894        stated: Stated::default(),
895        time_s: Vec::new(),
896        altitude_m: Vec::new(),
897        vertical_speed_m_s: None,
898        temperature_k: None,
899        battery_v: None,
900        channels: Vec::new(),
901        events: Vec::new(),
902        notes: decisions.notes.clone(),
903    };
904    log.notes.push(
905        "the log has no barometer, so the record's altitude track is empty: a GPS tracker's file \
906         holds positions only, and every column is a channel"
907            .to_owned(),
908    );
909    log.notes
910        .push(clock_note(layout, &sets, positions, first_row));
911    if let Some(note) = steps_back_note(&sets) {
912        log.notes.push(note);
913    }
914    if layout == Layout::GroundStation {
915        log.notes.push(trackers_note(&sets));
916    }
917    for position in positions.iter().filter(|p| p.zeros > 0) {
918        let names: Vec<String> = [Some(position.lat), Some(position.lon), position.alt]
919            .into_iter()
920            .flatten()
921            .map(|index| format!("`{}`", columns[index].name))
922            .collect();
923        log.notes.push(format!(
924            "{} rows have `{}` and `{}` both 0, as a receiver writes before it has a fix: their \
925             {} are read as gaps",
926            position.zeros,
927            columns[position.lat].name,
928            columns[position.lon].name,
929            list(&names)
930        ));
931    }
932    log.notes.extend(file_notes);
933    let mut notes = notes;
934    for column in columns.iter().filter(|c| c.gaps > 0) {
935        notes.push(format!(
936            "the column {:?} holds {} cells that are empty or not a number, such as {:?}: they \
937             are gaps",
938            short(&column.name),
939            column.gaps,
940            column.gap_example.as_deref().unwrap_or_default()
941        ));
942    }
943    for column in columns.iter().filter(|c| c.out_of_range > 0) {
944        let (what, most) = match column.role {
945            Role::Value(Kind::Stated(Quantity::Latitude, _)) => ("latitudes", "±90°"),
946            _ => ("longitudes", "±180°"),
947        };
948        notes.push(format!(
949            "the column {:?} holds {} {what} beyond {most}: they are gaps",
950            short(&column.name),
951            column.out_of_range
952        ));
953    }
954    log.notes.extend(notes.into_vec());
955
956    let zero = first_row.1;
957    let qualify = sets.len() > 1;
958    for set in sets {
959        let time_s: Vec<f64> = set
960            .times_ns
961            .iter()
962            .map(|&instant| seconds_between(zero, instant))
963            .collect();
964        for (column, values) in columns.iter().zip(set.values) {
965            let Some(quantity) = decisions.quantity(column.role) else {
966                continue;
967            };
968            let factor = decisions.factor(column.role);
969            let name = if qualify {
970                format!("{} [{}]", short(&column.name), short(&set.name))
971            } else {
972                column.name.clone()
973            };
974            // A value that the factor makes infinite, such as thousands of feet near the largest
975            // `f64`, is refused on its row's line (ADR-258 §3).
976            let mut si = Vec::with_capacity(values.len());
977            for (line, value) in set.lines.iter().zip(values) {
978                si.push(finite(value * factor, FORMAT, *line, &column.name)?);
979            }
980            log.channels.push(Channel {
981                column: name,
982                quantity,
983                time_s: time_s.clone(),
984                values: si,
985            });
986        }
987    }
988    Ok(log)
989}
990
991/// The note on the log's clock: its zero, and for the ground station the zone it doesn't state.
992fn clock_note(
993    layout: Layout,
994    sets: &[Set],
995    positions: &[Position],
996    first_row: &(String, i64),
997) -> String {
998    match layout {
999        Layout::Tracker => format!(
1000            "the log's clock is `UTCTIME`, read as UTC, and its zero is the first row's, {:?}",
1001            first_row.0
1002        ),
1003        Layout::GroundStation => {
1004            let solar = first_fix(sets, positions).map_or_else(
1005                || "The file has no fix to compare its `TIME` with the sun's".to_owned(),
1006                |(instant, longitude)| {
1007                    format!(
1008                        "At the first fix, `TIME` is {}. Read as UTC, that would be {:.1} h of \
1009                         local mean solar time at the fix's longitude",
1010                        clock_text(instant),
1011                        solar_hours(instant, longitude)
1012                    )
1013                },
1014            );
1015            format!(
1016                "`DATE` and `TIME` kept as written, in a time zone the file doesn't state. They \
1017                 are the log's clock, and its zero is the first row's, {:?}. {solar}",
1018                first_row.0
1019            )
1020        }
1021    }
1022}
1023
1024/// The first row, in the file's order, whose tracker position has a fix: its time and longitude.
1025fn first_fix(sets: &[Set], positions: &[Position]) -> Option<(i64, f64)> {
1026    let position = positions.first()?;
1027    sets.iter()
1028        .filter_map(|set| {
1029            (0..set.times_ns.len())
1030                .find(|&row| {
1031                    set.values[position.lat][row].is_finite()
1032                        && set.values[position.lon][row].is_finite()
1033                })
1034                .map(|row| (set.times_ns[row], set.values[position.lon][row]))
1035        })
1036        .min_by_key(|(instant, _)| *instant)
1037}
1038
1039/// A time's time of day, `HH:MM:SS.fff`, to the millisecond below it.
1040fn clock_text(instant: i64) -> String {
1041    let millis = instant.rem_euclid(NS_PER_DAY) / 1_000_000;
1042    format!(
1043        "{:02}:{:02}:{:02}.{:03}",
1044        millis / 3_600_000,
1045        millis / 60_000 % 60,
1046        millis / 1_000 % 60,
1047        millis % 1_000
1048    )
1049}
1050
1051/// The local mean solar time at a longitude, h, of a time read as UTC: the time of day plus the
1052/// longitude at 15° an hour, the Earth's mean turn, without the equation of time's quarter hour.
1053fn solar_hours(instant: i64, longitude_deg: f64) -> f64 {
1054    (seconds_of_day(instant) / 3_600.0 + longitude_deg / 15.0).rem_euclid(24.0)
1055}
1056
1057/// The note on times that go back or repeat within a tracker's rows, if any do.
1058fn steps_back_note(sets: &[Set]) -> Option<String> {
1059    let (mut backs, mut largest_ns, mut repeats) = (0usize, 0i64, 0usize);
1060    for set in sets {
1061        for pair in set.times_ns.windows(2) {
1062            if pair[1] < pair[0] {
1063                backs += 1;
1064                largest_ns = largest_ns.max(pair[0] - pair[1]);
1065            }
1066        }
1067        let mut sorted = set.times_ns.clone();
1068        sorted.sort_unstable();
1069        repeats += sorted.windows(2).filter(|pair| pair[0] == pair[1]).count();
1070    }
1071    let kept = "every row is kept, in the file's order";
1072    if backs > 0 {
1073        Some(format!(
1074            "times go back {backs} times from one row to the next, by up to {:.3} s, and {repeats} \
1075             rows repeat a time already written: {kept}",
1076            largest_ns as f64 / NS_PER_S as f64
1077        ))
1078    } else {
1079        (repeats > 0).then(|| format!("{repeats} rows repeat a time already written: {kept}"))
1080    }
1081}
1082
1083/// The note naming a ground station's trackers.
1084fn trackers_note(sets: &[Set]) -> String {
1085    match sets {
1086        [one] => format!(
1087            "the file holds one tracker's rows, {:?}, so its channels keep the header's names",
1088            short(&one.name)
1089        ),
1090        _ => {
1091            let names: Vec<String> = sets
1092                .iter()
1093                .map(|set| format!("{:?} ({} rows)", short(&set.name), set.times_ns.len()))
1094                .collect();
1095            format!(
1096                "the file holds {} trackers' rows, each its own set of channels named with the \
1097                 tracker in brackets, in the order they first appear: {}",
1098                sets.len(),
1099                list(&names)
1100            )
1101        }
1102    }
1103}
1104
1105/// The most names a note lists; past it, the rest are counted.
1106const MAX_LISTED: usize = 6;
1107
1108/// Names joined as `a`, `a and b`, or `a, b and c`; past [`MAX_LISTED`], the first few and a
1109/// count of the rest.
1110fn list(names: &[String]) -> String {
1111    if names.len() > MAX_LISTED {
1112        let shown = MAX_LISTED - 1;
1113        return format!(
1114            "{} and {} more",
1115            names[..shown].join(", "),
1116            names.len() - shown
1117        );
1118    }
1119    match names {
1120        [] => String::new(),
1121        [only] => only.clone(),
1122        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
1123    }
1124}
1125
1126/// What a speed check found.
1127#[derive(Debug, Clone, Copy, PartialEq)]
1128enum Check {
1129    /// The median ratio and the pairs it is over, in the band.
1130    Agrees(f64, usize),
1131    /// The same, outside the band.
1132    Disagrees(f64, usize),
1133    /// Fewer than [`MIN_PAIRS`] pairs, or no column to check.
1134    TooFew(usize),
1135}
1136
1137impl Check {
1138    fn from_ratios(mut ratios: Vec<f64>) -> Self {
1139        if ratios.len() < MIN_PAIRS {
1140            return Self::TooFew(ratios.len());
1141        }
1142        ratios.sort_by(f64::total_cmp);
1143        let median = ratios[ratios.len() / 2];
1144        if (AGREES.0..=AGREES.1).contains(&median) {
1145            Self::Agrees(median, ratios.len())
1146        } else {
1147            Self::Disagrees(median, ratios.len())
1148        }
1149    }
1150
1151    /// What the check found, such as `the change of `ALT` a second is a median of 1.012 times
1152    /// `VERTV` over 432 pairs of rows`, the change named by `change`.
1153    fn words(self, change: &str, speed: &str) -> String {
1154        match self {
1155            Self::Agrees(median, pairs) | Self::Disagrees(median, pairs) => format!(
1156                "{change} is a median of {median:.3} times `{speed}` over {pairs} pairs of rows"
1157            ),
1158            Self::TooFew(pairs) => format!(
1159                "the file has too few pairs of moving rows to check `{speed}` over, {pairs} of the \
1160                 {MIN_PAIRS} needed"
1161            ),
1162        }
1163    }
1164}
1165
1166/// What a speed is checked against.
1167#[derive(Debug, Clone, Copy)]
1168enum Track {
1169    /// An altitude column's change, as written.
1170    Height(usize),
1171    /// A position's great-circle distance, ft.
1172    Position(usize, usize),
1173}
1174
1175impl Track {
1176    /// The row's point, `None` if it has a gap.
1177    fn at(self, set: &Set, row: usize) -> Option<(f64, f64)> {
1178        let (a, b) = match self {
1179            Self::Height(column) => (set.values[column][row], 0.0),
1180            Self::Position(lat, lon) => (set.values[lat][row], set.values[lon][row]),
1181        };
1182        (a.is_finite() && b.is_finite()).then_some((a, b))
1183    }
1184
1185    /// The change from one point to another: up, as written, or a distance, ft.
1186    fn change(self, from: (f64, f64), to: (f64, f64)) -> f64 {
1187        match self {
1188            Self::Height(_) => to.0 - from.0,
1189            Self::Position(..) => great_circle_m(from, to) / FOOT_M,
1190        }
1191    }
1192}
1193
1194/// The great-circle distance between two positions in degrees, m, on a sphere of
1195/// [`EARTH_RADIUS_M`], by the haversine formula (Sinnott, "Virtues of the Haversine", *Sky and
1196/// Telescope* 68(2), 1984, p159).
1197fn great_circle_m(from: (f64, f64), to: (f64, f64)) -> f64 {
1198    let (lat1, lat2) = (from.0.to_radians(), to.0.to_radians());
1199    let (half_dlat, half_dlon) = ((lat2 - lat1) / 2.0, (to.1 - from.1).to_radians() / 2.0);
1200    let h = half_dlat.sin().powi(2) + lat1.cos() * lat2.cos() * half_dlon.sin().powi(2);
1201    2.0 * EARTH_RADIUS_M * h.sqrt().min(1.0).asin()
1202}
1203
1204/// The change of a track a second over a speed column, for each pair of rows a fix apart taken in
1205/// time order within each tracker: from the last row whose point differed, as the ground station
1206/// repeats a fix it hasn't heard anew, to the next that differs, more than [`MIN_STEP_S`] and
1207/// at most [`MAX_STEP_S`] later, at a speed of at least [`MIN_SPEED`] as written.
1208fn speed_check(sets: &[Set], track: Track, speed: usize) -> Check {
1209    let mut ratios = Vec::new();
1210    for set in sets {
1211        let mut order: Vec<usize> = (0..set.times_ns.len()).collect();
1212        order.sort_by_key(|&row| set.times_ns[row]);
1213        let mut start: Option<(usize, (f64, f64))> = None;
1214        for row in order {
1215            let Some(point) = track.at(set, row) else {
1216                start = None;
1217                continue;
1218            };
1219            if let Some((from, from_point)) = start {
1220                if point == from_point {
1221                    continue;
1222                }
1223                let step_s = seconds_between(set.times_ns[from], set.times_ns[row]);
1224                let speed = set.values[speed][row];
1225                if step_s > MIN_STEP_S && step_s <= MAX_STEP_S && speed.abs() >= MIN_SPEED {
1226                    ratios.push(track.change(from_point, point) / step_s / speed);
1227                }
1228            }
1229            start = Some((row, point));
1230        }
1231    }
1232    Check::from_ratios(ratios)
1233}
1234
1235/// Each decided kind: whether it is read in its unit, and the file's notes on them.
1236struct Decisions {
1237    heights: bool,
1238    vertical: bool,
1239    horizontal: bool,
1240    heading: bool,
1241    battery: bool,
1242    notes: Vec<String>,
1243}
1244
1245impl Decisions {
1246    fn from_file(columns: &[Column], sets: &[Set]) -> Self {
1247        let place = |name: &str| columns.iter().position(|c| c.name == name);
1248        let named = |kind: Kind| -> Vec<String> {
1249            columns
1250                .iter()
1251                .filter(|c| c.role == Role::Value(kind))
1252                .map(|c| format!("`{}`", short(&c.name)))
1253                .collect()
1254        };
1255        let values = |kind: Kind| {
1256            columns
1257                .iter()
1258                .enumerate()
1259                .filter(move |(_, c)| c.role == Role::Value(kind))
1260                .flat_map(move |(index, _)| sets.iter().flat_map(move |s| s.values[index].iter()))
1261                .copied()
1262                .filter(|value| value.is_finite())
1263        };
1264        let mut notes = Vec::new();
1265        let altitude = place("ALT").or_else(|| place("TRACKER Alt asl"));
1266        let position = place("LAT")
1267            .zip(place("LON"))
1268            .or_else(|| place("TRACKER Lat").zip(place("TRACKER Lon")));
1269        let altitude_name = altitude.map_or("ALT", |index| columns[index].name.as_str());
1270
1271        // One rule decides the file's lengths. `HORZV` against the distance between fixes is the
1272        // only check tied to an absolute length, so it and the manual decide the unit of every
1273        // length and speed the manual gives in feet; `VERTV` against the change of altitude only
1274        // shows whether `VERTV` is in the altitude's unit a second.
1275        let horizontal = match (position, place("HORZV")) {
1276            (Some((lat, lon)), Some(speed)) => speed_check(sets, Track::Position(lat, lon), speed),
1277            _ => Check::TooFew(0),
1278        };
1279        let vertical = match (altitude, place("VERTV")) {
1280            (Some(altitude), Some(speed)) => speed_check(sets, Track::Height(altitude), speed),
1281            _ => Check::TooFew(0),
1282        };
1283        let alt_agl = alt_agl_check(columns, sets);
1284        let feet = !matches!(horizontal, Check::Disagrees(..));
1285        let kept = if !feet {
1286            Some(Kept::HorizontalSpeed)
1287        } else if alt_agl.is_some_and(|check| !check.agrees()) {
1288            Some(Kept::AltAgl)
1289        } else if matches!(vertical, Check::Disagrees(..)) {
1290            Some(Kept::VerticalSpeed)
1291        } else {
1292            None
1293        };
1294        let horizontal_words =
1295            horizontal.words("the distance between fixes a second, in feet,", "HORZV");
1296        let vertical_words = vertical.words(
1297            &format!("the change of `{altitude_name}` a second"),
1298            "VERTV",
1299        );
1300
1301        if place("HORZV").is_some() {
1302            notes.push(match horizontal {
1303                Check::Agrees(..) => format!(
1304                    "`HORZV` read in feet per second, from the manual and the distance between \
1305                     fixes: {horizontal_words}"
1306                ),
1307                Check::TooFew(_) => format!(
1308                    "`HORZV` read in feet per second, from the manual alone: {horizontal_words}"
1309                ),
1310                Check::Disagrees(..) => format!(
1311                    "`HORZV` kept as written, the distance between fixes disagrees with the \
1312                     manual's feet per second. Here, {horizontal_words}. Every length and speed \
1313                     the manual gives in feet is kept as written with it"
1314                ),
1315            });
1316        }
1317
1318        let mut heights = named(Kind::Height {
1319            above_sea_level: true,
1320        });
1321        heights.extend(named(Kind::Height {
1322            above_sea_level: false,
1323        }));
1324        if !heights.is_empty() {
1325            let names = list(&heights);
1326            let mut evidence = vec![horizontal_words.clone()];
1327            if place("VERTV").is_some() {
1328                evidence.push(vertical_words.clone());
1329            }
1330            evidence.extend(alt_agl.map(AltAgl::words));
1331            evidence.extend(altitude_agl_words(columns, sets));
1332            let evidence = evidence.join("; ");
1333            notes.push(match kept {
1334                Some(why) => format!("{names} kept as written, {}: {evidence}", why.words()),
1335                None => {
1336                    let by_horizontal = matches!(horizontal, Check::Agrees(..));
1337                    let by_alt_agl = alt_agl.is_some_and(|check| check.rows > 0);
1338                    let source = match (by_horizontal, by_alt_agl) {
1339                        (true, false) => "from the manual and the horizontal speed",
1340                        (false, false) => "from the manual alone",
1341                        (true, true) => "from the manual, the horizontal speed and `Alt AGL (ft)`",
1342                        (false, true) => "from the manual and `Alt AGL (ft)`",
1343                    };
1344                    format!("{names} read in feet, {source}: {evidence}")
1345                }
1346            });
1347        }
1348
1349        if place("VERTV").is_some() {
1350            notes.push(match (kept, altitude, vertical) {
1351                (Some(Kept::VerticalSpeed), ..) => format!(
1352                    "`VERTV` kept as written, not in the altitude's unit a second: \
1353                     {vertical_words}"
1354                ),
1355                (Some(why), ..) => {
1356                    format!("`VERTV` kept as written, {}: {vertical_words}", why.words())
1357                }
1358                (None, None, _) => "`VERTV` read in feet per second, from the manual alone: the \
1359                                    file has no altitude to compare it with"
1360                    .to_owned(),
1361                (None, Some(_), Check::TooFew(_)) => format!(
1362                    "`VERTV` read in feet per second, in the altitude's unit, from the \
1363                     manual alone: {vertical_words}"
1364                ),
1365                (None, Some(_), _) => format!(
1366                    "`VERTV` read in feet per second, in the altitude's unit, from the \
1367                     change of altitude: {vertical_words}"
1368                ),
1369            });
1370        }
1371        let heights_read = kept.is_none();
1372
1373        let heading = values(Kind::Heading).fold(None, range);
1374        let heading_read = heading.is_none_or(|(lo, hi): (f64, f64)| lo >= -360.0 && hi <= 360.0);
1375        if place("HEAD").is_some() {
1376            let evidence = heading.map_or_else(
1377                || "the column holds no value; the manual gives degrees from north".to_owned(),
1378                |(lo, hi)| format!("it runs from {lo} to {hi}"),
1379            );
1380            notes.push(if heading_read {
1381                format!("`HEAD` read in degrees, from the manual and its range: {evidence}")
1382            } else {
1383                format!(
1384                    "`HEAD` kept as written, its range disagrees with the manual's degrees: \
1385                     {evidence}"
1386                )
1387            });
1388        }
1389
1390        let battery = values(Kind::Battery).fold(None, range);
1391        let battery_read = battery.is_none_or(|(lo, hi): (f64, f64)| lo >= 0.0 && hi <= MAX_CELL_V);
1392        if place("BATT").is_some() {
1393            let evidence = match battery {
1394                None => "the column holds no value".to_owned(),
1395                Some((lo, hi)) if lo == 0.0 && hi == 0.0 => {
1396                    "it reads 0 on every row, which no unit changes".to_owned()
1397                }
1398                Some((lo, hi)) => format!(
1399                    "it runs from {lo} to {hi}, where one lithium cell reads up to about 4.2 V and \
1400                     the ground station's serial millivolts would be thousands"
1401                ),
1402            };
1403            notes.push(if battery_read {
1404                format!("`BATT` read in volts, from its range: {evidence}")
1405            } else {
1406                format!(
1407                    "`BATT` kept as written, its range isn't one lithium cell's volts: {evidence}"
1408                )
1409            });
1410        }
1411
1412        if let Some(note) = unix_note(columns, sets) {
1413            notes.push(note);
1414        }
1415        Self {
1416            heights: heights_read,
1417            vertical: heights_read,
1418            horizontal: feet,
1419            heading: heading_read,
1420            battery: battery_read,
1421            notes,
1422        }
1423    }
1424
1425    /// A column's quantity, `None` for one that is no channel.
1426    fn quantity(&self, role: Role) -> Option<Quantity> {
1427        let decided = |read: bool, quantity| {
1428            if read {
1429                quantity
1430            } else {
1431                Quantity::Unrecognized
1432            }
1433        };
1434        Some(match role {
1435            Role::Date | Role::Tracker | Role::Label => return None,
1436            Role::Clock | Role::Time => Quantity::TimeOfDay,
1437            Role::Value(kind) => match kind {
1438                Kind::Height {
1439                    above_sea_level: true,
1440                } => decided(self.heights, Quantity::GnssAltitude),
1441                Kind::Height {
1442                    above_sea_level: false,
1443                } => decided(self.heights, Quantity::Distance),
1444                Kind::VerticalSpeed => decided(self.vertical, Quantity::Speed),
1445                Kind::HorizontalSpeed => decided(self.horizontal, Quantity::Speed),
1446                Kind::Heading => decided(self.heading, Quantity::Angle),
1447                Kind::Battery => decided(self.battery, Quantity::Voltage),
1448                Kind::UnixTime | Kind::Unknown => Quantity::Unrecognized,
1449                Kind::Stated(quantity, _) => quantity,
1450            },
1451        })
1452    }
1453
1454    /// A column's factor into SI, 1 for one kept as written.
1455    fn factor(&self, role: Role) -> f64 {
1456        match role {
1457            Role::Value(Kind::Height { .. }) if self.heights => FOOT_M,
1458            Role::Value(Kind::VerticalSpeed) if self.vertical => FOOT_M,
1459            Role::Value(Kind::HorizontalSpeed) if self.horizontal => FOOT_M,
1460            Role::Value(Kind::Stated(_, factor)) => factor,
1461            _ => 1.0,
1462        }
1463    }
1464}
1465
1466/// The lowest and highest of a list, folded.
1467fn range(acc: Option<(f64, f64)>, value: f64) -> Option<(f64, f64)> {
1468    Some(acc.map_or((value, value), |(lo, hi)| (lo.min(value), hi.max(value))))
1469}
1470
1471/// Why the heights and `VERTV` are kept as written, in the order the rule asks.
1472#[derive(Debug, Clone, Copy, PartialEq)]
1473enum Kept {
1474    /// `HORZV` disagrees with the distance between fixes in feet: the file's lengths aren't the
1475    /// manual's feet.
1476    HorizontalSpeed,
1477    /// `Alt AGL (ft)`, whose header says feet, isn't the heights' difference.
1478    AltAgl,
1479    /// `VERTV` isn't the change of the altitude a second.
1480    VerticalSpeed,
1481}
1482
1483impl Kept {
1484    /// Why, as a heights' note says before its colon.
1485    fn words(self) -> &'static str {
1486        match self {
1487            Self::HorizontalSpeed => "the horizontal speed disagrees with the manual's feet",
1488            Self::AltAgl => "`Alt AGL (ft)` disagrees with the manual's feet",
1489            Self::VerticalSpeed => "`VERTV` isn't their change a second",
1490        }
1491    }
1492}
1493
1494/// The longer ground-station log's check of its heights: on how many rows `Alt AGL (ft)`, whose
1495/// header says feet, is `TRACKER Alt asl` less `GS Alt asl` and `GS_ASL_offset`, to 0.15 ft.
1496#[derive(Debug, Clone, Copy, PartialEq)]
1497struct AltAgl {
1498    held: usize,
1499    rows: usize,
1500}
1501
1502impl AltAgl {
1503    /// Whether the heights are the header's feet: the difference holds on half the rows or more,
1504    /// or there is no row to check.
1505    fn agrees(self) -> bool {
1506        self.rows == 0 || self.held * 2 >= self.rows
1507    }
1508
1509    fn words(self) -> String {
1510        format!(
1511            "`Alt AGL (ft)` is `TRACKER Alt asl` less `GS Alt asl` and `GS_ASL_offset`, to 0.15 ft, \
1512             on {} of {} rows",
1513            self.held, self.rows
1514        )
1515    }
1516}
1517
1518/// The longer ground-station log's [`AltAgl`] check, `None` for a file without its four columns.
1519fn alt_agl_check(columns: &[Column], sets: &[Set]) -> Option<AltAgl> {
1520    let place = |name: &str| columns.iter().position(|c| c.name == name);
1521    let ((agl, tracker), (station, offset)) =
1522        place("Alt AGL (ft)")
1523            .zip(place("TRACKER Alt asl"))
1524            .zip(place("GS Alt asl").zip(place("GS_ASL_offset")))?;
1525    let (mut held, mut rows) = (0usize, 0usize);
1526    for set in sets {
1527        for row in 0..set.times_ns.len() {
1528            let at = |column: usize| set.values[column][row];
1529            let residual = at(agl) - (at(tracker) - at(station) - at(offset));
1530            if residual.is_finite() {
1531                rows += 1;
1532                held += usize::from(residual.abs() <= 0.15);
1533            }
1534        }
1535    }
1536    Some(AltAgl { held, rows })
1537}
1538
1539/// What the newer tracker log's `Altitude AGL` shows: on how many rows it is `ALT` less one
1540/// height, the pad's. It doesn't decide a unit, as both are in the file's one unit.
1541fn altitude_agl_words(columns: &[Column], sets: &[Set]) -> Option<String> {
1542    let place = |name: &str| columns.iter().position(|c| c.name == name);
1543    let (altitude, agl) = place("ALT").zip(place("Altitude AGL"))?;
1544    #[allow(
1545        clippy::cast_possible_truncation,
1546        reason = "finite by the filter; one past an i64's span saturates, matching none inside it"
1547    )]
1548    let mut differences: Vec<i64> = sets
1549        .iter()
1550        .flat_map(|set| {
1551            set.values[altitude]
1552                .iter()
1553                .zip(&set.values[agl])
1554                .map(|(alt, agl)| alt - agl)
1555        })
1556        .filter(|difference| difference.is_finite())
1557        // Tenths of a foot, as the newer log writes both; a difference past an i64's span
1558        // saturates, and so matches no difference inside it.
1559        .map(|difference| (difference * 10.0).round() as i64)
1560        .collect();
1561    differences.sort_unstable();
1562    let rows = differences.len();
1563    let most = differences
1564        .chunk_by(|a, b| a == b)
1565        .map(<[i64]>::len)
1566        .max()
1567        .unwrap_or(0);
1568    Some(format!(
1569        "`Altitude AGL` is `ALT` less one height, to 0.05 ft, on {most} of {rows} rows, as a \
1570         height above the pad is"
1571    ))
1572}
1573
1574/// The note on `UNIXTIME`: how far it runs from `UTCTIME`, and where each would put the sun.
1575fn unix_note(columns: &[Column], sets: &[Set]) -> Option<String> {
1576    let unix = columns
1577        .iter()
1578        .position(|c| c.role == Role::Value(Kind::UnixTime))?;
1579    // The offsets are taken from each row's time, which is `UTCTIME`'s in a tracker's log.
1580    columns.iter().find(|c| c.role == Role::Clock)?;
1581    let lon = columns.iter().position(|c| c.name == "LON");
1582    let mut offsets: Vec<f64> = Vec::new();
1583    let mut solar: Option<(f64, f64)> = None;
1584    for set in sets {
1585        for (row, &instant) in set.times_ns.iter().enumerate() {
1586            let written = set.values[unix][row];
1587            if !written.is_finite() {
1588                continue;
1589            }
1590            let utc_s = instant.div_euclid(NS_PER_S) as f64
1591                + instant.rem_euclid(NS_PER_S) as f64 / NS_PER_S as f64;
1592            offsets.push(written - utc_s);
1593            if solar.is_none()
1594                && let Some(longitude) = lon.map(|lon| set.values[lon][row])
1595                && longitude.is_finite()
1596            {
1597                let unix_of_day = written.rem_euclid(86_400.0) / 3_600.0;
1598                solar = Some((
1599                    solar_hours(instant, longitude),
1600                    (unix_of_day + longitude / 15.0).rem_euclid(24.0),
1601                ));
1602            }
1603        }
1604    }
1605    let hours = offsets.first().map(|offset| (offset / 3_600.0).round())?;
1606    // Cells written to the millisecond, so a whole number of hours is met to well within 0.01 s.
1607    let whole = offsets
1608        .iter()
1609        .all(|offset| (offset - hours * 3_600.0).abs() < 0.01);
1610    let sun = solar.map_or_else(String::new, |(utc, unix)| {
1611        format!(
1612            ". Read as UTC at the first fix's longitude, `UTCTIME` gives {utc:.1} h of local mean \
1613             solar time and `UNIXTIME` {unix:.1} h"
1614        )
1615    });
1616    Some(if whole {
1617        let offset = if hours >= 0.0 {
1618            format!("{hours} h ahead of")
1619        } else {
1620            format!("{} h behind", -hours)
1621        };
1622        format!(
1623            "`UNIXTIME` kept as written, off `UTCTIME` by whole hours: it runs {offset} \
1624             `UTCTIME` on every row{sun}"
1625        )
1626    } else {
1627        let (lo, hi) = offsets
1628            .iter()
1629            .copied()
1630            .fold(None, range)
1631            .unwrap_or_default();
1632        format!(
1633            "`UNIXTIME` kept as written, off `UTCTIME` by other than one whole number of hours. \
1634             It runs from {lo:.3} s to {hi:.3} s ahead of `UTCTIME`{sun}"
1635        )
1636    })
1637}
1638
1639fn syntax(line: usize, message: String) -> LogError {
1640    LogError::Syntax {
1641        format: FORMAT,
1642        line,
1643        message,
1644    }
1645}
1646
1647#[cfg(test)]
1648mod tests {
1649    use super::*;
1650
1651    const OLDER: &str =
1652        "UTCTIME,UNIXTIME,ALT,LAT,LON,#SATS,FIX,HORZV,VERTV,HEAD,FLAGS,>40,>32,>24,RSSI,BATT";
1653    const GROUND: &str =
1654        "TRACKER,DATE,TIME,LAT,LON,ALT,FIX,HORZV,VERTV,HEAD,FLAGS,#TOT,>40,>32,>24,RSSI,BATT";
1655    const LONGER: &str = "TRACKER,DATE,TIME,GS Lat,GS Lon,GS Alt asl,TRACKER Lat,TRACKER Lon,\
1656        TRACKER Alt asl,FIX,HORZV,VERTV,HEAD,FLAGS,#TOT,>40,>32,>24,RSSI Down,RSSI Up,\
1657        Horizontal range (ft),Alt AGL (ft),Total range (ft),LoRa Max Range (kft),\
1658        LoRa Success Rate,BATT,GS_batt_v,Down Sent,Down Rcvd,Found Sent,Up Sent,Up Rccvd,\
1659        Found rocket ID,Found rocket lat,Found rocket lon,Found rocket altitude,Found rocket fix,\
1660        Found rocket batt_v,Found RSSI,GS_ASL_offset";
1661
1662    /// Meters per degree of latitude on the reader's sphere.
1663    fn degree_m() -> f64 {
1664        EARTH_RADIUS_M.to_radians()
1665    }
1666
1667    /// An older tracker log of rows a second apart: each row's altitude, its upward and
1668    /// horizontal speeds as written, moving north by 30 ft a row.
1669    fn tracker_file(rows: usize, alt: impl Fn(usize) -> f64, vertv: f64, horzv: f64) -> String {
1670        tracker_file_with(rows, alt, vertv, horzv, 90, "4.0")
1671    }
1672
1673    /// [`tracker_file`] with a heading and a battery cell.
1674    fn tracker_file_with(
1675        rows: usize,
1676        alt: impl Fn(usize) -> f64,
1677        vertv: f64,
1678        horzv: f64,
1679        head: i32,
1680        batt: &str,
1681    ) -> String {
1682        moving_file(rows, alt, vertv, horzv, 30.0 * FOOT_M, head, batt)
1683    }
1684
1685    /// [`tracker_file_with`] moving north by `step_m` meters a row.
1686    fn moving_file(
1687        rows: usize,
1688        alt: impl Fn(usize) -> f64,
1689        vertv: f64,
1690        horzv: f64,
1691        step_m: f64,
1692        head: i32,
1693        batt: &str,
1694    ) -> String {
1695        let mut text = format!("{OLDER}\n");
1696        for row in 0..rows {
1697            let lat = 40.0 + step_m * row as f64 / degree_m();
1698            text.push_str(&format!(
1699                "Jun 1 2025 18:00:{row:02}.000 UTC,{}.000,{},{lat:.7},-105.0,12,3,{horzv},{vertv},\
1700                 {head},0x03,1,2,3,-50,{batt}\n",
1701                1_748_800_800 + row,
1702                alt(row)
1703            ));
1704        }
1705        text
1706    }
1707
1708    fn channel<'a>(log: &'a FlightLog, column: &str) -> &'a Channel {
1709        log.channels.iter().find(|c| c.column == column).unwrap()
1710    }
1711
1712    fn close(a: f64, b: f64) -> bool {
1713        (a - b).abs() <= 1e-9 * b.abs().max(1.0)
1714    }
1715
1716    fn climbing(row: usize) -> f64 {
1717        1000.0 + 100.0 * row as f64
1718    }
1719
1720    #[test]
1721    fn the_four_headers_are_recognized_and_nothing_else() {
1722        let newer = format!(
1723            "{OLDER},Altitude AGL,Launch detection,Apogee detection,Landing detection,\
1724             Distance (feet)"
1725        );
1726        for header in [OLDER, newer.as_str(), GROUND, LONGER] {
1727            assert!(
1728                recognizes(&format!("\u{feff}\r\n\n{header}\r\n")),
1729                "{header}"
1730            );
1731            assert!(recognizes(&header.replace(',', " , ")), "{header}");
1732        }
1733        for other in [
1734            "",
1735            "UTCTIME,UNIXTIME,ALT\n",
1736            "UNIXTIME,UTCTIME,ALT,LAT,LON\n",
1737            "utctime,unixtime,alt,lat,lon\n",
1738            "TRACKER,DATE,TIME,ALT,FIX\n",
1739            "TRACKER,DATE,TIME,GS Lat,GS Lon\n",
1740            "DATE,TIME,LAT,LON\n",
1741            "Time,Altitude,Velocity\n",
1742            "Year,Month,Day,Time,Flight_Time_(s),Sync,Gyro_X\n",
1743            "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\n",
1744        ] {
1745            assert!(!recognizes(other), "{other:?}");
1746        }
1747    }
1748
1749    /// `UTCTIME` against a hand computation, each month's name, leap days by the Gregorian rule,
1750    /// and a strict reading of everything else.
1751    #[test]
1752    fn tracker_times_are_read_strictly() {
1753        // 2031-07-14 17:04:31.250 UTC is 1,941,815,071.25 s after 1970.
1754        assert_eq!(
1755            utc_time("Jul 14 2031 17:04:31.250 UTC"),
1756            Some(1_941_815_071_250_000_000)
1757        );
1758        assert_eq!(utc_time("Jan 1 1970 00:00:00 UTC"), Some(0));
1759        assert_eq!(
1760            utc_time("jul  14 2031 17:04:31.250   UTC"),
1761            utc_time("Jul 14 2031 17:04:31.250 UTC")
1762        );
1763        let months = [
1764            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
1765        ];
1766        let mut last = i64::MIN;
1767        for month in months {
1768            let time = utc_time(&format!("{month} 1 2026 00:00:00 UTC")).unwrap();
1769            assert!(time > last, "{month}");
1770            last = time;
1771        }
1772        // 2024-02-29 is day 19,782 after 1970-01-01; the next day is March 1.
1773        assert_eq!(
1774            utc_time("Feb 29 2024 00:00:00 UTC"),
1775            Some(19_782 * NS_PER_DAY)
1776        );
1777        assert_eq!(
1778            utc_time("Mar 1 2024 00:00:00 UTC"),
1779            Some(19_783 * NS_PER_DAY)
1780        );
1781        assert!(
1782            utc_time("Feb 29 2000 12:00:00 UTC").is_some(),
1783            "divisible by 400"
1784        );
1785        for bad in [
1786            "Feb 29 2023 12:00:00 UTC",
1787            "Feb 29 2100 12:00:00 UTC",
1788            "Apr 31 2021 12:00:00 UTC",
1789            "Apr 0 2021 12:00:00 UTC",
1790            "Jul 14 2031 17:04:31.250",
1791            "Jul 14 2031 17:04:31.250 GMT",
1792            "Jul 14 2031 17:04:31.250 UTC x",
1793            "July 14 2031 17:04:31 UTC",
1794            "Jul 14 31 17:04:31 UTC",
1795            "Jul 14 1969 17:04:31 UTC",
1796            "Jul 14 2200 17:04:31 UTC",
1797            "Jul 100 2031 17:04:31 UTC",
1798            "Jul 14 2031 24:00:00 UTC",
1799            "",
1800        ] {
1801            assert_eq!(utc_time(bad), None, "{bad:?}");
1802        }
1803    }
1804
1805    #[test]
1806    fn ground_station_dates_and_times_are_read_strictly() {
1807        // 2000-03-01 is day 11,017; 2199-12-31, the last day read, day 84,005.
1808        assert_eq!(civil_date("2000-03-01"), Some(11_017));
1809        assert_eq!(civil_date("2199-12-31"), Some(84_005));
1810        assert_eq!(civil_date("2026-1-8"), civil_date("2026-01-08"));
1811        for bad in [
1812            "31-07-14",
1813            "2026-13-01",
1814            "2026-02-29",
1815            "2031-07-14-1",
1816            "2031/07/14",
1817            "",
1818        ] {
1819            assert_eq!(civil_date(bad), None, "{bad:?}");
1820        }
1821        assert_eq!(time_of_day_ns("0:00:00"), Some(0));
1822        assert_eq!(time_of_day_ns("14:27:09.375"), Some(52_029_375_000_000));
1823        assert_eq!(
1824            time_of_day_ns("23:59:60.123456789"),
1825            Some(86_400_123_456_789)
1826        );
1827        for bad in [
1828            "12:00",
1829            "12:00:00:00",
1830            "24:00:00",
1831            "12:60:00",
1832            "12:00:61",
1833            "12:5:00",
1834            "123:00:00",
1835            "12:00:00.",
1836            "12:00:00.1234567890",
1837            "12:00:00.x",
1838            "-1:00:00",
1839            "12:00:+1",
1840        ] {
1841            assert_eq!(time_of_day_ns(bad), None, "{bad:?}");
1842        }
1843        // A day's rollover is the date's: the last second of a year, then the first of the next.
1844        let before = civil_date("2025-12-31").unwrap() * NS_PER_DAY
1845            + time_of_day_ns("23:59:59.500").unwrap();
1846        let after = civil_date("2026-01-01").unwrap() * NS_PER_DAY
1847            + time_of_day_ns("00:00:00.250").unwrap();
1848        assert_eq!(seconds_between(before, after), 0.75);
1849        assert_eq!(clock_text(before), "23:59:59.500");
1850    }
1851
1852    #[test]
1853    fn cells_are_numbers_flags_hexadecimal_or_percentages() {
1854        assert_eq!(value("1.5"), Some(1.5));
1855        assert_eq!(value("-82"), Some(-82.0));
1856        assert_eq!(value("TRUE"), Some(1.0));
1857        assert_eq!(value("FALSE"), Some(0.0));
1858        assert_eq!(value("0x03"), Some(3.0));
1859        assert_eq!(value("0xff"), Some(255.0));
1860        assert_eq!(value("67%"), Some(67.0));
1861        assert_eq!(value("100%"), Some(100.0));
1862        for bad in [
1863            "",
1864            "NaN",
1865            "inf",
1866            "true",
1867            "0x",
1868            "0xg",
1869            "67 %",
1870            "%",
1871            "x",
1872            "0x12345678901234",
1873        ] {
1874            assert_eq!(value(bad), None, "{bad:?}");
1875        }
1876    }
1877
1878    /// The great-circle distance against a hand computation: a degree of latitude is
1879    /// 6,371,008.8 m × π / 180 = 111,195.08 m.
1880    #[test]
1881    fn a_degree_of_latitude_is_its_arc() {
1882        assert!((great_circle_m((40.0, -105.0), (41.0, -105.0)) - 111_195.08).abs() < 0.01);
1883        assert_eq!(great_circle_m((40.0, -105.0), (40.0, -105.0)), 0.0);
1884    }
1885
1886    /// A file whose speeds agree with the change of its altitude and position reads them in feet
1887    /// per second, and its altitude in feet.
1888    #[test]
1889    fn speeds_that_agree_are_read_in_feet_per_second() {
1890        let log = read(&tracker_file(14, climbing, 100.0, 30.0)).unwrap();
1891        let up = channel(&log, "VERTV");
1892        assert_eq!(up.quantity, Quantity::Speed);
1893        assert!(close(up.values[0], 30.48));
1894        assert!(close(channel(&log, "HORZV").values[0], 30.0 * FOOT_M));
1895        let alt = channel(&log, "ALT");
1896        assert_eq!(alt.quantity, Quantity::GnssAltitude);
1897        assert!(close(alt.values[0], 304.8), "1000 ft is 304.8 m");
1898        assert_eq!(
1899            log.notes[..3],
1900            [
1901                "`HORZV` read in feet per second, from the manual and the distance between fixes: \
1902                 the distance between fixes a second, in feet, is a median of 1.000 times `HORZV` \
1903                 over 13 pairs of rows",
1904                "`ALT` read in feet, from the manual and the horizontal speed: the distance between \
1905                 fixes a second, in feet, is a median of 1.000 times `HORZV` over 13 pairs of rows; \
1906                 the change of `ALT` a second is a median of 1.000 times `VERTV` over 13 pairs of \
1907                 rows",
1908                "`VERTV` read in feet per second, in the altitude's unit, from the change of altitude: the \
1909                 change of `ALT` a second is a median of 1.000 times `VERTV` over 13 pairs of rows",
1910            ],
1911            "{:#?}",
1912            log.notes
1913        );
1914    }
1915
1916    /// The review's file, all in meters: `ALT` from 1000 rising 50 a second, `VERTV` 50, and
1917    /// `HORZV` 25 over fixes 25 m apart, 30 rows a second apart. `VERTV` matches the change of
1918    /// `ALT`, as it would in feet; only `HORZV` against the distance between fixes, 3.28 times it
1919    /// in feet, shows the file isn't in feet, and every length and speed is kept as written.
1920    #[test]
1921    fn a_file_all_in_meters_keeps_its_lengths_as_written() {
1922        let rising = |row: usize| 1000.0 + 50.0 * row as f64;
1923        let log = read(&moving_file(30, rising, 50.0, 25.0, 25.0, 90, "4.0")).unwrap();
1924        for (column, written) in [("ALT", 1000.0), ("VERTV", 50.0), ("HORZV", 25.0)] {
1925            let channel = channel(&log, column);
1926            assert_eq!(channel.quantity, Quantity::Unrecognized, "{column}");
1927            assert_eq!(channel.values[0], written, "{column}");
1928        }
1929        let why = "the horizontal speed disagrees with the manual's feet: ";
1930        assert!(
1931            log.notes[0].starts_with(
1932                "`HORZV` kept as written, the distance between fixes disagrees with the manual's \
1933                 feet per second. Here, the distance between fixes a second, in feet, is a median \
1934                 of 3.280 times `HORZV` over 29 pairs of rows"
1935            ),
1936            "{:#?}",
1937            log.notes
1938        );
1939        assert!(log.notes[1].starts_with(&format!("`ALT` kept as written, {why}")));
1940        assert_eq!(
1941            log.notes[2],
1942            format!(
1943                "`VERTV` kept as written, {why}the change of `ALT` a second is a median of 1.000 \
1944                 times `VERTV` over 29 pairs of rows"
1945            )
1946        );
1947    }
1948
1949    /// The same flight written in feet, as the manual gives it: read in feet and feet per second.
1950    #[test]
1951    fn the_same_file_in_feet_reads_in_feet() {
1952        let ft = 1.0 / FOOT_M;
1953        let rising = |row: usize| (1000.0 + 50.0 * row as f64) / FOOT_M;
1954        let log = read(&moving_file(
1955            30,
1956            rising,
1957            50.0 * ft,
1958            25.0 * ft,
1959            25.0,
1960            90,
1961            "4.0",
1962        ))
1963        .unwrap();
1964        for (column, quantity, si) in [
1965            ("ALT", Quantity::GnssAltitude, 1000.0),
1966            ("VERTV", Quantity::Speed, 50.0),
1967            ("HORZV", Quantity::Speed, 25.0),
1968        ] {
1969            let channel = channel(&log, column);
1970            assert_eq!(channel.quantity, quantity, "{column}");
1971            assert!(
1972                close(channel.values[0], si),
1973                "{column}: {}",
1974                channel.values[0]
1975            );
1976        }
1977        assert!(
1978            log.notes[1].starts_with(
1979                "`ALT` read in feet, from the manual and the horizontal speed: the distance \
1980                 between fixes a second, in feet, is a median of 1.000 times `HORZV` over 29 pairs \
1981                 of rows"
1982            ),
1983            "{:#?}",
1984            log.notes
1985        );
1986    }
1987
1988    /// A file whose `VERTV` is in meters per second, 3.28 times smaller than the change of `ALT`
1989    /// in feet a second: `VERTV` and the heights kept as written, with notes saying so.
1990    #[test]
1991    fn a_vertical_speed_that_disagrees_is_kept_as_written() {
1992        let log = read(&tracker_file(14, climbing, 30.48, 30.0)).unwrap();
1993        let up = channel(&log, "VERTV");
1994        assert_eq!(up.quantity, Quantity::Unrecognized);
1995        assert_eq!(up.values[0], 30.48);
1996        let alt = channel(&log, "ALT");
1997        assert_eq!(alt.quantity, Quantity::Unrecognized);
1998        assert_eq!(alt.values[0], 1000.0);
1999        assert_eq!(
2000            log.notes[2],
2001            "`VERTV` kept as written, not in the altitude's unit a second: the change of `ALT` a second is \
2002             a median of 3.281 times `VERTV` over 13 pairs of rows"
2003        );
2004        assert!(
2005            log.notes[1]
2006                .starts_with("`ALT` kept as written, `VERTV` isn't their change a second: ")
2007        );
2008        // `HORZV` still agrees with the positions, so it is read on its own.
2009        assert_eq!(channel(&log, "HORZV").quantity, Quantity::Speed);
2010    }
2011
2012    /// A `HORZV` in miles per hour (1.467 times smaller than feet per second), a heading past
2013    /// ±360 and a battery in millivolts are each kept as written.
2014    #[test]
2015    fn horizontal_speed_heading_and_battery_that_disagree_are_kept() {
2016        let mph = 30.0 / 1.466_667;
2017        let log = read(&tracker_file_with(14, climbing, 100.0, mph, 400, "4010")).unwrap();
2018        let horizontal = channel(&log, "HORZV");
2019        assert_eq!(horizontal.quantity, Quantity::Unrecognized);
2020        assert!(close(horizontal.values[0], mph));
2021        assert_eq!(channel(&log, "HEAD").quantity, Quantity::Unrecognized);
2022        assert_eq!(channel(&log, "BATT").quantity, Quantity::Unrecognized);
2023        assert_eq!(channel(&log, "BATT").values[0], 4010.0);
2024        let notes = log.notes.join("\n");
2025        // A `HORZV` that isn't feet per second leaves the file's lengths as written too.
2026        assert_eq!(channel(&log, "ALT").quantity, Quantity::Unrecognized);
2027        assert_eq!(channel(&log, "VERTV").quantity, Quantity::Unrecognized);
2028        for expected in [
2029            "`HORZV` kept as written, the distance between fixes disagrees with the manual's feet \
2030             per second. Here, the distance between fixes a second, in feet, is a median of \
2031             1.466 times",
2032            "`HEAD` kept as written, its range disagrees with the manual's degrees: it runs from \
2033             400 to 400",
2034            "`BATT` kept as written, its range isn't one lithium cell's volts: it runs from 4010 \
2035             to 4010",
2036        ] {
2037            assert!(notes.contains(expected), "{expected}\n{notes}");
2038        }
2039        // Just inside the band, the speed reads in feet per second; just outside, as written.
2040        let inside = read(&tracker_file(14, climbing, 100.0, 30.0 / 1.39)).unwrap();
2041        assert_eq!(channel(&inside, "HORZV").quantity, Quantity::Speed);
2042        let outside = read(&tracker_file(14, climbing, 100.0, 30.0 / 1.41)).unwrap();
2043        assert_eq!(channel(&outside, "HORZV").quantity, Quantity::Unrecognized);
2044    }
2045
2046    /// Too few pairs of moving rows leave the manual's unit, with a note saying the file can't
2047    /// tell.
2048    #[test]
2049    fn too_few_pairs_leave_the_manuals_unit() {
2050        let log = read(&tracker_file(5, climbing, 30.48, 9.0)).unwrap();
2051        assert_eq!(channel(&log, "VERTV").quantity, Quantity::Speed);
2052        assert_eq!(channel(&log, "ALT").quantity, Quantity::GnssAltitude);
2053        assert_eq!(
2054            log.notes[..3],
2055            [
2056                "`HORZV` read in feet per second, from the manual alone: the file has too few \
2057                 pairs of moving rows to check `HORZV` over, 0 of the 10 needed",
2058                "`ALT` read in feet, from the manual alone: the file has too few pairs of moving \
2059                 rows to check `HORZV` over, 0 of the 10 needed; the file has too few pairs of \
2060                 moving rows to check `VERTV` over, 4 of the 10 needed",
2061                "`VERTV` read in feet per second, in the altitude's unit, from the manual alone: the file \
2062                 has too few pairs of moving rows to check `VERTV` over, 4 of the 10 needed",
2063            ]
2064        );
2065    }
2066
2067    /// A range in thousands of feet near the largest `f64` is finite as written and infinite in
2068    /// meters: refused on its row's line (ADR-258 §3).
2069    #[test]
2070    fn a_value_its_conversion_makes_infinite_is_refused() {
2071        let row = |range: &str| {
2072            format!(
2073                "T,2026-03-08,09:15:10,20,-100,3000,20.001,-100,4000,3,4,0,45,0x01,24,6,12,2,-50,\
2074                 -55,364.8,1005,0,{range},100%,4.0,4.1,1,1,0,1,1,,0,0,0,0,0,-60,-5"
2075            )
2076        };
2077        let file = format!("{LONGER}\n{}\n{}\n", row("12.5"), row("1.7e308"));
2078        assert_eq!(
2079            read(&file).unwrap_err().to_string(),
2080            "Featherweight GPS CSV line 3: the column LoRa Max Range (kft) holds a value too \
2081             large for its unit's conversion to SI"
2082        );
2083    }
2084
2085    /// The longer ground-station log whose `Alt AGL (ft)` doesn't follow its heights keeps them as
2086    /// written.
2087    #[test]
2088    fn heights_that_disagree_with_alt_agl_are_kept() {
2089        let row = |agl: f64| {
2090            format!(
2091                "T,2026-03-08,09:15:10,20,-100,3000,20.001,-100,4000,3,4,0,45,0x01,24,6,12,2,-50,\
2092                 -55,364.8,{agl},0,12.5,100%,4.0,4.1,1,1,0,1,1,,0,0,0,0,0,-60,-5"
2093            )
2094        };
2095        let agrees = read(&format!("{LONGER}\n{}\n", row(1005.0))).unwrap();
2096        assert_eq!(
2097            channel(&agrees, "GS Alt asl").quantity,
2098            Quantity::GnssAltitude
2099        );
2100        let disagrees = read(&format!("{LONGER}\n{}\n", row(304.8))).unwrap();
2101        assert_eq!(
2102            channel(&disagrees, "GS Alt asl").quantity,
2103            Quantity::Unrecognized
2104        );
2105        assert_eq!(
2106            channel(&disagrees, "GS_ASL_offset").quantity,
2107            Quantity::Unrecognized
2108        );
2109        // `VERTV` is in the heights' unit a second, so it is kept with them.
2110        assert_eq!(channel(&agrees, "VERTV").quantity, Quantity::Speed);
2111        assert_eq!(
2112            channel(&disagrees, "VERTV").quantity,
2113            Quantity::Unrecognized
2114        );
2115        assert!(disagrees.notes.contains(
2116            &"`VERTV` kept as written, `Alt AGL (ft)` disagrees with the manual's feet: the file \
2117              has too few pairs of moving rows to check `VERTV` over, 0 of the 10 needed"
2118                .to_owned()
2119        ));
2120        assert!(disagrees.notes.iter().any(|note| note.starts_with(
2121            "`GS Alt asl`, `TRACKER Alt asl`, `Found rocket altitude` and `GS_ASL_offset` kept as \
2122             written, `Alt AGL (ft)` disagrees with the manual's feet: "
2123        )));
2124    }
2125
2126    #[test]
2127    fn unixtime_off_by_other_than_whole_hours_is_said() {
2128        let text = format!(
2129            "{OLDER}\nJun 1 2025 18:00:00.000 UTC,1748800800.500,1,40,-105,1,3,0,0,0,0x03,1,1,1,\
2130             1,4\n"
2131        );
2132        let log = read(&text).unwrap();
2133        assert!(
2134            log.notes.iter().any(|note| note
2135                == "`UNIXTIME` kept as written, off `UTCTIME` by other than one whole number of \
2136                    hours. It runs from 0.500 s to 0.500 s ahead of `UTCTIME`. Read as UTC at the \
2137                    first fix's longitude, `UTCTIME` gives 11.0 h of local mean solar time and \
2138                    `UNIXTIME` 11.0 h"),
2139            "{:#?}",
2140            log.notes
2141        );
2142    }
2143
2144    /// A latitude beyond ±90° or a longitude beyond ±180° is a gap, counted per column; the
2145    /// edges themselves are read.
2146    #[test]
2147    fn positions_out_of_range_are_gaps() {
2148        let row = |lat: &str, lon: &str| {
2149            format!(
2150                "Jun 1 2025 18:00:00.000 UTC,1748800800,1,{lat},{lon},1,3,0,0,0,0x03,1,1,1,1,4\n"
2151            )
2152        };
2153        let text = format!(
2154            "{OLDER}\n{}{}{}{}",
2155            row("90", "-180"),
2156            row("90.5", "-105"),
2157            row("-91", "180.001"),
2158            row("40", "-181")
2159        );
2160        let log = read(&text).unwrap();
2161        let (lat, lon) = (channel(&log, "LAT"), channel(&log, "LON"));
2162        assert_eq!(lat.values[0], 90.0);
2163        assert_eq!(lon.values[0], -180.0);
2164        assert!(lat.values[1].is_nan() && lon.values[1] == -105.0);
2165        assert!(lat.values[2].is_nan() && lon.values[2].is_nan());
2166        assert!(lat.values[3] == 40.0 && lon.values[3].is_nan());
2167        for expected in [
2168            "the column \"LAT\" holds 2 latitudes beyond ±90°: they are gaps",
2169            "the column \"LON\" holds 2 longitudes beyond ±180°: they are gaps",
2170        ] {
2171            assert!(
2172                log.notes.iter().any(|note| note == expected),
2173                "{expected}\n{:#?}",
2174                log.notes
2175            );
2176        }
2177    }
2178
2179    /// A long line that doesn't open as a header is turned away by its first names.
2180    #[test]
2181    fn a_long_line_of_other_names_is_not_a_header() {
2182        let commas = ",".repeat(1 << 20);
2183        assert!(!recognizes(&commas));
2184        assert!(!recognizes(&format!("UTCTIME{commas}")));
2185        assert!(!recognizes(&format!("TRACKER,DATE{commas}")));
2186        assert!(recognizes(&format!("UTCTIME,UNIXTIME{commas}LAT,LON")));
2187    }
2188
2189    #[test]
2190    fn repeated_times_alone_are_noted() {
2191        let row = "Jun 1 2025 18:00:00.000 UTC,1748800800,1,40,-105,1,3,0,0,0,0x03,1,1,1,1,4";
2192        let log = read(&format!("{OLDER}\n{row}\n{row}\n")).unwrap();
2193        assert!(
2194            log.notes.contains(
2195                &"1 rows repeat a time already written: every row is kept, in the file's order"
2196                    .to_owned()
2197            )
2198        );
2199        assert_eq!(channel(&log, "ALT").time_s, [0.0, 0.0]);
2200    }
2201
2202    /// Past [`MAX_TRACKERS`] trackers, a further tracker's rows are left out and counted.
2203    #[test]
2204    fn trackers_past_the_cap_are_left_out() {
2205        let mut text = format!("{GROUND}\n");
2206        for tracker in 0..70 {
2207            text.push_str(&format!(
2208                "T{tracker},2026-01-01,10:00:{:02},1,1,1,3,0,0,0,0x03,1,1,1,1,1,0\n",
2209                tracker % 60
2210            ));
2211        }
2212        text.push_str("T69,2026-01-01,10:01:00,1,1,1,3,0,0,0,0x03,1,1,1,1,1,0\n");
2213        let log = read(&text).unwrap();
2214        assert_eq!(log.channels.len(), MAX_TRACKERS * 15);
2215        assert_eq!(log.channels[15].column, "TIME [T1]");
2216        assert!(
2217            log.notes.contains(
2218                &"7 rows of 6 more trackers were left out, past the first 64 trackers or 4096 \
2219                  channels. This keeps a file of many tracker names from making the reader hold a \
2220                  set of channels for each"
2221                    .to_owned()
2222            ),
2223            "{:#?}",
2224            log.notes
2225        );
2226    }
2227
2228    /// Each refusal names its line and what is wrong.
2229    #[test]
2230    fn malformed_files_are_refused_where_they_go_wrong() {
2231        let row = "Jun 1 2025 18:00:00.000 UTC,1748800800,1,40,-105,1,3,0,0,0,0x03,1,1,1,1,4";
2232        let cases = [
2233            (String::new(), "the file is empty"),
2234            ("\n\r\n".to_owned(), "the file is empty"),
2235            (
2236                "Time,Altitude\n0,0\n".to_owned(),
2237                "isn't a Featherweight GPS header",
2238            ),
2239            (format!("{OLDER}\n"), "no data rows"),
2240            (
2241                "UTCTIME,UNIXTIME,LAT,LON,,x\n".to_owned(),
2242                "line 1: the header's column 5 has no name",
2243            ),
2244            (
2245                format!("{OLDER}\n{row},9\n"),
2246                "line 2: the row has 17 cells, more than the header's 16",
2247            ),
2248            (
2249                format!("{OLDER}\n{}\n", row.replace("Jun 1", "Jun 31")),
2250                "line 2: the time \"Jun 31 2025 18:00:00.000 UTC\" in cell 1 isn't one",
2251            ),
2252            (
2253                format!("{GROUND}\nT,2026-02-30,10:00:00,1,1,1\n"),
2254                "line 2: the date \"2026-02-30\" in cell 2 isn't one",
2255            ),
2256            (
2257                format!("{GROUND}\nT,2026-02-03,10:00\n"),
2258                "line 2: the time \"10:00\" in cell 3 isn't one",
2259            ),
2260            (
2261                format!("{GROUND}\nT,2026-02-03\n"),
2262                "line 2: the row ends after 2 cells, before its \"TIME\"",
2263            ),
2264        ];
2265        for (text, expected) in cases {
2266            let error = read(&text).unwrap_err().to_string();
2267            assert!(error.contains(expected), "{text:?}: {error}");
2268        }
2269        let LogError::NotThisFormat { format, .. } = read("x").unwrap_err() else {
2270            panic!("refused for another reason");
2271        };
2272        assert_eq!(format, FORMAT);
2273    }
2274
2275    /// A header naming far more columns than its rows fill is refused before the reader allocates
2276    /// a gap for every cell left out; short rows within the bound are gaps, counted.
2277    #[test]
2278    fn short_rows_are_gaps_and_a_wide_header_is_refused() {
2279        let wide: String = (0..20_000).map(|i| format!(",c{i}")).collect();
2280        let rows: String = (0..100)
2281            .map(|i| format!("Jun 1 2025 18:00:{:02}.000 UTC\n", i % 60))
2282            .collect();
2283        let error = read(&format!("UTCTIME,UNIXTIME,LAT,LON{wide}\n{rows}"))
2284            .unwrap_err()
2285            .to_string();
2286        assert!(
2287            error.contains(
2288                "line 5: the header names 20004 columns, and the 4 rows down to this one hold \
2289                 only 4 cells"
2290            ),
2291            "{error}"
2292        );
2293        let log = read(&format!(
2294            "{OLDER}\nJun 1 2025 18:00:00.000 UTC,1748800800,1\n"
2295        ))
2296        .unwrap();
2297        assert!(channel(&log, "LAT").values[0].is_nan());
2298        assert!(log.notes.contains(
2299            &"1 rows, the first on line 2, have fewer cells than the header's 16: the cells they \
2300              leave out are gaps"
2301                .to_owned()
2302        ));
2303    }
2304
2305    /// A column the reader doesn't know is kept as written, with a note; notes about columns stay
2306    /// few.
2307    #[test]
2308    fn unknown_columns_are_kept_and_their_notes_stay_few() {
2309        let unknown: String = (0..30).map(|i| format!(",u{i}")).collect();
2310        let row = format!(
2311            "Jun 1 2025 18:00:00.000 UTC,1748800800,1,40,-105{}",
2312            ",7".repeat(30)
2313        );
2314        let log = read(&format!("UTCTIME,UNIXTIME,ALT,LAT,LON{unknown}\n{row}\n")).unwrap();
2315        assert_eq!(channel(&log, "u29").quantity, Quantity::Unrecognized);
2316        assert_eq!(channel(&log, "u29").values, [7.0]);
2317        assert_eq!(
2318            log.notes
2319                .iter()
2320                .filter(|note| note.contains("isn't one this reader knows"))
2321                .count(),
2322            20
2323        );
2324        assert!(log.notes.last().unwrap().starts_with("and 10 more notes"));
2325    }
2326
2327    proptest::proptest! {
2328        /// Any text is read or refused, never a panic; what is read has a time for each value on
2329        /// every channel, and an empty primary track.
2330        #[test]
2331        fn any_text_is_read_or_refused(
2332            rows in proptest::collection::vec(
2333                (proptest::bool::ANY, "[-0-9.,: xaTRUEFLSNC%Jn]{0,60}"),
2334                0..10,
2335            ),
2336            layout in 0..3usize,
2337        ) {
2338            let header = [OLDER, GROUND, LONGER][layout];
2339            // Most rows open with a clock, so that the rest of the row is read too.
2340            let clock = if layout == 0 {
2341                "Jun 1 2025 18:00:00.000 UTC,"
2342            } else {
2343                "T,2026-01-01,10:00:00,"
2344            };
2345            let rows: Vec<String> = rows
2346                .into_iter()
2347                .map(|(timed, rest)| if timed { format!("{clock}{rest}") } else { rest })
2348                .collect();
2349            let text = format!("{header}\n{}", rows.join("\n"));
2350            if let Ok(log) = read(&text) {
2351                proptest::prop_assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
2352                for channel in &log.channels {
2353                    proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
2354                    proptest::prop_assert!(channel.time_s.iter().all(|t| t.is_finite()));
2355                }
2356            }
2357        }
2358    }
2359}