1use super::interval;
104use super::{
105 ACCEL_BIAS_M_S2, ACCEL_NOISE_SIGMAS, ACCEL_SCALE_SHARE, Accelerometer, Apogee, BURN_LEAST_S,
106 BURNOUT_MEAN_S, Burnout, COAST_SPAN_S, Clip, FLAT_TOP_M_S2, FLAT_TOP_S, FLAT_TOP_SAMPLES,
107 FLAT_TOP_SHARE, GRAVITY_TOLERANCE_G, Gravity, GravityBy, LIFTOFF_ACCELERATION_M_S2, Liftoff,
108 MIN_INTERVAL_S, MaxAcceleration, Method, NOISE_SPAN_S, PAD_MIN_SAMPLES, Provenance,
109 RAIL_TILT_DEG, Reading, Readings, Reason, SPEED_NOISE_M_S, SPEED_WINDOW_S, SPIKE_THRESHOLD,
110 SPIKE_WINDOW_S, STANDARD_GRAVITY_MPS2, Source, Withheld, clocked, local_interval, median,
111 smallest_step,
112};
113use crate::filter::hampel;
114use crate::log::{Channel, FlightLog, LogFormat, Quantity};
115
116pub const SYNTHETIC_COLUMN: &str = "Axial acceleration (synthetic)";
119
120pub const SYNTHETIC_LOWER_RANGE_COLUMN: &str = "Axial acceleration, ±8 g (synthetic)";
123
124#[derive(Debug, Clone, Copy, PartialEq)]
126pub(super) struct Axial {
127 pub gravity: Option<Gravity>,
129 pub range_g: Option<f64>,
131}
132
133pub(super) fn family(format: LogFormat, column: &str) -> Option<Axial> {
137 use Gravity::{In, Out};
138 use LogFormat as F;
139 let axial = |gravity, range_g| Some(Axial { gravity, range_g });
140 match (format, column) {
141 (F::AltosCsv, SYNTHETIC_COLUMN) => axial(Some(In), Some(180.0)),
144 (F::BlueRavenCsv, SYNTHETIC_COLUMN) => axial(Some(In), Some(32.0)),
145 (F::BlueRavenCsv, SYNTHETIC_LOWER_RANGE_COLUMN) => axial(Some(In), Some(8.0)),
147 (
150 F::AltosCsv | F::AltosEeprom | F::AltosTelemetry | F::AltosTelemetryCsv,
151 "acceleration",
152 ) => axial(Some(Out), None),
153 (F::RavenFipCsv | F::RavenFipa | F::BlueRavenCsv, "Axial Accel (Gs)") => axial(None, None),
157 (F::EggtimerCsv | F::EggtimerText | F::EggtimerRtf, "Accel" | "AccelG" | "AccelFPSS") => {
160 axial(Some(Out), None)
161 }
162 (F::EntacoreAimCsv | F::EntacoreXtra | F::EntacoreDump, "acceleration") => {
164 axial(Some(In), Some(100.0))
165 }
166 (F::FluctusCsv, "vert-accel (m/s2)") => axial(None, Some(200.0)),
169 (F::Marsa, "acceleration") => axial(Some(Out), None),
171 (F::AltimaxXls, "ACCEL [m/s2]") | (F::AltimaxAls, "ACCEL") => axial(Some(In), None),
173 (F::Arts2Csv, "Acc") | (F::Arts2Odf, "Acc(HI)") => axial(Some(Out), Some(50.0)),
175 _ if column.to_ascii_lowercase().contains("axial") => axial(None, None),
177 _ => None,
178 }
179}
180
181fn first_at_each_time(channel: &Channel) -> Channel {
186 let mut kept = channel.clone();
187 kept.time_s.clear();
188 kept.values.clear();
189 for (&t, &value) in channel.time_s.iter().zip(&channel.values) {
190 if t.is_finite() && kept.time_s.last() != Some(&t) {
191 kept.time_s.push(t);
192 kept.values.push(value);
193 }
194 }
195 kept
196}
197
198fn from_the_barometer(log: &FlightLog, channel: &Channel) -> bool {
207 log.format == LogFormat::AltosCsv
208 && channel.column == "acceleration"
209 && !log
210 .channels
211 .iter()
212 .any(|other| matches!(other.column.as_str(), "accel_x" | "latitude"))
213}
214
215pub(super) fn noise(values: &[f64]) -> f64 {
220 let mut distances: Vec<f64> = values
221 .windows(3)
222 .map(|w| (w[1] - 0.5 * (w[0] + w[2])).abs())
223 .filter(|d| d.is_finite())
224 .collect();
225 median(&mut distances).map_or(0.0, |m| m / (0.674_489_750_196_081_7 * 1.5_f64.sqrt()))
226}
227
228pub(super) fn read(
230 log: &FlightLog,
231 heights: &Readings,
232) -> (
233 Option<Accelerometer>,
234 Reading<MaxAcceleration>,
235 Reading<Burnout>,
236) {
237 let fallback = |detail: Option<String>| from_speed(heights, detail);
238 let withheld = |reason, detail: String| {
239 (
240 None,
241 Reading::withheld(reason, detail.clone()),
242 fallback(Some(detail)),
243 )
244 };
245 let accelerometers: Vec<_> = log
246 .channels_of(Quantity::Acceleration)
247 .filter(|channel| !from_the_barometer(log, channel))
248 .collect();
249 if accelerometers.is_empty() {
250 let detail = if log
251 .channels_of(Quantity::Acceleration)
252 .any(|channel| from_the_barometer(log, channel))
253 {
254 "the log has no accelerometer. The file holds neither an inertial unit's columns \
255 (`accel_x` and on) nor a GPS receiver's. Every AltOS board with an axial \
256 accelerometer adds one of the two. So the file's `acceleration` is taken for a board with \
257 none of its own, an EasyMini's or a TeleMini's. That column is the board's \
258 estimate from its barometer, and HPR Sim doesn't read a top from it"
259 } else {
260 "the log has no accelerometer; HPR Sim doesn't difference a height twice to make \
261 one, as its steps would read as spikes of many g"
262 };
263 return (
264 None,
265 Reading::withheld(Reason::NoAccelerometer, detail),
266 fallback(None),
267 );
268 }
269 let Some((channel, stated)) = accelerometers
270 .iter()
271 .find_map(|channel| family(log.format, &channel.column).map(|axial| (*channel, axial)))
272 else {
273 let columns: Vec<String> = accelerometers
274 .iter()
275 .map(|channel| format!("`{}`", channel.column))
276 .collect();
277 return withheld(
278 Reason::AxisUnstated,
279 format!(
280 "the log's accelerometers ({}) don't say which lies along the rocket's axis",
281 columns.join(", ")
282 ),
283 );
284 };
285 let (time, raw) = match clocked(&first_at_each_time(channel)) {
286 Ok(clocked) => clocked,
287 Err((reason, detail)) => return withheld(reason, detail),
288 };
289 let (time, raw): (Vec<f64>, Vec<f64>) = time
291 .iter()
292 .zip(&raw)
293 .filter(|(_, value)| value.is_finite())
294 .map(|(t, value)| (*t, *value))
295 .unzip();
296 let apogee_s = match &heights.apogee {
297 Reading::Read(apogee) => apogee.time_s,
298 Reading::Withheld(Withheld { reason, detail }) => {
299 return withheld(
300 *reason,
301 format!(
302 "the top acceleration is searched up to apogee, which is withheld: {detail}"
303 ),
304 );
305 }
306 };
307 let boost: Vec<usize> = (0..time.len()).filter(|&k| time[k] <= apogee_s).collect();
308 if boost.len() < 3 {
309 return withheld(
310 Reason::TooShort,
311 format!(
312 "the accelerometer has {} samples before apogee, too few to take a reading from",
313 boost.len()
314 ),
315 );
316 }
317 let mut steps: Vec<f64> = boost
319 .windows(2)
320 .map(|pair| time[pair[1]] - time[pair[0]])
321 .collect();
322 let interval = median(&mut steps).unwrap_or(0.0);
323 if interval < MIN_INTERVAL_S * (1.0 - 1e-3) {
324 return withheld(
325 Reason::SampledTooFast,
326 format!(
327 "the accelerometer's samples come every {interval:.3e} s, faster than the \
328 {MIN_INTERVAL_S} s its readings were checked at"
329 ),
330 );
331 }
332 let clean = hampel(&raw, half_window(SPIKE_WINDOW_S, interval), SPIKE_THRESHOLD);
335 let end = boost.last().copied().unwrap_or(0);
339 let earliest_s = heights
340 .liftoff
341 .value()
342 .map(|liftoff| liftoff.time_s - liftoff.bound_s);
343 let from = earliest_s.map_or(0, |earliest_s| {
344 time[..=end].partition_point(|t| *t < earliest_s).min(end)
345 });
346 let half_mean = half_window(BURNOUT_MEAN_S, interval);
347 let either_way = |moved: f64| moved.abs() > 0.5 * LIFTOFF_ACCELERATION_M_S2;
355 let moved = first_move(&raw, &clean, either_way);
356 let flown = match &heights.apogee {
359 Reading::Read(apogee) => {
360 let start_s = apogee.time_s - apogee.time_bound_s - COAST_SPAN_S;
361 let lifted_s = heights
362 .liftoff
363 .value()
364 .map_or(time[0], |liftoff| liftoff.time_s + liftoff.bound_s);
365 !apogee.is_floor
366 && start_s >= lifted_s
367 && moved.is_some_and(|moved| time[moved] <= start_s)
368 }
369 _ => false,
370 };
371 let coasted = match &heights.apogee {
376 Reading::Read(apogee) => {
377 let start_s = apogee.time_s - apogee.time_bound_s - COAST_SPAN_S;
378 !apogee.is_floor && moved.is_some_and(|moved| time[moved] <= start_s)
379 }
380 _ => false,
381 };
382 let (way, said_by) = match direction(
383 pad_level(&time, &raw, &clean, &heights.liftoff, either_way),
384 coast_level(&time, &raw, &boost, &heights.apogee).filter(|_| flown),
385 &thrust_witness(
386 &time,
387 &clean,
388 from,
389 end,
390 half_mean,
391 interval,
392 heights.liftoff.value().map_or(
393 (
394 time[0] + BURN_LEAST_S,
395 "the log's start by 0.5 s, liftoff withheld",
396 false,
397 ),
398 |liftoff| {
399 (
400 liftoff.time_s + liftoff.bound_s,
401 "liftoff's latest time",
402 true,
403 )
404 },
405 ),
406 ),
407 ) {
408 Ok(settled) => settled,
409 Err(detail) => {
410 return withheld(
411 Reason::DirectionUnstated,
412 format!("the accelerometer `{}`: {detail}", channel.column),
413 );
414 }
415 };
416 let sign = way.sign();
417 let turned: Vec<f64> = raw.iter().map(|v| sign * v).collect();
418 let turned_clean: Vec<f64> = clean.iter().map(|v| sign * v).collect();
419 let g = STANDARD_GRAVITY_MPS2;
420 let tolerance = GRAVITY_TOLERANCE_G * g;
421 let pad = pad_level(&time, &turned, &turned_clean, &heights.liftoff, |moved| {
426 moved > 0.5 * LIFTOFF_ACCELERATION_M_S2
427 });
428 let by_pad = pad.and_then(|pad| {
431 if (pad - g).abs() <= tolerance {
432 Some(Gravity::In)
433 } else if pad.abs() <= tolerance {
434 Some(Gravity::Out)
435 } else {
436 None
437 }
438 });
439 let coast = coast_level(&time, &turned, &boost, &heights.apogee).filter(|_| coasted);
443 let by_coast = coast.and_then(|coast| {
444 if coast.abs() <= tolerance {
445 Some(Gravity::In)
446 } else if (coast + g).abs() <= tolerance {
447 Some(Gravity::Out)
448 } else {
449 None
450 }
451 });
452 let witnesses = [
453 (stated.gravity, GravityBy::Family),
454 (by_pad, GravityBy::Pad),
455 (by_coast, GravityBy::Coast),
456 ];
457 let said: Vec<(Gravity, GravityBy)> = witnesses
458 .iter()
459 .filter_map(|(word, by)| word.map(|word| (word, *by)))
460 .collect();
461 let lone_coast_out = matches!(said.as_slice(), [(Gravity::Out, GravityBy::Coast)]);
470 let gravity = match said.first() {
471 Some(&first) if !lone_coast_out && said.iter().all(|(word, _)| *word == first.0) => first,
472 _ => {
473 let family = match stated.gravity {
474 Some(Gravity::In) => "says its readings hold gravity",
475 Some(Gravity::Out) => "says gravity is taken out of its readings",
476 None => "doesn't say whether its readings hold gravity",
477 };
478 let level = |name: &str, level: Option<f64>, held: &str, out: &str| {
479 level.map_or_else(
480 || format!("no {name} is read to tell by"),
481 |level| {
482 format!(
483 "its {name} reads {:.2} g ({held} holds gravity, {out} doesn't)",
484 level / g
485 )
486 },
487 )
488 };
489 let verdict = if lone_coast_out {
490 "only the coast says, and a coast at −1 g says gravity is out only beside \
491 another witness: a part that holds gravity reads its drag there, and a rocket \
492 still fast at apogee, arcing over, can drag about 1 g"
493 } else {
494 "they don't settle it, or disagree"
495 };
496 return withheld(
497 Reason::GravityUnstated,
498 format!(
499 "the accelerometer `{}`'s family {family}; {}; {}: within \
500 {GRAVITY_TOLERANCE_G} g, {verdict}",
501 channel.column,
502 level("pad", pad, "1 g", "0"),
503 level("coast to apogee", coast, "0", "−1 g"),
504 ),
505 );
506 }
507 };
508 let gravity_m_s2 = match gravity.0 {
509 Gravity::In => 0.0,
510 Gravity::Out => g,
511 };
512 let f: Vec<f64> = turned.iter().map(|v| v + gravity_m_s2).collect();
513 let f_clean: Vec<f64> = turned_clean.iter().map(|v| v + gravity_m_s2).collect();
514 let step = smallest_step(&raw);
515 let accelerometer = Accelerometer {
516 column: channel.column.clone(),
517 gravity: gravity.0,
518 gravity_by: gravity.1,
519 turned_over: sign < 0.0,
520 sample_interval_s: interval,
521 step_m_s2: step,
522 };
523 let mean = running_mean(&f_clean, half_mean);
528 let spans = spans(&f_clean, &mean, from, end, interval);
529 if spans.is_empty() {
533 let by: Vec<&str> = said_by.iter().map(|by| by.words()).collect();
534 return withheld(
535 Reason::DirectionUnstated,
536 format!(
537 "the accelerometer `{}`, read {} as its {} say{} and with gravity put back. It \
538 never reads past {:.0} g from liftoff's earliest time to apogee, as a rocket \
539 leaving the pad does. The earliest time is the log's start where liftoff is \
540 withheld. The accelerometer shows no thrust to read the top or burnout from",
541 channel.column,
542 way.words(),
543 match by.split_last() {
544 Some((last, rest)) if !rest.is_empty() => {
545 format!("{} and {last}", rest.join(", "))
546 }
547 _ => by.join(""),
548 },
549 if by.len() == 1 { "s" } else { "" },
550 LIFTOFF_ACCELERATION_M_S2 / g
551 ),
552 );
553 }
554 let mut burns: Vec<Span> = spans
555 .iter()
556 .copied()
557 .filter(|span| span.held_s >= BURN_LEAST_S)
558 .collect();
559 if burns.is_empty() {
561 burns.extend(spans.first());
562 }
563 let ended = burns.last().is_some_and(|burn| burn.falls);
567 let began = burns
572 .first()
573 .is_none_or(|burn| burn.rise > 0 && f_clean[burn.rise - 1] < LIFTOFF_ACCELERATION_M_S2);
574 let thrust: Vec<usize> = burns
575 .iter()
576 .flat_map(|burn| burn.rise..=burn.fall)
577 .collect();
578 let top_index = thrust
579 .iter()
580 .copied()
581 .max_by(|a, b| f[*a].total_cmp(&f[*b]).then(b.cmp(a)))
582 .unwrap_or(from);
583 let top = f[top_index];
584 let around: Vec<f64> = boost
585 .iter()
586 .copied()
587 .filter(|&k| (time[k] - time[top_index]).abs() <= NOISE_SPAN_S)
588 .map(|k| f[k])
589 .collect();
590 let jump = [top_index.wrapping_sub(1), top_index + 1]
591 .iter()
592 .filter_map(|&k| f.get(k))
593 .filter(|v| v.is_finite())
594 .map(|v| (top - v).abs())
595 .fold(0.0, f64::max);
596 let zeroed_m_s2 = match gravity.0 {
597 Gravity::In => 0.0,
598 Gravity::Out => g * (1.0 - RAIL_TILT_DEG.to_radians().cos()),
599 };
600 let noise_m_s2 = noise(&around);
601 let strayed_m_s2 = match (by_pad, pad) {
603 (Some(Gravity::In), Some(pad)) => (pad - g).abs(),
604 (Some(Gravity::Out), Some(pad)) => pad.abs(),
605 _ => 0.0,
606 };
607 let bound_m_s2 = ACCEL_SCALE_SHARE * top.abs()
608 + ACCEL_BIAS_M_S2
609 + strayed_m_s2
610 + zeroed_m_s2
611 + ACCEL_NOISE_SIGMAS * noise_m_s2
612 + step
613 + jump;
614 let range_m_s2 = stated.range_g.map(|range| range * g);
615 let clip = if range_m_s2.is_some_and(|range| top >= range - 2.0 * step - tolerance) {
619 Some(Clip::Range)
620 } else if flat_top(&f, &thrust, top, interval, noise_m_s2, step) {
621 Some(Clip::Flat)
622 } else {
623 None
624 };
625 let is_floor = clip.is_some() || !ended || !began;
626 let max_acceleration = Reading::Read(MaxAcceleration {
627 acceleration_m_s2: top,
628 bound_m_s2,
629 interval_m_s2: (!is_floor)
630 .then(|| interval::TOP_ACCELERATION_SHARES.interval(top, bound_m_s2))
631 .flatten(),
632 lower_end_m_s2: clip
635 .is_some()
636 .then(|| interval::TOP_ACCELERATION_FLOOR_SHARES.lower_end(top, bound_m_s2))
637 .flatten(),
638 time_s: time[top_index],
639 range_m_s2,
640 is_floor,
641 clip,
642 source: Source::Accelerometer,
643 provenance: if clip.is_some() {
644 Provenance::Clipped
645 } else {
646 Provenance::Measured
647 },
648 method: Method::HighestReading,
649 });
650 let read = match burns.as_slice() {
655 [_, .., last] => Err(format!(
656 "the accelerometer shows {} burns, the last rising past {:.0} g at {:.2} s: burnout \
657 is read from a flight that burns once",
658 burns.len(),
659 LIFTOFF_ACCELERATION_M_S2 / g,
660 time[last.rise]
661 )),
662 _ if !ended => Err(format!(
663 "the accelerometer's thrust, past {:.0} g from {:.2} s, never falls through zero \
664 before {}. The thrust doesn't end on the channel, so it shows no burnout",
665 LIFTOFF_ACCELERATION_M_S2 / g,
666 burns.first().map_or(time[from], |burn| time[burn.rise]),
667 if end + 1 == time.len() {
668 "the accelerometer's last sample"
669 } else {
670 "apogee"
671 }
672 )),
673 _ => burnout(&time, &f, &mean, end, top_index, step, interval).and_then(
674 |(time_s, bound_s)| match earliest_s {
675 Some(earliest_s) if time_s < earliest_s => Err(format!(
676 "the accelerometer's burnout, {time_s:.2} s, would come before liftoff's \
677 earliest time by the heights, {earliest_s:.2} s"
678 )),
679 _ => Ok((time_s, bound_s)),
680 },
681 ),
682 };
683 let burnout = match read {
684 Ok((time_s, bound_s)) => Reading::Read(Burnout {
685 time_s,
686 bound_s,
687 interval_s: interval::BURNOUT_SHARES.interval(time_s, bound_s),
688 lower_end_s: None,
689 time_after_liftoff_s: heights.liftoff.value().map(|l| time_s - l.time_s),
690 is_floor: false,
691 source: Source::Accelerometer,
692 provenance: Provenance::Measured,
693 method: Method::LeastAfterThrust,
694 }),
695 Err(detail) => fallback(Some(detail)),
696 };
697 (Some(accelerometer), max_acceleration, burnout)
698}
699
700fn flat_top(
710 f: &[f64],
711 boost: &[usize],
712 top: f64,
713 interval: f64,
714 noise_m_s2: f64,
715 step_m_s2: f64,
716) -> bool {
717 let near = (FLAT_TOP_SHARE * top.abs())
718 .max(FLAT_TOP_M_S2)
719 .min(0.5 * noise_m_s2)
720 .max(0.5 * step_m_s2);
721 #[expect(
722 clippy::cast_possible_truncation,
723 clippy::cast_sign_loss,
724 reason = "a positive count of samples, rounded"
725 )]
726 let least = if interval > 0.0 {
727 ((FLAT_TOP_S / interval).round() as usize).max(FLAT_TOP_SAMPLES)
728 } else {
729 FLAT_TOP_SAMPLES
730 };
731 let mut run = 0;
732 let mut longest = 0;
733 let mut last = None;
734 for &k in boost {
735 let next = last.is_some_and(|previous| k == previous + 1);
737 run = if f[k] >= top - near {
738 if next { run + 1 } else { 1 }
739 } else {
740 0
741 };
742 longest = longest.max(run);
743 last = Some(k);
744 }
745 longest >= least
746}
747
748const TIE_SHARE: f64 = 1e-9;
752
753fn half_window(span_s: f64, interval: f64) -> usize {
756 #[expect(
757 clippy::cast_possible_truncation,
758 clippy::cast_sign_loss,
759 reason = "a positive count of samples, rounded: at MIN_INTERVAL_S a span of a second holds \
760 250 either side"
761 )]
762 let half = (0.5 * span_s / interval.max(MIN_INTERVAL_S) * (1.0 + TIE_SHARE)).round() as usize;
763 half
764}
765
766fn running_mean(values: &[f64], half: usize) -> Vec<f64> {
768 let last = values.len().saturating_sub(1);
769 (0..values.len())
770 .map(|k| {
771 let window = &values[k.saturating_sub(half)..=k.saturating_add(half).min(last)];
772 #[expect(
773 clippy::cast_precision_loss,
774 reason = "a window of a few samples converts exactly"
775 )]
776 let count = window.len() as f64;
777 window.iter().sum::<f64>() / count
778 })
779 .collect()
780}
781
782#[derive(Debug, Clone, Copy, PartialEq)]
786struct Span {
787 rise: usize,
789 fall: usize,
791 falls: bool,
793 held_s: f64,
796}
797
798fn spans(values: &[f64], mean: &[f64], from: usize, end: usize, interval: f64) -> Vec<Span> {
802 let mut spans = Vec::new();
803 let mut next = from;
804 while let Some(rise) = (next..=end).find(|&k| values[k] >= LIFTOFF_ACCELERATION_M_S2) {
805 let fall = (rise + 1..=end).find(|&k| mean[k] <= 0.0);
806 let to = fall.unwrap_or(end);
807 #[expect(
808 clippy::cast_precision_loss,
809 reason = "a count of samples converts exactly"
810 )]
811 let held_s = (rise..=to)
812 .filter(|&k| values[k] >= LIFTOFF_ACCELERATION_M_S2)
813 .count() as f64
814 * interval;
815 spans.push(Span {
816 rise,
817 fall: to,
818 falls: fall.is_some(),
819 held_s,
820 });
821 match fall {
822 Some(fall) => next = fall + 1,
823 None => break,
824 }
825 }
826 spans
827}
828
829#[derive(Debug, Clone, Copy, PartialEq, Eq)]
832enum Way {
833 Up,
834 Down,
835}
836
837impl Way {
838 fn sign(self) -> f64 {
840 match self {
841 Self::Up => 1.0,
842 Self::Down => -1.0,
843 }
844 }
845
846 fn other(self) -> Self {
848 match self {
849 Self::Up => Self::Down,
850 Self::Down => Self::Up,
851 }
852 }
853
854 fn words(self) -> &'static str {
855 match self {
856 Self::Up => "nose up",
857 Self::Down => "nose down",
858 }
859 }
860}
861
862#[derive(Debug, Clone, Copy, PartialEq, Eq)]
864enum WayBy {
865 Pad,
866 Coast,
867 Thrust,
868}
869
870impl WayBy {
871 fn words(self) -> &'static str {
872 match self {
873 Self::Pad => "pad",
874 Self::Coast => "coast to apogee",
875 Self::Thrust => "thrust",
876 }
877 }
878}
879
880#[derive(Debug, Clone, PartialEq)]
885struct ThrustWitness {
886 way: Option<Way>,
887 words: String,
888 alone: bool,
889}
890
891fn first_move(values: &[f64], clean: &[f64], moved: impl Fn(f64) -> bool) -> Option<usize> {
895 let mut start: Vec<f64> = values.iter().take(PAD_MIN_SAMPLES).copied().collect();
896 let level = median(&mut start).unwrap_or(f64::NAN);
897 (0..clean.len()).find(|&k| moved(clean[k] - level))
898}
899
900fn pad_level(
905 time: &[f64],
906 values: &[f64],
907 clean: &[f64],
908 liftoff: &Reading<Liftoff>,
909 moved: impl Fn(f64) -> bool,
910) -> Option<f64> {
911 let Reading::Read(liftoff) = liftoff else {
912 return None;
913 };
914 let rise = first_move(values, clean, moved)?;
915 if rise >= PAD_MIN_SAMPLES && time[rise] <= liftoff.time_s + liftoff.bound_s {
916 median(&mut values[..rise].to_vec())
917 } else {
918 None
919 }
920}
921
922fn coast_level(
926 time: &[f64],
927 values: &[f64],
928 boost: &[usize],
929 apogee: &Reading<Apogee>,
930) -> Option<f64> {
931 let Reading::Read(apogee) = apogee else {
932 return None;
933 };
934 let end = apogee.time_s - apogee.time_bound_s;
935 let mut readings: Vec<f64> = boost
936 .iter()
937 .filter(|&&k| time[k] >= end - COAST_SPAN_S && time[k] <= end)
938 .map(|&k| values[k])
939 .collect();
940 if readings.len() >= PAD_MIN_SAMPLES {
941 median(&mut readings)
942 } else {
943 None
944 }
945}
946
947fn thrust_witness(
963 time: &[f64],
964 clean: &[f64],
965 from: usize,
966 end: usize,
967 half: usize,
968 interval: f64,
969 lifted: (f64, &str, bool),
970) -> ThrustWitness {
971 let walk = |way: Way| {
972 let values: Vec<f64> = clean.iter().map(|v| way.sign() * v).collect();
973 let mean = running_mean(&values, half);
974 spans(&values, &mean, from, end, interval)
975 };
976 let (up, down) = (walk(Way::Up), walk(Way::Down));
977 let held = |spans: &[Span]| {
978 spans
979 .iter()
980 .find(|span| span.held_s >= BURN_LEAST_S)
981 .map(|span| span.rise)
982 };
983 let first_held = match (held(&up), held(&down)) {
984 (Some(up), Some(down)) if down < up => Some((Way::Down, down)),
985 (Some(up), _) => Some((Way::Up, up)),
986 (None, Some(down)) => Some((Way::Down, down)),
987 (None, None) => None,
988 };
989 let past = format!("{:.0} g", LIFTOFF_ACCELERATION_M_S2 / STANDARD_GRAVITY_MPS2);
990 let (lifted_s, lifted_by, alone) = lifted;
991 let says = |way: Way, words: String| ThrustWitness {
992 way: Some(way),
993 words: format!("its thrust says {}: {words}", way.words()),
994 alone,
995 };
996 let neither = |words: String| ThrustWitness {
997 way: None,
998 words: format!("its thrust says neither: {words}"),
999 alone,
1000 };
1001 let lifts = |way: Way, rise: usize, words: String| {
1004 if time[rise] <= lifted_s {
1005 says(way, words)
1006 } else {
1007 neither(format!(
1008 "its span that would say {}, from {:.2} s, rises after {lifted_by}, \
1009 {lifted_s:.2} s. A drag after a thrust too weak to read past {past} or a \
1010 second burn does so. That span is not the thrust that lifts the rocket",
1011 way.words(),
1012 time[rise]
1013 ))
1014 }
1015 };
1016 if let Some((way, rise)) = first_held {
1017 let other = match way {
1018 Way::Up => &down,
1019 Way::Down => &up,
1020 };
1021 return match other.first().filter(|span| span.rise < rise) {
1022 Some(before) => neither(format!(
1023 "the first span past {past} to hold there for {BURN_LEAST_S} s, {} from {:.2} s, \
1024 comes after one {} from {:.2} s. A drag after a short burn or a knock's \
1025 rebound may do so",
1026 way.words(),
1027 time[rise],
1028 way.other().words(),
1029 time[before.rise]
1030 )),
1031 None => lifts(
1032 way,
1033 rise,
1034 format!(
1035 "the first span past {past} to hold there for {BURN_LEAST_S} s, from {:.2} s",
1036 time[rise]
1037 ),
1038 ),
1039 };
1040 }
1041 let count = |spans: usize| match spans {
1042 1 => "1 span".to_owned(),
1043 spans => format!("{spans} spans"),
1044 };
1045 match (up.len(), down.len()) {
1046 (0, 0) => neither(format!(
1047 "as written, it never reads past {past} either way up from liftoff's earliest time \
1048 (the log's start where liftoff is withheld) to apogee"
1049 )),
1050 (spans, 0) | (0, spans) => {
1051 let (way, first) = if down.is_empty() {
1052 (Way::Up, &up[0])
1053 } else {
1054 (Way::Down, &down[0])
1055 };
1056 lifts(
1057 way,
1058 first.rise,
1059 format!(
1060 "no span past {past} holds there for {BURN_LEAST_S} s, and its {} {}, as a \
1061 short burn's does",
1062 count(spans),
1063 if spans == 1 {
1064 "reads so"
1065 } else {
1066 "all read so"
1067 }
1068 ),
1069 )
1070 }
1071 (up, down) => neither(format!(
1072 "it reads past {past} both ways up, in {} nose up and {} nose down, and never for \
1073 {BURN_LEAST_S} s, as a thrust holds",
1074 count(up),
1075 count(down)
1076 )),
1077 }
1078}
1079
1080fn direction(
1098 pad: Option<f64>,
1099 coast: Option<f64>,
1100 thrust: &ThrustWitness,
1101) -> Result<(Way, Vec<WayBy>), String> {
1102 let g = STANDARD_GRAVITY_MPS2;
1103 let tolerance = GRAVITY_TOLERANCE_G * g;
1104 let by_pad = pad.and_then(|pad| {
1105 if (pad - g).abs() <= tolerance {
1106 Some(Way::Up)
1107 } else if (pad + g).abs() <= tolerance {
1108 Some(Way::Down)
1109 } else {
1110 None
1111 }
1112 });
1113 let by_coast = coast.and_then(|coast| {
1114 if coast <= -(g - tolerance) {
1115 Some(Way::Up)
1116 } else if coast >= g - tolerance {
1117 Some(Way::Down)
1118 } else {
1119 None
1120 }
1121 });
1122 let said: Vec<(Way, WayBy)> = [
1123 (by_pad, WayBy::Pad),
1124 (by_coast, WayBy::Coast),
1125 (thrust.way, WayBy::Thrust),
1126 ]
1127 .iter()
1128 .filter_map(|(way, by)| way.map(|way| (way, *by)))
1129 .collect();
1130 let settles =
1134 by_pad.is_some() || (thrust.way.is_some() && (thrust.alone || by_coast.is_some()));
1135 match said.first() {
1136 Some(&(way, _)) if settles && said.iter().all(|(each, _)| *each == way) => {
1137 Ok((way, said.iter().map(|(_, by)| *by).collect()))
1138 }
1139 _ => {
1140 let level = |name: &str, level: Option<f64>, said: Option<Way>, marks: &str| {
1141 level.map_or_else(
1142 || format!("no {name} is read to tell by"),
1143 |level| {
1144 format!(
1145 "its {name} reads {:.2} g as written, which says {} ({marks})",
1146 level / g,
1147 said.map_or("neither", Way::words)
1148 )
1149 },
1150 )
1151 };
1152 let near = 1.0 - GRAVITY_TOLERANCE_G;
1153 Err(format!(
1154 "{}; {}; {}: {}",
1155 level(
1156 "pad",
1157 pad,
1158 by_pad,
1159 "about 1 g says nose up, about −1 g nose down"
1160 ),
1161 level(
1162 "coast to apogee",
1163 coast,
1164 by_coast,
1165 &format!("−{near} g or less says nose up, {near} g or more nose down")
1166 ),
1167 thrust.words,
1168 if said.is_empty() {
1169 "none of them says which way up it reads"
1170 } else if !settles && thrust.way.is_none() {
1171 "the coast alone says. A coast's second can hold a weak thrust still \
1172 burning or a canopy opened early. So the coast doesn't settle which way up it \
1173 reads on its own"
1174 } else if !settles {
1175 "the thrust alone says, at the start of a log whose liftoff is withheld, which \
1176 may start after burnout with a drag there. So the thrust doesn't settle which way \
1177 up it reads without the coast beside it"
1178 } else {
1179 "they disagree on which way up it reads"
1180 }
1181 ))
1182 }
1183 }
1184}
1185
1186fn burnout(
1190 time: &[f64],
1191 f: &[f64],
1192 mean: &[f64],
1193 end: usize,
1194 top_index: usize,
1195 step: f64,
1196 interval: f64,
1197) -> Result<(f64, f64), String> {
1198 let h = half_window(BURNOUT_MEAN_S, interval);
1201 let Some(crossing) = (top_index + 1..=end).find(|&k| mean[k] <= 0.0) else {
1202 return Err(
1203 "the accelerometer never reads below zero between its top and apogee, so it shows \
1204 no burnout"
1205 .to_owned(),
1206 );
1207 };
1208 let noise_end = time
1209 .partition_point(|t| *t <= time[crossing] + 1.0)
1210 .min(end + 1);
1211 #[expect(
1212 clippy::cast_precision_loss,
1213 reason = "a window of a few samples converts exactly"
1214 )]
1215 let averaged = ((2 * h + 1) as f64).sqrt();
1216 let n =
1217 ACCEL_NOISE_SIGMAS * noise(&f[top_index..noise_end.max(top_index + 1)]) / averaged + step;
1218 let mut least = (f64::INFINITY, crossing);
1219 let mut stop = None;
1220 for (k, value) in mean.iter().enumerate().take(end + 1).skip(crossing) {
1221 if *value < least.0 {
1222 least = (*value, k);
1223 } else if *value > least.0 + 4.0 * n {
1224 stop = Some(k);
1225 break;
1226 }
1227 }
1228 let Some(stop) = stop else {
1229 return Err(format!(
1230 "the accelerometer's reading doesn't climb {:.2} m/s² back from its least, four times \
1231 its noise and step, before apogee. Burnout can't be told from the coast",
1232 4.0 * n
1233 ));
1234 };
1235 if least.0 > -3.0 * n {
1236 return Err(format!(
1237 "the accelerometer's least reading after the thrust, {:.2} m/s², lies within {:.2} \
1238 m/s², three times its noise and step, of zero. That is too little drag to tell \
1239 burnout by",
1240 least.0,
1241 3.0 * n
1242 ));
1243 }
1244 let near: Vec<usize> = (crossing..stop)
1245 .filter(|&k| mean[k] <= least.0 + 2.0 * n)
1246 .collect();
1247 let (Some(&first), Some(&last)) = (near.first(), near.last()) else {
1249 return Err(
1250 "the accelerometer's least reading after the thrust can't be placed".to_owned(),
1251 );
1252 };
1253 let interval = local_interval(time, first).max(local_interval(time, last));
1261 #[expect(
1262 clippy::cast_precision_loss,
1263 reason = "a window of a few samples converts exactly"
1264 )]
1265 let half_window_s = h as f64 * interval;
1266 let bound_s = (time[last] - time[first] + interval + 2.0 * half_window_s).max(2.0 * interval);
1267 Ok((time[first] - half_window_s, bound_s))
1268}
1269
1270fn from_speed(heights: &Readings, why: Option<String>) -> Reading<Burnout> {
1273 match &heights.max_speed {
1274 Reading::Read(speed) => {
1275 let bound_s = 2.0 * SPEED_NOISE_M_S / STANDARD_GRAVITY_MPS2
1276 + 0.5 * SPEED_WINDOW_S
1277 + heights.sample_interval_s.unwrap_or(0.0);
1278 Reading::Read(Burnout {
1279 time_s: speed.time_s,
1280 bound_s,
1281 interval_s: None,
1282 lower_end_s: interval::BURNOUT_FLOOR_SHARES.lower_end(speed.time_s, bound_s),
1283 time_after_liftoff_s: heights.liftoff.value().map(|l| speed.time_s - l.time_s),
1284 is_floor: true,
1285 source: speed.source,
1286 provenance: Provenance::Derived,
1287 method: Method::SpeedPeak,
1288 })
1289 }
1290 Reading::Withheld(Withheld { reason, detail }) => Reading::withheld(
1291 *reason,
1292 match why {
1293 Some(why) => format!(
1294 "{why}; and burnout from the speed's peak needs the top speed, which is \
1295 withheld: {detail}"
1296 ),
1297 None => format!(
1298 "burnout from the speed's peak needs the top speed, which is withheld: \
1299 {detail}"
1300 ),
1301 },
1302 ),
1303 }
1304}
1305
1306#[cfg(test)]
1307mod tests {
1308 use super::super::read as read_all;
1309 use super::*;
1310 use crate::log::{Channel, Stated};
1311
1312 const G: f64 = STANDARD_GRAVITY_MPS2;
1313
1314 fn jitter(k: usize, amplitude: f64) -> f64 {
1316 #[expect(
1317 clippy::cast_precision_loss,
1318 reason = "a sample's index converts exactly"
1319 )]
1320 let x = (k as f64 * 12.9898).sin() * 43_758.545_3;
1321 amplitude * (x - x.floor() - 0.5)
1322 }
1323
1324 fn height(t: f64) -> f64 {
1327 let c = t - 3.0;
1328 if c <= 0.0 {
1329 0.0
1330 } else if c < 1.0 {
1331 2.0 * G * c * c
1332 } else if c < 5.0 {
1333 let d = c - 1.0;
1334 2.0 * G + 4.0 * G * d - 0.5 * G * d * d
1335 } else {
1336 (10.0 * G - 10.0 * (c - 5.0)).max(0.0)
1337 }
1338 }
1339
1340 fn specific_force(t: f64) -> f64 {
1344 if t < 3.0 {
1345 G
1346 } else if t < 4.0 {
1347 5.0 * G + G * (std::f64::consts::PI * (t - 3.0)).sin()
1348 } else if t < 4.1 {
1349 5.0 * G - 5.6 * G * (t - 4.0) / 0.1
1350 } else if t < 8.0 {
1351 -0.6 * G * (8.0 - t) / 3.9
1352 } else {
1353 G
1354 }
1355 }
1356
1357 fn log(
1360 format: LogFormat,
1361 column: &str,
1362 dt: f64,
1363 value: impl Fn(usize, f64) -> f64,
1364 ) -> FlightLog {
1365 let clock = |dt: f64| -> Vec<f64> {
1366 (0..)
1367 .map(|i| f64::from(i) * dt)
1368 .take_while(|t| *t <= 30.0 + 1e-9)
1369 .collect()
1370 };
1371 let time_s = clock(0.05);
1372 let accel_s = clock(dt);
1373 let values = accel_s
1374 .iter()
1375 .enumerate()
1376 .map(|(k, t)| value(k, *t))
1377 .collect();
1378 let mut log = FlightLog {
1379 format,
1380 logger: "test".to_owned(),
1381 serial_number: None,
1382 firmware: None,
1383 flight_number: None,
1384 stated: Stated::default(),
1385 altitude_m: time_s.iter().map(|t| height(*t)).collect(),
1386 time_s,
1387 vertical_speed_m_s: None,
1388 temperature_k: None,
1389 battery_v: None,
1390 channels: vec![Channel::new(
1391 column,
1392 Quantity::Acceleration,
1393 accel_s,
1394 values,
1395 )],
1396 events: Vec::new(),
1397 notes: Vec::new(),
1398 };
1399 if format == LogFormat::AltosCsv {
1401 let time_s = log.time_s.clone();
1402 let latitude = vec![40.0; time_s.len()];
1403 log.channels.push(Channel::new(
1404 "latitude",
1405 Quantity::Latitude,
1406 time_s,
1407 latitude,
1408 ));
1409 }
1410 log
1411 }
1412
1413 #[test]
1416 fn an_axial_trace_reads_its_top_and_burnout() {
1417 let readings = read_all(&log(
1418 LogFormat::GenericTable,
1419 "Axial accel",
1420 0.01,
1421 |k, t| specific_force(t) + jitter(k, 0.3),
1422 ));
1423 let accelerometer = readings.accelerometer.unwrap();
1424 assert_eq!(accelerometer.gravity, Gravity::In);
1425 assert_eq!(accelerometer.gravity_by, GravityBy::Pad);
1426 assert!(!accelerometer.turned_over);
1427 let top = readings.max_acceleration.value().unwrap();
1428 assert!(
1429 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1430 "{top:?}"
1431 );
1432 assert!((top.time_s - 3.5).abs() < 0.1, "{top:?}");
1433 assert_eq!(top.provenance, Provenance::Measured);
1434 assert_eq!(top.method, Method::HighestReading);
1435 assert_eq!(
1437 top.interval_m_s2,
1438 interval::TOP_ACCELERATION_SHARES.interval(top.acceleration_m_s2, top.bound_m_s2)
1439 );
1440 assert!(top.interval_m_s2.is_some() && top.lower_end_m_s2.is_none());
1441 let stated = readings.burnout.value().unwrap();
1442 assert_eq!(
1443 stated.interval_s,
1444 interval::BURNOUT_SHARES.interval(stated.time_s, stated.bound_s)
1445 );
1446 assert!(stated.interval_s.is_some() && stated.lower_end_s.is_none());
1447 assert_eq!(top.range_m_s2, None);
1448 let burnout = readings.burnout.value().unwrap();
1449 assert!(!burnout.is_floor);
1450 assert_eq!(burnout.method, Method::LeastAfterThrust);
1451 assert!(
1452 (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1453 "{burnout:?}"
1454 );
1455 assert!((burnout.time_s - 4.1).abs() <= 0.01, "{burnout:?}");
1457 let sigma = 0.3 / 12.0_f64.sqrt();
1461 let n = ACCEL_NOISE_SIGMAS * sigma / 7.0_f64.sqrt();
1462 let span = 2.0 * n / (0.6 * G / 3.9);
1463 assert!(
1464 (burnout.bound_s - (span + 0.01 + 0.07)).abs() < 0.03,
1465 "{burnout:?}, span {span}"
1466 );
1467 }
1468
1469 #[test]
1471 fn a_turned_over_part_without_gravity_reads_alike() {
1472 let readings = read_all(&log(
1473 LogFormat::GenericTable,
1474 "Axial accel",
1475 0.01,
1476 |k, t| -(specific_force(t) - G) + jitter(k, 0.3),
1477 ));
1478 let accelerometer = readings.accelerometer.unwrap();
1479 assert!(accelerometer.turned_over);
1480 assert_eq!(accelerometer.gravity, Gravity::Out);
1481 let top = readings.max_acceleration.value().unwrap();
1482 assert!(
1483 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1484 "{top:?}"
1485 );
1486 let burnout = readings.burnout.value().unwrap();
1487 assert!(
1488 (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1489 "{burnout:?}"
1490 );
1491 }
1492
1493 #[test]
1496 fn a_top_held_at_the_range_is_clipped() {
1497 let scale = 40.0;
1499 let readings = read_all(&log(
1500 LogFormat::FluctusCsv,
1501 "vert-accel (m/s2)",
1502 0.01,
1503 |_, t| {
1504 if t < 3.0 {
1505 G
1506 } else {
1507 (scale * (specific_force(t) - G) + G).min(200.0 * G)
1508 }
1509 },
1510 ));
1511 let top = readings.max_acceleration.value().unwrap();
1512 assert_eq!(top.provenance, Provenance::Clipped, "{top:?}");
1513 assert_eq!(top.range_m_s2, Some(200.0 * G));
1514 assert!(top.acceleration_m_s2 - top.bound_m_s2 <= scale * 5.0 * G + G);
1515 assert_eq!(
1518 top.lower_end_m_s2,
1519 Some(top.acceleration_m_s2 - 0.259 * top.bound_m_s2)
1520 );
1521 assert!(top.interval_m_s2.is_none());
1522 let readings = read_all(&log(
1524 LogFormat::FluctusCsv,
1525 "vert-accel (m/s2)",
1526 0.01,
1527 |k, t| {
1528 if t < 3.0 {
1529 G + jitter(k, 0.3)
1530 } else {
1531 20.0 * (specific_force(t) - G) + G + jitter(k, 0.3)
1532 }
1533 },
1534 ));
1535 let top = readings.max_acceleration.value().unwrap();
1536 assert_eq!(top.provenance, Provenance::Measured, "{top:?}");
1537 let readings = read_all(&log(
1539 LogFormat::GenericTable,
1540 "Axial accel",
1541 0.01,
1542 |k, t| (specific_force(t) + jitter(k, 0.3)).min(5.5 * G),
1543 ));
1544 let top = readings.max_acceleration.value().unwrap();
1545 assert_eq!(top.provenance, Provenance::Clipped, "{top:?}");
1546 assert_eq!(top.range_m_s2, None);
1547 assert!((top.acceleration_m_s2 - 5.5 * G).abs() < 1e-9);
1548 }
1549
1550 #[test]
1553 fn a_quiet_plateau_is_not_clipped() {
1554 let plateau = |t: f64| {
1555 if (3.0..4.0).contains(&t) {
1556 5.0 * G
1557 } else {
1558 specific_force(t)
1559 }
1560 };
1561 let readings = read_all(&log(
1562 LogFormat::GenericTable,
1563 "Axial accel",
1564 0.002,
1565 |k, t| plateau(t) + jitter(k, 0.1),
1566 ));
1567 let top = readings.max_acceleration.value().unwrap();
1568 assert!((top.acceleration_m_s2 - 5.0 * G).abs() <= top.bound_m_s2);
1569 assert_eq!(top.provenance, Provenance::Measured, "{top:?}");
1570 }
1571
1572 #[test]
1575 fn gravity_unsettled_withholds_the_top_and_burnout_falls_back() {
1576 let readings = read_all(&log(LogFormat::Marsa, "acceleration", 0.01, |_, t| {
1577 specific_force(t)
1578 }));
1579 assert_eq!(
1580 readings.max_acceleration.reason(),
1581 Some(Reason::GravityUnstated)
1582 );
1583 assert!(readings.accelerometer.is_none());
1584 let readings = read_all(&log(
1585 LogFormat::GenericTable,
1586 "Axial accel",
1587 0.01,
1588 |_, t| specific_force(t) - 0.5 * G,
1589 ));
1590 assert_eq!(
1591 readings.max_acceleration.reason(),
1592 Some(Reason::GravityUnstated)
1593 );
1594 let burnout = readings.burnout.value().unwrap();
1596 assert!(burnout.is_floor);
1597 assert_eq!(burnout.method, Method::SpeedPeak);
1598 assert_eq!(
1600 burnout.lower_end_s,
1601 interval::BURNOUT_FLOOR_SHARES.lower_end(burnout.time_s, burnout.bound_s)
1602 );
1603 assert_eq!(
1604 burnout.lower_end_s,
1605 Some(burnout.time_s + 0.0335 * burnout.bound_s)
1606 );
1607 assert!(burnout.interval_s.is_none());
1608 }
1609
1610 #[test]
1615 fn the_coast_settles_gravity_where_there_is_no_pad() {
1616 let eased = |t: f64| {
1617 if (4.1..8.0).contains(&t) {
1618 -0.6 * G * ((8.0 - t) / 3.9).powi(2)
1619 } else {
1620 specific_force(t)
1621 }
1622 };
1623 let late = |gravity_out: bool| {
1624 let mut log = log(LogFormat::GenericTable, "Axial accel", 0.01, |k, t| {
1625 eased(t) - if gravity_out { G } else { 0.0 } + jitter(k, 0.3)
1626 });
1627 let channel = &mut log.channels[0];
1629 let first = channel.time_s.iter().position(|t| *t >= 3.2).unwrap();
1630 channel.time_s.drain(..first);
1631 channel.values.drain(..first);
1632 read_all(&log)
1633 };
1634 let readings = late(false);
1635 let accelerometer = readings.accelerometer.unwrap();
1636 assert_eq!(accelerometer.gravity, Gravity::In);
1637 assert_eq!(accelerometer.gravity_by, GravityBy::Coast);
1638 let top = readings.max_acceleration.value().unwrap();
1639 assert!(
1640 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1641 "{top:?}"
1642 );
1643 let readings = late(true);
1644 assert!(readings.accelerometer.is_none());
1645 let Reading::Withheld(withheld) = &readings.max_acceleration else {
1646 panic!("{:?}", readings.max_acceleration);
1647 };
1648 assert_eq!(withheld.reason, Reason::GravityUnstated);
1649 assert!(
1650 withheld.detail.contains("only the coast says"),
1651 "{withheld:?}"
1652 );
1653 let mut log = log(LogFormat::Marsa, "acceleration", 0.01, |_, t| eased(t));
1655 let channel = &mut log.channels[0];
1656 let first = channel.time_s.iter().position(|t| *t >= 3.2).unwrap();
1657 channel.time_s.drain(..first);
1658 channel.values.drain(..first);
1659 let readings = read_all(&log);
1660 assert_eq!(
1661 readings.max_acceleration.reason(),
1662 Some(Reason::GravityUnstated)
1663 );
1664 }
1665
1666 #[test]
1671 fn a_fast_arc_over_doesnt_settle_gravity_out_alone() {
1672 let arcing = |t: f64| {
1673 if (4.1..8.0).contains(&t) {
1674 -G
1675 } else {
1676 specific_force(t)
1677 }
1678 };
1679 let late = |format, column| {
1681 let mut log = log(format, column, 0.01, |k, t| arcing(t) + jitter(k, 0.3));
1682 let channel = &mut log.channels[0];
1683 let first = channel.time_s.iter().position(|t| *t >= 3.2).unwrap();
1684 channel.time_s.drain(..first);
1685 channel.values.drain(..first);
1686 read_all(&log)
1687 };
1688 let readings = late(LogFormat::GenericTable, "Axial accel");
1689 assert!(
1690 readings.accelerometer.is_none(),
1691 "{:?}",
1692 readings.accelerometer
1693 );
1694 let Reading::Withheld(withheld) = &readings.max_acceleration else {
1695 panic!("{:?}", readings.max_acceleration);
1696 };
1697 assert_eq!(withheld.reason, Reason::GravityUnstated);
1698 assert!(
1700 withheld.detail.contains("only the coast says"),
1701 "{withheld:?}"
1702 );
1703 assert_eq!(
1706 late(LogFormat::EntacoreAimCsv, "acceleration")
1707 .max_acceleration
1708 .reason(),
1709 Some(Reason::GravityUnstated)
1710 );
1711 }
1712
1713 #[test]
1719 fn gravitys_coast_is_read_only_where_one_was_flown() {
1720 let log = log(LogFormat::Marsa, "acceleration", 0.01, |k, t| {
1721 specific_force(t) - G + jitter(k, 0.3)
1722 });
1723 let mut heights = super::super::heights(&log);
1724 let Reading::Read(apogee) = &mut heights.apogee else {
1725 panic!("{:?}", heights.apogee);
1726 };
1727 apogee.time_bound_s = apogee.time_s - 3.1;
1728 let (accelerometer, top, _) = read(&log, &heights);
1729 let accelerometer = accelerometer.unwrap_or_else(|| panic!("{top:?}"));
1730 assert_eq!(accelerometer.gravity, Gravity::Out);
1731 assert_eq!(accelerometer.gravity_by, GravityBy::Family);
1732 let top = top.value().unwrap();
1733 assert!(
1734 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1735 "{top:?}"
1736 );
1737 }
1738
1739 #[test]
1742 fn a_repeated_time_keeps_the_first_sample() {
1743 let mut log = log(LogFormat::GenericTable, "Axial accel", 0.01, |k, t| {
1744 specific_force(t) + jitter(k, 0.3)
1745 });
1746 let channel = &mut log.channels[0];
1747 let k = channel.time_s.iter().position(|t| *t >= 3.5).unwrap();
1748 channel.time_s.insert(k + 1, channel.time_s[k]);
1749 channel.values.insert(k + 1, 100.0 * G);
1750 let readings = read_all(&log);
1751 let top = readings.max_acceleration.value().unwrap();
1752 assert!(
1753 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1754 "{top:?}"
1755 );
1756 let channel = &mut log.channels[0];
1757 channel.time_s[k + 1] = channel.time_s[k] - 0.005;
1758 assert_eq!(
1759 read_all(&log).max_acceleration.reason(),
1760 Some(Reason::ClockOutOfOrder)
1761 );
1762 }
1763
1764 #[test]
1767 fn no_fall_below_zero_is_a_floor_from_the_speed() {
1768 let readings = read_all(&log(
1769 LogFormat::GenericTable,
1770 "Axial accel",
1771 0.01,
1772 |_, t| {
1773 if (4.0..8.0).contains(&t) {
1774 0.0
1775 } else {
1776 specific_force(t)
1777 }
1778 },
1779 ));
1780 assert!(readings.max_acceleration.value().is_some());
1781 let burnout = readings.burnout.value().unwrap();
1782 assert!(burnout.is_floor);
1783 assert_eq!(burnout.provenance, Provenance::Derived);
1784 assert!(burnout.time_s - 4.0 <= burnout.bound_s, "{burnout:?}");
1785 }
1786
1787 #[test]
1790 fn a_spike_neither_tops_nor_turns_the_trace() {
1791 let base = |k: usize, t: f64| specific_force(t) + jitter(k, 0.3);
1792 let readings = read_all(&log(
1794 LogFormat::GenericTable,
1795 "Axial accel",
1796 0.01,
1797 |k, t| {
1798 if (7.5..7.53).contains(&t) {
1799 12.0 * G
1800 } else {
1801 base(k, t)
1802 }
1803 },
1804 ));
1805 let top = readings.max_acceleration.value().unwrap();
1806 assert!(
1807 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1808 "{top:?}"
1809 );
1810 assert!(top.time_s < 4.1, "{top:?}");
1811 assert!(!readings.accelerometer.as_ref().unwrap().turned_over);
1812 let readings = read_all(&log(
1815 LogFormat::GenericTable,
1816 "Axial accel",
1817 0.01,
1818 |k, t| {
1819 if (7.0..7.2).contains(&t) {
1820 -20.0 * G
1821 } else {
1822 base(k, t)
1823 }
1824 },
1825 ));
1826 assert!(!readings.accelerometer.as_ref().unwrap().turned_over);
1827 let top = readings.max_acceleration.value().unwrap();
1828 assert!(
1829 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1830 "{top:?}"
1831 );
1832 let readings = read_all(&log(
1834 LogFormat::GenericTable,
1835 "Axial accel",
1836 0.01,
1837 |k, t| {
1838 if (t - 3.3).abs() < 1e-9 {
1839 -60.0 * G
1840 } else {
1841 base(k, t)
1842 }
1843 },
1844 ));
1845 assert!(!readings.accelerometer.as_ref().unwrap().turned_over);
1846 let top = readings.max_acceleration.value().unwrap();
1847 assert!(
1848 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1849 "{top:?}"
1850 );
1851 let burnout = readings.burnout.value().unwrap();
1852 assert!(!burnout.is_floor, "{burnout:?}");
1853 assert!(
1854 (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1855 "{burnout:?}"
1856 );
1857 }
1858
1859 #[test]
1861 fn a_sample_that_is_no_number_is_left_out() {
1862 for bad in [f64::NAN, f64::NEG_INFINITY, f64::INFINITY] {
1863 let readings = read_all(&log(
1864 LogFormat::GenericTable,
1865 "Axial accel",
1866 0.01,
1867 |k, t| {
1868 if (t - 3.8).abs() < 1e-9 {
1869 bad
1870 } else {
1871 specific_force(t) + jitter(k, 0.3)
1872 }
1873 },
1874 ));
1875 let top = readings.max_acceleration.value().unwrap();
1876 assert!(
1877 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1878 "{bad}: {top:?}"
1879 );
1880 let burnout = readings.burnout.value().unwrap();
1881 assert!(!burnout.is_floor, "{bad}: {burnout:?}");
1882 assert!(
1883 (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1884 "{bad}: {burnout:?}"
1885 );
1886 }
1887 }
1888
1889 #[test]
1892 fn an_accelerometer_sampled_too_fast_is_withheld() {
1893 let readings = read_all(&log(
1894 LogFormat::GenericTable,
1895 "Axial accel",
1896 0.001,
1897 |_, t| specific_force(t),
1898 ));
1899 assert_eq!(
1900 readings.max_acceleration.reason(),
1901 Some(Reason::SampledTooFast)
1902 );
1903 assert!(readings.accelerometer.is_none());
1904 assert!(readings.burnout.value().unwrap().is_floor);
1905 let mut fast = log(LogFormat::GenericTable, "Axial accel", 0.01, |_, t| {
1908 specific_force(t)
1909 });
1910 let time_s: Vec<f64> = (0..160_000).map(|i| 3.0 + f64::from(i) * 1e-7).collect();
1911 let values = time_s.iter().map(|t| specific_force(*t)).collect();
1912 fast.channels = vec![Channel::new(
1913 "Axial accel",
1914 Quantity::Acceleration,
1915 time_s,
1916 values,
1917 )];
1918 assert_eq!(
1919 read_all(&fast).max_acceleration.reason(),
1920 Some(Reason::SampledTooFast)
1921 );
1922 }
1923
1924 #[test]
1929 fn a_second_burn_is_searched_for_the_top_and_leaves_burnout_to_the_speed() {
1930 let with = |from: f64, to: f64, peak_g: f64| {
1931 read_all(&log(
1932 LogFormat::GenericTable,
1933 "Axial accel",
1934 0.01,
1935 |k, t| {
1936 let value = if (from..to).contains(&t) {
1937 peak_g * G * ((t - from) / 0.05).min((to - t) / 0.05).min(1.0)
1938 } else {
1939 specific_force(t)
1940 };
1941 value + jitter(k, 0.3)
1942 },
1943 ))
1944 };
1945 let readings = with(5.0, 6.5, 8.0);
1947 let top = readings.max_acceleration.value().unwrap();
1948 assert!(
1949 (top.acceleration_m_s2 - 8.0 * G).abs() <= top.bound_m_s2,
1950 "{top:?}"
1951 );
1952 assert!((5.0..6.5).contains(&top.time_s), "{top:?}");
1953 let burnout = readings.burnout.value().unwrap();
1954 assert!(burnout.is_floor, "{burnout:?}");
1955 assert_eq!(burnout.method, Method::SpeedPeak);
1956 let readings = with(7.0, 7.4, 10.0);
1958 let top = readings.max_acceleration.value().unwrap();
1959 assert!(
1960 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
1961 "{top:?}"
1962 );
1963 let burnout = readings.burnout.value().unwrap();
1964 assert!(!burnout.is_floor, "{burnout:?}");
1965 assert!(
1966 (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1967 "{burnout:?}"
1968 );
1969 }
1970
1971 #[test]
1975 fn a_burn_holds_past_two_g_or_is_the_only_one() {
1976 let readings = read_all(&log(
1978 LogFormat::GenericTable,
1979 "Axial accel",
1980 0.01,
1981 |k, t| {
1982 let value = if (2.5..2.65).contains(&t) {
1983 4.0 * G
1984 } else if (2.65..2.8).contains(&t) {
1985 -2.0 * G
1986 } else {
1987 specific_force(t)
1988 };
1989 value + jitter(k, 0.3)
1990 },
1991 ));
1992 let burnout = readings.burnout.value().unwrap();
1993 assert!(!burnout.is_floor, "{burnout:?}");
1994 assert!(
1995 (burnout.time_s - 4.1).abs() <= burnout.bound_s,
1996 "{burnout:?}"
1997 );
1998 let readings = read_all(&log(
2000 LogFormat::GenericTable,
2001 "Axial accel",
2002 0.01,
2003 |k, t| {
2004 let value = if t < 3.0 {
2005 G
2006 } else if t < 3.3 {
2007 6.0 * G
2008 } else if t < 3.4 {
2009 6.0 * G - 6.6 * G * (t - 3.3) / 0.1
2010 } else if (7.0..7.4).contains(&t) {
2011 10.0 * G
2012 } else if t < 8.0 {
2013 -0.6 * G * (8.0 - t) / 4.6
2014 } else {
2015 G
2016 };
2017 value + jitter(k, 0.3)
2018 },
2019 ));
2020 let top = readings.max_acceleration.value().unwrap();
2021 assert!(
2022 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
2023 "{top:?}"
2024 );
2025 assert!(top.time_s < 3.4, "{top:?}");
2026 }
2027
2028 #[test]
2031 fn a_bump_on_the_pad_isnt_the_top() {
2032 let readings = read_all(&log(
2034 LogFormat::GenericTable,
2035 "Axial accel",
2036 0.01,
2037 |k, t| {
2038 let value = if (1.0..1.3).contains(&t) {
2039 G + 6.0 * G * (std::f64::consts::PI * (t - 1.0) / 0.3).sin()
2040 } else {
2041 specific_force(t)
2042 };
2043 value + jitter(k, 0.3)
2044 },
2045 ));
2046 let top = readings.max_acceleration.value().unwrap();
2047 assert!(
2048 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
2049 "{top:?}"
2050 );
2051 assert!(top.time_s >= 3.0, "{top:?}");
2052 let burnout = readings.burnout.value().unwrap();
2053 assert!(!burnout.is_floor, "{burnout:?}");
2054 assert!(
2055 (burnout.time_s - 4.1).abs() <= burnout.bound_s,
2056 "{burnout:?}"
2057 );
2058 }
2059
2060 #[test]
2063 fn a_window_on_a_tie_rounds_up() {
2064 assert_eq!(half_window(BURNOUT_MEAN_S, 0.05), 1);
2065 assert_eq!(half_window(BURNOUT_MEAN_S, 0.050_000_000_000_000_71), 1);
2066 assert_eq!(half_window(BURNOUT_MEAN_S, 0.01), 3);
2067 assert_eq!(half_window(BURNOUT_MEAN_S, 0.010_000_000_000_000_2), 3);
2068 assert_eq!(half_window(BURNOUT_MEAN_S, 0.002), 13);
2069 assert_eq!(half_window(BURNOUT_MEAN_S, 0.002_000_000_000_000_002), 13);
2070 }
2071
2072 #[test]
2075 fn a_top_reaching_the_range_in_one_sample_is_clipped() {
2076 let peak = |t: f64| {
2078 if t < 3.0 {
2079 G
2080 } else {
2081 39.8 * (specific_force(t) - G) + G
2082 }
2083 };
2084 let fluctus = read_all(&log(
2085 LogFormat::FluctusCsv,
2086 "vert-accel (m/s2)",
2087 0.01,
2088 |_, t| peak(t),
2089 ));
2090 let top = fluctus.max_acceleration.value().unwrap();
2091 assert_eq!(top.provenance, Provenance::Clipped, "{top:?}");
2092 let unstated = read_all(&log(
2093 LogFormat::GenericTable,
2094 "Axial accel",
2095 0.01,
2096 |_, t| peak(t),
2097 ));
2098 let top = unstated.max_acceleration.value().unwrap();
2099 assert_eq!(top.provenance, Provenance::Measured, "{top:?}");
2100 }
2101
2102 #[test]
2105 fn burnout_refuses_a_coast_it_cant_tell() {
2106 let dt = 0.01;
2107 let time: Vec<f64> = (0..=790).map(|i| f64::from(i) * dt).collect();
2108 let try_burnout = |drag_g: f64, back: bool| {
2109 let f: Vec<f64> = time
2110 .iter()
2111 .enumerate()
2112 .map(|(k, &t)| {
2113 let coast = if back && t >= 7.5 { G } else { -drag_g * G };
2114 (if t < 4.0 { specific_force(t) } else { coast }) + jitter(k, 0.3)
2115 })
2116 .collect();
2117 let mean = running_mean(&f, half_window(BURNOUT_MEAN_S, dt));
2118 let top = (0..f.len()).max_by(|a, b| f[*a].total_cmp(&f[*b])).unwrap();
2119 burnout(&time, &f, &mean, time.len() - 1, top, 0.0, dt)
2120 };
2121 let error = try_burnout(0.6, false).unwrap_err();
2123 assert!(error.contains("doesn't climb"), "{error}");
2124 let error = try_burnout(0.02, true).unwrap_err();
2126 assert!(error.contains("too little drag"), "{error}");
2127 assert!(try_burnout(0.6, true).is_ok());
2129 }
2130
2131 #[test]
2139 fn a_trace_that_shows_no_thrust_either_way_up_is_withheld() {
2140 let pulse = |t: f64, at: f64| {
2141 if (at..at + 0.2).contains(&t) {
2142 4.0 * G
2143 } else {
2144 0.0
2145 }
2146 };
2147 let weak = |t: f64| {
2148 if (1.0..1.3).contains(&t) {
2149 -3.0 * G
2150 } else if t < 3.0 {
2151 G
2152 } else if t < 4.5 {
2153 1.8 * G
2154 } else if t < 8.0 {
2155 -0.2 * G * (8.0 - t) / 3.5
2156 } else {
2157 G
2158 }
2159 };
2160 for (case, words, trace) in [
2161 (
2162 "flat",
2163 "none of them says",
2164 Box::new(|_: f64| G) as Box<dyn Fn(f64) -> f64>,
2165 ),
2166 (
2167 "both ways",
2168 "which says nose down",
2169 Box::new(move |t: f64| G + pulse(t, 3.4) - 1.5 * pulse(t, 5.0)),
2171 ),
2172 ("weak", "shows no thrust", Box::new(weak)),
2173 ] {
2174 let readings = read_all(&log(
2175 LogFormat::GenericTable,
2176 "Axial accel",
2177 0.01,
2178 |k, t| trace(t) + jitter(k, 0.3),
2179 ));
2180 let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2181 panic!("{case}: {:?}", readings.max_acceleration);
2182 };
2183 assert_eq!(*reason, Reason::DirectionUnstated, "{case}");
2184 assert!(detail.contains(words), "{case}: {detail}");
2185 let burnout = readings.burnout.value().unwrap();
2186 assert_eq!(burnout.method, Method::SpeedPeak, "{case}");
2187 assert!(burnout.is_floor, "{case}");
2188 }
2189 }
2190
2191 #[test]
2196 fn a_dip_on_the_pad_doesnt_turn_the_trace_over() {
2197 let dipped = |t: f64| {
2198 if (1.0..1.3).contains(&t) {
2199 G - 4.0 * G * (std::f64::consts::PI * (t - 1.0) / 0.3).sin()
2200 } else {
2201 specific_force(t)
2202 }
2203 };
2204 for (format, column, out_m_s2) in [
2205 (LogFormat::GenericTable, "Axial accel", 0.0),
2206 (LogFormat::AltosCsv, "acceleration", G),
2207 ] {
2208 let readings = read_all(&log(format, column, 0.01, |k, t| {
2209 dipped(t) - out_m_s2 + jitter(k, 0.3)
2210 }));
2211 let accelerometer = readings.accelerometer.as_ref().unwrap();
2212 assert!(!accelerometer.turned_over, "{column}: {accelerometer:?}");
2213 let top = readings.max_acceleration.value().unwrap();
2214 assert!(
2215 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
2216 "{column}: {top:?}"
2217 );
2218 assert!((top.time_s - 3.5).abs() < 0.1, "{column}: {top:?}");
2219 let burnout = readings.burnout.value().unwrap();
2220 assert_eq!(burnout.method, Method::LeastAfterThrust, "{column}");
2221 assert!(
2222 (burnout.time_s - 4.1).abs() <= burnout.bound_s,
2223 "{column}: {burnout:?}"
2224 );
2225 }
2226 }
2227
2228 #[test]
2233 fn a_knock_with_its_rebound_first_doesnt_turn_the_trace_over() {
2234 let readings = read_all(&log(
2235 LogFormat::GenericTable,
2236 "Axial accel",
2237 0.01,
2238 |k, t| {
2239 let value = if (2.5..2.65).contains(&t) {
2240 -2.5 * G
2241 } else if (2.65..2.8).contains(&t) {
2242 4.0 * G
2243 } else {
2244 specific_force(t)
2245 };
2246 value + jitter(k, 0.3)
2247 },
2248 ));
2249 assert!(!readings.accelerometer.as_ref().unwrap().turned_over);
2250 let liftoff = readings.liftoff.value().unwrap();
2251 let earliest = liftoff.time_s - liftoff.bound_s;
2252 let top = readings.max_acceleration.value().unwrap();
2253 assert!(
2254 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
2255 "{top:?}"
2256 );
2257 assert!(top.time_s >= earliest.max(3.0), "{top:?}, {liftoff:?}");
2258 let burnout = readings.burnout.value().unwrap();
2259 assert_eq!(burnout.method, Method::LeastAfterThrust, "{burnout:?}");
2260 assert!(
2261 (burnout.time_s - 4.1).abs() <= burnout.bound_s,
2262 "{burnout:?}"
2263 );
2264 assert!(burnout.time_s >= earliest, "{burnout:?}, {liftoff:?}");
2265 assert!(
2266 burnout
2267 .time_after_liftoff_s
2268 .is_some_and(|after| after > 0.0),
2269 "{burnout:?}"
2270 );
2271 }
2272
2273 fn short_burn(t: f64) -> f64 {
2276 if t < 3.0 {
2277 G
2278 } else if t < 3.3 {
2279 40.0 * G
2280 } else if t < 4.5 {
2281 -8.0 * G + 5.1 * G * (t - 3.3) / 1.2
2282 } else if t < 6.0 {
2283 -2.9 * G * (6.0 - t) / 1.5
2284 } else if t < 8.0 {
2285 0.0
2286 } else {
2287 G
2288 }
2289 }
2290
2291 #[test]
2297 fn a_short_burn_before_a_heavy_drag_reads_nose_up() {
2298 let without = read_all(&log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2299 short_burn(t) - G + jitter(k, 0.3)
2300 }));
2301 let Reading::Withheld(Withheld { reason, detail }) = &without.max_acceleration else {
2302 panic!("{:?}", without.max_acceleration);
2303 };
2304 assert_eq!(*reason, Reason::DirectionUnstated);
2305 assert!(detail.contains("the coast alone says"), "{detail}");
2306 let (format, column, out_m_s2) = (LogFormat::GenericTable, "Axial accel", 0.0);
2307 let readings = read_all(&log(format, column, 0.01, |k, t| {
2308 short_burn(t) - out_m_s2 + jitter(k, 0.3)
2309 }));
2310 let accelerometer = readings.accelerometer.as_ref();
2311 assert!(
2312 accelerometer.is_some_and(|a| !a.turned_over),
2313 "{column}: {accelerometer:?}, {:?}",
2314 readings.max_acceleration
2315 );
2316 let top = readings.max_acceleration.value().unwrap();
2317 assert!(
2318 (top.acceleration_m_s2 - 40.0 * G).abs() <= top.bound_m_s2,
2319 "{column}: {top:?}"
2320 );
2321 assert!((3.0..3.3).contains(&top.time_s), "{column}: {top:?}");
2322 assert_eq!(top.provenance, Provenance::Measured, "{column}");
2323 assert!(!top.is_floor, "{column}: {top:?}");
2324 let burnout = readings.burnout.value().unwrap();
2325 assert!(
2326 (burnout.time_s - 3.3).abs() <= burnout.bound_s,
2327 "{column}: {burnout:?}"
2328 );
2329 }
2330
2331 #[test]
2335 fn a_short_burn_read_nose_down_reads_alike() {
2336 let without = read_all(&log(
2337 LogFormat::GenericTable,
2338 "Axial accel",
2339 0.01,
2340 |k, t| -(short_burn(t) - G) + jitter(k, 0.3),
2341 ));
2342 assert_eq!(
2343 without.max_acceleration.reason(),
2344 Some(Reason::DirectionUnstated)
2345 );
2346 let out_m_s2 = 0.0;
2347 let readings = read_all(&log(
2348 LogFormat::GenericTable,
2349 "Axial accel",
2350 0.01,
2351 |k, t| -(short_burn(t) - out_m_s2) + jitter(k, 0.3),
2352 ));
2353 let accelerometer = readings.accelerometer.as_ref();
2354 assert!(
2355 accelerometer.is_some_and(|a| a.turned_over),
2356 "out {out_m_s2}: {accelerometer:?}, {:?}",
2357 readings.max_acceleration
2358 );
2359 let top = readings.max_acceleration.value().unwrap();
2360 assert!(
2361 (top.acceleration_m_s2 - 40.0 * G).abs() <= top.bound_m_s2,
2362 "out {out_m_s2}: {top:?}"
2363 );
2364 assert!(!top.is_floor, "out {out_m_s2}: {top:?}");
2365 }
2366
2367 #[test]
2371 fn a_pad_that_disagrees_with_the_thrust_is_withheld() {
2372 let readings = read_all(&log(
2373 LogFormat::GenericTable,
2374 "Axial accel",
2375 0.01,
2376 |k, t| if t < 3.0 { G } else { -specific_force(t) } + jitter(k, 0.3),
2377 ));
2378 let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2379 panic!("{:?}", readings.max_acceleration);
2380 };
2381 assert_eq!(*reason, Reason::DirectionUnstated);
2382 for words in [
2383 "its pad reads 1.00 g as written, which says nose up",
2384 "its coast to apogee reads",
2385 "its thrust says nose down",
2386 "they disagree",
2387 ] {
2388 assert!(detail.contains(words), "{words}: {detail}");
2389 }
2390 assert!(readings.accelerometer.is_none());
2391 let burnout = readings.burnout.value().unwrap();
2392 assert_eq!(burnout.method, Method::SpeedPeak);
2393 assert!(burnout.is_floor);
2394 }
2395
2396 #[test]
2403 fn a_weak_thrust_without_gravity_is_withheld_not_turned() {
2404 let weak = |drag_g: f64| {
2405 move |t: f64| {
2406 if t < 3.0 {
2407 G
2408 } else if t < 4.5 {
2409 2.5 * G
2410 } else if t < 8.0 {
2411 -drag_g * G * (8.0 - t) / 3.5
2412 } else {
2413 G
2414 }
2415 }
2416 };
2417 let light = weak(0.4);
2418 let readings = read_all(&log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2419 light(t) - G + jitter(k, 0.3)
2420 }));
2421 let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2422 panic!("{:?}", readings.max_acceleration);
2423 };
2424 assert_eq!(*reason, Reason::DirectionUnstated);
2425 assert!(detail.contains("which says nose up"), "{detail}");
2426 assert!(detail.contains("the coast alone says"), "{detail}");
2427 let burnout = readings.burnout.value().unwrap();
2428 assert_eq!(burnout.method, Method::SpeedPeak, "{burnout:?}");
2429 assert!(burnout.is_floor);
2430 let heavy = weak(1.5);
2431 let readings = read_all(&log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2432 heavy(t) - G + jitter(k, 0.3)
2433 }));
2434 let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2435 panic!("{:?}", readings.max_acceleration);
2436 };
2437 assert_eq!(*reason, Reason::DirectionUnstated);
2438 assert!(detail.contains("which says nose up"), "{detail}");
2439 assert!(
2440 detail.contains("rises after liftoff's latest time"),
2441 "{detail}"
2442 );
2443 assert!(detail.contains("the coast alone says"), "{detail}");
2444 }
2445
2446 #[test]
2453 fn a_drag_after_a_weak_thrust_isnt_the_thrust() {
2454 let weak = |t: f64| {
2455 if t < 3.0 {
2456 G
2457 } else if t < 4.5 {
2458 2.5 * G
2459 } else if t < 8.0 {
2460 -1.5 * G * (8.0 - t) / 3.5
2461 } else {
2462 G
2463 }
2464 };
2465 for end_s in [5.6, 6.5, 7.0, 7.5] {
2466 let mut log = log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2467 weak(t) - G + jitter(k, 0.3)
2468 });
2469 let cut = |time_s: &[f64]| time_s.partition_point(|t| *t <= end_s + 1e-9);
2470 let channel = &mut log.channels[0];
2471 let kept = cut(&channel.time_s);
2472 channel.time_s.truncate(kept);
2473 channel.values.truncate(kept);
2474 let kept = cut(&log.time_s);
2475 log.time_s.truncate(kept);
2476 log.altitude_m.truncate(kept);
2477 let readings = read_all(&log);
2478 assert_eq!(
2479 readings.max_acceleration.reason(),
2480 Some(Reason::DirectionUnstated),
2481 "to {end_s} s: {:?}",
2482 readings.max_acceleration
2483 );
2484 }
2485 }
2486
2487 #[test]
2492 fn altos_acceleration_without_an_accelerometer_board_isnt_read() {
2493 let sensor = log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2494 specific_force(t) - G + jitter(k, 0.3)
2495 });
2496 assert!(read_all(&sensor).max_acceleration.value().is_some());
2497 let mut barometer = sensor.clone();
2498 barometer
2499 .channels
2500 .retain(|channel| channel.column != "latitude");
2501 let readings = read_all(&barometer);
2502 let Reading::Withheld(withheld) = &readings.max_acceleration else {
2503 panic!("{:?}", readings.max_acceleration);
2504 };
2505 assert_eq!(withheld.reason, Reason::NoAccelerometer);
2506 assert!(
2507 withheld.detail.contains("estimate from its barometer"),
2508 "{withheld:?}"
2509 );
2510 assert!(readings.accelerometer.is_none());
2511 let burnout = readings.burnout.value().expect("from the top speed");
2512 assert_eq!(burnout.method, Method::SpeedPeak, "{burnout:?}");
2513 let mut inertial = barometer.clone();
2514 let (time_s, values) = (inertial.time_s.clone(), vec![9.8; inertial.time_s.len()]);
2515 inertial.channels.push(Channel::new(
2516 "accel_x",
2517 Quantity::Acceleration,
2518 time_s,
2519 values,
2520 ));
2521 assert!(read_all(&inertial).max_acceleration.value().is_some());
2522 let mut unfixed = sensor.clone();
2524 for channel in &mut unfixed.channels {
2525 if channel.column == "latitude" {
2526 channel.values.fill(f64::NAN);
2527 }
2528 }
2529 assert!(read_all(&unfixed).max_acceleration.value().is_some());
2530 }
2531
2532 #[test]
2538 fn a_log_that_starts_in_the_thrust_gives_its_top_as_a_floor() {
2539 for (format, column, out_m_s2, whole) in [
2540 (LogFormat::AltosCsv, "acceleration", G, true),
2541 (LogFormat::GenericTable, "Axial accel", 0.0, false),
2542 ] {
2543 let mut log = log(format, column, 0.01, |k, t| {
2544 specific_force(t) - out_m_s2 + jitter(k, 0.3)
2545 });
2546 let from = |time_s: &[f64]| time_s.partition_point(|t| *t < 3.6);
2547 let channel = &mut log.channels[0];
2548 let cut = from(&channel.time_s);
2549 channel.time_s.drain(..cut);
2550 channel.values.drain(..cut);
2551 if whole {
2552 let cut = from(&log.time_s);
2553 log.time_s.drain(..cut);
2554 log.altitude_m.drain(..cut);
2555 }
2556 let readings = read_all(&log);
2557 let top = readings.max_acceleration.value();
2558 let top = top.unwrap_or_else(|| panic!("{column}: {:?}", readings.max_acceleration));
2559 assert!(top.is_floor, "{column}: {top:?}");
2560 assert_eq!(top.clip, None, "{column}");
2561 assert!(
2562 top.acceleration_m_s2 - top.bound_m_s2 <= 6.0 * G,
2563 "{column}: {top:?}"
2564 );
2565 assert!(top.lower_end_m_s2.is_none(), "{column}");
2567 assert!(top.interval_m_s2.is_none(), "{column}");
2568 }
2569 }
2570
2571 #[test]
2578 fn a_thrust_at_a_log_start_settles_only_beside_the_coast() {
2579 let trimmed = |trace: &dyn Fn(f64) -> f64, dt: f64, from_s: f64, to_s: f64| {
2580 let mut log = log(LogFormat::AltosCsv, "acceleration", dt, |k, t| {
2581 trace(t) - G + jitter(k, 0.3)
2582 });
2583 let keep = |time_s: &[f64]| {
2584 (
2585 time_s.partition_point(|t| *t < from_s - 1e-9),
2586 time_s.partition_point(|t| *t <= to_s + 1e-9),
2587 )
2588 };
2589 let channel = &mut log.channels[0];
2590 let (a, b) = keep(&channel.time_s);
2591 channel.time_s = channel.time_s[a..b].to_vec();
2592 channel.values = channel.values[a..b].to_vec();
2593 let (a, b) = keep(&log.time_s);
2594 log.time_s = log.time_s[a..b].to_vec();
2595 log.altitude_m = log.altitude_m[a..b].to_vec();
2596 read_all(&log)
2597 };
2598 let started = trimmed(&specific_force, 0.01, 3.35, f64::INFINITY);
2599 assert!(started.liftoff.reason().is_some(), "{:?}", started.liftoff);
2600 let accelerometer = started.accelerometer.as_ref();
2601 assert!(
2602 accelerometer.is_some_and(|a| !a.turned_over),
2603 "{accelerometer:?}, {:?}",
2604 started.max_acceleration
2605 );
2606 let top = started.max_acceleration.value().unwrap();
2607 assert!(
2608 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
2609 "{top:?}"
2610 );
2611 let weak = |t: f64| {
2612 if t < 3.0 {
2613 G
2614 } else if t < 4.5 {
2615 2.5 * G
2616 } else if t < 8.0 {
2617 -1.5 * G * (8.0 - t) / 3.5
2618 } else {
2619 G
2620 }
2621 };
2622 let strong = |t: f64| {
2623 if t < 3.0 {
2624 G
2625 } else if t < 4.5 {
2626 6.0 * G
2627 } else if t < 8.0 {
2628 -3.0 * G * (8.0 - t) / 3.5
2629 } else {
2630 G
2631 }
2632 };
2633 for (case, readings) in [
2634 ("weak, 0.01 s", trimmed(&weak, 0.01, 4.6, f64::INFINITY)),
2635 ("weak, 0.02 s", trimmed(&weak, 0.02, 4.6, f64::INFINITY)),
2636 ("weak, 0.05 s", trimmed(&weak, 0.05, 4.6, f64::INFINITY)),
2637 ("weak, to 6.5 s", trimmed(&weak, 0.01, 4.6, 6.5)),
2638 ("strong, to 7 s", trimmed(&strong, 0.01, 4.6, 7.0)),
2639 ] {
2640 assert!(
2641 readings.max_acceleration.value().is_none()
2642 && readings
2643 .accelerometer
2644 .as_ref()
2645 .is_none_or(|a| !a.turned_over),
2646 "{case}: {:?}, {:?}",
2647 readings.accelerometer,
2648 readings.max_acceleration
2649 );
2650 }
2651 }
2652
2653 #[test]
2660 fn a_lone_coast_settles_nothing() {
2661 let canopy = |t: f64| {
2662 if t < 3.0 {
2663 0.5 * G
2664 } else if t < 3.3 {
2665 40.0 * G
2666 } else if t < 4.5 {
2667 -8.0 * G + 5.1 * G * (t - 3.3) / 1.2
2668 } else if t < 6.0 {
2669 -2.9 * G * (6.0 - t) / 1.5
2670 } else {
2671 G
2672 }
2673 };
2674 let burning = |t: f64| {
2675 if t < 3.0 {
2676 G
2677 } else if t < 7.5 {
2678 2.5 * G
2679 } else if t < 8.0 {
2680 -0.3 * G
2681 } else {
2682 G
2683 }
2684 };
2685 for (case, readings) in [
2686 (
2687 "a canopy opened early",
2688 read_all(&log(
2689 LogFormat::GenericTable,
2690 "Axial accel",
2691 0.01,
2692 |k, t| canopy(t) + jitter(k, 0.3),
2693 )),
2694 ),
2695 (
2696 "a thrust still burning",
2697 read_all(&log(LogFormat::AltosCsv, "acceleration", 0.01, |k, t| {
2698 burning(t) - G + jitter(k, 0.3)
2699 })),
2700 ),
2701 ] {
2702 let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2703 panic!("{case}: {:?}", readings.max_acceleration);
2704 };
2705 assert_eq!(*reason, Reason::DirectionUnstated, "{case}");
2706 assert!(detail.contains("the coast alone says"), "{case}: {detail}");
2707 }
2708 }
2709
2710 #[test]
2717 fn a_coast_before_the_trace_moves_says_nothing() {
2718 let readings = read_all(&log(
2719 LogFormat::EntacoreAimCsv,
2720 "acceleration",
2721 0.01,
2722 |k, t| if t < 7.6 { G } else { 6.0 * G } + jitter(k, 0.3),
2723 ));
2724 let Reading::Withheld(Withheld { reason, detail }) = &readings.max_acceleration else {
2725 panic!("{:?}", readings.max_acceleration);
2726 };
2727 assert_eq!(*reason, Reason::DirectionUnstated);
2728 assert!(detail.contains("no coast to apogee is read"), "{detail}");
2729 assert!(
2730 detail.contains("rises after liftoff's latest time"),
2731 "{detail}"
2732 );
2733 }
2734
2735 #[test]
2740 fn the_thrust_witness_says_its_way_or_nothing() {
2741 let dt = 0.01;
2742 let time: Vec<f64> = (0..=600).map(|i| f64::from(i) * dt).collect();
2743 let witness = |from_s: f64, trace: &dyn Fn(f64) -> f64| {
2744 let clean: Vec<f64> = time.iter().map(|t| trace(*t)).collect();
2745 let from = time.partition_point(|t| *t < from_s);
2746 thrust_witness(
2747 &time,
2748 &clean,
2749 from,
2750 time.len() - 1,
2751 half_window(BURNOUT_MEAN_S, dt),
2752 dt,
2753 (1.2, "liftoff's latest time", true),
2754 )
2755 };
2756 let pulse = |t: f64, at: f64, long: f64, g: f64| {
2758 if (at..at + long).contains(&t) {
2759 g * G
2760 } else {
2761 0.0
2762 }
2763 };
2764 let thrust = move |t: f64| G + pulse(t, 1.0, 1.0, 4.0) - pulse(t, 2.0, 2.0, 1.5);
2765 let short_then_drag = move |t: f64| pulse(t, 1.0, 0.3, 40.0) - pulse(t, 1.3, 1.0, 8.0);
2766 let short = move |t: f64| pulse(t, 1.0, 0.3, 6.0) - pulse(t, 1.3, 2.0, 0.5);
2767 let both = move |t: f64| pulse(t, 1.0, 0.2, 5.0) - pulse(t, 3.0, 0.2, 5.0);
2768 let knocked = move |t: f64| -pulse(t, 0.5, 0.15, 3.5) + thrust(t);
2769 type Case<'a> = (&'a str, f64, &'a dyn Fn(f64) -> f64, Option<Way>, &'a str);
2771 let cases: [Case; 9] = [
2772 ("held", 0.0, &thrust, Some(Way::Up), "to hold there"),
2773 (
2774 "held, down",
2775 0.0,
2776 &|t| -thrust(t),
2777 Some(Way::Down),
2778 "to hold",
2779 ),
2780 (
2781 "drag after a short burn",
2782 0.0,
2783 &short_then_drag,
2784 None,
2785 "comes after one nose up",
2786 ),
2787 (
2788 "mirrored",
2789 0.0,
2790 &|t| -short_then_drag(t),
2791 None,
2792 "comes after one nose down",
2793 ),
2794 ("short only", 0.0, &short, Some(Way::Up), "1 span reads so"),
2795 (
2796 "short, down",
2797 0.0,
2798 &|t| -short(t),
2799 Some(Way::Down),
2800 "1 span reads so",
2801 ),
2802 ("both ways", 0.0, &both, None, "both ways up"),
2803 ("flat", 0.0, &|_| G, None, "never reads past"),
2804 (
2805 "knock before the search",
2806 0.8,
2807 &knocked,
2808 Some(Way::Up),
2809 "from 1.00 s",
2810 ),
2811 ];
2812 for (case, from_s, trace, way, words) in cases {
2813 let said = witness(from_s, trace);
2814 assert_eq!(said.way, way, "{case}: {said:?}");
2815 assert!(said.words.contains(words), "{case}: {said:?}");
2816 }
2817 assert_eq!(witness(0.0, &knocked).way, None);
2819 let weak_then_drag = move |t: f64| pulse(t, 1.0, 1.5, 1.5) - pulse(t, 2.5, 1.5, 2.5);
2822 let said = witness(0.0, &weak_then_drag);
2823 assert_eq!(said.way, None, "{said:?}");
2824 assert!(
2825 said.words
2826 .contains("from 2.50 s, rises after liftoff's latest time, 1.20 s"),
2827 "{said:?}"
2828 );
2829 let started = |at_s: f64| {
2832 let clean: Vec<f64> = time.iter().map(|t| thrust(*t + 1.0 - at_s)).collect();
2833 thrust_witness(
2834 &time,
2835 &clean,
2836 0,
2837 time.len() - 1,
2838 half_window(BURNOUT_MEAN_S, dt),
2839 dt,
2840 (
2841 BURN_LEAST_S,
2842 "the log's start by 0.5 s, liftoff withheld",
2843 false,
2844 ),
2845 )
2846 };
2847 assert_eq!(started(0.2).way, Some(Way::Up), "{:?}", started(0.2));
2848 let late = started(1.0);
2849 assert_eq!(late.way, None, "{late:?}");
2850 assert!(
2851 late.words
2852 .contains("rises after the log's start by 0.5 s, liftoff withheld"),
2853 "{late:?}"
2854 );
2855 }
2856
2857 #[test]
2862 fn the_pad_and_the_coast_say_by_their_levels() {
2863 let silent = ThrustWitness {
2864 way: None,
2865 words: "its thrust says neither".to_owned(),
2866 alone: true,
2867 };
2868 let up = ThrustWitness {
2869 way: Some(Way::Up),
2870 words: "its thrust says nose up".to_owned(),
2871 alone: true,
2872 };
2873 let down = ThrustWitness {
2874 way: Some(Way::Down),
2875 words: "its thrust says nose down".to_owned(),
2876 alone: true,
2877 };
2878 let way = |pad: Option<f64>, coast: Option<f64>, thrust: &ThrustWitness| {
2879 direction(pad.map(|g| g * G), coast.map(|g| g * G), thrust).map(|(way, _)| way)
2880 };
2881 assert_eq!(way(Some(1.0), None, &silent), Ok(Way::Up));
2882 assert_eq!(way(Some(1.24), None, &silent), Ok(Way::Up));
2883 assert_eq!(way(Some(-1.0), None, &silent), Ok(Way::Down));
2884 assert!(way(Some(1.26), None, &silent).is_err());
2885 assert!(way(Some(0.0), None, &silent).is_err());
2886 for coast in [-1.0, -0.76, -3.0, 1.3, -0.74, 0.0] {
2887 assert!(way(None, Some(coast), &silent).is_err(), "{coast}");
2888 }
2889 assert!(
2890 direction(None, Some(-G), &silent)
2891 .unwrap_err()
2892 .ends_with("So the coast doesn't settle which way up it reads on its own"),
2893 );
2894 assert_eq!(way(None, Some(-1.0), &up), Ok(Way::Up));
2895 assert_eq!(way(None, Some(-0.76), &up), Ok(Way::Up));
2896 assert_eq!(way(None, Some(-3.0), &up), Ok(Way::Up));
2897 assert!(way(None, Some(-0.76), &down).is_err());
2898 assert_eq!(way(None, Some(-0.74), &down), Ok(Way::Down));
2899 assert_eq!(way(None, Some(1.3), &down), Ok(Way::Down));
2900 assert!(way(None, Some(0.76), &up).is_err());
2901 assert_eq!(way(None, Some(0.74), &up), Ok(Way::Up));
2902 assert_eq!(way(Some(1.0), Some(-1.0), &silent), Ok(Way::Up));
2903 let at_start = ThrustWitness {
2906 way: Some(Way::Up),
2907 words: "its thrust says nose up".to_owned(),
2908 alone: false,
2909 };
2910 assert!(
2911 direction(None, None, &at_start)
2912 .unwrap_err()
2913 .ends_with("without the coast beside it")
2914 );
2915 assert_eq!(way(None, Some(-1.0), &at_start), Ok(Way::Up));
2916 assert!(way(None, Some(1.0), &at_start).is_err());
2917 assert_eq!(way(Some(-1.0), Some(1.0), &silent), Ok(Way::Down));
2918 assert!(way(None, None, &silent).is_err());
2919 assert_eq!(way(None, None, &down), Ok(Way::Down));
2920 assert_eq!(
2921 direction(Some(G), Some(-G), &up),
2922 Ok((Way::Up, vec![WayBy::Pad, WayBy::Coast, WayBy::Thrust]))
2923 );
2924 assert!(way(Some(1.0), Some(1.0), &silent).is_err());
2925 assert!(way(Some(1.0), None, &down).is_err());
2926 assert!(way(None, Some(-1.0), &down).is_err());
2927 let none = direction(None, None, &silent).unwrap_err();
2929 assert!(none.starts_with("no pad is read to tell by"), "{none}");
2930 assert!(
2931 none.ends_with("none of them says which way up it reads"),
2932 "{none}"
2933 );
2934 let split = direction(Some(G), Some(G), &silent).unwrap_err();
2935 for words in [
2936 "its pad reads 1.00 g as written, which says nose up",
2937 "its coast to apogee reads 1.00 g as written, which says nose down",
2938 "they disagree on which way up it reads",
2939 ] {
2940 assert!(split.contains(words), "{words}: {split}");
2941 }
2942 }
2943
2944 #[test]
2951 fn an_accelerometer_that_ends_in_the_thrust_gives_its_top_as_a_floor() {
2952 let rising = |t: f64| {
2953 if t < 3.0 {
2954 G
2955 } else {
2956 3.0 * G + 3.0 * G * (t - 3.0)
2957 }
2958 };
2959 for (end_s, whole) in [(3.7, true), (3.7, false), (6.0, true)] {
2960 let mut log = log(LogFormat::GenericTable, "Axial accel", 0.01, |k, t| {
2961 rising(t) + jitter(k, 0.3)
2962 });
2963 let cut = |time_s: &[f64]| time_s.partition_point(|t| *t <= end_s + 1e-9);
2964 let channel = &mut log.channels[0];
2965 let kept = cut(&channel.time_s);
2966 channel.time_s.truncate(kept);
2967 channel.values.truncate(kept);
2968 if whole {
2969 let kept = cut(&log.time_s);
2970 log.time_s.truncate(kept);
2971 log.altitude_m.truncate(kept);
2972 }
2973 let readings = read_all(&log);
2974 let case = format!("to {end_s} s, whole {whole}");
2975 let top = readings.max_acceleration.value();
2976 let top = top.unwrap_or_else(|| panic!("{case}: {:?}", readings.max_acceleration));
2977 assert!(top.is_floor, "{case}: {top:?}");
2978 assert_eq!(top.provenance, Provenance::Measured, "{case}");
2979 assert!(
2981 top.acceleration_m_s2 - top.bound_m_s2 <= rising(end_s),
2982 "{case}: {top:?}"
2983 );
2984 assert!(
2985 readings
2986 .burnout
2987 .value()
2988 .is_none_or(|burnout| burnout.method != Method::LeastAfterThrust),
2989 "{case}: {:?}",
2990 readings.burnout
2991 );
2992 }
2993 }
2994
2995 #[test]
2998 fn a_peak_between_two_samples_is_within_the_jump() {
2999 let peaked = |t: f64| {
3000 if (3.0..4.0).contains(&t) {
3001 4.0 * G + 6.0 * G * (1.0 - (t - 3.525).abs() / 0.05).max(0.0)
3002 } else if (4.0..4.1).contains(&t) {
3003 4.0 * G - 4.6 * G * (t - 4.0) / 0.1
3004 } else {
3005 specific_force(t)
3006 }
3007 };
3008 let readings = read_all(&log(
3009 LogFormat::GenericTable,
3010 "Axial accel",
3011 0.05,
3012 |k, t| peaked(t) + jitter(k, 0.3),
3013 ));
3014 let top = readings.max_acceleration.value().unwrap();
3015 assert!(top.acceleration_m_s2 < 7.1 * G, "{top:?}");
3016 assert!(
3017 (top.acceleration_m_s2 - 10.0 * G).abs() <= top.bound_m_s2,
3018 "{top:?}"
3019 );
3020 }
3021
3022 #[test]
3025 fn a_repeat_after_a_sample_with_no_time_is_left_out() {
3026 let mut log = log(LogFormat::GenericTable, "Axial accel", 0.01, |k, t| {
3027 specific_force(t) + jitter(k, 0.3)
3028 });
3029 let channel = &mut log.channels[0];
3030 let k = channel.time_s.iter().position(|t| *t >= 3.5).unwrap();
3031 let repeated = channel.time_s[k];
3032 channel.time_s.splice(k + 1..k + 1, [f64::NAN, repeated]);
3033 channel.values.splice(k + 1..k + 1, [100.0 * G, 100.0 * G]);
3034 let kept = first_at_each_time(&log.channels[0]);
3035 assert_eq!(kept.time_s.len(), log.channels[0].time_s.len() - 2);
3036 assert!(kept.time_s.iter().all(|t| t.is_finite()));
3037 let readings = read_all(&log);
3038 let top = readings.max_acceleration.value().unwrap();
3039 assert!(
3040 (top.acceleration_m_s2 - 6.0 * G).abs() <= top.bound_m_s2,
3041 "{top:?}"
3042 );
3043 }
3044
3045 #[test]
3047 fn the_noise_is_the_scatter_about_the_curve() {
3048 let line: Vec<f64> = (0..100).map(|k| f64::from(k) * 0.5).collect();
3049 assert!(noise(&line).abs() < 1e-12);
3050 let scattered: Vec<f64> = (0..20_000).map(|k| jitter(k, 1.0)).collect();
3051 let sigma = 1.0 / 12.0_f64.sqrt();
3052 assert!(
3054 (noise(&scattered) / sigma - 1.0).abs() < 0.15,
3055 "{}",
3056 noise(&scattered)
3057 );
3058 }
3059}