1use std::collections::HashMap;
179
180use crate::error::LogError;
181use crate::log::{Channel, FlightLog, LogFormat, Quantity, Stated, too_sparse};
182use crate::perfectflite::FOOT_M;
183use crate::table::{Notes, finite, number, numbered_lines, short};
184
185const FORMAT: &str = "Featherweight GPS CSV";
187
188pub const MAX_TRACKERS: usize = 64;
191
192pub const MAX_CHANNELS: usize = 4_096;
195
196const MIN_STEP_S: f64 = 0.5;
200
201const MAX_STEP_S: f64 = 2.5;
204
205const MIN_SPEED: f64 = 20.0;
208
209const MIN_PAIRS: usize = 10;
211
212const AGREES: (f64, f64) = (0.7, 1.4);
218
219const MAX_CELL_V: f64 = 5.0;
221
222const EARTH_RADIUS_M: f64 = 6_371_008.8;
226
227const NS_PER_S: i64 = 1_000_000_000;
229const NS_PER_DAY: i64 = 86_400 * NS_PER_S;
230
231const YEARS: std::ops::RangeInclusive<i64> = 1970..=2199;
234
235pub(crate) fn recognizes(text: &str) -> bool {
237 numbered_lines(text)
238 .map(|(_, line)| line)
239 .find(|line| !line.trim().is_empty())
240 .and_then(layout)
241 .is_some()
242}
243
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246enum Layout {
247 Tracker,
249 GroundStation,
251}
252
253fn layout(header: &str) -> Option<Layout> {
258 let mut names = header.split(',').map(str::trim);
259 let layout = match (names.next()?, names.next()?) {
260 ("UTCTIME", "UNIXTIME") => Layout::Tracker,
261 ("TRACKER", "DATE") if names.next()? == "TIME" => Layout::GroundStation,
262 _ => return None,
263 };
264 let (mut lat, mut lon, mut tracker_lat, mut tracker_lon) = (false, false, false, false);
265 for name in names {
266 match name {
267 "LAT" => lat = true,
268 "LON" => lon = true,
269 "TRACKER Lat" => tracker_lat = true,
270 "TRACKER Lon" => tracker_lon = true,
271 _ => {}
272 }
273 }
274 let position = (lat && lon) || (layout == Layout::GroundStation && tracker_lat && tracker_lon);
275 position.then_some(layout)
276}
277
278#[derive(Debug, Clone, Copy, PartialEq)]
280enum Role {
281 Clock,
283 Date,
285 Time,
287 Tracker,
289 Label,
291 Value(Kind),
293}
294
295#[derive(Debug, Clone, Copy, PartialEq)]
297enum Kind {
298 Height { above_sea_level: bool },
300 VerticalSpeed,
302 HorizontalSpeed,
304 Heading,
306 Battery,
308 UnixTime,
310 Stated(Quantity, f64),
312 Unknown,
314}
315
316fn role(name: &str) -> Role {
318 use Quantity as Q;
319 let value = |kind| Role::Value(kind);
320 let stated = |quantity, factor| Role::Value(Kind::Stated(quantity, factor));
321 match name {
322 "UTCTIME" => Role::Clock,
323 "DATE" => Role::Date,
324 "TIME" => Role::Time,
325 "TRACKER" => Role::Tracker,
326 "Found rocket ID" => Role::Label,
327 "UNIXTIME" => value(Kind::UnixTime),
328 "ALT" | "TRACKER Alt asl" | "GS Alt asl" | "Found rocket altitude" => value(Kind::Height {
329 above_sea_level: true,
330 }),
331 "Altitude AGL" | "GS_ASL_offset" => value(Kind::Height {
332 above_sea_level: false,
333 }),
334 "LAT" | "TRACKER Lat" | "GS Lat" | "Found rocket lat" => stated(Q::Latitude, 1.0),
335 "LON" | "TRACKER Lon" | "GS Lon" | "Found rocket lon" => stated(Q::Longitude, 1.0),
336 "HORZV" => value(Kind::HorizontalSpeed),
337 "VERTV" => value(Kind::VerticalSpeed),
338 "HEAD" => value(Kind::Heading),
339 "BATT" => value(Kind::Battery),
340 "GS_batt_v" | "Found rocket batt_v" => stated(Q::Voltage, 1.0),
341 "Distance (feet)" | "Alt AGL (ft)" | "Horizontal range (ft)" | "Total range (ft)" => {
342 stated(Q::Distance, FOOT_M)
343 }
344 "LoRa Max Range (kft)" => stated(Q::Distance, 1_000.0 * FOOT_M),
345 "#SATS" | "#TOT" | "FIX" | "FLAGS" | ">40" | ">32" | ">24" | "RSSI" | "RSSI Down"
346 | "RSSI Up" | "Found RSSI" | "Found rocket fix" | "Down Sent" | "Down Rcvd"
347 | "Found Sent" | "Up Sent" | "Up Rccvd" | "LoRa Success Rate" | "Launch detection"
348 | "Apogee detection" | "Landing detection" => stated(Q::Number, 1.0),
349 _ => value(Kind::Unknown),
350 }
351}
352
353struct Column {
355 name: String,
356 role: Role,
357 gaps: usize,
359 gap_example: Option<String>,
360 out_of_range: usize,
362}
363
364struct Set {
367 name: String,
368 times_ns: Vec<i64>,
369 lines: Vec<usize>,
371 values: Vec<Vec<f64>>,
372}
373
374#[derive(Debug, Clone, Copy)]
376struct Position {
377 lat: usize,
378 lon: usize,
379 alt: Option<usize>,
380 zeros: usize,
382}
383
384pub fn read(text: &str) -> Result<FlightLog, LogError> {
394 let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
395 let Some((header_line, header)) = lines.next() else {
396 return Err(LogError::NotThisFormat {
397 format: FORMAT,
398 message: "the file is empty".to_owned(),
399 });
400 };
401 let Some(layout) = layout(header) else {
402 return Err(LogError::NotThisFormat {
403 format: FORMAT,
404 message: format!(
405 "its first line, {:?}, isn't a Featherweight GPS header, which opens \
406 `UTCTIME,UNIXTIME` or `TRACKER,DATE,TIME`",
407 short(header)
408 ),
409 });
410 };
411 let mut notes = Notes::default();
412 let mut columns = Vec::new();
413 for (index, name) in header.split(',').map(str::trim).enumerate() {
414 if name.is_empty() {
415 return Err(syntax(
416 header_line,
417 format!("the header's column {} has no name", index + 1),
418 ));
419 }
420 let role = role(name);
421 if role == Role::Value(Kind::Unknown) {
422 notes.push(format!(
423 "the column {:?} isn't one this reader knows, and was kept as written",
424 short(name)
425 ));
426 }
427 columns.push(Column {
428 name: name.to_owned(),
429 role,
430 gaps: 0,
431 gap_example: None,
432 out_of_range: 0,
433 });
434 }
435 let find = |role: Role| columns.iter().position(|c| c.role == role);
436 let clock = match layout {
438 Layout::Tracker => Clock::Utc(find(Role::Clock).unwrap_or(0)),
439 Layout::GroundStation => Clock::DateTime {
440 date: find(Role::Date).unwrap_or(1),
441 time: find(Role::Time).unwrap_or(2),
442 tracker: find(Role::Tracker).unwrap_or(0),
443 },
444 };
445 let mut positions = positions(&columns);
446 let channels_per_set = columns
447 .iter()
448 .filter(|c| matches!(c.role, Role::Clock | Role::Time | Role::Value(_)))
449 .count();
450
451 let mut sets: Vec<Set> = Vec::new();
452 let mut set_of: HashMap<String, usize> = HashMap::new();
453 let mut left_out = LeftOut::default();
454 let (mut rows, mut cells_written) = (0usize, 0usize);
455 let (mut short_rows, mut first_short_row) = (0usize, 0usize);
456 let mut first_row: Option<(String, i64)> = None;
457 for (line_number, line) in lines {
458 let cells: Vec<&str> = line.split(',').map(str::trim).collect();
459 if cells.len() > columns.len() {
460 return Err(syntax(
461 line_number,
462 format!(
463 "the row has {} cells, more than the header's {}",
464 cells.len(),
465 columns.len()
466 ),
467 ));
468 }
469 rows += 1;
470 cells_written += cells.len();
471 if too_sparse(columns.len(), rows, cells_written) {
474 return Err(syntax(
475 line_number,
476 format!(
477 "the header names {} columns, and the {rows} rows down to this one hold only \
478 {cells_written} cells",
479 columns.len()
480 ),
481 ));
482 }
483 if cells.len() < columns.len() {
484 if short_rows == 0 {
485 first_short_row = line_number;
486 }
487 short_rows += 1;
488 }
489 let instant = clock.read(&cells, &columns, line_number)?;
490 if first_row.is_none() {
491 first_row = Some((clock.as_written(&cells), instant));
492 }
493 let tracker = clock.tracker(&cells);
494 let index = match set_of.get(tracker) {
495 Some(&index) => index,
496 None if sets.is_empty()
497 || (sets.len() < MAX_TRACKERS
498 && (sets.len() + 1).saturating_mul(channels_per_set) <= MAX_CHANNELS) =>
499 {
500 set_of.insert(tracker.to_owned(), sets.len());
501 sets.push(Set {
502 name: tracker.to_owned(),
503 times_ns: Vec::new(),
504 lines: Vec::new(),
505 values: vec![Vec::new(); columns.len()],
506 });
507 sets.len() - 1
508 }
509 None => {
510 left_out.row(tracker);
511 continue;
512 }
513 };
514 let set = &mut sets[index];
515 set.times_ns.push(instant);
516 set.lines.push(line_number);
517 read_cells(set, &mut columns, &cells, instant);
518 for position in &mut positions {
519 no_fix(set, position);
520 }
521 }
522 let Some(first_row) = first_row else {
523 return Err(LogError::NoData { format: FORMAT });
524 };
525 let mut file_notes = Vec::new();
526 if short_rows > 0 {
527 file_notes.push(format!(
528 "{short_rows} rows, the first on line {first_short_row}, have fewer cells than the \
529 header's {}: the cells they leave out are gaps",
530 columns.len()
531 ));
532 }
533 if let Some(note) = left_out.note() {
534 file_notes.push(note);
535 }
536 build(
537 layout, &columns, sets, &positions, &first_row, notes, file_notes,
538 )
539}
540
541#[derive(Debug, Clone, Copy)]
543enum Clock {
544 Utc(usize),
546 DateTime {
548 date: usize,
549 time: usize,
550 tracker: usize,
551 },
552}
553
554impl Clock {
555 fn read(self, cells: &[&str], columns: &[Column], line: usize) -> Result<i64, LogError> {
558 let cell = |index: usize| {
559 cells.get(index).copied().ok_or_else(|| {
560 syntax(
561 line,
562 format!(
563 "the row ends after {} cells, before its {:?}",
564 cells.len(),
565 short(&columns[index].name)
566 ),
567 )
568 })
569 };
570 let refuse = |what: &str, cell: &str, index: usize| {
571 syntax(
572 line,
573 format!(
574 "the {what} {:?} in cell {} isn't one",
575 short(cell),
576 index + 1
577 ),
578 )
579 };
580 match self {
581 Self::Utc(index) => {
582 let text = cell(index)?;
583 utc_time(text).ok_or_else(|| refuse("time", text, index))
584 }
585 Self::DateTime { date, time, .. } => {
586 let (date_text, time_text) = (cell(date)?, cell(time)?);
587 let day = civil_date(date_text).ok_or_else(|| refuse("date", date_text, date))?;
588 let of_day =
589 time_of_day_ns(time_text).ok_or_else(|| refuse("time", time_text, time))?;
590 Ok(day * NS_PER_DAY + of_day)
591 }
592 }
593 }
594
595 fn tracker<'a>(self, cells: &[&'a str]) -> &'a str {
597 match self {
598 Self::Utc(_) => "",
599 Self::DateTime { tracker, .. } => cells.get(tracker).copied().unwrap_or_default(),
600 }
601 }
602
603 fn as_written(self, cells: &[&str]) -> String {
605 match self {
606 Self::Utc(index) => short(cells.get(index).copied().unwrap_or_default()),
607 Self::DateTime { date, time, .. } => short(&format!(
608 "{} {}",
609 cells.get(date).copied().unwrap_or_default(),
610 cells.get(time).copied().unwrap_or_default()
611 )),
612 }
613 }
614}
615
616#[derive(Default)]
618struct LeftOut {
619 names: Vec<String>,
620 rows: usize,
621}
622
623impl LeftOut {
624 fn row(&mut self, tracker: &str) {
625 self.rows += 1;
626 if self.names.len() < MAX_TRACKERS && !self.names.iter().any(|name| name == tracker) {
628 self.names.push(tracker.to_owned());
629 }
630 }
631
632 fn note(&self) -> Option<String> {
633 (self.rows > 0).then(|| {
634 let trackers = if self.names.len() < MAX_TRACKERS {
635 format!("{} more trackers", self.names.len())
636 } else {
637 format!("{MAX_TRACKERS} or more further trackers")
638 };
639 format!(
640 "{} rows of {trackers} were left out, past the first {MAX_TRACKERS} trackers or \
641 {MAX_CHANNELS} channels. This keeps a file of many tracker names from making the \
642 reader hold a set of channels for each",
643 self.rows
644 )
645 })
646 }
647}
648
649fn read_cells(set: &mut Set, columns: &mut [Column], cells: &[&str], instant: i64) {
652 for (index, column) in columns.iter_mut().enumerate() {
653 let value = match column.role {
654 Role::Date | Role::Tracker | Role::Label => continue,
655 Role::Clock => seconds_of_day(instant),
656 Role::Time => cells
657 .get(index)
658 .and_then(|cell| time_of_day_ns(cell))
659 .map_or(f64::NAN, |ns| ns as f64 / NS_PER_S as f64),
660 Role::Value(kind) => match cells.get(index) {
661 None => f64::NAN,
662 Some(cell) => match value(cell) {
663 Some(value) if value.abs() > most_degrees(kind) => {
664 column.out_of_range += 1;
665 f64::NAN
666 }
667 Some(value) => value,
668 None => {
669 column.gaps += 1;
670 if column.gap_example.is_none() {
671 column.gap_example = Some(short(cell));
672 }
673 f64::NAN
674 }
675 },
676 },
677 };
678 set.values[index].push(value);
679 }
680}
681
682fn most_degrees(kind: Kind) -> f64 {
685 match kind {
686 Kind::Stated(Quantity::Latitude, _) => 90.0,
687 Kind::Stated(Quantity::Longitude, _) => 180.0,
688 _ => f64::INFINITY,
689 }
690}
691
692fn value(cell: &str) -> Option<f64> {
695 if let Some(value) = number(cell, false) {
696 return Some(value);
697 }
698 match cell {
699 "TRUE" => return Some(1.0),
700 "FALSE" => return Some(0.0),
701 _ => {}
702 }
703 if let Some(digits) = cell.strip_prefix("0x").or_else(|| cell.strip_prefix("0X")) {
704 if digits.is_empty() || digits.len() > 13 || !digits.bytes().all(|b| b.is_ascii_hexdigit())
705 {
706 return None;
707 }
708 return u64::from_str_radix(digits, 16).ok().map(|bits| bits as f64);
710 }
711 cell.strip_suffix('%')
712 .filter(|rest| !rest.ends_with(char::is_whitespace))
713 .and_then(|rest| number(rest, false))
714}
715
716fn positions(columns: &[Column]) -> Vec<Position> {
719 let place = |name: &str| columns.iter().position(|c| c.name == name);
720 [
721 ("LAT", "LON", "ALT"),
722 ("TRACKER Lat", "TRACKER Lon", "TRACKER Alt asl"),
723 ("GS Lat", "GS Lon", "GS Alt asl"),
724 (
725 "Found rocket lat",
726 "Found rocket lon",
727 "Found rocket altitude",
728 ),
729 ]
730 .into_iter()
731 .filter_map(|(lat, lon, alt)| {
732 Some(Position {
733 lat: place(lat)?,
734 lon: place(lon)?,
735 alt: place(alt),
736 zeros: 0,
737 })
738 })
739 .collect()
740}
741
742fn no_fix(set: &mut Set, position: &mut Position) {
744 let last = |column: usize| set.values[column].last().copied();
745 if last(position.lat) == Some(0.0) && last(position.lon) == Some(0.0) {
746 position.zeros += 1;
747 for column in [Some(position.lat), Some(position.lon), position.alt]
748 .into_iter()
749 .flatten()
750 {
751 if let Some(value) = set.values[column].last_mut() {
752 *value = f64::NAN;
753 }
754 }
755 }
756}
757
758fn utc_time(cell: &str) -> Option<i64> {
761 let mut parts = cell.split_whitespace();
762 let (month, day, year, time, zone) = (
763 parts.next()?,
764 parts.next()?,
765 parts.next()?,
766 parts.next()?,
767 parts.next()?,
768 );
769 if parts.next().is_some() || zone != "UTC" {
770 return None;
771 }
772 const MONTHS: [&str; 12] = [
773 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
774 ];
775 let month = MONTHS
776 .iter()
777 .position(|name| name.eq_ignore_ascii_case(month))?;
778 let day = days(year, u32::try_from(month).ok()? + 1, day)?;
779 Some(day * NS_PER_DAY + time_of_day_ns(time)?)
780}
781
782fn civil_date(cell: &str) -> Option<i64> {
784 let mut parts = cell.split('-');
785 let (year, month, day) = (parts.next()?, parts.next()?, parts.next()?);
786 if parts.next().is_some() || year.len() != 4 || !digits(month, 1..=2) {
787 return None;
788 }
789 days(year, month.parse().ok()?, day)
790}
791
792fn digits(text: &str, count: std::ops::RangeInclusive<usize>) -> bool {
794 count.contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit())
795}
796
797fn days(year: &str, month: u32, day: &str) -> Option<i64> {
800 if !digits(year, 4..=4) || !digits(day, 1..=2) {
801 return None;
802 }
803 let year: i64 = year.parse().ok()?;
804 let day: u32 = day.parse().ok()?;
805 let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
806 let length = match month {
807 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
808 4 | 6 | 9 | 11 => 30,
809 2 if leap => 29,
810 2 => 28,
811 _ => return None,
812 };
813 (YEARS.contains(&year) && (1..=length).contains(&day))
814 .then(|| days_from_civil(year, month, day))
815}
816
817fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
821 let year = if month <= 2 { year - 1 } else { year };
822 let era = year.div_euclid(400);
823 let year_of_era = year - era * 400;
824 let day_of_year = (153 * i64::from((month + 9) % 12) + 2) / 5 + i64::from(day) - 1;
825 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
826 era * 146_097 + day_of_era - 719_468
827}
828
829fn time_of_day_ns(cell: &str) -> Option<i64> {
832 let mut parts = cell.split(':');
833 let (hours, minutes, seconds) = (parts.next()?, parts.next()?, parts.next()?);
834 if parts.next().is_some() {
835 return None;
836 }
837 let (whole, fraction) = seconds.split_once('.').unwrap_or((seconds, ""));
838 if !digits(hours, 1..=2)
839 || !digits(minutes, 2..=2)
840 || !digits(whole, 2..=2)
841 || !(fraction.is_empty() || digits(fraction, 1..=9))
842 || (seconds.contains('.') && fraction.is_empty())
843 {
844 return None;
845 }
846 let (hours, minutes, whole): (i64, i64, i64) = (
847 hours.parse().ok()?,
848 minutes.parse().ok()?,
849 whole.parse().ok()?,
850 );
851 if hours >= 24 || minutes >= 60 || whole > 60 {
852 return None;
853 }
854 let mut nanos: i64 = 0;
855 for (place, digit) in fraction.bytes().enumerate() {
856 nanos += i64::from(digit - b'0') * 10_i64.pow(8 - u32::try_from(place).ok()?);
858 }
859 Some(((hours * 60 + minutes) * 60 + whole) * NS_PER_S + nanos)
860}
861
862fn seconds_of_day(instant: i64) -> f64 {
864 instant.rem_euclid(NS_PER_DAY) as f64 / NS_PER_S as f64
865}
866
867fn seconds_between(from: i64, to: i64) -> f64 {
869 (to - from) as f64 / NS_PER_S as f64
871}
872
873fn build(
875 layout: Layout,
876 columns: &[Column],
877 sets: Vec<Set>,
878 positions: &[Position],
879 first_row: &(String, i64),
880 notes: Notes,
881 file_notes: Vec<String>,
882) -> Result<FlightLog, LogError> {
883 let decisions = Decisions::from_file(columns, &sets);
884 let mut log = FlightLog {
885 format: LogFormat::FeatherweightGpsCsv,
886 logger: match layout {
887 Layout::Tracker => "Featherweight GPS tracker",
888 Layout::GroundStation => "Featherweight GPS ground station",
889 }
890 .to_owned(),
891 serial_number: None,
892 firmware: None,
893 flight_number: None,
894 stated: Stated::default(),
895 time_s: Vec::new(),
896 altitude_m: Vec::new(),
897 vertical_speed_m_s: None,
898 temperature_k: None,
899 battery_v: None,
900 channels: Vec::new(),
901 events: Vec::new(),
902 notes: decisions.notes.clone(),
903 };
904 log.notes.push(
905 "the log has no barometer, so the record's altitude track is empty: a GPS tracker's file \
906 holds positions only, and every column is a channel"
907 .to_owned(),
908 );
909 log.notes
910 .push(clock_note(layout, &sets, positions, first_row));
911 if let Some(note) = steps_back_note(&sets) {
912 log.notes.push(note);
913 }
914 if layout == Layout::GroundStation {
915 log.notes.push(trackers_note(&sets));
916 }
917 for position in positions.iter().filter(|p| p.zeros > 0) {
918 let names: Vec<String> = [Some(position.lat), Some(position.lon), position.alt]
919 .into_iter()
920 .flatten()
921 .map(|index| format!("`{}`", columns[index].name))
922 .collect();
923 log.notes.push(format!(
924 "{} rows have `{}` and `{}` both 0, as a receiver writes before it has a fix: their \
925 {} are read as gaps",
926 position.zeros,
927 columns[position.lat].name,
928 columns[position.lon].name,
929 list(&names)
930 ));
931 }
932 log.notes.extend(file_notes);
933 let mut notes = notes;
934 for column in columns.iter().filter(|c| c.gaps > 0) {
935 notes.push(format!(
936 "the column {:?} holds {} cells that are empty or not a number, such as {:?}: they \
937 are gaps",
938 short(&column.name),
939 column.gaps,
940 column.gap_example.as_deref().unwrap_or_default()
941 ));
942 }
943 for column in columns.iter().filter(|c| c.out_of_range > 0) {
944 let (what, most) = match column.role {
945 Role::Value(Kind::Stated(Quantity::Latitude, _)) => ("latitudes", "±90°"),
946 _ => ("longitudes", "±180°"),
947 };
948 notes.push(format!(
949 "the column {:?} holds {} {what} beyond {most}: they are gaps",
950 short(&column.name),
951 column.out_of_range
952 ));
953 }
954 log.notes.extend(notes.into_vec());
955
956 let zero = first_row.1;
957 let qualify = sets.len() > 1;
958 for set in sets {
959 let time_s: Vec<f64> = set
960 .times_ns
961 .iter()
962 .map(|&instant| seconds_between(zero, instant))
963 .collect();
964 for (column, values) in columns.iter().zip(set.values) {
965 let Some(quantity) = decisions.quantity(column.role) else {
966 continue;
967 };
968 let factor = decisions.factor(column.role);
969 let name = if qualify {
970 format!("{} [{}]", short(&column.name), short(&set.name))
971 } else {
972 column.name.clone()
973 };
974 let mut si = Vec::with_capacity(values.len());
977 for (line, value) in set.lines.iter().zip(values) {
978 si.push(finite(value * factor, FORMAT, *line, &column.name)?);
979 }
980 log.channels.push(Channel {
981 column: name,
982 quantity,
983 time_s: time_s.clone(),
984 values: si,
985 });
986 }
987 }
988 Ok(log)
989}
990
991fn clock_note(
993 layout: Layout,
994 sets: &[Set],
995 positions: &[Position],
996 first_row: &(String, i64),
997) -> String {
998 match layout {
999 Layout::Tracker => format!(
1000 "the log's clock is `UTCTIME`, read as UTC, and its zero is the first row's, {:?}",
1001 first_row.0
1002 ),
1003 Layout::GroundStation => {
1004 let solar = first_fix(sets, positions).map_or_else(
1005 || "The file has no fix to compare its `TIME` with the sun's".to_owned(),
1006 |(instant, longitude)| {
1007 format!(
1008 "At the first fix, `TIME` is {}. Read as UTC, that would be {:.1} h of \
1009 local mean solar time at the fix's longitude",
1010 clock_text(instant),
1011 solar_hours(instant, longitude)
1012 )
1013 },
1014 );
1015 format!(
1016 "`DATE` and `TIME` kept as written, in a time zone the file doesn't state. They \
1017 are the log's clock, and its zero is the first row's, {:?}. {solar}",
1018 first_row.0
1019 )
1020 }
1021 }
1022}
1023
1024fn first_fix(sets: &[Set], positions: &[Position]) -> Option<(i64, f64)> {
1026 let position = positions.first()?;
1027 sets.iter()
1028 .filter_map(|set| {
1029 (0..set.times_ns.len())
1030 .find(|&row| {
1031 set.values[position.lat][row].is_finite()
1032 && set.values[position.lon][row].is_finite()
1033 })
1034 .map(|row| (set.times_ns[row], set.values[position.lon][row]))
1035 })
1036 .min_by_key(|(instant, _)| *instant)
1037}
1038
1039fn clock_text(instant: i64) -> String {
1041 let millis = instant.rem_euclid(NS_PER_DAY) / 1_000_000;
1042 format!(
1043 "{:02}:{:02}:{:02}.{:03}",
1044 millis / 3_600_000,
1045 millis / 60_000 % 60,
1046 millis / 1_000 % 60,
1047 millis % 1_000
1048 )
1049}
1050
1051fn solar_hours(instant: i64, longitude_deg: f64) -> f64 {
1054 (seconds_of_day(instant) / 3_600.0 + longitude_deg / 15.0).rem_euclid(24.0)
1055}
1056
1057fn steps_back_note(sets: &[Set]) -> Option<String> {
1059 let (mut backs, mut largest_ns, mut repeats) = (0usize, 0i64, 0usize);
1060 for set in sets {
1061 for pair in set.times_ns.windows(2) {
1062 if pair[1] < pair[0] {
1063 backs += 1;
1064 largest_ns = largest_ns.max(pair[0] - pair[1]);
1065 }
1066 }
1067 let mut sorted = set.times_ns.clone();
1068 sorted.sort_unstable();
1069 repeats += sorted.windows(2).filter(|pair| pair[0] == pair[1]).count();
1070 }
1071 let kept = "every row is kept, in the file's order";
1072 if backs > 0 {
1073 Some(format!(
1074 "times go back {backs} times from one row to the next, by up to {:.3} s, and {repeats} \
1075 rows repeat a time already written: {kept}",
1076 largest_ns as f64 / NS_PER_S as f64
1077 ))
1078 } else {
1079 (repeats > 0).then(|| format!("{repeats} rows repeat a time already written: {kept}"))
1080 }
1081}
1082
1083fn trackers_note(sets: &[Set]) -> String {
1085 match sets {
1086 [one] => format!(
1087 "the file holds one tracker's rows, {:?}, so its channels keep the header's names",
1088 short(&one.name)
1089 ),
1090 _ => {
1091 let names: Vec<String> = sets
1092 .iter()
1093 .map(|set| format!("{:?} ({} rows)", short(&set.name), set.times_ns.len()))
1094 .collect();
1095 format!(
1096 "the file holds {} trackers' rows, each its own set of channels named with the \
1097 tracker in brackets, in the order they first appear: {}",
1098 sets.len(),
1099 list(&names)
1100 )
1101 }
1102 }
1103}
1104
1105const MAX_LISTED: usize = 6;
1107
1108fn list(names: &[String]) -> String {
1111 if names.len() > MAX_LISTED {
1112 let shown = MAX_LISTED - 1;
1113 return format!(
1114 "{} and {} more",
1115 names[..shown].join(", "),
1116 names.len() - shown
1117 );
1118 }
1119 match names {
1120 [] => String::new(),
1121 [only] => only.clone(),
1122 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
1123 }
1124}
1125
1126#[derive(Debug, Clone, Copy, PartialEq)]
1128enum Check {
1129 Agrees(f64, usize),
1131 Disagrees(f64, usize),
1133 TooFew(usize),
1135}
1136
1137impl Check {
1138 fn from_ratios(mut ratios: Vec<f64>) -> Self {
1139 if ratios.len() < MIN_PAIRS {
1140 return Self::TooFew(ratios.len());
1141 }
1142 ratios.sort_by(f64::total_cmp);
1143 let median = ratios[ratios.len() / 2];
1144 if (AGREES.0..=AGREES.1).contains(&median) {
1145 Self::Agrees(median, ratios.len())
1146 } else {
1147 Self::Disagrees(median, ratios.len())
1148 }
1149 }
1150
1151 fn words(self, change: &str, speed: &str) -> String {
1154 match self {
1155 Self::Agrees(median, pairs) | Self::Disagrees(median, pairs) => format!(
1156 "{change} is a median of {median:.3} times `{speed}` over {pairs} pairs of rows"
1157 ),
1158 Self::TooFew(pairs) => format!(
1159 "the file has too few pairs of moving rows to check `{speed}` over, {pairs} of the \
1160 {MIN_PAIRS} needed"
1161 ),
1162 }
1163 }
1164}
1165
1166#[derive(Debug, Clone, Copy)]
1168enum Track {
1169 Height(usize),
1171 Position(usize, usize),
1173}
1174
1175impl Track {
1176 fn at(self, set: &Set, row: usize) -> Option<(f64, f64)> {
1178 let (a, b) = match self {
1179 Self::Height(column) => (set.values[column][row], 0.0),
1180 Self::Position(lat, lon) => (set.values[lat][row], set.values[lon][row]),
1181 };
1182 (a.is_finite() && b.is_finite()).then_some((a, b))
1183 }
1184
1185 fn change(self, from: (f64, f64), to: (f64, f64)) -> f64 {
1187 match self {
1188 Self::Height(_) => to.0 - from.0,
1189 Self::Position(..) => great_circle_m(from, to) / FOOT_M,
1190 }
1191 }
1192}
1193
1194fn great_circle_m(from: (f64, f64), to: (f64, f64)) -> f64 {
1198 let (lat1, lat2) = (from.0.to_radians(), to.0.to_radians());
1199 let (half_dlat, half_dlon) = ((lat2 - lat1) / 2.0, (to.1 - from.1).to_radians() / 2.0);
1200 let h = half_dlat.sin().powi(2) + lat1.cos() * lat2.cos() * half_dlon.sin().powi(2);
1201 2.0 * EARTH_RADIUS_M * h.sqrt().min(1.0).asin()
1202}
1203
1204fn speed_check(sets: &[Set], track: Track, speed: usize) -> Check {
1209 let mut ratios = Vec::new();
1210 for set in sets {
1211 let mut order: Vec<usize> = (0..set.times_ns.len()).collect();
1212 order.sort_by_key(|&row| set.times_ns[row]);
1213 let mut start: Option<(usize, (f64, f64))> = None;
1214 for row in order {
1215 let Some(point) = track.at(set, row) else {
1216 start = None;
1217 continue;
1218 };
1219 if let Some((from, from_point)) = start {
1220 if point == from_point {
1221 continue;
1222 }
1223 let step_s = seconds_between(set.times_ns[from], set.times_ns[row]);
1224 let speed = set.values[speed][row];
1225 if step_s > MIN_STEP_S && step_s <= MAX_STEP_S && speed.abs() >= MIN_SPEED {
1226 ratios.push(track.change(from_point, point) / step_s / speed);
1227 }
1228 }
1229 start = Some((row, point));
1230 }
1231 }
1232 Check::from_ratios(ratios)
1233}
1234
1235struct Decisions {
1237 heights: bool,
1238 vertical: bool,
1239 horizontal: bool,
1240 heading: bool,
1241 battery: bool,
1242 notes: Vec<String>,
1243}
1244
1245impl Decisions {
1246 fn from_file(columns: &[Column], sets: &[Set]) -> Self {
1247 let place = |name: &str| columns.iter().position(|c| c.name == name);
1248 let named = |kind: Kind| -> Vec<String> {
1249 columns
1250 .iter()
1251 .filter(|c| c.role == Role::Value(kind))
1252 .map(|c| format!("`{}`", short(&c.name)))
1253 .collect()
1254 };
1255 let values = |kind: Kind| {
1256 columns
1257 .iter()
1258 .enumerate()
1259 .filter(move |(_, c)| c.role == Role::Value(kind))
1260 .flat_map(move |(index, _)| sets.iter().flat_map(move |s| s.values[index].iter()))
1261 .copied()
1262 .filter(|value| value.is_finite())
1263 };
1264 let mut notes = Vec::new();
1265 let altitude = place("ALT").or_else(|| place("TRACKER Alt asl"));
1266 let position = place("LAT")
1267 .zip(place("LON"))
1268 .or_else(|| place("TRACKER Lat").zip(place("TRACKER Lon")));
1269 let altitude_name = altitude.map_or("ALT", |index| columns[index].name.as_str());
1270
1271 let horizontal = match (position, place("HORZV")) {
1276 (Some((lat, lon)), Some(speed)) => speed_check(sets, Track::Position(lat, lon), speed),
1277 _ => Check::TooFew(0),
1278 };
1279 let vertical = match (altitude, place("VERTV")) {
1280 (Some(altitude), Some(speed)) => speed_check(sets, Track::Height(altitude), speed),
1281 _ => Check::TooFew(0),
1282 };
1283 let alt_agl = alt_agl_check(columns, sets);
1284 let feet = !matches!(horizontal, Check::Disagrees(..));
1285 let kept = if !feet {
1286 Some(Kept::HorizontalSpeed)
1287 } else if alt_agl.is_some_and(|check| !check.agrees()) {
1288 Some(Kept::AltAgl)
1289 } else if matches!(vertical, Check::Disagrees(..)) {
1290 Some(Kept::VerticalSpeed)
1291 } else {
1292 None
1293 };
1294 let horizontal_words =
1295 horizontal.words("the distance between fixes a second, in feet,", "HORZV");
1296 let vertical_words = vertical.words(
1297 &format!("the change of `{altitude_name}` a second"),
1298 "VERTV",
1299 );
1300
1301 if place("HORZV").is_some() {
1302 notes.push(match horizontal {
1303 Check::Agrees(..) => format!(
1304 "`HORZV` read in feet per second, from the manual and the distance between \
1305 fixes: {horizontal_words}"
1306 ),
1307 Check::TooFew(_) => format!(
1308 "`HORZV` read in feet per second, from the manual alone: {horizontal_words}"
1309 ),
1310 Check::Disagrees(..) => format!(
1311 "`HORZV` kept as written, the distance between fixes disagrees with the \
1312 manual's feet per second. Here, {horizontal_words}. Every length and speed \
1313 the manual gives in feet is kept as written with it"
1314 ),
1315 });
1316 }
1317
1318 let mut heights = named(Kind::Height {
1319 above_sea_level: true,
1320 });
1321 heights.extend(named(Kind::Height {
1322 above_sea_level: false,
1323 }));
1324 if !heights.is_empty() {
1325 let names = list(&heights);
1326 let mut evidence = vec![horizontal_words.clone()];
1327 if place("VERTV").is_some() {
1328 evidence.push(vertical_words.clone());
1329 }
1330 evidence.extend(alt_agl.map(AltAgl::words));
1331 evidence.extend(altitude_agl_words(columns, sets));
1332 let evidence = evidence.join("; ");
1333 notes.push(match kept {
1334 Some(why) => format!("{names} kept as written, {}: {evidence}", why.words()),
1335 None => {
1336 let by_horizontal = matches!(horizontal, Check::Agrees(..));
1337 let by_alt_agl = alt_agl.is_some_and(|check| check.rows > 0);
1338 let source = match (by_horizontal, by_alt_agl) {
1339 (true, false) => "from the manual and the horizontal speed",
1340 (false, false) => "from the manual alone",
1341 (true, true) => "from the manual, the horizontal speed and `Alt AGL (ft)`",
1342 (false, true) => "from the manual and `Alt AGL (ft)`",
1343 };
1344 format!("{names} read in feet, {source}: {evidence}")
1345 }
1346 });
1347 }
1348
1349 if place("VERTV").is_some() {
1350 notes.push(match (kept, altitude, vertical) {
1351 (Some(Kept::VerticalSpeed), ..) => format!(
1352 "`VERTV` kept as written, not in the altitude's unit a second: \
1353 {vertical_words}"
1354 ),
1355 (Some(why), ..) => {
1356 format!("`VERTV` kept as written, {}: {vertical_words}", why.words())
1357 }
1358 (None, None, _) => "`VERTV` read in feet per second, from the manual alone: the \
1359 file has no altitude to compare it with"
1360 .to_owned(),
1361 (None, Some(_), Check::TooFew(_)) => format!(
1362 "`VERTV` read in feet per second, in the altitude's unit, from the \
1363 manual alone: {vertical_words}"
1364 ),
1365 (None, Some(_), _) => format!(
1366 "`VERTV` read in feet per second, in the altitude's unit, from the \
1367 change of altitude: {vertical_words}"
1368 ),
1369 });
1370 }
1371 let heights_read = kept.is_none();
1372
1373 let heading = values(Kind::Heading).fold(None, range);
1374 let heading_read = heading.is_none_or(|(lo, hi): (f64, f64)| lo >= -360.0 && hi <= 360.0);
1375 if place("HEAD").is_some() {
1376 let evidence = heading.map_or_else(
1377 || "the column holds no value; the manual gives degrees from north".to_owned(),
1378 |(lo, hi)| format!("it runs from {lo} to {hi}"),
1379 );
1380 notes.push(if heading_read {
1381 format!("`HEAD` read in degrees, from the manual and its range: {evidence}")
1382 } else {
1383 format!(
1384 "`HEAD` kept as written, its range disagrees with the manual's degrees: \
1385 {evidence}"
1386 )
1387 });
1388 }
1389
1390 let battery = values(Kind::Battery).fold(None, range);
1391 let battery_read = battery.is_none_or(|(lo, hi): (f64, f64)| lo >= 0.0 && hi <= MAX_CELL_V);
1392 if place("BATT").is_some() {
1393 let evidence = match battery {
1394 None => "the column holds no value".to_owned(),
1395 Some((lo, hi)) if lo == 0.0 && hi == 0.0 => {
1396 "it reads 0 on every row, which no unit changes".to_owned()
1397 }
1398 Some((lo, hi)) => format!(
1399 "it runs from {lo} to {hi}, where one lithium cell reads up to about 4.2 V and \
1400 the ground station's serial millivolts would be thousands"
1401 ),
1402 };
1403 notes.push(if battery_read {
1404 format!("`BATT` read in volts, from its range: {evidence}")
1405 } else {
1406 format!(
1407 "`BATT` kept as written, its range isn't one lithium cell's volts: {evidence}"
1408 )
1409 });
1410 }
1411
1412 if let Some(note) = unix_note(columns, sets) {
1413 notes.push(note);
1414 }
1415 Self {
1416 heights: heights_read,
1417 vertical: heights_read,
1418 horizontal: feet,
1419 heading: heading_read,
1420 battery: battery_read,
1421 notes,
1422 }
1423 }
1424
1425 fn quantity(&self, role: Role) -> Option<Quantity> {
1427 let decided = |read: bool, quantity| {
1428 if read {
1429 quantity
1430 } else {
1431 Quantity::Unrecognized
1432 }
1433 };
1434 Some(match role {
1435 Role::Date | Role::Tracker | Role::Label => return None,
1436 Role::Clock | Role::Time => Quantity::TimeOfDay,
1437 Role::Value(kind) => match kind {
1438 Kind::Height {
1439 above_sea_level: true,
1440 } => decided(self.heights, Quantity::GnssAltitude),
1441 Kind::Height {
1442 above_sea_level: false,
1443 } => decided(self.heights, Quantity::Distance),
1444 Kind::VerticalSpeed => decided(self.vertical, Quantity::Speed),
1445 Kind::HorizontalSpeed => decided(self.horizontal, Quantity::Speed),
1446 Kind::Heading => decided(self.heading, Quantity::Angle),
1447 Kind::Battery => decided(self.battery, Quantity::Voltage),
1448 Kind::UnixTime | Kind::Unknown => Quantity::Unrecognized,
1449 Kind::Stated(quantity, _) => quantity,
1450 },
1451 })
1452 }
1453
1454 fn factor(&self, role: Role) -> f64 {
1456 match role {
1457 Role::Value(Kind::Height { .. }) if self.heights => FOOT_M,
1458 Role::Value(Kind::VerticalSpeed) if self.vertical => FOOT_M,
1459 Role::Value(Kind::HorizontalSpeed) if self.horizontal => FOOT_M,
1460 Role::Value(Kind::Stated(_, factor)) => factor,
1461 _ => 1.0,
1462 }
1463 }
1464}
1465
1466fn range(acc: Option<(f64, f64)>, value: f64) -> Option<(f64, f64)> {
1468 Some(acc.map_or((value, value), |(lo, hi)| (lo.min(value), hi.max(value))))
1469}
1470
1471#[derive(Debug, Clone, Copy, PartialEq)]
1473enum Kept {
1474 HorizontalSpeed,
1477 AltAgl,
1479 VerticalSpeed,
1481}
1482
1483impl Kept {
1484 fn words(self) -> &'static str {
1486 match self {
1487 Self::HorizontalSpeed => "the horizontal speed disagrees with the manual's feet",
1488 Self::AltAgl => "`Alt AGL (ft)` disagrees with the manual's feet",
1489 Self::VerticalSpeed => "`VERTV` isn't their change a second",
1490 }
1491 }
1492}
1493
1494#[derive(Debug, Clone, Copy, PartialEq)]
1497struct AltAgl {
1498 held: usize,
1499 rows: usize,
1500}
1501
1502impl AltAgl {
1503 fn agrees(self) -> bool {
1506 self.rows == 0 || self.held * 2 >= self.rows
1507 }
1508
1509 fn words(self) -> String {
1510 format!(
1511 "`Alt AGL (ft)` is `TRACKER Alt asl` less `GS Alt asl` and `GS_ASL_offset`, to 0.15 ft, \
1512 on {} of {} rows",
1513 self.held, self.rows
1514 )
1515 }
1516}
1517
1518fn alt_agl_check(columns: &[Column], sets: &[Set]) -> Option<AltAgl> {
1520 let place = |name: &str| columns.iter().position(|c| c.name == name);
1521 let ((agl, tracker), (station, offset)) =
1522 place("Alt AGL (ft)")
1523 .zip(place("TRACKER Alt asl"))
1524 .zip(place("GS Alt asl").zip(place("GS_ASL_offset")))?;
1525 let (mut held, mut rows) = (0usize, 0usize);
1526 for set in sets {
1527 for row in 0..set.times_ns.len() {
1528 let at = |column: usize| set.values[column][row];
1529 let residual = at(agl) - (at(tracker) - at(station) - at(offset));
1530 if residual.is_finite() {
1531 rows += 1;
1532 held += usize::from(residual.abs() <= 0.15);
1533 }
1534 }
1535 }
1536 Some(AltAgl { held, rows })
1537}
1538
1539fn altitude_agl_words(columns: &[Column], sets: &[Set]) -> Option<String> {
1542 let place = |name: &str| columns.iter().position(|c| c.name == name);
1543 let (altitude, agl) = place("ALT").zip(place("Altitude AGL"))?;
1544 #[allow(
1545 clippy::cast_possible_truncation,
1546 reason = "finite by the filter; one past an i64's span saturates, matching none inside it"
1547 )]
1548 let mut differences: Vec<i64> = sets
1549 .iter()
1550 .flat_map(|set| {
1551 set.values[altitude]
1552 .iter()
1553 .zip(&set.values[agl])
1554 .map(|(alt, agl)| alt - agl)
1555 })
1556 .filter(|difference| difference.is_finite())
1557 .map(|difference| (difference * 10.0).round() as i64)
1560 .collect();
1561 differences.sort_unstable();
1562 let rows = differences.len();
1563 let most = differences
1564 .chunk_by(|a, b| a == b)
1565 .map(<[i64]>::len)
1566 .max()
1567 .unwrap_or(0);
1568 Some(format!(
1569 "`Altitude AGL` is `ALT` less one height, to 0.05 ft, on {most} of {rows} rows, as a \
1570 height above the pad is"
1571 ))
1572}
1573
1574fn unix_note(columns: &[Column], sets: &[Set]) -> Option<String> {
1576 let unix = columns
1577 .iter()
1578 .position(|c| c.role == Role::Value(Kind::UnixTime))?;
1579 columns.iter().find(|c| c.role == Role::Clock)?;
1581 let lon = columns.iter().position(|c| c.name == "LON");
1582 let mut offsets: Vec<f64> = Vec::new();
1583 let mut solar: Option<(f64, f64)> = None;
1584 for set in sets {
1585 for (row, &instant) in set.times_ns.iter().enumerate() {
1586 let written = set.values[unix][row];
1587 if !written.is_finite() {
1588 continue;
1589 }
1590 let utc_s = instant.div_euclid(NS_PER_S) as f64
1591 + instant.rem_euclid(NS_PER_S) as f64 / NS_PER_S as f64;
1592 offsets.push(written - utc_s);
1593 if solar.is_none()
1594 && let Some(longitude) = lon.map(|lon| set.values[lon][row])
1595 && longitude.is_finite()
1596 {
1597 let unix_of_day = written.rem_euclid(86_400.0) / 3_600.0;
1598 solar = Some((
1599 solar_hours(instant, longitude),
1600 (unix_of_day + longitude / 15.0).rem_euclid(24.0),
1601 ));
1602 }
1603 }
1604 }
1605 let hours = offsets.first().map(|offset| (offset / 3_600.0).round())?;
1606 let whole = offsets
1608 .iter()
1609 .all(|offset| (offset - hours * 3_600.0).abs() < 0.01);
1610 let sun = solar.map_or_else(String::new, |(utc, unix)| {
1611 format!(
1612 ". Read as UTC at the first fix's longitude, `UTCTIME` gives {utc:.1} h of local mean \
1613 solar time and `UNIXTIME` {unix:.1} h"
1614 )
1615 });
1616 Some(if whole {
1617 let offset = if hours >= 0.0 {
1618 format!("{hours} h ahead of")
1619 } else {
1620 format!("{} h behind", -hours)
1621 };
1622 format!(
1623 "`UNIXTIME` kept as written, off `UTCTIME` by whole hours: it runs {offset} \
1624 `UTCTIME` on every row{sun}"
1625 )
1626 } else {
1627 let (lo, hi) = offsets
1628 .iter()
1629 .copied()
1630 .fold(None, range)
1631 .unwrap_or_default();
1632 format!(
1633 "`UNIXTIME` kept as written, off `UTCTIME` by other than one whole number of hours. \
1634 It runs from {lo:.3} s to {hi:.3} s ahead of `UTCTIME`{sun}"
1635 )
1636 })
1637}
1638
1639fn syntax(line: usize, message: String) -> LogError {
1640 LogError::Syntax {
1641 format: FORMAT,
1642 line,
1643 message,
1644 }
1645}
1646
1647#[cfg(test)]
1648mod tests {
1649 use super::*;
1650
1651 const OLDER: &str =
1652 "UTCTIME,UNIXTIME,ALT,LAT,LON,#SATS,FIX,HORZV,VERTV,HEAD,FLAGS,>40,>32,>24,RSSI,BATT";
1653 const GROUND: &str =
1654 "TRACKER,DATE,TIME,LAT,LON,ALT,FIX,HORZV,VERTV,HEAD,FLAGS,#TOT,>40,>32,>24,RSSI,BATT";
1655 const LONGER: &str = "TRACKER,DATE,TIME,GS Lat,GS Lon,GS Alt asl,TRACKER Lat,TRACKER Lon,\
1656 TRACKER Alt asl,FIX,HORZV,VERTV,HEAD,FLAGS,#TOT,>40,>32,>24,RSSI Down,RSSI Up,\
1657 Horizontal range (ft),Alt AGL (ft),Total range (ft),LoRa Max Range (kft),\
1658 LoRa Success Rate,BATT,GS_batt_v,Down Sent,Down Rcvd,Found Sent,Up Sent,Up Rccvd,\
1659 Found rocket ID,Found rocket lat,Found rocket lon,Found rocket altitude,Found rocket fix,\
1660 Found rocket batt_v,Found RSSI,GS_ASL_offset";
1661
1662 fn degree_m() -> f64 {
1664 EARTH_RADIUS_M.to_radians()
1665 }
1666
1667 fn tracker_file(rows: usize, alt: impl Fn(usize) -> f64, vertv: f64, horzv: f64) -> String {
1670 tracker_file_with(rows, alt, vertv, horzv, 90, "4.0")
1671 }
1672
1673 fn tracker_file_with(
1675 rows: usize,
1676 alt: impl Fn(usize) -> f64,
1677 vertv: f64,
1678 horzv: f64,
1679 head: i32,
1680 batt: &str,
1681 ) -> String {
1682 moving_file(rows, alt, vertv, horzv, 30.0 * FOOT_M, head, batt)
1683 }
1684
1685 fn moving_file(
1687 rows: usize,
1688 alt: impl Fn(usize) -> f64,
1689 vertv: f64,
1690 horzv: f64,
1691 step_m: f64,
1692 head: i32,
1693 batt: &str,
1694 ) -> String {
1695 let mut text = format!("{OLDER}\n");
1696 for row in 0..rows {
1697 let lat = 40.0 + step_m * row as f64 / degree_m();
1698 text.push_str(&format!(
1699 "Jun 1 2025 18:00:{row:02}.000 UTC,{}.000,{},{lat:.7},-105.0,12,3,{horzv},{vertv},\
1700 {head},0x03,1,2,3,-50,{batt}\n",
1701 1_748_800_800 + row,
1702 alt(row)
1703 ));
1704 }
1705 text
1706 }
1707
1708 fn channel<'a>(log: &'a FlightLog, column: &str) -> &'a Channel {
1709 log.channels.iter().find(|c| c.column == column).unwrap()
1710 }
1711
1712 fn close(a: f64, b: f64) -> bool {
1713 (a - b).abs() <= 1e-9 * b.abs().max(1.0)
1714 }
1715
1716 fn climbing(row: usize) -> f64 {
1717 1000.0 + 100.0 * row as f64
1718 }
1719
1720 #[test]
1721 fn the_four_headers_are_recognized_and_nothing_else() {
1722 let newer = format!(
1723 "{OLDER},Altitude AGL,Launch detection,Apogee detection,Landing detection,\
1724 Distance (feet)"
1725 );
1726 for header in [OLDER, newer.as_str(), GROUND, LONGER] {
1727 assert!(
1728 recognizes(&format!("\u{feff}\r\n\n{header}\r\n")),
1729 "{header}"
1730 );
1731 assert!(recognizes(&header.replace(',', " , ")), "{header}");
1732 }
1733 for other in [
1734 "",
1735 "UTCTIME,UNIXTIME,ALT\n",
1736 "UNIXTIME,UTCTIME,ALT,LAT,LON\n",
1737 "utctime,unixtime,alt,lat,lon\n",
1738 "TRACKER,DATE,TIME,ALT,FIX\n",
1739 "TRACKER,DATE,TIME,GS Lat,GS Lon\n",
1740 "DATE,TIME,LAT,LON\n",
1741 "Time,Altitude,Velocity\n",
1742 "Year,Month,Day,Time,Flight_Time_(s),Sync,Gyro_X\n",
1743 "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\n",
1744 ] {
1745 assert!(!recognizes(other), "{other:?}");
1746 }
1747 }
1748
1749 #[test]
1752 fn tracker_times_are_read_strictly() {
1753 assert_eq!(
1755 utc_time("Jul 14 2031 17:04:31.250 UTC"),
1756 Some(1_941_815_071_250_000_000)
1757 );
1758 assert_eq!(utc_time("Jan 1 1970 00:00:00 UTC"), Some(0));
1759 assert_eq!(
1760 utc_time("jul 14 2031 17:04:31.250 UTC"),
1761 utc_time("Jul 14 2031 17:04:31.250 UTC")
1762 );
1763 let months = [
1764 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
1765 ];
1766 let mut last = i64::MIN;
1767 for month in months {
1768 let time = utc_time(&format!("{month} 1 2026 00:00:00 UTC")).unwrap();
1769 assert!(time > last, "{month}");
1770 last = time;
1771 }
1772 assert_eq!(
1774 utc_time("Feb 29 2024 00:00:00 UTC"),
1775 Some(19_782 * NS_PER_DAY)
1776 );
1777 assert_eq!(
1778 utc_time("Mar 1 2024 00:00:00 UTC"),
1779 Some(19_783 * NS_PER_DAY)
1780 );
1781 assert!(
1782 utc_time("Feb 29 2000 12:00:00 UTC").is_some(),
1783 "divisible by 400"
1784 );
1785 for bad in [
1786 "Feb 29 2023 12:00:00 UTC",
1787 "Feb 29 2100 12:00:00 UTC",
1788 "Apr 31 2021 12:00:00 UTC",
1789 "Apr 0 2021 12:00:00 UTC",
1790 "Jul 14 2031 17:04:31.250",
1791 "Jul 14 2031 17:04:31.250 GMT",
1792 "Jul 14 2031 17:04:31.250 UTC x",
1793 "July 14 2031 17:04:31 UTC",
1794 "Jul 14 31 17:04:31 UTC",
1795 "Jul 14 1969 17:04:31 UTC",
1796 "Jul 14 2200 17:04:31 UTC",
1797 "Jul 100 2031 17:04:31 UTC",
1798 "Jul 14 2031 24:00:00 UTC",
1799 "",
1800 ] {
1801 assert_eq!(utc_time(bad), None, "{bad:?}");
1802 }
1803 }
1804
1805 #[test]
1806 fn ground_station_dates_and_times_are_read_strictly() {
1807 assert_eq!(civil_date("2000-03-01"), Some(11_017));
1809 assert_eq!(civil_date("2199-12-31"), Some(84_005));
1810 assert_eq!(civil_date("2026-1-8"), civil_date("2026-01-08"));
1811 for bad in [
1812 "31-07-14",
1813 "2026-13-01",
1814 "2026-02-29",
1815 "2031-07-14-1",
1816 "2031/07/14",
1817 "",
1818 ] {
1819 assert_eq!(civil_date(bad), None, "{bad:?}");
1820 }
1821 assert_eq!(time_of_day_ns("0:00:00"), Some(0));
1822 assert_eq!(time_of_day_ns("14:27:09.375"), Some(52_029_375_000_000));
1823 assert_eq!(
1824 time_of_day_ns("23:59:60.123456789"),
1825 Some(86_400_123_456_789)
1826 );
1827 for bad in [
1828 "12:00",
1829 "12:00:00:00",
1830 "24:00:00",
1831 "12:60:00",
1832 "12:00:61",
1833 "12:5:00",
1834 "123:00:00",
1835 "12:00:00.",
1836 "12:00:00.1234567890",
1837 "12:00:00.x",
1838 "-1:00:00",
1839 "12:00:+1",
1840 ] {
1841 assert_eq!(time_of_day_ns(bad), None, "{bad:?}");
1842 }
1843 let before = civil_date("2025-12-31").unwrap() * NS_PER_DAY
1845 + time_of_day_ns("23:59:59.500").unwrap();
1846 let after = civil_date("2026-01-01").unwrap() * NS_PER_DAY
1847 + time_of_day_ns("00:00:00.250").unwrap();
1848 assert_eq!(seconds_between(before, after), 0.75);
1849 assert_eq!(clock_text(before), "23:59:59.500");
1850 }
1851
1852 #[test]
1853 fn cells_are_numbers_flags_hexadecimal_or_percentages() {
1854 assert_eq!(value("1.5"), Some(1.5));
1855 assert_eq!(value("-82"), Some(-82.0));
1856 assert_eq!(value("TRUE"), Some(1.0));
1857 assert_eq!(value("FALSE"), Some(0.0));
1858 assert_eq!(value("0x03"), Some(3.0));
1859 assert_eq!(value("0xff"), Some(255.0));
1860 assert_eq!(value("67%"), Some(67.0));
1861 assert_eq!(value("100%"), Some(100.0));
1862 for bad in [
1863 "",
1864 "NaN",
1865 "inf",
1866 "true",
1867 "0x",
1868 "0xg",
1869 "67 %",
1870 "%",
1871 "x",
1872 "0x12345678901234",
1873 ] {
1874 assert_eq!(value(bad), None, "{bad:?}");
1875 }
1876 }
1877
1878 #[test]
1881 fn a_degree_of_latitude_is_its_arc() {
1882 assert!((great_circle_m((40.0, -105.0), (41.0, -105.0)) - 111_195.08).abs() < 0.01);
1883 assert_eq!(great_circle_m((40.0, -105.0), (40.0, -105.0)), 0.0);
1884 }
1885
1886 #[test]
1889 fn speeds_that_agree_are_read_in_feet_per_second() {
1890 let log = read(&tracker_file(14, climbing, 100.0, 30.0)).unwrap();
1891 let up = channel(&log, "VERTV");
1892 assert_eq!(up.quantity, Quantity::Speed);
1893 assert!(close(up.values[0], 30.48));
1894 assert!(close(channel(&log, "HORZV").values[0], 30.0 * FOOT_M));
1895 let alt = channel(&log, "ALT");
1896 assert_eq!(alt.quantity, Quantity::GnssAltitude);
1897 assert!(close(alt.values[0], 304.8), "1000 ft is 304.8 m");
1898 assert_eq!(
1899 log.notes[..3],
1900 [
1901 "`HORZV` read in feet per second, from the manual and the distance between fixes: \
1902 the distance between fixes a second, in feet, is a median of 1.000 times `HORZV` \
1903 over 13 pairs of rows",
1904 "`ALT` read in feet, from the manual and the horizontal speed: the distance between \
1905 fixes a second, in feet, is a median of 1.000 times `HORZV` over 13 pairs of rows; \
1906 the change of `ALT` a second is a median of 1.000 times `VERTV` over 13 pairs of \
1907 rows",
1908 "`VERTV` read in feet per second, in the altitude's unit, from the change of altitude: the \
1909 change of `ALT` a second is a median of 1.000 times `VERTV` over 13 pairs of rows",
1910 ],
1911 "{:#?}",
1912 log.notes
1913 );
1914 }
1915
1916 #[test]
1921 fn a_file_all_in_meters_keeps_its_lengths_as_written() {
1922 let rising = |row: usize| 1000.0 + 50.0 * row as f64;
1923 let log = read(&moving_file(30, rising, 50.0, 25.0, 25.0, 90, "4.0")).unwrap();
1924 for (column, written) in [("ALT", 1000.0), ("VERTV", 50.0), ("HORZV", 25.0)] {
1925 let channel = channel(&log, column);
1926 assert_eq!(channel.quantity, Quantity::Unrecognized, "{column}");
1927 assert_eq!(channel.values[0], written, "{column}");
1928 }
1929 let why = "the horizontal speed disagrees with the manual's feet: ";
1930 assert!(
1931 log.notes[0].starts_with(
1932 "`HORZV` kept as written, the distance between fixes disagrees with the manual's \
1933 feet per second. Here, the distance between fixes a second, in feet, is a median \
1934 of 3.280 times `HORZV` over 29 pairs of rows"
1935 ),
1936 "{:#?}",
1937 log.notes
1938 );
1939 assert!(log.notes[1].starts_with(&format!("`ALT` kept as written, {why}")));
1940 assert_eq!(
1941 log.notes[2],
1942 format!(
1943 "`VERTV` kept as written, {why}the change of `ALT` a second is a median of 1.000 \
1944 times `VERTV` over 29 pairs of rows"
1945 )
1946 );
1947 }
1948
1949 #[test]
1951 fn the_same_file_in_feet_reads_in_feet() {
1952 let ft = 1.0 / FOOT_M;
1953 let rising = |row: usize| (1000.0 + 50.0 * row as f64) / FOOT_M;
1954 let log = read(&moving_file(
1955 30,
1956 rising,
1957 50.0 * ft,
1958 25.0 * ft,
1959 25.0,
1960 90,
1961 "4.0",
1962 ))
1963 .unwrap();
1964 for (column, quantity, si) in [
1965 ("ALT", Quantity::GnssAltitude, 1000.0),
1966 ("VERTV", Quantity::Speed, 50.0),
1967 ("HORZV", Quantity::Speed, 25.0),
1968 ] {
1969 let channel = channel(&log, column);
1970 assert_eq!(channel.quantity, quantity, "{column}");
1971 assert!(
1972 close(channel.values[0], si),
1973 "{column}: {}",
1974 channel.values[0]
1975 );
1976 }
1977 assert!(
1978 log.notes[1].starts_with(
1979 "`ALT` read in feet, from the manual and the horizontal speed: the distance \
1980 between fixes a second, in feet, is a median of 1.000 times `HORZV` over 29 pairs \
1981 of rows"
1982 ),
1983 "{:#?}",
1984 log.notes
1985 );
1986 }
1987
1988 #[test]
1991 fn a_vertical_speed_that_disagrees_is_kept_as_written() {
1992 let log = read(&tracker_file(14, climbing, 30.48, 30.0)).unwrap();
1993 let up = channel(&log, "VERTV");
1994 assert_eq!(up.quantity, Quantity::Unrecognized);
1995 assert_eq!(up.values[0], 30.48);
1996 let alt = channel(&log, "ALT");
1997 assert_eq!(alt.quantity, Quantity::Unrecognized);
1998 assert_eq!(alt.values[0], 1000.0);
1999 assert_eq!(
2000 log.notes[2],
2001 "`VERTV` kept as written, not in the altitude's unit a second: the change of `ALT` a second is \
2002 a median of 3.281 times `VERTV` over 13 pairs of rows"
2003 );
2004 assert!(
2005 log.notes[1]
2006 .starts_with("`ALT` kept as written, `VERTV` isn't their change a second: ")
2007 );
2008 assert_eq!(channel(&log, "HORZV").quantity, Quantity::Speed);
2010 }
2011
2012 #[test]
2015 fn horizontal_speed_heading_and_battery_that_disagree_are_kept() {
2016 let mph = 30.0 / 1.466_667;
2017 let log = read(&tracker_file_with(14, climbing, 100.0, mph, 400, "4010")).unwrap();
2018 let horizontal = channel(&log, "HORZV");
2019 assert_eq!(horizontal.quantity, Quantity::Unrecognized);
2020 assert!(close(horizontal.values[0], mph));
2021 assert_eq!(channel(&log, "HEAD").quantity, Quantity::Unrecognized);
2022 assert_eq!(channel(&log, "BATT").quantity, Quantity::Unrecognized);
2023 assert_eq!(channel(&log, "BATT").values[0], 4010.0);
2024 let notes = log.notes.join("\n");
2025 assert_eq!(channel(&log, "ALT").quantity, Quantity::Unrecognized);
2027 assert_eq!(channel(&log, "VERTV").quantity, Quantity::Unrecognized);
2028 for expected in [
2029 "`HORZV` kept as written, the distance between fixes disagrees with the manual's feet \
2030 per second. Here, the distance between fixes a second, in feet, is a median of \
2031 1.466 times",
2032 "`HEAD` kept as written, its range disagrees with the manual's degrees: it runs from \
2033 400 to 400",
2034 "`BATT` kept as written, its range isn't one lithium cell's volts: it runs from 4010 \
2035 to 4010",
2036 ] {
2037 assert!(notes.contains(expected), "{expected}\n{notes}");
2038 }
2039 let inside = read(&tracker_file(14, climbing, 100.0, 30.0 / 1.39)).unwrap();
2041 assert_eq!(channel(&inside, "HORZV").quantity, Quantity::Speed);
2042 let outside = read(&tracker_file(14, climbing, 100.0, 30.0 / 1.41)).unwrap();
2043 assert_eq!(channel(&outside, "HORZV").quantity, Quantity::Unrecognized);
2044 }
2045
2046 #[test]
2049 fn too_few_pairs_leave_the_manuals_unit() {
2050 let log = read(&tracker_file(5, climbing, 30.48, 9.0)).unwrap();
2051 assert_eq!(channel(&log, "VERTV").quantity, Quantity::Speed);
2052 assert_eq!(channel(&log, "ALT").quantity, Quantity::GnssAltitude);
2053 assert_eq!(
2054 log.notes[..3],
2055 [
2056 "`HORZV` read in feet per second, from the manual alone: the file has too few \
2057 pairs of moving rows to check `HORZV` over, 0 of the 10 needed",
2058 "`ALT` read in feet, from the manual alone: the file has too few pairs of moving \
2059 rows to check `HORZV` over, 0 of the 10 needed; the file has too few pairs of \
2060 moving rows to check `VERTV` over, 4 of the 10 needed",
2061 "`VERTV` read in feet per second, in the altitude's unit, from the manual alone: the file \
2062 has too few pairs of moving rows to check `VERTV` over, 4 of the 10 needed",
2063 ]
2064 );
2065 }
2066
2067 #[test]
2070 fn a_value_its_conversion_makes_infinite_is_refused() {
2071 let row = |range: &str| {
2072 format!(
2073 "T,2026-03-08,09:15:10,20,-100,3000,20.001,-100,4000,3,4,0,45,0x01,24,6,12,2,-50,\
2074 -55,364.8,1005,0,{range},100%,4.0,4.1,1,1,0,1,1,,0,0,0,0,0,-60,-5"
2075 )
2076 };
2077 let file = format!("{LONGER}\n{}\n{}\n", row("12.5"), row("1.7e308"));
2078 assert_eq!(
2079 read(&file).unwrap_err().to_string(),
2080 "Featherweight GPS CSV line 3: the column LoRa Max Range (kft) holds a value too \
2081 large for its unit's conversion to SI"
2082 );
2083 }
2084
2085 #[test]
2088 fn heights_that_disagree_with_alt_agl_are_kept() {
2089 let row = |agl: f64| {
2090 format!(
2091 "T,2026-03-08,09:15:10,20,-100,3000,20.001,-100,4000,3,4,0,45,0x01,24,6,12,2,-50,\
2092 -55,364.8,{agl},0,12.5,100%,4.0,4.1,1,1,0,1,1,,0,0,0,0,0,-60,-5"
2093 )
2094 };
2095 let agrees = read(&format!("{LONGER}\n{}\n", row(1005.0))).unwrap();
2096 assert_eq!(
2097 channel(&agrees, "GS Alt asl").quantity,
2098 Quantity::GnssAltitude
2099 );
2100 let disagrees = read(&format!("{LONGER}\n{}\n", row(304.8))).unwrap();
2101 assert_eq!(
2102 channel(&disagrees, "GS Alt asl").quantity,
2103 Quantity::Unrecognized
2104 );
2105 assert_eq!(
2106 channel(&disagrees, "GS_ASL_offset").quantity,
2107 Quantity::Unrecognized
2108 );
2109 assert_eq!(channel(&agrees, "VERTV").quantity, Quantity::Speed);
2111 assert_eq!(
2112 channel(&disagrees, "VERTV").quantity,
2113 Quantity::Unrecognized
2114 );
2115 assert!(disagrees.notes.contains(
2116 &"`VERTV` kept as written, `Alt AGL (ft)` disagrees with the manual's feet: the file \
2117 has too few pairs of moving rows to check `VERTV` over, 0 of the 10 needed"
2118 .to_owned()
2119 ));
2120 assert!(disagrees.notes.iter().any(|note| note.starts_with(
2121 "`GS Alt asl`, `TRACKER Alt asl`, `Found rocket altitude` and `GS_ASL_offset` kept as \
2122 written, `Alt AGL (ft)` disagrees with the manual's feet: "
2123 )));
2124 }
2125
2126 #[test]
2127 fn unixtime_off_by_other_than_whole_hours_is_said() {
2128 let text = format!(
2129 "{OLDER}\nJun 1 2025 18:00:00.000 UTC,1748800800.500,1,40,-105,1,3,0,0,0,0x03,1,1,1,\
2130 1,4\n"
2131 );
2132 let log = read(&text).unwrap();
2133 assert!(
2134 log.notes.iter().any(|note| note
2135 == "`UNIXTIME` kept as written, off `UTCTIME` by other than one whole number of \
2136 hours. It runs from 0.500 s to 0.500 s ahead of `UTCTIME`. Read as UTC at the \
2137 first fix's longitude, `UTCTIME` gives 11.0 h of local mean solar time and \
2138 `UNIXTIME` 11.0 h"),
2139 "{:#?}",
2140 log.notes
2141 );
2142 }
2143
2144 #[test]
2147 fn positions_out_of_range_are_gaps() {
2148 let row = |lat: &str, lon: &str| {
2149 format!(
2150 "Jun 1 2025 18:00:00.000 UTC,1748800800,1,{lat},{lon},1,3,0,0,0,0x03,1,1,1,1,4\n"
2151 )
2152 };
2153 let text = format!(
2154 "{OLDER}\n{}{}{}{}",
2155 row("90", "-180"),
2156 row("90.5", "-105"),
2157 row("-91", "180.001"),
2158 row("40", "-181")
2159 );
2160 let log = read(&text).unwrap();
2161 let (lat, lon) = (channel(&log, "LAT"), channel(&log, "LON"));
2162 assert_eq!(lat.values[0], 90.0);
2163 assert_eq!(lon.values[0], -180.0);
2164 assert!(lat.values[1].is_nan() && lon.values[1] == -105.0);
2165 assert!(lat.values[2].is_nan() && lon.values[2].is_nan());
2166 assert!(lat.values[3] == 40.0 && lon.values[3].is_nan());
2167 for expected in [
2168 "the column \"LAT\" holds 2 latitudes beyond ±90°: they are gaps",
2169 "the column \"LON\" holds 2 longitudes beyond ±180°: they are gaps",
2170 ] {
2171 assert!(
2172 log.notes.iter().any(|note| note == expected),
2173 "{expected}\n{:#?}",
2174 log.notes
2175 );
2176 }
2177 }
2178
2179 #[test]
2181 fn a_long_line_of_other_names_is_not_a_header() {
2182 let commas = ",".repeat(1 << 20);
2183 assert!(!recognizes(&commas));
2184 assert!(!recognizes(&format!("UTCTIME{commas}")));
2185 assert!(!recognizes(&format!("TRACKER,DATE{commas}")));
2186 assert!(recognizes(&format!("UTCTIME,UNIXTIME{commas}LAT,LON")));
2187 }
2188
2189 #[test]
2190 fn repeated_times_alone_are_noted() {
2191 let row = "Jun 1 2025 18:00:00.000 UTC,1748800800,1,40,-105,1,3,0,0,0,0x03,1,1,1,1,4";
2192 let log = read(&format!("{OLDER}\n{row}\n{row}\n")).unwrap();
2193 assert!(
2194 log.notes.contains(
2195 &"1 rows repeat a time already written: every row is kept, in the file's order"
2196 .to_owned()
2197 )
2198 );
2199 assert_eq!(channel(&log, "ALT").time_s, [0.0, 0.0]);
2200 }
2201
2202 #[test]
2204 fn trackers_past_the_cap_are_left_out() {
2205 let mut text = format!("{GROUND}\n");
2206 for tracker in 0..70 {
2207 text.push_str(&format!(
2208 "T{tracker},2026-01-01,10:00:{:02},1,1,1,3,0,0,0,0x03,1,1,1,1,1,0\n",
2209 tracker % 60
2210 ));
2211 }
2212 text.push_str("T69,2026-01-01,10:01:00,1,1,1,3,0,0,0,0x03,1,1,1,1,1,0\n");
2213 let log = read(&text).unwrap();
2214 assert_eq!(log.channels.len(), MAX_TRACKERS * 15);
2215 assert_eq!(log.channels[15].column, "TIME [T1]");
2216 assert!(
2217 log.notes.contains(
2218 &"7 rows of 6 more trackers were left out, past the first 64 trackers or 4096 \
2219 channels. This keeps a file of many tracker names from making the reader hold a \
2220 set of channels for each"
2221 .to_owned()
2222 ),
2223 "{:#?}",
2224 log.notes
2225 );
2226 }
2227
2228 #[test]
2230 fn malformed_files_are_refused_where_they_go_wrong() {
2231 let row = "Jun 1 2025 18:00:00.000 UTC,1748800800,1,40,-105,1,3,0,0,0,0x03,1,1,1,1,4";
2232 let cases = [
2233 (String::new(), "the file is empty"),
2234 ("\n\r\n".to_owned(), "the file is empty"),
2235 (
2236 "Time,Altitude\n0,0\n".to_owned(),
2237 "isn't a Featherweight GPS header",
2238 ),
2239 (format!("{OLDER}\n"), "no data rows"),
2240 (
2241 "UTCTIME,UNIXTIME,LAT,LON,,x\n".to_owned(),
2242 "line 1: the header's column 5 has no name",
2243 ),
2244 (
2245 format!("{OLDER}\n{row},9\n"),
2246 "line 2: the row has 17 cells, more than the header's 16",
2247 ),
2248 (
2249 format!("{OLDER}\n{}\n", row.replace("Jun 1", "Jun 31")),
2250 "line 2: the time \"Jun 31 2025 18:00:00.000 UTC\" in cell 1 isn't one",
2251 ),
2252 (
2253 format!("{GROUND}\nT,2026-02-30,10:00:00,1,1,1\n"),
2254 "line 2: the date \"2026-02-30\" in cell 2 isn't one",
2255 ),
2256 (
2257 format!("{GROUND}\nT,2026-02-03,10:00\n"),
2258 "line 2: the time \"10:00\" in cell 3 isn't one",
2259 ),
2260 (
2261 format!("{GROUND}\nT,2026-02-03\n"),
2262 "line 2: the row ends after 2 cells, before its \"TIME\"",
2263 ),
2264 ];
2265 for (text, expected) in cases {
2266 let error = read(&text).unwrap_err().to_string();
2267 assert!(error.contains(expected), "{text:?}: {error}");
2268 }
2269 let LogError::NotThisFormat { format, .. } = read("x").unwrap_err() else {
2270 panic!("refused for another reason");
2271 };
2272 assert_eq!(format, FORMAT);
2273 }
2274
2275 #[test]
2278 fn short_rows_are_gaps_and_a_wide_header_is_refused() {
2279 let wide: String = (0..20_000).map(|i| format!(",c{i}")).collect();
2280 let rows: String = (0..100)
2281 .map(|i| format!("Jun 1 2025 18:00:{:02}.000 UTC\n", i % 60))
2282 .collect();
2283 let error = read(&format!("UTCTIME,UNIXTIME,LAT,LON{wide}\n{rows}"))
2284 .unwrap_err()
2285 .to_string();
2286 assert!(
2287 error.contains(
2288 "line 5: the header names 20004 columns, and the 4 rows down to this one hold \
2289 only 4 cells"
2290 ),
2291 "{error}"
2292 );
2293 let log = read(&format!(
2294 "{OLDER}\nJun 1 2025 18:00:00.000 UTC,1748800800,1\n"
2295 ))
2296 .unwrap();
2297 assert!(channel(&log, "LAT").values[0].is_nan());
2298 assert!(log.notes.contains(
2299 &"1 rows, the first on line 2, have fewer cells than the header's 16: the cells they \
2300 leave out are gaps"
2301 .to_owned()
2302 ));
2303 }
2304
2305 #[test]
2308 fn unknown_columns_are_kept_and_their_notes_stay_few() {
2309 let unknown: String = (0..30).map(|i| format!(",u{i}")).collect();
2310 let row = format!(
2311 "Jun 1 2025 18:00:00.000 UTC,1748800800,1,40,-105{}",
2312 ",7".repeat(30)
2313 );
2314 let log = read(&format!("UTCTIME,UNIXTIME,ALT,LAT,LON{unknown}\n{row}\n")).unwrap();
2315 assert_eq!(channel(&log, "u29").quantity, Quantity::Unrecognized);
2316 assert_eq!(channel(&log, "u29").values, [7.0]);
2317 assert_eq!(
2318 log.notes
2319 .iter()
2320 .filter(|note| note.contains("isn't one this reader knows"))
2321 .count(),
2322 20
2323 );
2324 assert!(log.notes.last().unwrap().starts_with("and 10 more notes"));
2325 }
2326
2327 proptest::proptest! {
2328 #[test]
2331 fn any_text_is_read_or_refused(
2332 rows in proptest::collection::vec(
2333 (proptest::bool::ANY, "[-0-9.,: xaTRUEFLSNC%Jn]{0,60}"),
2334 0..10,
2335 ),
2336 layout in 0..3usize,
2337 ) {
2338 let header = [OLDER, GROUND, LONGER][layout];
2339 let clock = if layout == 0 {
2341 "Jun 1 2025 18:00:00.000 UTC,"
2342 } else {
2343 "T,2026-01-01,10:00:00,"
2344 };
2345 let rows: Vec<String> = rows
2346 .into_iter()
2347 .map(|(timed, rest)| if timed { format!("{clock}{rest}") } else { rest })
2348 .collect();
2349 let text = format!("{header}\n{}", rows.join("\n"));
2350 if let Ok(log) = read(&text) {
2351 proptest::prop_assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
2352 for channel in &log.channels {
2353 proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
2354 proptest::prop_assert!(channel.time_s.iter().all(|t| t.is_finite()));
2355 }
2356 }
2357 }
2358 }
2359}