1use hpr_atmos::ussa76::Ussa76;
170
171use crate::error::LogError;
172use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
173use crate::perfectflite::FOOT_M;
174use crate::table::{self, Notes, finite, numbered_lines, short};
175
176const FORMAT: &str = "RRC3 CSV";
178
179const HPA_PA: f64 = 100.0;
181
182const PRESSURE_RANGE_HPA: (f64, f64) = (10.0, 1_200.0);
185
186const PAD_RANGE_HPA: (f64, f64) = (500.0, 1_100.0);
191
192const PRESSURE_STEP_S: f64 = 0.05;
194
195const STEP_MARGIN: f64 = 0.05;
198
199const SETTLING_CLIMB_M: f64 = 10.0;
201
202const ALTITUDE_MARGIN: f64 = 0.25;
204
205const VELOCITY_CLIMB_M: f64 = 50.0;
207
208const VELOCITY_MARGIN: f64 = 0.03;
210
211const DELAY_SEARCH_S: (f64, f64, f64) = (-2.0, 4.0, 0.05);
214
215const START_SHARE: f64 = 0.01;
218
219const CLOSURE_SHARE: f64 = 0.01;
224
225const END_HEIGHT: f64 = 0.5;
228
229const END_ERROR: f64 = 0.001;
232
233const SPEEDS: [(&str, &[&str], f64); 4] = [
236 ("feet per second", &["ft/s", "fps"], FOOT_M),
237 ("miles per hour", &["mph"], 0.447_04),
238 ("meters per second", &["m/s", "mps"], 1.0),
239 ("kilometers per hour", &["km/h", "kph"], 1.0 / 3.6),
240];
241
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244enum Kind {
245 Time,
246 Altitude,
247 Pressure,
248 Velocity,
249 Temperature,
250 Events,
251 Voltages,
252}
253
254impl Kind {
255 fn from_name(name: &str) -> Option<Kind> {
256 [
257 ("time", Kind::Time),
258 ("altitude", Kind::Altitude),
259 ("pressure", Kind::Pressure),
260 ("velocity", Kind::Velocity),
261 ("temperature", Kind::Temperature),
262 ("events", Kind::Events),
263 ("voltages", Kind::Voltages),
264 ]
265 .into_iter()
266 .find(|(known, _)| name.eq_ignore_ascii_case(known))
267 .map(|(_, kind)| kind)
268 }
269
270 fn is_slow(self) -> bool {
272 matches!(self, Kind::Temperature | Kind::Voltages)
273 }
274}
275
276struct Column {
278 kind: Kind,
279 written: String,
280 unit: Option<String>,
281}
282
283fn split_name(cell: &str) -> (&str, Option<&str>) {
285 let cell = cell.trim();
286 match (cell.find('['), cell.strip_suffix(']')) {
287 (Some(open), Some(inner)) if open < inner.len() => {
288 (cell[..open].trim(), Some(inner[open + 1..].trim()))
289 }
290 _ => (cell, None),
291 }
292}
293
294fn separator(header: &str) -> char {
296 if header.contains(';') {
297 ';'
298 } else if header.contains('\t') {
299 '\t'
300 } else {
301 ','
302 }
303}
304
305fn header_columns(header: &str) -> Option<(char, bool, Vec<Column>)> {
308 let separator = separator(header);
309 let trimmed = header.trim_end();
311 let (names, trailing) = match trimmed.strip_suffix(';') {
312 Some(names) if separator == ';' => (names, true),
313 _ => (trimmed, false),
314 };
315 let mut columns: Vec<Column> = Vec::new();
316 for cell in names.split(separator) {
317 let (name, unit) = split_name(cell);
318 let kind = Kind::from_name(name)?;
319 if columns.iter().any(|column| column.kind == kind) {
320 return None;
321 }
322 let first = [Kind::Time, Kind::Altitude, Kind::Pressure, Kind::Velocity];
323 match first.get(columns.len()) {
324 Some(expected) if *expected != kind => return None,
325 _ => {}
326 }
327 columns.push(Column {
328 kind,
329 written: cell.trim().to_owned(),
330 unit: unit.map(str::to_owned),
331 });
332 }
333 (columns.len() >= 4).then_some((separator, trailing, columns))
334}
335
336pub(crate) fn recognizes(text: &str) -> bool {
339 numbered_lines(text)
340 .map(|(_, line)| line)
341 .find(|line| !line.trim().is_empty())
342 .is_some_and(|header| header_columns(header).is_some())
343}
344
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
347enum Length {
348 Feet,
349 Meters,
350}
351
352impl Length {
353 fn meters(self) -> f64 {
354 match self {
355 Length::Feet => FOOT_M,
356 Length::Meters => 1.0,
357 }
358 }
359
360 fn words(self) -> &'static str {
361 match self {
362 Length::Feet => "feet",
363 Length::Meters => "meters",
364 }
365 }
366}
367
368#[derive(Debug, Clone, Copy, PartialEq, Eq)]
370enum Temperature {
371 Fahrenheit,
372 Celsius,
373}
374
375impl Temperature {
376 fn kelvin(self, value: f64) -> f64 {
377 match self {
378 Temperature::Fahrenheit => (value - 32.0) * 5.0 / 9.0 + 273.15,
379 Temperature::Celsius => value + 273.15,
380 }
381 }
382}
383
384#[derive(Default)]
386struct HeaderUnits {
387 altitude: Option<Length>,
388 pressure_hpa: bool,
389 velocity: Option<usize>,
391 temperature: Option<Temperature>,
392}
393
394fn header_units(columns: &[Column], line: usize) -> Result<HeaderUnits, LogError> {
396 let mut units = HeaderUnits::default();
397 for column in columns {
398 let Some(unit) = column.unit.as_deref() else {
399 continue;
400 };
401 let lower = unit.to_ascii_lowercase();
402 let known = match column.kind {
403 Kind::Time => lower == "s",
404 Kind::Altitude => {
405 units.altitude = match lower.as_str() {
406 "ft" => Some(Length::Feet),
407 "m" => Some(Length::Meters),
408 _ => None,
409 };
410 units.altitude.is_some()
411 }
412 Kind::Pressure => {
413 units.pressure_hpa = lower == "mbar" || lower == "hpa";
414 units.pressure_hpa
415 }
416 Kind::Velocity => {
417 units.velocity = SPEEDS
418 .iter()
419 .position(|(_, spellings, _)| spellings.contains(&lower.as_str()));
420 units.velocity.is_some()
421 }
422 Kind::Temperature => {
423 units.temperature = match lower.trim_start_matches('°') {
424 "f" => Some(Temperature::Fahrenheit),
425 "c" => Some(Temperature::Celsius),
426 _ => None,
427 };
428 units.temperature.is_some()
429 }
430 Kind::Voltages => lower == "v",
431 Kind::Events => false,
432 };
433 if !known {
434 return Err(LogError::Unit {
435 format: FORMAT,
436 line,
437 message: format!(
438 "the column {:?} states a unit this reader doesn't know for it",
439 short(&column.written)
440 ),
441 });
442 }
443 }
444 Ok(units)
445}
446
447struct Rows {
450 lines: Vec<usize>,
451 time_s: Vec<f64>,
452 values: Vec<Vec<f64>>,
454 events: Vec<Event>,
455 short: usize,
456 padded: usize,
457 first_short_line: Option<usize>,
458 skipped: usize,
459 first_skipped_line: Option<usize>,
460}
461
462pub fn read(text: &str) -> Result<FlightLog, LogError> {
473 let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
474 let Some((header_line, header)) = lines.next() else {
475 return Err(LogError::NotThisFormat {
476 format: FORMAT,
477 message: "the file is empty".to_owned(),
478 });
479 };
480 let Some((separator, trailing, columns)) = header_columns(header) else {
481 return Err(LogError::NotThisFormat {
482 format: FORMAT,
483 message: format!(
484 "its first line, {:?}, isn't an mDACS export's header: `Time`, `Altitude`, \
485 `Pressure`, `Velocity`, then any of `Temperature`, `Events` and `Voltages`",
486 short(header)
487 ),
488 });
489 };
490 let units = header_units(&columns, header_line)?;
491 let mut notes = Notes::default();
492 let rows = read_rows(lines, separator, trailing, &columns, &mut notes)?;
493 if rows.time_s.is_empty() {
494 return Err(LogError::NoData { format: FORMAT });
495 }
496 build(&columns, &units, rows, header_line, notes)
497}
498
499fn read_rows<'a>(
503 lines: impl Iterator<Item = (usize, &'a str)>,
504 separator: char,
505 trailing: bool,
506 columns: &[Column],
507 notes: &mut Notes,
508) -> Result<Rows, LogError> {
509 let decimal_comma = separator != ',';
510 let width = columns.len();
511 let fast: Vec<usize> = (0..width).filter(|&i| !columns[i].kind.is_slow()).collect();
513 let has_slow = fast.len() < width;
514 let mut rows = Rows {
515 lines: Vec::new(),
516 time_s: Vec::new(),
517 values: columns.iter().map(|_| Vec::new()).collect(),
518 events: Vec::new(),
519 short: 0,
520 padded: 0,
521 first_short_line: None,
522 skipped: 0,
523 first_skipped_line: None,
524 };
525 let mut placed: Vec<Option<&str>> = vec![None; width];
526 for (number, line) in lines {
527 let mut cells: Vec<&str> = line.split(separator).map(str::trim).collect();
528 if trailing
532 && line.trim_end().ends_with(';')
533 && cells.last().is_some_and(|c| c.is_empty())
534 && (cells.len() == width + 1 || cells.len() == fast.len() + 1)
535 {
536 cells.pop();
537 }
538 let empty_from = |from: usize| {
539 cells
540 .get(from..)
541 .is_some_and(|rest| rest.iter().all(|c| c.is_empty()))
542 };
543 if cells.first().is_none_or(|time| time.is_empty()) {
544 let only_altitude = cells
546 .iter()
547 .enumerate()
548 .all(|(index, cell)| index == 1 || cell.is_empty());
549 if cells.len() <= width && only_altitude {
550 rows.skipped += 1;
551 rows.first_skipped_line.get_or_insert(number);
552 continue;
553 }
554 return Err(syntax(number, "the row has no time".to_owned()));
555 }
556 placed.fill(None);
557 if cells.len() == width && !(has_slow && empty_from(fast.len())) {
558 for (slot, cell) in placed.iter_mut().zip(&cells) {
559 *slot = Some(*cell);
560 }
561 } else if has_slow
562 && (cells.len() == fast.len() || (cells.len() == width && empty_from(fast.len())))
563 {
564 for (&index, cell) in fast.iter().zip(&cells) {
565 if let Some(slot) = placed.get_mut(index) {
566 *slot = Some(*cell);
567 }
568 }
569 rows.short += 1;
570 if cells.len() == width {
571 rows.padded += 1;
572 }
573 rows.first_short_line.get_or_insert(number);
574 } else {
575 let without = if has_slow {
576 format!(", and a row without its 1 Hz cells has {}", fast.len())
577 } else {
578 String::new()
579 };
580 return Err(syntax(
581 number,
582 format!(
583 "the row has {} cells: the header names {width}{without}",
584 cells.len()
585 ),
586 ));
587 }
588 read_row(&mut rows, columns, &placed, number, decimal_comma, notes)?;
589 }
590 Ok(rows)
591}
592
593fn read_row(
595 rows: &mut Rows,
596 columns: &[Column],
597 placed: &[Option<&str>],
598 number: usize,
599 decimal_comma: bool,
600 notes: &mut Notes,
601) -> Result<(), LogError> {
602 let mut time_s = f64::NAN;
603 let mut event = None;
604 let mut values = Vec::with_capacity(columns.len());
605 for (column, cell) in columns.iter().zip(placed) {
606 let Some(cell) = *cell else {
607 values.push(f64::NAN);
608 continue;
609 };
610 match column.kind {
611 Kind::Events => {
612 if !(cell.is_empty() || cell == "-") {
613 if !cell.bytes().all(|b| b.is_ascii_alphabetic()) {
614 return Err(syntax(
615 number,
616 format!(
617 "{:?} under {:?} isn't an event, `-` or a word such as `Drogue`",
618 short(cell),
619 short(&column.written)
620 ),
621 ));
622 }
623 event = Some(cell.to_owned());
624 }
625 values.push(f64::NAN);
626 }
627 _ => {
628 let value = table::number(cell, decimal_comma).ok_or_else(|| {
629 syntax(
630 number,
631 format!(
632 "{:?} under {:?} isn't a number",
633 short(cell),
634 short(&column.written)
635 ),
636 )
637 })?;
638 if column.kind == Kind::Time {
639 time_s = value;
640 }
641 values.push(value);
642 }
643 }
644 }
645 if let Some(&last) = rows.time_s.last()
646 && time_s <= last
647 {
648 return Err(syntax(
649 number,
650 format!("the time {time_s} s doesn't come after the one above it, {last} s"),
651 ));
652 }
653 rows.lines.push(number);
654 rows.time_s.push(time_s);
655 for ((column, store), value) in columns.iter().zip(&mut rows.values).zip(values) {
656 if !matches!(column.kind, Kind::Time | Kind::Events) {
657 store.push(value);
658 }
659 }
660 if let Some(name) = event {
661 if !["Drogue", "Main", "Aux"].contains(&name.as_str()) {
662 notes.push(format!(
663 "line {number}'s event {:?} isn't one of the three mDACS charts, `Drogue`, \
664 `Main` and `Aux`; it was kept as written",
665 short(&name)
666 ));
667 }
668 rows.events.push(Event { time_s, name });
669 }
670 Ok(())
671}
672
673struct Decided {
675 quantity: Quantity,
676 values: Vec<f64>,
677}
678
679fn build(
682 columns: &[Column],
683 units: &HeaderUnits,
684 rows: Rows,
685 header_line: usize,
686 mut notes: Notes,
687) -> Result<FlightLog, LogError> {
688 let mut log = FlightLog {
689 format: LogFormat::Rrc3Csv,
690 logger: "Missile Works RRC3".to_owned(),
691 serial_number: None,
692 firmware: None,
693 flight_number: None,
694 stated: Stated::default(),
695 time_s: Vec::new(),
696 altitude_m: Vec::new(),
697 vertical_speed_m_s: None,
698 temperature_k: None,
699 battery_v: None,
700 channels: Vec::new(),
701 events: rows.events,
702 notes: Vec::new(),
703 };
704 let column_of = |kind: Kind| columns.iter().position(|column| column.kind == kind);
705 let values_of = |kind: Kind| column_of(kind).and_then(|index| rows.values.get(index));
706 let written_of = |kind: Kind| {
707 column_of(kind)
708 .map(|index| columns[index].written.as_str())
709 .unwrap_or_default()
710 };
711 let (Some(altitude), Some(pressure), Some(velocity)) = (
713 values_of(Kind::Altitude),
714 values_of(Kind::Pressure),
715 values_of(Kind::Velocity),
716 ) else {
717 return Err(syntax(header_line, "the header lacks a column".to_owned()));
718 };
719
720 let pressure = decide_pressure(pressure, units, written_of(Kind::Pressure), &mut log.notes);
721 let (length, length_from_evidence) = decide_altitude(
722 altitude,
723 &pressure,
724 units,
725 &rows.lines,
726 written_of(Kind::Altitude),
727 header_line,
728 &mut log.notes,
729 )?;
730 let altitude_m: Vec<f64> = altitude
731 .iter()
732 .map(|value| value * length.meters())
733 .collect();
734 let track = Track {
735 time_s: &rows.time_s,
736 altitude_m: &altitude_m,
737 known: length_from_evidence,
738 };
739 let velocity = decide_velocity(
740 velocity,
741 &track,
742 units,
743 written_of(Kind::Velocity),
744 header_line,
745 &mut log.notes,
746 )?;
747
748 for (column, values) in columns.iter().zip(&rows.values) {
749 let decided = match column.kind {
750 Kind::Time => {
751 if column.unit.is_none() {
752 log.notes.push(time_note(&column.written, &rows.time_s));
753 }
754 continue;
755 }
756 Kind::Events => continue,
757 Kind::Altitude => Decided {
758 quantity: Quantity::AltitudeAboveGround,
759 values: altitude_m.clone(),
760 },
761 Kind::Pressure => Decided {
762 quantity: pressure.quantity,
763 values: pressure.values.clone(),
764 },
765 Kind::Velocity => Decided {
766 quantity: velocity.quantity,
767 values: velocity.values.clone(),
768 },
769 Kind::Temperature => {
770 let decided = decide_temperature(values, units, &column.written, &mut log.notes);
771 if decided.quantity == Quantity::Temperature {
772 log.temperature_k = Some(decided.values.clone());
773 }
774 decided
775 }
776 Kind::Voltages => {
777 if column.unit.is_none() {
778 log.notes.push(format!(
779 "`{}` read in volts, assumed. The RRC3 records its battery's voltage \
780 (mDACS manual p. 2) and takes a battery of at most 10 V (RRC3 manual \
781 p. 6). The column's values, as written, run {}",
782 short(&column.written),
783 span(values)
784 ));
785 }
786 log.battery_v = Some(values.clone());
787 Decided {
788 quantity: Quantity::Voltage,
789 values: values.clone(),
790 }
791 }
792 };
793 for (line, value) in rows.lines.iter().zip(&decided.values) {
796 finite(*value, FORMAT, *line, &column.written)?;
797 }
798 log.channels.push(Channel {
799 column: column.written.clone(),
800 quantity: decided.quantity,
801 time_s: rows.time_s.clone(),
802 values: decided.values,
803 });
804 }
805
806 if let Some(&first) = altitude_m.first()
807 && first.abs() > SETTLING_CLIMB_M
808 {
809 notes.push(format!(
810 "the altitude starts at {first:.1} m, not at the pad's zero the RRC3 measures from"
811 ));
812 }
813 if rows.short > 0 {
814 log.notes.push(format!(
815 "{} rows, the first on line {}, leave out the 1 Hz {}: they are gaps{}",
816 rows.short,
817 rows.first_short_line.unwrap_or_default(),
818 slow_names(columns),
819 if rows.padded > 0 {
820 format!(
821 "; {} of them pad the row to the header's width with empty cells after the \
822 others",
823 rows.padded
824 )
825 } else {
826 String::new()
827 }
828 ));
829 }
830 if rows.skipped > 0 {
831 log.notes.push(format!(
832 "{} rows with no time and nothing but an altitude cell, the first on line {}, were \
833 skipped",
834 rows.skipped,
835 rows.first_skipped_line.unwrap_or_default()
836 ));
837 }
838 log.time_s = rows.time_s;
839 log.altitude_m = altitude_m;
840 if velocity.quantity == Quantity::Speed {
841 log.vertical_speed_m_s = Some(velocity.values);
842 }
843 log.notes.extend(notes.into_vec());
844 Ok(log)
845}
846
847fn time_note(written: &str, time_s: &[f64]) -> String {
850 let mut steps: Vec<f64> = time_s.windows(2).map(|pair| pair[1] - pair[0]).collect();
851 steps.sort_by(f64::total_cmp);
852 let chart = "mDACS's chart is timed in seconds (mDACS manual p. 8)";
853 match steps.get(steps.len() / 2) {
854 Some(&median) if (median / PRESSURE_STEP_S - 1.0).abs() <= STEP_MARGIN => format!(
855 "`{}` read in seconds, from the step. The median step between rows, {median} as \
856 written, is within {:.0}% of the {PRESSURE_STEP_S} s. That is the step of the 20 Hz \
857 the RRC3 records its pressure at (RRC3 manual p. 23)",
858 short(written),
859 STEP_MARGIN * 100.0
860 ),
861 Some(&median) => format!(
862 "`{}` read in seconds, assumed. The median step between rows, {median} as written, \
863 isn't within {:.0}% of the {PRESSURE_STEP_S} s. That is the step of the 20 Hz the \
864 RRC3 records its pressure at (RRC3 manual p. 23). {chart}",
865 short(written),
866 STEP_MARGIN * 100.0
867 ),
868 None => format!(
869 "`{}` read in seconds, assumed: a single row has no step to measure; {chart}",
870 short(written)
871 ),
872 }
873}
874
875fn slow_names(columns: &[Column]) -> String {
877 let names: Vec<String> = columns
878 .iter()
879 .filter(|column| column.kind.is_slow())
880 .map(|column| format!("`{}`", short(&column.written)))
881 .collect();
882 match names.as_slice() {
883 [one] => format!("{one} cell"),
884 _ => format!("{} cells", names.join(" and ")),
885 }
886}
887
888fn span(values: &[f64]) -> String {
890 let (low, high) = values
891 .iter()
892 .filter(|value| value.is_finite())
893 .fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), &value| {
894 (low.min(value), high.max(value))
895 });
896 if low.is_finite() {
897 format!("from {low} to {high}")
898 } else {
899 "to no number".to_owned()
900 }
901}
902
903fn decide_pressure(
906 values: &[f64],
907 units: &HeaderUnits,
908 written: &str,
909 notes: &mut Vec<String>,
910) -> Decided {
911 let in_hpa = Decided {
912 quantity: Quantity::Pressure,
913 values: values.iter().map(|value| value * HPA_PA).collect(),
914 };
915 if units.pressure_hpa {
916 return in_hpa;
917 }
918 let highest = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
919 let pad = values.first().copied().unwrap_or(f64::NAN);
920 let (low, high) = PRESSURE_RANGE_HPA;
921 let (pad_low, pad_high) = PAD_RANGE_HPA;
922 let measured = (low..=high).contains(&highest);
923 let on_a_pad = (pad_low..=pad_high).contains(&pad);
924 let ranges = format!(
925 "the first row's, {pad}, {} the {pad_low} to {pad_high} hPa of any launch site. The \
926 highest, {highest}, {} the {low} to {high} mbar the RRC3 measures (RRC3 manual p. 9)",
927 if on_a_pad {
928 "lies within"
929 } else {
930 "lies outside"
931 },
932 if measured {
933 "lies within"
934 } else {
935 "lies outside"
936 }
937 );
938 if measured && on_a_pad {
939 notes.push(format!(
940 "`{}` read in hectopascals, from the values: {ranges}",
941 short(written)
942 ));
943 in_hpa
944 } else {
945 notes.push(format!(
946 "`{}` kept as written, its unit unknown: {ranges}",
947 short(written)
948 ));
949 Decided {
950 quantity: Quantity::Unrecognized,
951 values: values.to_vec(),
952 }
953 }
954}
955
956fn pressure_climb(pressure: &Decided) -> Option<(usize, f64)> {
960 if pressure.quantity != Quantity::Pressure {
961 return None;
962 }
963 let atmosphere = Ussa76::standard();
964 let first = *pressure.values.first()?;
965 let (lowest, lowest_pa) = pressure.values.iter().copied().enumerate().fold(
966 (0, first),
967 |(at, low), (index, value)| {
968 if value < low {
969 (index, value)
970 } else {
971 (at, low)
972 }
973 },
974 );
975 let climb_m = atmosphere.pressure_altitude_m(lowest_pa).ok()?
976 - atmosphere.pressure_altitude_m(first).ok()?;
977 Some((lowest, climb_m))
978}
979
980fn decide_altitude(
983 altitude: &[f64],
984 pressure: &Decided,
985 units: &HeaderUnits,
986 lines: &[usize],
987 written: &str,
988 header_line: usize,
989 notes: &mut Vec<String>,
990) -> Result<(Length, bool), LogError> {
991 let climb = pressure_climb(pressure);
992 let Some((lowest, climb_m)) = climb.filter(|(_, climb_m)| *climb_m >= SETTLING_CLIMB_M) else {
993 if let Some(stated) = units.altitude {
994 return Ok((stated, true));
995 }
996 let why = match climb {
997 _ if pressure.quantity != Quantity::Pressure => {
998 "the pressure's unit is unknown, so it can't tell feet from meters".to_owned()
999 }
1000 Some((_, climb_m)) => format!(
1001 "the pressure climbs {climb_m:.1} m, under the {SETTLING_CLIMB_M} m from which \
1002 it tells feet from meters"
1003 ),
1004 None => "a pressure isn't positive, so it gives no climb".to_owned(),
1005 };
1006 notes.push(format!(
1007 "`{}` read in feet, assumed: {why}; feet are the RRC3's default unit (RRC3 manual p. \
1008 12)",
1009 short(written)
1010 ));
1011 return Ok((Length::Feet, false));
1012 };
1013 let (Some(&first), Some(&at_lowest)) = (altitude.first(), altitude.get(lowest)) else {
1014 return Ok((Length::Feet, false));
1015 };
1016 let written_climb = at_lowest - first;
1017 let miss = |length: Length| written_climb * length.meters() / climb_m - 1.0;
1018 let (feet, meters) = (miss(Length::Feet), miss(Length::Meters));
1019 let evidence = format!(
1020 "from line {} to line {} the pressure falls from {:.2} hPa to {:.2} hPa. That is a climb \
1021 of {:.1} m in the U.S. Standard Atmosphere (1976). The altitude climbs {:.2} as \
1022 written, {:+.2}% off that climb read in feet and {:+.1}% read in meters",
1023 lines.first().copied().unwrap_or_default(),
1024 lines.get(lowest).copied().unwrap_or_default(),
1025 pressure.values.first().copied().unwrap_or_default() / HPA_PA,
1026 pressure.values.get(lowest).copied().unwrap_or_default() / HPA_PA,
1027 climb_m,
1028 written_climb,
1029 feet * 100.0,
1030 meters * 100.0
1031 );
1032 let fits = |miss: f64| miss.abs() <= ALTITUDE_MARGIN;
1033 if let Some(stated) = units.altitude {
1034 let stated_miss = miss(stated);
1035 if !fits(stated_miss) {
1036 return Err(LogError::Unit {
1037 format: FORMAT,
1038 line: header_line,
1039 message: format!(
1040 "{:?} states {}, which the pressure contradicts: {evidence}",
1041 short(written),
1042 stated.words()
1043 ),
1044 });
1045 }
1046 return Ok((stated, true));
1047 }
1048 let length = if fits(feet) {
1049 Length::Feet
1050 } else if fits(meters) {
1051 Length::Meters
1052 } else {
1053 return Err(LogError::Unit {
1054 format: FORMAT,
1055 line: header_line,
1056 message: format!(
1057 "{:?} is in neither feet nor meters by the pressure, within {:.0}%: {evidence}",
1058 short(written),
1059 ALTITUDE_MARGIN * 100.0
1060 ),
1061 });
1062 };
1063 notes.push(format!(
1064 "`{}` read in {}, from the pressure: {evidence}",
1065 short(written),
1066 length.words()
1067 ));
1068 Ok((length, true))
1069}
1070
1071#[derive(Debug, Clone, Copy)]
1073struct Scale {
1074 by_area: f64,
1077 by_fit: f64,
1080 delay_s: f64,
1082 end_height: f64,
1084 end_error: f64,
1087 start_share: f64,
1089 closure: f64,
1092}
1093
1094fn running_integral(time_s: &[f64], velocity: &[f64]) -> Vec<f64> {
1096 let mut integral = 0.0;
1097 let mut out = Vec::with_capacity(time_s.len().min(velocity.len()));
1098 let mut previous: Option<(f64, f64)> = None;
1099 for (&time, &value) in time_s.iter().zip(velocity) {
1100 if let Some((before_s, before)) = previous {
1101 integral += 0.5 * (value + before) * (time - before_s);
1102 }
1103 out.push(integral);
1104 previous = Some((time, value));
1105 }
1106 out
1107}
1108
1109fn altitude_at(time_s: &[f64], above_m: &[f64], time: f64, cursor: &mut usize) -> f64 {
1113 while time_s.get(*cursor + 1).is_some_and(|next| *next <= time) {
1114 *cursor += 1;
1115 }
1116 match (
1117 time_s.get(*cursor),
1118 time_s.get(*cursor + 1),
1119 above_m.get(*cursor),
1120 above_m.get(*cursor + 1),
1121 ) {
1122 (Some(&from_s), _, Some(&from), _) if time <= from_s => from,
1123 (Some(&from_s), Some(&to_s), Some(&from), Some(&to)) => {
1124 from + (to - from) * (time - from_s) / (to_s - from_s)
1125 }
1126 _ => above_m.last().copied().unwrap_or_default(),
1127 }
1128}
1129
1130fn velocity_scale(time_s: &[f64], altitude_m: &[f64], velocity: &[f64]) -> Option<Scale> {
1133 let first = *altitude_m.first()?;
1134 let above: Vec<f64> = altitude_m.iter().map(|value| value - first).collect();
1135 let integral = running_integral(time_s, velocity);
1136 let rows = integral.len().min(above.len());
1137 let (time_s, above, integral) = (&time_s[..rows], &above[..rows], &integral[..rows]);
1138
1139 let (earliest, latest, step) = DELAY_SEARCH_S;
1140 #[allow(
1141 clippy::cast_possible_truncation,
1142 reason = "a constant search of 120 steps"
1143 )]
1144 let steps = ((latest - earliest) / step).round() as i32;
1145 let mut best: Option<(f64, f64, f64)> = None;
1146 for at in 0..=steps {
1147 let delay_s = earliest + f64::from(at) * step;
1148 let (mut product, mut square) = (0.0, 0.0);
1149 let mut cursor = 0;
1150 for (&time, &value) in time_s.iter().zip(integral) {
1151 let earlier = altitude_at(time_s, above, time - delay_s, &mut cursor);
1152 product += value * earlier;
1153 square += earlier * earlier;
1154 }
1155 let explained = product * product / square;
1157 if square > 0.0 && best.is_none_or(|(most, _, _)| explained > most) {
1158 best = Some((explained, product / square, delay_s));
1159 }
1160 }
1161 let (_, by_fit, delay_s) = best?;
1162 let mut cursor = 0;
1165 let earlier: Vec<f64> = time_s
1166 .iter()
1167 .map(|time| altitude_at(time_s, above, time - delay_s, &mut cursor))
1168 .collect();
1169 let (mut integral_area, mut altitude_area) = (0.0, 0.0);
1170 for index in 1..rows {
1171 let step_s = time_s[index] - time_s[index - 1];
1172 integral_area += 0.5 * (integral[index] + integral[index - 1]) * step_s;
1173 altitude_area += 0.5 * (earlier[index] + earlier[index - 1]) * step_s;
1174 }
1175 let by_area = integral_area / altitude_area;
1176 let climb_m = above.iter().copied().fold(0.0, f64::max);
1177 let (&end_s, &end_m) = (time_s.last()?, above.last()?);
1178 let span_s = (end_s - time_s.first()?).min(1.0);
1181 let rate_to = |to_s: f64| {
1182 (altitude_at(time_s, above, to_s, &mut 0)
1183 - altitude_at(time_s, above, to_s - span_s, &mut 0))
1184 / span_s
1185 };
1186 let end_rate = rate_to(end_s).abs().max(rate_to(end_s - delay_s).abs());
1187 let end_error = delay_s * delay_s * end_rate / (2.0 * altitude_area);
1188 let peak = velocity[..rows]
1189 .iter()
1190 .fold(0.0, |most: f64, v| most.max(v.abs()));
1191 let start_share = if peak > 0.0 {
1192 velocity.first()?.abs() / peak
1193 } else {
1194 0.0
1195 };
1196 let closure = (integral.last()? - by_fit * earlier.last()?).abs() / (by_fit.abs() * climb_m);
1197 (altitude_area > 0.0 && by_area.is_finite() && by_fit.is_finite()).then_some(Scale {
1198 by_area,
1199 by_fit,
1200 delay_s,
1201 end_height: end_m / climb_m,
1202 end_error: if span_s > 0.0 {
1203 end_error
1204 } else {
1205 f64::INFINITY
1206 },
1207 start_share,
1208 closure,
1209 })
1210}
1211
1212fn speed_misses(slope: f64) -> Vec<(usize, f64)> {
1214 let mut misses: Vec<(usize, f64)> = SPEEDS
1215 .iter()
1216 .enumerate()
1217 .map(|(index, (_, _, m_s))| (index, slope * m_s - 1.0))
1218 .collect();
1219 misses.sort_by(|a, b| (a.1 + 1.0).ln().abs().total_cmp(&(b.1 + 1.0).ln().abs()));
1220 misses
1221}
1222
1223struct Track<'a> {
1226 time_s: &'a [f64],
1227 altitude_m: &'a [f64],
1228 known: bool,
1229}
1230
1231fn agreed_unit(scale: &Scale) -> Option<usize> {
1236 if !(scale.end_height <= END_HEIGHT
1237 && scale.end_error <= END_ERROR
1238 && scale.start_share <= START_SHARE
1239 && scale.closure <= CLOSURE_SHARE)
1240 {
1241 return None;
1242 }
1243 measures_agree(scale)
1244}
1245
1246fn measures_agree(scale: &Scale) -> Option<usize> {
1249 let (area_unit, area_miss) = *speed_misses(scale.by_area).first()?;
1250 let (fit_unit, fit_miss) = *speed_misses(scale.by_fit).first()?;
1251 (area_unit == fit_unit
1252 && area_miss.abs() <= VELOCITY_MARGIN
1253 && fit_miss.abs() <= VELOCITY_MARGIN)
1254 .then_some(area_unit)
1255}
1256
1257fn unit_misses(index: usize, scale: &Scale) -> (&'static str, f64, f64) {
1259 let (words, _, m_s) = SPEEDS.get(index).copied().unwrap_or(SPEEDS[0]);
1260 (words, scale.by_area * m_s - 1.0, scale.by_fit * m_s - 1.0)
1261}
1262
1263fn decide_velocity(
1265 values: &[f64],
1266 track: &Track,
1267 units: &HeaderUnits,
1268 written: &str,
1269 header_line: usize,
1270 notes: &mut Vec<String>,
1271) -> Result<Decided, LogError> {
1272 let Track {
1273 time_s,
1274 altitude_m,
1275 known: altitude_known,
1276 } = *track;
1277 let first = altitude_m.first().copied().unwrap_or_default();
1278 let climb_m = altitude_m.iter().copied().fold(first, f64::max) - first;
1279 let scale = (altitude_known && climb_m >= VELOCITY_CLIMB_M)
1280 .then(|| velocity_scale(time_s, altitude_m, values))
1281 .flatten();
1282 let in_si = |index: usize| {
1283 let m_s = SPEEDS.get(index).map_or(1.0, |(_, _, m_s)| *m_s);
1284 Decided {
1285 quantity: Quantity::Speed,
1286 values: values.iter().map(|value| value * m_s).collect(),
1287 }
1288 };
1289 let nearest = scale.map(|scale| {
1291 let by_area = speed_misses(scale.by_area);
1292 let by_fit = speed_misses(scale.by_fit);
1293 (scale, by_area, by_fit)
1294 });
1295 let decided = nearest.as_ref().and_then(|(scale, by_area, _)| {
1296 let index = agreed_unit(scale)?;
1297 Some((*scale, index, by_area.get(1).map(|(other, _)| *other)))
1298 });
1299 let lead = |scale: &Scale| {
1302 format!(
1303 "the altitude above the first row, in meters, is taken as it was {:.2} s earlier",
1304 scale.delay_s
1305 )
1306 };
1307 let measures = |scale: &Scale| {
1308 format!(
1309 "The area under the velocity's running integral is {:.4} times that altitude's. The \
1310 integral's least-squares slope against that altitude is {:.4}",
1311 scale.by_area, scale.by_fit
1312 )
1313 };
1314 if let Some(stated) = units.velocity {
1315 if let Some((scale, index, _)) = decided
1316 && index != stated
1317 {
1318 return Err(LogError::Unit {
1319 format: FORMAT,
1320 line: header_line,
1321 message: format!(
1322 "{:?} states {}, but the two measures land nearest {}. {}. {}",
1323 short(written),
1324 SPEEDS.get(stated).map_or("", |unit| unit.0),
1325 SPEEDS.get(index).map_or("", |unit| unit.0),
1326 crate::log::capitalized(&lead(&scale)),
1327 measures(&scale)
1328 ),
1329 });
1330 }
1331 return Ok(in_si(stated));
1332 }
1333 match decided {
1334 Some((scale, index, runner_up)) => {
1335 let runner_up = runner_up
1336 .map(|other| {
1337 let (words, by_area, by_fit) = unit_misses(other, &scale);
1338 format!(
1339 ". The next nearest, {words}, would miss both by {:+.1}% and {:+.1}%",
1340 by_area * 100.0,
1341 by_fit * 100.0
1342 )
1343 })
1344 .unwrap_or_default();
1345 let (words, by_area, by_fit) = unit_misses(index, &scale);
1346 notes.push(format!(
1347 "`{}` read in {words}, from the altitude. Over {} rows, {}. {}. Read in {words}, the \
1348 velocity would give {:.4} per m/s, {:+.2}% off the area and {:+.2}% off the \
1349 slope{runner_up}",
1350 short(written),
1351 time_s.len(),
1352 lead(&scale),
1353 measures(&scale),
1354 1.0 / SPEEDS.get(index).map_or(1.0, |unit| unit.2),
1355 by_area * 100.0,
1356 by_fit * 100.0
1357 ));
1358 Ok(in_si(index))
1359 }
1360 None => {
1361 let why = if !altitude_known {
1362 "the altitude's unit is only assumed, so the velocity can't be measured against \
1363 it"
1364 .to_owned()
1365 } else if climb_m < VELOCITY_CLIMB_M {
1366 format!(
1367 "the altitude climbs {climb_m:.1} m, under the {VELOCITY_CLIMB_M} m over which \
1368 the velocity is measured against it"
1369 )
1370 } else {
1371 match &nearest {
1372 Some((scale, _, _))
1373 if scale.end_height > END_HEIGHT || scale.end_height.is_nan() =>
1374 {
1375 format!(
1376 "the record ends {:.0}% of the way up the climb. That is above the \
1377 {:.0}% it must come down to for the velocity to be measured against \
1378 the altitude",
1379 scale.end_height * 100.0,
1380 END_HEIGHT * 100.0
1381 )
1382 }
1383 Some((scale, _, _))
1384 if scale.end_error > END_ERROR || scale.end_error.is_nan() =>
1385 {
1386 format!(
1387 "the record ends with the altitude still moving, which could move \
1388 the area under the velocity's running integral by about {:.2}%, \
1389 over the {:.1}% allowed",
1390 scale.end_error * 100.0,
1391 END_ERROR * 100.0
1392 )
1393 }
1394 Some((scale, _, _)) if scale.start_share > START_SHARE => {
1395 format!(
1396 "the velocity's first row is {:.1}% of its peak, above the {:.0}% it \
1397 may be at rest, so its integral may have missed the start of the climb",
1398 scale.start_share * 100.0,
1399 START_SHARE * 100.0
1400 )
1401 }
1402 Some((scale, _, _)) if scale.closure > CLOSURE_SHARE => {
1403 format!(
1404 "the velocity's running integral ends {:.1}% of the climb from the \
1405 altitude, over the {:.0}% allowed, as a smoothing across the record's \
1406 ends can leave it",
1407 scale.closure * 100.0,
1408 CLOSURE_SHARE * 100.0
1409 )
1410 }
1411 Some((scale, by_area, by_fit)) => {
1412 let nearest_of = |misses: &[(usize, f64)]| {
1413 misses.first().map_or(String::new(), |(index, miss)| {
1414 format!(
1415 "{} {:+.1}%",
1416 SPEEDS.get(*index).map_or("", |unit| unit.0),
1417 miss * 100.0
1418 )
1419 })
1420 };
1421 format!(
1422 "{}. {}. The two measures don't both land within {:.0}% of one of ft/s, mph, \
1423 m/s and km/h (the nearest {} and {})",
1424 lead(scale),
1425 measures(scale),
1426 VELOCITY_MARGIN * 100.0,
1427 nearest_of(by_area),
1428 nearest_of(by_fit)
1429 )
1430 }
1431 None => {
1432 "its running integral can't be measured against the altitude".to_owned()
1433 }
1434 }
1435 };
1436 notes.push(format!(
1437 "`{}` kept as written, its unit unknown: {why}",
1438 short(written)
1439 ));
1440 Ok(Decided {
1441 quantity: Quantity::Unrecognized,
1442 values: values.to_vec(),
1443 })
1444 }
1445 }
1446}
1447
1448fn decide_temperature(
1451 values: &[f64],
1452 units: &HeaderUnits,
1453 written: &str,
1454 notes: &mut Vec<String>,
1455) -> Decided {
1456 let Some(unit) = units.temperature else {
1457 notes.push(format!(
1458 "`{}` kept as written, its unit unknown. The file states none. mDACS sets the \
1459 temperature's unit by its own preference, apart from the altitude's (mDACS manual \
1460 p. 5). The column's values, as written, run {}",
1461 short(written),
1462 span(values)
1463 ));
1464 return Decided {
1465 quantity: Quantity::Unrecognized,
1466 values: values.to_vec(),
1467 };
1468 };
1469 Decided {
1470 quantity: Quantity::Temperature,
1471 values: values.iter().map(|value| unit.kelvin(*value)).collect(),
1472 }
1473}
1474
1475fn syntax(line: usize, message: String) -> LogError {
1476 LogError::Syntax {
1477 format: FORMAT,
1478 line,
1479 message,
1480 }
1481}
1482
1483#[cfg(test)]
1484mod tests {
1485 use super::*;
1486
1487 const HEADER: &str = "Time,Altitude,Pressure,Velocity,Temperature,Events,Voltages";
1488
1489 fn pressure_hpa(height_m: f64) -> f64 {
1492 1_013.25 * (1.0 - height_m / 44_330.8).powf(1.0 / 0.190_263)
1493 }
1494
1495 fn flight(top_m: f64, climb_m_s: f64, length: f64, per_m_s: f64, tail: usize) -> String {
1500 let mut text = format!("{HEADER}\n");
1501 let mut heights = vec![0.0_f64; 2];
1502 let mut climbing = true;
1503 while climbing || heights.last().is_some_and(|height| *height > 0.0) {
1504 let height = heights.last().copied().unwrap_or_default();
1505 climbing &= height < top_m;
1506 let speed = if climbing {
1507 climb_m_s
1508 } else {
1509 -climb_m_s / 3.0
1510 };
1511 heights.push((height + speed * 0.5).clamp(0.0, top_m));
1512 }
1513 heights.push(0.0);
1514 let count = heights.len();
1515 let speed = |index: usize| {
1518 let before = index.saturating_sub(1);
1519 let after = (index + 1).min(count - 1);
1520 (heights[after] - heights[before]) / ((after - before) as f64 * 0.5)
1521 };
1522 for (index, &height) in heights.iter().enumerate() {
1523 let (time, speed) = (index as f64 * 0.5, speed(index));
1524 let event = if index == 3 { "Drogue" } else { "-" };
1525 let common = format!(
1526 "{time:.2},{:.3},{:.2},{:.3}",
1527 height / length,
1528 pressure_hpa(height),
1529 speed * per_m_s
1530 );
1531 if index + tail >= count {
1532 text.push_str(&format!("{common}, {event}\n"));
1533 } else {
1534 text.push_str(&format!("{common},70.00, {event},9.20\n"));
1535 }
1536 }
1537 text
1538 }
1539
1540 fn close(a: f64, b: f64) -> bool {
1541 (a - b).abs() <= 1e-9 * b.abs().max(1.0)
1542 }
1543
1544 fn notes_starting<'a>(log: &'a FlightLog, start: &str) -> Vec<&'a String> {
1545 log.notes.iter().filter(|n| n.starts_with(start)).collect()
1546 }
1547
1548 fn temperature_as_written(log: &FlightLog) -> &[f64] {
1550 let column = log.channels.iter().find(|c| c.column == "Temperature");
1551 let column = column.unwrap();
1552 assert_eq!(column.quantity, Quantity::Unrecognized);
1553 &column.values
1554 }
1555
1556 #[test]
1561 fn an_unbracketed_temperature_is_kept_as_written_whatever_the_altitude() {
1562 for (first, last) in [(47.2, 43.2), (69.8, 70.5)] {
1563 let mut text = format!("{HEADER}\n");
1564 for i in 0..5 {
1565 let t = first + (last - first) * f64::from(i) / 4.0;
1566 text.push_str(&format!(
1567 "{},{},{:.2},0,{t:.1}, -,9.2\n",
1568 f64::from(i) * 0.05,
1569 i,
1570 1_000.0 - 0.04 * f64::from(i)
1571 ));
1572 }
1573 let log = read(&text).unwrap();
1574 assert!(log.temperature_k.is_none());
1575 let written = temperature_as_written(&log);
1576 assert_eq!((written[0], written[4]), (first, last));
1577 }
1578 for (unit, kelvin) in [("[C]", 70.0 + 273.15), ("[F]", 294.261)] {
1579 let header = HEADER.replace("Temperature", &format!("Temperature {unit}"));
1580 let log = read(&format!("{header}\n0,0,1000,0,70, -,9.2\n")).unwrap();
1581 let read_k = log.temperature_k.as_deref().unwrap()[0];
1582 assert!((read_k - kelvin).abs() < 1e-3, "{unit}: {read_k}");
1583 }
1584 }
1585
1586 #[test]
1589 fn a_value_its_conversion_makes_infinite_is_refused() {
1590 let cases = [
1591 (
1592 "Time,Altitude,Pressure [hPa],Velocity\n0,0,1013,0\n0.05,1,1.7e308,0\n",
1593 "line 3: the column Pressure [hPa] holds",
1594 ),
1595 (
1596 "Time,Altitude,Pressure,Velocity,Temperature [F]\n0,0,1013,0,70\n\
1597 0.05,1,1013,0,-1.7e308\n",
1598 "line 3: the column Temperature [F] holds",
1599 ),
1600 ];
1601 for (text, refusal) in cases {
1602 assert_eq!(
1603 read(text).unwrap_err().to_string(),
1604 format!("RRC3 CSV {refusal} a value too large for its unit's conversion to SI")
1605 );
1606 }
1607 }
1608
1609 fn european(text: &str) -> String {
1612 text.lines()
1613 .map(|line| format!("{};\n", line.replace(',', ";").replace('.', ",")))
1614 .collect()
1615 }
1616
1617 #[test]
1618 fn a_european_export_ending_its_lines_in_semicolons_reads_alike() {
1619 for tail in [0, 3] {
1621 let text = flight(300.0, 60.0, FOOT_M, 3.2808, tail);
1622 let plain = read(&text).unwrap();
1623 let semicolons = read(&european(&text)).unwrap();
1624 assert_eq!(semicolons.time_s, plain.time_s, "{tail}");
1625 assert_eq!(semicolons.altitude_m, plain.altitude_m);
1626 let json = |log: &FlightLog| serde_json::to_string(log).unwrap();
1628 assert_eq!(json(&semicolons), json(&plain), "{tail}");
1629 }
1630 let text = flight(300.0, 60.0, FOOT_M, 3.2808, 0);
1631 let plain = read(&text).unwrap();
1632 let short_text = european(&flight(300.0, 60.0, FOOT_M, 3.2808, 3));
1634 let short = read(&short_text).unwrap();
1635 let padded = short_text
1636 .lines()
1637 .map(|line| {
1638 if line.matches(';').count() == 5 {
1639 format!("{line};;\n")
1640 } else {
1641 format!("{line}\n")
1642 }
1643 })
1644 .collect::<String>();
1645 assert_eq!(padded.matches(";;;\n").count(), 3);
1646 let json = |log: &FlightLog| serde_json::to_string(&log.channels).unwrap();
1647 assert_eq!(json(&read(&padded).unwrap()), json(&short));
1648 let unclosed = short_text
1650 .lines()
1651 .map(|line| {
1652 if line.matches(';').count() == 5 {
1653 format!("{line};\n")
1654 } else {
1655 format!("{line}\n")
1656 }
1657 })
1658 .collect::<String>();
1659 assert_eq!(unclosed.matches(";;\n").count(), 3);
1660 assert_eq!(json(&read(&unclosed).unwrap()), json(&short));
1661 let with_blank = format!("{};;;;;;;\n", european(&text));
1663 assert_eq!(read(&with_blank).unwrap().time_s, plain.time_s);
1664 let extra = european(&text).replacen(";9,20;\n", ";9,20;1\n", 1);
1666 assert!(matches!(
1667 read(&extra),
1668 Err(LogError::Syntax { line: 2, .. })
1669 ));
1670 }
1671
1672 #[test]
1673 fn rows_sorted_as_text_are_refused_where_the_time_goes_back() {
1674 let text = european(&flight(300.0, 60.0, FOOT_M, 3.2808, 0));
1676 let mut lines: Vec<&str> = text.lines().collect();
1677 let header = lines.remove(0);
1678 lines.sort_unstable();
1679 let sorted = format!("{header}\n{}\n", lines.join("\n"));
1680 let back = lines
1681 .windows(2)
1682 .position(|pair| {
1683 let time = |line: &str| line.split(';').next().unwrap().replace(',', ".");
1684 time(pair[1]).parse::<f64>().unwrap() <= time(pair[0]).parse::<f64>().unwrap()
1685 })
1686 .unwrap();
1687 assert!(matches!(
1688 read(&sorted),
1689 Err(LogError::Syntax { line, ref message, .. })
1690 if line == back + 3 && message.contains("doesn't come after the one above it")
1691 ));
1692 }
1693
1694 #[test]
1695 fn recognizes_only_an_mdacs_header() {
1696 let yes = [
1697 HEADER,
1698 "\u{feff}\r\n\r\nTime,Altitude,Pressure,Velocity,Events",
1699 "Time,Altitude,Pressure,Velocity,Temperature",
1700 "Time,Altitude,Pressure,Velocity,Voltages",
1701 "time,ALTITUDE,pressure,Velocity",
1702 "Time [s],Altitude [ft],Pressure [mbar],Velocity [ft/s],Temperature [F],Events,Voltages [V]",
1703 "Time;Altitude;Pressure;Velocity;Temperature;Events;Voltages",
1704 "Time\tAltitude\tPressure\tVelocity\tEvents",
1705 "Time,Altitude [yd],Pressure,Velocity",
1707 ];
1708 for header in yes {
1709 assert!(recognizes(header), "{header:?}");
1710 }
1711 let no = [
1712 "",
1713 "Time,Altitude,Velocity,Temperature (F),Voltage",
1715 "Time, Altitude, Velocity",
1716 "Time,Altitude,Pressure",
1717 "Time,Pressure,Altitude,Velocity",
1718 "Time,Altitude,Pressure,Velocity,Temperature,Temperature",
1719 "Time,Altitude,Pressure,Velocity,Accel",
1720 "Time,Altitude,Pressure,Velocity,",
1721 "# Time,Altitude,Pressure,Velocity",
1722 "Time,Altitude [ft,Pressure,Velocity",
1723 ];
1724 for header in no {
1725 assert!(!recognizes(header), "{header:?}");
1726 }
1727 assert!(!recognizes("x\nTime,Altitude,Pressure,Velocity\n"));
1729 }
1730
1731 #[test]
1734 fn decides_feet_and_feet_per_second_from_the_file() {
1735 let text = flight(300.0, 60.0, FOOT_M, 1.0 / FOOT_M, 2);
1736 let log = read(&text).unwrap();
1737 assert_eq!(log.format, LogFormat::Rrc3Csv);
1738 let quantities: Vec<Quantity> = log.channels.iter().map(|c| c.quantity).collect();
1739 assert_eq!(
1740 quantities,
1741 [
1742 Quantity::AltitudeAboveGround,
1743 Quantity::Pressure,
1744 Quantity::Speed,
1745 Quantity::Unrecognized,
1746 Quantity::Voltage
1747 ]
1748 );
1749 assert!(close(log.altitude_m[2], 98.425 * FOOT_M));
1751 assert!(close(
1752 log.vertical_speed_m_s.as_deref().unwrap()[2],
1753 196.85 * FOOT_M
1754 ));
1755 assert!(log.temperature_k.is_none());
1757 let temperature = temperature_as_written(&log);
1758 assert_eq!(temperature[0], 70.0);
1759 let n = log.time_s.len();
1760 assert!(temperature[n - 2..].iter().all(|t| t.is_nan()));
1761 assert!(temperature[n - 3].is_finite());
1762 assert_eq!(log.events.len(), 1);
1763 assert_eq!(
1764 (log.events[0].time_s, log.events[0].name.as_str()),
1765 (1.5, "Drogue")
1766 );
1767 for start in [
1768 "`Altitude` read in feet, from the pressure: ",
1769 "`Velocity` read in feet per second, from the altitude. ",
1770 "`Pressure` read in hectopascals, from the values: ",
1771 "`Temperature` kept as written, its unit unknown. ",
1772 "`Voltages` read in volts, assumed. ",
1773 "`Time` read in seconds, assumed. ",
1774 "2 rows, the first on line ",
1775 ] {
1776 assert_eq!(
1777 notes_starting(&log, start).len(),
1778 1,
1779 "{start}: {:?}",
1780 log.notes
1781 );
1782 }
1783 }
1784
1785 #[test]
1787 fn each_velocity_unit_is_told_apart() {
1788 for (words, _, m_s) in SPEEDS {
1789 let text = flight(300.0, 60.0, FOOT_M, 1.0 / m_s, 0);
1790 let log = read(&text).unwrap();
1791 let start = format!("`Velocity` read in {words}, from the altitude. ");
1792 assert_eq!(
1793 notes_starting(&log, &start).len(),
1794 1,
1795 "{words}: {:?}",
1796 log.notes
1797 );
1798 assert!(
1800 (log.vertical_speed_m_s.as_deref().unwrap()[2] - 60.0).abs() < 5e-4 * m_s.max(1.0)
1801 );
1802 }
1803 }
1804
1805 #[test]
1807 fn decides_meters_from_the_pressure() {
1808 let text = flight(300.0, 60.0, 1.0, 1.0, 0);
1809 let log = read(&text).unwrap();
1810 assert!(close(log.altitude_m[2], 30.0));
1811 assert_eq!(
1812 notes_starting(&log, "`Altitude` read in meters, from the pressure: ").len(),
1813 1
1814 );
1815 assert!(log.temperature_k.is_none());
1817 assert_eq!(temperature_as_written(&log)[0], 70.0);
1818 assert_eq!(
1819 notes_starting(&log, "`Temperature` kept as written, its unit unknown. ").len(),
1820 1
1821 );
1822 }
1823
1824 #[test]
1827 fn a_velocity_that_cant_be_told_is_kept_as_written() {
1828 let full = flight(300.0, 60.0, FOOT_M, 1.0 / FOOT_M, 0);
1830 let cut: String = full
1831 .lines()
1832 .take(14)
1833 .map(|line| format!("{line}\n"))
1834 .collect();
1835 let above_rest: String = full
1837 .lines()
1838 .enumerate()
1839 .filter(|(row, _)| *row != 1)
1840 .map(|(_, line)| format!("{line}\n"))
1841 .collect();
1842 let open_ended: String = full
1844 .lines()
1845 .map(|line| {
1846 let mut cells: Vec<String> = line.split(',').map(str::to_owned).collect();
1847 if let Some(rate) = cells.get(3).and_then(|cell| cell.parse::<f64>().ok())
1848 && rate < 0.0
1849 {
1850 cells[3] = format!("{:.3}", rate * 1.2);
1851 }
1852 cells.join(",") + "\n"
1853 })
1854 .collect();
1855 let at_rest = flight(300.0, 60.0, FOOT_M, 0.0, 0);
1857 let cases = [
1858 (
1859 flight(300.0, 60.0, FOOT_M, 3.0, 0),
1860 "don't both land within 3% of one",
1861 ),
1862 (
1863 flight(40.0, 20.0, FOOT_M, 1.0 / FOOT_M, 0),
1864 "under the 50 m",
1865 ),
1866 (flight(8.0, 4.0, FOOT_M, 1.0 / FOOT_M, 0), "only assumed"),
1867 (cut, "of the way up the climb. That is above the 50%"),
1868 (above_rest, "above the 1% it may be at rest"),
1869 (open_ended, "over the 1% allowed"),
1870 (at_rest, "the record ends with the altitude still moving"),
1871 ];
1872 for (text, why) in cases {
1873 let log = read(&text).unwrap();
1874 assert_eq!(log.channels[2].quantity, Quantity::Unrecognized);
1875 assert!(log.vertical_speed_m_s.is_none());
1876 let kept = notes_starting(&log, "`Velocity` kept as written, its unit unknown: ");
1877 assert_eq!(kept.len(), 1, "{:?}", log.notes);
1878 assert!(kept[0].contains(why), "{why}: {kept:?}");
1879 }
1880 let log = read(&flight(8.0, 4.0, FOOT_M, 1.0 / FOOT_M, 0)).unwrap();
1882 let assumed = notes_starting(&log, "`Altitude` read in feet, assumed: ");
1883 assert!(assumed[0].contains("climbs 8.0 m"), "{assumed:?}");
1884 }
1885
1886 #[test]
1888 fn a_pressure_of_unknown_unit_is_kept_as_written() {
1889 let text = format!("{HEADER}\n0,0,101325,0,70, -,9.2\n0.05,1,101310,1,70, -,9.2\n");
1890 let log = read(&text).unwrap();
1891 assert_eq!(log.channels[1].quantity, Quantity::Unrecognized);
1892 assert_eq!(log.channels[1].values, [101_325.0, 101_310.0]);
1893 assert_eq!(
1894 notes_starting(&log, "`Pressure` kept as written, its unit unknown: ").len(),
1895 1
1896 );
1897 let assumed = notes_starting(&log, "`Altitude` read in feet, assumed: ");
1898 assert!(assumed[0].contains("unit is unknown"), "{assumed:?}");
1899 }
1900
1901 #[test]
1903 fn bracketed_units() {
1904 let text = flight(300.0, 60.0, 1.0, 3.6, 0).replacen(
1905 HEADER,
1906 "Time [s],Altitude [m],Pressure [hPa],Velocity [kph],Temperature [°F],Events,Voltages [V]",
1907 1,
1908 );
1909 let log = read(&text).unwrap();
1910 assert!(close(log.vertical_speed_m_s.as_deref().unwrap()[2], 60.0));
1911 assert!((log.temperature_k.as_deref().unwrap()[0] - 294.261).abs() < 1e-3);
1913 assert!(
1914 log.notes.iter().all(|n| !n.contains(" read in ")),
1915 "{:?}",
1916 log.notes
1917 );
1918
1919 let wrong_altitude = text.replacen("Altitude [m]", "Altitude [ft]", 1);
1921 let error = read(&wrong_altitude).unwrap_err();
1922 assert!(
1923 matches!(&error, LogError::Unit { line: 1, message, .. } if message.contains("states feet, which the pressure contradicts")),
1924 "{error:?}"
1925 );
1926 let wrong_speed = text.replacen("Velocity [kph]", "Velocity [m/s]", 1);
1927 let error = read(&wrong_speed).unwrap_err();
1928 assert!(
1929 matches!(&error, LogError::Unit { line: 1, message, .. } if message.contains("\"Velocity [m/s]\" states meters per second, but the two measures land nearest kilometers per hour. The altitude above the first row")),
1930 "{error:?}"
1931 );
1932 for header in [
1933 "Time [ms],Altitude,Pressure,Velocity",
1934 "Time,Altitude [yd],Pressure,Velocity",
1935 "Time,Altitude,Pressure [psi],Velocity",
1936 "Time,Altitude,Pressure,Velocity [knots]",
1937 "Time,Altitude,Pressure,Velocity,Temperature [K]",
1938 "Time,Altitude,Pressure,Velocity,Events [x]",
1939 "Time,Altitude,Pressure,Velocity,Voltages [mV]",
1940 ] {
1941 let error = read(&format!("{header}\n0,0,1000,0\n")).unwrap_err();
1942 assert!(
1943 matches!(&error, LogError::Unit { line: 1, message, .. } if message.contains("states a unit this reader doesn't know")),
1944 "{header}: {error:?}"
1945 );
1946 }
1947 }
1948
1949 #[test]
1951 fn an_altitude_in_neither_unit_is_refused() {
1952 let text = flight(300.0, 60.0, 1.0 / 1.6, 1.0, 0);
1953 let error = read(&text).unwrap_err();
1954 assert!(
1955 matches!(&error, LogError::Unit { line: 1, message, .. } if message.contains("neither feet nor meters")),
1956 "{error:?}"
1957 );
1958 }
1959
1960 #[test]
1962 fn semicolons_and_tabs_take_decimal_commas() {
1963 let comma = "0,00;0;1013,25;0;21,5; -;9,2\n0,05;1,5;1013,07;2,5;21,5; Main;9,1\n";
1964 let log = read(&format!("{}\n{comma}", HEADER.replace(',', ";"))).unwrap();
1965 assert_eq!(log.time_s, [0.0, 0.05]);
1966 assert_eq!(log.events[0].name, "Main");
1967 assert!(close(log.channels[1].values[1], 101_307.0));
1968 let tabbed = comma.replace(';', "\t");
1969 let log = read(&format!("{}\n{tabbed}", HEADER.replace(',', "\t"))).unwrap();
1970 assert_eq!(log.battery_v.as_deref(), Some(&[9.2, 9.1][..]));
1971 let error = read(&format!("{HEADER}\n0,0,1013,25,0,70, -,9,2\n")).unwrap_err();
1972 assert!(
1973 error.to_string().contains("line 2: the row has 9 cells"),
1974 "{error}"
1975 );
1976 }
1977
1978 #[test]
1980 fn short_rows_leave_out_the_one_hertz_cells() {
1981 let text =
1982 format!("{HEADER}\n0,0,1000,0,70, -,9.2\n0.05,1,999.9,1, Drogue\n0.1,1,999.9,1, -,,\n");
1983 let log = read(&text).unwrap();
1984 assert_eq!(log.events.len(), 1);
1985 assert_eq!(log.events[0].time_s, 0.05);
1986 let temperature = temperature_as_written(&log);
1987 assert!(temperature[0].is_finite() && temperature[1].is_nan() && temperature[2].is_nan());
1988 assert!(log.notes.iter().any(|n| n.starts_with(
1989 "2 rows, the first on line 3, leave out the 1 Hz `Temperature` and `Voltages` cells: \
1990 they are gaps; 1 of them pad"
1991 )));
1992 let log = read("Time,Altitude,Pressure,Velocity,Temperature\n0,0,1000,0,70\n1,1,999.9,1\n")
1994 .unwrap();
1995 assert!(temperature_as_written(&log)[1].is_nan());
1996 let error = read("Time,Altitude,Pressure,Velocity,Events\n0,0,1000,0\n").unwrap_err();
1998 assert!(
1999 error
2000 .to_string()
2001 .contains("line 2: the row has 4 cells: the header names 5"),
2002 "{error}"
2003 );
2004 let error = read(&format!("{HEADER}\n0,0,1000,0, -, -,9.2\n")).unwrap_err();
2006 assert!(
2007 error
2008 .to_string()
2009 .contains("line 2: \"-\" under \"Temperature\" isn't a number"),
2010 "{error}"
2011 );
2012 let error = read(&format!("{HEADER}\n0,0,1000,0,70,,\n")).unwrap_err();
2014 assert!(
2015 error
2016 .to_string()
2017 .contains("line 2: \"70\" under \"Events\" isn't an event"),
2018 "{error}"
2019 );
2020 }
2021
2022 #[test]
2025 fn rows_with_no_time() {
2026 let text = format!("{HEADER}\n0,0,1000,0,70, -,9.2\n,4,,,,,\n,4\n");
2027 let log = read(&text).unwrap();
2028 assert_eq!(log.time_s.len(), 1);
2029 assert!(log.notes.iter().any(|n| n.starts_with(
2030 "2 rows with no time and nothing but an altitude cell, the first on line 3"
2031 )));
2032 let error = read(&format!("{HEADER}\n,4,1000,,,,\n")).unwrap_err();
2033 assert!(
2034 error.to_string().contains("line 2: the row has no time"),
2035 "{error}"
2036 );
2037 }
2038
2039 #[test]
2041 fn malformed_files_are_refused_where_they_go_wrong() {
2042 let cases = [
2043 (String::new(), "the file is empty"),
2044 (
2045 "Time,Altitude,Velocity\n0,0,0\n".to_owned(),
2046 "isn't an mDACS export's header",
2047 ),
2048 (format!("{HEADER}\n"), "no data rows"),
2049 (format!("{HEADER}\n,4\n"), "no data rows"),
2050 (
2051 format!("{HEADER}\n0,0,1000,0,70, -,9.2\n0,0,1000,0,70, -,9.2\n"),
2052 "line 3: the time 0 s doesn't come after the one above it, 0 s",
2053 ),
2054 (
2055 format!("{HEADER}\n1,0,1000,0,70, -,9.2\n0.5,0,1000,0,70, -,9.2\n"),
2056 "line 3: the time 0.5 s doesn't come after",
2057 ),
2058 (
2059 format!("{HEADER}\nx,0,1000,0,70, -,9.2\n"),
2060 "line 2: \"x\" under \"Time\" isn't a number",
2061 ),
2062 (
2063 format!("{HEADER}\n0,,1000,0,70, -,9.2\n"),
2064 "line 2: \"\" under \"Altitude\" isn't a number",
2065 ),
2066 (
2067 format!("{HEADER}\n0,0,1000,0,70, Main 2,9.2\n"),
2068 "line 2: \"Main 2\" under \"Events\"",
2069 ),
2070 (
2071 format!("{HEADER}\n0,0,1000,0,70, -,9.2,1\n"),
2072 "line 2: the row has 8 cells",
2073 ),
2074 (
2075 format!("{HEADER}\n0,0,1000\n"),
2076 "line 2: the row has 3 cells",
2077 ),
2078 ];
2079 for (text, expected) in cases {
2080 let error = read(&text).unwrap_err().to_string();
2081 assert!(error.contains(expected), "{text:?}: {error}");
2082 }
2083 }
2084
2085 #[test]
2087 fn unknown_events_are_kept_and_notes_stay_few() {
2088 let mut text = format!("{HEADER}\n");
2089 for index in 0..30 {
2090 text.push_str(&format!("{index},0,1000,0,70, Apogee,9.2\n"));
2091 }
2092 let log = read(&text).unwrap();
2093 assert_eq!(log.events.len(), 30);
2094 assert_eq!(log.events[0].name, "Apogee");
2095 let about_events = log
2096 .notes
2097 .iter()
2098 .filter(|n| n.contains("\"Apogee\""))
2099 .count();
2100 assert_eq!(about_events, 20);
2101 assert!(
2102 log.notes.iter().any(|n| n.starts_with("and 10 more notes")),
2103 "{:?}",
2104 log.notes
2105 );
2106 }
2107
2108 #[test]
2111 fn line_ends_and_quotes() {
2112 let rows = ["0,0,1000,0,70, -,9.2", "0.05,0.5,999.98,1,70, -,9.2"];
2113 for end in ["\r", "\n", "\r\n"] {
2114 let text = format!("\u{feff}{HEADER}{end}{}{end}{end}{}{end}", rows[0], rows[1]);
2115 let log = read(&text).unwrap();
2116 assert_eq!(log.time_s, [0.0, 0.05], "{end:?}");
2117 }
2118 let error = read(&format!("{HEADER}\n{}\n", "9".repeat(10_000))).unwrap_err();
2119 assert!(error.to_string().chars().count() < 400, "{error}");
2120 let error = read(&"\u{fffd}".repeat(100_000)).unwrap_err();
2121 assert!(error.to_string().chars().count() < 400, "{error}");
2122 }
2123
2124 fn arc(top_m: f64, descent_m_s: f64) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
2128 arc_of(1.0, 80.0, 12.0, top_m, descent_m_s)
2129 }
2130
2131 fn arc_of(
2133 pad_s: f64,
2134 boost: f64,
2135 coast: f64,
2136 top_m: f64,
2137 descent_m_s: f64,
2138 ) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
2139 let gravity = 9.8;
2140 let boost_s = (top_m / (boost / 2.0 + boost * boost / (2.0 * coast))).sqrt();
2141 let burnout_m_s = boost * boost_s;
2142 let apogee_s = boost_s + burnout_m_s / coast;
2143 let fall_s = descent_m_s / gravity;
2144 let (mut times, mut heights, mut rates) = (vec![], vec![], vec![]);
2145 let mut landed_s = None;
2146 for row in 0_u32.. {
2147 let t = f64::from(row) * 0.05 - pad_s;
2148 let (height, rate): (f64, f64) = if t < 0.0 {
2149 (0.0, 0.0)
2150 } else if t < boost_s {
2151 (boost * t * t / 2.0, boost * t)
2152 } else if t < apogee_s {
2153 let u = t - boost_s;
2154 (
2155 boost * boost_s * boost_s / 2.0 + burnout_m_s * u - coast * u * u / 2.0,
2156 burnout_m_s - coast * u,
2157 )
2158 } else if t < apogee_s + fall_s {
2159 let u = t - apogee_s;
2160 (top_m - gravity * u * u / 2.0, -gravity * u)
2161 } else {
2162 let u = t - apogee_s - fall_s;
2163 (
2164 top_m - gravity * fall_s * fall_s / 2.0 - descent_m_s * u,
2165 -descent_m_s,
2166 )
2167 };
2168 let (height, rate) = if height <= 0.0 && t > 0.0 {
2169 (0.0, 0.0)
2170 } else {
2171 (height, rate)
2172 };
2173 if t > 0.0 && height == 0.0 {
2174 landed_s.get_or_insert(t);
2175 }
2176 if landed_s.is_some_and(|landed| t > landed + 3.0) {
2177 break;
2178 }
2179 times.push(t + pad_s);
2180 heights.push(height);
2181 rates.push(rate);
2182 }
2183 (times, heights, rates)
2184 }
2185
2186 #[test]
2192 fn the_velocity_unit_is_never_decided_wrong() {
2193 let atmosphere = Ussa76::standard();
2194 let height_of = |hpa: f64| {
2195 atmosphere
2196 .pressure_altitude_m(hpa * HPA_PA)
2197 .unwrap_or(f64::NAN)
2198 };
2199 let pad_m = height_of((pressure_hpa(0.0) * 10.0).round() / 10.0);
2200 let lags = [
2201 ("late", 0.0),
2202 ("late", 1.0),
2203 ("late", 2.0),
2204 ("late", 3.0),
2205 ("first-order", 0.5),
2206 ("first-order", 1.0),
2207 ("first-order", 2.0),
2208 ("first-order", 3.0),
2209 ("moving average", 1.0),
2210 ("moving average", 2.0),
2211 ("moving average", 3.0),
2212 ("centered", 3.0),
2213 ("centered", 4.0),
2214 ("centered", 5.0),
2215 ];
2216 let (mut decided, mut cases) = (0, 0);
2217 for top_m in [20.0, 30.0, 50.0, 100.0, 200.0, 300.0, 1_000.0] {
2218 for descent_m_s in [10.0, 25.0, 40.0] {
2219 let (time_s, height_m, rate_m_s) = arc(top_m, descent_m_s);
2220 let altitude_m: Vec<f64> = height_m
2221 .iter()
2222 .map(|height| {
2223 let hpa = (pressure_hpa(*height) * 10.0).round() / 10.0;
2224 ((height_of(hpa) - pad_m) * 100.0).round() / 100.0
2225 })
2226 .collect();
2227 for (kind, lag_s) in lags {
2228 let steps = (lag_s / 0.05_f64).round() as usize;
2229 let lagged: Vec<f64> = match kind {
2230 "late" => (0..rate_m_s.len())
2231 .map(|i| i.checked_sub(steps).map_or(0.0, |j| rate_m_s[j]))
2232 .collect(),
2233 "first-order" => {
2234 let mut smoothed = 0.0;
2235 rate_m_s
2236 .iter()
2237 .map(|rate| {
2238 smoothed += (rate - smoothed) * 0.05 / (lag_s + 0.05);
2239 smoothed
2240 })
2241 .collect()
2242 }
2243 "centered" => (0..rate_m_s.len())
2244 .map(|i| {
2245 let from = i.saturating_sub(steps / 2);
2246 let to = (i + steps / 2).min(rate_m_s.len() - 1);
2247 rate_m_s[from..=to].iter().sum::<f64>() / (to - from + 1) as f64
2248 })
2249 .collect(),
2250 _ => (0..rate_m_s.len())
2251 .map(|i| {
2252 let from = (i + 1).saturating_sub(steps);
2253 rate_m_s[from..=i].iter().sum::<f64>() / steps as f64
2254 })
2255 .collect(),
2256 };
2257 for (unit, (words, _, m_s)) in SPEEDS.iter().enumerate() {
2258 let velocity: Vec<f64> = lagged
2259 .iter()
2260 .map(|rate| (rate / m_s * 100.0).round() / 100.0)
2261 .collect();
2262 for tenths in 3..=10 {
2263 let rows = time_s.len() * tenths / 10;
2264 let Some(scale) =
2265 velocity_scale(&time_s[..rows], &altitude_m[..rows], &velocity)
2266 else {
2267 continue;
2268 };
2269 cases += 1;
2270 let agreed = agreed_unit(&scale);
2271 if kind == "late" && lag_s <= 1.0 && tenths == 10 && top_m >= 50.0 {
2273 assert_eq!(
2274 agreed,
2275 Some(unit),
2276 "{top_m} m, {descent_m_s} m/s, {lag_s} s late, {words}: \
2277 {scale:?}"
2278 );
2279 }
2280 if let Some(index) = agreed {
2281 decided += 1;
2282 assert_eq!(
2283 index, unit,
2284 "{top_m} m, {descent_m_s} m/s, {kind} {lag_s} s, {words}, \
2285 {tenths}0% of the record: {scale:?}"
2286 );
2287 }
2288 }
2289 }
2290 }
2291 }
2292 }
2293 assert!(decided * 10 > cases, "{decided} of {cases}");
2295 }
2296
2297 #[test]
2302 fn a_velocity_smoothed_around_each_sample_keeps_its_unit_on_this_grid() {
2303 let atmosphere = Ussa76::standard();
2304 let height_of = |hpa: f64| {
2305 atmosphere
2306 .pressure_altitude_m(hpa * HPA_PA)
2307 .unwrap_or(f64::NAN)
2308 };
2309 let pad_m = height_of((pressure_hpa(0.0) * 10.0).round() / 10.0);
2310 let (mut decided, mut alone, mut alone_wrong) = (0_u32, 0_u32, 0_u32);
2312 for pad_s in [0.05, 0.25, 0.5, 1.0, 2.0, 2.3, 2.85, 4.0] {
2313 for (boost, coast) in [(30.0, 8.0), (80.0, 12.0), (200.0, 25.0), (30.0, 25.0)] {
2314 for top_m in [20.0, 50.0, 100.0, 300.0, 1_000.0, 2_000.0] {
2315 for descent_m_s in [10.0, 25.0, 40.0] {
2316 let (time_s, height_m, rate_m_s) =
2317 arc_of(pad_s, boost, coast, top_m, descent_m_s);
2318 let altitude_m: Vec<f64> = height_m
2319 .iter()
2320 .map(|height| {
2321 let hpa = (pressure_hpa(*height) * 10.0).round() / 10.0;
2322 ((height_of(hpa) - pad_m) * 100.0).round() / 100.0
2323 })
2324 .collect();
2325 for window_s in [3.0, 3.5, 4.0, 4.5, 5.0] {
2326 let half = (window_s / 0.05_f64 / 2.0).round() as usize;
2327 let smoothed: Vec<f64> = (0..rate_m_s.len())
2328 .map(|i| {
2329 let from = i.saturating_sub(half);
2330 let to = (i + half).min(rate_m_s.len() - 1);
2331 rate_m_s[from..=to].iter().sum::<f64>() / (to - from + 1) as f64
2332 })
2333 .collect();
2334 for (unit, (words, _, m_s)) in SPEEDS.iter().enumerate() {
2335 let velocity: Vec<f64> = smoothed
2336 .iter()
2337 .map(|rate| (rate / m_s * 100.0).round() / 100.0)
2338 .collect();
2339 for tenths in 3..=10 {
2340 let rows = time_s.len() * tenths / 10;
2341 let Some(scale) = velocity_scale(
2342 &time_s[..rows],
2343 &altitude_m[..rows],
2344 &velocity,
2345 ) else {
2346 continue;
2347 };
2348 if let Some(index) = measures_agree(&scale) {
2349 alone += 1;
2350 alone_wrong += u32::from(index != unit);
2351 }
2352 if let Some(index) = agreed_unit(&scale) {
2353 decided += 1;
2354 assert_eq!(
2355 index, unit,
2356 "pad {pad_s} s, boost {boost}, coast {coast}, \
2357 {top_m} m, {descent_m_s} m/s, {window_s} s, {words}, \
2358 {tenths}0% of the record: {scale:?}"
2359 );
2360 }
2361 }
2362 }
2363 }
2364 }
2365 }
2366 }
2367 }
2368 eprintln!("the measures alone: {alone_wrong} wrong of {alone}; the rules: {decided}");
2369 assert!(
2371 alone_wrong * 100 > alone && alone_wrong * 33 < alone,
2372 "{alone_wrong} of {alone}"
2373 );
2374 assert!(
2376 decided * 6 > alone && decided * 3 < alone,
2377 "{decided} of {alone}"
2378 );
2379 }
2380
2381 #[test]
2384 fn the_velocity_scale_takes_out_a_delay() {
2385 let time_s: Vec<f64> = (0..800).map(|i| f64::from(i) * 0.05).collect();
2386 let rate = |t: f64| match t {
2388 t if t < 1.0 => 0.0,
2389 t if t < 6.0 => 50.0,
2390 t if t < 26.0 => -12.5,
2391 _ => 0.0,
2392 };
2393 let mut altitude_m = vec![0.0];
2394 for pair in time_s.windows(2) {
2395 let last = altitude_m.last().copied().unwrap_or_default();
2396 altitude_m.push(last + 0.5 * (rate(pair[0]) + rate(pair[1])) * (pair[1] - pair[0]));
2397 }
2398 let velocity: Vec<f64> = time_s.iter().map(|t| rate(t - 1.5) * 2.0).collect();
2399 let scale = velocity_scale(&time_s, &altitude_m, &velocity).unwrap();
2400 assert!((scale.delay_s - 1.5).abs() < 1e-9, "{scale:?}");
2401 assert!((scale.by_area / 2.0 - 1.0).abs() < 1e-3, "{scale:?}");
2402 assert!((scale.by_fit / 2.0 - 1.0).abs() < 1e-3, "{scale:?}");
2403 assert!(
2404 scale.end_height.abs() < 1e-9 && scale.end_error < 1e-9,
2405 "{scale:?}"
2406 );
2407 assert!(velocity_scale(&[0.0, 1.0], &[5.0, 5.0], &[1.0, 1.0]).is_none());
2408 }
2409
2410 #[test]
2413 fn the_time_is_read_in_seconds_from_the_step_or_assumed() {
2414 let rows = |step: f64, count: usize| -> String {
2415 (0..count)
2416 .map(|i| format!("{:.2},0,1000,0\n", i as f64 * step))
2417 .collect()
2418 };
2419 let header = "Time,Altitude,Pressure,Velocity\n";
2420 let log = read(&format!("{header}{}", rows(0.05, 5))).unwrap();
2421 let from_step = notes_starting(&log, "`Time` read in seconds, from the step. ");
2422 assert!(
2423 from_step[0].contains("step between rows, 0.05"),
2424 "{from_step:?}"
2425 );
2426 let log = read(&format!("{header}{}", rows(0.5, 5))).unwrap();
2427 let assumed = notes_starting(&log, "`Time` read in seconds, assumed. ");
2428 assert!(
2429 assumed[0].contains("0.5 as written, isn't within 5%"),
2430 "{assumed:?}"
2431 );
2432 let log = read(&format!("{header}{}", rows(0.05, 1))).unwrap();
2433 assert_eq!(
2434 notes_starting(&log, "`Time` read in seconds, assumed: a single row").len(),
2435 1
2436 );
2437 let log = read(&format!(
2438 "Time [s],Altitude,Pressure,Velocity\n{}",
2439 rows(0.05, 5)
2440 ))
2441 .unwrap();
2442 assert!(
2443 log.notes.iter().all(|n| !n.contains("`Time")),
2444 "{:?}",
2445 log.notes
2446 );
2447 }
2448
2449 #[test]
2453 fn a_pressure_off_the_pad_range_is_kept_as_written() {
2454 for (pad, next) in [
2455 (101.3, 101.2),
2456 (29.92, 29.9),
2457 (499.0, 498.9),
2458 (1_101.0, 1_100.9),
2459 ] {
2460 let text = format!("{HEADER}\n0,0,{pad},0,70, -,9.2\n0.05,1,{next},1,70, -,9.2\n");
2461 let log = read(&text).unwrap();
2462 assert_eq!(log.channels[1].quantity, Quantity::Unrecognized, "{pad}");
2463 assert_eq!(log.channels[1].values, [pad, next]);
2464 let kept = notes_starting(&log, "`Pressure` kept as written, its unit unknown: ");
2465 assert!(
2466 kept[0].contains(&format!(
2467 "the first row's, {pad}, lies outside the 500 to 1100"
2468 )),
2469 "{kept:?}"
2470 );
2471 let assumed = notes_starting(&log, "`Altitude` read in feet, assumed: ");
2472 assert!(assumed[0].contains("unit is unknown"), "{assumed:?}");
2473 }
2474 for (pad, next) in [(500.0, 499.9), (1_100.0, 1_099.9)] {
2476 let text = format!("{HEADER}\n0,0,{pad},0,70, -,9.2\n0.05,1,{next},1,70, -,9.2\n");
2477 let log = read(&text).unwrap();
2478 assert_eq!(log.channels[1].quantity, Quantity::Pressure, "{pad}");
2479 }
2480 }
2481
2482 proptest::proptest! {
2483 #[test]
2486 fn any_text_is_read_or_refused(rows in proptest::collection::vec("[-0-9.,; DrogueMainx]{0,32}", 0..12)) {
2487 let text = format!("{HEADER}\n{}", rows.join("\n"));
2488 if let Ok(log) = read(&text) {
2489 proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
2490 proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
2491 for channel in &log.channels {
2492 proptest::prop_assert_eq!(&channel.time_s, &log.time_s);
2493 proptest::prop_assert_eq!(channel.values.len(), log.time_s.len());
2494 }
2495 }
2496 }
2497 }
2498}