1use std::collections::BTreeMap;
26
27use hpr_atmos::PowerLawWind;
28use hpr_core::random::SeededRng;
29use hpr_flightdata::log::FlightLog;
30use hpr_flightdata::readings;
31use hpr_flightdata::readings::interval::{Interval, Shares, Z_90};
32use hpr_sim::Simulation;
33use serde::{Deserialize, Serialize};
34
35use super::designs::{DESIGNS, DesignFiles};
36use super::intervals::{Counts, Probe, Test};
37use super::logger::Profile;
38use super::noise::between;
39use super::truth::{self};
40use super::{Draw, Flight, Model, Set, SyntheticError};
41use crate::fit::{
42 self, FLOWN, Fit, Forward, Noise, Observations, Parameters, Prior, Sampling, Stated,
43};
44use crate::posterior::Posterior;
45use crate::residuals::{HeightKind, Simulated, Track};
46
47pub const ASKED: [Asked; 5] = [
49 Asked::DragScale,
50 Asked::ImpulseScale,
51 Asked::WindEast,
52 Asked::WindNorth,
53 Asked::MassScale,
54];
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
58#[serde(rename_all = "kebab-case")]
59pub enum Method {
60 LeastSquares,
63 Bayesian,
65}
66
67impl Method {
68 pub const ALL: [Self; 2] = [Self::LeastSquares, Self::Bayesian];
70
71 #[must_use]
73 pub fn name(self) -> &'static str {
74 match self {
75 Self::LeastSquares => "least squares",
76 Self::Bayesian => "Bayesian",
77 }
78 }
79}
80
81pub const POSTERIOR_PILOT: usize = 100;
88pub const POSTERIOR_DRAWS: usize = 400;
90
91#[must_use]
94pub fn sampling(set: Set, index: u64) -> Sampling {
95 Sampling {
96 pilot: POSTERIOR_PILOT,
97 draws: POSTERIOR_DRAWS,
98 seed: SeededRng::for_stream(set.seed(), &[index, super::POSTERIOR_KEY]).next_u64(),
99 }
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
104#[serde(rename_all = "kebab-case")]
105pub enum Asked {
106 DragScale,
108 ImpulseScale,
110 WindEast,
112 WindNorth,
114 MassScale,
116}
117
118impl Asked {
119 #[must_use]
121 pub fn name(self) -> &'static str {
122 match self {
123 Self::DragScale => "drag scale",
124 Self::ImpulseScale => "impulse scale",
125 Self::WindEast => "wind toward the east, m/s",
126 Self::WindNorth => "wind toward the north, m/s",
127 Self::MassScale => "mass on the weighed mass",
128 }
129 }
130
131 #[must_use]
138 pub fn stated_on_height_alone(self) -> bool {
139 !matches!(self, Self::WindEast | Self::WindNorth)
140 }
141
142 #[must_use]
144 pub fn index(self) -> usize {
145 match self {
146 Self::DragScale => 0,
147 Self::ImpulseScale => 1,
148 Self::WindEast => 3,
149 Self::WindNorth => 4,
150 Self::MassScale => 5,
151 }
152 }
153
154 #[must_use]
158 pub fn stated_width(self) -> f64 {
159 match self {
160 Self::DragScale => 0.9 * 0.4,
161 Self::ImpulseScale => 0.9 * 0.12,
162 Self::WindEast | Self::WindNorth => 2.0 * wind_component_point(),
163 Self::MassScale => 0.9 * 2.0 * WEIGHED_WITHIN,
164 }
165 }
166}
167
168#[must_use]
175pub fn stated_for(observed: Option<&Observations>) -> Stated {
176 let mut stated = stated();
177 if observed.is_some_and(|o| o.horizontal.is_empty()) {
178 stated[Asked::WindEast.index()].mean = super::MAX_WIND_M_S / 3.0_f64.sqrt();
179 }
180 stated
181}
182
183pub const WEIGHED_WITHIN: f64 = 0.02;
186
187#[must_use]
191pub fn wind_component_point() -> f64 {
192 let v_max = super::MAX_WIND_M_S;
193 let upper_share = |x: f64| {
194 let steps = 20_000_u32;
196 let sum: f64 = (0..steps)
197 .map(|k| {
198 let theta = std::f64::consts::PI * (f64::from(k) + 0.5) / f64::from(steps);
199 (1.0 - x / (v_max * theta.sin())).max(0.0)
200 })
201 .sum();
202 0.5 * sum / f64::from(steps)
203 };
204 let (mut low, mut high) = (0.0, v_max);
205 for _ in 0..60 {
206 let middle = 0.5 * (low + high);
207 if upper_share(middle) > 0.05 {
208 low = middle;
209 } else {
210 high = middle;
211 }
212 }
213 0.5 * (low + high)
214}
215
216#[must_use]
221pub fn stated() -> Stated {
222 let of_width = |mean: f64, width: f64| Prior {
223 mean,
224 sd: width / (2.0 * Z_90),
225 };
226 [
227 of_width(1.0, Asked::DragScale.stated_width()),
228 of_width(1.0, Asked::ImpulseScale.stated_width()),
229 of_width(1.0, 0.9 * 0.2),
230 of_width(0.0, Asked::WindEast.stated_width()),
231 of_width(0.0, Asked::WindNorth.stated_width()),
232 of_width(1.0, Asked::MassScale.stated_width()),
233 ]
234}
235
236#[must_use]
239pub fn weighed_factor(set: Set, index: u64) -> f64 {
240 let mut rng = SeededRng::for_stream(set.seed(), &[index, super::WEIGHING_KEY]);
241 between(&mut rng, 1.0 - WEIGHED_WITHIN, 1.0 + WEIGHED_WITHIN)
242}
243
244#[derive(Debug)]
247pub struct Flown<'a> {
248 draw: Draw,
249 files: &'a DesignFiles,
250 weighed: f64,
251 tables: &'a mut BTreeMap<usize, Simulation>,
252}
253
254impl<'a> Flown<'a> {
255 pub fn new(
257 draw: &Draw,
258 files: &'a DesignFiles,
259 weighed: f64,
260 tables: &'a mut BTreeMap<usize, Simulation>,
261 ) -> Self {
262 Self {
263 draw: *draw,
264 files,
265 weighed,
266 tables,
267 }
268 }
269}
270
271impl Forward for Flown<'_> {
272 fn fly(&mut self, p: &Parameters, until_s: f64) -> Result<Simulated, String> {
273 self.flown(p, until_s, None)
274 }
275
276 fn fly_sheared(
278 &mut self,
279 p: &Parameters,
280 until_s: f64,
281 exponent: f64,
282 ) -> Result<Simulated, String> {
283 self.flown(p, until_s, Some(exponent))
284 }
285}
286
287impl Flown<'_> {
288 fn flown(
290 &mut self,
291 p: &Parameters,
292 until_s: f64,
293 shear: Option<f64>,
294 ) -> Result<Simulated, String> {
295 if p.drag_scale <= 0.0 || p.impulse_scale <= 0.0 || p.burn_time_scale <= 0.0 {
296 return Err("a scale that isn't positive".to_owned());
297 }
298 let wind_speed_m_s = p.wind_east_m_s.hypot(p.wind_north_m_s);
299 let wind_from_rad = (-p.wind_east_m_s)
301 .atan2(-p.wind_north_m_s)
302 .rem_euclid(std::f64::consts::TAU);
303 let told = Draw {
304 impulse_scale: p.impulse_scale,
305 burn_time_scale: p.burn_time_scale,
306 drag_scale: p.drag_scale,
307 wind_speed_m_s,
308 wind_from_rad,
309 model: Model::Same,
310 ..self.draw
311 };
312 let mut inputs = truth::inputs(&told, self.files).map_err(|e| e.to_string())?;
313 if let Some(exponent) = shear {
314 inputs.environment = inputs.environment.with_wind(
315 PowerLawWind::new(
316 wind_speed_m_s,
317 truth::SHEAR_REFERENCE_HEIGHT_M,
318 exponent,
319 wind_from_rad,
320 told.elevation_m,
321 )
322 .map_err(|e| e.to_string())?,
323 );
324 }
325 inputs.recovery.clear();
326 inputs.settings.max_time_s = until_s;
327 let mut simulation = inputs.simulation().map_err(|e| e.to_string())?;
328 match self.tables.get(&told.design) {
329 Some(nominal) => {
330 simulation.share_supersonic_table(nominal.aero());
331 }
332 None => {
333 let nominal = inputs.simulation().map_err(|e| e.to_string())?;
334 self.tables.insert(told.design, nominal);
335 }
336 }
337 let simulation = simulation
338 .with_structure_mass_scale(self.weighed * p.mass_scale)
339 .map_err(|e| e.to_string())?;
340 let mut track = Track::new();
341 simulation.run(&mut track).map_err(|e| e.to_string())?;
342 track
343 .simulated(&inputs.environment)
344 .map_err(|e| e.to_string())
345 }
346}
347
348#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
350pub struct Compared {
351 pub value: f64,
353 pub standard_error: f64,
355 pub truth: f64,
357}
358
359impl Compared {
360 #[must_use]
362 pub fn share(&self) -> f64 {
363 (self.value - self.truth) / self.standard_error
364 }
365}
366
367#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
369pub struct FlightFit {
370 pub index: u64,
372 pub design: usize,
374 pub fitted: bool,
376 pub drift: bool,
378 pub converged: bool,
380 pub misfit_share: Option<f64>,
382 pub compared: [Compared; ASKED.len()],
384 pub rms_m: Option<f64>,
386 pub flown: u64,
388 pub posterior: Option<Posterior<FLOWN>>,
391}
392
393pub fn noise_free_observations(
402 observed: &Observations,
403 read: &[bool],
404 flight: &Flight,
405 files: &DesignFiles,
406) -> Result<Observations, SyntheticError> {
407 let environment = truth::inputs(&flight.draw, files)?.environment;
408 let flown = Simulated::new(flight.truth.samples.clone(), &environment).map_err(|_| {
409 SyntheticError::Flight {
410 what: "a truth the day's air doesn't reach",
411 }
412 })?;
413 if read.len() != observed.heights.len() {
414 return Err(SyntheticError::Flight {
415 what: "a fit's bins that aren't this log's",
416 });
417 }
418 let to_flight = |t: f64| t - flight.draw.logger.pad_s;
419 Ok(Observations {
420 kind: observed.kind,
421 heights: observed
425 .heights
426 .iter()
427 .zip(read)
428 .filter(|(_, read)| **read)
429 .map(|(&(t, _), _)| {
430 let at = to_flight(t);
431 (at, flown.read_height_m(at, observed.kind))
432 })
433 .collect(),
434 horizontal: observed
438 .heights
439 .iter()
440 .map(|&(t, _)| {
441 let at = to_flight(t);
442 let (east, north) = flown.drift_m(at);
443 (at, east, north)
444 })
445 .collect(),
446 liftoff_s: flight.truth.events.liftoff_s,
447 flown_s: observed.flown_s,
448 reads_transonic: true,
450 })
451}
452
453pub fn noise_free(
465 observed: &Observations,
466 answer: &Fit,
467 flight: &Flight,
468 files: &DesignFiles,
469 tables: &mut BTreeMap<usize, Simulation>,
470) -> Result<Fit, SyntheticError> {
471 let filled = noise_free_observations(observed, &answer.read, flight, files)?;
472 let mut told = stated_for(Some(&filled));
473 told[Asked::MassScale.index()] = Prior {
474 mean: 1.0,
475 sd: 1e-6,
476 };
477 Ok(fit::fit(
478 Some(&filled),
479 &told,
480 Noise::Given {
481 height_m: answer.height_noise_m,
482 horizontal_m: answer.horizontal_noise_m,
483 },
484 &mut Flown::new(&flight.draw, files, 1.0, tables),
485 ))
486}
487
488pub fn fit_log(
496 log: &FlightLog,
497 flight: &Flight,
498 set: Set,
499 bayesian: bool,
500 files: &DesignFiles,
501 tables: &mut BTreeMap<usize, Simulation>,
502) -> Result<FlightFit, SyntheticError> {
503 let draw = &flight.draw;
504 let weighed = weighed_factor(set, draw.index);
505 let read = readings::read(log);
506 let observed = fit::observations(log, &read);
507 let told = stated_for(observed.as_ref());
508 let (answer, posterior) = fitted_and_sampled(
509 observed.as_ref(),
510 &told,
511 bayesian.then(|| sampling(set, draw.index)),
512 &mut Flown::new(draw, files, weighed, tables),
513 );
514 let mut flown = answer.flown;
515 let mut converged = answer.converged;
516 let truth: [f64; FLOWN] = match draw.model {
517 Model::Same => {
518 let (speed, from) = (draw.wind_speed_m_s, draw.wind_from_rad);
520 [
521 draw.drag_scale,
522 draw.impulse_scale,
523 draw.burn_time_scale,
524 -speed * from.sin(),
525 -speed * from.cos(),
526 f64::NAN,
527 ]
528 }
529 Model::Other { .. } => match observed.as_ref().filter(|_| answer.fitted) {
530 Some(observed) => {
531 let free = noise_free(observed, &answer, flight, files, tables)?;
532 if !free.fitted {
533 return Err(SyntheticError::Flight {
534 what: "no noise-free fit",
535 });
536 }
537 converged &= free.converged;
538 flown += free.flown;
539 free.parameters.to_array()
540 }
541 None => [f64::NAN; FLOWN],
542 },
543 };
544 let values = answer.parameters.to_array();
545 let compared = ASKED.map(|asked| {
546 let i = asked.index();
547 Compared {
548 value: values[i],
549 standard_error: answer.standard_errors[i],
550 truth: if asked == Asked::MassScale {
552 1.0 / weighed
553 } else {
554 truth[i]
555 },
556 }
557 });
558 Ok(FlightFit {
559 index: draw.index,
560 design: draw.design,
561 fitted: answer.fitted,
562 drift: answer.fitted && observed.is_some_and(|o| !o.horizontal.is_empty()),
563 converged,
564 misfit_share: answer.misfit_share,
565 compared,
566 rms_m: answer.rms_m,
567 flown,
568 posterior,
569 })
570}
571
572fn fitted_and_sampled(
574 observed: Option<&Observations>,
575 told: &Stated,
576 sampling: Option<Sampling>,
577 forward: &mut dyn Forward,
578) -> (Fit, Option<Posterior<FLOWN>>) {
579 match sampling {
580 Some(sampling) => {
581 let answer = fit::bayesian(observed, told, Noise::FromResiduals, forward, sampling);
582 (answer.least_squares, answer.posterior)
583 }
584 None => (
585 fit::fit(observed, told, Noise::FromResiduals, forward),
586 None,
587 ),
588 }
589}
590
591#[must_use]
594pub fn noise_log(log: &FlightLog, size_m: f64, seed: u64, index: u64) -> FlightLog {
595 let mut rng = SeededRng::for_stream(seed, &[index, super::NOISE_LOG_KEY]);
596 let (time_s, _) = readings::height_track(log).unwrap_or_default();
597 let altitude_m = time_s
598 .iter()
599 .map(|_| between(&mut rng, -size_m, size_m))
600 .collect();
601 FlightLog {
602 time_s,
603 altitude_m,
604 vertical_speed_m_s: None,
605 channels: Vec::new(),
606 events: Vec::new(),
607 ..log.clone()
608 }
609}
610
611fn shares_of(fit: &FlightFit, asked: Asked) -> Shares {
614 if fit.fitted {
615 shares(asked, fit.drift)
616 } else {
617 Shares {
618 low: -Z_90,
619 high: Z_90,
620 }
621 }
622}
623
624pub fn fit_noise_bins(
628 flight: &Flight,
629 set: Set,
630 bayesian: bool,
631 size_m: f64,
632 track_m: Option<f64>,
633 files: &DesignFiles,
634 tables: &mut BTreeMap<usize, Simulation>,
635) -> FlightFit {
636 let index = flight.draw.index;
637 let mut rng = SeededRng::for_stream(set.seed(), &[index, super::NOISE_LOG_KEY, 1]);
638 let heights = (0..80)
639 .map(|k| (0.25 * f64::from(k), between(&mut rng, -size_m, size_m)))
640 .collect();
641 let horizontal: Vec<(f64, f64, f64)> = track_m.map_or_else(Vec::new, |track_m| {
642 (0..80)
643 .map(|k| {
644 (
645 0.25 * f64::from(k),
646 between(&mut rng, -track_m, track_m),
647 between(&mut rng, -track_m, track_m),
648 )
649 })
650 .collect()
651 });
652 let drift = !horizontal.is_empty();
653 let observed = Observations {
654 kind: HeightKind::Barometric,
655 heights,
656 horizontal,
657 liftoff_s: 0.0,
658 flown_s: 20.0,
659 reads_transonic: false,
660 };
661 let weighed = weighed_factor(set, index);
662 let (answer, posterior) = fitted_and_sampled(
663 Some(&observed),
664 &stated_for(Some(&observed)),
665 bayesian.then(|| sampling(set, index)),
666 &mut Flown::new(&flight.draw, files, weighed, tables),
667 );
668 let values = answer.parameters.to_array();
669 FlightFit {
670 index,
671 design: flight.draw.design,
672 fitted: answer.fitted,
673 drift: answer.fitted && drift,
674 converged: answer.converged,
675 misfit_share: answer.misfit_share,
676 compared: ASKED.map(|asked| Compared {
677 value: values[asked.index()],
678 standard_error: answer.standard_errors[asked.index()],
679 truth: f64::NAN,
680 }),
681 rms_m: answer.rms_m,
682 flown: answer.flown,
683 posterior,
684 }
685}
686
687#[must_use]
690pub fn interval_of(method: Method, fit: &FlightFit, asked: Asked) -> Option<Interval> {
691 let slot = ASKED.iter().position(|a| *a == asked)?;
692 let compared = fit.compared[slot];
693 match method {
694 Method::Bayesian if fit.fitted => {
695 let [low, _, high] = fit.posterior.as_ref()?.quantiles[asked.index()];
696 (low.is_finite() && high.is_finite() && low <= high).then_some(Interval { low, high })
697 }
698 _ => shares_of(fit, asked).interval(compared.value, compared.standard_error),
699 }
700}
701
702fn point_of(method: Method, fit: &FlightFit, asked: Asked, slot: usize) -> f64 {
704 match (method, &fit.posterior) {
705 (Method::Bayesian, Some(posterior)) if fit.fitted => posterior.quantiles[asked.index()][1],
706 (Method::Bayesian, None) if fit.fitted => f64::NAN,
707 _ => fit.compared[slot].value,
708 }
709}
710
711#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
715pub struct Identification {
716 pub median_width: f64,
718 pub stated_width: f64,
720 pub identified: bool,
722}
723
724impl Identification {
725 #[must_use]
727 pub fn of(asked: Asked, fits: &[FlightFit]) -> Self {
728 Self::by(Method::LeastSquares, asked, fits)
729 }
730
731 #[must_use]
734 pub fn by(method: Method, asked: Asked, fits: &[FlightFit]) -> Self {
735 let slot = ASKED.iter().position(|a| *a == asked).unwrap_or(0);
736 let mut widths: Vec<f64> = fits
737 .iter()
738 .map(|f| match method {
739 Method::LeastSquares => {
740 let shares = shares_of(f, asked);
741 (shares.high - shares.low) * f.compared[slot].standard_error
742 }
743 Method::Bayesian => interval_of(method, f, asked)
744 .map_or(f64::INFINITY, |interval| interval.high - interval.low),
745 })
746 .collect();
747 widths.sort_by(f64::total_cmp);
748 let median_width = widths.get(widths.len() / 2).copied().unwrap_or(f64::NAN);
749 let stated_width = asked.stated_width();
750 Self {
751 median_width,
752 stated_width,
753 identified: median_width <= 0.5 * stated_width,
754 }
755 }
756}
757
758pub const RESIDUAL_SPLIT_M: f64 = 1.0;
761
762#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
764pub struct Check {
765 pub asked: Asked,
767 pub test: Test,
769 pub probes: BTreeMap<Probe, Test>,
771 pub by_design: BTreeMap<String, Counts>,
773 pub by_drift: BTreeMap<String, Counts>,
775 pub by_residual: BTreeMap<String, Counts>,
778 pub mean_error: f64,
780 pub identification: Identification,
782}
783
784#[must_use]
786pub fn check(asked: Asked, fits: &[FlightFit]) -> Check {
787 check_by(Method::LeastSquares, asked, fits)
788}
789
790#[must_use]
792pub fn check_by(method: Method, asked: Asked, fits: &[FlightFit]) -> Check {
793 let slot = ASKED.iter().position(|a| *a == asked).unwrap_or(0);
794 let mut counts = Counts::default();
795 let mut probes: BTreeMap<Probe, Counts> =
796 Probe::ALL.iter().map(|&p| (p, Counts::default())).collect();
797 let mut by_design: BTreeMap<String, Counts> = BTreeMap::new();
798 let mut by_drift: BTreeMap<String, Counts> = BTreeMap::new();
799 let mut by_residual: BTreeMap<String, Counts> = BTreeMap::new();
800 let mut error_sum = 0.0;
801 let mut stated_count = 0_u32;
802 for fit in fits {
803 if !fit.fitted || (!fit.drift && !asked.stated_on_height_alone()) {
806 continue;
807 }
808 stated_count += 1;
809 let compared = fit.compared[slot];
810 let Some(interval) = interval_of(method, fit, asked) else {
811 let nowhere = Interval {
813 low: f64::NAN,
814 high: f64::NAN,
815 };
816 counts.add(nowhere, f64::NAN);
817 continue;
818 };
819 counts.add(interval, compared.truth);
820 for (probe, counted) in &mut probes {
821 counted.add(probe.apply(interval), compared.truth);
822 }
823 by_design
824 .entry(
825 DESIGNS
826 .get(fit.design)
827 .map_or("an unknown design", |design| design.name)
828 .to_owned(),
829 )
830 .or_default()
831 .add(interval, compared.truth);
832 by_drift
833 .entry(
834 if fit.drift {
835 "with a horizontal track"
836 } else {
837 "height alone"
838 }
839 .to_owned(),
840 )
841 .or_default()
842 .add(interval, compared.truth);
843 if let Some(rms_m) = fit.rms_m {
844 by_residual
845 .entry(
846 if rms_m < RESIDUAL_SPLIT_M {
847 "heights fit within 1 m"
848 } else {
849 "heights fit to 1 m or worse"
850 }
851 .to_owned(),
852 )
853 .or_default()
854 .add(interval, compared.truth);
855 }
856 error_sum += point_of(method, fit, asked, slot) - compared.truth;
857 }
858 Check {
859 asked,
860 test: Test::of(counts),
861 probes: probes.into_iter().map(|(p, c)| (p, Test::of(c))).collect(),
862 by_design,
863 by_drift,
864 by_residual,
865 mean_error: error_sum / f64::from(stated_count.max(1)),
866 identification: Identification::by(method, asked, fits),
867 }
868}
869
870#[must_use]
874pub fn track_flights(set: Set, count: u64) -> Vec<u64> {
875 (0..)
876 .filter(|&index| super::draw(set, index).logger.profile == Profile::Altos)
877 .take(usize::try_from(count).unwrap_or(usize::MAX))
878 .collect()
879}
880
881#[must_use]
884pub fn fitted(asked: Asked, drift: bool, fits: &[FlightFit]) -> Option<Shares> {
885 let slot = ASKED.iter().position(|a| *a == asked)?;
886 let shares: Vec<f64> = fits
887 .iter()
888 .filter(|f| f.fitted && f.drift == drift)
889 .map(|f| f.compared[slot].share())
890 .collect();
891 hpr_flightdata::readings::interval::fit(&shares)
892}
893
894#[must_use]
899pub fn shares(asked: Asked, drift: bool) -> Shares {
900 let (low, high) = match (asked, drift) {
901 (Asked::DragScale, false) => (-1.26, 1.43),
902 (Asked::ImpulseScale, false) => (-1.53, 1.47),
903 (Asked::WindEast, false) => (-0.374, 3.25),
904 (Asked::WindNorth, false) => (-1.71, 1.74),
905 (Asked::MassScale, false) => (-1.66, 1.67),
906 (Asked::DragScale, true) => (-1.29, 2.12),
907 (Asked::ImpulseScale, true) => (-1.5, 1.84),
908 (Asked::WindEast, true) => (-1.4, 1.29),
909 (Asked::WindNorth, true) => (-1.5, 1.38),
910 (Asked::MassScale, true) => (-1.68, 1.7),
911 };
912 Shares { low, high }
913}
914
915#[cfg(test)]
916#[allow(
917 clippy::unwrap_used,
918 clippy::expect_used,
919 reason = "a test stops at the failure (clippy.toml)"
920)]
921mod tests {
922 use super::*;
923
924 #[test]
925 fn the_wind_components_stated_width_is_what_the_draw_gives() {
926 let mut rng = SeededRng::for_stream(7, &[1]);
928 let mut values: Vec<f64> = (0..200_000)
929 .map(|_| {
930 let v = between(&mut rng, 0.0, super::super::MAX_WIND_M_S);
931 let theta = between(&mut rng, 0.0, std::f64::consts::TAU);
932 v * theta.sin()
933 })
934 .collect();
935 values.sort_by(f64::total_cmp);
936 let point = wind_component_point();
937 assert!(
938 (values[190_000] - point).abs() < 0.05,
939 "{} against {point}",
940 values[190_000]
941 );
942 assert!((values[10_000] + point).abs() < 0.05);
943 }
944
945 #[test]
946 fn with_no_log_each_interval_is_its_stated_range() {
947 for asked in ASKED {
948 let told = stated()[asked.index()];
949 let width = 2.0 * Z_90 * told.sd;
950 assert!((width - asked.stated_width()).abs() < 1e-12, "{asked:?}");
951 }
952 }
953
954 #[test]
955 fn each_method_states_its_own_interval() {
956 let compared = Compared {
957 value: 1.0,
958 standard_error: 0.1,
959 truth: 1.05,
960 };
961 let posterior = Posterior {
962 quantiles: std::array::from_fn(|i| {
964 let i = f64::from(u8::try_from(i).unwrap());
965 [0.9 - 0.1 * i, 1.0, 1.3 + 0.1 * i]
966 }),
967 effective_draws: 150.0,
968 draws: 500,
969 failed: 0,
970 enough: true,
971 };
972 let fit = FlightFit {
973 index: 0,
974 design: 0,
975 fitted: true,
976 drift: false,
977 converged: true,
978 misfit_share: Some(0.01),
979 compared: [compared; ASKED.len()],
980 rms_m: Some(0.5),
981 flown: 70,
982 posterior: Some(posterior),
983 };
984 let bayes = interval_of(Method::Bayesian, &fit, Asked::DragScale).unwrap();
986 assert_eq!((bayes.low, bayes.high), (0.9, 1.3));
987 let mass = interval_of(Method::Bayesian, &fit, Asked::MassScale).unwrap();
988 assert!((mass.low - 0.4).abs() < 1e-12 && (mass.high - 1.8).abs() < 1e-12);
989 let shares = shares(Asked::DragScale, false);
991 let least = interval_of(Method::LeastSquares, &fit, Asked::DragScale).unwrap();
992 assert!((least.low - (1.0 - shares.high * 0.1)).abs() < 1e-12);
993 let without = FlightFit {
996 posterior: None,
997 ..fit.clone()
998 };
999 assert!(interval_of(Method::Bayesian, &without, Asked::DragScale).is_none());
1000 let nothing = FlightFit {
1001 fitted: false,
1002 posterior: None,
1003 ..fit
1004 };
1005 let both = Method::ALL.map(|m| interval_of(m, ¬hing, Asked::DragScale).unwrap());
1006 assert_eq!(both[0], both[1]);
1007 assert!((both[0].high - (1.0 + Z_90 * 0.1)).abs() < 1e-12);
1008 }
1009
1010 #[test]
1011 fn the_weighing_factor_stays_in_its_range_and_fills_it() {
1012 let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
1013 for k in 0..2_000 {
1014 let f = weighed_factor(Set::A, k);
1015 low = low.min(f);
1016 high = high.max(f);
1017 }
1018 assert!((0.98..0.981).contains(&low), "{low}");
1019 assert!(high <= 1.02 && high > 1.019, "{high}");
1020 }
1021}