1use hpr_atmos::ussa76::{DRY_AIR_GAS_CONSTANT_J_PER_KG_K, SEA_LEVEL_PRESSURE_PA, Ussa76};
146use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
147
148use crate::error::LogError;
149use crate::log::{Channel, FlightLog, LogFormat, Quantity, Stated};
150use crate::perfectflite::FOOT_M;
151use crate::table::{finite, number, numbered_lines, short};
152
153const FORMAT: &str = "ARTS2 CSV";
155
156const LOGGER: &str = "Ozark Aerospace ARTS2";
158
159const NAMES: [&str; 5] = ["MET", "Acc", "Vel", "iAlt", "pAlt"];
161
162const COARSEST_STEP_FT: f64 = 28.89;
165
166pub(crate) const ALTITUDE_STEP_M: f64 = COARSEST_STEP_FT * FOOT_M;
173
174const COUNT_PA: f64 = 1_000.0 / (1_024.0 * 0.010_59);
181
182const COUNT_TOLERANCE: f64 = 0.15;
188
189const HIGHEST_SITE_M: f64 = 3_000.0;
191
192const WEATHER_SPREAD: f64 = 0.05;
194
195const COLDEST_K: f64 = 253.15;
197const HOTTEST_K: f64 = 318.15;
198
199const STEP_REPEATS: usize = 3;
202
203const STEP_SPREAD: f64 = 2.0 * ROUNDING;
206
207const APOGEE_WINDOW_S: f64 = 1.0;
210
211const DEPLOYMENT_SEARCH_S: f64 = 2.0;
219
220const JUMP_REFERENCE_ROWS: usize = 3;
222
223const JUMP_SHARE: f64 = 0.5;
226
227const APOGEE_SAMPLES: usize = 3;
229
230const GRAVITY_MARGIN: f64 = 0.25;
234
235const INTEGRAL_MARGIN: f64 = 0.10;
239
240const BAROMETRIC_MARGIN: f64 = 0.25;
244
245const SETTLING_CLIMB_M: f64 = 20.0 * ALTITUDE_STEP_M;
248
249const ROUNDING: f64 = 0.01;
251
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254enum Length {
255 Meter,
256 Foot,
257}
258
259impl Length {
260 const BOTH: [Self; 2] = [Self::Meter, Self::Foot];
261
262 fn meters(self) -> f64 {
264 match self {
265 Self::Meter => 1.0,
266 Self::Foot => FOOT_M,
267 }
268 }
269
270 fn gravity(self) -> f64 {
272 STANDARD_GRAVITY_MPS2 / self.meters()
273 }
274
275 fn name(self) -> &'static str {
277 match self {
278 Self::Meter => "meters",
279 Self::Foot => "feet",
280 }
281 }
282
283 fn symbol(self) -> &'static str {
285 match self {
286 Self::Meter => "m",
287 Self::Foot => "ft",
288 }
289 }
290}
291
292fn first_line(text: &str) -> Option<&str> {
294 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
295 text.split(['\r', '\n'])
296 .map(str::trim)
297 .find(|line| !line.is_empty())
298}
299
300fn is_header(line: &str) -> bool {
302 let Some(rest) = line.trim().strip_prefix('#') else {
303 return false;
304 };
305 let mut names = rest.split([' ', '\t', ',']).filter(|name| !name.is_empty());
306 NAMES.iter().all(|expected| {
307 names
308 .next()
309 .is_some_and(|name| name.eq_ignore_ascii_case(expected))
310 }) && names.next().is_none()
311}
312
313pub fn recognizes(text: &str) -> bool {
316 first_line(text).is_some_and(is_header)
317}
318
319struct Rows {
321 time_s: Vec<f64>,
323 values: [Vec<f64>; 4],
325 lines: Vec<usize>,
327 gaps: [(usize, usize); 4],
329}
330
331const ACC: usize = 0;
333const VEL: usize = 1;
334const IALT: usize = 2;
335const PALT: usize = 3;
336
337pub fn read(text: &str) -> Result<FlightLog, LogError> {
348 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
349 let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
350 let Some((header_line, header)) = lines.next() else {
351 return Err(LogError::NotThisFormat {
352 format: FORMAT,
353 message: "the file is empty".to_owned(),
354 });
355 };
356 if !is_header(header) {
357 return Err(LogError::NotThisFormat {
358 format: FORMAT,
359 message: format!(
360 "its first line, {:?}, isn't the ARTS2's interpreted-data header, \
361 `# MET Acc Vel iAlt pAlt`",
362 short(header)
363 ),
364 });
365 }
366 let rows = rows(lines)?;
367 if rows.time_s.is_empty() {
368 return Err(LogError::NoData { format: FORMAT });
369 }
370 let units = decide(&rows, header_line)?;
371 let mut notes = units.notes.clone();
372 let mut values = rows.values.clone();
373 closing_zeros(&rows, &units, &mut values, &mut notes);
374 for (index, (count, line)) in rows.gaps.iter().enumerate() {
375 if *count > 0 {
376 notes.push(format!(
377 "`{}` has {count} cells that are empty or aren't a number, the first on line \
378 {line}: gaps",
379 NAMES[index + 1]
380 ));
381 }
382 }
383 let length = units.length.meters();
384 let acc_scale = units.acceleration.unwrap_or(1.0);
385 let ialt_scale = if units.inertial { length } else { 1.0 };
386 let convert_column = |column: usize, scale: f64| {
387 let column_values = values.get(column).map_or(&[][..], Vec::as_slice);
388 convert(column_values, scale, &rows.lines, NAMES[column + 1])
389 };
390 let acc = convert_column(ACC, acc_scale)?;
391 let vel = convert_column(VEL, length)?;
392 let ialt = convert_column(IALT, ialt_scale)?;
393 let altitude_m = convert_column(PALT, length)?;
394 if let Some(first) = altitude_m.first()
395 && first.is_finite()
396 && first.abs() > ALTITUDE_STEP_M
397 {
398 notes.push(format!(
399 "`pAlt` reads {first:.2} m on the first row, more than one barometer step from zero: \
400 the logger's ground isn't where the record starts"
401 ));
402 }
403 let channel = |index: usize, quantity: Quantity, values: Vec<f64>| Channel {
404 column: NAMES[index + 1].to_owned(),
405 quantity,
406 time_s: rows.time_s.clone(),
407 values,
408 };
409 let acc_quantity = if units.acceleration.is_some() {
410 Quantity::Acceleration
411 } else {
412 Quantity::Unrecognized
413 };
414 let ialt_quantity = if units.inertial {
415 Quantity::InertialAltitude
416 } else {
417 Quantity::Unrecognized
418 };
419 let channels = vec![
420 channel(ACC, acc_quantity, acc),
421 channel(VEL, Quantity::Speed, vel),
422 channel(IALT, ialt_quantity, ialt),
423 channel(PALT, Quantity::AltitudeAboveGround, altitude_m.clone()),
424 ];
425 Ok(FlightLog {
426 format: LogFormat::Arts2Csv,
427 logger: LOGGER.to_owned(),
428 serial_number: None,
429 firmware: None,
430 flight_number: None,
431 stated: Stated::default(),
432 time_s: rows.time_s,
433 altitude_m,
434 vertical_speed_m_s: None,
435 temperature_k: None,
436 battery_v: None,
437 channels,
438 events: Vec::new(),
439 notes,
440 })
441}
442
443fn convert(
453 values: &[f64],
454 scale: f64,
455 lines: &[usize],
456 column: &str,
457) -> Result<Vec<f64>, LogError> {
458 values
459 .iter()
460 .zip(lines)
461 .map(|(value, &line)| finite(value * scale, FORMAT, line, column))
462 .collect()
463}
464
465fn rows<'a>(lines: impl Iterator<Item = (usize, &'a str)>) -> Result<Rows, LogError> {
467 let mut rows = Rows {
468 time_s: Vec::new(),
469 values: Default::default(),
470 lines: Vec::new(),
471 gaps: [(0, 0); 4],
472 };
473 for (line, text) in lines {
474 let cells: Vec<&str> = text.split(',').take(NAMES.len() + 1).collect();
477 if cells.len() != NAMES.len() {
478 return Err(LogError::Syntax {
479 format: FORMAT,
480 line,
481 message: format!(
482 "a row of {} cells, where the header names {}: {:?}",
483 if cells.len() > NAMES.len() {
484 format!("more than {}", NAMES.len())
485 } else {
486 cells.len().to_string()
487 },
488 NAMES.len(),
489 short(text)
490 ),
491 });
492 }
493 let Some(time) = cells.first().and_then(|cell| number(cell, false)) else {
494 return Err(LogError::Syntax {
495 format: FORMAT,
496 line,
497 message: format!("`MET` isn't a number: {:?}", short(text)),
498 });
499 };
500 if let Some(previous) = rows.time_s.last()
501 && time <= *previous
502 {
503 return Err(LogError::Syntax {
504 format: FORMAT,
505 line,
506 message: format!(
507 "`MET` {time} doesn't come after the row before's, {previous}: the clock must \
508 increase"
509 ),
510 });
511 }
512 rows.time_s.push(time);
513 rows.lines.push(line);
514 for (index, cell) in cells.iter().skip(1).enumerate() {
515 let value = number(cell, false).unwrap_or(f64::NAN);
516 if value.is_nan() {
517 let (count, first) = &mut rows.gaps[index];
518 if *count == 0 {
519 *first = line;
520 }
521 *count += 1;
522 }
523 rows.values[index].push(value);
524 }
525 }
526 Ok(rows)
527}
528
529#[derive(Debug, Clone)]
531struct Units {
532 length: Length,
534 acceleration: Option<f64>,
536 inertial: bool,
538 boost_ratio: Option<f64>,
540 notes: Vec<String>,
541}
542
543struct Apogee {
545 peak: usize,
547 row: usize,
549 time_s: f64,
551}
552
553fn apogee(time_s: &[f64], vel: &[f64]) -> Option<Apogee> {
555 let peak = vel
556 .iter()
557 .enumerate()
558 .filter(|(_, value)| value.is_finite())
559 .fold(
560 None,
561 |best: Option<(usize, f64)>, (row, value)| match best {
562 Some((_, top)) if top >= *value => best,
563 _ => Some((row, *value)),
564 },
565 )
566 .filter(|(_, top)| *top > 0.0)?
567 .0;
568 let mut before = (peak, *vel.get(peak)?);
569 for (row, value) in vel.iter().enumerate().skip(peak + 1) {
570 if !value.is_finite() {
571 continue;
572 }
573 if *value <= 0.0 {
574 let (t0, t1) = (*time_s.get(before.0)?, *time_s.get(row)?);
575 let share = before.1 / (before.1 - value);
576 return Some(Apogee {
577 peak,
578 row,
579 time_s: t0 + share * (t1 - t0),
580 });
581 }
582 before = (row, *value);
583 }
584 None
585}
586
587fn acc_jumps(acc: &[f64], row: usize) -> bool {
592 let Some(before) = row
593 .checked_sub(JUMP_REFERENCE_ROWS)
594 .and_then(|start| acc.get(start..row))
595 else {
596 return true;
597 };
598 let mut before = before.to_vec();
599 if before.iter().any(|value| !value.is_finite()) {
600 return true;
601 }
602 before.sort_by(f64::total_cmp);
603 let Some(&level) = before.get(JUMP_REFERENCE_ROWS / 2) else {
604 return true;
605 };
606 let off = |row: usize| {
608 acc.get(row).is_none_or(|value| {
609 let close = (value - level).abs() <= JUMP_SHARE * level.abs();
610 !close
611 })
612 };
613 off(row) && off(row + 1)
614}
615
616struct Coast {
618 slope: f64,
620 points: usize,
622 jump_s: Option<f64>,
624}
625
626struct NoCoast {
629 jump_s: Option<f64>,
630 points: usize,
631}
632
633fn coast_slope(
639 time_s: &[f64],
640 vel: &[f64],
641 acc: &[f64],
642 apogee: &Apogee,
643) -> Result<Coast, NoCoast> {
644 let time = |row: usize| time_s.get(row).copied().unwrap_or(f64::NAN);
645 let scan_from_s = apogee.time_s - DEPLOYMENT_SEARCH_S - APOGEE_WINDOW_S;
646 let jumps: Vec<usize> = (apogee.peak + 1..=apogee.row)
647 .filter(|row| time(*row) >= scan_from_s && acc_jumps(acc, *row))
648 .collect();
649 let first = jumps
650 .iter()
651 .copied()
652 .find(|row| time(*row) >= apogee.time_s - DEPLOYMENT_SEARCH_S);
653 let (end, to_s, jump_s) = match first {
654 Some(row) => (row, time(row), Some(time(row))),
655 None => (apogee.row + 1, apogee.time_s, None),
656 };
657 let start = jumps
658 .iter()
659 .copied()
660 .filter(|row| *row < end)
661 .fold(apogee.peak, usize::max);
662 let points: Vec<(f64, f64)> = (start..end)
663 .filter_map(|row| Some((*time_s.get(row)?, *vel.get(row)?)))
664 .filter(|(time, value)| value.is_finite() && *time >= to_s - APOGEE_WINDOW_S)
665 .collect();
666 let fit = fitted_slope(&points);
667 match fit {
668 Some(slope) if points.len() >= APOGEE_SAMPLES => Ok(Coast {
669 slope,
670 points: points.len(),
671 jump_s,
672 }),
673 _ => Err(NoCoast {
674 jump_s,
675 points: points.len(),
676 }),
677 }
678}
679
680fn fitted_slope(points: &[(f64, f64)]) -> Option<f64> {
682 let count = points.len() as f64;
683 let mean_t = points.iter().map(|p| p.0).sum::<f64>() / count;
684 let mean_v = points.iter().map(|p| p.1).sum::<f64>() / count;
685 let spread: f64 = points.iter().map(|p| (p.0 - mean_t).powi(2)).sum();
686 let slope = points
687 .iter()
688 .map(|p| (p.0 - mean_t) * (p.1 - mean_v))
689 .sum::<f64>()
690 / spread;
691 slope.is_finite().then_some(slope)
692}
693
694fn ground_densities_kg_m3() -> (f64, f64) {
699 let gas = DRY_AIR_GAS_CONSTANT_J_PER_KG_K;
700 let densest = SEA_LEVEL_PRESSURE_PA * (1.0 + WEATHER_SPREAD) / (gas * COLDEST_K);
701 let highest_pa = Ussa76::standard()
702 .sample(HIGHEST_SITE_M)
703 .map_or(f64::NAN, |sample| sample.air.pressure_pa);
704 let thinnest = highest_pa * (1.0 - WEATHER_SPREAD) / (gas * HOTTEST_K);
705 (densest, thinnest)
706}
707
708fn step_band_m() -> (f64, f64) {
712 let (densest, thinnest) = ground_densities_kg_m3();
713 (
714 COUNT_PA * (1.0 - COUNT_TOLERANCE) / (densest * STANDARD_GRAVITY_MPS2),
715 COUNT_PA * (1.0 + COUNT_TOLERANCE) / (thinnest * STANDARD_GRAVITY_MPS2),
716 )
717}
718
719fn step_band(unit: Length) -> (f64, f64) {
721 let (least, most) = step_band_m();
722 (least / unit.meters(), most / unit.meters())
723}
724
725fn smallest_step(palt: &[f64]) -> Option<(f64, usize)> {
730 let written: Vec<f64> = palt.iter().copied().filter(|v| v.is_finite()).collect();
731 let mut steps: Vec<f64> = written
733 .windows(2)
734 .filter_map(|pair| match pair {
735 [a, b] => Some(((b - a).abs() * 100.0).round()),
736 _ => None,
737 })
738 .filter(|step| step.is_finite() && *step >= 1.0)
739 .collect();
740 steps.sort_by(f64::total_cmp);
741 let spread = (STEP_SPREAD * 100.0).round();
742 steps.iter().enumerate().find_map(|(at, step)| {
743 let within = steps
744 .get(at..)
745 .unwrap_or_default()
746 .iter()
747 .take_while(|other| **other <= step + spread)
748 .count();
749 (within >= STEP_REPEATS).then_some((step / 100.0, within))
750 })
751}
752
753fn rise_and_integral(time_s: &[f64], of: &[f64], rate: &[f64], end: usize) -> (f64, f64) {
756 let mut rise = 0.0;
757 let mut integral = 0.0;
758 for row in 1..=end.min(time_s.len().saturating_sub(1)) {
759 let (Some(&[t0, t1]), Some(&[a0, a1]), Some(&[r0, r1])) = (
760 time_s
761 .get(row - 1..=row)
762 .and_then(|s| <&[f64; 2]>::try_from(s).ok()),
763 of.get(row - 1..=row)
764 .and_then(|s| <&[f64; 2]>::try_from(s).ok()),
765 rate.get(row - 1..=row)
766 .and_then(|s| <&[f64; 2]>::try_from(s).ok()),
767 ) else {
768 continue;
769 };
770 if [a0, a1, r0, r1].iter().all(|value| value.is_finite()) {
771 rise += a1 - a0;
772 integral += 0.5 * (r0 + r1) * (t1 - t0);
773 }
774 }
775 (rise, integral)
776}
777
778fn near(value: f64, target: f64, margin: f64) -> bool {
780 value.is_finite() && (value - target).abs() <= margin * target.abs()
781}
782
783fn decide(rows: &Rows, header_line: usize) -> Result<Units, LogError> {
785 let [acc, vel, ialt, palt] = &rows.values;
786 let time_s = &rows.time_s;
787 let line_of = |row: usize| rows.lines.get(row).copied().unwrap_or(header_line);
788 let refuse = |line: usize, message: String| LogError::Unit {
789 format: FORMAT,
790 line,
791 message,
792 };
793
794 let Some(apogee) = apogee(time_s, vel) else {
796 return Err(refuse(
797 header_line,
798 "`Vel` never comes back to zero after its highest value: without the apogee, no \
799 unit for it, nor for `pAlt`, can be decided"
800 .to_owned(),
801 ));
802 };
803 let apogee_line = line_of(apogee.row);
804 let window = |jump_s: Option<f64>| {
805 jump_s.map_or_else(
806 || format!("the {APOGEE_WINDOW_S} s before"),
807 |at| format!("the {APOGEE_WINDOW_S} s of coast before `Acc` jumps at {at:.2} s"),
808 )
809 };
810 let coast = match coast_slope(time_s, vel, acc, &apogee) {
811 Ok(coast) => coast,
812 Err(none) => {
813 return Err(refuse(
814 apogee_line,
815 format!(
816 "into its zero at {:.2} s, `Vel` has {} samples, fewer than {APOGEE_SAMPLES}, \
817 in {}. Its slope at the apogee decides its unit, and it can't be fitted",
818 apogee.time_s,
819 none.points,
820 window(none.jump_s)
821 ),
822 ));
823 }
824 };
825 let slope = coast.slope;
826 let by_slope: Vec<Length> = Length::BOTH
827 .into_iter()
828 .filter(|unit| near(-slope, unit.gravity(), GRAVITY_MARGIN))
829 .collect();
830 let [length] = by_slope[..] else {
831 return Err(refuse(
832 apogee_line,
833 format!(
834 "into its zero at {:.2} s, over {}, `Vel` changes by {slope:.3} a second. That is \
835 not within {:.0}% of standard gravity in either m/s² (−9.807) or ft/s² \
836 (−32.174). No unit for it, nor for `pAlt`, can be decided",
837 apogee.time_s,
838 window(coast.jump_s),
839 GRAVITY_MARGIN * 100.0
840 ),
841 ));
842 };
843
844 let (_, climb) = rise_and_integral(time_s, vel, vel, apogee.row);
846 let climb_m = climb * length.meters();
847 let settles = climb_m >= SETTLING_CLIMB_M;
849 if !settles {
850 return Err(refuse(
851 apogee_line,
852 format!(
853 "`Vel` integrates to a climb of {climb_m:.1} m by the apogee. That is under the \
854 {SETTLING_CLIMB_M:.0} m from which the barometer's step lets `pAlt`'s unit be \
855 decided"
856 ),
857 ));
858 }
859 let bands = Length::BOTH.map(|unit| {
860 let (least, most) = step_band(unit);
861 format!("{least:.2} to {most:.2} {}", unit.symbol())
862 });
863 let Some((step, repeats)) = smallest_step(palt) else {
864 return Err(refuse(
865 header_line,
866 format!(
867 "`pAlt` has no step written {STEP_REPEATS} times, to within {STEP_SPREAD:.2}. The \
868 barometer's count can't be measured, and it must bear out the unit `Vel`'s \
869 slope gives"
870 ),
871 ));
872 };
873 let by_step: Vec<Length> = Length::BOTH
874 .into_iter()
875 .filter(|unit| {
876 let (least, most) = step_band(*unit);
877 step >= least && step <= most
878 })
879 .collect();
880 let [stepped] = by_step[..] else {
881 return Err(refuse(
882 header_line,
883 format!(
884 "`pAlt`'s smallest step, {step:.2}, is one count of the barometer near the ground \
885 in neither meters ({}) nor feet ({}). No unit for it, nor for `Vel`, can be \
886 decided",
887 bands[0], bands[1]
888 ),
889 ));
890 };
891 if stepped != length {
892 return Err(refuse(
893 apogee_line,
894 format!(
895 "`Vel`'s slope into its zero at {:.2} s, {slope:.3} a second, is standard gravity \
896 in {} per second squared. `pAlt`'s smallest step, {step:.2}, is one count of \
897 the barometer in {}. The two disagree, and no unit is decided",
898 apogee.time_s,
899 length.name(),
900 stepped.name()
901 ),
902 ));
903 }
904 let gravities = -slope / length.gravity();
905 let mut notes = vec![format!(
906 "`Vel` read in {} per second, from the apogee and the barometer's step: its line falls \
907 at {:.3} a second. That line runs through its {} samples of {}, into its zero at \
908 {:.2} s. The line's fall is {gravities:.3} of standard gravity's {:.3} {}/s², within \
909 {:.0}%, and `pAlt`'s step is a count in {} too",
910 length.name(),
911 -slope,
912 coast.points,
913 window(coast.jump_s),
914 apogee.time_s,
915 length.gravity(),
916 length.symbol(),
917 GRAVITY_MARGIN * 100.0,
918 length.name()
919 )];
920
921 let highest = palt
923 .iter()
924 .filter(|value| value.is_finite())
925 .fold(f64::NEG_INFINITY, |top, value| top.max(*value));
926 let share = highest / climb;
927 if !near(share, 1.0, BAROMETRIC_MARGIN) {
928 return Err(refuse(
929 apogee_line,
930 format!(
931 "`pAlt`'s highest value, {highest:.2}, is {share:.3} times the climb `Vel` \
932 integrates to by the apogee, {climb:.2} {}, not within {:.0}%. No unit for the \
933 barometric altitude can be decided",
934 length.symbol(),
935 BAROMETRIC_MARGIN * 100.0
936 ),
937 ));
938 }
939 let band = match length {
940 Length::Meter => &bands[0],
941 Length::Foot => &bands[1],
942 };
943 notes.push(format!(
944 "`pAlt` read in {}, from its step and `Vel`: its smallest step is {step:.2}. {repeats} of \
945 its steps are within {STEP_SPREAD:.2} of it. The smallest step is one count of the \
946 barometer near the ground in {} ({band}). `pAlt`'s highest value, {highest:.2}, is \
947 {share:.3} times the climb `Vel` integrates to by the apogee, {climb:.2} {}, within \
948 {:.0}%",
949 length.name(),
950 length.name(),
951 length.symbol(),
952 BAROMETRIC_MARGIN * 100.0
953 ));
954 let met_note = format!(
955 "`MET` read in seconds, from the apogee: `Vel` is in {} per second, as the barometer's \
956 step has it. `Vel` falls into its zero at {gravities:.3} of standard gravity a second. A \
957 clock in milliseconds or minutes would put that fall 1,000 or 60 times off",
958 length.name()
959 );
960
961 let (rise, integral) = rise_and_integral(time_s, vel, acc, apogee.peak);
963 let ratio = rise / integral;
964 let boost_ratio = ratio.is_finite().then_some(ratio);
965 let acceleration = if near(ratio, 1.0, INTEGRAL_MARGIN) {
966 notes.push(format!(
967 "`Acc` read in {} per second squared, from `Vel`: over the boost, `Vel` rises \
968 {ratio:.3} times `Acc`'s integral, within {:.0}% of 1",
969 length.name(),
970 INTEGRAL_MARGIN * 100.0
971 ));
972 Some(length.meters())
973 } else if near(ratio, length.gravity(), INTEGRAL_MARGIN) {
974 notes.push(format!(
975 "`Acc` read in standard gravities, 9.806 65 m/s², from `Vel`: over the boost, `Vel` \
976 rises {ratio:.3} times `Acc`'s integral. That is within {:.0}% of standard \
977 gravity's {:.3} {}/s²",
978 INTEGRAL_MARGIN * 100.0,
979 length.gravity(),
980 length.symbol()
981 ));
982 Some(STANDARD_GRAVITY_MPS2)
983 } else {
984 notes.push(format!(
985 "`Acc` kept as written: over the boost, `Vel` rises {ratio:.3} times `Acc`'s \
986 integral. That is within {:.0}% of neither 1 nor standard gravity in {} per second \
987 squared",
988 INTEGRAL_MARGIN * 100.0,
989 length.name()
990 ));
991 None
992 };
993
994 let (rise, integral) = rise_and_integral(time_s, ialt, vel, apogee.row);
996 let ratio = rise / integral;
997 let inertial = near(ratio, 1.0, INTEGRAL_MARGIN);
998 notes.push(if inertial {
999 format!(
1000 "`iAlt` read in {}, from `Vel`: to the apogee it rises {ratio:.4} times `Vel`'s \
1001 integral, within {:.0}% of 1",
1002 length.name(),
1003 INTEGRAL_MARGIN * 100.0
1004 )
1005 } else {
1006 format!(
1007 "`iAlt` kept as written: to the apogee it rises {ratio:.4} times `Vel`'s integral, \
1008 not within {:.0}% of 1",
1009 INTEGRAL_MARGIN * 100.0
1010 )
1011 });
1012 notes.push(met_note);
1013 Ok(Units {
1014 length,
1015 acceleration,
1016 inertial,
1017 boost_ratio,
1018 notes,
1019 })
1020}
1021
1022fn closing_zeros(rows: &Rows, units: &Units, values: &mut [Vec<f64>; 4], notes: &mut Vec<String>) {
1025 let count = rows.time_s.len();
1026 let at = |column: usize, row: usize| rows.values[column].get(row).copied().unwrap_or(f64::NAN);
1027 let vel_scale = units.acceleration.and(units.boost_ratio).map(f64::abs);
1030 for (column, rate, scale) in [(VEL, ACC, vel_scale), (IALT, VEL, Some(1.0))] {
1031 let run = (0..count)
1032 .rev()
1033 .take_while(|row| at(column, *row) == 0.0)
1034 .count();
1035 let Some(before) = count.checked_sub(run + 1) else {
1036 continue;
1037 };
1038 let (Some(scale), Some(last), Some(&start)) =
1039 (scale, count.checked_sub(1), rows.time_s.get(before))
1040 else {
1041 continue;
1042 };
1043 let span = rows.time_s.get(last).map_or(f64::NAN, |end| end - start);
1044 let fastest = (before..count)
1047 .map(|row| at(rate, row).abs())
1048 .filter(|value| value.is_finite())
1049 .fold(0.0, f64::max);
1050 let reach = fastest * scale * span;
1051 let previous = at(column, before);
1052 if run > 0
1053 && previous.is_finite()
1054 && reach.is_finite()
1055 && previous.abs() > 2.0 * reach + ROUNDING
1056 {
1057 for row in before + 1..count {
1058 if let Some(cell) = values[column].get_mut(row) {
1059 *cell = f64::NAN;
1060 }
1061 }
1062 notes.push(format!(
1063 "the last {run} rows, from line {}, write `{}` as 0, where the row before reads \
1064 {previous:.2}. That is more than twice what `{}` can change it by in {span:.2} s. \
1065 So they aren't its integral, and they are gaps",
1066 rows.lines.get(before + 1).copied().unwrap_or_default(),
1067 NAMES[column + 1],
1068 NAMES[rate + 1],
1069 ));
1070 }
1071 }
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076 use super::*;
1077
1078 fn flight(boost_s: f64, boost_m_s2: f64, length_m: f64, acc_m_s2: f64) -> String {
1085 flight_deploying(boost_s, boost_m_s2, length_m, acc_m_s2, None, 0.1)
1086 }
1087
1088 fn flight_deploying(
1093 boost_s: f64,
1094 boost_m_s2: f64,
1095 length_m: f64,
1096 acc_m_s2: f64,
1097 deploy_m_s: Option<f64>,
1098 dt: f64,
1099 ) -> String {
1100 let mut deployed = false;
1101 let mut text = String::from("# MET Acc Vel iAlt pAlt \n");
1102 let (mut vel, mut ialt, mut previous) = (0.0_f64, 0.0_f64, None::<f64>);
1103 let mut apogee: Option<(f64, f64)> = None;
1104 for row in 0..10_000 {
1105 let time = f64::from(row) * dt;
1106 let acc_si = if row == 0 {
1107 0.0
1108 } else if time <= boost_s + 1e-9 {
1109 boost_m_s2
1110 } else if apogee.is_none() {
1111 deployed |= deploy_m_s.is_some_and(|speed| vel <= speed);
1112 let chute = if deployed {
1113 STANDARD_GRAVITY_MPS2 * (vel / 5.0).powi(2)
1114 } else {
1115 0.0
1116 };
1117 -STANDARD_GRAVITY_MPS2 - 0.0004 * vel * vel.abs() - chute
1118 } else {
1119 -0.3
1120 };
1121 let acc = (acc_si / acc_m_s2 * 100.0).round() / 100.0;
1122 if let Some(before) = previous {
1123 let next = vel + 0.5 * (before + acc) * acc_m_s2 * dt;
1124 ialt = (ialt + 0.5 * (vel + next) * dt).max(0.0);
1125 if apogee.is_none() && vel > 0.0 && next <= 0.0 {
1126 apogee = Some((time, 0.97 * ialt));
1127 }
1128 vel = next;
1129 }
1130 previous = Some(acc);
1131 let baro = apogee.map_or(0.97 * ialt, |(at, top)| (top - 20.0 * (time - at)).max(0.0));
1132 let palt = (baro / 9.0).round() * 9.0;
1133 text.push_str(&format!(
1134 "{time:.3},{acc:.2},{:.2},{:.2},{:.2}\n",
1135 vel / length_m,
1136 ialt / length_m,
1137 palt / length_m
1138 ));
1139 if apogee.is_some_and(|(at, _)| time > at + 5.0) {
1140 break;
1141 }
1142 }
1143 text
1144 }
1145
1146 fn metric() -> String {
1148 flight(2.0, 70.0, 1.0, 1.0)
1149 }
1150
1151 fn english() -> String {
1153 flight(2.0, 70.0, FOOT_M, STANDARD_GRAVITY_MPS2)
1154 }
1155
1156 fn scaled(text: &str, column: usize, factor: f64) -> String {
1158 text.lines()
1159 .map(|line| {
1160 if line.starts_with('#') {
1161 return format!("{line}\n");
1162 }
1163 let cells: Vec<String> = line
1164 .split(',')
1165 .enumerate()
1166 .map(|(index, cell)| {
1167 if index == column + 1 {
1168 format!("{:.2}", cell.parse::<f64>().unwrap() * factor)
1169 } else {
1170 cell.to_owned()
1171 }
1172 })
1173 .collect();
1174 format!("{}\n", cells.join(","))
1175 })
1176 .collect()
1177 }
1178
1179 fn highest(values: &[f64]) -> f64 {
1180 values
1181 .iter()
1182 .filter(|value| value.is_finite())
1183 .fold(f64::NEG_INFINITY, |top, value| top.max(*value))
1184 }
1185
1186 fn unit_message(result: Result<FlightLog, LogError>) -> String {
1187 match result {
1188 Err(LogError::Unit { message, .. }) => message,
1189 other => panic!("expected a unit error, got {other:?}"),
1190 }
1191 }
1192
1193 #[test]
1194 fn the_header_is_recognized_and_others_are_not() {
1195 assert!(recognizes(
1196 "# MET Acc Vel iAlt pAlt \n0.000,0.00,0.00,0.00,0.00\n"
1197 ));
1198 assert!(recognizes("\u{feff}\r\n#MET,Acc,Vel,iAlt,pAlt\r\n"));
1199 assert!(recognizes("# met acc vel ialt palt\n"));
1200 for other in [
1201 "MET,Acc(HI),Acc/Baro(LO),Baro(HI),State\n0.000,512,4,777,64\n",
1202 "#version,serial,flight,call,time,clock,rssi,lqi\n",
1203 "# Comments\n# MET Acc Vel iAlt pAlt\n",
1204 "# MET Acc Vel iAlt\n",
1205 "# MET Acc Vel iAlt pAlt State\n",
1206 "# MET Acc Vel pAlt iAlt\n",
1207 "MET Acc Vel iAlt pAlt\n",
1208 "",
1209 ] {
1210 assert!(!recognizes(other), "{other:?}");
1211 }
1212 }
1213
1214 #[test]
1218 fn metric_and_english_files_read_to_the_same_flight() {
1219 let metric = read(&metric()).unwrap();
1220 let english = read(&english()).unwrap();
1221 let top_m = highest(&metric.altitude_m);
1222 let top_e = highest(&english.altitude_m);
1223 assert!(top_m > 700.0 && top_m < 1_000.0, "{top_m}");
1224 assert!((top_m - top_e).abs() < 0.01, "{top_m} m against {top_e} m");
1226 for (column, allowed) in [(0, 0.06), (1, 3.0), (2, 3.0), (3, 9.01)] {
1230 let (a, b) = (&metric.channels[column], &english.channels[column]);
1231 assert_eq!(a.quantity, b.quantity, "{}", a.column);
1232 let worst = a
1233 .values
1234 .iter()
1235 .zip(&b.values)
1236 .filter(|(x, y)| x.is_finite() && y.is_finite())
1237 .map(|(x, y)| (x - y).abs())
1238 .fold(0.0, f64::max);
1239 assert!(worst < allowed, "{}: {worst}", a.column);
1240 }
1241 let quantities: Vec<Quantity> = metric.channels.iter().map(|c| c.quantity).collect();
1242 assert_eq!(
1243 quantities,
1244 [
1245 Quantity::Acceleration,
1246 Quantity::Speed,
1247 Quantity::InertialAltitude,
1248 Quantity::AltitudeAboveGround
1249 ]
1250 );
1251 let from = "per second, from the apogee and the barometer's step: ";
1252 assert!(metric.notes[0].starts_with(&format!("`Vel` read in meters {from}")));
1253 assert!(english.notes[0].starts_with(&format!("`Vel` read in feet {from}")));
1254 assert!(metric.notes[1].starts_with("`pAlt` read in meters, from its step and `Vel`: "));
1255 assert!(english.notes[1].starts_with("`pAlt` read in feet, from its step and `Vel`: "));
1256 assert!(english.notes[2].starts_with("`Acc` read in standard gravities, "));
1257 assert!(metric.notes[2].starts_with("`Acc` read in meters per second squared, "));
1258 for log in [&metric, &english] {
1259 assert!(log.notes[4].starts_with("`MET` read in seconds, from the apogee: "));
1260 }
1261 assert!(metric.vertical_speed_m_s.is_none());
1262 }
1263
1264 #[test]
1267 fn a_velocity_that_falls_at_no_gravity_is_refused() {
1268 for factor in [2.0, 0.5, 1.6 / FOOT_M] {
1269 let message = unit_message(read(&scaled(&metric(), VEL, factor)));
1270 assert!(
1271 message.contains("not within 25% of standard gravity in either"),
1272 "{factor}: {message}"
1273 );
1274 }
1275 }
1276
1277 #[test]
1282 fn a_barometric_altitude_in_another_unit_is_refused() {
1283 for (text, slope, step) in [
1284 (scaled(&metric(), PALT, 1.0 / FOOT_M), "meters", "feet"),
1285 (scaled(&english(), PALT, FOOT_M), "feet", "meters"),
1286 ] {
1287 let message = unit_message(read(&text));
1288 assert!(
1289 message.contains(&format!(
1290 "is standard gravity in {slope} per second squared"
1291 )) && message.contains(&format!(
1292 "one count of the barometer in {step}. The two disagree"
1293 )),
1294 "{message}"
1295 );
1296 }
1297 for text in [metric(), english()] {
1298 let message = unit_message(read(&scaled(&text, PALT, 1.5)));
1299 assert!(message.starts_with("`pAlt`'s highest value, "), "{message}");
1300 }
1301 }
1302
1303 #[test]
1307 fn a_step_in_neither_band_is_refused() {
1308 let (least_m, most_m) = step_band(Length::Meter);
1309 let (least_ft, most_ft) = step_band(Length::Foot);
1310 assert!(most_m < least_ft, "{most_m} m against {least_ft} ft");
1312 assert!((COUNT_PA - 92.216).abs() < 1e-3, "{COUNT_PA}");
1314 let (densest, thinnest) = ground_densities_kg_m3();
1315 assert!((densest - 1.4640).abs() < 1e-3, "{densest}");
1316 assert!((thinnest - 0.7294).abs() < 1e-3, "{thinnest}");
1317 assert!((least_m - 5.460).abs() < 1e-3 && (most_m - 14.83).abs() < 1e-2);
1318 assert!((least_ft - 17.91).abs() < 1e-2 && (most_ft - 48.64).abs() < 1e-2);
1319 for factor in [0.5, 1.8] {
1322 let message = unit_message(read(&scaled(&metric(), PALT, factor)));
1323 assert!(
1324 message.contains("in neither meters ("),
1325 "{factor}: {message}"
1326 );
1327 }
1328 assert_eq!(smallest_step(&[0.0, 9.0, 29.0, 70.0, 153.0]), None);
1331 let steps = [0.0, 9.0, 18.01, f64::NAN, 27.02, 36.02, 30.0];
1332 assert_eq!(smallest_step(&steps), Some((9.0, 4)));
1333 let text: String = metric()
1335 .lines()
1336 .enumerate()
1337 .map(|(row, line)| match line.rsplit_once(',') {
1338 Some((head, _)) if row > 0 => {
1339 let row = row as f64;
1340 format!("{head},{:.2}\n", 0.37 * row * (row + 1.0) / 2.0)
1341 }
1342 _ => format!("{line}\n"),
1343 })
1344 .collect();
1345 let message = unit_message(read(&text));
1346 assert!(
1347 message.starts_with("`pAlt` has no step written 3 times"),
1348 "{message}"
1349 );
1350 }
1351
1352 #[test]
1356 fn a_parachute_out_more_than_2_s_early_slows_vel_little() {
1357 let g = STANDARD_GRAVITY_MPS2;
1358 let least = 4.0 * g / std::f64::consts::PI;
1360 assert!((least * std::f64::consts::FRAC_PI_2 / g - DEPLOYMENT_SEARCH_S).abs() < 1e-12);
1361 let fall = |rate: f64| rate * (g / rate).tan() / g;
1363 let mut before = fall(least);
1364 assert!(before < 1.28 && before > 1.27, "{before}");
1365 for rate in (1..=100).map(|step| least + f64::from(step)) {
1366 let now = fall(rate);
1367 assert!(now < before && now > 1.0, "{rate}: {now}");
1368 before = now;
1369 }
1370 assert!(!near(1.28 * FOOT_M, 1.0, GRAVITY_MARGIN));
1372 assert!(!near(1.28 / FOOT_M, 1.0, GRAVITY_MARGIN));
1373 }
1374
1375 #[test]
1377 fn columns_no_check_bears_out_are_kept_as_written() {
1378 let log = read(&scaled(&metric(), ACC, 3.0)).unwrap();
1379 assert_eq!(log.channels[0].quantity, Quantity::Unrecognized);
1380 assert!(
1381 log.notes
1382 .iter()
1383 .any(|n| n.starts_with("`Acc` kept as written: "))
1384 );
1385 let log = read(&scaled(&metric(), IALT, 1.0 / FOOT_M)).unwrap();
1386 assert_eq!(log.channels[2].quantity, Quantity::Unrecognized);
1387 assert!(
1388 log.notes
1389 .iter()
1390 .any(|n| n.starts_with("`iAlt` kept as written: "))
1391 );
1392 let log = read(&scaled(&metric(), ACC, 1.0 / STANDARD_GRAVITY_MPS2)).unwrap();
1394 assert_eq!(log.channels[0].quantity, Quantity::Acceleration);
1395 assert!(log.notes[2].starts_with("`Acc` read in standard gravities"));
1396 }
1397
1398 #[test]
1402 fn the_apogee_margin_is_25_percent() {
1403 for (factor, reads) in [(1.22, true), (1.28, false), (0.78, true), (0.72, false)] {
1404 let text = [ACC, VEL, IALT, PALT]
1405 .into_iter()
1406 .fold(metric(), |text, column| scaled(&text, column, factor));
1407 let result = read(&text);
1408 if reads {
1409 let log = result.unwrap();
1410 assert!(log.notes[0].starts_with("`Vel` read in meters per second"));
1411 } else {
1412 assert!(matches!(result, Err(LogError::Unit { .. })), "{factor}");
1413 }
1414 }
1415 }
1416
1417 #[test]
1420 fn low_and_unfinished_flights_are_refused() {
1421 let message = unit_message(read(&flight(1.0, 40.0, 1.0, 1.0)));
1423 assert!(message.contains("under the 176 m"), "{message}");
1424 let message = unit_message(read(&flight(0.3, 30.0, 1.0, 1.0)));
1426 assert!(
1427 message.contains("`Vel` has 1 samples, fewer than 3, in the 1 s of coast before"),
1428 "{message}"
1429 );
1430 let cut: String = metric()
1431 .lines()
1432 .take(60)
1433 .map(|l| format!("{l}\n"))
1434 .collect();
1435 let message = unit_message(read(&cut));
1436 assert!(
1437 message.starts_with("`Vel` never comes back to zero"),
1438 "{message}"
1439 );
1440 let message = unit_message(read("# MET Acc Vel iAlt pAlt\n0,,,,\n0.02,,,,\n"));
1441 assert!(
1442 message.starts_with("`Vel` never comes back to zero"),
1443 "{message}"
1444 );
1445 }
1446
1447 #[test]
1449 fn closing_zeros_beyond_reach_are_gaps() {
1450 let mut text = metric();
1451 let last = text.trim_end().rsplit_once('\n').unwrap().1.to_owned();
1452 let cells: Vec<&str> = last.split(',').collect();
1453 let time: f64 = cells[0].parse().unwrap();
1454 text.push_str(&format!(
1455 "{:.3},{},0.00,{},{}\n",
1456 time + 0.1,
1457 cells[1],
1458 cells[3],
1459 cells[4]
1460 ));
1461 text.push_str(&format!("{:.3},0.00,0.00,0.00,0.00\n", time + 0.2));
1462 let log = read(&text).unwrap();
1463 let vel = &log.channels[1].values;
1464 assert!(vel[vel.len() - 2..].iter().all(|v| v.is_nan()));
1465 assert!(vel[vel.len() - 3].is_finite());
1466 assert!(
1467 log.notes
1468 .iter()
1469 .any(|n| n.starts_with("the last 2 rows, from line "))
1470 );
1471 assert_eq!(log.altitude_m.last(), Some(&0.0));
1473 assert_eq!(log.channels[0].values.last(), Some(&0.0));
1474 let text = "# MET Acc Vel iAlt pAlt\n0,0,0,0,0\n0.02,50,0.5,0,0\n0.04,-50,0,0.01,0\n";
1476 let rows = rows(numbered_lines(text).skip(1)).unwrap();
1477 let units = Units {
1478 length: Length::Meter,
1479 acceleration: Some(1.0),
1480 inertial: true,
1481 boost_ratio: Some(1.0),
1482 notes: Vec::new(),
1483 };
1484 let mut values = rows.values.clone();
1485 let mut notes = Vec::new();
1486 closing_zeros(&rows, &units, &mut values, &mut notes);
1487 assert_eq!(values[VEL][2], 0.0);
1488 assert!(notes.is_empty(), "{notes:?}");
1489 }
1490
1491 #[test]
1494 fn rows_are_checked_and_bad_cells_are_gaps() {
1495 let header = "# MET Acc Vel iAlt pAlt\n";
1496 for (body, line) in [
1497 ("0,0,0,0,0\n0.1,0,0,0\n", 3),
1498 ("0,0,0,0,0\n0,0,0,0,0\n", 3),
1499 ("0,0,0,0,0\n,0,0,0,0\n", 3),
1500 ("0,0,0,0,0,\n", 2),
1501 ] {
1502 match read(&format!("{header}{body}")) {
1503 Err(LogError::Syntax { line: at, .. }) => assert_eq!(at, line, "{body:?}"),
1504 other => panic!("{body:?}: {other:?}"),
1505 }
1506 }
1507 assert_eq!(read(header), Err(LogError::NoData { format: FORMAT }));
1508 let text = metric().replacen("\n1.000,", "\n1.000,x", 1);
1509 let log = read(&text).unwrap();
1510 assert!(log.channels[0].values[10].is_nan());
1511 assert!(
1512 log.notes
1513 .iter()
1514 .any(|n| n.starts_with("`Acc` has 1 cells that are empty or aren't a number"))
1515 );
1516 match read(&format!("{header}0,0,0,0,0{}\n", ",0".repeat(1_000))) {
1518 Err(LogError::Syntax {
1519 line: 2, message, ..
1520 }) => {
1521 assert!(
1522 message.starts_with("a row of more than 5 cells, "),
1523 "{message}"
1524 );
1525 }
1526 other => panic!("{other:?}"),
1527 }
1528 }
1529
1530 #[test]
1532 fn a_value_its_conversion_makes_infinite_is_refused() {
1533 let text = english();
1534 let at = text.find("\n17.000,").unwrap() + 1;
1535 let end = at + text[at..].find(',').unwrap();
1536 let next = end + 1 + text[end + 1..].find(',').unwrap();
1537 let text = format!("{}1e308{}", &text[..=end], &text[next..]);
1538 assert_eq!(
1539 read(&text).unwrap_err().to_string(),
1540 "ARTS2 CSV line 172: the column Acc holds a value too large for its unit's \
1541 conversion to SI"
1542 );
1543 let values = convert(&[1e308, f64::NAN, 2.0], 1.0, &[2, 3, 4], "Acc").unwrap();
1545 assert!(values[0] == 1e308 && values[1].is_nan() && values[2] == 2.0);
1546 assert_eq!(
1548 convert(&[2.0, -1e308, 1e308], 10.0, &[2, 3, 4], "Acc")
1549 .unwrap_err()
1550 .to_string(),
1551 "ARTS2 CSV line 3: the column Acc holds a value too large for its unit's conversion \
1552 to SI"
1553 );
1554 }
1555
1556 #[test]
1559 fn closing_zeros_need_an_acceleration_in_a_unit() {
1560 let text = "# MET Acc Vel iAlt pAlt\n0,0,0,0,0\n0.02,1,100,0,0\n0.04,1,0,2,0\n";
1561 let rows = rows(numbered_lines(text).skip(1)).unwrap();
1562 for (acceleration, kept) in [(Some(1.0), false), (None, true)] {
1563 let units = Units {
1564 length: Length::Meter,
1565 acceleration,
1566 inertial: true,
1567 boost_ratio: Some(1.0),
1568 notes: Vec::new(),
1569 };
1570 let mut values = rows.values.clone();
1571 let mut notes = Vec::new();
1572 closing_zeros(&rows, &units, &mut values, &mut notes);
1573 assert_eq!(values[VEL][2] == 0.0, kept, "{acceleration:?}");
1574 assert_eq!(notes.is_empty(), kept, "{notes:?}");
1575 }
1576 }
1577
1578 #[test]
1580 fn a_ground_off_zero_is_noted() {
1581 let text = metric().replacen(
1582 "\n0.000,0.00,0.00,0.00,0.00\n",
1583 "\n0.000,0.00,0.00,0.00,27.00\n",
1584 1,
1585 );
1586 let log = read(&text).unwrap();
1587 assert!(
1588 log.notes
1589 .iter()
1590 .any(|n| n.starts_with("`pAlt` reads 27.00 m on the first row"))
1591 );
1592 let log = read(&metric()).unwrap();
1593 assert!(!log.notes.iter().any(|n| n.contains("first row")));
1594 }
1595
1596 #[test]
1603 fn a_parachute_out_before_the_apogee_does_not_flip_the_unit() {
1604 let text = flight_deploying(2.0, 70.0, 1.0, 1.0, Some(25.0), 0.02);
1605 let rows = rows(numbered_lines(&text).skip(1)).unwrap();
1606 let [acc, vel, _, palt] = &rows.values;
1607 let apogee = apogee(&rows.time_s, vel).unwrap();
1608 let old: Vec<(f64, f64)> = (apogee.peak..=apogee.row)
1610 .map(|row| (rows.time_s[row], vel[row]))
1611 .filter(|(time, _)| *time >= apogee.time_s - APOGEE_WINDOW_S)
1612 .collect();
1613 let old_slope = fitted_slope(&old).unwrap();
1614 assert!(
1615 near(-old_slope, Length::Foot.gravity(), GRAVITY_MARGIN),
1616 "{old_slope}"
1617 );
1618 assert!(!near(-old_slope, Length::Meter.gravity(), GRAVITY_MARGIN));
1619 let Ok(coast) = coast_slope(&rows.time_s, vel, acc, &apogee) else {
1621 panic!("no coast");
1622 };
1623 let jump = coast.jump_s.unwrap();
1624 assert!(
1625 jump < apogee.time_s - 0.5 && jump > apogee.time_s - 1.0,
1626 "{jump}"
1627 );
1628 assert!(
1629 near(-coast.slope, Length::Meter.gravity(), 0.1),
1630 "{}",
1631 coast.slope
1632 );
1633 assert_eq!(smallest_step(palt).map(|(step, _)| step), Some(9.0));
1634 let log = read(&text).unwrap();
1635 let note = &log.notes[0];
1636 assert!(
1637 note.starts_with(
1638 "`Vel` read in meters per second, from the apogee and the barometer's step: "
1639 ) && note.contains(&format!("of coast before `Acc` jumps at {jump:.2} s")),
1640 "{note}"
1641 );
1642 let top = highest(&log.altitude_m);
1643 assert!(top > 700.0 && top < 1_000.0, "{top}");
1644 }
1645
1646 #[test]
1647 fn the_step_is_the_coarsest_of_the_sample_files() {
1648 assert!((ALTITUDE_STEP_M - 8.805_672).abs() < 1e-9);
1649 }
1650}