Skip to main content

hpr_flightdata/
rrc3.rs

1//! Missile Works' RRC3 flight logs, as its mDACS software exports a flight to a CSV file.
2//!
3//! The RRC3 is a barometric dual-deploy altimeter (*RRC3+ / RRC3 User Manual* v1.71, p. 2): it
4//! records its pressure at 20 Hz, and its temperature and battery voltage at 1 Hz (p. 23).
5//! mDACS works the altitude and the "displacement velocity" out of the pressure (*mDACS User
6//! Manual* Rev 1.71, May 2024, p. 2) and exports "a standard Excel .CSV format", the columns shown
7//! on its chart; "Time, Altitude and Pressure are always exported" (p. 10). One header line names
8//! the columns; each row below is one sample:
9//!
10//! ```text
11//! Time,Altitude,Pressure,Velocity,Temperature,Events,Voltages
12//! 0.00,0,1013.20,0,71.60, -,9.20
13//! 0.05,2.71,1013.10,1.30,71.60, -,9.20
14//! …
15//! 52.30,0,1013.20,0, -
16//! ```
17//!
18//! **Recognition.** A header whose names, compared without regard to case and with any bracketed
19//! unit taken off, start `Time`, `Altitude`, `Pressure`, `Velocity`, and go on with any of
20//! `Temperature`, `Events` and `Voltages`, each at most once. A PerfectFlite export, `Time,
21//! Altitude, Velocity, …`, has no pressure and isn't one. The cells are separated by commas, or by
22//! semicolons or tabs, in which case a number may be written with a decimal comma: Debrief's notes
23//! describe a European-locale export, semicolon-separated with decimal commas
24//! (`lib/parsers/missileworksRrc3.ts`, MIT, the project owner's own; see
25//! `THIRD-PARTY-NOTICES.md`). As of 2026-10-12, every one of the 50 RRC3 files among the
26//! project's sample logs is comma-separated. One more, filed until 2026-10-15 as generic CSV, is
27//! such an export, and ends every line, the header's too, with a semicolon: under a header that
28//! does, a row's last cell, empty, after the semicolon it ends with, is dropped. Its rows were
29//! sorted by their time's text, `10,05` before `2`, so it is refused where the time goes back.
30//!
31//! **Units.** Most exports name none; some name each in brackets, as `Time [s],Altitude
32//! [ft],Pressure [mbar],Velocity [ft/s],Temperature [F],Events,Voltages [V]`. A bracketed unit is
33//! taken as written, and one the reader doesn't know is refused ([`LogError::Unit`]). A unit the
34//! header doesn't name is decided as the table says, and a note on the record states how and on
35//! what evidence:
36//!
37//! | Column | Quantity | Read from | When the header names no unit |
38//! |---|---|---|---|
39//! | `Time` | the clock, s | `[s]` | seconds, from the step: the median step between rows within 5% of 0.05 s, the RRC3's 20 Hz pressure rate (RRC3 manual p. 23); otherwise assumed, as mDACS's chart is timed in seconds (mDACS manual p. 8) |
40//! | `Altitude` | [`Quantity::AltitudeAboveGround`] | `[ft]`, `[m]` | feet or meters, from the pressure (below); feet assumed if the pressure can't tell |
41//! | `Pressure` | [`Quantity::Pressure`] | `[mbar]`, `[hPa]`, × 100 Pa | hectopascals if the first row's value, on the pad, lies within 500 to 1,100 hPa (below) and the highest within the 10 to 1,200 mbar the RRC3 measures (RRC3 manual p. 9); otherwise kept as written |
42//! | `Velocity` | [`Quantity::Speed`], up positive | `[ft/s]`, `[mph]`, `[m/s]`, `[km/h]` (or the RRC3's `fps`, `mps`, `kph`) | measured against the altitude (below); otherwise kept as written |
43//! | `Temperature` | [`Quantity::Temperature`] | `[F]`, `[C]` | kept as written, [`Quantity::Unrecognized`], with a note: the altitude's unit doesn't decide it (below) |
44//! | `Voltages` | [`Quantity::Voltage`] | `[V]` | assumed volts: the RRC3's battery voltage (mDACS manual p. 2), from a battery of at most 10 V (RRC3 manual p. 6) |
45//! | `Events` | [`FlightLog::events`] | | |
46//!
47//! mDACS sets the altitude's, the velocity's and the temperature's units by preference (mDACS
48//! manual p. 5), and the velocity's apart from the altitude's: as of 2026-10-12, 8 of the 50 RRC3
49//! files among the project's sample logs write their velocity in miles per hour beside an
50//! altitude in feet. The RRC3's own settings name four sets: feet, °F and ft/s; meters, °C and
51//! km/h; feet, °F and mph; meters, °C and m/s, the first the default (RRC3 manual p. 12). mDACS's
52//! export doesn't keep to them, so a temperature with no unit in brackets is kept as written
53//! (#852). Two public exports, both in feet, show it: one's temperature runs 47.2 to 43.2, which
54//! fits °C beside the three other sensors on its flight (41 °C to 50 °C) and as °F would be 8 °C,
55//! 26 K below the airport's air that afternoon; the other's runs 69.8 to 70.5, which fits °F
56//! beside its airport's 60.8 °F and as °C would be 54 K above it. Their values alone don't settle
57//! the unit; other measurements did: the flight's other sensors, or the airport's air.
58//!
59//! *The pressure on the pad.* The RRC3 measures 10 to 1,200 mbar, but kilopascals (about 100 at
60//! sea level) and inches of mercury (about 30) lie within that too, so the first row's pressure,
61//! taken on the pad, must also be a launch site's: at least 500 hPa, the U.S. Standard
62//! Atmosphere's pressure about 5,570 m up, above any launch site, and at most 1,100 hPa, above
63//! both the highest sea-level pressure on record below 750 m of elevation, 1,083.8 hPa (WMO,
64//! *Records of Weather and Climate Extremes*, as of 31 July 2025), and the standard atmosphere's
65//! 1,066 hPa at the lowest dry land, the Dead Sea's shore about 430 m below sea level. A pressure
66//! outside either range is kept as written, with a note, and the altitude's unit is then assumed.
67//!
68//! *The altitude from the pressure.* mDACS converts pressure to altitude by NOAA's pressure
69//! altitude, the standard atmosphere's (RRC3 manual p. 23), or by a geopotential method that
70//! brings in the day's temperature and humidity (mDACS manual p. 5). Between the first row, on
71//! the pad (the RRC3 keeps a second of samples from before launch, p. 23), and the row of lowest
72//! pressure, the reader works out the climb the pressure implies in the U.S. Standard Atmosphere,
73//! 1976 ([`hpr_atmos::ussa76`]) and compares the altitude column's climb between the same rows,
74//! read in feet and in meters. The unit within 25% of the pressure's climb is taken: a day's air
75//! from −40 °C to +50 °C is within about 20% of the standard's temperature, which is how far the
76//! geopotential method can move the altitude, and feet and meters are 3.28 times apart, so at
77//! most one unit can be within 25%. As of 2026-10-12, over the 50 RRC3 files among the project's
78//! sample logs, feet came within 0.05% every time and meters at least 227% off. Neither within 25%
79//! is refused ([`LogError::Unit`]), as is a stated unit the
80//! pressure contradicts by more. Below a climb of 10 m the pressure can't settle it: a step of the
81//! pressure, 0.1 hPa in every sample log, is 0.83 m of altitude at sea level, more than 8% of
82//! such a climb. Then, or with a pressure of unknown unit, feet are assumed, the RRC3's default.
83//!
84//! *The velocity against the altitude.* The velocity is mDACS's rate of the altitude, in its own
85//! unit: ft/s, mph, m/s and km/h are 3.2808, 2.2369, 1 and 3.6 times a speed in m/s. The RRC3
86//! works it out through a 21-element filter at 20 Hz (RRC3 manual p. 23), so it runs behind the
87//! altitude, and mDACS may smooth both for its viewer (mDACS manual p. 5). The reader integrates
88//! the velocity by trapezoids from zero at the first row, on the pad, and measures the running
89//! integral against the altitude above the first row, in meters, two ways:
90//!
91//! - *By the fit:* the least-squares slope, through zero, of the integral against the altitude as
92//!   it was a delay earlier, the delay from −2 to 4 s, in steps of 0.05 s, that fits best. A
93//!   velocity that is the altitude's rate a delay late integrates to the altitude that delay late,
94//!   times the unit, so the delay is fitted out rather than read as a smaller slope. Smoothing
95//!   still rounds off the integral's apogee, which moves the slope.
96//! - *By the areas:* the area under the integral over the area under the delayed altitude, both
97//!   over the record. A filter that passes a steady speed unchanged (one of unit gain) keeps the
98//!   area of what it filters, however it delays or spreads it, so this measure holds exactly when
99//!   the record runs from rest on the pad to rest on the ground, as the RRC3's does: it stops
100//!   after the velocity has stayed above −3 ft/s for 2 s (RRC3 manual p. 10). A record that ends
101//!   with the altitude still moving at a rate `v` leaves out about `σ²·v / 2` of the area, `σ²`
102//!   the filter's variance. The reader takes `σ` as the delay (a first-order filter's spread
103//!   equals its delay, a moving average's is 0.58 times it, a pure delay's is zero), `v` as the
104//!   faster of the altitude's rates over the last second and over the second a delay earlier, and
105//!   requires the share left out to be at most 0.1%; and the record must end at most halfway up
106//!   the climb, as near apogee this estimate fails.
107//!
108//! The unit is taken only when both measures land within 3% of the same one. ft/s and km/h, the
109//! nearest two, are 9.7% apart, so the runner-up is then at least 6.4% off. As of 2026-10-12, over
110//! the 50 RRC3 files among the project's sample logs, 48 records end low and still enough, and on
111//! each both measures came within 0.26% of the unit the file is in (ft/s or mph; 4 of them state
112//! it in brackets) and put the runner-up at least 8.8% off; the other 2 records stop before
113//! coming halfway down, so their velocity is kept as written. The 0.1% allowed is more than ten
114//! times the largest share any of those records' ends could leave out. On invented flights 20 m
115//! to 1 km up, coming down at 10 to 40 m/s, their velocity late by up to 3 s or smoothed by a
116//! first-order filter or a trailing moving average over up to 3 s, in each unit, and cut off at
117//! each tenth of the way through from 30%, none is decided in the wrong unit, and a whole record
118//! up to 1 s late is decided from 50 m up (the module's tests; `tests/rrc3_csv.rs` adds km/h and
119//! ft/s flights 1 and 2 s late, 100 to 300 m up). These filters only look back. A smoothing that
120//! also looks ahead, centered on each sample, starts the velocity above rest at the record's
121//! first row, so the integral misses the start of the climb; on a record cut short it also runs
122//! past the last row. Over a window of 3 to 5 s, about 2 in 100 cases the two measures decide on
123//! the module's sweep of invented flights takes the wrong unit, such as km/h for ft/s. So the
124//! velocity is measured only where its first row is near rest, at most 1% of the column's own
125//! peak, and its integral ends within 1% of the climb from the altitude. That sweep then decides
126//! about a quarter as many, and none wrongly. It doesn't catch every such smoothing: a window that
127//! shrinks to one sample at the first row, or a first row set to zero, still decides a few wrongly
128//! ([#1100](https://github.com/nrdptel/fusionspace-eridanus/issues/1100)). None of the sample
129//! files is known to smooth this way: their 51 records' first rows are at rest, their integrals end
130//! within 0.53%, and these rules change none of the 49 units they decide. Otherwise the column is
131//! kept as written,
132//! [`Quantity::Unrecognized`], with a note: also
133//! when the altitude climbs under 50 m, where half a step of the pressure, 0.42 m at sea level,
134//! is 0.8% of the climb and a larger share of the area of a flight that spends its time low; and
135//! when the altitude's own unit was only assumed. A stated velocity unit that both measures
136//! place within 3% of another unit is refused.
137//!
138//! **Events.** The `Events` column marks a deployment: ` -` for none, ` Drogue`, ` Main` or ` Aux`
139//! at the sample it fired, the three events mDACS charts (mDACS manual p. 8). It holds words, not
140//! numbers, so it isn't a channel: each word is an [`Event`] at its row's time, and with the
141//! events the record keeps every column. A word other than those three is kept too, with a note;
142//! a cell that isn't a word is refused.
143//!
144//! **Short rows.** The temperature and battery voltage are written on every row (their 1 Hz
145//! snapshot repeated), but as of 2026-10-12, in 45 of the 50 RRC3 files among the project's sample
146//! logs, the last 11 to 30 rows leave those cells out and close up the rest: a 7-column file's
147//! tail rows hold 5 cells, `Time`, `Altitude`, `Pressure`, `Velocity`, `Events`, and a file with
148//! one of the two columns, one cell fewer than its header. Two more pad those rows back to the
149//! header's width with empty cells after `Events` instead; the 3 files with neither column have
150//! no short rows. The reader takes a row as wide as the header, cell for cell; a row as wide as
151//! the header without `Temperature` and `Voltages`, or as wide as the header but empty from that
152//! width on, as the other columns in order, its temperature and voltage gaps (`NaN`), counted in
153//! a note. So `-`, an event cell, can't land in the temperature. Some exports end with rows that
154//! have no time and only an altitude cell; such rows are skipped, counted in a note. Any other
155//! row of another width, a cell that isn't a number, or a time that doesn't increase, is refused,
156//! naming its line. Lines may end in CR, LF or both, and a byte-order mark is dropped.
157//!
158//! **The primary track.** The time, the altitude, which is above the pad (the RRC3 tracks its
159//! "floor" altitude on the pad, RRC3 manual p. 23), and the velocity as the vertical speed when
160//! its unit was decided: it is the barometer's, as the RRC3 has no other sensor of motion. The
161//! temperature and battery voltage share the clock, with gaps where a row leaves them out.
162//!
163//! **Where this comes from.** The columns, the units and the rules above are the manuals' and the
164//! files'. Debrief's reader decides feet or meters from the pressure too, and is followed in
165//! that; where this reader departs from it: it reads the velocity's unit from the data where
166//! Debrief ties it to the altitude's (which reads a file in mph 32% low), it reads the short rows
167//! by the rule above, and it refuses what Debrief passes over.
168
169use hpr_atmos::ussa76::Ussa76;
170
171use crate::error::LogError;
172use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
173use crate::perfectflite::FOOT_M;
174use crate::table::{self, Notes, finite, numbered_lines, short};
175
176/// The format's name in errors.
177const FORMAT: &str = "RRC3 CSV";
178
179/// Pascals in a hectopascal, a millibar.
180const HPA_PA: f64 = 100.0;
181
182/// The pressure the RRC3 measures, mbar: below 10 or above 1,200 is a sensor fault (RRC3 manual
183/// p. 9).
184const PRESSURE_RANGE_HPA: (f64, f64) = (10.0, 1_200.0);
185
186/// The pressure, hPa, the first row (on the pad) may hold for the pressure to be read in
187/// hectopascals: 500 hPa is the standard atmosphere's at about 5,570 m, above any launch site, and
188/// 1,100 hPa is above the highest sea-level pressure on record and the air at the lowest dry land
189/// (module docs).
190const PAD_RANGE_HPA: (f64, f64) = (500.0, 1_100.0);
191
192/// The RRC3's pressure rate, 20 Hz, as a step between rows, s (RRC3 manual p. 23).
193const PRESSURE_STEP_S: f64 = 0.05;
194
195/// How far, as a fraction, the median step between rows may be from [`PRESSURE_STEP_S`] for the
196/// time to be read in seconds from it.
197const STEP_MARGIN: f64 = 0.05;
198
199/// The least climb, m, from which the pressure tells feet from meters (module docs).
200const SETTLING_CLIMB_M: f64 = 10.0;
201
202/// How far, as a fraction, the altitude's climb may be from the pressure's in its unit.
203const ALTITUDE_MARGIN: f64 = 0.25;
204
205/// The least climb, m, over which the velocity's unit is measured against the altitude.
206const VELOCITY_CLIMB_M: f64 = 50.0;
207
208/// How far, as a fraction, each of the velocity's two measures may be from its unit's.
209const VELOCITY_MARGIN: f64 = 0.03;
210
211/// The earliest and latest delay, s, of the velocity behind the altitude that the fit tries, and
212/// its step: the RRC3's own filter runs about half a second behind (module docs).
213const DELAY_SEARCH_S: (f64, f64, f64) = (-2.0, 4.0, 0.05);
214
215/// The most the velocity's first row may be, as a fraction of the column's own peak, for it to be
216/// measured: above rest, its integral has missed the start of the climb (module docs).
217const START_SHARE: f64 = 0.01;
218
219/// The most the velocity's running integral may end from the altitude it is fitted to, as a
220/// fraction of the climb, for it to be measured: a velocity that is the altitude's rate closes on
221/// it, and one smoothed across the record's ends doesn't (module docs). The sample files' largest
222/// is 0.53%.
223const CLOSURE_SHARE: f64 = 0.01;
224
225/// The highest the record may end, as a fraction of the climb above the first row, for the
226/// velocity to be measured: it must have come down at least halfway (module docs).
227const END_HEIGHT: f64 = 0.5;
228
229/// The most, as a fraction, that the record ending with the altitude still moving may move the
230/// velocity's measure by the areas (module docs).
231const END_ERROR: f64 = 0.001;
232
233/// The velocity units mDACS may write: the unit's words, its bracketed spellings in lower case,
234/// and meters per second in one of it. A mile is 1,609.344 m and a foot 0.3048 m, exactly.
235const SPEEDS: [(&str, &[&str], f64); 4] = [
236    ("feet per second", &["ft/s", "fps"], FOOT_M),
237    ("miles per hour", &["mph"], 0.447_04),
238    ("meters per second", &["m/s", "mps"], 1.0),
239    ("kilometers per hour", &["km/h", "kph"], 1.0 / 3.6),
240];
241
242/// What a header column holds.
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244enum Kind {
245    Time,
246    Altitude,
247    Pressure,
248    Velocity,
249    Temperature,
250    Events,
251    Voltages,
252}
253
254impl Kind {
255    fn from_name(name: &str) -> Option<Kind> {
256        [
257            ("time", Kind::Time),
258            ("altitude", Kind::Altitude),
259            ("pressure", Kind::Pressure),
260            ("velocity", Kind::Velocity),
261            ("temperature", Kind::Temperature),
262            ("events", Kind::Events),
263            ("voltages", Kind::Voltages),
264        ]
265        .into_iter()
266        .find(|(known, _)| name.eq_ignore_ascii_case(known))
267        .map(|(_, kind)| kind)
268    }
269
270    /// Whether the RRC3 logs it at 1 Hz, so that the last rows may leave it out.
271    fn is_slow(self) -> bool {
272        matches!(self, Kind::Temperature | Kind::Voltages)
273    }
274}
275
276/// A header column: what it holds, its name as written, and its bracketed unit if any.
277struct Column {
278    kind: Kind,
279    written: String,
280    unit: Option<String>,
281}
282
283/// A header cell's name and its bracketed unit: `Altitude [ft]` is `Altitude` and `ft`.
284fn split_name(cell: &str) -> (&str, Option<&str>) {
285    let cell = cell.trim();
286    match (cell.find('['), cell.strip_suffix(']')) {
287        (Some(open), Some(inner)) if open < inner.len() => {
288            (cell[..open].trim(), Some(inner[open + 1..].trim()))
289        }
290        _ => (cell, None),
291    }
292}
293
294/// The separator a header line uses: a semicolon or a tab if it has one, else a comma.
295fn separator(header: &str) -> char {
296    if header.contains(';') {
297        ';'
298    } else if header.contains('\t') {
299        '\t'
300    } else {
301        ','
302    }
303}
304
305/// The header's separator, whether it ends with one, and its columns, if it is an RRC3 export's
306/// (module docs, *Recognition*).
307fn header_columns(header: &str) -> Option<(char, bool, Vec<Column>)> {
308    let separator = separator(header);
309    // A European locale's export ends each line with a semicolon (module docs, *Recognition*).
310    let trimmed = header.trim_end();
311    let (names, trailing) = match trimmed.strip_suffix(';') {
312        Some(names) if separator == ';' => (names, true),
313        _ => (trimmed, false),
314    };
315    let mut columns: Vec<Column> = Vec::new();
316    for cell in names.split(separator) {
317        let (name, unit) = split_name(cell);
318        let kind = Kind::from_name(name)?;
319        if columns.iter().any(|column| column.kind == kind) {
320            return None;
321        }
322        let first = [Kind::Time, Kind::Altitude, Kind::Pressure, Kind::Velocity];
323        match first.get(columns.len()) {
324            Some(expected) if *expected != kind => return None,
325            _ => {}
326        }
327        columns.push(Column {
328            kind,
329            written: cell.trim().to_owned(),
330            unit: unit.map(str::to_owned),
331        });
332    }
333    (columns.len() >= 4).then_some((separator, trailing, columns))
334}
335
336/// Whether the text is in this reader's layout, judged from its first line that isn't blank,
337/// never the file's name.
338pub(crate) fn recognizes(text: &str) -> bool {
339    numbered_lines(text)
340        .map(|(_, line)| line)
341        .find(|line| !line.trim().is_empty())
342        .is_some_and(|header| header_columns(header).is_some())
343}
344
345/// A length unit.
346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
347enum Length {
348    Feet,
349    Meters,
350}
351
352impl Length {
353    fn meters(self) -> f64 {
354        match self {
355            Length::Feet => FOOT_M,
356            Length::Meters => 1.0,
357        }
358    }
359
360    fn words(self) -> &'static str {
361        match self {
362            Length::Feet => "feet",
363            Length::Meters => "meters",
364        }
365    }
366}
367
368/// A temperature unit.
369#[derive(Debug, Clone, Copy, PartialEq, Eq)]
370enum Temperature {
371    Fahrenheit,
372    Celsius,
373}
374
375impl Temperature {
376    fn kelvin(self, value: f64) -> f64 {
377        match self {
378            Temperature::Fahrenheit => (value - 32.0) * 5.0 / 9.0 + 273.15,
379            Temperature::Celsius => value + 273.15,
380        }
381    }
382}
383
384/// The units the header states in brackets.
385#[derive(Default)]
386struct HeaderUnits {
387    altitude: Option<Length>,
388    pressure_hpa: bool,
389    /// An index into [`SPEEDS`].
390    velocity: Option<usize>,
391    temperature: Option<Temperature>,
392}
393
394/// The bracketed units, each checked against what its column can be in.
395fn header_units(columns: &[Column], line: usize) -> Result<HeaderUnits, LogError> {
396    let mut units = HeaderUnits::default();
397    for column in columns {
398        let Some(unit) = column.unit.as_deref() else {
399            continue;
400        };
401        let lower = unit.to_ascii_lowercase();
402        let known = match column.kind {
403            Kind::Time => lower == "s",
404            Kind::Altitude => {
405                units.altitude = match lower.as_str() {
406                    "ft" => Some(Length::Feet),
407                    "m" => Some(Length::Meters),
408                    _ => None,
409                };
410                units.altitude.is_some()
411            }
412            Kind::Pressure => {
413                units.pressure_hpa = lower == "mbar" || lower == "hpa";
414                units.pressure_hpa
415            }
416            Kind::Velocity => {
417                units.velocity = SPEEDS
418                    .iter()
419                    .position(|(_, spellings, _)| spellings.contains(&lower.as_str()));
420                units.velocity.is_some()
421            }
422            Kind::Temperature => {
423                units.temperature = match lower.trim_start_matches('°') {
424                    "f" => Some(Temperature::Fahrenheit),
425                    "c" => Some(Temperature::Celsius),
426                    _ => None,
427                };
428                units.temperature.is_some()
429            }
430            Kind::Voltages => lower == "v",
431            Kind::Events => false,
432        };
433        if !known {
434            return Err(LogError::Unit {
435                format: FORMAT,
436                line,
437                message: format!(
438                    "the column {:?} states a unit this reader doesn't know for it",
439                    short(&column.written)
440                ),
441            });
442        }
443    }
444    Ok(units)
445}
446
447/// The rows read: each column's values as written (`NaN` where a short row leaves it out), and
448/// what the reader noticed.
449struct Rows {
450    lines: Vec<usize>,
451    time_s: Vec<f64>,
452    /// Per header column; empty for the time and events columns.
453    values: Vec<Vec<f64>>,
454    events: Vec<Event>,
455    short: usize,
456    padded: usize,
457    first_short_line: Option<usize>,
458    skipped: usize,
459    first_skipped_line: Option<usize>,
460}
461
462/// Reads an RRC3's mDACS CSV export from its text.
463///
464/// # Errors
465///
466/// [`LogError::NotThisFormat`] if the first line that isn't blank isn't an mDACS export's header;
467/// [`LogError::Unit`] for a bracketed unit the reader doesn't know, or a unit the pressure or the
468/// altitude contradicts (module docs); [`LogError::Syntax`] for a row of the wrong width, a cell
469/// that isn't a number or an event, a time that doesn't increase, or a value its unit's conversion
470/// makes infinite, naming the line;
471/// [`LogError::NoData`] if no row has a time.
472pub fn read(text: &str) -> Result<FlightLog, LogError> {
473    let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
474    let Some((header_line, header)) = lines.next() else {
475        return Err(LogError::NotThisFormat {
476            format: FORMAT,
477            message: "the file is empty".to_owned(),
478        });
479    };
480    let Some((separator, trailing, columns)) = header_columns(header) else {
481        return Err(LogError::NotThisFormat {
482            format: FORMAT,
483            message: format!(
484                "its first line, {:?}, isn't an mDACS export's header: `Time`, `Altitude`, \
485                 `Pressure`, `Velocity`, then any of `Temperature`, `Events` and `Voltages`",
486                short(header)
487            ),
488        });
489    };
490    let units = header_units(&columns, header_line)?;
491    let mut notes = Notes::default();
492    let rows = read_rows(lines, separator, trailing, &columns, &mut notes)?;
493    if rows.time_s.is_empty() {
494        return Err(LogError::NoData { format: FORMAT });
495    }
496    build(&columns, &units, rows, header_line, notes)
497}
498
499/// Reads the data rows (module docs, *Short rows*). Under a header that ends with a semicolon
500/// (`trailing`), a row that ends with one too, full or short, has its last cell, empty, dropped;
501/// a row that is full or short as it stands, its last real cell empty, is read as written.
502fn read_rows<'a>(
503    lines: impl Iterator<Item = (usize, &'a str)>,
504    separator: char,
505    trailing: bool,
506    columns: &[Column],
507    notes: &mut Notes,
508) -> Result<Rows, LogError> {
509    let decimal_comma = separator != ',';
510    let width = columns.len();
511    // The columns a short row holds, in order.
512    let fast: Vec<usize> = (0..width).filter(|&i| !columns[i].kind.is_slow()).collect();
513    let has_slow = fast.len() < width;
514    let mut rows = Rows {
515        lines: Vec::new(),
516        time_s: Vec::new(),
517        values: columns.iter().map(|_| Vec::new()).collect(),
518        events: Vec::new(),
519        short: 0,
520        padded: 0,
521        first_short_line: None,
522        skipped: 0,
523        first_skipped_line: None,
524    };
525    let mut placed: Vec<Option<&str>> = vec![None; width];
526    for (number, line) in lines {
527        let mut cells: Vec<&str> = line.split(separator).map(str::trim).collect();
528        // A row ends with the semicolon too, full or short: its last cell, empty, is dropped,
529        // where that leaves a full or short row; a row of either width as it stands, its last
530        // real cell empty, is read as written.
531        if trailing
532            && line.trim_end().ends_with(';')
533            && cells.last().is_some_and(|c| c.is_empty())
534            && (cells.len() == width + 1 || cells.len() == fast.len() + 1)
535        {
536            cells.pop();
537        }
538        let empty_from = |from: usize| {
539            cells
540                .get(from..)
541                .is_some_and(|rest| rest.iter().all(|c| c.is_empty()))
542        };
543        if cells.first().is_none_or(|time| time.is_empty()) {
544            // A row with no time and only an altitude, as one sample log ends with.
545            let only_altitude = cells
546                .iter()
547                .enumerate()
548                .all(|(index, cell)| index == 1 || cell.is_empty());
549            if cells.len() <= width && only_altitude {
550                rows.skipped += 1;
551                rows.first_skipped_line.get_or_insert(number);
552                continue;
553            }
554            return Err(syntax(number, "the row has no time".to_owned()));
555        }
556        placed.fill(None);
557        if cells.len() == width && !(has_slow && empty_from(fast.len())) {
558            for (slot, cell) in placed.iter_mut().zip(&cells) {
559                *slot = Some(*cell);
560            }
561        } else if has_slow
562            && (cells.len() == fast.len() || (cells.len() == width && empty_from(fast.len())))
563        {
564            for (&index, cell) in fast.iter().zip(&cells) {
565                if let Some(slot) = placed.get_mut(index) {
566                    *slot = Some(*cell);
567                }
568            }
569            rows.short += 1;
570            if cells.len() == width {
571                rows.padded += 1;
572            }
573            rows.first_short_line.get_or_insert(number);
574        } else {
575            let without = if has_slow {
576                format!(", and a row without its 1 Hz cells has {}", fast.len())
577            } else {
578                String::new()
579            };
580            return Err(syntax(
581                number,
582                format!(
583                    "the row has {} cells: the header names {width}{without}",
584                    cells.len()
585                ),
586            ));
587        }
588        read_row(&mut rows, columns, &placed, number, decimal_comma, notes)?;
589    }
590    Ok(rows)
591}
592
593/// Reads one row's cells, placed under their columns (`None` for a cell the row leaves out).
594fn read_row(
595    rows: &mut Rows,
596    columns: &[Column],
597    placed: &[Option<&str>],
598    number: usize,
599    decimal_comma: bool,
600    notes: &mut Notes,
601) -> Result<(), LogError> {
602    let mut time_s = f64::NAN;
603    let mut event = None;
604    let mut values = Vec::with_capacity(columns.len());
605    for (column, cell) in columns.iter().zip(placed) {
606        let Some(cell) = *cell else {
607            values.push(f64::NAN);
608            continue;
609        };
610        match column.kind {
611            Kind::Events => {
612                if !(cell.is_empty() || cell == "-") {
613                    if !cell.bytes().all(|b| b.is_ascii_alphabetic()) {
614                        return Err(syntax(
615                            number,
616                            format!(
617                                "{:?} under {:?} isn't an event, `-` or a word such as `Drogue`",
618                                short(cell),
619                                short(&column.written)
620                            ),
621                        ));
622                    }
623                    event = Some(cell.to_owned());
624                }
625                values.push(f64::NAN);
626            }
627            _ => {
628                let value = table::number(cell, decimal_comma).ok_or_else(|| {
629                    syntax(
630                        number,
631                        format!(
632                            "{:?} under {:?} isn't a number",
633                            short(cell),
634                            short(&column.written)
635                        ),
636                    )
637                })?;
638                if column.kind == Kind::Time {
639                    time_s = value;
640                }
641                values.push(value);
642            }
643        }
644    }
645    if let Some(&last) = rows.time_s.last()
646        && time_s <= last
647    {
648        return Err(syntax(
649            number,
650            format!("the time {time_s} s doesn't come after the one above it, {last} s"),
651        ));
652    }
653    rows.lines.push(number);
654    rows.time_s.push(time_s);
655    for ((column, store), value) in columns.iter().zip(&mut rows.values).zip(values) {
656        if !matches!(column.kind, Kind::Time | Kind::Events) {
657            store.push(value);
658        }
659    }
660    if let Some(name) = event {
661        if !["Drogue", "Main", "Aux"].contains(&name.as_str()) {
662            notes.push(format!(
663                "line {number}'s event {:?} isn't one of the three mDACS charts, `Drogue`, \
664                 `Main` and `Aux`; it was kept as written",
665                short(&name)
666            ));
667        }
668        rows.events.push(Event { time_s, name });
669    }
670    Ok(())
671}
672
673/// What a column was decided to be: its quantity, and its values in SI.
674struct Decided {
675    quantity: Quantity,
676    values: Vec<f64>,
677}
678
679/// The record from the rows read: each unit decided, every channel, the primary track and the
680/// notes.
681fn build(
682    columns: &[Column],
683    units: &HeaderUnits,
684    rows: Rows,
685    header_line: usize,
686    mut notes: Notes,
687) -> Result<FlightLog, LogError> {
688    let mut log = FlightLog {
689        format: LogFormat::Rrc3Csv,
690        logger: "Missile Works RRC3".to_owned(),
691        serial_number: None,
692        firmware: None,
693        flight_number: None,
694        stated: Stated::default(),
695        time_s: Vec::new(),
696        altitude_m: Vec::new(),
697        vertical_speed_m_s: None,
698        temperature_k: None,
699        battery_v: None,
700        channels: Vec::new(),
701        events: rows.events,
702        notes: Vec::new(),
703    };
704    let column_of = |kind: Kind| columns.iter().position(|column| column.kind == kind);
705    let values_of = |kind: Kind| column_of(kind).and_then(|index| rows.values.get(index));
706    let written_of = |kind: Kind| {
707        column_of(kind)
708            .map(|index| columns[index].written.as_str())
709            .unwrap_or_default()
710    };
711    // Invariant: the header has `Altitude`, `Pressure` and `Velocity` (header_columns).
712    let (Some(altitude), Some(pressure), Some(velocity)) = (
713        values_of(Kind::Altitude),
714        values_of(Kind::Pressure),
715        values_of(Kind::Velocity),
716    ) else {
717        return Err(syntax(header_line, "the header lacks a column".to_owned()));
718    };
719
720    let pressure = decide_pressure(pressure, units, written_of(Kind::Pressure), &mut log.notes);
721    let (length, length_from_evidence) = decide_altitude(
722        altitude,
723        &pressure,
724        units,
725        &rows.lines,
726        written_of(Kind::Altitude),
727        header_line,
728        &mut log.notes,
729    )?;
730    let altitude_m: Vec<f64> = altitude
731        .iter()
732        .map(|value| value * length.meters())
733        .collect();
734    let track = Track {
735        time_s: &rows.time_s,
736        altitude_m: &altitude_m,
737        known: length_from_evidence,
738    };
739    let velocity = decide_velocity(
740        velocity,
741        &track,
742        units,
743        written_of(Kind::Velocity),
744        header_line,
745        &mut log.notes,
746    )?;
747
748    for (column, values) in columns.iter().zip(&rows.values) {
749        let decided = match column.kind {
750            Kind::Time => {
751                if column.unit.is_none() {
752                    log.notes.push(time_note(&column.written, &rows.time_s));
753                }
754                continue;
755            }
756            Kind::Events => continue,
757            Kind::Altitude => Decided {
758                quantity: Quantity::AltitudeAboveGround,
759                values: altitude_m.clone(),
760            },
761            Kind::Pressure => Decided {
762                quantity: pressure.quantity,
763                values: pressure.values.clone(),
764            },
765            Kind::Velocity => Decided {
766                quantity: velocity.quantity,
767                values: velocity.values.clone(),
768            },
769            Kind::Temperature => {
770                let decided = decide_temperature(values, units, &column.written, &mut log.notes);
771                if decided.quantity == Quantity::Temperature {
772                    log.temperature_k = Some(decided.values.clone());
773                }
774                decided
775            }
776            Kind::Voltages => {
777                if column.unit.is_none() {
778                    log.notes.push(format!(
779                        "`{}` read in volts, assumed. The RRC3 records its battery's voltage \
780                         (mDACS manual p. 2) and takes a battery of at most 10 V (RRC3 manual \
781                         p. 6). The column's values, as written, run {}",
782                        short(&column.written),
783                        span(values)
784                    ));
785                }
786                log.battery_v = Some(values.clone());
787                Decided {
788                    quantity: Quantity::Voltage,
789                    values: values.clone(),
790                }
791            }
792        };
793        // A value that its unit's conversion makes infinite, a pressure in hPa or a temperature
794        // in °F, is refused on its row's line (ADR-258 §3).
795        for (line, value) in rows.lines.iter().zip(&decided.values) {
796            finite(*value, FORMAT, *line, &column.written)?;
797        }
798        log.channels.push(Channel {
799            column: column.written.clone(),
800            quantity: decided.quantity,
801            time_s: rows.time_s.clone(),
802            values: decided.values,
803        });
804    }
805
806    if let Some(&first) = altitude_m.first()
807        && first.abs() > SETTLING_CLIMB_M
808    {
809        notes.push(format!(
810            "the altitude starts at {first:.1} m, not at the pad's zero the RRC3 measures from"
811        ));
812    }
813    if rows.short > 0 {
814        log.notes.push(format!(
815            "{} rows, the first on line {}, leave out the 1 Hz {}: they are gaps{}",
816            rows.short,
817            rows.first_short_line.unwrap_or_default(),
818            slow_names(columns),
819            if rows.padded > 0 {
820                format!(
821                    "; {} of them pad the row to the header's width with empty cells after the \
822                     others",
823                    rows.padded
824                )
825            } else {
826                String::new()
827            }
828        ));
829    }
830    if rows.skipped > 0 {
831        log.notes.push(format!(
832            "{} rows with no time and nothing but an altitude cell, the first on line {}, were \
833             skipped",
834            rows.skipped,
835            rows.first_skipped_line.unwrap_or_default()
836        ));
837    }
838    log.time_s = rows.time_s;
839    log.altitude_m = altitude_m;
840    if velocity.quantity == Quantity::Speed {
841        log.vertical_speed_m_s = Some(velocity.values);
842    }
843    log.notes.extend(notes.into_vec());
844    Ok(log)
845}
846
847/// The note on the time read in seconds when the header names no unit: from the step between
848/// rows if it is the RRC3's 20 Hz, else assumed (module docs).
849fn time_note(written: &str, time_s: &[f64]) -> String {
850    let mut steps: Vec<f64> = time_s.windows(2).map(|pair| pair[1] - pair[0]).collect();
851    steps.sort_by(f64::total_cmp);
852    let chart = "mDACS's chart is timed in seconds (mDACS manual p. 8)";
853    match steps.get(steps.len() / 2) {
854        Some(&median) if (median / PRESSURE_STEP_S - 1.0).abs() <= STEP_MARGIN => format!(
855            "`{}` read in seconds, from the step. The median step between rows, {median} as \
856             written, is within {:.0}% of the {PRESSURE_STEP_S} s. That is the step of the 20 Hz \
857             the RRC3 records its pressure at (RRC3 manual p. 23)",
858            short(written),
859            STEP_MARGIN * 100.0
860        ),
861        Some(&median) => format!(
862            "`{}` read in seconds, assumed. The median step between rows, {median} as written, \
863             isn't within {:.0}% of the {PRESSURE_STEP_S} s. That is the step of the 20 Hz the \
864             RRC3 records its pressure at (RRC3 manual p. 23). {chart}",
865            short(written),
866            STEP_MARGIN * 100.0
867        ),
868        None => format!(
869            "`{}` read in seconds, assumed: a single row has no step to measure; {chart}",
870            short(written)
871        ),
872    }
873}
874
875/// The 1 Hz columns the header names, as a note lists them.
876fn slow_names(columns: &[Column]) -> String {
877    let names: Vec<String> = columns
878        .iter()
879        .filter(|column| column.kind.is_slow())
880        .map(|column| format!("`{}`", short(&column.written)))
881        .collect();
882    match names.as_slice() {
883        [one] => format!("{one} cell"),
884        _ => format!("{} cells", names.join(" and ")),
885    }
886}
887
888/// The least and greatest of a column's values that are numbers, as a note writes them.
889fn span(values: &[f64]) -> String {
890    let (low, high) = values
891        .iter()
892        .filter(|value| value.is_finite())
893        .fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), &value| {
894            (low.min(value), high.max(value))
895        });
896    if low.is_finite() {
897        format!("from {low} to {high}")
898    } else {
899        "to no number".to_owned()
900    }
901}
902
903/// The pressure's unit: hectopascals if stated, or if the first row's value is a launch site's
904/// and the highest is within what the RRC3 measures; otherwise kept as written (module docs).
905fn decide_pressure(
906    values: &[f64],
907    units: &HeaderUnits,
908    written: &str,
909    notes: &mut Vec<String>,
910) -> Decided {
911    let in_hpa = Decided {
912        quantity: Quantity::Pressure,
913        values: values.iter().map(|value| value * HPA_PA).collect(),
914    };
915    if units.pressure_hpa {
916        return in_hpa;
917    }
918    let highest = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
919    let pad = values.first().copied().unwrap_or(f64::NAN);
920    let (low, high) = PRESSURE_RANGE_HPA;
921    let (pad_low, pad_high) = PAD_RANGE_HPA;
922    let measured = (low..=high).contains(&highest);
923    let on_a_pad = (pad_low..=pad_high).contains(&pad);
924    let ranges = format!(
925        "the first row's, {pad}, {} the {pad_low} to {pad_high} hPa of any launch site. The \
926         highest, {highest}, {} the {low} to {high} mbar the RRC3 measures (RRC3 manual p. 9)",
927        if on_a_pad {
928            "lies within"
929        } else {
930            "lies outside"
931        },
932        if measured {
933            "lies within"
934        } else {
935            "lies outside"
936        }
937    );
938    if measured && on_a_pad {
939        notes.push(format!(
940            "`{}` read in hectopascals, from the values: {ranges}",
941            short(written)
942        ));
943        in_hpa
944    } else {
945        notes.push(format!(
946            "`{}` kept as written, its unit unknown: {ranges}",
947            short(written)
948        ));
949        Decided {
950            quantity: Quantity::Unrecognized,
951            values: values.to_vec(),
952        }
953    }
954}
955
956/// The climb the pressure implies between the first row and the row of lowest pressure: that
957/// row's index and the climb, m, in the standard atmosphere; `None` if the pressure's unit isn't
958/// known or a pressure isn't positive.
959fn pressure_climb(pressure: &Decided) -> Option<(usize, f64)> {
960    if pressure.quantity != Quantity::Pressure {
961        return None;
962    }
963    let atmosphere = Ussa76::standard();
964    let first = *pressure.values.first()?;
965    let (lowest, lowest_pa) = pressure.values.iter().copied().enumerate().fold(
966        (0, first),
967        |(at, low), (index, value)| {
968            if value < low {
969                (index, value)
970            } else {
971                (at, low)
972            }
973        },
974    );
975    let climb_m = atmosphere.pressure_altitude_m(lowest_pa).ok()?
976        - atmosphere.pressure_altitude_m(first).ok()?;
977    Some((lowest, climb_m))
978}
979
980/// The altitude's unit, and whether it was stated or decided from the pressure rather than
981/// assumed (module docs).
982fn decide_altitude(
983    altitude: &[f64],
984    pressure: &Decided,
985    units: &HeaderUnits,
986    lines: &[usize],
987    written: &str,
988    header_line: usize,
989    notes: &mut Vec<String>,
990) -> Result<(Length, bool), LogError> {
991    let climb = pressure_climb(pressure);
992    let Some((lowest, climb_m)) = climb.filter(|(_, climb_m)| *climb_m >= SETTLING_CLIMB_M) else {
993        if let Some(stated) = units.altitude {
994            return Ok((stated, true));
995        }
996        let why = match climb {
997            _ if pressure.quantity != Quantity::Pressure => {
998                "the pressure's unit is unknown, so it can't tell feet from meters".to_owned()
999            }
1000            Some((_, climb_m)) => format!(
1001                "the pressure climbs {climb_m:.1} m, under the {SETTLING_CLIMB_M} m from which \
1002                 it tells feet from meters"
1003            ),
1004            None => "a pressure isn't positive, so it gives no climb".to_owned(),
1005        };
1006        notes.push(format!(
1007            "`{}` read in feet, assumed: {why}; feet are the RRC3's default unit (RRC3 manual p. \
1008             12)",
1009            short(written)
1010        ));
1011        return Ok((Length::Feet, false));
1012    };
1013    let (Some(&first), Some(&at_lowest)) = (altitude.first(), altitude.get(lowest)) else {
1014        return Ok((Length::Feet, false));
1015    };
1016    let written_climb = at_lowest - first;
1017    let miss = |length: Length| written_climb * length.meters() / climb_m - 1.0;
1018    let (feet, meters) = (miss(Length::Feet), miss(Length::Meters));
1019    let evidence = format!(
1020        "from line {} to line {} the pressure falls from {:.2} hPa to {:.2} hPa. That is a climb \
1021         of {:.1} m in the U.S. Standard Atmosphere (1976). The altitude climbs {:.2} as \
1022         written, {:+.2}% off that climb read in feet and {:+.1}% read in meters",
1023        lines.first().copied().unwrap_or_default(),
1024        lines.get(lowest).copied().unwrap_or_default(),
1025        pressure.values.first().copied().unwrap_or_default() / HPA_PA,
1026        pressure.values.get(lowest).copied().unwrap_or_default() / HPA_PA,
1027        climb_m,
1028        written_climb,
1029        feet * 100.0,
1030        meters * 100.0
1031    );
1032    let fits = |miss: f64| miss.abs() <= ALTITUDE_MARGIN;
1033    if let Some(stated) = units.altitude {
1034        let stated_miss = miss(stated);
1035        if !fits(stated_miss) {
1036            return Err(LogError::Unit {
1037                format: FORMAT,
1038                line: header_line,
1039                message: format!(
1040                    "{:?} states {}, which the pressure contradicts: {evidence}",
1041                    short(written),
1042                    stated.words()
1043                ),
1044            });
1045        }
1046        return Ok((stated, true));
1047    }
1048    let length = if fits(feet) {
1049        Length::Feet
1050    } else if fits(meters) {
1051        Length::Meters
1052    } else {
1053        return Err(LogError::Unit {
1054            format: FORMAT,
1055            line: header_line,
1056            message: format!(
1057                "{:?} is in neither feet nor meters by the pressure, within {:.0}%: {evidence}",
1058                short(written),
1059                ALTITUDE_MARGIN * 100.0
1060            ),
1061        });
1062    };
1063    notes.push(format!(
1064        "`{}` read in {}, from the pressure: {evidence}",
1065        short(written),
1066        length.words()
1067    ));
1068    Ok((length, true))
1069}
1070
1071/// The velocity's unit per m/s of the altitude's rate, measured two ways (module docs).
1072#[derive(Debug, Clone, Copy)]
1073struct Scale {
1074    /// The area under the velocity's running integral over the area under the altitude above
1075    /// the first row, both over the whole record.
1076    by_area: f64,
1077    /// The least-squares slope, through zero, of the running integral against the altitude above
1078    /// the first row taken `delay_s` earlier, the delay that fits best.
1079    by_fit: f64,
1080    /// How far, s, the velocity runs behind the altitude, as the fit finds it.
1081    delay_s: f64,
1082    /// The last row's altitude above the first row's, as a fraction of the climb.
1083    end_height: f64,
1084    /// About the most a filter as spread as the delay can move `by_area`, as a fraction, given
1085    /// the altitude's rate at the record's end (module docs).
1086    end_error: f64,
1087    /// The first row's velocity, as a fraction of the column's own peak; 0 for a column of zeros.
1088    start_share: f64,
1089    /// How far the running integral ends from the altitude `delay_s` earlier, in the fit's unit,
1090    /// as a fraction of the climb.
1091    closure: f64,
1092}
1093
1094/// The velocity's running integral by trapezoids, zero at the first row.
1095fn running_integral(time_s: &[f64], velocity: &[f64]) -> Vec<f64> {
1096    let mut integral = 0.0;
1097    let mut out = Vec::with_capacity(time_s.len().min(velocity.len()));
1098    let mut previous: Option<(f64, f64)> = None;
1099    for (&time, &value) in time_s.iter().zip(velocity) {
1100        if let Some((before_s, before)) = previous {
1101            integral += 0.5 * (value + before) * (time - before_s);
1102        }
1103        out.push(integral);
1104        previous = Some((time, value));
1105    }
1106    out
1107}
1108
1109/// The altitude above the first row at a time, linear between rows, and the first or the last
1110/// row's before or after the record. `cursor` is the row at or before the time last asked for,
1111/// so that asking in increasing order walks the rows once.
1112fn altitude_at(time_s: &[f64], above_m: &[f64], time: f64, cursor: &mut usize) -> f64 {
1113    while time_s.get(*cursor + 1).is_some_and(|next| *next <= time) {
1114        *cursor += 1;
1115    }
1116    match (
1117        time_s.get(*cursor),
1118        time_s.get(*cursor + 1),
1119        above_m.get(*cursor),
1120        above_m.get(*cursor + 1),
1121    ) {
1122        (Some(&from_s), _, Some(&from), _) if time <= from_s => from,
1123        (Some(&from_s), Some(&to_s), Some(&from), Some(&to)) => {
1124            from + (to - from) * (time - from_s) / (to_s - from_s)
1125        }
1126        _ => above_m.last().copied().unwrap_or_default(),
1127    }
1128}
1129
1130/// The velocity's unit per m/s, by the areas and by the fit with a delay (module docs); `None`
1131/// if the altitude never leaves the first row's or a measure isn't a number.
1132fn velocity_scale(time_s: &[f64], altitude_m: &[f64], velocity: &[f64]) -> Option<Scale> {
1133    let first = *altitude_m.first()?;
1134    let above: Vec<f64> = altitude_m.iter().map(|value| value - first).collect();
1135    let integral = running_integral(time_s, velocity);
1136    let rows = integral.len().min(above.len());
1137    let (time_s, above, integral) = (&time_s[..rows], &above[..rows], &integral[..rows]);
1138
1139    let (earliest, latest, step) = DELAY_SEARCH_S;
1140    #[allow(
1141        clippy::cast_possible_truncation,
1142        reason = "a constant search of 120 steps"
1143    )]
1144    let steps = ((latest - earliest) / step).round() as i32;
1145    let mut best: Option<(f64, f64, f64)> = None;
1146    for at in 0..=steps {
1147        let delay_s = earliest + f64::from(at) * step;
1148        let (mut product, mut square) = (0.0, 0.0);
1149        let mut cursor = 0;
1150        for (&time, &value) in time_s.iter().zip(integral) {
1151            let earlier = altitude_at(time_s, above, time - delay_s, &mut cursor);
1152            product += value * earlier;
1153            square += earlier * earlier;
1154        }
1155        // The residual is Σ I² − (Σ I h)² / Σ h²: the best delay explains the most of it.
1156        let explained = product * product / square;
1157        if square > 0.0 && best.is_none_or(|(most, _, _)| explained > most) {
1158            best = Some((explained, product / square, delay_s));
1159        }
1160    }
1161    let (_, by_fit, delay_s) = best?;
1162    // The areas, both over the record, under the integral and under the altitude as it was
1163    // `delay_s` earlier, by trapezoids.
1164    let mut cursor = 0;
1165    let earlier: Vec<f64> = time_s
1166        .iter()
1167        .map(|time| altitude_at(time_s, above, time - delay_s, &mut cursor))
1168        .collect();
1169    let (mut integral_area, mut altitude_area) = (0.0, 0.0);
1170    for index in 1..rows {
1171        let step_s = time_s[index] - time_s[index - 1];
1172        integral_area += 0.5 * (integral[index] + integral[index - 1]) * step_s;
1173        altitude_area += 0.5 * (earlier[index] + earlier[index - 1]) * step_s;
1174    }
1175    let by_area = integral_area / altitude_area;
1176    let climb_m = above.iter().copied().fold(0.0, f64::max);
1177    let (&end_s, &end_m) = (time_s.last()?, above.last()?);
1178    // The altitude's rate over the record's last second, and over the second the velocity's
1179    // last row reflects, `delay_s` earlier: the faster of the two.
1180    let span_s = (end_s - time_s.first()?).min(1.0);
1181    let rate_to = |to_s: f64| {
1182        (altitude_at(time_s, above, to_s, &mut 0)
1183            - altitude_at(time_s, above, to_s - span_s, &mut 0))
1184            / span_s
1185    };
1186    let end_rate = rate_to(end_s).abs().max(rate_to(end_s - delay_s).abs());
1187    let end_error = delay_s * delay_s * end_rate / (2.0 * altitude_area);
1188    let peak = velocity[..rows]
1189        .iter()
1190        .fold(0.0, |most: f64, v| most.max(v.abs()));
1191    let start_share = if peak > 0.0 {
1192        velocity.first()?.abs() / peak
1193    } else {
1194        0.0
1195    };
1196    let closure = (integral.last()? - by_fit * earlier.last()?).abs() / (by_fit.abs() * climb_m);
1197    (altitude_area > 0.0 && by_area.is_finite() && by_fit.is_finite()).then_some(Scale {
1198        by_area,
1199        by_fit,
1200        delay_s,
1201        end_height: end_m / climb_m,
1202        end_error: if span_s > 0.0 {
1203            end_error
1204        } else {
1205            f64::INFINITY
1206        },
1207        start_share,
1208        closure,
1209    })
1210}
1211
1212/// Each speed unit's miss from a slope, as a fraction, nearest first.
1213fn speed_misses(slope: f64) -> Vec<(usize, f64)> {
1214    let mut misses: Vec<(usize, f64)> = SPEEDS
1215        .iter()
1216        .enumerate()
1217        .map(|(index, (_, _, m_s))| (index, slope * m_s - 1.0))
1218        .collect();
1219    misses.sort_by(|a, b| (a.1 + 1.0).ln().abs().total_cmp(&(b.1 + 1.0).ln().abs()));
1220    misses
1221}
1222
1223/// The altitude a velocity is measured against: its clock, its values in meters, and whether its
1224/// unit was stated or decided rather than assumed.
1225struct Track<'a> {
1226    time_s: &'a [f64],
1227    altitude_m: &'a [f64],
1228    known: bool,
1229}
1230
1231/// The speed unit both measures land nearest, each within [`VELOCITY_MARGIN`], as an index into
1232/// [`SPEEDS`]; `None` if they don't, if the record ends too high or still moving for the measure
1233/// by the areas to hold, or if the velocity starts above rest or its integral doesn't close on
1234/// the altitude (module docs).
1235fn agreed_unit(scale: &Scale) -> Option<usize> {
1236    if !(scale.end_height <= END_HEIGHT
1237        && scale.end_error <= END_ERROR
1238        && scale.start_share <= START_SHARE
1239        && scale.closure <= CLOSURE_SHARE)
1240    {
1241        return None;
1242    }
1243    measures_agree(scale)
1244}
1245
1246/// The speed unit both measures land nearest, each within [`VELOCITY_MARGIN`], whatever the record
1247/// is like.
1248fn measures_agree(scale: &Scale) -> Option<usize> {
1249    let (area_unit, area_miss) = *speed_misses(scale.by_area).first()?;
1250    let (fit_unit, fit_miss) = *speed_misses(scale.by_fit).first()?;
1251    (area_unit == fit_unit
1252        && area_miss.abs() <= VELOCITY_MARGIN
1253        && fit_miss.abs() <= VELOCITY_MARGIN)
1254        .then_some(area_unit)
1255}
1256
1257/// A speed unit's words and its miss from each measure, as a note writes them.
1258fn unit_misses(index: usize, scale: &Scale) -> (&'static str, f64, f64) {
1259    let (words, _, m_s) = SPEEDS.get(index).copied().unwrap_or(SPEEDS[0]);
1260    (words, scale.by_area * m_s - 1.0, scale.by_fit * m_s - 1.0)
1261}
1262
1263/// The velocity's unit, from the header or measured against the altitude (module docs).
1264fn decide_velocity(
1265    values: &[f64],
1266    track: &Track,
1267    units: &HeaderUnits,
1268    written: &str,
1269    header_line: usize,
1270    notes: &mut Vec<String>,
1271) -> Result<Decided, LogError> {
1272    let Track {
1273        time_s,
1274        altitude_m,
1275        known: altitude_known,
1276    } = *track;
1277    let first = altitude_m.first().copied().unwrap_or_default();
1278    let climb_m = altitude_m.iter().copied().fold(first, f64::max) - first;
1279    let scale = (altitude_known && climb_m >= VELOCITY_CLIMB_M)
1280        .then(|| velocity_scale(time_s, altitude_m, values))
1281        .flatten();
1282    let in_si = |index: usize| {
1283        let m_s = SPEEDS.get(index).map_or(1.0, |(_, _, m_s)| *m_s);
1284        Decided {
1285            quantity: Quantity::Speed,
1286            values: values.iter().map(|value| value * m_s).collect(),
1287        }
1288    };
1289    // The unit both measures land nearest, each within the margin, if there is one.
1290    let nearest = scale.map(|scale| {
1291        let by_area = speed_misses(scale.by_area);
1292        let by_fit = speed_misses(scale.by_fit);
1293        (scale, by_area, by_fit)
1294    });
1295    let decided = nearest.as_ref().and_then(|(scale, by_area, _)| {
1296        let index = agreed_unit(scale)?;
1297        Some((*scale, index, by_area.get(1).map(|(other, _)| *other)))
1298    });
1299    // The two measures as sentences: first the altitude both take, delayed (in lower case, to
1300    // follow a lead-in; `capitalized` starts a sentence with it), then the area and the slope.
1301    let lead = |scale: &Scale| {
1302        format!(
1303            "the altitude above the first row, in meters, is taken as it was {:.2} s earlier",
1304            scale.delay_s
1305        )
1306    };
1307    let measures = |scale: &Scale| {
1308        format!(
1309            "The area under the velocity's running integral is {:.4} times that altitude's. The \
1310             integral's least-squares slope against that altitude is {:.4}",
1311            scale.by_area, scale.by_fit
1312        )
1313    };
1314    if let Some(stated) = units.velocity {
1315        if let Some((scale, index, _)) = decided
1316            && index != stated
1317        {
1318            return Err(LogError::Unit {
1319                format: FORMAT,
1320                line: header_line,
1321                message: format!(
1322                    "{:?} states {}, but the two measures land nearest {}. {}. {}",
1323                    short(written),
1324                    SPEEDS.get(stated).map_or("", |unit| unit.0),
1325                    SPEEDS.get(index).map_or("", |unit| unit.0),
1326                    crate::log::capitalized(&lead(&scale)),
1327                    measures(&scale)
1328                ),
1329            });
1330        }
1331        return Ok(in_si(stated));
1332    }
1333    match decided {
1334        Some((scale, index, runner_up)) => {
1335            let runner_up = runner_up
1336                .map(|other| {
1337                    let (words, by_area, by_fit) = unit_misses(other, &scale);
1338                    format!(
1339                        ". The next nearest, {words}, would miss both by {:+.1}% and {:+.1}%",
1340                        by_area * 100.0,
1341                        by_fit * 100.0
1342                    )
1343                })
1344                .unwrap_or_default();
1345            let (words, by_area, by_fit) = unit_misses(index, &scale);
1346            notes.push(format!(
1347                "`{}` read in {words}, from the altitude. Over {} rows, {}. {}. Read in {words}, the \
1348                 velocity would give {:.4} per m/s, {:+.2}% off the area and {:+.2}% off the \
1349                 slope{runner_up}",
1350                short(written),
1351                time_s.len(),
1352                lead(&scale),
1353                measures(&scale),
1354                1.0 / SPEEDS.get(index).map_or(1.0, |unit| unit.2),
1355                by_area * 100.0,
1356                by_fit * 100.0
1357            ));
1358            Ok(in_si(index))
1359        }
1360        None => {
1361            let why = if !altitude_known {
1362                "the altitude's unit is only assumed, so the velocity can't be measured against \
1363                 it"
1364                .to_owned()
1365            } else if climb_m < VELOCITY_CLIMB_M {
1366                format!(
1367                    "the altitude climbs {climb_m:.1} m, under the {VELOCITY_CLIMB_M} m over which \
1368                     the velocity is measured against it"
1369                )
1370            } else {
1371                match &nearest {
1372                    Some((scale, _, _))
1373                        if scale.end_height > END_HEIGHT || scale.end_height.is_nan() =>
1374                    {
1375                        format!(
1376                            "the record ends {:.0}% of the way up the climb. That is above the \
1377                             {:.0}% it must come down to for the velocity to be measured against \
1378                             the altitude",
1379                            scale.end_height * 100.0,
1380                            END_HEIGHT * 100.0
1381                        )
1382                    }
1383                    Some((scale, _, _))
1384                        if scale.end_error > END_ERROR || scale.end_error.is_nan() =>
1385                    {
1386                        format!(
1387                            "the record ends with the altitude still moving, which could move \
1388                             the area under the velocity's running integral by about {:.2}%, \
1389                             over the {:.1}% allowed",
1390                            scale.end_error * 100.0,
1391                            END_ERROR * 100.0
1392                        )
1393                    }
1394                    Some((scale, _, _)) if scale.start_share > START_SHARE => {
1395                        format!(
1396                            "the velocity's first row is {:.1}% of its peak, above the {:.0}% it \
1397                             may be at rest, so its integral may have missed the start of the climb",
1398                            scale.start_share * 100.0,
1399                            START_SHARE * 100.0
1400                        )
1401                    }
1402                    Some((scale, _, _)) if scale.closure > CLOSURE_SHARE => {
1403                        format!(
1404                            "the velocity's running integral ends {:.1}% of the climb from the \
1405                             altitude, over the {:.0}% allowed, as a smoothing across the record's \
1406                             ends can leave it",
1407                            scale.closure * 100.0,
1408                            CLOSURE_SHARE * 100.0
1409                        )
1410                    }
1411                    Some((scale, by_area, by_fit)) => {
1412                        let nearest_of = |misses: &[(usize, f64)]| {
1413                            misses.first().map_or(String::new(), |(index, miss)| {
1414                                format!(
1415                                    "{} {:+.1}%",
1416                                    SPEEDS.get(*index).map_or("", |unit| unit.0),
1417                                    miss * 100.0
1418                                )
1419                            })
1420                        };
1421                        format!(
1422                            "{}. {}. The two measures don't both land within {:.0}% of one of ft/s, mph, \
1423                             m/s and km/h (the nearest {} and {})",
1424                            lead(scale),
1425                            measures(scale),
1426                            VELOCITY_MARGIN * 100.0,
1427                            nearest_of(by_area),
1428                            nearest_of(by_fit)
1429                        )
1430                    }
1431                    None => {
1432                        "its running integral can't be measured against the altitude".to_owned()
1433                    }
1434                }
1435            };
1436            notes.push(format!(
1437                "`{}` kept as written, its unit unknown: {why}",
1438                short(written)
1439            ));
1440            Ok(Decided {
1441                quantity: Quantity::Unrecognized,
1442                values: values.to_vec(),
1443            })
1444        }
1445    }
1446}
1447
1448/// The temperature in its header's unit, or kept as written when the header states none: the
1449/// altitude's unit doesn't decide it (module docs).
1450fn decide_temperature(
1451    values: &[f64],
1452    units: &HeaderUnits,
1453    written: &str,
1454    notes: &mut Vec<String>,
1455) -> Decided {
1456    let Some(unit) = units.temperature else {
1457        notes.push(format!(
1458            "`{}` kept as written, its unit unknown. The file states none. mDACS sets the \
1459             temperature's unit by its own preference, apart from the altitude's (mDACS manual \
1460             p. 5). The column's values, as written, run {}",
1461            short(written),
1462            span(values)
1463        ));
1464        return Decided {
1465            quantity: Quantity::Unrecognized,
1466            values: values.to_vec(),
1467        };
1468    };
1469    Decided {
1470        quantity: Quantity::Temperature,
1471        values: values.iter().map(|value| unit.kelvin(*value)).collect(),
1472    }
1473}
1474
1475fn syntax(line: usize, message: String) -> LogError {
1476    LogError::Syntax {
1477        format: FORMAT,
1478        line,
1479        message,
1480    }
1481}
1482
1483#[cfg(test)]
1484mod tests {
1485    use super::*;
1486
1487    const HEADER: &str = "Time,Altitude,Pressure,Velocity,Temperature,Events,Voltages";
1488
1489    /// The pressure, hPa, at a height above the pad, m, in the standard atmosphere's troposphere
1490    /// (the altimeter formula of [`Ussa76::pressure_altitude_m`], inverted), the pad at sea level.
1491    fn pressure_hpa(height_m: f64) -> f64 {
1492        1_013.25 * (1.0 - height_m / 44_330.8).powf(1.0 / 0.190_263)
1493    }
1494
1495    /// An invented flight, one row every half second: a row at rest on the pad, as the sample
1496    /// exports start, a climb at `climb_m_s` to `top_m`, then a
1497    /// descent at a third of it, the altitude written in `length`, the velocity's m/s multiplied by
1498    /// `per_m_s`, the temperature 70 and the battery 9.2; `tail` short rows at the end.
1499    fn flight(top_m: f64, climb_m_s: f64, length: f64, per_m_s: f64, tail: usize) -> String {
1500        let mut text = format!("{HEADER}\n");
1501        let mut heights = vec![0.0_f64; 2];
1502        let mut climbing = true;
1503        while climbing || heights.last().is_some_and(|height| *height > 0.0) {
1504            let height = heights.last().copied().unwrap_or_default();
1505            climbing &= height < top_m;
1506            let speed = if climbing {
1507                climb_m_s
1508            } else {
1509                -climb_m_s / 3.0
1510            };
1511            heights.push((height + speed * 0.5).clamp(0.0, top_m));
1512        }
1513        heights.push(0.0);
1514        let count = heights.len();
1515        // The speed at each row: the altitude's rate across its neighbors, or to its one
1516        // neighbor at either end.
1517        let speed = |index: usize| {
1518            let before = index.saturating_sub(1);
1519            let after = (index + 1).min(count - 1);
1520            (heights[after] - heights[before]) / ((after - before) as f64 * 0.5)
1521        };
1522        for (index, &height) in heights.iter().enumerate() {
1523            let (time, speed) = (index as f64 * 0.5, speed(index));
1524            let event = if index == 3 { "Drogue" } else { "-" };
1525            let common = format!(
1526                "{time:.2},{:.3},{:.2},{:.3}",
1527                height / length,
1528                pressure_hpa(height),
1529                speed * per_m_s
1530            );
1531            if index + tail >= count {
1532                text.push_str(&format!("{common}, {event}\n"));
1533            } else {
1534                text.push_str(&format!("{common},70.00, {event},9.20\n"));
1535            }
1536        }
1537        text
1538    }
1539
1540    fn close(a: f64, b: f64) -> bool {
1541        (a - b).abs() <= 1e-9 * b.abs().max(1.0)
1542    }
1543
1544    fn notes_starting<'a>(log: &'a FlightLog, start: &str) -> Vec<&'a String> {
1545        log.notes.iter().filter(|n| n.starts_with(start)).collect()
1546    }
1547
1548    /// The `Temperature` column's values as written, from a header that gives it no unit.
1549    fn temperature_as_written(log: &FlightLog) -> &[f64] {
1550        let column = log.channels.iter().find(|c| c.column == "Temperature");
1551        let column = column.unwrap();
1552        assert_eq!(column.quantity, Quantity::Unrecognized);
1553        &column.values
1554    }
1555
1556    /// Neither unit is taken from the altitude's (#852). Two real files, both in feet, are
1557    /// shaped here: one whose temperature, 47.2 falling to 43.2, is °C beside the other loggers
1558    /// on its flight, and one whose 69.8 to 70.5 is °F beside the airport's air. Both keep their
1559    /// numbers as written, and a bracketed unit is still read.
1560    #[test]
1561    fn an_unbracketed_temperature_is_kept_as_written_whatever_the_altitude() {
1562        for (first, last) in [(47.2, 43.2), (69.8, 70.5)] {
1563            let mut text = format!("{HEADER}\n");
1564            for i in 0..5 {
1565                let t = first + (last - first) * f64::from(i) / 4.0;
1566                text.push_str(&format!(
1567                    "{},{},{:.2},0,{t:.1}, -,9.2\n",
1568                    f64::from(i) * 0.05,
1569                    i,
1570                    1_000.0 - 0.04 * f64::from(i)
1571                ));
1572            }
1573            let log = read(&text).unwrap();
1574            assert!(log.temperature_k.is_none());
1575            let written = temperature_as_written(&log);
1576            assert_eq!((written[0], written[4]), (first, last));
1577        }
1578        for (unit, kelvin) in [("[C]", 70.0 + 273.15), ("[F]", 294.261)] {
1579            let header = HEADER.replace("Temperature", &format!("Temperature {unit}"));
1580            let log = read(&format!("{header}\n0,0,1000,0,70, -,9.2\n")).unwrap();
1581            let read_k = log.temperature_k.as_deref().unwrap()[0];
1582            assert!((read_k - kelvin).abs() < 1e-3, "{unit}: {read_k}");
1583        }
1584    }
1585
1586    /// A pressure in hPa and a temperature in °F near the largest `f64` are finite as written and
1587    /// infinite in SI: each is refused on its line (ADR-258 §3).
1588    #[test]
1589    fn a_value_its_conversion_makes_infinite_is_refused() {
1590        let cases = [
1591            (
1592                "Time,Altitude,Pressure [hPa],Velocity\n0,0,1013,0\n0.05,1,1.7e308,0\n",
1593                "line 3: the column Pressure [hPa] holds",
1594            ),
1595            (
1596                "Time,Altitude,Pressure,Velocity,Temperature [F]\n0,0,1013,0,70\n\
1597                 0.05,1,1013,0,-1.7e308\n",
1598                "line 3: the column Temperature [F] holds",
1599            ),
1600        ];
1601        for (text, refusal) in cases {
1602            assert_eq!(
1603                read(text).unwrap_err().to_string(),
1604                format!("RRC3 CSV {refusal} a value too large for its unit's conversion to SI")
1605            );
1606        }
1607    }
1608
1609    /// The flight as a European locale's export writes it: semicolons, decimal commas, and a
1610    /// semicolon ending every line.
1611    fn european(text: &str) -> String {
1612        text.lines()
1613            .map(|line| format!("{};\n", line.replace(',', ";").replace('.', ",")))
1614            .collect()
1615    }
1616
1617    #[test]
1618    fn a_european_export_ending_its_lines_in_semicolons_reads_alike() {
1619        // With and without short rows, as most exports end, without their 1 Hz cells.
1620        for tail in [0, 3] {
1621            let text = flight(300.0, 60.0, FOOT_M, 3.2808, tail);
1622            let plain = read(&text).unwrap();
1623            let semicolons = read(&european(&text)).unwrap();
1624            assert_eq!(semicolons.time_s, plain.time_s, "{tail}");
1625            assert_eq!(semicolons.altitude_m, plain.altitude_m);
1626            // As JSON, where a gap, `NaN`, is `null` and equal to itself.
1627            let json = |log: &FlightLog| serde_json::to_string(log).unwrap();
1628            assert_eq!(json(&semicolons), json(&plain), "{tail}");
1629        }
1630        let text = flight(300.0, 60.0, FOOT_M, 3.2808, 0);
1631        let plain = read(&text).unwrap();
1632        // A short row padded with empty 1 Hz cells after its own reads as the short row does.
1633        let short_text = european(&flight(300.0, 60.0, FOOT_M, 3.2808, 3));
1634        let short = read(&short_text).unwrap();
1635        let padded = short_text
1636            .lines()
1637            .map(|line| {
1638                if line.matches(';').count() == 5 {
1639                    format!("{line};;\n")
1640                } else {
1641                    format!("{line}\n")
1642                }
1643            })
1644            .collect::<String>();
1645        assert_eq!(padded.matches(";;;\n").count(), 3);
1646        let json = |log: &FlightLog| serde_json::to_string(&log.channels).unwrap();
1647        assert_eq!(json(&read(&padded).unwrap()), json(&short));
1648        // Padded to the full width with no closing semicolon, its last 1 Hz cell empty, alike.
1649        let unclosed = short_text
1650            .lines()
1651            .map(|line| {
1652                if line.matches(';').count() == 5 {
1653                    format!("{line};\n")
1654                } else {
1655                    format!("{line}\n")
1656                }
1657            })
1658            .collect::<String>();
1659        assert_eq!(unclosed.matches(";;\n").count(), 3);
1660        assert_eq!(json(&read(&unclosed).unwrap()), json(&short));
1661        // A row of empty cells at the end, as one sample ends, is skipped as the plain file's is.
1662        let with_blank = format!("{};;;;;;;\n", european(&text));
1663        assert_eq!(read(&with_blank).unwrap().time_s, plain.time_s);
1664        // A row with a cell more than the header names, its last not empty, is refused.
1665        let extra = european(&text).replacen(";9,20;\n", ";9,20;1\n", 1);
1666        assert!(matches!(
1667            read(&extra),
1668            Err(LogError::Syntax { line: 2, .. })
1669        ));
1670    }
1671
1672    #[test]
1673    fn rows_sorted_as_text_are_refused_where_the_time_goes_back() {
1674        // A spreadsheet sorting the rows by the time's text puts `10,5` before `2`.
1675        let text = european(&flight(300.0, 60.0, FOOT_M, 3.2808, 0));
1676        let mut lines: Vec<&str> = text.lines().collect();
1677        let header = lines.remove(0);
1678        lines.sort_unstable();
1679        let sorted = format!("{header}\n{}\n", lines.join("\n"));
1680        let back = lines
1681            .windows(2)
1682            .position(|pair| {
1683                let time = |line: &str| line.split(';').next().unwrap().replace(',', ".");
1684                time(pair[1]).parse::<f64>().unwrap() <= time(pair[0]).parse::<f64>().unwrap()
1685            })
1686            .unwrap();
1687        assert!(matches!(
1688            read(&sorted),
1689            Err(LogError::Syntax { line, ref message, .. })
1690                if line == back + 3 && message.contains("doesn't come after the one above it")
1691        ));
1692    }
1693
1694    #[test]
1695    fn recognizes_only_an_mdacs_header() {
1696        let yes = [
1697            HEADER,
1698            "\u{feff}\r\n\r\nTime,Altitude,Pressure,Velocity,Events",
1699            "Time,Altitude,Pressure,Velocity,Temperature",
1700            "Time,Altitude,Pressure,Velocity,Voltages",
1701            "time,ALTITUDE,pressure,Velocity",
1702            "Time [s],Altitude [ft],Pressure [mbar],Velocity [ft/s],Temperature [F],Events,Voltages [V]",
1703            "Time;Altitude;Pressure;Velocity;Temperature;Events;Voltages",
1704            "Time\tAltitude\tPressure\tVelocity\tEvents",
1705            // An unknown unit is recognized, then refused by `read` as a unit.
1706            "Time,Altitude [yd],Pressure,Velocity",
1707        ];
1708        for header in yes {
1709            assert!(recognizes(header), "{header:?}");
1710        }
1711        let no = [
1712            "",
1713            // PerfectFlite's exports: no pressure.
1714            "Time,Altitude,Velocity,Temperature (F),Voltage",
1715            "Time, Altitude, Velocity",
1716            "Time,Altitude,Pressure",
1717            "Time,Pressure,Altitude,Velocity",
1718            "Time,Altitude,Pressure,Velocity,Temperature,Temperature",
1719            "Time,Altitude,Pressure,Velocity,Accel",
1720            "Time,Altitude,Pressure,Velocity,",
1721            "# Time,Altitude,Pressure,Velocity",
1722            "Time,Altitude [ft,Pressure,Velocity",
1723        ];
1724        for header in no {
1725            assert!(!recognizes(header), "{header:?}");
1726        }
1727        // Only the first line that isn't blank is looked at.
1728        assert!(!recognizes("x\nTime,Altitude,Pressure,Velocity\n"));
1729    }
1730
1731    /// The common file: feet and ft/s decided from the file, the temperature kept as written and
1732    /// volts assumed, events at their rows, the short tail's 1 Hz cells gaps.
1733    #[test]
1734    fn decides_feet_and_feet_per_second_from_the_file() {
1735        let text = flight(300.0, 60.0, FOOT_M, 1.0 / FOOT_M, 2);
1736        let log = read(&text).unwrap();
1737        assert_eq!(log.format, LogFormat::Rrc3Csv);
1738        let quantities: Vec<Quantity> = log.channels.iter().map(|c| c.quantity).collect();
1739        assert_eq!(
1740            quantities,
1741            [
1742                Quantity::AltitudeAboveGround,
1743                Quantity::Pressure,
1744                Quantity::Speed,
1745                Quantity::Unrecognized,
1746                Quantity::Voltage
1747            ]
1748        );
1749        // Written to three decimals: 98.425 ft and 196.850 ft/s.
1750        assert!(close(log.altitude_m[2], 98.425 * FOOT_M));
1751        assert!(close(
1752            log.vertical_speed_m_s.as_deref().unwrap()[2],
1753            196.85 * FOOT_M
1754        ));
1755        // The altitude in feet doesn't make the temperature °F (#852): 70 as written, no kelvins.
1756        assert!(log.temperature_k.is_none());
1757        let temperature = temperature_as_written(&log);
1758        assert_eq!(temperature[0], 70.0);
1759        let n = log.time_s.len();
1760        assert!(temperature[n - 2..].iter().all(|t| t.is_nan()));
1761        assert!(temperature[n - 3].is_finite());
1762        assert_eq!(log.events.len(), 1);
1763        assert_eq!(
1764            (log.events[0].time_s, log.events[0].name.as_str()),
1765            (1.5, "Drogue")
1766        );
1767        for start in [
1768            "`Altitude` read in feet, from the pressure: ",
1769            "`Velocity` read in feet per second, from the altitude. ",
1770            "`Pressure` read in hectopascals, from the values: ",
1771            "`Temperature` kept as written, its unit unknown. ",
1772            "`Voltages` read in volts, assumed. ",
1773            "`Time` read in seconds, assumed. ",
1774            "2 rows, the first on line ",
1775        ] {
1776            assert_eq!(
1777                notes_starting(&log, start).len(),
1778                1,
1779                "{start}: {:?}",
1780                log.notes
1781            );
1782        }
1783    }
1784
1785    /// Each velocity unit is told from the others, km/h from ft/s too, 9.7% apart.
1786    #[test]
1787    fn each_velocity_unit_is_told_apart() {
1788        for (words, _, m_s) in SPEEDS {
1789            let text = flight(300.0, 60.0, FOOT_M, 1.0 / m_s, 0);
1790            let log = read(&text).unwrap();
1791            let start = format!("`Velocity` read in {words}, from the altitude. ");
1792            assert_eq!(
1793                notes_starting(&log, &start).len(),
1794                1,
1795                "{words}: {:?}",
1796                log.notes
1797            );
1798            // Written to three decimals, within half a thousandth of the unit.
1799            assert!(
1800                (log.vertical_speed_m_s.as_deref().unwrap()[2] - 60.0).abs() < 5e-4 * m_s.max(1.0)
1801            );
1802        }
1803    }
1804
1805    /// Meters decided from the pressure; the temperature then assumed in °C.
1806    #[test]
1807    fn decides_meters_from_the_pressure() {
1808        let text = flight(300.0, 60.0, 1.0, 1.0, 0);
1809        let log = read(&text).unwrap();
1810        assert!(close(log.altitude_m[2], 30.0));
1811        assert_eq!(
1812            notes_starting(&log, "`Altitude` read in meters, from the pressure: ").len(),
1813            1
1814        );
1815        // Nor do meters make it °C.
1816        assert!(log.temperature_k.is_none());
1817        assert_eq!(temperature_as_written(&log)[0], 70.0);
1818        assert_eq!(
1819            notes_starting(&log, "`Temperature` kept as written, its unit unknown. ").len(),
1820            1
1821        );
1822    }
1823
1824    /// A velocity in none of the four units, or measured over too short a climb, or against an
1825    /// altitude whose unit is only assumed, is kept as written.
1826    #[test]
1827    fn a_velocity_that_cant_be_told_is_kept_as_written() {
1828        // Cut off before the descent: the last row stands above half the climb.
1829        let full = flight(300.0, 60.0, FOOT_M, 1.0 / FOOT_M, 0);
1830        let cut: String = full
1831            .lines()
1832            .take(14)
1833            .map(|line| format!("{line}\n"))
1834            .collect();
1835        // Without its row on the pad: the velocity starts at half its peak.
1836        let above_rest: String = full
1837            .lines()
1838            .enumerate()
1839            .filter(|(row, _)| *row != 1)
1840            .map(|(_, line)| format!("{line}\n"))
1841            .collect();
1842        // The descent's velocity a fifth too fast: its integral ends a fifth of the climb away.
1843        let open_ended: String = full
1844            .lines()
1845            .map(|line| {
1846                let mut cells: Vec<String> = line.split(',').map(str::to_owned).collect();
1847                if let Some(rate) = cells.get(3).and_then(|cell| cell.parse::<f64>().ok())
1848                    && rate < 0.0
1849                {
1850                    cells[3] = format!("{:.3}", rate * 1.2);
1851                }
1852                cells.join(",") + "\n"
1853            })
1854            .collect();
1855        // A column of zeros is at rest throughout: no first row above rest to blame.
1856        let at_rest = flight(300.0, 60.0, FOOT_M, 0.0, 0);
1857        let cases = [
1858            (
1859                flight(300.0, 60.0, FOOT_M, 3.0, 0),
1860                "don't both land within 3% of one",
1861            ),
1862            (
1863                flight(40.0, 20.0, FOOT_M, 1.0 / FOOT_M, 0),
1864                "under the 50 m",
1865            ),
1866            (flight(8.0, 4.0, FOOT_M, 1.0 / FOOT_M, 0), "only assumed"),
1867            (cut, "of the way up the climb. That is above the 50%"),
1868            (above_rest, "above the 1% it may be at rest"),
1869            (open_ended, "over the 1% allowed"),
1870            (at_rest, "the record ends with the altitude still moving"),
1871        ];
1872        for (text, why) in cases {
1873            let log = read(&text).unwrap();
1874            assert_eq!(log.channels[2].quantity, Quantity::Unrecognized);
1875            assert!(log.vertical_speed_m_s.is_none());
1876            let kept = notes_starting(&log, "`Velocity` kept as written, its unit unknown: ");
1877            assert_eq!(kept.len(), 1, "{:?}", log.notes);
1878            assert!(kept[0].contains(why), "{why}: {kept:?}");
1879        }
1880        // Under 10 m of climb, feet are assumed and said so.
1881        let log = read(&flight(8.0, 4.0, FOOT_M, 1.0 / FOOT_M, 0)).unwrap();
1882        let assumed = notes_starting(&log, "`Altitude` read in feet, assumed: ");
1883        assert!(assumed[0].contains("climbs 8.0 m"), "{assumed:?}");
1884    }
1885
1886    /// A pressure outside the RRC3's range is kept as written, and the altitude assumed in feet.
1887    #[test]
1888    fn a_pressure_of_unknown_unit_is_kept_as_written() {
1889        let text = format!("{HEADER}\n0,0,101325,0,70, -,9.2\n0.05,1,101310,1,70, -,9.2\n");
1890        let log = read(&text).unwrap();
1891        assert_eq!(log.channels[1].quantity, Quantity::Unrecognized);
1892        assert_eq!(log.channels[1].values, [101_325.0, 101_310.0]);
1893        assert_eq!(
1894            notes_starting(&log, "`Pressure` kept as written, its unit unknown: ").len(),
1895            1
1896        );
1897        let assumed = notes_starting(&log, "`Altitude` read in feet, assumed: ");
1898        assert!(assumed[0].contains("unit is unknown"), "{assumed:?}");
1899    }
1900
1901    /// Units in brackets are taken as written, cross-checked, and an unknown one refused.
1902    #[test]
1903    fn bracketed_units() {
1904        let text = flight(300.0, 60.0, 1.0, 3.6, 0).replacen(
1905            HEADER,
1906            "Time [s],Altitude [m],Pressure [hPa],Velocity [kph],Temperature [°F],Events,Voltages [V]",
1907            1,
1908        );
1909        let log = read(&text).unwrap();
1910        assert!(close(log.vertical_speed_m_s.as_deref().unwrap()[2], 60.0));
1911        // 70 °F is 294.261 K.
1912        assert!((log.temperature_k.as_deref().unwrap()[0] - 294.261).abs() < 1e-3);
1913        assert!(
1914            log.notes.iter().all(|n| !n.contains(" read in ")),
1915            "{:?}",
1916            log.notes
1917        );
1918
1919        // A stated unit the file contradicts is refused as a unit.
1920        let wrong_altitude = text.replacen("Altitude [m]", "Altitude [ft]", 1);
1921        let error = read(&wrong_altitude).unwrap_err();
1922        assert!(
1923            matches!(&error, LogError::Unit { line: 1, message, .. } if message.contains("states feet, which the pressure contradicts")),
1924            "{error:?}"
1925        );
1926        let wrong_speed = text.replacen("Velocity [kph]", "Velocity [m/s]", 1);
1927        let error = read(&wrong_speed).unwrap_err();
1928        assert!(
1929            matches!(&error, LogError::Unit { line: 1, message, .. } if message.contains("\"Velocity [m/s]\" states meters per second, but the two measures land nearest kilometers per hour. The altitude above the first row")),
1930            "{error:?}"
1931        );
1932        for header in [
1933            "Time [ms],Altitude,Pressure,Velocity",
1934            "Time,Altitude [yd],Pressure,Velocity",
1935            "Time,Altitude,Pressure [psi],Velocity",
1936            "Time,Altitude,Pressure,Velocity [knots]",
1937            "Time,Altitude,Pressure,Velocity,Temperature [K]",
1938            "Time,Altitude,Pressure,Velocity,Events [x]",
1939            "Time,Altitude,Pressure,Velocity,Voltages [mV]",
1940        ] {
1941            let error = read(&format!("{header}\n0,0,1000,0\n")).unwrap_err();
1942            assert!(
1943                matches!(&error, LogError::Unit { line: 1, message, .. } if message.contains("states a unit this reader doesn't know")),
1944                "{header}: {error:?}"
1945            );
1946        }
1947    }
1948
1949    /// An altitude whose climb matches the pressure's in neither unit is refused.
1950    #[test]
1951    fn an_altitude_in_neither_unit_is_refused() {
1952        let text = flight(300.0, 60.0, 1.0 / 1.6, 1.0, 0);
1953        let error = read(&text).unwrap_err();
1954        assert!(
1955            matches!(&error, LogError::Unit { line: 1, message, .. } if message.contains("neither feet nor meters")),
1956            "{error:?}"
1957        );
1958    }
1959
1960    /// Semicolons or tabs with decimal commas; a comma file doesn't take them.
1961    #[test]
1962    fn semicolons_and_tabs_take_decimal_commas() {
1963        let comma = "0,00;0;1013,25;0;21,5; -;9,2\n0,05;1,5;1013,07;2,5;21,5; Main;9,1\n";
1964        let log = read(&format!("{}\n{comma}", HEADER.replace(',', ";"))).unwrap();
1965        assert_eq!(log.time_s, [0.0, 0.05]);
1966        assert_eq!(log.events[0].name, "Main");
1967        assert!(close(log.channels[1].values[1], 101_307.0));
1968        let tabbed = comma.replace(';', "\t");
1969        let log = read(&format!("{}\n{tabbed}", HEADER.replace(',', "\t"))).unwrap();
1970        assert_eq!(log.battery_v.as_deref(), Some(&[9.2, 9.1][..]));
1971        let error = read(&format!("{HEADER}\n0,0,1013,25,0,70, -,9,2\n")).unwrap_err();
1972        assert!(
1973            error.to_string().contains("line 2: the row has 9 cells"),
1974            "{error}"
1975        );
1976    }
1977
1978    /// Short rows: the 1 Hz cells left out, or padded back empty; `-` never a temperature.
1979    #[test]
1980    fn short_rows_leave_out_the_one_hertz_cells() {
1981        let text =
1982            format!("{HEADER}\n0,0,1000,0,70, -,9.2\n0.05,1,999.9,1, Drogue\n0.1,1,999.9,1, -,,\n");
1983        let log = read(&text).unwrap();
1984        assert_eq!(log.events.len(), 1);
1985        assert_eq!(log.events[0].time_s, 0.05);
1986        let temperature = temperature_as_written(&log);
1987        assert!(temperature[0].is_finite() && temperature[1].is_nan() && temperature[2].is_nan());
1988        assert!(log.notes.iter().any(|n| n.starts_with(
1989            "2 rows, the first on line 3, leave out the 1 Hz `Temperature` and `Voltages` cells: \
1990             they are gaps; 1 of them pad"
1991        )));
1992        // One 1 Hz column alone: four cells.
1993        let log = read("Time,Altitude,Pressure,Velocity,Temperature\n0,0,1000,0,70\n1,1,999.9,1\n")
1994            .unwrap();
1995        assert!(temperature_as_written(&log)[1].is_nan());
1996        // A file without 1 Hz columns has no short rows.
1997        let error = read("Time,Altitude,Pressure,Velocity,Events\n0,0,1000,0\n").unwrap_err();
1998        assert!(
1999            error
2000                .to_string()
2001                .contains("line 2: the row has 4 cells: the header names 5"),
2002            "{error}"
2003        );
2004        // `-` where the temperature stands, in a full row, isn't a number.
2005        let error = read(&format!("{HEADER}\n0,0,1000,0, -, -,9.2\n")).unwrap_err();
2006        assert!(
2007            error
2008                .to_string()
2009                .contains("line 2: \"-\" under \"Temperature\" isn't a number"),
2010            "{error}"
2011        );
2012        // A number where a short row's event stands isn't an event.
2013        let error = read(&format!("{HEADER}\n0,0,1000,0,70,,\n")).unwrap_err();
2014        assert!(
2015            error
2016                .to_string()
2017                .contains("line 2: \"70\" under \"Events\" isn't an event"),
2018            "{error}"
2019        );
2020    }
2021
2022    /// Rows with no time and only an altitude are skipped and counted; other rows with no time
2023    /// are refused.
2024    #[test]
2025    fn rows_with_no_time() {
2026        let text = format!("{HEADER}\n0,0,1000,0,70, -,9.2\n,4,,,,,\n,4\n");
2027        let log = read(&text).unwrap();
2028        assert_eq!(log.time_s.len(), 1);
2029        assert!(log.notes.iter().any(|n| n.starts_with(
2030            "2 rows with no time and nothing but an altitude cell, the first on line 3"
2031        )));
2032        let error = read(&format!("{HEADER}\n,4,1000,,,,\n")).unwrap_err();
2033        assert!(
2034            error.to_string().contains("line 2: the row has no time"),
2035            "{error}"
2036        );
2037    }
2038
2039    /// Each refusal names its line and what is wrong.
2040    #[test]
2041    fn malformed_files_are_refused_where_they_go_wrong() {
2042        let cases = [
2043            (String::new(), "the file is empty"),
2044            (
2045                "Time,Altitude,Velocity\n0,0,0\n".to_owned(),
2046                "isn't an mDACS export's header",
2047            ),
2048            (format!("{HEADER}\n"), "no data rows"),
2049            (format!("{HEADER}\n,4\n"), "no data rows"),
2050            (
2051                format!("{HEADER}\n0,0,1000,0,70, -,9.2\n0,0,1000,0,70, -,9.2\n"),
2052                "line 3: the time 0 s doesn't come after the one above it, 0 s",
2053            ),
2054            (
2055                format!("{HEADER}\n1,0,1000,0,70, -,9.2\n0.5,0,1000,0,70, -,9.2\n"),
2056                "line 3: the time 0.5 s doesn't come after",
2057            ),
2058            (
2059                format!("{HEADER}\nx,0,1000,0,70, -,9.2\n"),
2060                "line 2: \"x\" under \"Time\" isn't a number",
2061            ),
2062            (
2063                format!("{HEADER}\n0,,1000,0,70, -,9.2\n"),
2064                "line 2: \"\" under \"Altitude\" isn't a number",
2065            ),
2066            (
2067                format!("{HEADER}\n0,0,1000,0,70, Main 2,9.2\n"),
2068                "line 2: \"Main 2\" under \"Events\"",
2069            ),
2070            (
2071                format!("{HEADER}\n0,0,1000,0,70, -,9.2,1\n"),
2072                "line 2: the row has 8 cells",
2073            ),
2074            (
2075                format!("{HEADER}\n0,0,1000\n"),
2076                "line 2: the row has 3 cells",
2077            ),
2078        ];
2079        for (text, expected) in cases {
2080            let error = read(&text).unwrap_err().to_string();
2081            assert!(error.contains(expected), "{text:?}: {error}");
2082        }
2083    }
2084
2085    /// An event word the manual doesn't name is kept, with a note; the notes stay few.
2086    #[test]
2087    fn unknown_events_are_kept_and_notes_stay_few() {
2088        let mut text = format!("{HEADER}\n");
2089        for index in 0..30 {
2090            text.push_str(&format!("{index},0,1000,0,70, Apogee,9.2\n"));
2091        }
2092        let log = read(&text).unwrap();
2093        assert_eq!(log.events.len(), 30);
2094        assert_eq!(log.events[0].name, "Apogee");
2095        let about_events = log
2096            .notes
2097            .iter()
2098            .filter(|n| n.contains("\"Apogee\""))
2099            .count();
2100        assert_eq!(about_events, 20);
2101        assert!(
2102            log.notes.iter().any(|n| n.starts_with("and 10 more notes")),
2103            "{:?}",
2104            log.notes
2105        );
2106    }
2107
2108    /// Lines end in CR, LF or both; a byte-order mark and blank lines are dropped; a long line
2109    /// is quoted short.
2110    #[test]
2111    fn line_ends_and_quotes() {
2112        let rows = ["0,0,1000,0,70, -,9.2", "0.05,0.5,999.98,1,70, -,9.2"];
2113        for end in ["\r", "\n", "\r\n"] {
2114            let text = format!("\u{feff}{HEADER}{end}{}{end}{end}{}{end}", rows[0], rows[1]);
2115            let log = read(&text).unwrap();
2116            assert_eq!(log.time_s, [0.0, 0.05], "{end:?}");
2117        }
2118        let error = read(&format!("{HEADER}\n{}\n", "9".repeat(10_000))).unwrap_err();
2119        assert!(error.to_string().chars().count() < 400, "{error}");
2120        let error = read(&"\u{fffd}".repeat(100_000)).unwrap_err();
2121        assert!(error.to_string().chars().count() < 400, "{error}");
2122    }
2123
2124    /// An invented flight sampled at 20 Hz, as (time, height, climb rate): a second on the pad, a
2125    /// boost at 80 m/s² and a coast at 12 m/s² to `top_m`, a fall at 9.8 m/s² to
2126    /// `descent_m_s`, that speed to the ground, and three seconds there.
2127    fn arc(top_m: f64, descent_m_s: f64) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
2128        arc_of(1.0, 80.0, 12.0, top_m, descent_m_s)
2129    }
2130
2131    /// [`arc`] with its pad's length, boost and coast, m/s² and s.
2132    fn arc_of(
2133        pad_s: f64,
2134        boost: f64,
2135        coast: f64,
2136        top_m: f64,
2137        descent_m_s: f64,
2138    ) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
2139        let gravity = 9.8;
2140        let boost_s = (top_m / (boost / 2.0 + boost * boost / (2.0 * coast))).sqrt();
2141        let burnout_m_s = boost * boost_s;
2142        let apogee_s = boost_s + burnout_m_s / coast;
2143        let fall_s = descent_m_s / gravity;
2144        let (mut times, mut heights, mut rates) = (vec![], vec![], vec![]);
2145        let mut landed_s = None;
2146        for row in 0_u32.. {
2147            let t = f64::from(row) * 0.05 - pad_s;
2148            let (height, rate): (f64, f64) = if t < 0.0 {
2149                (0.0, 0.0)
2150            } else if t < boost_s {
2151                (boost * t * t / 2.0, boost * t)
2152            } else if t < apogee_s {
2153                let u = t - boost_s;
2154                (
2155                    boost * boost_s * boost_s / 2.0 + burnout_m_s * u - coast * u * u / 2.0,
2156                    burnout_m_s - coast * u,
2157                )
2158            } else if t < apogee_s + fall_s {
2159                let u = t - apogee_s;
2160                (top_m - gravity * u * u / 2.0, -gravity * u)
2161            } else {
2162                let u = t - apogee_s - fall_s;
2163                (
2164                    top_m - gravity * fall_s * fall_s / 2.0 - descent_m_s * u,
2165                    -descent_m_s,
2166                )
2167            };
2168            let (height, rate) = if height <= 0.0 && t > 0.0 {
2169                (0.0, 0.0)
2170            } else {
2171                (height, rate)
2172            };
2173            if t > 0.0 && height == 0.0 {
2174                landed_s.get_or_insert(t);
2175            }
2176            if landed_s.is_some_and(|landed| t > landed + 3.0) {
2177                break;
2178            }
2179            times.push(t + pad_s);
2180            heights.push(height);
2181            rates.push(rate);
2182        }
2183        (times, heights, rates)
2184    }
2185
2186    /// The velocity's unit is never decided wrong on invented flights 20 m to 1 km up, coming
2187    /// down at 10 to 40 m/s, the pressure written to 0.1 hPa and the altitude worked back from
2188    /// it, the velocity late by up to 3 s or smoothed over up to 3 s, in each of the four units,
2189    /// and each record cut off anywhere from 30% of the way through to its end. Many are left
2190    /// unknown; none is decided in another unit.
2191    #[test]
2192    fn the_velocity_unit_is_never_decided_wrong() {
2193        let atmosphere = Ussa76::standard();
2194        let height_of = |hpa: f64| {
2195            atmosphere
2196                .pressure_altitude_m(hpa * HPA_PA)
2197                .unwrap_or(f64::NAN)
2198        };
2199        let pad_m = height_of((pressure_hpa(0.0) * 10.0).round() / 10.0);
2200        let lags = [
2201            ("late", 0.0),
2202            ("late", 1.0),
2203            ("late", 2.0),
2204            ("late", 3.0),
2205            ("first-order", 0.5),
2206            ("first-order", 1.0),
2207            ("first-order", 2.0),
2208            ("first-order", 3.0),
2209            ("moving average", 1.0),
2210            ("moving average", 2.0),
2211            ("moving average", 3.0),
2212            ("centered", 3.0),
2213            ("centered", 4.0),
2214            ("centered", 5.0),
2215        ];
2216        let (mut decided, mut cases) = (0, 0);
2217        for top_m in [20.0, 30.0, 50.0, 100.0, 200.0, 300.0, 1_000.0] {
2218            for descent_m_s in [10.0, 25.0, 40.0] {
2219                let (time_s, height_m, rate_m_s) = arc(top_m, descent_m_s);
2220                let altitude_m: Vec<f64> = height_m
2221                    .iter()
2222                    .map(|height| {
2223                        let hpa = (pressure_hpa(*height) * 10.0).round() / 10.0;
2224                        ((height_of(hpa) - pad_m) * 100.0).round() / 100.0
2225                    })
2226                    .collect();
2227                for (kind, lag_s) in lags {
2228                    let steps = (lag_s / 0.05_f64).round() as usize;
2229                    let lagged: Vec<f64> = match kind {
2230                        "late" => (0..rate_m_s.len())
2231                            .map(|i| i.checked_sub(steps).map_or(0.0, |j| rate_m_s[j]))
2232                            .collect(),
2233                        "first-order" => {
2234                            let mut smoothed = 0.0;
2235                            rate_m_s
2236                                .iter()
2237                                .map(|rate| {
2238                                    smoothed += (rate - smoothed) * 0.05 / (lag_s + 0.05);
2239                                    smoothed
2240                                })
2241                                .collect()
2242                        }
2243                        "centered" => (0..rate_m_s.len())
2244                            .map(|i| {
2245                                let from = i.saturating_sub(steps / 2);
2246                                let to = (i + steps / 2).min(rate_m_s.len() - 1);
2247                                rate_m_s[from..=to].iter().sum::<f64>() / (to - from + 1) as f64
2248                            })
2249                            .collect(),
2250                        _ => (0..rate_m_s.len())
2251                            .map(|i| {
2252                                let from = (i + 1).saturating_sub(steps);
2253                                rate_m_s[from..=i].iter().sum::<f64>() / steps as f64
2254                            })
2255                            .collect(),
2256                    };
2257                    for (unit, (words, _, m_s)) in SPEEDS.iter().enumerate() {
2258                        let velocity: Vec<f64> = lagged
2259                            .iter()
2260                            .map(|rate| (rate / m_s * 100.0).round() / 100.0)
2261                            .collect();
2262                        for tenths in 3..=10 {
2263                            let rows = time_s.len() * tenths / 10;
2264                            let Some(scale) =
2265                                velocity_scale(&time_s[..rows], &altitude_m[..rows], &velocity)
2266                            else {
2267                                continue;
2268                            };
2269                            cases += 1;
2270                            let agreed = agreed_unit(&scale);
2271                            // A whole record, its velocity up to 1 s late, is decided from 50 m up.
2272                            if kind == "late" && lag_s <= 1.0 && tenths == 10 && top_m >= 50.0 {
2273                                assert_eq!(
2274                                    agreed,
2275                                    Some(unit),
2276                                    "{top_m} m, {descent_m_s} m/s, {lag_s} s late, {words}: \
2277                                     {scale:?}"
2278                                );
2279                            }
2280                            if let Some(index) = agreed {
2281                                decided += 1;
2282                                assert_eq!(
2283                                    index, unit,
2284                                    "{top_m} m, {descent_m_s} m/s, {kind} {lag_s} s, {words}, \
2285                                     {tenths}0% of the record: {scale:?}"
2286                                );
2287                            }
2288                        }
2289                    }
2290                }
2291            }
2292        }
2293        // The rule decides a fair share, not only the whole records.
2294        assert!(decided * 10 > cases, "{decided} of {cases}");
2295    }
2296
2297    /// A smoothing that looks ahead, centered on each sample, on this grid of flights short and
2298    /// long, pads short and long, at each tenth of the record from 30%: the two rules leave no wrong
2299    /// unit, where the measures alone take about 2 in 100 wrongly (#514). Other window shapes still
2300    /// decide a few wrongly (#1100).
2301    #[test]
2302    fn a_velocity_smoothed_around_each_sample_keeps_its_unit_on_this_grid() {
2303        let atmosphere = Ussa76::standard();
2304        let height_of = |hpa: f64| {
2305            atmosphere
2306                .pressure_altitude_m(hpa * HPA_PA)
2307                .unwrap_or(f64::NAN)
2308        };
2309        let pad_m = height_of((pressure_hpa(0.0) * 10.0).round() / 10.0);
2310        // Cases the rules decide, those the measures alone decide and those of them wrong.
2311        let (mut decided, mut alone, mut alone_wrong) = (0_u32, 0_u32, 0_u32);
2312        for pad_s in [0.05, 0.25, 0.5, 1.0, 2.0, 2.3, 2.85, 4.0] {
2313            for (boost, coast) in [(30.0, 8.0), (80.0, 12.0), (200.0, 25.0), (30.0, 25.0)] {
2314                for top_m in [20.0, 50.0, 100.0, 300.0, 1_000.0, 2_000.0] {
2315                    for descent_m_s in [10.0, 25.0, 40.0] {
2316                        let (time_s, height_m, rate_m_s) =
2317                            arc_of(pad_s, boost, coast, top_m, descent_m_s);
2318                        let altitude_m: Vec<f64> = height_m
2319                            .iter()
2320                            .map(|height| {
2321                                let hpa = (pressure_hpa(*height) * 10.0).round() / 10.0;
2322                                ((height_of(hpa) - pad_m) * 100.0).round() / 100.0
2323                            })
2324                            .collect();
2325                        for window_s in [3.0, 3.5, 4.0, 4.5, 5.0] {
2326                            let half = (window_s / 0.05_f64 / 2.0).round() as usize;
2327                            let smoothed: Vec<f64> = (0..rate_m_s.len())
2328                                .map(|i| {
2329                                    let from = i.saturating_sub(half);
2330                                    let to = (i + half).min(rate_m_s.len() - 1);
2331                                    rate_m_s[from..=to].iter().sum::<f64>() / (to - from + 1) as f64
2332                                })
2333                                .collect();
2334                            for (unit, (words, _, m_s)) in SPEEDS.iter().enumerate() {
2335                                let velocity: Vec<f64> = smoothed
2336                                    .iter()
2337                                    .map(|rate| (rate / m_s * 100.0).round() / 100.0)
2338                                    .collect();
2339                                for tenths in 3..=10 {
2340                                    let rows = time_s.len() * tenths / 10;
2341                                    let Some(scale) = velocity_scale(
2342                                        &time_s[..rows],
2343                                        &altitude_m[..rows],
2344                                        &velocity,
2345                                    ) else {
2346                                        continue;
2347                                    };
2348                                    if let Some(index) = measures_agree(&scale) {
2349                                        alone += 1;
2350                                        alone_wrong += u32::from(index != unit);
2351                                    }
2352                                    if let Some(index) = agreed_unit(&scale) {
2353                                        decided += 1;
2354                                        assert_eq!(
2355                                            index, unit,
2356                                            "pad {pad_s} s, boost {boost}, coast {coast}, \
2357                                             {top_m} m, {descent_m_s} m/s, {window_s} s, {words}, \
2358                                             {tenths}0% of the record: {scale:?}"
2359                                        );
2360                                    }
2361                                }
2362                            }
2363                        }
2364                    }
2365                }
2366            }
2367        }
2368        eprintln!("the measures alone: {alone_wrong} wrong of {alone}; the rules: {decided}");
2369        // The module docs' "about 2 in 100".
2370        assert!(
2371            alone_wrong * 100 > alone && alone_wrong * 33 < alone,
2372            "{alone_wrong} of {alone}"
2373        );
2374        // Not by deciding nothing: the module docs' "about a quarter as many".
2375        assert!(
2376            decided * 6 > alone && decided * 3 < alone,
2377            "{decided} of {alone}"
2378        );
2379    }
2380
2381    /// The two measures of the velocity's unit, on a flight whose velocity runs 1.5 s behind
2382    /// its altitude: the delay found, and neither measure moved by it.
2383    #[test]
2384    fn the_velocity_scale_takes_out_a_delay() {
2385        let time_s: Vec<f64> = (0..800).map(|i| f64::from(i) * 0.05).collect();
2386        // Up at 50 m/s for 5 s, down at 12.5 m/s to the pad, then at rest.
2387        let rate = |t: f64| match t {
2388            t if t < 1.0 => 0.0,
2389            t if t < 6.0 => 50.0,
2390            t if t < 26.0 => -12.5,
2391            _ => 0.0,
2392        };
2393        let mut altitude_m = vec![0.0];
2394        for pair in time_s.windows(2) {
2395            let last = altitude_m.last().copied().unwrap_or_default();
2396            altitude_m.push(last + 0.5 * (rate(pair[0]) + rate(pair[1])) * (pair[1] - pair[0]));
2397        }
2398        let velocity: Vec<f64> = time_s.iter().map(|t| rate(t - 1.5) * 2.0).collect();
2399        let scale = velocity_scale(&time_s, &altitude_m, &velocity).unwrap();
2400        assert!((scale.delay_s - 1.5).abs() < 1e-9, "{scale:?}");
2401        assert!((scale.by_area / 2.0 - 1.0).abs() < 1e-3, "{scale:?}");
2402        assert!((scale.by_fit / 2.0 - 1.0).abs() < 1e-3, "{scale:?}");
2403        assert!(
2404            scale.end_height.abs() < 1e-9 && scale.end_error < 1e-9,
2405            "{scale:?}"
2406        );
2407        assert!(velocity_scale(&[0.0, 1.0], &[5.0, 5.0], &[1.0, 1.0]).is_none());
2408    }
2409
2410    /// The time read in seconds from a 20 Hz step, assumed at another step or with one row, and
2411    /// with no note when the header states `[s]`.
2412    #[test]
2413    fn the_time_is_read_in_seconds_from_the_step_or_assumed() {
2414        let rows = |step: f64, count: usize| -> String {
2415            (0..count)
2416                .map(|i| format!("{:.2},0,1000,0\n", i as f64 * step))
2417                .collect()
2418        };
2419        let header = "Time,Altitude,Pressure,Velocity\n";
2420        let log = read(&format!("{header}{}", rows(0.05, 5))).unwrap();
2421        let from_step = notes_starting(&log, "`Time` read in seconds, from the step. ");
2422        assert!(
2423            from_step[0].contains("step between rows, 0.05"),
2424            "{from_step:?}"
2425        );
2426        let log = read(&format!("{header}{}", rows(0.5, 5))).unwrap();
2427        let assumed = notes_starting(&log, "`Time` read in seconds, assumed. ");
2428        assert!(
2429            assumed[0].contains("0.5 as written, isn't within 5%"),
2430            "{assumed:?}"
2431        );
2432        let log = read(&format!("{header}{}", rows(0.05, 1))).unwrap();
2433        assert_eq!(
2434            notes_starting(&log, "`Time` read in seconds, assumed: a single row").len(),
2435            1
2436        );
2437        let log = read(&format!(
2438            "Time [s],Altitude,Pressure,Velocity\n{}",
2439            rows(0.05, 5)
2440        ))
2441        .unwrap();
2442        assert!(
2443            log.notes.iter().all(|n| !n.contains("`Time")),
2444            "{:?}",
2445            log.notes
2446        );
2447    }
2448
2449    /// A pressure whose first row isn't a launch site's, in hectopascals, is kept as written:
2450    /// kilopascals (about 100) and inches of mercury (about 30) lie within what the RRC3 measures,
2451    /// so only the pad tells them apart; the altitude is then assumed in feet.
2452    #[test]
2453    fn a_pressure_off_the_pad_range_is_kept_as_written() {
2454        for (pad, next) in [
2455            (101.3, 101.2),
2456            (29.92, 29.9),
2457            (499.0, 498.9),
2458            (1_101.0, 1_100.9),
2459        ] {
2460            let text = format!("{HEADER}\n0,0,{pad},0,70, -,9.2\n0.05,1,{next},1,70, -,9.2\n");
2461            let log = read(&text).unwrap();
2462            assert_eq!(log.channels[1].quantity, Quantity::Unrecognized, "{pad}");
2463            assert_eq!(log.channels[1].values, [pad, next]);
2464            let kept = notes_starting(&log, "`Pressure` kept as written, its unit unknown: ");
2465            assert!(
2466                kept[0].contains(&format!(
2467                    "the first row's, {pad}, lies outside the 500 to 1100"
2468                )),
2469                "{kept:?}"
2470            );
2471            let assumed = notes_starting(&log, "`Altitude` read in feet, assumed: ");
2472            assert!(assumed[0].contains("unit is unknown"), "{assumed:?}");
2473        }
2474        // At either edge of the pad's range, hectopascals.
2475        for (pad, next) in [(500.0, 499.9), (1_100.0, 1_099.9)] {
2476            let text = format!("{HEADER}\n0,0,{pad},0,70, -,9.2\n0.05,1,{next},1,70, -,9.2\n");
2477            let log = read(&text).unwrap();
2478            assert_eq!(log.channels[1].quantity, Quantity::Pressure, "{pad}");
2479        }
2480    }
2481
2482    proptest::proptest! {
2483        /// Any text is read or refused, never a panic; what is read has increasing times, every
2484        /// channel on them.
2485        #[test]
2486        fn any_text_is_read_or_refused(rows in proptest::collection::vec("[-0-9.,; DrogueMainx]{0,32}", 0..12)) {
2487            let text = format!("{HEADER}\n{}", rows.join("\n"));
2488            if let Ok(log) = read(&text) {
2489                proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
2490                proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
2491                for channel in &log.channels {
2492                    proptest::prop_assert_eq!(&channel.time_s, &log.time_s);
2493                    proptest::prop_assert_eq!(channel.values.len(), log.time_s.len());
2494                }
2495            }
2496        }
2497    }
2498}