1use std::collections::BTreeMap;
28
29use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
30use hpr_flightdata::log::FlightLog;
31use hpr_flightdata::readings::interval::{self, FloorShares, Interval, Shares, Z_90};
32use hpr_flightdata::readings::{self, GRAVITY_TOLERANCE_G, Reading, Reason};
33use serde::{Deserialize, Serialize};
34
35use super::designs::DESIGNS;
36use super::held::{Quantity, top_specific_force};
37use super::logger::{
38 ACCEL_BIAS_G, LOWER_RANGE_G, accelerometer_log_clipping_at, accelerometer_log_top_scaled,
39};
40use super::smoothed::{BAND_CONFIDENCE, MISS_SHARE, clopper_pearson_lower, clopper_pearson_upper};
41use super::{Flight, SyntheticError};
42
43pub const STATED: [Quantity; 12] = [
45 Quantity::Liftoff,
46 Quantity::ApogeeHeight,
47 Quantity::ApogeeTime,
48 Quantity::TopSpeed,
49 Quantity::Landing,
50 Quantity::FlightTime,
51 Quantity::DescentRate,
52 Quantity::TopAcceleration,
53 Quantity::Burnout,
54 Quantity::DrogueRate,
55 Quantity::MainOpening,
56 Quantity::MainRate,
57];
58
59pub const INSIDE_SHARE: f64 = 0.90;
61
62pub const LEAST_FLOORS: u64 = 149;
64
65pub const FLOORED: [Quantity; 2] = [Quantity::TopAcceleration, Quantity::Burnout];
67
68pub fn shares(quantity: Quantity) -> Option<Shares> {
70 match quantity {
71 Quantity::ApogeeHeight => Some(interval::APOGEE_HEIGHT_SHARES),
72 Quantity::ApogeeTime => Some(interval::APOGEE_TIME_SHARES),
73 Quantity::Liftoff => Some(interval::LIFTOFF_SHARES),
74 Quantity::TopSpeed => Some(interval::TOP_SPEED_SHARES),
75 Quantity::Landing => Some(interval::LANDING_SHARES),
76 Quantity::FlightTime => Some(interval::FLIGHT_TIME_SHARES),
77 Quantity::DescentRate => Some(interval::DESCENT_RATE_SHARES),
78 Quantity::TopAcceleration => Some(interval::TOP_ACCELERATION_SHARES),
79 Quantity::Burnout => Some(interval::BURNOUT_SHARES),
80 Quantity::DrogueRate => Some(interval::DROGUE_RATE_SHARES),
81 Quantity::MainOpening => Some(interval::MAIN_OPENING_SHARES),
82 Quantity::MainRate => Some(interval::MAIN_RATE_SHARES),
83 }
84}
85
86pub fn floor_shares(quantity: Quantity) -> Option<FloorShares> {
88 match quantity {
89 Quantity::TopAcceleration => Some(interval::TOP_ACCELERATION_FLOOR_SHARES),
90 Quantity::Burnout => Some(interval::BURNOUT_FLOOR_SHARES),
91 _ => None,
92 }
93}
94
95pub fn withheld_by_rule(quantity: Quantity, reason: Reason) -> bool {
102 matches!(
103 (quantity, reason),
104 (Quantity::TopSpeed | Quantity::Burnout, Reason::Transonic)
105 | (Quantity::TopAcceleration, Reason::NoAccelerometer)
106 )
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
111pub struct Compared {
112 pub reading: f64,
114 pub bound: f64,
116 pub interval: Interval,
118 pub truth: f64,
120}
121
122impl Compared {
123 pub fn share(&self) -> f64 {
126 (self.reading - self.truth) / self.bound
127 }
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
132pub struct ComparedFloor {
133 pub reading: f64,
135 pub bound: f64,
137 pub low: f64,
139 pub standard_error: f64,
141 pub truth: f64,
143}
144
145impl ComparedFloor {
146 pub fn share(&self) -> f64 {
148 (self.reading - self.truth) / self.bound
149 }
150
151 pub fn below(&self, low: f64) -> bool {
154 self.truth.is_nan() || low.is_nan() || self.truth < low
155 }
156}
157
158#[derive(Debug, Clone, Copy, PartialEq)]
160pub enum Said {
161 Stated(Compared),
163 Floor(ComparedFloor),
165 Unstated,
167 PastClip(ComparedFloor),
170 WholeAtClip,
173 WholePastClip,
175 Absent,
178 Withheld(Reason),
180}
181
182#[derive(Debug, Clone, PartialEq)]
185pub struct FlightSaid {
186 pub index: u64,
188 pub design: usize,
190 pub logger: &'static str,
192 pub air_offset_k: f64,
194 pub said: Vec<(Quantity, Said)>,
196}
197
198struct Part {
200 reading: f64,
201 bound: f64,
202 interval: Option<Interval>,
203 lower_end: Option<f64>,
204 truth: f64,
205}
206
207impl Part {
208 fn of(reading: f64, bound: f64, interval: Option<Interval>, truth: f64) -> Self {
210 Self {
211 reading,
212 bound,
213 interval,
214 lower_end: None,
215 truth,
216 }
217 }
218}
219
220pub fn said(seed: u64, index: u64, flight: &Flight) -> Result<FlightSaid, SyntheticError> {
226 let read = readings::read(&flight.log);
227 let truth = &flight.truth;
228 let pad_s = flight.draw.logger.pad_s;
229 let events = &truth.events;
230 let descent_rate = events.apogee_m / (events.landing_s - events.apogee_s);
234 let height = |t_log: f64| truth.at(t_log - pad_s).map_or(f64::NAN, |x| x.height_m);
235 let chord = |from_s: f64, to_s: f64| (height(from_s) - height(to_s)) / (to_s - from_s);
236 let deployments = events.deployments.len();
237 let two_canopies = deployments >= 2;
238 fn of<T>(reading: &Reading<T>, take: impl Fn(&T) -> Part) -> Result<Part, Said> {
239 match reading {
240 Reading::Read(value) => Ok(take(value)),
241 Reading::Withheld(withheld) => Err(Said::Withheld(withheld.reason)),
242 }
243 }
244 let mut said: Vec<(Quantity, Said)> = STATED
245 .iter()
246 .map(|&quantity| {
247 let part = match quantity {
248 Quantity::Liftoff => of(&read.liftoff, |l| {
249 Part::of(l.time_s, l.bound_s, l.interval_s, pad_s + events.liftoff_s)
250 }),
251 Quantity::ApogeeHeight => of(&read.apogee, |a| {
252 Part::of(
253 a.height_m,
254 a.bound_m,
255 a.height_interval_m,
256 truth.apogee_above_pad_m(),
257 )
258 }),
259 Quantity::ApogeeTime => of(&read.apogee, |a| {
260 Part::of(
261 a.time_s,
262 a.time_bound_s,
263 a.time_interval_s,
264 pad_s + events.apogee_s,
265 )
266 }),
267 Quantity::TopSpeed => of(&read.max_speed, |s| {
268 Part::of(
269 s.speed_m_s,
270 s.bound_m_s,
271 s.interval_m_s,
272 truth.top_speed().0,
273 )
274 }),
275 Quantity::Landing => of(&read.landing, |l| {
276 Part::of(l.time_s, l.bound_s, l.interval_s, pad_s + events.landing_s)
277 }),
278 Quantity::FlightTime => of(&read.flight_time, |f| {
279 Part::of(
280 f.time_s,
281 f.bound_s,
282 f.interval_s,
283 events.landing_s - events.liftoff_s,
284 )
285 }),
286 Quantity::DescentRate => of(&read.landing, |l| {
287 Part::of(
288 l.mean_descent_rate_m_s,
289 l.mean_descent_rate_bound_m_s,
290 l.mean_descent_rate_interval_m_s,
291 descent_rate,
292 )
293 }),
294 Quantity::TopAcceleration => of(&read.max_acceleration, |a| Part {
295 reading: a.acceleration_m_s2,
296 bound: a.bound_m_s2,
297 interval: a.interval_m_s2,
298 lower_end: a.lower_end_m_s2,
299 truth: top_specific_force(flight),
300 }),
301 Quantity::Burnout => of(&read.burnout, |b| Part {
302 reading: b.time_s,
303 bound: b.bound_s,
304 interval: b.interval_s,
305 lower_end: b.lower_end_s,
306 truth: pad_s + events.burnout_s,
307 }),
308 Quantity::DrogueRate => match &read.drogue_descent {
309 Reading::Withheld(withheld)
310 if withheld.reason == Reason::OneCanopy && !two_canopies =>
311 {
312 Err(Said::Absent)
313 }
314 drogue => of(drogue, |d| {
315 Part::of(
316 d.rate_m_s,
317 d.bound_m_s,
318 d.interval_m_s,
319 chord(d.from_s, d.to_s),
320 )
321 }),
322 },
323 Quantity::MainOpening => match &read.main_descent {
324 Reading::Withheld(withheld) => Err(Said::Withheld(withheld.reason)),
325 Reading::Read(main) => match main.opening {
326 Some(opening) => Ok(Part::of(
329 opening.time_s,
330 opening.bound_s,
331 opening.interval_s,
332 if two_canopies {
333 pad_s + events.deployments[deployments - 1].1
334 } else {
335 f64::NAN
336 },
337 )),
338 None if two_canopies => Err(Said::Withheld(Reason::OneCanopy)),
340 None => Err(Said::Absent),
341 },
342 },
343 Quantity::MainRate => of(&read.main_descent, |d| {
344 Part::of(
345 d.rate_m_s,
346 d.bound_m_s,
347 d.interval_m_s,
348 chord(d.from_s, d.to_s),
349 )
350 }),
351 };
352 let said = match part {
353 Err(said) => said,
354 Ok(Part {
355 reading,
356 bound,
357 interval: Some(interval),
358 truth,
359 ..
360 }) => Said::Stated(Compared {
361 reading,
362 bound,
363 interval,
364 truth,
365 }),
366 Ok(Part {
367 reading,
368 bound,
369 lower_end: Some(low),
370 truth,
371 ..
372 }) => Said::Floor(compared_floor(quantity, reading, bound, low, truth)),
373 Ok(_) => Said::Unstated,
374 };
375 (quantity, said)
376 })
377 .collect();
378 let top = top_specific_force(flight);
380 if let (Some(scale), true) = (
381 flight.draw.logger.profile.accelerometer_scale(),
382 top > STANDARD_GRAVITY_MPS2,
383 ) {
384 let range = LOWER_RANGE_G * STANDARD_GRAVITY_MPS2;
385 let near = range * top_over_clip(seed, index, scale);
386 let log = accelerometer_log_top_scaled(
387 &flight.draw.logger,
388 truth,
389 (top, near),
390 LOWER_RANGE_G,
391 seed,
392 index,
393 )?;
394 if let Some(log) = log {
395 said.push((
396 Quantity::TopAcceleration,
397 clipped_top(&log, near, Said::Floor, Said::WholeAtClip),
398 ));
399 }
400 let log =
401 accelerometer_log_clipping_at(&flight.draw.logger, truth, LOWER_RANGE_G, seed, index)?;
402 if let Some(log) = log {
403 said.push((
404 Quantity::TopAcceleration,
405 clipped_top(&log, top, Said::PastClip, Said::WholePastClip),
406 ));
407 }
408 }
409 Ok(FlightSaid {
410 index,
411 design: flight.draw.design,
412 logger: flight.draw.logger.profile.name(),
413 air_offset_k: flight.draw.temperature_offset_k,
414 said,
415 })
416}
417
418pub fn top_over_clip(seed: u64, index: u64, scale: f64) -> f64 {
427 let least = (1.0 - (GRAVITY_TOLERANCE_G + ACCEL_BIAS_G) / LOWER_RANGE_G) / (1.0 + scale);
428 let most = 1.0 / (1.0 - scale);
429 let start = (seed % 1_000_000) as f64 * 0.754_877_666_246_692_7;
430 let place = (start + index as f64 * 0.618_033_988_749_894_9).fract();
431 least + (most - least) * place
432}
433
434fn clipped_top(log: &FlightLog, truth: f64, floor: fn(ComparedFloor) -> Said, whole: Said) -> Said {
437 let top = match readings::read(log).max_acceleration {
438 Reading::Read(top) => top,
439 Reading::Withheld(withheld) => return Said::Withheld(withheld.reason),
440 };
441 let Some(low) = top.lower_end_m_s2 else {
442 return whole;
443 };
444 floor(compared_floor(
445 Quantity::TopAcceleration,
446 top.acceleration_m_s2,
447 top.bound_m_s2,
448 low,
449 truth,
450 ))
451}
452
453fn compared_floor(
456 quantity: Quantity,
457 reading: f64,
458 bound: f64,
459 low: f64,
460 truth: f64,
461) -> ComparedFloor {
462 ComparedFloor {
463 reading,
464 bound,
465 low,
466 standard_error: floor_shares(quantity).map_or(0.0, |shares| shares.standard_error(bound)),
467 truth,
468 }
469}
470
471#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
473#[serde(rename_all = "kebab-case")]
474pub enum FloorProbe {
475 Raised,
477 Lowered,
480}
481
482impl FloorProbe {
483 pub const ALL: [Self; 2] = [Self::Raised, Self::Lowered];
485
486 pub fn name(self) -> &'static str {
488 match self {
489 Self::Raised => "raised one standard error",
490 Self::Lowered => "lowered two standard errors",
491 }
492 }
493
494 pub fn apply(self, floor: &ComparedFloor) -> f64 {
496 match self {
497 Self::Raised => floor.low + floor.standard_error,
498 Self::Lowered => floor.low - 2.0 * floor.standard_error,
499 }
500 }
501}
502
503#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
506pub struct FloorTest {
507 pub given: u64,
509 pub below: u64,
511 pub band: Band,
513}
514
515impl FloorTest {
516 pub fn of(given: u64, below: u64) -> Self {
518 Self {
519 given,
520 below,
521 band: Band::of(below, given),
522 }
523 }
524
525 pub fn passes(&self) -> bool {
527 self.band.holds(MISS_SHARE)
528 }
529
530 pub fn no_more_than_its_share(&self) -> bool {
532 self.band.low <= MISS_SHARE
533 }
534}
535
536#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
538pub struct FloorCheck {
539 pub test: FloorTest,
541 pub probes: BTreeMap<FloorProbe, FloorTest>,
543 pub by_logger: BTreeMap<String, (u64, u64)>,
545 pub by_design: BTreeMap<String, (u64, u64)>,
547}
548
549impl FloorCheck {
550 pub fn holds(&self) -> bool {
552 self.test.passes() && self.probes.values().all(|t| !t.passes())
553 }
554
555 fn of<'a>(floors: impl Iterator<Item = (&'a str, usize, &'a ComparedFloor)>) -> Option<Self> {
557 let (mut given, mut misses) = (0, 0);
558 let mut probed: BTreeMap<FloorProbe, u64> =
559 FloorProbe::ALL.iter().map(|&p| (p, 0)).collect();
560 let mut by_logger: BTreeMap<String, (u64, u64)> = BTreeMap::new();
561 let mut by_design: BTreeMap<String, (u64, u64)> = BTreeMap::new();
562 for (logger, design, floor) in floors {
563 let missed = u64::from(floor.below(floor.low));
564 given += 1;
565 misses += missed;
566 let entry = by_logger.entry(logger.to_owned()).or_default();
567 entry.0 += 1;
568 entry.1 += missed;
569 let entry = by_design
570 .entry(DESIGNS[design].name.to_owned())
571 .or_default();
572 entry.0 += 1;
573 entry.1 += missed;
574 for (probe, count) in &mut probed {
575 *count += u64::from(floor.below(probe.apply(floor)));
576 }
577 }
578 (given > 0).then(|| Self {
579 test: FloorTest::of(given, misses),
580 probes: probed
581 .into_iter()
582 .map(|(p, x)| (p, FloorTest::of(given, x)))
583 .collect(),
584 by_logger,
585 by_design,
586 })
587 }
588}
589
590#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
592#[serde(rename_all = "kebab-case")]
593pub enum Probe {
594 Narrowed,
596 Widened,
598 ShiftedDown,
600}
601
602impl Probe {
603 pub const ALL: [Self; 3] = [Self::Narrowed, Self::Widened, Self::ShiftedDown];
605
606 pub fn name(self) -> &'static str {
608 match self {
609 Self::Narrowed => "narrowed to 0.8",
610 Self::Widened => "widened to 1.25",
611 Self::ShiftedDown => "shifted down one standard error",
612 }
613 }
614
615 pub fn apply(self, interval: Interval) -> Interval {
617 let middle = 0.5 * (interval.low + interval.high);
618 let half = 0.5 * (interval.high - interval.low);
619 let about = |factor: f64| Interval {
620 low: middle - factor * half,
621 high: middle + factor * half,
622 };
623 match self {
624 Self::Narrowed => about(0.8),
625 Self::Widened => about(1.25),
626 Self::ShiftedDown => {
627 let sd = half / Z_90;
628 Interval {
629 low: interval.low - sd,
630 high: interval.high - sd,
631 }
632 }
633 }
634 }
635}
636
637#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
639pub struct Counts {
640 pub given: u64,
642 pub below: u64,
644 pub inside: u64,
646 pub above: u64,
648}
649
650impl Counts {
651 pub(crate) fn add(&mut self, interval: Interval, truth: f64) {
653 self.given += 1;
654 let below = truth.is_nan() || truth < interval.low;
655 let above = truth.is_nan() || truth > interval.high;
656 self.below += u64::from(below);
657 self.above += u64::from(above);
658 self.inside += u64::from(!below && !above);
659 }
660}
661
662#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
664pub struct Band {
665 pub low: f64,
667 pub high: f64,
669}
670
671impl Band {
672 fn of(x: u64, n: u64) -> Self {
674 if n == 0 {
675 return Self {
676 low: f64::NAN,
677 high: f64::NAN,
678 };
679 }
680 Self {
681 low: clopper_pearson_lower(x, n, BAND_CONFIDENCE),
682 high: clopper_pearson_upper(x, n, BAND_CONFIDENCE),
683 }
684 }
685
686 pub fn holds(&self, share: f64) -> bool {
688 self.low <= share && share <= self.high
689 }
690}
691
692#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
694pub struct Test {
695 pub counts: Counts,
697 pub below: Band,
699 pub inside: Band,
701 pub above: Band,
703}
704
705impl Test {
706 pub fn of(counts: Counts) -> Self {
708 Self {
709 counts,
710 below: Band::of(counts.below, counts.given),
711 inside: Band::of(counts.inside, counts.given),
712 above: Band::of(counts.above, counts.given),
713 }
714 }
715
716 pub fn passes(&self) -> bool {
718 self.below.holds(MISS_SHARE)
719 && self.above.holds(MISS_SHARE)
720 && self.inside.holds(INSIDE_SHARE)
721 }
722}
723
724#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
726pub struct Check {
727 pub quantity: Quantity,
729 pub flights: u64,
731 pub unstated: u64,
733 pub floors: u64,
735 pub floor: Option<FloorCheck>,
737 pub past_clip: Option<FloorTest>,
740 pub absent: u64,
742 pub whole_at_clip: u64,
744 pub whole_past_clip: u64,
746 pub withheld: BTreeMap<Reason, u64>,
748 pub test: Test,
750 pub probes: BTreeMap<Probe, Test>,
752 pub by_design: BTreeMap<String, Counts>,
754 pub by_logger: BTreeMap<String, Counts>,
756 pub by_air: BTreeMap<AirBand, Counts>,
758 pub mean_error: f64,
761 pub largest_error: f64,
764}
765
766impl Check {
767 pub fn holds(&self) -> bool {
769 self.test.passes()
770 && self.probes.values().all(|t| !t.passes())
771 && self.floor.as_ref().is_none_or(FloorCheck::holds)
772 && self
773 .past_clip
774 .as_ref()
775 .is_none_or(FloorTest::no_more_than_its_share)
776 }
777}
778
779pub fn check(quantity: Quantity, flights: &[FlightSaid]) -> Check {
781 let mut counts = Counts::default();
782 let mut probes: BTreeMap<Probe, Counts> =
783 Probe::ALL.iter().map(|&p| (p, Counts::default())).collect();
784 let mut by_design: BTreeMap<String, Counts> = BTreeMap::new();
785 let mut by_logger: BTreeMap<String, Counts> = BTreeMap::new();
786 let mut by_air: BTreeMap<AirBand, Counts> = BTreeMap::new();
787 let mut withheld: BTreeMap<Reason, u64> = BTreeMap::new();
788 let mut unstated = 0;
789 let mut floors = 0;
790 let mut absent = 0;
791 let (mut whole_at_clip, mut whole_past_clip) = (0, 0);
792 let mut error_sum = 0.0;
793 let mut largest_error = 0.0_f64;
794 for flight in flights {
795 for (q, said) in &flight.said {
796 if *q != quantity {
797 continue;
798 }
799 match said {
800 Said::Stated(c) => {
801 counts.add(c.interval, c.truth);
802 for (probe, counted) in &mut probes {
803 counted.add(probe.apply(c.interval), c.truth);
804 }
805 by_design
806 .entry(DESIGNS[flight.design].name.to_owned())
807 .or_default()
808 .add(c.interval, c.truth);
809 by_logger
810 .entry(flight.logger.to_owned())
811 .or_default()
812 .add(c.interval, c.truth);
813 by_air
814 .entry(AirBand::of(flight.air_offset_k))
815 .or_default()
816 .add(c.interval, c.truth);
817 let error = c.reading - c.truth;
818 error_sum += error;
819 if error.is_nan() || error.abs() > largest_error {
821 largest_error = error.abs();
822 }
823 }
824 Said::Floor(_) => floors += 1,
825 Said::PastClip(_) => {}
826 Said::WholeAtClip => whole_at_clip += 1,
827 Said::WholePastClip => whole_past_clip += 1,
828 Said::Unstated => unstated += 1,
829 Said::Absent => absent += 1,
830 Said::Withheld(reason) => *withheld.entry(*reason).or_default() += 1,
831 }
832 }
833 }
834 Check {
835 quantity,
836 flights: flights.len() as u64,
837 unstated,
838 floors,
839 past_clip: {
840 let (mut given, mut below) = (0, 0);
841 for (q, said) in flights.iter().flat_map(|f| &f.said) {
842 if let (true, Said::PastClip(floor)) = (*q == quantity, said) {
843 given += 1;
844 below += u64::from(floor.below(floor.low));
845 }
846 }
847 (given > 0).then(|| FloorTest::of(given, below))
848 },
849 floor: FloorCheck::of(flights.iter().flat_map(|flight| {
850 flight.said.iter().filter_map(move |(q, said)| match said {
851 Said::Floor(floor) if *q == quantity => Some((flight.logger, flight.design, floor)),
852 _ => None,
853 })
854 })),
855 absent,
856 whole_at_clip,
857 whole_past_clip,
858 withheld,
859 test: Test::of(counts),
860 probes: probes.into_iter().map(|(p, c)| (p, Test::of(c))).collect(),
861 by_design,
862 by_logger,
863 by_air,
864 mean_error: if counts.given == 0 {
865 f64::NAN
866 } else {
867 error_sum / counts.given as f64
868 },
869 largest_error: if counts.given == 0 {
870 f64::NAN
871 } else {
872 largest_error
873 },
874 }
875}
876
877pub fn fitted(quantity: Quantity, flights: &[FlightSaid]) -> Option<Shares> {
880 let shares: Vec<f64> = flights
881 .iter()
882 .flat_map(|f| &f.said)
883 .filter_map(|(q, said)| match said {
884 Said::Stated(c) if *q == quantity => Some(c.share()),
885 _ => None,
886 })
887 .collect();
888 interval::fit(&shares)
889}
890
891pub fn fitted_floor(quantity: Quantity, flights: &[FlightSaid]) -> Option<FloorShares> {
894 let shares: Vec<f64> = flights
895 .iter()
896 .flat_map(|f| &f.said)
897 .filter_map(|(q, said)| match said {
898 Said::Floor(floor) if *q == quantity => Some(floor.share()),
899 _ => None,
900 })
901 .collect();
902 interval::fit_floor(&shares)
903}
904
905pub fn three_figures(x: f64) -> f64 {
907 if x == 0.0 || !x.is_finite() {
908 return x;
909 }
910 let scale = 10f64.powi(2 - x.abs().log10().floor() as i32);
911 (x * scale).round() / scale
912}
913
914#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
918#[serde(rename_all = "kebab-case")]
919pub enum AirBand {
920 Cold,
922 Middle,
924 Warm,
926}
927
928impl AirBand {
929 pub const ALL: [Self; 3] = [Self::Cold, Self::Middle, Self::Warm];
931
932 pub fn of(offset_k: f64) -> Self {
934 if offset_k < -10.0 {
935 Self::Cold
936 } else if offset_k > 10.0 {
937 Self::Warm
938 } else {
939 Self::Middle
940 }
941 }
942
943 pub fn name(self) -> &'static str {
945 match self {
946 Self::Cold => "colder than −10 K",
947 Self::Middle => "−10 to +10 K",
948 Self::Warm => "warmer than +10 K",
949 }
950 }
951}
952
953#[cfg(test)]
954mod tests {
955 use super::*;
956
957 fn compared(truth: f64) -> Said {
958 Said::Stated(Compared {
959 reading: 0.0,
960 bound: 1.0,
961 interval: Interval {
962 low: -Z_90,
963 high: Z_90,
964 },
965 truth,
966 })
967 }
968
969 fn normal_flights() -> Vec<FlightSaid> {
972 (0..1000)
973 .map(|k| {
974 let p = (k as f64 + 0.5) / 1000.0;
975 FlightSaid {
976 index: k,
977 design: (k % 10) as usize,
978 logger: "altos",
979 air_offset_k: 0.0,
980 said: vec![(Quantity::ApogeeHeight, compared(normal_quantile(p)))],
981 }
982 })
983 .collect()
984 }
985
986 fn normal_quantile(p: f64) -> f64 {
988 let cdf = |x: f64| 0.5 * erfc(-x / std::f64::consts::SQRT_2);
989 let (mut lo, mut hi) = (-10.0, 10.0);
990 for _ in 0..200 {
991 let mid = 0.5 * (lo + hi);
992 if cdf(mid) < p {
993 lo = mid;
994 } else {
995 hi = mid;
996 }
997 }
998 0.5 * (lo + hi)
999 }
1000
1001 fn erfc(x: f64) -> f64 {
1004 let z = x.abs();
1005 let t = 2.0 / (2.0 + z);
1006 let ans = t
1007 * (-z * z - 1.265_512_23
1008 + t * (1.000_023_68
1009 + t * (0.374_091_96
1010 + t * (0.096_784_18
1011 + t * (-0.186_288_06
1012 + t * (0.278_868_07
1013 + t * (-1.135_203_98
1014 + t * (1.488_515_87
1015 + t * (-0.822_152_23 + t * 0.170_872_77)))))))))
1016 .exp();
1017 if x >= 0.0 { ans } else { 2.0 - ans }
1018 }
1019
1020 #[test]
1021 fn a_correct_interval_passes_and_every_probe_fails() {
1022 let flights = normal_flights();
1023 let check = check(Quantity::ApogeeHeight, &flights);
1024 assert_eq!(check.test.counts.given, 1000);
1025 assert_eq!(check.test.counts.below, 50);
1026 assert_eq!(check.test.counts.above, 50);
1027 assert!(check.test.passes());
1028 for (probe, test) in &check.probes {
1029 assert!(!test.passes(), "{probe:?}: {:?}", test.counts);
1030 }
1031 assert!(check.holds());
1032 assert_eq!(check.by_design.len(), 10);
1033 assert!(check.mean_error.abs() < 1e-3, "{}", check.mean_error);
1034 let farthest = normal_quantile(0.0005)
1036 .abs()
1037 .max(normal_quantile(0.9995).abs());
1038 assert_eq!(check.largest_error, farthest);
1039 let narrowed = check.probes[&Probe::Narrowed].counts;
1042 assert!(
1043 (185..=195).contains(&(narrowed.below + narrowed.above)),
1044 "{narrowed:?}"
1045 );
1046 let widened = check.probes[&Probe::Widened].counts;
1047 assert!(
1048 (35..=45).contains(&(widened.below + widened.above)),
1049 "{widened:?}"
1050 );
1051 let shifted = check.probes[&Probe::ShiftedDown].counts;
1052 assert!((255..=265).contains(&shifted.above), "{shifted:?}");
1053 }
1054
1055 #[test]
1056 fn a_one_sided_miss_fails_on_its_own_tail() {
1057 let mut flights = normal_flights();
1059 for f in &mut flights {
1060 if let (_, Said::Stated(c)) = &mut f.said[0] {
1061 c.truth += 0.3;
1062 }
1063 }
1064 let check = check(Quantity::ApogeeHeight, &flights);
1065 assert!(!check.test.passes(), "{:?}", check.test.counts);
1066 assert!(!check.test.above.holds(MISS_SHARE));
1067 assert!(!check.test.below.holds(MISS_SHARE));
1068 }
1069
1070 #[test]
1071 fn a_truth_that_is_not_a_number_leaves_no_error_scale() {
1072 let mut flights = normal_flights();
1073 flights[3].said = vec![(Quantity::ApogeeHeight, compared(f64::NAN))];
1074 let check = check(Quantity::ApogeeHeight, &flights);
1075 assert!(check.mean_error.is_nan());
1076 assert!(check.largest_error.is_nan(), "{}", check.largest_error);
1077 }
1078
1079 #[test]
1080 fn a_truth_that_is_not_a_number_misses_both_ways() {
1081 let mut counts = Counts::default();
1082 counts.add(
1083 Interval {
1084 low: 0.0,
1085 high: 1.0,
1086 },
1087 f64::NAN,
1088 );
1089 assert_eq!(
1090 (counts.given, counts.below, counts.inside, counts.above),
1091 (1, 1, 0, 1)
1092 );
1093 counts.add(
1094 Interval {
1095 low: 0.0,
1096 high: 1.0,
1097 },
1098 1.0,
1099 );
1100 assert_eq!(counts.inside, 1);
1101 }
1102
1103 #[test]
1106 fn a_reading_withheld_by_rule_is_named() {
1107 for (quantity, reason) in [
1108 (Quantity::TopSpeed, Reason::Transonic),
1109 (Quantity::Burnout, Reason::Transonic),
1110 (Quantity::TopAcceleration, Reason::NoAccelerometer),
1111 ] {
1112 assert!(withheld_by_rule(quantity, reason), "{quantity:?}");
1113 }
1114 assert!(!withheld_by_rule(Quantity::TopSpeed, Reason::NoClimb));
1115 for quantity in STATED {
1116 assert!(
1117 !withheld_by_rule(quantity, Reason::EndsBeforeLanding),
1118 "{quantity:?}"
1119 );
1120 if !matches!(quantity, Quantity::TopSpeed | Quantity::Burnout) {
1121 assert!(
1122 !withheld_by_rule(quantity, Reason::Transonic),
1123 "{quantity:?}"
1124 );
1125 }
1126 if quantity != Quantity::TopAcceleration {
1127 assert!(
1128 !withheld_by_rule(quantity, Reason::NoAccelerometer),
1129 "{quantity:?}"
1130 );
1131 }
1132 }
1133 }
1134
1135 fn normal_floors() -> Vec<FlightSaid> {
1138 (0..1000)
1139 .map(|k| {
1140 let p = (k as f64 + 0.5) / 1000.0;
1141 FlightSaid {
1142 index: k,
1143 design: 0,
1144 logger: if k % 2 == 0 { "altos" } else { "rrc3" },
1145 air_offset_k: 0.0,
1146 said: vec![(
1147 Quantity::Burnout,
1148 Said::Floor(ComparedFloor {
1149 reading: 0.0,
1150 bound: 1.0,
1151 low: -Z_90,
1152 standard_error: 1.0,
1153 truth: normal_quantile(p),
1154 }),
1155 )],
1156 }
1157 })
1158 .collect()
1159 }
1160
1161 #[test]
1162 fn a_correct_floor_passes_on_its_lower_tail_and_its_probes_fail() {
1163 let check = check(Quantity::Burnout, &normal_floors());
1164 assert_eq!(check.floors, 1000);
1165 assert_eq!(check.test.counts.given, 0);
1167 let floor = check.floor.as_ref().unwrap();
1168 assert_eq!((floor.test.given, floor.test.below), (1000, 50));
1169 assert!(floor.test.passes());
1170 assert!(floor.holds());
1171 let raised = floor.probes[&FloorProbe::Raised];
1173 assert!((250..=270).contains(&raised.below), "{raised:?}");
1174 assert!(!raised.passes());
1175 let lowered = floor.probes[&FloorProbe::Lowered];
1176 assert!(lowered.below <= 3, "{lowered:?}");
1177 assert!(!lowered.passes());
1178 assert_eq!(floor.by_logger["altos"].0, 500);
1179 assert_eq!(floor.by_design[DESIGNS[0].name].0, 1000);
1180 }
1181
1182 #[test]
1183 fn a_floor_missing_too_often_or_too_rarely_fails() {
1184 for (shift, tail) in [(-1.0, "too often"), (2.0, "too rarely")] {
1185 let mut flights = normal_floors();
1186 for f in &mut flights {
1187 if let (_, Said::Floor(c)) = &mut f.said[0] {
1188 c.truth += shift;
1190 }
1191 }
1192 let floor = check(Quantity::Burnout, &flights).floor.unwrap();
1193 assert!(!floor.test.passes(), "{tail}: {:?}", floor.test);
1194 assert!(!floor.holds(), "{tail}");
1195 }
1196 }
1197
1198 #[test]
1199 fn a_floors_truth_that_is_not_a_number_counts_below() {
1200 let mut flights = normal_floors();
1201 if let (_, Said::Floor(c)) = &mut flights[500].said[0] {
1202 c.truth = f64::NAN;
1203 }
1204 let floor = check(Quantity::Burnout, &flights).floor.unwrap();
1205 assert_eq!(floor.test.below, 51);
1206 assert_eq!(floor.probes[&FloorProbe::Lowered].below, 1);
1208 }
1209
1210 #[test]
1213 fn tops_past_the_clip_may_miss_less_than_their_share_but_not_more() {
1214 let past = |truth: f64| -> Vec<FlightSaid> {
1215 (0..200)
1216 .map(|k| FlightSaid {
1217 index: k,
1218 design: 0,
1219 logger: "altos",
1220 air_offset_k: 0.0,
1221 said: vec![(
1222 Quantity::TopAcceleration,
1223 Said::PastClip(ComparedFloor {
1224 reading: 0.0,
1225 bound: 1.0,
1226 low: 0.0,
1227 standard_error: 1.0,
1228 truth,
1229 }),
1230 )],
1231 })
1232 .collect()
1233 };
1234 let none = check(Quantity::TopAcceleration, &past(1.0));
1235 let test = none.past_clip.unwrap();
1236 assert_eq!((test.given, test.below), (200, 0));
1237 assert!(test.no_more_than_its_share());
1238 assert!(fitted_floor(Quantity::TopAcceleration, &past(1.0)).is_none());
1239 let all = check(Quantity::TopAcceleration, &past(-1.0));
1240 let test = all.past_clip.unwrap();
1241 assert!(!test.no_more_than_its_share(), "{test:?}");
1242 let mut some = past(1.0);
1244 for flight in &mut some[..10] {
1245 flight.said = past(-1.0)[0].said.clone();
1246 }
1247 let test = check(Quantity::TopAcceleration, &some).past_clip.unwrap();
1248 assert_eq!(test.below, 10);
1249 assert!(test.band.low < MISS_SHARE && test.band.high > MISS_SHARE);
1250 assert!(test.no_more_than_its_share(), "{test:?}");
1251 }
1252
1253 #[test]
1254 fn a_flight_with_no_canopy_to_read_is_counted_apart() {
1255 let flights = vec![FlightSaid {
1256 index: 0,
1257 design: 0,
1258 logger: "altos",
1259 air_offset_k: 0.0,
1260 said: vec![(Quantity::DrogueRate, Said::Absent)],
1261 }];
1262 let check = check(Quantity::DrogueRate, &flights);
1263 assert_eq!((check.absent, check.test.counts.given), (1, 0));
1264 assert!(check.withheld.is_empty());
1265 }
1266
1267 #[test]
1271 fn a_top_lands_wherever_the_reader_can_call_it_clipped() {
1272 let reach = 1.0 - 0.3 / 8.0;
1273 for (scale, least, most) in [
1274 (0.03, reach / 1.03, 1.0 / 0.97),
1275 (0.10, reach / 1.1, 1.0 / 0.9),
1276 ] {
1277 let ratios: Vec<f64> = (0..1000)
1278 .map(|k| top_over_clip(2_026_102_900, k, scale))
1279 .collect();
1280 assert!(ratios.iter().all(|r| (least..most).contains(r)));
1281 let tenth = least + 0.1 * (most - least);
1282 let lowest = ratios.iter().filter(|r| **r < tenth).count();
1283 assert!((98..=102).contains(&lowest), "{lowest}");
1284 }
1285 let (a, b) = (2_026_101_701, 2_026_101_702);
1287 assert_ne!(top_over_clip(a, 7, 0.03), top_over_clip(b, 7, 0.03));
1288 assert_ne!(top_over_clip(a, 8, 0.03), top_over_clip(b, 7, 0.03));
1289 let read = reach / 1.03 * 1.03 * 8.0 + ACCEL_BIAS_G;
1293 assert!((read - (8.0 - GRAVITY_TOLERANCE_G)).abs() < 1e-9, "{read}");
1294 }
1295
1296 #[test]
1299 fn a_flight_says_its_top_accelerations_floors_from_clipping_logs() {
1300 use super::super::designs::DesignFiles;
1301 use super::super::{Flyer, Set};
1302 let mut flyer = Flyer::new(DesignFiles::committed());
1303 let range = LOWER_RANGE_G * STANDARD_GRAVITY_MPS2;
1304 let (index, flight, said) = (0..120)
1306 .filter_map(|k| flyer.flight(Set::Tuning, k).ok().map(|f| (k, f)))
1307 .filter(|(_, f)| {
1308 f.draw.logger.profile.accelerometer_range_m_s2().is_some()
1309 && top_specific_force(f) > 1.2 * range
1310 })
1311 .map(|(k, f)| {
1312 let said = said(Set::Tuning.seed(), k, &f).unwrap();
1313 (k, f, said)
1314 })
1315 .find(|(_, _, s)| s.said.iter().any(|(_, x)| matches!(x, Said::Floor(_))))
1316 .unwrap();
1317 let tops: Vec<&Said> = said
1318 .said
1319 .iter()
1320 .filter(|(q, _)| *q == Quantity::TopAcceleration)
1321 .map(|(_, s)| s)
1322 .collect();
1323 assert!(matches!(tops[0], Said::Stated(_)), "{tops:?}");
1325 let Said::Floor(at_clip) = tops[1] else {
1326 panic!("{tops:?}");
1327 };
1328 let scale = flight.draw.logger.profile.accelerometer_scale().unwrap();
1329 assert_eq!(
1330 at_clip.truth,
1331 range * top_over_clip(Set::Tuning.seed(), index, scale)
1332 );
1333 assert!((at_clip.reading - range).abs() < 0.2 * range, "{at_clip:?}");
1334 let Said::PastClip(past) = tops[2] else {
1335 panic!("{tops:?}");
1336 };
1337 let top = top_specific_force(&flight);
1338 assert_eq!(past.truth, top);
1339 assert!(past.reading < top, "{past:?}");
1340 assert!(past.low < past.reading, "{past:?}");
1341 }
1342
1343 #[test]
1344 fn floors_and_withheld_readings_are_counted_apart() {
1345 let flights = vec![
1346 FlightSaid {
1347 index: 0,
1348 design: 0,
1349 logger: "altos",
1350 air_offset_k: 0.0,
1351 said: vec![(Quantity::ApogeeHeight, Said::Unstated)],
1352 },
1353 FlightSaid {
1354 index: 1,
1355 design: 0,
1356 logger: "altos",
1357 air_offset_k: 0.0,
1358 said: vec![(Quantity::ApogeeHeight, Said::Withheld(Reason::NoClimb))],
1359 },
1360 ];
1361 let check = check(Quantity::ApogeeHeight, &flights);
1362 assert_eq!(
1363 (check.flights, check.unstated, check.test.counts.given),
1364 (2, 1, 0)
1365 );
1366 assert_eq!(check.withheld[&Reason::NoClimb], 1);
1367 assert!(!check.test.passes());
1369 }
1370
1371 #[test]
1372 fn the_fit_reads_the_errors_as_shares_of_the_bound() {
1373 let flights: Vec<FlightSaid> = (0..199)
1374 .map(|k| FlightSaid {
1375 index: k,
1376 design: 0,
1377 logger: "altos",
1378 air_offset_k: 0.0,
1379 said: vec![(
1380 Quantity::ApogeeHeight,
1381 Said::Stated(Compared {
1382 reading: k as f64,
1383 bound: 2.0,
1384 interval: Interval {
1385 low: 0.0,
1386 high: 1.0,
1387 },
1388 truth: 0.0,
1389 }),
1390 )],
1391 })
1392 .collect();
1393 let fitted = fitted(Quantity::ApogeeHeight, &flights).unwrap();
1395 assert_eq!((fitted.low, fitted.high), (4.5, 94.5));
1396 assert!(fitted_none_below_twenty());
1397 }
1398
1399 fn fitted_none_below_twenty() -> bool {
1400 fitted(Quantity::ApogeeTime, &[]).is_none()
1401 }
1402
1403 #[test]
1404 fn three_figures_rounds_as_the_library_writes() {
1405 assert_eq!(three_figures(0.612_49), 0.612);
1406 assert_eq!(three_figures(-0.000_123_56), -0.000_124);
1407 assert_eq!(three_figures(12_345.0), 12_300.0);
1408 assert_eq!(three_figures(0.0), 0.0);
1409 }
1410}