1use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
97
98use crate::error::LogError;
99use crate::log::{Channel, FlightLog, LogFormat, Quantity, Stated};
100use crate::perfectflite::FOOT_M;
101use crate::table::finite;
102
103const FORMAT: &str = "Raven FIP CSV";
105
106const ATM_PA: f64 = 101_325.0;
108
109const MPH_M_S: f64 = 0.447_04;
111
112const STATUS: &str = "bilba";
114
115const BARO_AGL: &str = "altitude (baro-ft-agl)";
117
118const BARE_AGL: &str = "altitude (ft-agl)";
120
121#[derive(Debug, Clone, Copy, PartialEq)]
123enum Scale {
124 By(f64),
126 Fahrenheit,
128}
129
130const KNOWN: [(&str, Quantity, Scale); 12] = [
134 (
135 "axial accel (gs)",
136 Quantity::Acceleration,
137 Scale::By(STANDARD_GRAVITY_MPS2),
138 ),
139 (
140 "lateral accel (gs)",
141 Quantity::Acceleration,
142 Scale::By(STANDARD_GRAVITY_MPS2),
143 ),
144 ("baro (atm)", Quantity::Pressure, Scale::By(ATM_PA)),
145 ("current draw (a)", Quantity::Current, Scale::By(1.0)),
146 ("temperature (f)", Quantity::Temperature, Scale::Fahrenheit),
147 (
148 "velocity (accel-ft/sec)",
149 Quantity::Speed,
150 Scale::By(FOOT_M),
151 ),
152 ("velocity (accel-mph)", Quantity::Speed, Scale::By(MPH_M_S)),
153 (
154 "altitude (accel-ft)",
155 Quantity::InertialAltitude,
156 Scale::By(FOOT_M),
157 ),
158 (BARO_AGL, Quantity::AltitudeAboveGround, Scale::By(FOOT_M)),
159 (BARE_AGL, Quantity::AltitudeAboveGround, Scale::By(FOOT_M)),
160 (
161 "altitude (baro-ft-asl)",
162 Quantity::AltitudeMsl,
163 Scale::By(FOOT_M),
164 ),
165 ("liftoff", Quantity::Number, Scale::By(1.0)),
166];
167
168fn key(name: &str) -> String {
170 let name = name.trim();
171 let name = name
172 .strip_prefix('[')
173 .and_then(|inner| inner.strip_suffix(']'))
174 .unwrap_or(name);
175 name.trim().to_ascii_lowercase()
176}
177
178fn known(name: &str) -> Option<(Quantity, Scale)> {
180 let key = key(name);
181 if key.starts_with("volts ") && key.ends_with("(v)") {
182 return Some((Quantity::Voltage, Scale::By(1.0)));
183 }
184 KNOWN
185 .iter()
186 .find(|(known, _, _)| *known == key)
187 .map(|(_, quantity, scale)| (*quantity, *scale))
188}
189
190fn is_clock(name: &str) -> bool {
192 name.get(..4)
193 .is_some_and(|start| start.eq_ignore_ascii_case("time"))
194}
195
196struct Column {
198 name: String,
199 quantity: Quantity,
200 scale: Scale,
201 values: Vec<f64>,
202 status: Option<Vec<f64>>,
203 empty: usize,
205 not_numbers: usize,
207 not_number_example: String,
208}
209
210struct Clock {
212 name: String,
213 time_s: Vec<f64>,
214 columns: Vec<Column>,
215 repeats: usize,
217 differing_repeats: usize,
218}
219
220impl Clock {
221 fn sample_width(&self) -> usize {
223 1 + self.columns.len() + self.columns.iter().filter(|c| c.status.is_some()).count()
224 }
225
226 fn empty_width(&self) -> usize {
228 1 + self.columns.len()
229 }
230}
231
232pub fn read(text: &str) -> Result<FlightLog, LogError> {
242 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
243 let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
244 let Some((header_line, header)) = lines.next() else {
245 return Err(LogError::NotThisFormat {
246 format: FORMAT,
247 message: "the file is empty".to_owned(),
248 });
249 };
250 let mut notes = Notes::default();
251 let mut clocks = header_clocks(header, header_line, &mut notes)?;
252
253 for (number, line) in lines {
254 read_row(&mut clocks, line, number, RowEnd::Exact)?;
255 }
256 build(clocks, header_line, notes)
257}
258
259pub fn read_rows(header: &str, rows: &str) -> Result<FlightLog, LogError> {
292 rows_under(header, rows, &[])
293}
294
295pub fn read_rows_around(header: &str, rows: &str, pasted: &[usize]) -> Result<FlightLog, LogError> {
330 if pasted.contains(&0) {
331 return Err(LogError::Mapping {
332 message: "the pasted columns are numbered from 1, and one is 0".to_owned(),
333 });
334 }
335 let pasted: Vec<usize> = pasted.iter().map(|column| column - 1).collect();
336 rows_under(header, rows, &pasted)
337}
338
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
341enum RowEnd<'a> {
342 Exact,
344 Padded { pasted: &'a [usize] },
347}
348
349fn rows_under(header: &str, rows: &str, pasted: &[usize]) -> Result<FlightLog, LogError> {
352 let mut notes = Notes::default();
353 let mut clocks = header_clocks(header, 0, &mut notes).map_err(|error| LogError::Mapping {
354 message: format!("the header stated for a Raven FIP export's rows: {error}"),
355 })?;
356 let rows = rows.strip_prefix('\u{feff}').unwrap_or(rows);
357 let mut lines = numbered_lines(rows)
358 .filter(|(_, line)| !line.trim().is_empty())
359 .peekable();
360 if let Some((number, line)) = lines.peek()
361 && line
362 .split(',')
363 .next()
364 .is_some_and(|first| is_clock(first.trim()))
365 {
366 return Err(syntax(
367 *number,
368 format!(
369 "the rows open with a header line, {:?}: the export has its own, and is read \
370 whole",
371 short(line)
372 ),
373 ));
374 }
375 let mut covered = vec![0usize; clocks.len()];
377 for (number, line) in lines {
378 let row = read_row(&mut clocks, line, number, RowEnd::Padded { pasted })?;
379 for (rows, hidden) in covered.iter_mut().zip(row) {
380 *rows += usize::from(hidden);
381 }
382 }
383 notes.push(
384 "read under a header line the caller stated, the rows' own header missing".to_owned(),
385 );
386 let mut kept = Vec::with_capacity(clocks.len());
387 for (clock, rows) in clocks.into_iter().zip(covered) {
388 if rows == 0 {
389 kept.push(clock);
390 continue;
391 }
392 let names: Vec<String> = clock
393 .columns
394 .iter()
395 .map(|column| format!("{:?}", short(&column.name)))
396 .collect();
397 notes.push(format!(
398 "{} left out: the pasted columns cover its cells in {rows} rows",
399 names.join(", ")
400 ));
401 }
402 build(kept, 0, notes).map_err(|error| match error {
404 LogError::Syntax {
405 line: 0, message, ..
406 } => LogError::Mapping {
407 message: format!("the header stated for a Raven FIP export's rows: {message}"),
408 },
409 other => other,
410 })
411}
412
413fn numbered_lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
415 let mut rest = Some(text);
416 let mut number = 0;
417 std::iter::from_fn(move || {
418 let current = rest?;
419 number += 1;
420 match current.find(['\r', '\n']) {
421 Some(end) => {
422 let skip = if current[end..].starts_with("\r\n") {
423 2
424 } else {
425 1
426 };
427 rest = Some(¤t[end + skip..]);
428 Some((number, ¤t[..end]))
429 }
430 None => {
431 rest = None;
432 (!current.is_empty()).then_some((number, current))
433 }
434 }
435 })
436}
437
438fn header_clocks(header: &str, line: usize, notes: &mut Notes) -> Result<Vec<Clock>, LogError> {
440 let names: Vec<&str> = header.split(',').map(str::trim).collect();
441 let is_raven = names.first().is_some_and(|first| is_clock(first))
442 && names.iter().any(|name| known(name).is_some());
443 if !is_raven {
444 return Err(LogError::NotThisFormat {
445 format: FORMAT,
446 message: format!(
447 "its first line, {:?}, isn't a FIP export's header, a clock such as \
448 `Time@Axial Accel (Gs)` and the Raven's channels",
449 short(header)
450 ),
451 });
452 }
453 let mut clocks: Vec<Clock> = Vec::new();
454 for (index, name) in names.iter().enumerate() {
455 let column_number = index + 1;
456 if name.is_empty() {
457 return Err(syntax(
458 line,
459 format!("the header's column {column_number} has no name"),
460 ));
461 }
462 if is_clock(name) {
463 if let Some(last) = clocks.last()
464 && last.columns.is_empty()
465 {
466 return Err(syntax(
467 line,
468 format!("the clock {:?} has no channel", short(&last.name)),
469 ));
470 }
471 clocks.push(Clock {
472 name: (*name).to_owned(),
473 time_s: Vec::new(),
474 columns: Vec::new(),
475 repeats: 0,
476 differing_repeats: 0,
477 });
478 continue;
479 }
480 let Some(clock) = clocks.last_mut() else {
482 continue;
483 };
484 if name.eq_ignore_ascii_case(STATUS) {
485 match clock.columns.last_mut() {
486 Some(column) if column.status.is_none() => column.status = Some(Vec::new()),
487 _ => {
488 return Err(syntax(
489 line,
490 format!("the status column {column_number} follows no channel of its own"),
491 ));
492 }
493 }
494 continue;
495 }
496 let (quantity, scale) = known(name).unwrap_or_else(|| {
497 notes.push(format!(
498 "the column {:?} isn't one this reader knows, and was kept as written",
499 short(name)
500 ));
501 (Quantity::Unrecognized, Scale::By(1.0))
502 });
503 clock.columns.push(Column {
504 name: (*name).to_owned(),
505 quantity,
506 scale,
507 values: Vec::new(),
508 status: None,
509 empty: 0,
510 not_numbers: 0,
511 not_number_example: String::new(),
512 });
513 }
514 if let Some(last) = clocks.last()
515 && last.columns.is_empty()
516 {
517 return Err(syntax(
518 line,
519 format!("the clock {:?} has no channel", short(&last.name)),
520 ));
521 }
522 Ok(clocks)
523}
524
525fn read_row(
530 clocks: &mut [Clock],
531 line: &str,
532 number: usize,
533 end: RowEnd,
534) -> Result<Vec<bool>, LogError> {
535 let pasted: &[usize] = match end {
536 RowEnd::Exact => &[],
537 RowEnd::Padded { pasted } => pasted,
538 };
539 let cells: Vec<&str> = line.split(',').map(str::trim).collect();
540 let mut covered = vec![false; clocks.len()];
541 let mut at = 0;
542 for (clock, covered) in clocks.iter_mut().zip(&mut covered) {
543 let empty_width = clock.empty_width();
544 let Some(head) = cells.get(at..at + empty_width) else {
545 return Err(syntax(
546 number,
547 format!(
548 "the row ends at cell {} before the clock {:?}'s cells",
549 cells.len(),
550 short(&clock.name)
551 ),
552 ));
553 };
554 let known = |k: &usize| !pasted.contains(&(at + k));
555 let filled = (0..empty_width).filter(known).any(|k| !head[k].is_empty());
556 let hidden = (0..empty_width).any(|k| !known(&k));
557 let width = clock.sample_width();
558 let sampled = if filled || !hidden {
559 filled
560 } else {
561 let one_status = clock.columns.len() == 1 && width > empty_width;
566 let after = (one_status && !pasted.contains(&(at + empty_width)))
567 .then(|| cells.get(at + empty_width).copied());
568 match after {
569 Some(Some(cell)) if !cell.is_empty() => status_cell(cell).is_some(),
570 Some(None) => false,
572 _ => {
573 return Err(syntax(
574 number,
575 format!(
576 "the pasted columns hide whether the clock {:?} has a sample in the row",
577 short(&clock.name)
578 ),
579 ));
580 }
581 }
582 };
583 if !sampled {
584 at += empty_width;
585 continue;
586 }
587 let Some(sample) = cells.get(at..at + width) else {
588 return Err(syntax(
589 number,
590 format!(
591 "the row ends at cell {} inside the clock {:?}'s sample",
592 cells.len(),
593 short(&clock.name)
594 ),
595 ));
596 };
597 if (at..at + width).any(|k| pasted.contains(&k)) {
598 *covered = true;
599 } else {
600 read_sample(clock, sample, number, at)?;
601 }
602 at += width;
603 }
604 let rest_filled = cells
607 .iter()
608 .enumerate()
609 .skip(at)
610 .any(|(k, cell)| !cell.is_empty() && !pasted.contains(&k));
611 let fits = match end {
612 RowEnd::Exact => at == cells.len(),
613 RowEnd::Padded { .. } => !rest_filled,
614 };
615 if !fits {
616 return Err(syntax(
617 number,
618 format!(
619 "the row has {} cells and its channels' samples take {at}",
620 cells.len()
621 ),
622 ));
623 }
624 Ok(covered)
625}
626
627fn read_sample(
629 clock: &mut Clock,
630 sample: &[&str],
631 number: usize,
632 first: usize,
633) -> Result<(), LogError> {
634 let time = sample[0];
635 let time_s = time
636 .parse::<f64>()
637 .ok()
638 .filter(|value| value.is_finite())
639 .ok_or_else(|| {
640 syntax(
641 number,
642 format!(
643 "the time {:?} in cell {} isn't a finite number",
644 short(time),
645 first + 1
646 ),
647 )
648 })?;
649 let mut parsed: Vec<(f64, Option<f64>)> = Vec::with_capacity(clock.columns.len());
651 let mut at = 1;
652 for column in &mut clock.columns {
653 let cell = sample[at];
654 let value = value_cell(column, cell).ok_or_else(|| {
655 syntax(
656 number,
657 format!(
658 "{:?} in cell {}, under {:?}, isn't a number",
659 short(cell),
660 first + at + 1,
661 short(&column.name)
662 ),
663 )
664 })?;
665 let value = finite(value, FORMAT, number, &column.name)?;
668 at += 1;
669 let status = if column.status.is_some() {
670 let cell = sample[at];
671 let status = status_cell(cell).ok_or_else(|| {
672 syntax(
673 number,
674 format!(
675 "the status {:?} in cell {} isn't `b` and binary digits",
676 short(cell),
677 first + at + 1
678 ),
679 )
680 })?;
681 at += 1;
682 Some(status)
683 } else {
684 None
685 };
686 parsed.push((value, status));
687 }
688 if let Some(&last) = clock.time_s.last() {
689 if time_s < last {
690 return Err(syntax(
691 number,
692 format!(
693 "the time {time_s} s on the clock {:?} comes before the one above it, {last} s",
694 short(&clock.name)
695 ),
696 ));
697 }
698 if time_s == last {
699 clock.repeats += 1;
700 let same = clock
701 .columns
702 .iter()
703 .zip(&parsed)
704 .all(|(column, (value, status))| {
705 same_bits(column.values.last(), Some(value))
706 && same_bits(
707 column.status.as_ref().and_then(|statuses| statuses.last()),
708 status.as_ref(),
709 )
710 });
711 if !same {
712 clock.differing_repeats += 1;
713 }
714 return Ok(());
715 }
716 }
717 clock.time_s.push(time_s);
718 for (column, (value, status)) in clock.columns.iter_mut().zip(parsed) {
719 column.values.push(value);
720 if let (Some(statuses), Some(status)) = (column.status.as_mut(), status) {
721 statuses.push(status);
722 }
723 }
724 Ok(())
725}
726
727fn same_bits(a: Option<&f64>, b: Option<&f64>) -> bool {
729 match (a, b) {
730 (Some(a), Some(b)) => a.to_bits() == b.to_bits(),
731 (None, None) => true,
732 _ => false,
733 }
734}
735
736fn value_cell(column: &mut Column, cell: &str) -> Option<f64> {
739 if cell.is_empty() {
740 column.empty += 1;
741 return Some(f64::NAN);
742 }
743 match cell.parse::<f64>() {
744 Ok(value) if value.is_finite() => Some(si(column.scale, value)),
745 Ok(_) => Some(not_a_number(column, cell)),
746 Err(_) if is_windows_non_number(cell) => Some(not_a_number(column, cell)),
747 Err(_) => None,
748 }
749}
750
751fn not_a_number(column: &mut Column, cell: &str) -> f64 {
753 if column.not_numbers == 0 {
754 column.not_number_example = short(cell);
755 }
756 column.not_numbers += 1;
757 f64::NAN
758}
759
760fn is_windows_non_number(cell: &str) -> bool {
763 let unsigned = cell.trim_start_matches(['-', '+']);
764 let Some(rest) = unsigned.strip_prefix("1.#") else {
765 return false;
766 };
767 let word = rest.trim_end_matches(|c: char| c.is_ascii_digit());
768 ["QNAN", "SNAN", "IND", "INF"]
769 .iter()
770 .any(|known| word.eq_ignore_ascii_case(known))
771}
772
773fn status_cell(cell: &str) -> Option<f64> {
777 if cell.is_empty() {
778 return Some(f64::NAN);
779 }
780 let digits = cell.strip_prefix(['b', 'B'])?;
781 if digits.is_empty() || digits.len() > 52 || !digits.bytes().all(|b| b == b'0' || b == b'1') {
782 return None;
783 }
784 u64::from_str_radix(digits, 2).ok().map(|bits| bits as f64)
786}
787
788fn si(scale: Scale, value: f64) -> f64 {
790 match scale {
791 Scale::By(factor) => value * factor,
792 Scale::Fahrenheit => (value - 32.0) * 5.0 / 9.0 + 273.15,
793 }
794}
795
796fn build(clocks: Vec<Clock>, header_line: usize, mut notes: Notes) -> Result<FlightLog, LogError> {
798 let mut log = FlightLog {
799 format: LogFormat::RavenFipCsv,
800 logger: "Featherweight Raven".to_owned(),
801 serial_number: None,
802 firmware: None,
803 flight_number: None,
804 stated: Stated::default(),
805 time_s: Vec::new(),
806 altitude_m: Vec::new(),
807 vertical_speed_m_s: None,
808 temperature_k: None,
809 battery_v: None,
810 channels: Vec::new(),
811 events: Vec::new(),
812 notes: Vec::new(),
813 };
814 for clock in clocks {
815 if clock.repeats > 0 {
816 notes.push(format!(
817 "the clock {:?} repeats the time before it {} times; the repeats were dropped, \
818 {} of them differing from the sample they repeat",
819 short(&clock.name),
820 clock.repeats,
821 clock.differing_repeats
822 ));
823 }
824 for column in clock.columns {
825 if column.not_numbers > 0 {
826 notes.push(format!(
827 "the column {:?} holds {} cells that aren't a number, such as {:?}: they are \
828 gaps",
829 short(&column.name),
830 column.not_numbers,
831 column.not_number_example
832 ));
833 }
834 if column.empty > 0 {
835 notes.push(format!(
836 "the column {:?} leaves {} samples' values empty: they are gaps",
837 short(&column.name),
838 column.empty
839 ));
840 }
841 log.channels.push(Channel {
842 column: column.name,
843 quantity: column.quantity,
844 time_s: clock.time_s.clone(),
845 values: column.values,
846 });
847 if let Some(status) = column.status {
848 log.channels.push(Channel {
849 column: "bILBA".to_owned(),
850 quantity: Quantity::Number,
851 time_s: clock.time_s.clone(),
852 values: status,
853 });
854 }
855 }
856 }
857
858 let primary = log
859 .channels
860 .iter()
861 .find(|channel| key(&channel.column) == BARO_AGL)
862 .or_else(|| {
863 let bare = log
864 .channels
865 .iter()
866 .find(|channel| key(&channel.column) == BARE_AGL);
867 if let Some(channel) = bare {
868 log.notes.push(format!(
869 "the file has no `[Altitude (Baro-Ft-AGL)]`; its {:?}, which names no sensor, \
870 was taken as the altitude above the pad",
871 channel.column
872 ));
873 }
874 bare
875 });
876 let Some(primary) = primary else {
877 return Err(syntax(
878 header_line,
879 "the file has no altitude above the pad, `[Altitude (Baro-Ft-AGL)]` or `Altitude \
880 (Ft-AGL)`"
881 .to_owned(),
882 ));
883 };
884 if primary.time_s.is_empty() {
885 return Err(LogError::NoData { format: FORMAT });
886 }
887 log.time_s.clone_from(&primary.time_s);
888 log.altitude_m.clone_from(&primary.values);
889 let on_primary_clock = |channel: &&Channel| channel.time_s == log.time_s;
891 let temperature = log
892 .channels_of(Quantity::Temperature)
893 .find(on_primary_clock)
894 .map(|channel| channel.values.clone());
895 let battery = log
896 .channels_of(Quantity::Voltage)
897 .filter(|channel| key(&channel.column).contains("battery"))
898 .find(on_primary_clock)
899 .map(|channel| channel.values.clone());
900 log.temperature_k = temperature;
901 log.battery_v = battery;
902
903 log.notes.extend(notes.kept);
904 if notes.left_out > 0 {
905 log.notes.push(format!(
906 "and {} more notes, left out so that a broken file's list stays short",
907 notes.left_out
908 ));
909 }
910 Ok(log)
911}
912
913const MAX_NOTES: usize = 20;
915
916#[derive(Default)]
919struct Notes {
920 kept: Vec<String>,
921 left_out: usize,
922}
923
924impl Notes {
925 fn push(&mut self, note: String) {
926 if self.kept.len() < MAX_NOTES {
927 self.kept.push(note);
928 } else {
929 self.left_out += 1;
930 }
931 }
932}
933
934fn syntax(line: usize, message: String) -> LogError {
935 LogError::Syntax {
936 format: FORMAT,
937 line,
938 message,
939 }
940}
941
942fn short(text: &str) -> String {
945 if text.chars().count() <= QUOTED_CHARS {
946 text.to_owned()
947 } else {
948 let mut cut: String = text.chars().take(QUOTED_CHARS - 1).collect();
949 cut.push('…');
950 cut
951 }
952}
953
954const QUOTED_CHARS: usize = 80;
956
957#[cfg(test)]
958mod tests {
959 use super::*;
960
961 const HEADER: &str = "Time@Axial Accel (Gs),Axial Accel (Gs),bILBA,\
962 Time@Baro (Atm),Baro (Atm),bILBA,\
963 Time@[Altitude (Baro-Ft-AGL)],[Altitude (Baro-Ft-AGL)],bILBA";
964
965 fn close(a: f64, b: f64) -> bool {
966 (a - b).abs() <= 1e-12 * b.abs().max(1.0)
967 }
968
969 #[test]
972 fn reads_each_channel_on_its_own_clock() {
973 let text = format!(
974 "{HEADER}\r\n\
975 0,1,b0000,0.01,1,b0000,0.01,0,b0000\r\n\
976 0.0025,2,b0101,0.06,0.5,b1100,0.06,100,b1100\r\n"
977 );
978 let log = read(&text).unwrap();
979 assert_eq!(log.format, LogFormat::RavenFipCsv);
980 assert_eq!(log.logger, "Featherweight Raven");
981 let columns: Vec<&str> = log.channels.iter().map(|c| c.column.as_str()).collect();
982 assert_eq!(
983 columns,
984 [
985 "Axial Accel (Gs)",
986 "bILBA",
987 "Baro (Atm)",
988 "bILBA",
989 "[Altitude (Baro-Ft-AGL)]",
990 "bILBA"
991 ]
992 );
993 assert_eq!(log.channels[0].time_s, [0.0, 0.0025]);
994 assert_eq!(log.channels[0].values, [9.806_65, 2.0 * 9.806_65]);
995 assert_eq!(log.channels[1].values, [0.0, 5.0]);
996 assert_eq!(log.channels[2].values, [101_325.0, 50_662.5]);
997 assert_eq!(log.channels[3].values, [0.0, 12.0]);
998 assert_eq!(log.time_s, [0.01, 0.06]);
999 assert_eq!(log.altitude_m, [0.0, 30.48]);
1000 assert!(log.vertical_speed_m_s.is_none());
1001 assert!(log.events.is_empty());
1002 assert!(log.notes.is_empty(), "{:?}", log.notes);
1003 }
1004
1005 #[test]
1008 fn a_stopped_channel_drops_its_status_cell() {
1009 let text = format!(
1010 "{HEADER}\n\
1011 0,1,b0000,0.01,1,b0000,0.01,0,b0000\n\
1012 0.0025,1,b0000,,,0.06,10,b1000\n\
1013 0.005,1,b0000,,,,\n\
1014 ,,,,,\n"
1015 );
1016 let log = read(&text).unwrap();
1017 assert_eq!(log.channels[0].time_s, [0.0, 0.0025, 0.005]);
1018 assert_eq!(log.channels[2].time_s, [0.01]);
1019 assert_eq!(log.time_s, [0.01, 0.06]);
1020 assert!(close(log.altitude_m[1], 3.048));
1021 assert_eq!(log.channels[5].values, [0.0, 8.0]);
1022
1023 let text = format!("{HEADER}\n0.0025,1,b0000,,,,0.06,10,b1000\n");
1025 let error = read(&text).unwrap_err().to_string();
1026 assert!(error.contains("line 2:"), "{error}");
1027 }
1028
1029 #[test]
1032 fn without_status_columns_rows_keep_their_width() {
1033 let text = "Time@Axial Accel (Gs),Axial Accel (Gs),Time@Temperature (F),Temperature (F),\
1034 Time@[Altitude (Baro-Ft-AGL)],[Altitude (Baro-Ft-AGL)]\n\
1035 0,1,0.01,32,0.01,0\n\
1036 0.0025,1,,,0.06,1\n";
1037 let log = read(text).unwrap();
1038 assert_eq!(log.channels.len(), 3);
1039 assert_eq!(log.channels[1].values, [273.15]);
1040 assert!(log.temperature_k.is_none(), "not on the altitude's clock");
1041 assert_eq!(log.time_s, [0.01, 0.06]);
1042 }
1043
1044 #[test]
1047 fn one_clock_layout_fills_the_track() {
1048 let text = "Time,LiftOff,Axial Accel (Gs),Temperature (F),Volts Battery (V),\
1049 Volts Pyro Main (V),[Altitude (Baro-Ft-AGL)],[Velocity (Accel-MPH)]\n\
1050 0,0,1,212,8.1,0.1,0,0\n\
1051 0.001,0,1,212,8.1,0.1,0,0\n\
1052 0.001,0,1,212,8.1,0.1,0,0\n\
1053 0.002,1,5,212,8.0,0.1,1,10\n";
1054 let log = read(text).unwrap();
1055 assert_eq!(log.time_s, [0.0, 0.001, 0.002]);
1056 let temperature = log.temperature_k.as_deref().unwrap();
1057 assert!(close(temperature[0], 373.15));
1058 assert_eq!(log.battery_v.as_deref(), Some(&[8.1, 8.1, 8.0][..]));
1059 assert_eq!(log.channels[0].quantity, Quantity::Number);
1060 assert!(close(log.channels[6].values[2], 4.4704));
1061 assert_eq!(
1062 log.notes,
1063 [
1064 "the clock \"Time\" repeats the time before it 1 times; the repeats were dropped, 0 \
1065 of them differing from the sample they repeat"
1066 ]
1067 );
1068 }
1069
1070 #[test]
1072 fn the_bare_altitude_is_taken_with_a_note() {
1073 let text = "Time-Axial Accel (Gs), Axial Accel (Gs), bILBA, Time (s), Altitude (Ft-AGL), \
1074 bILBA\n0, 1, b0000, 0, 10, b1000\n";
1075 let log = read(text).unwrap();
1076 assert_eq!(log.altitude_m, [3.048]);
1077 assert!(log.notes[0].contains("names no sensor"), "{:?}", log.notes);
1078 }
1079
1080 #[test]
1082 fn windows_non_numbers_are_gaps() {
1083 let text = format!(
1084 "{HEADER}\n0,-1.#QNAN,b0000,0.01,,b0000,0.01,0,b0000\n\
1085 0.0025,1.#INF,b0000,0.06,1,b0000,0.06,0,b0000\n"
1086 );
1087 let log = read(&text).unwrap();
1088 assert!(log.channels[0].values.iter().all(|v| v.is_nan()));
1089 assert!(log.channels[2].values[0].is_nan());
1090 assert_eq!(log.notes.len(), 2, "{:?}", log.notes);
1091 assert!(log.notes[0].contains("2 cells that aren't a number, such as \"-1.#QNAN\""));
1092 assert!(log.notes[1].contains("leaves 1 samples' values empty"));
1093 assert!(is_windows_non_number("-1.#IND00"));
1094 assert!(!is_windows_non_number("1.#X"));
1095 let error = read(&format!("{HEADER}\n0,x,b0000,,,,\n")).unwrap_err();
1096 assert!(
1097 error.to_string().contains("line 2: \"x\" in cell 2"),
1098 "{error}"
1099 );
1100 }
1101
1102 #[test]
1105 fn status_cells_are_binary_numbers() {
1106 assert_eq!(status_cell("b0101"), Some(5.0));
1107 assert_eq!(status_cell("b1000"), Some(8.0));
1108 assert_eq!(status_cell("b1111"), Some(15.0));
1109 assert!(status_cell("").unwrap().is_nan());
1110 for bad in ["0101", "b", "b012", "bx", &format!("b{}", "1".repeat(53))] {
1111 assert_eq!(status_cell(bad), None, "{bad}");
1112 }
1113 }
1114
1115 #[test]
1117 fn malformed_files_are_refused_where_they_go_wrong() {
1118 let cases = [
1119 (String::new(), "the file is empty"),
1120 (
1121 "Time,Altitude\n0,0\n".to_owned(),
1122 "isn't a FIP export's header",
1123 ),
1124 (
1125 "Axial Accel (Gs),Time\n".to_owned(),
1126 "isn't a FIP export's header",
1127 ),
1128 (format!("{HEADER}\n"), "no data rows"),
1129 (
1130 "Time@Axial Accel (Gs),Axial Accel (Gs)\n0,1\n".to_owned(),
1131 "line 1: the file has no altitude above the pad",
1132 ),
1133 (
1134 "Time@x,Time@Axial Accel (Gs),Axial Accel (Gs)\n".to_owned(),
1135 "line 1: the clock \"Time@x\" has no channel",
1136 ),
1137 (
1138 "Time@Axial Accel (Gs),bILBA,Axial Accel (Gs)\n".to_owned(),
1139 "line 1: the status column 2 follows no channel",
1140 ),
1141 (
1142 "Time@Axial Accel (Gs),Axial Accel (Gs),,x\n".to_owned(),
1143 "line 1: the header's column 3 has no name",
1144 ),
1145 (
1146 format!("{HEADER}\n0,1,b0,0.5,1,b0,0.5,0,b0\n0,1,b0,0.4,1,b0,0.6,0,b0\n"),
1147 "line 3: the time 0.4 s on the clock \"Time@Baro (Atm)\" comes before",
1148 ),
1149 (
1150 format!("{HEADER}\nx,1,b0,,,,\n"),
1151 "line 2: the time \"x\" in cell 1",
1152 ),
1153 (
1154 format!("{HEADER}\n0,1,b0,0,1,b0,0,1,b2\n"),
1155 "line 2: the status \"b2\" in cell 9",
1156 ),
1157 (
1158 format!("{HEADER}\n0,1,b0,0,1\n"),
1159 "line 2: the row ends at cell 5",
1160 ),
1161 (
1162 format!("{HEADER}\n0,1,b0,,,0.1,1,b0,7\n"),
1163 "line 2: the row has 9 cells and its channels' samples take 8",
1164 ),
1165 (format!("{HEADER}\n0,1,b0,,,,\n"), "no data rows"),
1166 ];
1167 for (text, expected) in cases {
1168 let error = read(&text).unwrap_err().to_string();
1169 assert!(error.contains(expected), "{text:?}: {error}");
1170 }
1171 }
1172
1173 #[test]
1176 fn a_value_its_conversion_makes_infinite_is_refused() {
1177 let cases = [
1178 (
1179 format!("{HEADER}\n0,1,b0,0,1,b0,0,0,b0\n0.1,1.7e308,b0,,,,\n"),
1180 "Raven FIP CSV line 3: the column Axial Accel (Gs) holds a value too large for \
1181 its unit's conversion to SI",
1182 ),
1183 (
1184 format!("{HEADER}\n0,1,b0,0,-1.7e308,b0,0,0,b0\n"),
1185 "Raven FIP CSV line 2: the column Baro (Atm) holds a value too large for its \
1186 unit's conversion to SI",
1187 ),
1188 (
1189 "Time@Temperature (F),Temperature (F),\
1190 Time@[Altitude (Baro-Ft-AGL)],[Altitude (Baro-Ft-AGL)]\n\
1191 0,70,0,0\n0.1,1.7e308,0.1,1\n"
1192 .to_owned(),
1193 "Raven FIP CSV line 3: the column Temperature (F) holds a value too large for \
1194 its unit's conversion to SI",
1195 ),
1196 ];
1197 for (text, expected) in cases {
1198 assert_eq!(read(&text).unwrap_err().to_string(), expected, "{text:?}");
1199 }
1200 }
1201
1202 #[test]
1204 fn marks_and_line_ends() {
1205 let text = format!("\u{feff}\r{HEADER}\r0,1,b0,0,1,b0,0,1,b0\r\r");
1206 let log = read(&text).unwrap();
1207 assert_eq!(log.altitude_m, [FOOT_M]);
1208 let lines: Vec<(usize, &str)> = numbered_lines("a\r\nb\rc\n\nd").collect();
1209 assert_eq!(lines, [(1, "a"), (2, "b"), (3, "c"), (4, ""), (5, "d")]);
1210 }
1211
1212 #[test]
1214 fn notes_stay_few() {
1215 let unknown: String = (0..100).map(|i| format!(",u{i}")).collect();
1216 let text = format!("Time@[Altitude (Baro-Ft-AGL)],[Altitude (Baro-Ft-AGL)]{unknown}\n");
1217 let row = format!("0{}\n", ",1".repeat(101));
1218 let log = read(&format!("{text}{row}")).unwrap();
1219 assert_eq!(log.notes.len(), MAX_NOTES + 1);
1220 assert!(
1221 log.notes[MAX_NOTES].starts_with("and 80 more notes"),
1222 "{:?}",
1223 log.notes
1224 );
1225 assert_eq!(log.channels.len(), 101);
1226 assert_eq!(log.channels[100].quantity, Quantity::Unrecognized);
1227 }
1228
1229 #[test]
1231 fn a_long_line_is_quoted_short() {
1232 let junk = "\u{fffd}".repeat(100_000);
1233 let error = read(&junk).unwrap_err().to_string();
1234 assert!(error.len() < 400, "{} bytes", error.len());
1235 }
1236
1237 proptest::proptest! {
1238 #[test]
1241 fn any_text_is_read_or_refused(rows in proptest::collection::vec("[-0-9.b,x#QNA]{0,24}", 0..10)) {
1242 let text = format!("{HEADER}\n{}", rows.join("\n"));
1243 if let Ok(log) = read(&text) {
1244 proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
1245 proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
1246 for channel in &log.channels {
1247 proptest::prop_assert!(channel.time_s.windows(2).all(|pair| pair[1] > pair[0]));
1248 proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
1249 }
1250 }
1251 }
1252 }
1253
1254 const ROWS: &str = "0,1.02,b0000,0,0.97,b0000,0,0,b0000\n\
1257 0.05,1.01,b0000,0.05,0.97,b0000,0.05,1,b0000\n\
1258 ,,0.1,0.96,b0000,0.1,3,b0000\n\
1259 ,,,,0.15,6,b0000\n";
1260
1261 fn padded() -> String {
1263 ROWS.lines()
1264 .map(|row| {
1265 let cells = row.split(',').count();
1266 format!("{row}{}\n", ",".repeat(9 - cells))
1267 })
1268 .collect()
1269 }
1270
1271 #[test]
1272 fn rows_a_sheet_padded_read_as_the_export_with_its_header() {
1273 let whole = read(&format!("{HEADER}\n{ROWS}")).unwrap();
1274 let rows = read_rows(HEADER, &padded()).unwrap();
1275 assert_eq!(rows.channels, whole.channels);
1276 assert_eq!(
1277 (&rows.time_s, &rows.altitude_m),
1278 (&whole.time_s, &whole.altitude_m)
1279 );
1280 assert_eq!(rows.time_s, [0.0, 0.05, 0.1, 0.15]);
1281 assert!(
1282 rows.notes
1283 .iter()
1284 .any(|note| note.contains("header line the caller stated"))
1285 );
1286 assert_eq!(read_rows(HEADER, ROWS).unwrap().channels, whole.channels);
1288 }
1289
1290 #[test]
1291 fn a_value_past_the_last_channel_is_refused_padded_or_not() {
1292 let mut rows = padded();
1294 rows.push_str(",,,,0.2,7,b0000,,5\n");
1295 match read_rows(HEADER, &rows) {
1296 Err(LogError::Syntax { line, message, .. }) => {
1297 assert_eq!(line, 5);
1298 assert!(
1299 message.contains("its channels' samples take 7"),
1300 "{message}"
1301 );
1302 }
1303 other => panic!("expected a syntax refusal, got {other:?}"),
1304 }
1305 assert!(matches!(
1307 read(&format!("{HEADER}\n{}", padded())),
1308 Err(LogError::Syntax { line: 4, .. })
1309 ));
1310 }
1311
1312 #[test]
1313 fn rows_with_a_header_of_their_own_are_refused() {
1314 match read_rows(HEADER, &format!("{HEADER}\n{ROWS}")) {
1315 Err(LogError::Syntax { line, message, .. }) => {
1316 assert_eq!(line, 1);
1317 assert!(message.contains("open with a header line"), "{message}");
1318 }
1319 other => panic!("expected a syntax refusal, got {other:?}"),
1320 }
1321 }
1322
1323 #[test]
1324 fn a_stated_header_that_cant_read_the_rows_is_the_callers_to_fix() {
1325 for (header, says) in [
1326 ("Altitude,Speed", "isn't a FIP export's header"),
1327 (
1328 "Time@Axial Accel (Gs),Axial Accel (Gs),bILBA",
1329 "no altitude above the pad",
1330 ),
1331 ] {
1332 match read_rows(header, "0,1.02,b0000\n") {
1333 Err(LogError::Mapping { message }) => {
1334 assert!(message.contains("the header stated"), "{message}");
1335 assert!(message.contains(says), "{message}");
1336 }
1337 other => panic!("{header}: expected a mapping refusal, got {other:?}"),
1338 }
1339 }
1340 }
1341
1342 fn header_with_velocity() -> String {
1344 format!("{HEADER},Time@[Velocity (Accel-Ft/Sec)],[Velocity (Accel-Ft/Sec)],bILBA")
1345 }
1346
1347 #[test]
1348 fn a_channel_pasted_over_in_any_row_is_left_out_and_the_rest_read() {
1349 let rows = [
1354 "0,1.02,b0000,0,0.97,b0000,0,0,b0000,0,0,b0000",
1355 "0.05,1.01,b0000,0.05,0.97,b0000,0.05,1,b0000,0.05,10,b0000",
1356 ",,0.1,0.96,b0000,0.1,3,b0000,0.1,20,b0000",
1357 ",,,,0.15,6,b0000,0.15,30,b0000",
1358 ];
1359 let sheet: String = rows
1360 .iter()
1361 .map(|row| {
1362 let mut cells: Vec<&str> = row.split(',').collect();
1363 cells.resize(12, "");
1364 cells[10] = "7";
1365 cells[11] = "8";
1366 format!("{}\n", cells.join(","))
1367 })
1368 .collect();
1369 let header = header_with_velocity();
1370 let log = read_rows_around(&header, &sheet, &[11, 12]).unwrap();
1371 let whole = read_rows(&header, &rows.join("\n")).unwrap();
1372 let unpasted: Vec<_> = whole
1373 .channels
1374 .iter()
1375 .filter(|c| c.column != "[Velocity (Accel-Ft/Sec)]")
1376 .collect();
1377 assert_eq!(log.channels.len(), 6);
1379 assert!(log.channels.iter().zip(&unpasted).all(|(a, b)| a == *b));
1380 assert_eq!(
1381 (&log.time_s, &log.altitude_m),
1382 (&whole.time_s, &whole.altitude_m)
1383 );
1384 assert!(log.notes.iter().any(|note| note
1385 == "\"[Velocity (Accel-Ft/Sec)]\" left out: the pasted columns cover its cells in 3 rows"));
1386 assert!(matches!(
1388 read_rows(&header, &sheet),
1389 Err(LogError::Syntax { line: 1, .. })
1390 ));
1391 }
1392
1393 #[test]
1394 fn a_status_cell_tells_whether_a_pasted_over_channel_has_a_sample() {
1395 let sheet = "0,1.02,b0000,7,8,b0000,0,0,b0000\n0.05,1.01,b0000,7,8,0.05,1,b0000,\n";
1399 let log = read_rows_around(HEADER, sheet, &[4, 5]).unwrap();
1400 assert_eq!(log.time_s, [0.0, 0.05]);
1401 assert_eq!(log.altitude_m, [0.0, 0.3048]);
1402 assert!(
1403 log.notes.iter().any(|note| note
1404 == "\"Baro (Atm)\" left out: the pasted columns cover its cells in 1 rows")
1405 );
1406 assert!(!log.channels.iter().any(|c| c.column == "Baro (Atm)"));
1407 let hidden = "0,1.02,b0000,7,8,b0000,0,0,b0000\n,,,7,8,6,b0000,,\n";
1410 match read_rows_around(HEADER, hidden, &[4, 5]) {
1411 Err(LogError::Syntax { line, message, .. }) => {
1412 assert_eq!(line, 2);
1413 assert!(
1414 message.contains("hide whether the clock \"Time@Baro (Atm)\" has a sample"),
1415 "{message}"
1416 );
1417 }
1418 other => panic!("expected a syntax refusal, got {other:?}"),
1419 }
1420 for row in [
1423 "0.05,1.01,b0000,7,8,,,,",
1424 "0.05,1.01,b0000,7,8,,0.05,1,b0000",
1425 ] {
1426 let sheet = format!("0,1.02,b0000,7,8,b0000,0,0,b0000\n{row}\n");
1427 match read_rows_around(HEADER, &sheet, &[4, 5]) {
1428 Err(LogError::Syntax { line, message, .. }) => {
1429 assert_eq!(line, 2, "{row}");
1430 assert!(
1431 message.contains("hide whether the clock \"Time@Baro (Atm)\" has a sample"),
1432 "{row}: {message}"
1433 );
1434 }
1435 other => panic!("{row}: expected a syntax refusal, got {other:?}"),
1436 }
1437 }
1438 }
1439
1440 #[test]
1444 fn a_pasted_over_clock_of_two_channels_is_refused() {
1445 let header = "Time@A,Axial Accel (Gs),bILBA,Lateral Accel (Gs),bILBA,\
1446 Time@B,[Altitude (Baro-Ft-AGL)],bILBA";
1447 let sheet = "0,1,b0000,2,b0000,0,0,b0000\n9,9,,5,,,,\n";
1448 match read_rows_around(header, sheet, &[1, 2]) {
1449 Err(LogError::Syntax { line, message, .. }) => {
1450 assert_eq!(line, 2);
1451 assert!(
1452 message.contains("hide whether the clock \"Time@A\" has a sample"),
1453 "{message}"
1454 );
1455 }
1456 other => panic!("expected a syntax refusal, got {other:?}"),
1457 }
1458 }
1459
1460 #[test]
1461 fn pasted_columns_are_numbered_from_1() {
1462 match read_rows_around(HEADER, ROWS, &[0]) {
1463 Err(LogError::Mapping { message }) => {
1464 assert!(message.contains("numbered from 1"), "{message}");
1465 }
1466 other => panic!("expected a mapping refusal, got {other:?}"),
1467 }
1468 assert_eq!(
1470 read_rows_around(HEADER, &padded(), &[]).unwrap(),
1471 read_rows(HEADER, &padded()).unwrap()
1472 );
1473 }
1474}