1use std::collections::BTreeSet;
154use std::f64::consts::PI;
155
156use hpr_atmos::ussa76::Ussa76;
157use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
158
159use crate::error::LogError;
160use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
161use crate::table::{Notes, finite, number, numbered_lines, short};
162
163const FORMAT: &str = "SillyGoose text";
165
166const LOGGER: &str = "AerospaceNU SillyGoose";
168
169const CLOCK: &str = "timestampMs";
171
172const MARKS: [&str; 2] = ["pressurePa", "altitudeM"];
174
175const CONFIG: &str = "CONFIG";
177
178pub(crate) const ALTITUDE_STEP_M: f64 = 0.01;
186
187const PAD_PA: (f64, f64) = (50_000.0, 110_000.0);
189
190const BAY_K: (f64, f64) = (233.15, 333.15);
192
193const VOLTS_MAX: f64 = 20.0;
196
197const GRAVITY_MARGIN: f64 = 0.1;
199
200const GRAVITY_LEAST_S: f64 = 1.0;
202
203const GRAVITY_LEAD: f64 = 2.0;
205
206const GRAVITY_STEP_MAX_S: f64 = 5.0;
210
211pub const MAX_COLUMNS: usize = 256;
213
214const FAST_STEP_S: f64 = 0.05;
217
218const TURN_STEPS: usize = 10;
220
221const TURN_GRAVITY_MARGIN: f64 = 0.15;
223
224const TURN_LEAST_RAD: f64 = 0.2;
227
228const TURN_LEAST_STRETCHES: usize = 3;
230
231const TURN_FACTOR: f64 = 4.0;
234
235const RATE_MAX_RAD_S: f64 = 20_000.0 * PI / 180.0;
238
239const CHECK_CLIMB_M: f64 = 10.0;
243
244const CLIMB_MARGIN: f64 = 0.25;
247
248const SPEED_MARGIN: f64 = 0.25;
250
251const SPEED_LEAST_M: f64 = 10.0;
253
254const GROUND_OFF_M: f64 = 100.0;
257
258const STILL_CLIMB_M: f64 = 100.0;
260
261const MAX_EVENTS: usize = 1_000;
263
264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266enum Role {
267 Pressure,
268 Temperature,
270 Accel(usize),
272 Gyro(usize),
274 ImuTemperature,
276 Battery,
277 Altitude,
279 Speed,
281 Estimate,
283 Unfiltered,
285 State,
287 Continuity,
289 Fired,
291 Tilt,
292 AngularVelocity,
293 Quaternion,
294 Unknown,
295}
296
297const KNOWN: [(&str, Role); 27] = [
299 ("pressurePa", Role::Pressure),
300 ("tempK", Role::Temperature),
301 ("accelX", Role::Accel(0)),
302 ("accelY", Role::Accel(1)),
303 ("accelZ", Role::Accel(2)),
304 ("gyroX", Role::Gyro(0)),
305 ("gyroY", Role::Gyro(1)),
306 ("gyroZ", Role::Gyro(2)),
307 ("imuTemp", Role::ImuTemperature),
308 ("battV", Role::Battery),
309 ("altitudeM", Role::Altitude),
310 ("velocityMS", Role::Speed),
311 ("accelerationMSS", Role::Estimate),
312 ("unfiltAlt", Role::Unfiltered),
313 ("flightState", Role::State),
314 ("drogueCont", Role::Continuity),
315 ("mainCont", Role::Continuity),
316 ("drogueFired", Role::Fired),
317 ("mainFired", Role::Fired),
318 ("tiltMagnitudeDeg", Role::Tilt),
319 ("angularVelRadS_x", Role::AngularVelocity),
320 ("angularVelRadS_y", Role::AngularVelocity),
321 ("angularVelRadS_z", Role::AngularVelocity),
322 ("quaternion_a", Role::Quaternion),
323 ("quaternion_b", Role::Quaternion),
324 ("quaternion_c", Role::Quaternion),
325 ("quaternion_d", Role::Quaternion),
326];
327
328fn role_of(name: &str) -> Role {
330 KNOWN
331 .iter()
332 .find(|(known, _)| known.eq_ignore_ascii_case(name))
333 .map_or(Role::Unknown, |(_, role)| *role)
334}
335
336fn cells(line: &str, tabs: bool) -> Box<dyn Iterator<Item = &str> + '_> {
338 if tabs {
339 Box::new(line.split('\t').map(str::trim))
340 } else {
341 Box::new(line.split_whitespace())
342 }
343}
344
345fn is_header(line: &str) -> bool {
348 let mut names = cells(line, line.contains('\t'));
349 if !names
350 .next()
351 .is_some_and(|first| first.eq_ignore_ascii_case(CLOCK))
352 {
353 return false;
354 }
355 let mut seen = [false; MARKS.len()];
356 for name in names {
357 for (mark, seen) in MARKS.iter().zip(&mut seen) {
358 *seen |= name.eq_ignore_ascii_case(mark);
359 }
360 if seen.iter().all(|seen| *seen) {
361 return true;
362 }
363 }
364 false
365}
366
367fn is_config(line: &str) -> bool {
369 cells(line, line.contains('\t')).next() == Some(CONFIG)
370}
371
372pub fn recognizes(text: &str) -> bool {
375 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
376 let mut lines = text
377 .split(['\r', '\n'])
378 .map(str::trim)
379 .filter(|line| !line.is_empty());
380 match lines.next() {
381 Some(first) if is_config(first) => lines.next().is_some_and(is_header),
382 Some(first) => is_header(first),
383 None => false,
384 }
385}
386
387struct Column {
389 name: String,
390 role: Role,
391 values: Vec<f64>,
393 quantity: Quantity,
395 scale: f64,
397}
398
399impl Column {
400 fn new(name: &str) -> Self {
402 let role = role_of(name);
403 let (quantity, scale) = match role {
404 Role::Pressure => (Quantity::Pressure, 1.0),
405 Role::Temperature | Role::ImuTemperature => (Quantity::Temperature, 1.0),
406 Role::Accel(_) | Role::Estimate => (Quantity::Acceleration, 1.0),
407 Role::Gyro(_) => (Quantity::AngularRate, 1.0),
408 Role::AngularVelocity => (Quantity::AngularRate, 180.0 / PI),
409 Role::Battery => (Quantity::Voltage, 1.0),
410 Role::Altitude | Role::Unfiltered => (Quantity::AltitudeAboveGround, 1.0),
411 Role::Speed => (Quantity::Speed, 1.0),
412 Role::Tilt => (Quantity::Angle, 1.0),
413 Role::State | Role::Continuity | Role::Fired | Role::Quaternion => {
414 (Quantity::Number, 1.0)
415 }
416 Role::Unknown => (Quantity::Unrecognized, 1.0),
417 };
418 Self {
419 name: name.to_owned(),
420 role,
421 values: Vec::new(),
422 quantity,
423 scale,
424 }
425 }
426
427 fn keep(&mut self) {
429 self.quantity = Quantity::Unrecognized;
430 self.scale = 1.0;
431 }
432
433 fn quoted(&self) -> String {
435 format!("`{}`", short(&self.name))
436 }
437
438 fn range(&self) -> Option<(f64, f64)> {
440 let mut finite = self.values.iter().copied().filter(|v| v.is_finite());
441 let first = finite.next()?;
442 Some(finite.fold((first, first), |(lo, hi), v| (lo.min(v), hi.max(v))))
443 }
444}
445
446pub fn read(text: &str) -> Result<FlightLog, LogError> {
457 let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
458 let Some(first) = lines.next() else {
459 return Err(not_this("the file is empty".to_owned()));
460 };
461 let (config, (header_line, header)) = if is_config(first.1.trim()) {
462 let Some(next) = lines.next() else {
463 return Err(not_this(
464 "the file holds a `CONFIG` line and nothing after it".to_owned(),
465 ));
466 };
467 (Some(first.1.trim()), next)
468 } else {
469 (None, first)
470 };
471 let header = header.trim();
472 if !is_header(header) {
473 return Err(not_this(format!(
474 "its header, {:?}, isn't a SillyGoose log's: `timestampMs` first, then names such as \
475 `pressurePa` and `altitudeM`",
476 short(header)
477 )));
478 }
479 let tabs = header.contains('\t');
480
481 let mut columns: Vec<Column> = Vec::new();
482 let mut seen: BTreeSet<String> = BTreeSet::new();
483 for (index, name) in cells(header, tabs).enumerate() {
484 if index >= MAX_COLUMNS {
485 return Err(syntax(
486 header_line,
487 format!("the header names more than {MAX_COLUMNS} columns"),
488 ));
489 }
490 if name.is_empty() {
491 return Err(syntax(
492 header_line,
493 format!("the header's column {} has no name", index + 1),
494 ));
495 }
496 if !seen.insert(name.to_ascii_lowercase()) {
497 return Err(syntax(
498 header_line,
499 format!("the header names {:?} twice", short(name)),
500 ));
501 }
502 if index > 0 {
503 columns.push(Column::new(name));
504 }
505 }
506 let width = columns.len() + 1;
507
508 let mut times: Vec<f64> = Vec::new();
509 let mut row_lines: Vec<usize> = Vec::new();
511 let mut gaps = 0usize;
512 let mut first_gap = None;
513 let mut short_rows = 0usize;
514 let mut first_short = None;
515 let mut cells_written = 0usize;
516 for (number_of_line, line) in lines {
517 let row: Vec<&str> = cells(line.trim_end(), tabs).take(width + 1).collect();
520 if row.len() > width {
521 return Err(syntax(
522 number_of_line,
523 format!("the row has more than {width} cells, where the header names {width}"),
524 ));
525 }
526 if row.len() < width {
527 short_rows += 1;
528 first_short.get_or_insert(number_of_line);
529 }
530 cells_written = cells_written.saturating_add(row.len());
531 let mut value_at = |index: usize| match row.get(index) {
532 Some(cell) => number(cell, false).unwrap_or_else(|| {
533 gaps += 1;
534 first_gap.get_or_insert(number_of_line);
535 f64::NAN
536 }),
537 None => f64::NAN,
538 };
539 times.push(value_at(0) / 1_000.0);
540 row_lines.push(number_of_line);
541 for (index, column) in columns.iter_mut().enumerate() {
542 column.values.push(value_at(index + 1));
543 }
544 if crate::log::too_sparse(width, times.len(), cells_written) {
545 return Err(syntax(
546 number_of_line,
547 format!(
548 "{} rows hold {cells_written} of the {} cells the header's {width} columns \
549 name: too few for the header to be this file's",
550 times.len(),
551 times.len().saturating_mul(width)
552 ),
553 ));
554 }
555 }
556 if !times.iter().any(|time| time.is_finite()) {
557 return Err(LogError::NoData { format: FORMAT });
558 }
559 let Some(primary) = columns.iter().position(|c| c.role == Role::Altitude) else {
560 return Err(syntax(
562 header_line,
563 "the file has no `altitudeM`".to_owned(),
564 ));
565 };
566
567 let mut decisions: Vec<String> = Vec::new();
568 let pressure_pa = decide_pressure(&mut columns, &mut decisions);
569 decide_temperatures(&mut columns, &mut decisions);
570 let gravity = decide_accelerometer(&mut columns, ×, &mut decisions);
571 decide_gyroscope(&mut columns, ×, gravity, &mut decisions);
572 decide_by_range(&mut columns, &mut decisions);
573 decide_altitudes(&mut columns, pressure_pa, header_line, &mut decisions)?;
574 decide_speed(&mut columns, ×, &mut decisions);
575 let mut unknown_notes = Notes::default();
577 for column in &columns {
578 if column.role == Role::Unknown {
579 unknown_notes.push(format!(
580 "the column {} isn't one this reader knows; its values are kept as written",
581 column.quoted()
582 ));
583 }
584 }
585 decisions.extend(unknown_notes.into_vec());
586
587 let (logger, firmware, config_note) = settings(config);
588
589 let mut channels: Vec<Channel> = Vec::with_capacity(columns.len());
592 for column in &columns {
593 let mut values = Vec::with_capacity(column.values.len());
594 for (line, value) in row_lines.iter().zip(&column.values) {
595 values.push(finite(value * column.scale, FORMAT, *line, &column.name)?);
596 }
597 channels.push(Channel {
598 column: column.name.clone(),
599 quantity: column.quantity,
600 time_s: times.clone(),
601 values,
602 });
603 }
604
605 let mut events = Vec::new();
607 let mut events_left_out = 0usize;
608 for column in columns.iter().filter(|c| c.role == Role::Fired) {
609 let mut before: Option<f64> = None;
610 for (value, time) in column.values.iter().zip(×) {
611 if !value.is_finite() {
612 continue;
613 }
614 if before == Some(0.0) && *value == 1.0 && time.is_finite() {
615 if events.len() < MAX_EVENTS {
616 events.push(Event {
617 time_s: *time,
618 name: column.name.clone(),
619 });
620 } else {
621 events_left_out += 1;
622 }
623 }
624 before = Some(*value);
625 }
626 }
627 events.sort_by(|a, b| a.time_s.total_cmp(&b.time_s));
628
629 let mut order: Vec<usize> = (0..times.len()).filter(|&i| times[i].is_finite()).collect();
631 let untimed = times.len() - order.len();
632 let backwards = order
633 .windows(2)
634 .filter(|pair| times[pair[1]] < times[pair[0]])
635 .count();
636 order.sort_by(|&a, &b| times[a].total_cmp(×[b]));
637 let before = order.len();
638 order.dedup_by(|later, earlier| times[*later] == times[*earlier]);
639 let repeats = before - order.len();
640 let on_track = |index: usize| -> Vec<f64> {
641 order
642 .iter()
643 .map(|&row| channels[index].values[row])
644 .collect()
645 };
646 let time_s: Vec<f64> = order.iter().map(|&row| times[row]).collect();
647 let altitude_m = on_track(primary);
648 let track_of = |role: Role, quantity: Quantity| {
649 columns
650 .iter()
651 .position(|c| c.role == role && c.quantity == quantity)
652 .map(on_track)
653 };
654 let vertical_speed_m_s = track_of(Role::Speed, Quantity::Speed);
655 let temperature_k = track_of(Role::Temperature, Quantity::Temperature);
656 let battery_v = track_of(Role::Battery, Quantity::Voltage);
657
658 let mut notes = decisions;
659 notes.extend(config_note);
660 if backwards > 0 || repeats > 0 || untimed > 0 {
661 notes.push(format!(
662 "the clock goes back {backwards} times and repeats a time {repeats} times, and \
663 {untimed} samples have no time. The record's track takes the samples in time order, \
664 the first at each time, and leaves out those without one. The channels keep them all"
665 ));
666 }
667 if let Some(ground) = altitude_m.iter().copied().find(|v| v.is_finite())
668 && ground.abs() > GROUND_OFF_M
669 {
670 notes.push(format!(
671 "`{}` reads {ground:.2} m at the track's first sample, not near zero. The record \
672 starts away from the board's zero, as a log after a restart in flight does",
673 short(&columns[primary].name)
674 ));
675 }
676 notes.extend(still_temperature(&columns, primary));
677 let mut line_notes = Notes::default();
678 if gaps > 0 {
679 line_notes.push(format!(
680 "{gaps} cells, the first on line {}, are empty or not numbers: each is a gap",
681 first_gap.unwrap_or(header_line)
682 ));
683 }
684 if short_rows > 0 {
685 line_notes.push(format!(
686 "{short_rows} rows, the first on line {}, hold fewer cells than the header names: the \
687 cells they leave out are gaps",
688 first_short.unwrap_or(header_line)
689 ));
690 }
691 if events_left_out > 0 {
692 line_notes.push(format!(
693 "and {events_left_out} more rises of the fired flags, left out of the events so that \
694 the list stays short"
695 ));
696 }
697 notes.extend(line_notes.into_vec());
698
699 Ok(FlightLog {
700 format: LogFormat::SillyGooseText,
701 logger,
702 serial_number: None,
703 firmware,
704 flight_number: None,
705 stated: Stated::default(),
706 time_s,
707 altitude_m,
708 vertical_speed_m_s,
709 temperature_k,
710 battery_v,
711 channels,
712 events,
713 notes,
714 })
715}
716
717fn find(columns: &[Column], role: Role) -> Option<usize> {
719 columns.iter().position(|c| c.role == role)
720}
721
722fn decide_pressure(columns: &mut [Column], decisions: &mut Vec<String>) -> bool {
725 let Some(at) = find(columns, Role::Pressure) else {
726 return false;
727 };
728 let column = &mut columns[at];
729 match column.values.iter().copied().find(|v| v.is_finite()) {
730 Some(first) if (PAD_PA.0..=PAD_PA.1).contains(&first) => true,
731 first => {
732 let why = first.map_or_else(
733 || "it holds no number".to_owned(),
734 |first| {
735 format!(
736 "its first value, {first}, is no pressure near the ground in them \
737 (50,000 to 110,000 Pa)"
738 )
739 },
740 );
741 decisions.push(format!(
742 "{} kept as written: its name says pascals, but {why}",
743 column.quoted()
744 ));
745 column.keep();
746 false
747 }
748 }
749}
750
751fn bay_kelvin(column: &Column) -> bool {
754 column
755 .range()
756 .is_some_and(|(lo, hi)| lo >= BAY_K.0 && hi <= BAY_K.1)
757}
758
759fn not_kelvin(column: &Column) -> String {
761 match column.range() {
762 None => "it holds no number".to_owned(),
763 Some((lo, hi)) if lo == 0.0 && hi == 0.0 => {
764 "every value is exactly 0, no temperature in kelvin, and a placeholder rather than a \
765 reading in any unit"
766 .to_owned()
767 }
768 Some((lo, hi)) => format!(
769 "its values run from {lo} to {hi}, outside the 233.15 to 333.15 K (−40 to 60 °C) an \
770 electronics bay can have{}",
771 if lo < 0.0 {
772 ", and below 0 no temperature in kelvin can be"
773 } else {
774 ""
775 }
776 ),
777 }
778}
779
780fn decide_temperatures(columns: &mut [Column], decisions: &mut Vec<String>) {
783 for column in columns.iter_mut() {
784 match column.role {
785 Role::Temperature if !bay_kelvin(column) => {
786 decisions.push(format!(
787 "{} kept as written: its name says kelvin, but {}; nothing in the file says \
788 which unit it is in",
789 column.quoted(),
790 not_kelvin(column)
791 ));
792 column.keep();
793 }
794 Role::ImuTemperature => {
795 if let (true, Some((lo, hi))) = (bay_kelvin(column), column.range()) {
796 decisions.push(format!(
797 "{} read in kelvin, from the values: they run from {lo} to {hi}. That is within \
798 the 233.15 to 333.15 K an electronics bay can have. In degrees \
799 Celsius or Fahrenheit they would be hotter than any bay survives",
800 column.quoted()
801 ));
802 } else {
803 decisions.push(format!(
804 "{} kept as written: its name states no unit, and {}",
805 column.quoted(),
806 not_kelvin(column)
807 ));
808 column.keep();
809 }
810 }
811 _ => {}
812 }
813 }
814}
815
816fn axes(columns: &[Column], role: fn(usize) -> Role) -> Option<[usize; 3]> {
818 Some([
819 find(columns, role(0))?,
820 find(columns, role(1))?,
821 find(columns, role(2))?,
822 ])
823}
824
825fn vector(columns: &[Column], axes: [usize; 3], row: usize) -> [f64; 3] {
827 axes.map(|at| columns[at].values[row])
828}
829
830fn magnitude(v: [f64; 3]) -> f64 {
831 (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
832}
833
834fn listed_at(columns: &[Column], at: &[usize]) -> String {
836 let quoted: Vec<String> = at.iter().map(|&i| columns[i].quoted()).collect();
837 match quoted.as_slice() {
838 [] => String::new(),
839 [one] => one.clone(),
840 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
841 }
842}
843
844fn decide_accelerometer(
847 columns: &mut [Column],
848 times: &[f64],
849 decisions: &mut Vec<String>,
850) -> Option<f64> {
851 let axes = axes(columns, Role::Accel)?;
852 let mut in_ms2 = 0.0;
853 let mut in_g = 0.0;
854 for row in 0..times.len().saturating_sub(1) {
855 let step = times[row + 1] - times[row];
856 let reading = magnitude(vector(columns, axes, row));
857 if !(step > 0.0 && step.is_finite() && reading.is_finite()) {
858 continue;
859 }
860 let weight = step.min(GRAVITY_STEP_MAX_S);
861 if (reading - STANDARD_GRAVITY_MPS2).abs() <= GRAVITY_MARGIN * STANDARD_GRAVITY_MPS2 {
862 in_ms2 += weight;
863 }
864 if (reading - 1.0).abs() <= GRAVITY_MARGIN {
865 in_g += weight;
866 }
867 }
868 let names = listed_at(columns, &axes);
869 let evidence = format!(
870 "the three axes' magnitude reads within 10% of 9.806 65 for {in_ms2:.1} s of the file's \
871 time. It reads within 10% of 1 for {in_g:.1} s. A board at rest or under a parachute \
872 reads 1 g. The unit whose 1 g lasts at least 1 s and twice as long as the other's is \
873 taken"
874 );
875 let decided = if in_ms2 >= GRAVITY_LEAST_S && in_ms2 >= GRAVITY_LEAD * in_g {
876 decisions.push(format!(
877 "{names} read in meters per second squared, from the pad's gravity: {evidence}"
878 ));
879 Some((STANDARD_GRAVITY_MPS2, 1.0))
880 } else if in_g >= GRAVITY_LEAST_S && in_g >= GRAVITY_LEAD * in_ms2 {
881 decisions.push(format!(
882 "{names} read in standard gravities, × 9.806 65 m/s², from the pad's gravity: \
883 {evidence}"
884 ));
885 Some((1.0, STANDARD_GRAVITY_MPS2))
886 } else {
887 decisions.push(format!(
888 "{names} kept as written: the pad's gravity doesn't settle their unit: {evidence}"
889 ));
890 None
891 };
892 for at in axes {
893 match decided {
894 Some((_, scale)) => columns[at].scale = scale,
895 None => columns[at].keep(),
896 }
897 }
898 decided.map(|(one_g, _)| one_g)
899}
900
901#[derive(Debug, Clone, Copy, PartialEq)]
903struct Turning {
904 stretches: usize,
906 accelerometer_rad: f64,
908 gyroscope_rad: f64,
910}
911
912fn turning(
915 columns: &[Column],
916 times: &[f64],
917 accel: [usize; 3],
918 gyro: [usize; 3],
919 one_g: f64,
920) -> Turning {
921 let mut found = Turning {
922 stretches: 0,
923 accelerometer_rad: 0.0,
924 gyroscope_rad: 0.0,
925 };
926 let near_g = |row: usize| {
927 let reading = magnitude(vector(columns, accel, row));
928 reading.is_finite() && (reading - one_g).abs() <= TURN_GRAVITY_MARGIN * one_g
929 };
930 let fast = |row: usize| {
931 let step = times[row + 1] - times[row];
932 step > 0.0
933 && step <= FAST_STEP_S
934 && vector(columns, gyro, row).iter().all(|v| v.is_finite())
935 };
936 let direction = |row: usize| {
937 let a = vector(columns, accel, row);
938 let m = magnitude(a);
939 a.map(|v| v / m)
940 };
941 let mut start = 0;
942 while start + TURN_STEPS < times.len() {
943 let end = start + TURN_STEPS;
944 if !((start..end).all(fast) && (start..=end).all(near_g)) {
945 start += 1;
946 continue;
947 }
948 let (from, to) = (direction(start), direction(end));
949 let cosine = (from[0] * to[0] + from[1] * to[1] + from[2] * to[2]).clamp(-1.0, 1.0);
950 let mut gyroscope = 0.0;
951 for row in start..end {
952 let w = vector(columns, gyro, row);
953 let a = direction(row);
954 let across = [
955 w[1] * a[2] - w[2] * a[1],
956 w[2] * a[0] - w[0] * a[2],
957 w[0] * a[1] - w[1] * a[0],
958 ];
959 gyroscope += magnitude(across) * (times[row + 1] - times[row]);
960 }
961 found.stretches += 1;
962 found.accelerometer_rad += cosine.acos();
963 found.gyroscope_rad += gyroscope;
964 start = end;
965 }
966 found
967}
968
969fn decide_gyroscope(
971 columns: &mut [Column],
972 times: &[f64],
973 one_g: Option<f64>,
974 decisions: &mut Vec<String>,
975) {
976 let Some(gyro) = axes(columns, Role::Gyro) else {
977 return;
978 };
979 let names = listed_at(columns, &gyro);
980 let accel = axes(columns, Role::Accel);
981 let (Some(accel), Some(one_g)) = (accel, one_g) else {
982 decisions.push(format!(
983 "{names} kept as written: their unit is decided from the accelerometer's gravity as \
984 the board turns. The file has no accelerometer read in a known unit"
985 ));
986 for at in gyro {
987 columns[at].keep();
988 }
989 return;
990 };
991 let found = turning(columns, times, accel, gyro, one_g);
992 let ratio = found.gyroscope_rad / found.accelerometer_rad;
993 let degrees = PI / 180.0;
994 let evidence = format!(
995 "over {} stretches of {TURN_STEPS} steps at most {FAST_STEP_S} s apart with the \
996 accelerometer within 15% of 1 g, its direction turns {:.3} rad. A board at rest or \
997 under a parachute reads so. Over the same stretches, the gyroscope's rates turn the \
998 board across that direction {:.3} rad read in radians per second, {:.3} rad read in \
999 degrees",
1000 found.stretches,
1001 found.accelerometer_rad,
1002 found.gyroscope_rad,
1003 found.gyroscope_rad * degrees
1004 );
1005 let within = |ratio: f64| (1.0 / TURN_FACTOR..=TURN_FACTOR).contains(&ratio);
1006 let enough =
1007 found.stretches >= TURN_LEAST_STRETCHES && found.accelerometer_rad >= TURN_LEAST_RAD;
1008 let scale = if enough && within(ratio) {
1009 decisions.push(format!(
1010 "{names} read in radians per second, from the board's turning: {evidence}. The unit \
1011 whose turn is within a quarter to 4 times the accelerometer's is taken"
1012 ));
1013 Some(180.0 / PI)
1014 } else if enough && within(ratio * degrees) {
1015 decisions.push(format!(
1016 "{names} read in degrees per second, from the board's turning: {evidence}. The unit \
1017 whose turn is within a quarter to 4 times the accelerometer's is taken"
1018 ));
1019 Some(1.0)
1020 } else {
1021 let why = if enough {
1022 "in neither unit is the gyroscope's turn within a quarter to 4 times the \
1023 accelerometer's"
1024 } else {
1025 "too little turning to tell, under 3 stretches or 0.2 rad"
1026 };
1027 decisions.push(format!(
1028 "{names} kept as written: the board's turning doesn't settle their unit, {why}: \
1029 {evidence}"
1030 ));
1031 None
1032 };
1033 for at in gyro {
1034 match scale {
1035 Some(scale) => columns[at].scale = scale,
1036 None => columns[at].keep(),
1037 }
1038 }
1039}
1040
1041fn decide_by_range(columns: &mut [Column], decisions: &mut Vec<String>) {
1044 let mut rates = Vec::new();
1045 let mut rates_beyond = None;
1046 for (at, column) in columns.iter_mut().enumerate() {
1047 let range = column.range();
1048 match column.role {
1049 Role::Battery => {
1050 if let Some((lo, hi)) = range.filter(|(lo, hi)| *lo < 0.0 || *hi > VOLTS_MAX) {
1051 decisions.push(format!(
1052 "{} kept as written: its name says volts, but its values run from {lo} \
1053 to {hi}. That is outside the 0 to 20 V a board's battery reads",
1054 column.quoted()
1055 ));
1056 column.keep();
1057 }
1058 }
1059 Role::Tilt => {
1060 if let Some((lo, hi)) = range.filter(|(lo, hi)| *lo < 0.0 || *hi > 180.0) {
1061 decisions.push(format!(
1062 "{} kept as written: its name says degrees, but its values run from {lo} \
1063 to {hi}, where a tilt's size lies within 0 to 180°",
1064 column.quoted()
1065 ));
1066 column.keep();
1067 }
1068 }
1069 Role::AngularVelocity => {
1070 rates.push(at);
1071 if let Some((lo, hi)) = range {
1072 let largest = lo.abs().max(hi.abs());
1073 if largest > RATE_MAX_RAD_S {
1074 rates_beyond = Some(rates_beyond.map_or(largest, |l: f64| l.max(largest)));
1075 }
1076 }
1077 }
1078 _ => {}
1079 }
1080 }
1081 if let Some(largest) = rates_beyond {
1082 decisions.push(format!(
1083 "{} kept as written: their names say radians per second, but they reach {largest}. \
1084 That is beyond the 20,000 °/s (349 rad/s) full scale of Analog Devices' ADXRS649. \
1085 That gyroscope is made for very high rates",
1086 listed_at(columns, &rates)
1087 ));
1088 for at in rates {
1089 columns[at].keep();
1090 }
1091 }
1092}
1093
1094#[derive(Debug, Clone, Copy, PartialEq)]
1096enum Climb {
1097 Unchecked(Option<f64>),
1099 Checked { pressure_m: f64, column: f64 },
1101}
1102
1103fn climb(columns: &[Column], pressure: Option<usize>, altitude: usize) -> Climb {
1106 let Some(pressure) = pressure else {
1107 return Climb::Unchecked(None);
1108 };
1109 let pairs = columns[pressure]
1110 .values
1111 .iter()
1112 .zip(&columns[altitude].values)
1113 .filter(|(p, a)| p.is_finite() && **p > 0.0 && a.is_finite());
1114 let mut first = None;
1115 let mut lowest: Option<(f64, f64)> = None;
1116 for (p, a) in pairs {
1117 first.get_or_insert((*p, *a));
1118 if lowest.is_none_or(|(low, _)| *p < low) {
1119 lowest = Some((*p, *a));
1120 }
1121 }
1122 let (Some(first), Some(lowest)) = (first, lowest) else {
1123 return Climb::Unchecked(None);
1124 };
1125 let atmosphere = Ussa76::standard();
1126 let Ok(pressure_m) = atmosphere
1127 .pressure_altitude_m(lowest.0)
1128 .and_then(|low| atmosphere.pressure_altitude_m(first.0).map(|pad| low - pad))
1129 else {
1130 return Climb::Unchecked(None);
1131 };
1132 if pressure_m < CHECK_CLIMB_M {
1133 return Climb::Unchecked(Some(pressure_m));
1134 }
1135 Climb::Checked {
1136 pressure_m,
1137 column: lowest.1 - first.1,
1138 }
1139}
1140
1141fn decide_altitudes(
1144 columns: &mut [Column],
1145 pressure_pa: bool,
1146 header_line: usize,
1147 decisions: &mut Vec<String>,
1148) -> Result<(), LogError> {
1149 let pressure = find(columns, Role::Pressure).filter(|_| pressure_pa);
1150 let within = |pressure_m: f64, column: f64| (column / pressure_m - 1.0).abs() <= CLIMB_MARGIN;
1151 let unchecked = |climb: Option<f64>| match climb {
1152 Some(climb) => format!(
1153 "the pressure climbs {climb:.2} m in the standard atmosphere, under the \
1154 {CHECK_CLIMB_M} m from which it checks an altitude's unit"
1155 ),
1156 None => "the file has no pressure in pascals to check it by".to_owned(),
1157 };
1158 if let Some(at) = find(columns, Role::Altitude) {
1159 match climb(columns, pressure, at) {
1160 Climb::Checked { pressure_m, column } if !within(pressure_m, column) => {
1161 return Err(LogError::Unit {
1162 format: FORMAT,
1163 line: header_line,
1164 message: format!(
1165 "{} climbs {column:.1} from the first sample to the one of lowest \
1166 pressure. The pressure's climb in the standard atmosphere is \
1167 {pressure_m:.1} m. The column's name says meters, but the two aren't within 25%",
1168 columns[at].quoted()
1169 ),
1170 });
1171 }
1172 Climb::Checked { .. } => {}
1173 Climb::Unchecked(climb) => decisions.push(format!(
1174 "{} read in meters, from its name: {}",
1175 columns[at].quoted(),
1176 unchecked(climb)
1177 )),
1178 }
1179 }
1180 if let Some(at) = find(columns, Role::Unfiltered) {
1181 match climb(columns, pressure, at) {
1182 Climb::Checked { pressure_m, column } if within(pressure_m, column) => {
1183 decisions.push(format!(
1184 "{} read in meters, from the pressure: from the first sample to the one of \
1185 lowest pressure it climbs {column:.1}. The standard atmosphere climbs \
1186 {pressure_m:.1} m, and the two are within 25%",
1187 columns[at].quoted()
1188 ));
1189 }
1190 Climb::Checked { pressure_m, column } => {
1191 decisions.push(format!(
1192 "{} kept as written: from the first sample to the one of lowest pressure it \
1193 climbs {column:.1}. The standard atmosphere climbs {pressure_m:.1} m, and \
1194 the two aren't within 25%",
1195 columns[at].quoted()
1196 ));
1197 columns[at].keep();
1198 }
1199 Climb::Unchecked(climb) => {
1200 decisions.push(format!(
1201 "{} kept as written: its name states no unit, and {}",
1202 columns[at].quoted(),
1203 unchecked(climb)
1204 ));
1205 columns[at].keep();
1206 }
1207 }
1208 }
1209 Ok(())
1210}
1211
1212fn decide_speed(columns: &mut [Column], times: &[f64], decisions: &mut Vec<String>) {
1215 let (Some(speed), Some(altitude)) = (find(columns, Role::Speed), find(columns, Role::Altitude))
1216 else {
1217 return;
1218 };
1219 let v = &columns[speed].values;
1220 let z = &columns[altitude].values;
1221 let (mut cross, mut square, mut moved) = (0.0, 0.0, 0.0);
1222 for row in 0..times.len().saturating_sub(1) {
1223 let step = times[row + 1] - times[row];
1224 let traveled = 0.5 * (v[row] + v[row + 1]) * step;
1225 let risen = z[row + 1] - z[row];
1226 if !(step > 0.0 && step <= FAST_STEP_S && traveled.is_finite() && risen.is_finite()) {
1227 continue;
1228 }
1229 cross += traveled * risen;
1230 square += traveled * traveled;
1231 moved += traveled.abs();
1232 }
1233 let name = columns[speed].quoted();
1234 if moved < SPEED_LEAST_M {
1235 decisions.push(format!(
1236 "{name} read in meters per second, from its name: over the steps at most \
1237 {FAST_STEP_S} s long it moves {moved:.1} m. That is under the {SPEED_LEAST_M} m from which \
1238 the altitude checks it"
1239 ));
1240 return;
1241 }
1242 let slope = cross / square;
1243 let within = (slope - 1.0).abs() <= SPEED_MARGIN;
1245 if !within {
1246 let found = if slope.is_finite() {
1247 format!("the altitude changes {slope:.3} times what it integrates to")
1248 } else {
1249 "the slope of the altitude's change on what it integrates to can't be computed, the \
1250 sums being too large to hold"
1251 .to_owned()
1252 };
1253 decisions.push(format!(
1254 "{name} kept as written: its name says meters per second, but over the steps at most \
1255 {FAST_STEP_S} s long {found}, not within 25% of once"
1256 ));
1257 columns[speed].keep();
1258 }
1259}
1260
1261fn still_temperature(columns: &[Column], primary: usize) -> Option<String> {
1264 let at = find(columns, Role::Temperature)?;
1265 let column = &columns[at];
1266 if column.quantity != Quantity::Temperature {
1267 return None;
1268 }
1269 let (lo, hi) = column.range()?;
1270 let samples = column.values.iter().filter(|v| v.is_finite()).count();
1271 let (low, high) = columns[primary].range()?;
1272 (lo == hi && samples >= 2 && high - low > STILL_CLIMB_M).then(|| {
1273 format!(
1274 "{} reads {lo} at every one of its {samples} samples while the altitude spans \
1275 {:.0} m. A board's sensor warms or cools in flight. So the file may be a replay of \
1276 recorded or made-up values rather than the board's own log",
1277 column.quoted(),
1278 high - low
1279 )
1280 })
1281}
1282
1283fn settings(config: Option<&str>) -> (String, Option<String>, Option<String>) {
1285 let mut logger = LOGGER.to_owned();
1286 let mut firmware = None;
1287 let Some(config) = config else {
1288 return (logger, firmware, None);
1289 };
1290 let mut others = 0usize;
1291 let mut first_other = None;
1292 for setting in cells(config, config.contains('\t')).skip(1) {
1293 let Some((key, value)) = setting.split_once('=') else {
1294 others += 1;
1295 continue;
1296 };
1297 let value = value.trim();
1298 match key.trim() {
1299 "BOARD_NAME" if !value.is_empty() => logger = short(value),
1300 "FIRMWARE_VERSION" if !value.is_empty() => firmware = Some(short(value)),
1301 key => {
1302 others += 1;
1303 first_other.get_or_insert_with(|| short(key));
1304 }
1305 }
1306 }
1307 let note = (others > 0).then(|| {
1308 format!(
1309 "the `CONFIG` line's {others} other settings{} are left out: no source gives their \
1310 meanings or units",
1311 first_other.map_or_else(String::new, |key| format!(", such as `{key}`,"))
1312 )
1313 });
1314 (logger, firmware, note)
1315}
1316
1317fn not_this(message: String) -> LogError {
1318 LogError::NotThisFormat {
1319 format: FORMAT,
1320 message,
1321 }
1322}
1323
1324fn syntax(line: usize, message: String) -> LogError {
1325 LogError::Syntax {
1326 format: FORMAT,
1327 line,
1328 message,
1329 }
1330}
1331
1332#[cfg(test)]
1333mod tests {
1334 use super::*;
1335
1336 const G: f64 = STANDARD_GRAVITY_MPS2;
1337 const FOOT_M: f64 = 0.3048;
1338
1339 const HEADER: &str = "timestampMs\tpressurePa\ttempK\taccelX\taccelY\taccelZ\tgyroX\tgyroY\t\
1340 gyroZ\timuTemp\tbattV\taltitudeM\tvelocityMS\taccelerationMSS\t\
1341 unfiltAlt\tflightState\tdrogueCont\tdrogueFired\tmainCont\tmainFired";
1342
1343 fn pressure_at(altitude_m: f64) -> f64 {
1346 101_325.0 * (1.0 - (300.0 + altitude_m) / 44_330.8).powf(1.0 / 0.190_263)
1347 }
1348
1349 #[derive(Debug, Clone, Copy)]
1352 struct Written {
1353 accel: f64,
1354 gyro: f64,
1355 altitude: f64,
1356 unfiltered: f64,
1357 speed: f64,
1358 pressure: f64,
1359 temp: f64,
1360 imu_temp: f64,
1361 battery: f64,
1362 turning: bool,
1363 }
1364
1365 impl Default for Written {
1366 fn default() -> Self {
1367 Self {
1368 accel: 1.0,
1369 gyro: 1.0,
1370 altitude: 1.0,
1371 unfiltered: 1.0,
1372 speed: 1.0,
1373 pressure: 1.0,
1374 temp: 290.15,
1375 imu_temp: 293.15,
1376 battery: 4.0,
1377 turning: true,
1378 }
1379 }
1380 }
1381
1382 struct Sample {
1384 t_ms: f64,
1385 altitude_m: f64,
1386 speed_m_s: f64,
1387 accel: [f64; 3],
1388 gyro: [f64; 3],
1389 drogue: u8,
1390 main: u8,
1391 }
1392
1393 fn samples(turning: bool) -> Vec<Sample> {
1397 let mut out = Vec::new();
1398 for k in 0..4 {
1399 out.push(Sample {
1400 t_ms: 1_000.0 + 5_000.0 * f64::from(k),
1401 altitude_m: 0.0,
1402 speed_m_s: 0.0,
1403 accel: [0.0, 0.0, G],
1404 gyro: [0.0; 3],
1405 drogue: 0,
1406 main: 0,
1407 });
1408 }
1409 for k in 1..=20 {
1410 let tau = 0.05 * f64::from(k);
1411 out.push(Sample {
1412 t_ms: 16_000.0 + 50.0 * f64::from(k),
1413 altitude_m: 40.0 * tau * tau,
1414 speed_m_s: 80.0 * tau,
1415 accel: [0.0, 0.0, 7.0 * G],
1416 gyro: [0.0; 3],
1417 drogue: 0,
1418 main: 0,
1419 });
1420 }
1421 let rate = if turning { 1.0 } else { 0.0 };
1422 for k in 0..60 {
1423 let tau = 0.02 * f64::from(k);
1424 let angle = rate * tau;
1425 out.push(Sample {
1426 t_ms: 21_000.0 + 20.0 * f64::from(k),
1427 altitude_m: 300.0 - 15.0 * tau,
1428 speed_m_s: -15.0,
1429 accel: [0.0, G * angle.sin(), G * angle.cos()],
1430 gyro: [rate, 0.0, 0.0],
1431 drogue: 1,
1432 main: 0,
1433 });
1434 }
1435 for k in 0..3 {
1436 out.push(Sample {
1437 t_ms: 60_000.0 + 5_000.0 * f64::from(k),
1438 altitude_m: 0.4,
1439 speed_m_s: 0.0,
1440 accel: [0.0, G, 0.0],
1441 gyro: [0.0; 3],
1442 drogue: 1,
1443 main: 1,
1444 });
1445 }
1446 out
1447 }
1448
1449 fn text(w: Written) -> String {
1451 let mut text = format!("{HEADER}\n");
1452 for (k, s) in samples(w.turning).into_iter().enumerate() {
1453 let a = s.accel.map(|v| v * w.accel);
1454 let g = s.gyro.map(|v| v * w.gyro);
1455 text.push_str(&format!(
1456 "{}\t{:.4}\t{:.3}\t{:.6}\t{:.6}\t{:.6}\t{:.6}\t{:.6}\t{:.6}\t{}\t{}\t{:.3}\t{:.3}\t\
1457 0.00\t{:.3}\t0\t1\t{}\t1\t{}\n",
1458 s.t_ms,
1459 pressure_at(s.altitude_m) * w.pressure,
1460 w.temp + 0.001 * k as f64,
1461 a[0],
1462 a[1],
1463 a[2],
1464 g[0],
1465 g[1],
1466 g[2],
1467 w.imu_temp,
1468 w.battery,
1469 s.altitude_m * w.altitude,
1470 s.speed_m_s * w.speed,
1471 (300.0 + s.altitude_m) * w.unfiltered,
1472 s.drogue,
1473 s.main
1474 ));
1475 }
1476 text
1477 }
1478
1479 fn text_with_temperature(temperature: impl Fn(usize) -> f64) -> String {
1481 let text = text(Written::default());
1482 let mut lines = text.lines();
1483 let mut out = format!("{}\n", lines.next().unwrap_or_default());
1484 for (k, line) in lines.enumerate() {
1485 let mut cells: Vec<String> = line.split('\t').map(str::to_owned).collect();
1486 cells[2] = format!("{}", temperature(k));
1487 out.push_str(&cells.join("\t"));
1488 out.push('\n');
1489 }
1490 out
1491 }
1492
1493 fn channel<'a>(log: &'a FlightLog, column: &str) -> &'a Channel {
1494 log.channels
1495 .iter()
1496 .find(|c| c.column == column)
1497 .unwrap_or_else(|| panic!("no {column}"))
1498 }
1499
1500 fn values<'a>(log: &'a FlightLog, column: &str) -> &'a [f64] {
1501 &channel(log, column).values
1502 }
1503
1504 fn quantity(log: &FlightLog, column: &str) -> Quantity {
1505 channel(log, column).quantity
1506 }
1507
1508 fn note<'a>(log: &'a FlightLog, start: &str) -> &'a str {
1509 let matching: Vec<&String> = log.notes.iter().filter(|n| n.starts_with(start)).collect();
1510 assert_eq!(matching.len(), 1, "{start}: {:?}", log.notes);
1511 matching[0]
1512 }
1513
1514 fn has_note(log: &FlightLog, start: &str) -> bool {
1515 log.notes.iter().any(|n| n.starts_with(start))
1516 }
1517
1518 fn counted(note: &str) -> Option<&str> {
1521 let (decision, _) = note.split_once(": ")?;
1522 (decision.starts_with('`')
1523 && (decision.contains("` read in ") || decision.contains("` kept as written")))
1524 .then_some(decision)
1525 }
1526
1527 fn close(a: f64, b: f64) -> bool {
1528 (a - b).abs() <= 1e-9 * b.abs().max(1.0)
1529 }
1530
1531 #[test]
1532 fn recognizes_the_header_and_nothing_like_it() {
1533 assert!(recognizes(&format!("\u{feff}\r\n{HEADER}\r\n1\t2\n")));
1534 assert!(recognizes(&HEADER.replace('\t', " ")));
1535 assert!(recognizes("TIMESTAMPMS altitudeM PRESSUREPA\n"));
1536 assert!(recognizes(&format!("CONFIG\tBOARD_NAME=x\n\n{HEADER}\n")));
1537 for other in [
1538 "",
1539 "timestampMs\tpressurePa\n",
1540 "timestampMs,pressurePa,altitudeM\n",
1541 "time\tpressurePa\taltitudeM\n",
1542 "timestamp_ms,pressurePa,altitudeM\n",
1543 "CONFIG\tconverted_from=x\n6098809,0,302.7,-2.8\n",
1544 "CONFIG\tBOARD_NAME=x\n",
1545 "time,pressure,Pressure AGL,time,launch detect\n",
1546 "# MET Acc Vel iAlt pAlt\n",
1547 ] {
1548 assert!(!recognizes(other), "{other:?}");
1549 }
1550 assert!(!recognizes(&format!("a note\n{HEADER}\n")));
1552 }
1553
1554 #[test]
1555 fn reads_an_invented_flight_in_si() {
1556 let log = read(&text(Written::default())).unwrap();
1557 assert_eq!(log.format, LogFormat::SillyGooseText);
1558 assert_eq!(log.logger, LOGGER);
1559 assert_eq!(log.time_s.len(), 87);
1560 assert_eq!(log.time_s[0], 1.0);
1561 assert_eq!(log.channels.len(), 19);
1562 assert!(log.channels.iter().all(|c| c.time_s.len() == 87));
1563 assert_eq!(quantity(&log, "pressurePa"), Quantity::Pressure);
1564 assert_eq!(quantity(&log, "accelZ"), Quantity::Acceleration);
1565 assert_eq!(quantity(&log, "gyroX"), Quantity::AngularRate);
1566 assert_eq!(quantity(&log, "flightState"), Quantity::Number);
1567 assert!(close(values(&log, "accelZ")[0], G));
1568 assert!(close(values(&log, "gyroX")[30], 180.0 / PI));
1570 let top = log.altitude_m.iter().copied().fold(f64::MIN, f64::max);
1571 assert_eq!(top, 300.0);
1572 assert_eq!(log.vertical_speed_m_s.as_ref().unwrap()[10], 28.0);
1573 assert_eq!(log.temperature_k.as_ref().unwrap()[0], 290.15);
1574 assert_eq!(log.battery_v.as_ref().unwrap()[0], 4.0);
1575 let events: Vec<(f64, &str)> = log
1576 .events
1577 .iter()
1578 .map(|e| (e.time_s, e.name.as_str()))
1579 .collect();
1580 assert_eq!(events, [(21.0, "drogueFired"), (60.0, "mainFired")]);
1581 for note in log.notes.iter().filter(|n| n.starts_with('`')) {
1583 assert!(counted(note).is_some(), "{note}");
1584 }
1585 assert!(log.notes.iter().all(|n| !n.contains("assum")));
1586 }
1587
1588 #[test]
1591 fn the_accelerometer_s_unit_is_decided_by_the_pad_s_gravity_both_ways() {
1592 let in_ms2 = read(&text(Written::default())).unwrap();
1593 let in_g = read(&text(Written {
1594 accel: 1.0 / G,
1595 ..Written::default()
1596 }))
1597 .unwrap();
1598 note(
1599 &in_ms2,
1600 "`accelX`, `accelY` and `accelZ` read in meters per second squared, from the pad's \
1601 gravity: ",
1602 );
1603 note(
1604 &in_g,
1605 "`accelX`, `accelY` and `accelZ` read in standard gravities, × 9.806 65 m/s², from \
1606 the pad's gravity: ",
1607 );
1608 for (a, b) in values(&in_g, "accelZ")
1609 .iter()
1610 .zip(values(&in_ms2, "accelZ"))
1611 {
1612 assert!((a - b).abs() < 1e-5, "{a} {b}");
1613 }
1614 assert!(close(values(&in_g, "accelZ")[0], G));
1615 assert_eq!(quantity(&in_g, "gyroX"), Quantity::AngularRate);
1617
1618 let neither = read(&text(Written {
1621 accel: 0.5,
1622 ..Written::default()
1623 }))
1624 .unwrap();
1625 assert_eq!(quantity(&neither, "accelX"), Quantity::Unrecognized);
1626 assert!(close(values(&neither, "accelZ")[0], 0.5 * G));
1627 note(
1628 &neither,
1629 "`accelX`, `accelY` and `accelZ` kept as written: ",
1630 );
1631 assert!(
1632 note(&neither, "`gyroX`, `gyroY` and `gyroZ` kept as written: ")
1633 .contains("no accelerometer read in a known unit")
1634 );
1635 }
1636
1637 #[test]
1640 fn the_pad_s_gravity_weighs_each_reading_by_its_time() {
1641 let mut text = format!("{HEADER}\n");
1642 for t in (0..=24).map(|k| 5_000.0 * f64::from(k)) {
1643 text.push_str(&format!(
1644 "{t}\t97772\t290\t0\t0\t{G}\t0\t0\t0\t293\t4\t0\t0\t0\t300\t0\t0\t0\t0\t0\n"
1645 ));
1646 }
1647 for k in 1..=300 {
1648 let t = 120_000.0 + 10.0 * f64::from(k);
1649 text.push_str(&format!(
1650 "{t}\t97772\t290\t0\t0\t1.0\t0\t0\t0\t293\t4\t0\t0\t0\t300\t0\t0\t0\t0\t0\n"
1651 ));
1652 }
1653 let log = read(&text).unwrap();
1654 assert!(
1655 note(
1656 &log,
1657 "`accelX`, `accelY` and `accelZ` read in meters per second squared"
1658 )
1659 .contains("within 10% of 9.806 65 for 120.0 s of the file's time. It reads within 10% of 1 for 3.0 s"),
1660 "{:?}",
1661 log.notes
1662 );
1663 }
1664
1665 #[test]
1669 fn a_jump_of_the_clock_counts_for_at_most_5_s_of_gravity() {
1670 let mut text = format!("{HEADER}\n");
1671 let row = |t: f64, z: f64| {
1672 format!("{t}\t97772\t290\t0\t0\t{z}\t0\t0\t0\t293\t4\t0\t0\t0\t300\t0\t0\t0\t0\t0\n")
1673 };
1674 for k in 0..6 {
1675 text.push_str(&row(5_000.0 * f64::from(k), G));
1676 }
1677 text.push_str(&row(30_000.0, 1.0));
1678 text.push_str(&row(630_000.0, G));
1679 text.push_str(&row(635_000.0, G));
1680 let log = read(&text).unwrap();
1681 assert!(
1682 note(
1683 &log,
1684 "`accelX`, `accelY` and `accelZ` read in meters per second squared"
1685 )
1686 .contains(
1687 "within 10% of 9.806 65 for 35.0 s of the file's time. It reads within 10% of 1 for 5.0 s"
1688 ),
1689 "{:?}",
1690 log.notes
1691 );
1692 assert!(close(values(&log, "accelZ")[0], G));
1693 }
1694
1695 #[test]
1698 fn the_gyroscope_s_unit_is_decided_by_the_board_s_turning_both_ways() {
1699 let radians = read(&text(Written::default())).unwrap();
1700 let degrees = read(&text(Written {
1701 gyro: 180.0 / PI,
1702 ..Written::default()
1703 }))
1704 .unwrap();
1705 assert!(
1706 note(
1707 &radians,
1708 "`gyroX`, `gyroY` and `gyroZ` read in radians per second, from the board's \
1709 turning: "
1710 )
1711 .contains("over 5 stretches")
1712 );
1713 note(
1714 °rees,
1715 "`gyroX`, `gyroY` and `gyroZ` read in degrees per second, from the board's turning: ",
1716 );
1717 for (a, b) in values(&radians, "gyroX")
1718 .iter()
1719 .zip(values(°rees, "gyroX"))
1720 {
1721 assert!((a - b).abs() < 1e-4, "{a} {b}");
1722 }
1723 assert!(close(values(&radians, "gyroX")[30], 180.0 / PI));
1724
1725 let still = read(&text(Written {
1727 turning: false,
1728 ..Written::default()
1729 }))
1730 .unwrap();
1731 assert_eq!(quantity(&still, "gyroX"), Quantity::Unrecognized);
1732 assert!(
1733 note(&still, "`gyroX`, `gyroY` and `gyroZ` kept as written: ")
1734 .contains("too little turning to tell")
1735 );
1736
1737 let off = read(&text(Written {
1740 gyro: 10.0,
1741 ..Written::default()
1742 }))
1743 .unwrap();
1744 assert_eq!(quantity(&off, "gyroX"), Quantity::Unrecognized);
1745 assert!(
1746 note(&off, "`gyroX`, `gyroY` and `gyroZ` kept as written: ")
1747 .contains("in neither unit")
1748 );
1749 }
1750
1751 #[test]
1752 fn the_turning_check_measures_a_known_turn() {
1753 let log_text = text(Written::default());
1754 let mut lines = numbered_lines(&log_text);
1755 let _ = lines.next();
1756 let mut columns: Vec<Column> = HEADER.split('\t').skip(1).map(Column::new).collect();
1757 let mut times = Vec::new();
1758 for (_, line) in lines {
1759 let mut cells = line
1760 .split('\t')
1761 .map(|c| c.parse::<f64>().unwrap_or(f64::NAN));
1762 times.push(cells.next().unwrap_or(f64::NAN) / 1_000.0);
1763 for (column, value) in columns.iter_mut().zip(cells) {
1764 column.values.push(value);
1765 }
1766 }
1767 let accel = axes(&columns, Role::Accel).unwrap();
1768 let gyro = axes(&columns, Role::Gyro).unwrap();
1769 let found = turning(&columns, ×, accel, gyro, G);
1770 assert_eq!(found.stretches, 5);
1772 assert!((found.accelerometer_rad - 1.0).abs() < 1e-5, "{found:?}");
1773 assert!((found.gyroscope_rad - 1.0).abs() < 1e-5, "{found:?}");
1774 }
1775
1776 #[test]
1777 fn temperatures_are_kelvin_only_where_the_values_bear_it_out() {
1778 let log = read(&text(Written::default())).unwrap();
1779 assert_eq!(quantity(&log, "tempK"), Quantity::Temperature);
1780 assert_eq!(quantity(&log, "imuTemp"), Quantity::Temperature);
1781 note(&log, "`imuTemp` read in kelvin, from the values: ");
1782 assert!(!has_note(&log, "`tempK`"), "{:?}", log.notes);
1783
1784 let refuted = read(&text(Written {
1785 temp: -9.0,
1786 imu_temp: 0.0,
1787 ..Written::default()
1788 }))
1789 .unwrap();
1790 assert_eq!(quantity(&refuted, "tempK"), Quantity::Unrecognized);
1791 assert!(refuted.temperature_k.is_none());
1792 assert_eq!(values(&refuted, "tempK")[0], -9.0);
1793 assert!(
1794 note(
1795 &refuted,
1796 "`tempK` kept as written: its name says kelvin, but "
1797 )
1798 .contains("below 0 no temperature in kelvin can be")
1799 );
1800 assert!(
1801 note(
1802 &refuted,
1803 "`imuTemp` kept as written: its name states no unit, and "
1804 )
1805 .contains("every value is exactly 0")
1806 );
1807
1808 let celsius = read(&text(Written {
1810 temp: 20.0,
1811 imu_temp: 22.5,
1812 ..Written::default()
1813 }))
1814 .unwrap();
1815 assert_eq!(quantity(&celsius, "tempK"), Quantity::Unrecognized);
1816 assert_eq!(quantity(&celsius, "imuTemp"), Quantity::Unrecognized);
1817 assert!(
1818 note(&celsius, "`tempK` kept as written: ")
1819 .contains("run from 20 to 20.086, outside the 233.15 to 333.15 K")
1820 );
1821 }
1822
1823 #[test]
1826 fn altitudes_are_checked_against_the_pressure() {
1827 match read(&text(Written {
1828 altitude: 1.0 / FOOT_M,
1829 ..Written::default()
1830 })) {
1831 Err(LogError::Unit {
1832 line: 1, message, ..
1833 }) => {
1834 assert!(message.contains("`altitudeM` climbs 984.3"), "{message}");
1835 assert!(message.contains("aren't within 25%"), "{message}");
1836 }
1837 other => panic!("{other:?}"),
1838 }
1839 let unfiltered = read(&text(Written {
1840 unfiltered: 1.0 / FOOT_M,
1841 ..Written::default()
1842 }))
1843 .unwrap();
1844 assert_eq!(quantity(&unfiltered, "unfiltAlt"), Quantity::Unrecognized);
1845 assert!(
1846 note(&unfiltered, "`unfiltAlt` kept as written: ")
1847 .contains("climbs 984.3. The standard atmosphere climbs 300.0 m")
1848 );
1849 let meters = read(&text(Written::default())).unwrap();
1850 assert_eq!(
1851 quantity(&meters, "unfiltAlt"),
1852 Quantity::AltitudeAboveGround
1853 );
1854 note(&meters, "`unfiltAlt` read in meters, from the pressure: ");
1855 assert!(!has_note(&meters, "`altitudeM`"));
1856 }
1857
1858 #[test]
1859 fn a_pressure_that_is_no_pad_s_in_pascals_is_kept_and_the_altitude_unchecked() {
1860 let hectopascals = read(&text(Written {
1861 pressure: 0.01,
1862 ..Written::default()
1863 }))
1864 .unwrap();
1865 assert_eq!(
1866 quantity(&hectopascals, "pressurePa"),
1867 Quantity::Unrecognized
1868 );
1869 assert!(
1870 note(
1871 &hectopascals,
1872 "`pressurePa` kept as written: its name says pascals, but "
1873 )
1874 .contains("(50,000 to 110,000 Pa)")
1875 );
1876 assert!(
1877 note(&hectopascals, "`altitudeM` read in meters, from its name: ")
1878 .contains("no pressure in pascals")
1879 );
1880 note(&hectopascals, "`unfiltAlt` kept as written: ");
1881 }
1882
1883 #[test]
1886 fn the_speed_is_checked_against_the_altitude() {
1887 let log = read(&text(Written::default())).unwrap();
1888 assert_eq!(quantity(&log, "velocityMS"), Quantity::Speed);
1889 assert!(!has_note(&log, "`velocityMS`"));
1890 let feet = read(&text(Written {
1891 speed: 1.0 / FOOT_M,
1892 ..Written::default()
1893 }))
1894 .unwrap();
1895 assert_eq!(quantity(&feet, "velocityMS"), Quantity::Unrecognized);
1896 assert!(feet.vertical_speed_m_s.is_none());
1897 assert!(note(&feet, "`velocityMS` kept as written: ").contains("0.305 times"));
1898 }
1899
1900 #[test]
1903 fn a_speed_whose_slope_cannot_be_computed_is_kept() {
1904 let mut text = "timestampMs\tpressurePa\taltitudeM\tvelocityMS\n".to_owned();
1905 for k in 0..50 {
1906 let (altitude, speed) = match k {
1907 20 => ("1e160", "1e160"),
1908 21 => ("0", "1e160"),
1909 _ => ("0", "0"),
1910 };
1911 text.push_str(&format!("{}\t0\t{altitude}\t{speed}\n", 10 * k));
1912 }
1913 let log = read(&text).unwrap();
1914 assert_eq!(quantity(&log, "velocityMS"), Quantity::Unrecognized);
1915 assert!(log.vertical_speed_m_s.is_none());
1916 let kept = note(&log, "`velocityMS` kept as written: ");
1917 assert!(kept.contains("can't be computed"), "{kept}");
1918 assert!(!kept.contains("NaN"), "{kept}");
1919 assert!(counted(kept).is_some());
1920 }
1921
1922 fn text_in_g_with(cell: usize, value: &str) -> String {
1924 let text = text(Written {
1925 accel: 1.0 / G,
1926 ..Written::default()
1927 });
1928 let mut lines = text.lines();
1929 let mut out = format!("{}\n", lines.next().unwrap_or_default());
1930 for (k, line) in lines.enumerate() {
1931 let mut cells: Vec<String> = line.split('\t').map(str::to_owned).collect();
1932 if k == 1 {
1933 cells[cell] = value.to_owned();
1934 }
1935 out.push_str(&cells.join("\t"));
1936 out.push('\n');
1937 }
1938 out
1939 }
1940
1941 #[test]
1944 fn a_value_its_conversion_makes_infinite_is_refused() {
1945 assert_eq!(
1946 read(&text_in_g_with(3, "-1.7e308"))
1947 .unwrap_err()
1948 .to_string(),
1949 "SillyGoose text line 3: the column accelX holds a value too large for its unit's \
1950 conversion to SI"
1951 );
1952 let log = read(&text_in_g_with(3, "1e307")).unwrap();
1954 assert_eq!(quantity(&log, "accelX"), Quantity::Acceleration);
1955 assert!(close(values(&log, "accelX")[1], 1e307 * G));
1956 }
1957
1958 #[test]
1961 fn a_value_its_conversion_makes_infinite_is_refused_for_the_gyroscope() {
1962 assert_eq!(
1963 read(&text_in_g_with(7, "1.7e308")).unwrap_err().to_string(),
1964 "SillyGoose text line 3: the column gyroY holds a value too large for its unit's \
1965 conversion to SI"
1966 );
1967 }
1968
1969 #[test]
1972 fn an_unknown_column_is_kept_and_its_notes_stay_few() {
1973 let names: Vec<String> = (0..30).map(|k| format!("extra_{k}")).collect();
1974 let text = format!(
1975 "timestampMs\tpressurePa\taltitudeM\t{}\n1000\t97772\t0\t{}\n",
1976 names.join("\t"),
1977 ["7"; 30].join("\t")
1978 );
1979 let log = read(&text).unwrap();
1980 assert_eq!(log.channels.len(), 32);
1981 assert_eq!(quantity(&log, "extra_29"), Quantity::Unrecognized);
1982 assert_eq!(values(&log, "extra_29"), [7.0]);
1983 let kept = log
1984 .notes
1985 .iter()
1986 .filter(|n| n.starts_with("the column `extra_"))
1987 .count();
1988 assert_eq!(kept, 20);
1989 note(&log, "and 10 more notes");
1990
1991 let names: Vec<String> = (0..MAX_COLUMNS - 3).map(|k| format!("c{k}")).collect();
1992 let widest = read(&format!(
1993 "timestampMs\tpressurePa\taltitudeM\t{}\n1000\t97772\t0\n",
1994 names.join("\t")
1995 ))
1996 .unwrap();
1997 assert_eq!(widest.channels.len(), MAX_COLUMNS - 1);
1998 assert!(widest.notes.len() <= 30, "{}", widest.notes.len());
1999 }
2000
2001 #[test]
2004 fn a_log_on_the_pad_reads_its_units_from_their_names() {
2005 let mut text = format!("{HEADER}\n");
2006 for k in 0..6 {
2007 let t = 1_000 + 5_000 * k;
2008 text.push_str(&format!(
2009 "{t}\t97772.5\t290.2\t0.01\t0.02\t9.79\t0.001\t0\t0\t293\t4.1\t0.{k}\t0.0\t0\t\
2010 300.{k}\t0\t0\t0\t0\t0\n"
2011 ));
2012 }
2013 let log = read(&text).unwrap();
2014 assert!(
2015 note(&log, "`altitudeM` read in meters, from its name: ")
2016 .contains("the pressure climbs 0.00 m")
2017 );
2018 note(
2019 &log,
2020 "`velocityMS` read in meters per second, from its name: ",
2021 );
2022 note(
2023 &log,
2024 "`unfiltAlt` kept as written: its name states no unit, and ",
2025 );
2026 note(&log, "`gyroX`, `gyroY` and `gyroZ` kept as written: ");
2027 assert!(log.events.is_empty());
2028 }
2029
2030 #[test]
2031 fn the_settings_line_names_the_board_and_the_extra_columns_are_checked() {
2032 let header = format!(
2033 "{HEADER}\ttiltMagnitudeDeg\tangularVelRadS_x\tangularVelRadS_y\tangularVelRadS_z\t\
2034 quaternion_a\tquaternion_b\tquaternion_c\tquaternion_d"
2035 );
2036 let file = |config: &str, tilt: f64, rate: f64, battery: f64| {
2037 let mut text = format!("{config}\n{header}\n");
2038 for k in 0..3 {
2039 text.push_str(&format!(
2040 "{}\t97772\t290\t0\t0\t9.8\t0\t0\t0\t293\t{battery}\t0\t0\t0\t300\t0\t0\t0\t\
2041 0\t0\t{tilt}\t{rate}\t0\t0\t1\t0\t0\t0\n",
2042 1_000 + 5_000 * k
2043 ));
2044 }
2045 text
2046 };
2047 let log = read(&file(
2048 "CONFIG\tBOARD_NAME=Bench\tFIRMWARE_VERSION=2.1\tA=1\tNOVALUE",
2049 12.5,
2050 3.0,
2051 4.0,
2052 ))
2053 .unwrap();
2054 assert_eq!(log.logger, "Bench");
2055 assert_eq!(log.firmware.as_deref(), Some("2.1"));
2056 note(
2057 &log,
2058 "the `CONFIG` line's 2 other settings, such as `A`, are left out: ",
2059 );
2060 assert_eq!(quantity(&log, "tiltMagnitudeDeg"), Quantity::Angle);
2061 assert_eq!(quantity(&log, "quaternion_a"), Quantity::Number);
2062 assert_eq!(quantity(&log, "angularVelRadS_x"), Quantity::AngularRate);
2063 assert!(close(values(&log, "angularVelRadS_x")[0], 3.0 * 180.0 / PI));
2064
2065 let refuted = read(&file("CONFIG\tBOARD_NAME=", 190.0, 400.0, 3_700.0)).unwrap();
2067 assert_eq!(refuted.logger, LOGGER);
2068 assert!(refuted.firmware.is_none());
2069 for column in [
2070 "angularVelRadS_x",
2071 "angularVelRadS_y",
2072 "tiltMagnitudeDeg",
2073 "battV",
2074 ] {
2075 assert_eq!(
2076 quantity(&refuted, column),
2077 Quantity::Unrecognized,
2078 "{column}"
2079 );
2080 }
2081 assert!(refuted.battery_v.is_none());
2082 assert!(
2083 note(
2084 &refuted,
2085 "`angularVelRadS_x`, `angularVelRadS_y` and `angularVelRadS_z` kept as written: "
2086 )
2087 .contains("reach 400")
2088 );
2089 note(&refuted, "`tiltMagnitudeDeg` kept as written: ");
2090 note(&refuted, "`battV` kept as written: ");
2091 let inside = read(&file("CONFIG", 10.0, 349.0, 4.0)).unwrap();
2093 assert_eq!(quantity(&inside, "angularVelRadS_x"), Quantity::AngularRate);
2094 }
2095
2096 #[test]
2097 fn malformed_files_are_refused_naming_the_line() {
2098 let syntax_line = |text: &str| match read(text) {
2099 Err(LogError::Syntax { line, message, .. }) => (line, message),
2100 other => panic!("{other:?}"),
2101 };
2102 let wide = format!("{HEADER}\n{}\t1\n", ["0"; 20].join("\t"));
2103 let (line, message) = syntax_line(&wide);
2104 assert_eq!(line, 2);
2105 assert!(
2106 message.contains("more than 20 cells, where the header names 20"),
2107 "{message}"
2108 );
2109 let long = format!("{HEADER}\n{}\n", ["0"; 100_000].join("\t"));
2111 let (line, message) = syntax_line(&long);
2112 assert_eq!(line, 2);
2113 assert!(message.contains("more than 20 cells"), "{message}");
2114 let names: Vec<String> = (0..MAX_COLUMNS).map(|k| format!("c{k}")).collect();
2116 let (line, message) = syntax_line(&format!(
2117 "timestampMs\tpressurePa\taltitudeM\t{}\n0\t0\t0\n",
2118 names.join("\t")
2119 ));
2120 assert_eq!(line, 1);
2121 assert!(
2122 message.contains("the header names more than 256 columns"),
2123 "{message}"
2124 );
2125 let (line, message) = syntax_line("timestampMs pressurePa altitudeM altitudeM\n1 2 3 4\n");
2126 assert_eq!(line, 1);
2127 assert!(message.contains("names \"altitudeM\" twice"), "{message}");
2128 let (_, message) = syntax_line("timestampMs\tpressurePa\t\taltitudeM\n");
2129 assert!(message.contains("column 3 has no name"), "{message}");
2130 for text in ["", "\n\n", "CONFIG\tA=1\n", "hello\n"] {
2131 assert!(
2132 matches!(read(text), Err(LogError::NotThisFormat { .. })),
2133 "{text:?}"
2134 );
2135 }
2136 assert!(matches!(
2137 read("timestampMs pressurePa altitudeM\n"),
2138 Err(LogError::NoData { .. })
2139 ));
2140 assert!(matches!(
2141 read("timestampMs pressurePa altitudeM\nx 97000 0\n"),
2142 Err(LogError::NoData { .. })
2143 ));
2144 let names: Vec<String> = (0..250).map(|k| format!("c{k}")).collect();
2147 let mut sparse = format!("timestampMs\tpressurePa\taltitudeM\t{}\n", names.join("\t"));
2148 for k in 0..300 {
2149 sparse.push_str(&format!("{k}\n"));
2150 }
2151 let (_, message) = syntax_line(&sparse);
2152 assert!(message.contains("too few for the header"), "{message}");
2153 }
2154
2155 #[test]
2156 fn empty_and_unreadable_cells_and_short_rows_are_gaps() {
2157 let text = "timestampMs pressurePa altitudeM extra\n\
2158 1000 97772 0 1\n\
2159 2000 x 1 2\n\
2160 3000 97760 2\n";
2161 let log = read(text).unwrap();
2162 assert!(values(&log, "pressurePa")[1].is_nan());
2163 assert!(values(&log, "extra")[2].is_nan());
2164 assert_eq!(quantity(&log, "extra"), Quantity::Unrecognized);
2165 note(
2166 &log,
2167 "1 cells, the first on line 3, are empty or not numbers: ",
2168 );
2169 note(
2170 &log,
2171 "1 rows, the first on line 4, hold fewer cells than the header names: ",
2172 );
2173 note(&log, "the column `extra` isn't one this reader knows");
2174 let tabbed = read("timestampMs\tpressurePa\taltitudeM\n1000\t\t0\n").unwrap();
2175 assert!(tabbed.channels[0].values[0].is_nan());
2176 note(
2177 &tabbed,
2178 "1 cells, the first on line 2, are empty or not numbers: ",
2179 );
2180 }
2181
2182 #[test]
2183 fn the_track_is_put_in_time_order_and_the_channels_kept_as_written() {
2184 let text = "timestampMs pressurePa altitudeM\n\
2185 1000 97772 0\n\
2186 3000 97749 2\n\
2187 2000 97760 1\n\
2188 3000 97668 9\n\
2189 - 97714 5\n";
2190 let log = read(text).unwrap();
2191 assert_eq!(log.time_s, [1.0, 2.0, 3.0]);
2192 assert_eq!(log.altitude_m, [0.0, 1.0, 2.0]);
2193 assert_eq!(values(&log, "altitudeM"), [0.0, 2.0, 1.0, 9.0, 5.0]);
2194 note(
2195 &log,
2196 "the clock goes back 1 times and repeats a time 1 times, and 1 samples have no time",
2197 );
2198 }
2199
2200 #[test]
2201 fn a_log_starting_aloft_and_a_temperature_that_never_changes_are_noted() {
2202 let text = "timestampMs pressurePa tempK altitudeM\n\
2203 100 96000 290.15 150\n\
2204 200 96010 290.15 149\n";
2205 let log = read(text).unwrap();
2206 note(
2207 &log,
2208 "`altitudeM` reads 150.00 m at the track's first sample, not near zero",
2209 );
2210 assert!(!has_note(&log, "`tempK` reads"));
2212
2213 let replay = read(&text_with_temperature(|_| 300.0)).unwrap();
2214 assert!(
2215 note(
2216 &replay,
2217 "`tempK` reads 300 at every one of its 87 samples while the altitude spans 300 m"
2218 )
2219 .contains("replay")
2220 );
2221 let recording = read(&text_with_temperature(|k| 300.0 + 0.01 * k as f64)).unwrap();
2222 assert!(!has_note(&recording, "`tempK` reads"));
2223 }
2224
2225 #[test]
2226 fn a_fired_flag_s_rises_are_events_and_one_already_set_is_not() {
2227 let text = "timestampMs pressurePa altitudeM drogueFired mainFired drogueCont flightState\n\
2228 1000 97772 0 0 1 1 0\n\
2229 2000 97770 0 1 1 0 1\n\
2230 3000 97770 0 - 0 1 2\n\
2231 4000 97770 0 1 1 0 3\n\
2232 5000 97770 0 0 0 1 4\n\
2233 6000 97770 0 1 0 1 4\n";
2234 let log = read(text).unwrap();
2235 let events: Vec<(f64, &str)> = log
2236 .events
2237 .iter()
2238 .map(|e| (e.time_s, e.name.as_str()))
2239 .collect();
2240 assert_eq!(
2243 events,
2244 [
2245 (2.0, "drogueFired"),
2246 (4.0, "mainFired"),
2247 (6.0, "drogueFired")
2248 ]
2249 );
2250 assert_eq!(quantity(&log, "drogueCont"), Quantity::Number);
2251 assert_eq!(quantity(&log, "flightState"), Quantity::Number);
2252 }
2253
2254 #[test]
2255 fn listed_names_read_as_a_sentence() {
2256 let columns: Vec<Column> = ["a", "b", "c"].into_iter().map(Column::new).collect();
2257 assert_eq!(listed_at(&columns, &[0]), "`a`");
2258 assert_eq!(listed_at(&columns, &[0, 1]), "`a` and `b`");
2259 assert_eq!(listed_at(&columns, &[0, 1, 2]), "`a`, `b` and `c`");
2260 }
2261
2262 proptest::proptest! {
2263 #[test]
2266 fn any_text_is_read_or_refused(
2267 text in "(CONFIG\tBOARD_NAME=[a-z]{0,4}\n)?timestampMs[ \t]pressurePa[ \t]altitudeM\
2268 ([ \t](accelX|accelY|accelZ|gyroX|gyroY|gyroZ|tempK|velocityMS|mainFired)){0,6}\n\
2269 ([-0-9. \t]{0,30}\n){0,16}"
2270 ) {
2271 if let Ok(log) = read(&text) {
2272 proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
2273 proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
2274 for channel in &log.channels {
2275 proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
2276 }
2277 }
2278 }
2279 }
2280}