1use std::f64::consts::{FRAC_PI_2, PI};
88use std::sync::Arc;
89
90use hpr_aero::table::DragTable;
91use hpr_aero::{AeroModel, DragModel};
92use hpr_atmos::{AtmosError, DirectionTurn, Wind, WindLevel, WindSample};
93use hpr_core::random::SeededRng;
94use hpr_core::{DMat3, DVec3};
95use hpr_design::{InertiaOverride, LaidOut, Rocket};
96use hpr_motor::motor::{Propellant, PropellantColumn};
97use hpr_motor::{BatesGrains, Delay, SolidMotor, ThrustCurve};
98use hpr_sim::{
99 Device, DeviceDrag, Environment, FlightMetrics, FlightSettings, FlightSummary, Rail,
100 Separation, SimError, Simulation,
101};
102use serde::{Deserialize, Serialize};
103
104use crate::ellipse::Scatter;
105use crate::error::AnalysisError;
106use crate::statistics::Distribution;
107
108#[derive(Debug, Clone)]
111#[non_exhaustive]
112pub enum DragOverride {
113 Table(DragTable),
115 Model(Arc<dyn DragModel>),
117}
118
119#[derive(Debug, Clone)]
122pub struct FlightInputs {
123 pub rocket: Rocket,
125 pub configuration_id: String,
127 pub environment: Environment,
129 pub rail: Rail,
131 pub settings: FlightSettings,
133 pub recovery: Vec<Device>,
135 pub drag: Option<DragOverride>,
137 pub drag_scale: f64,
139 pub separations: Vec<Separation>,
142}
143
144impl FlightInputs {
145 pub fn new(
148 rocket: Rocket,
149 configuration_id: impl Into<String>,
150 environment: Environment,
151 rail: Rail,
152 ) -> Self {
153 Self {
154 rocket,
155 configuration_id: configuration_id.into(),
156 environment,
157 rail,
158 settings: FlightSettings::default(),
159 recovery: Vec::new(),
160 drag: None,
161 drag_scale: 1.0,
162 separations: Vec::new(),
163 }
164 }
165
166 pub fn simulation(&self) -> Result<Simulation, SimError> {
173 self.simulation_on(self.rocket.lay_out()?)
174 }
175
176 fn simulation_on(&self, laid_out: LaidOut) -> Result<Simulation, SimError> {
178 let mut simulation = Simulation::from_laid_out(
179 laid_out,
180 &self.configuration_id,
181 self.environment.clone(),
182 self.rail,
183 self.settings,
184 )?;
185 match &self.drag {
186 Some(DragOverride::Table(table)) => {
187 simulation = simulation.with_drag_table(table.clone());
188 }
189 Some(DragOverride::Model(model)) => {
190 simulation = simulation.with_shared_drag_model(Arc::clone(model));
191 }
192 None => {}
193 }
194 if self.drag_scale != 1.0 {
195 simulation = simulation.with_drag_scale(self.drag_scale)?;
196 }
197 if !self.recovery.is_empty() {
198 simulation = simulation.with_recovery(self.recovery.clone())?;
199 }
200 if self.separations.is_empty() {
201 Ok(simulation)
202 } else {
203 simulation.with_separations(self.separations.clone())
204 }
205 }
206
207 pub fn fly(&self) -> Result<FlightSummary, SimError> {
214 self.fly_on(self.simulation()?)
215 }
216
217 fn fly_sharing(&self, shared: Option<&Shared>) -> Result<FlightSummary, SimError> {
222 let Some(shared) = shared else {
223 return self.fly();
224 };
225 let mut simulation = self.simulation_on(shared.laid_out.relay(self.rocket.clone())?)?;
226 simulation.share_supersonic_table(&shared.tables);
227 self.fly_on(simulation)
228 }
229
230 fn fly_on(&self, simulation: Simulation) -> Result<FlightSummary, SimError> {
232 let mut metrics = FlightMetrics::new();
233 let result = simulation.run(&mut metrics)?;
234 metrics.summary(&result, &self.environment)
235 }
236}
237
238#[derive(Debug, Clone)]
241struct Shared {
242 laid_out: LaidOut,
243 tables: AeroModel,
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
249#[serde(default, deny_unknown_fields)]
250pub struct Dispersion {
251 pub dry_mass_sd_fraction: f64,
253 pub cg_sd_m: f64,
255 pub drag_sd_fraction: f64,
257 pub impulse_sd_fraction: f64,
259 pub burn_time_sd_fraction: f64,
261 pub ejection_delay_sd_s: f64,
263 pub wind_speed_sd_fraction: f64,
265 pub wind_heading_sd_rad: f64,
267 pub rail_elevation_sd_rad: f64,
269 pub rail_azimuth_sd_rad: f64,
271 pub deployment_lag_sd_s: f64,
273}
274
275impl Dispersion {
276 fn named(&self) -> [(&'static str, f64); 11] {
278 [
279 ("dry-mass standard deviation", self.dry_mass_sd_fraction),
280 ("center-of-mass standard deviation (m)", self.cg_sd_m),
281 ("drag standard deviation", self.drag_sd_fraction),
282 ("impulse standard deviation", self.impulse_sd_fraction),
283 ("burn-time standard deviation", self.burn_time_sd_fraction),
284 (
285 "ejection-delay standard deviation (s)",
286 self.ejection_delay_sd_s,
287 ),
288 ("wind-speed standard deviation", self.wind_speed_sd_fraction),
289 (
290 "wind-heading standard deviation (rad)",
291 self.wind_heading_sd_rad,
292 ),
293 (
294 "rail-elevation standard deviation (rad)",
295 self.rail_elevation_sd_rad,
296 ),
297 (
298 "rail-azimuth standard deviation (rad)",
299 self.rail_azimuth_sd_rad,
300 ),
301 (
302 "deployment-lag standard deviation (s)",
303 self.deployment_lag_sd_s,
304 ),
305 ]
306 }
307
308 pub fn validate(&self) -> Result<(), AnalysisError> {
314 for (what, value) in self.named() {
315 if !(value.is_finite() && value >= 0.0) {
316 return Err(AnalysisError::Domain { what, value });
317 }
318 }
319 Ok(())
320 }
321}
322
323#[derive(Debug, Clone, Copy)]
326enum Input {
327 DryMass = 1,
328 CenterOfMass = 2,
329 Drag = 3,
330 Impulse = 4,
331 BurnTime = 5,
332 EjectionDelay = 6,
333 WindSpeed = 7,
334 WindHeading = 8,
335 RailElevation = 9,
336 RailAzimuth = 10,
337 DeploymentLag = 11,
338}
339
340#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
345pub struct Draw {
346 pub dry_mass_scale: Vec<f64>,
348 pub cg_shift_m: Vec<f64>,
350 pub drag_scale: f64,
352 pub impulse_scale: Vec<f64>,
354 pub burn_time_scale: Vec<f64>,
356 pub ejection_delay_offset_s: Vec<f64>,
358 pub wind_speed_scale: f64,
360 pub wind_turn_rad: f64,
362 pub rail_elevation_offset_rad: f64,
364 pub rail_azimuth_offset_rad: f64,
366 pub deployment_lag_offset_s: Vec<f64>,
368}
369
370#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
372#[serde(tag = "outcome", rename_all = "snake_case")]
373pub enum Outcome {
374 Flown {
377 summary: Box<FlightSummary>,
379 },
380 Failed {
382 at: FailedAt,
384 reason: String,
386 },
387}
388
389#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
391#[serde(rename_all = "snake_case")]
392pub enum FailedAt {
393 Inputs,
396 Flight,
399}
400
401#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
403pub struct Sample {
404 pub index: u64,
406 pub draw: Draw,
408 pub outcome: Outcome,
410}
411
412impl Sample {
413 pub fn summary(&self) -> Option<&FlightSummary> {
415 match &self.outcome {
416 Outcome::Flown { summary } => Some(summary),
417 Outcome::Failed { .. } => None,
418 }
419 }
420}
421
422#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
424pub struct Run {
425 pub seed: u64,
427 pub samples: Vec<Sample>,
429}
430
431impl Run {
432 pub fn failed(&self) -> impl Iterator<Item = &Sample> {
434 self.samples
435 .iter()
436 .filter(|sample| matches!(sample.outcome, Outcome::Failed { .. }))
437 }
438
439 pub fn distribution(
446 &self,
447 value: impl Fn(&FlightSummary) -> Option<f64>,
448 ) -> Result<Distribution, AnalysisError> {
449 let values = self
450 .samples
451 .iter()
452 .filter_map(|sample| sample.summary().and_then(&value))
453 .collect();
454 Distribution::new(values, self.samples.len())
455 }
456
457 pub fn apogee(&self) -> Result<Distribution, AnalysisError> {
463 self.distribution(|summary| {
464 summary
465 .apogee
466 .as_ref()
467 .map(|apogee| apogee.height_above_ground_m)
468 })
469 }
470
471 pub fn landing(&self) -> Result<Scatter, AnalysisError> {
481 let points = self
482 .samples
483 .iter()
484 .filter_map(|sample| sample.summary()?.nose_landing())
485 .map(|landing| [landing.east_m, landing.north_m])
486 .collect();
487 Scatter::new(points, self.samples.len())
488 }
489}
490
491#[derive(Debug, Clone, Copy)]
493struct StageMass {
494 mass_kg: f64,
495 cg_aft_m: f64,
497 inertia_kg_m2: DMat3,
499}
500
501#[derive(Debug, Clone)]
503pub struct MonteCarlo {
504 nominal: FlightInputs,
505 dispersion: Dispersion,
506 stages: Vec<StageMass>,
507 configuration: usize,
508 shared: Option<Shared>,
511}
512
513impl MonteCarlo {
514 pub fn new(nominal: FlightInputs, dispersion: Dispersion) -> Result<Self, AnalysisError> {
524 dispersion.validate()?;
525 let configuration = nominal
526 .rocket
527 .configurations
528 .iter()
529 .position(|c| c.id == nominal.configuration_id)
530 .ok_or_else(|| AnalysisError::NoConfiguration(nominal.configuration_id.clone()))?;
531 let layout = nominal.rocket.layout()?;
532 let stages = layout
533 .stages
534 .iter()
535 .map(|stage| StageMass {
536 mass_kg: stage.mass.mass_kg,
537 cg_aft_m: -stage.mass.cg_m.z - stage.fore_station_m,
539 inertia_kg_m2: stage.mass.inertia_kg_m2,
540 })
541 .collect();
542 if dispersion.impulse_sd_fraction > 0.0 || dispersion.burn_time_sd_fraction > 0.0 {
543 for mounted in &nominal.rocket.configurations[configuration].motors {
544 dispersed_motor(&mounted.motor, 1.0, 1.0)?;
545 }
546 }
547 let shared = nominal.rocket.lay_out().ok().and_then(|laid_out| {
548 let tables = AeroModel::new(laid_out.layout()).ok()?;
549 Some(Shared { laid_out, tables })
550 });
551 Ok(Self {
552 nominal,
553 dispersion,
554 stages,
555 configuration,
556 shared,
557 })
558 }
559
560 pub fn nominal(&self) -> &FlightInputs {
562 &self.nominal
563 }
564
565 pub fn dispersion(&self) -> &Dispersion {
567 &self.dispersion
568 }
569
570 pub fn draw(&self, seed: u64, index: u64) -> Draw {
572 let d = &self.dispersion;
573 let normal = |input: Input, copy: usize, sd: f64| {
574 if sd > 0.0 {
575 sd * SeededRng::for_stream(seed, &[index, input as u64, copy as u64])
577 .standard_normal()
578 } else {
579 0.0
580 }
581 };
582 let per = |count: usize, input: Input, sd: f64, base: f64| -> Vec<f64> {
583 (0..count)
584 .map(|copy| base + normal(input, copy, sd))
585 .collect()
586 };
587 let stages = self.nominal.rocket.stages.len();
588 let motors = self.nominal.rocket.configurations[self.configuration]
589 .motors
590 .len();
591 let lags = self
594 .nominal
595 .recovery
596 .iter()
597 .enumerate()
598 .map(|(copy, device)| match device.drag {
599 DeviceDrag::Tumble { .. } => 0.0,
600 _ => normal(Input::DeploymentLag, copy, d.deployment_lag_sd_s),
601 })
602 .collect();
603 Draw {
604 dry_mass_scale: per(stages, Input::DryMass, d.dry_mass_sd_fraction, 1.0),
605 cg_shift_m: per(stages, Input::CenterOfMass, d.cg_sd_m, 0.0),
606 drag_scale: 1.0 + normal(Input::Drag, 0, d.drag_sd_fraction),
607 impulse_scale: per(motors, Input::Impulse, d.impulse_sd_fraction, 1.0),
608 burn_time_scale: per(motors, Input::BurnTime, d.burn_time_sd_fraction, 1.0),
609 ejection_delay_offset_s: per(motors, Input::EjectionDelay, d.ejection_delay_sd_s, 0.0),
610 wind_speed_scale: 1.0 + normal(Input::WindSpeed, 0, d.wind_speed_sd_fraction),
611 wind_turn_rad: normal(Input::WindHeading, 0, d.wind_heading_sd_rad),
612 rail_elevation_offset_rad: normal(Input::RailElevation, 0, d.rail_elevation_sd_rad),
613 rail_azimuth_offset_rad: normal(Input::RailAzimuth, 0, d.rail_azimuth_sd_rad),
614 deployment_lag_offset_s: lags,
615 }
616 }
617
618 pub fn inputs(&self, draw: &Draw) -> Result<FlightInputs, AnalysisError> {
632 self.check(draw)?;
633 let mut inputs = self.nominal.clone();
634 for ((stage, nominal), (&scale, &shift)) in inputs
635 .rocket
636 .stages
637 .iter_mut()
638 .zip(&self.stages)
639 .zip(draw.dry_mass_scale.iter().zip(&draw.cg_shift_m))
640 {
641 if scale != 1.0 {
642 stage.overrides.mass_kg = Some(nominal.mass_kg * scale);
643 if let Some(inertia) = &mut stage.overrides.inertia {
645 for value in [
646 &mut inertia.xx_kg_m2,
647 &mut inertia.yy_kg_m2,
648 &mut inertia.zz_kg_m2,
649 &mut inertia.xy_kg_m2,
650 &mut inertia.xz_kg_m2,
651 &mut inertia.yz_kg_m2,
652 ] {
653 *value *= scale;
654 }
655 }
656 }
657 if shift != 0.0 {
658 stage.overrides.cg_aft_m = Some(nominal.cg_aft_m + shift);
659 }
660 if (scale != 1.0 || shift != 0.0)
665 && !stage.override_rule.is_rescaled()
666 && stage.overrides.inertia.is_none()
667 {
668 let i = nominal.inertia_kg_m2 * scale;
669 stage.overrides.inertia = Some(InertiaOverride {
670 xx_kg_m2: i.x_axis.x,
671 yy_kg_m2: i.y_axis.y,
672 zz_kg_m2: i.z_axis.z,
673 xy_kg_m2: i.x_axis.y,
674 xz_kg_m2: i.x_axis.z,
675 yz_kg_m2: i.y_axis.z,
676 });
677 }
678 }
679 let motors = &mut inputs.rocket.configurations[self.configuration].motors;
680 for (mounted, ((&impulse, &burn), &delay)) in motors.iter_mut().zip(
681 draw.impulse_scale
682 .iter()
683 .zip(&draw.burn_time_scale)
684 .zip(&draw.ejection_delay_offset_s),
685 ) {
686 if impulse != 1.0 || burn != 1.0 {
687 mounted.motor = dispersed_motor(&mounted.motor, impulse, burn)?;
688 }
689 if delay != 0.0
690 && let Some(Delay::Seconds(delay_s)) = mounted.delay
691 {
692 mounted.delay = Some(Delay::Seconds((delay_s + delay).max(0.0)));
693 }
694 }
695 if draw.drag_scale != 1.0 {
696 inputs.drag_scale *= draw.drag_scale;
697 }
698 if draw.wind_speed_scale != 1.0 || draw.wind_turn_rad != 0.0 {
699 inputs.environment.wind = Arc::new(DispersedWind::new(
700 Arc::clone(&inputs.environment.wind),
701 draw.wind_speed_scale.max(0.0),
702 draw.wind_turn_rad,
703 )?);
704 }
705 if draw.rail_elevation_offset_rad != 0.0 || draw.rail_azimuth_offset_rad != 0.0 {
706 inputs.rail = tilted(
707 inputs.rail,
708 draw.rail_elevation_offset_rad,
709 draw.rail_azimuth_offset_rad,
710 );
711 }
712 for (device, &offset) in inputs
713 .recovery
714 .iter_mut()
715 .zip(&draw.deployment_lag_offset_s)
716 {
717 if offset != 0.0 {
718 device.lag_s = (device.lag_s + offset).max(0.0);
719 }
720 }
721 Ok(inputs)
722 }
723
724 fn check(&self, draw: &Draw) -> Result<(), AnalysisError> {
727 let stages = self.nominal.rocket.stages.len();
728 let motors = self.nominal.rocket.configurations[self.configuration]
729 .motors
730 .len();
731 let devices = self.nominal.recovery.len();
732 let lists: [(&'static str, &[f64], usize); 6] = [
733 (
734 "dry-mass factors, against the stages",
735 &draw.dry_mass_scale,
736 stages,
737 ),
738 (
739 "center-of-mass shifts, against the stages",
740 &draw.cg_shift_m,
741 stages,
742 ),
743 (
744 "impulse factors, against the motors",
745 &draw.impulse_scale,
746 motors,
747 ),
748 (
749 "burn-time factors, against the motors",
750 &draw.burn_time_scale,
751 motors,
752 ),
753 (
754 "ejection-delay offsets, against the motors",
755 &draw.ejection_delay_offset_s,
756 motors,
757 ),
758 (
759 "deployment-lag offsets, against the recovery devices",
760 &draw.deployment_lag_offset_s,
761 devices,
762 ),
763 ];
764 for (what, list, count) in lists {
765 if list.len() != count {
766 return Err(AnalysisError::Length {
767 what,
768 length: list.len(),
769 expected: count,
770 });
771 }
772 if let Some(&bad) = list.iter().find(|v| !v.is_finite()) {
773 return Err(AnalysisError::Domain {
774 what: "entry of a draw",
775 value: bad,
776 });
777 }
778 }
779 for value in [
780 draw.drag_scale,
781 draw.wind_speed_scale,
782 draw.wind_turn_rad,
783 draw.rail_elevation_offset_rad,
784 draw.rail_azimuth_offset_rad,
785 ] {
786 if !value.is_finite() {
787 return Err(AnalysisError::Domain {
788 what: "entry of a draw",
789 value,
790 });
791 }
792 }
793 Ok(())
794 }
795
796 pub fn fly(&self, draw: &Draw) -> Result<FlightSummary, AnalysisError> {
806 Ok(self.inputs(draw)?.fly_sharing(self.shared.as_ref())?)
807 }
808
809 pub fn sample(&self, seed: u64, index: u64) -> Sample {
812 let draw = self.draw(seed, index);
813 let outcome = match self.inputs(&draw) {
814 Err(error) => Outcome::Failed {
815 at: FailedAt::Inputs,
816 reason: error.to_string(),
817 },
818 Ok(inputs) => match inputs.fly_sharing(self.shared.as_ref()) {
819 Ok(summary) => Outcome::Flown {
820 summary: Box::new(summary),
821 },
822 Err(error) => Outcome::Failed {
823 at: FailedAt::Flight,
824 reason: error.to_string(),
825 },
826 },
827 };
828 Sample {
829 index,
830 draw,
831 outcome,
832 }
833 }
834
835 pub fn run(&self, seed: u64, count: u64) -> Run {
837 Run {
838 seed,
839 samples: (0..count).map(|index| self.sample(seed, index)).collect(),
840 }
841 }
842
843 #[cfg(feature = "parallel")]
847 pub fn run_parallel(&self, seed: u64, count: u64) -> Run {
848 use rayon::prelude::*;
849 Run {
850 seed,
851 samples: (0..count)
852 .into_par_iter()
853 .map(|index| self.sample(seed, index))
854 .collect(),
855 }
856 }
857}
858
859pub fn dispersed_motor(
872 motor: &SolidMotor,
873 impulse_scale: f64,
874 burn_time_scale: f64,
875) -> Result<SolidMotor, AnalysisError> {
876 for (what, value) in [
877 ("impulse factor", impulse_scale),
878 ("burn-time factor", burn_time_scale),
879 ] {
880 if !(value.is_finite() && value > 0.0) {
881 return Err(AnalysisError::Domain { what, value });
882 }
883 }
884 let curve = motor.curve();
885 let thrust_scale = impulse_scale / burn_time_scale;
886 let curve = ThrustCurve::new(
887 curve
888 .times_s()
889 .iter()
890 .map(|t| t * burn_time_scale)
891 .collect(),
892 curve.thrusts_n().iter().map(|f| f * thrust_scale).collect(),
893 )?;
894 let propellant = match motor.propellant() {
895 Propellant::Column(column) => Propellant::Column(PropellantColumn {
896 mass_kg: column.mass_kg * impulse_scale,
897 ..*column
898 }),
899 Propellant::Grains(grains) => Propellant::Grains(BatesGrains {
900 density_kg_m3: grains.density_kg_m3 * impulse_scale,
901 ..*grains
902 }),
903 other => {
904 return Err(AnalysisError::Unsupported(format!(
905 "dispersing the impulse of a motor whose propellant is {other:?}"
906 )));
907 }
908 };
909 Ok(SolidMotor::new(
910 curve,
911 propellant,
912 motor.dry(),
913 motor.nozzle(),
914 )?)
915}
916
917fn tilted(rail: Rail, elevation_offset_rad: f64, azimuth_offset_rad: f64) -> Rail {
921 let mut tilted = rail;
922 tilted.elevation_rad += elevation_offset_rad;
923 tilted.azimuth_rad += azimuth_offset_rad;
924 if tilted.elevation_rad > FRAC_PI_2 {
925 tilted.elevation_rad = PI - tilted.elevation_rad;
926 tilted.azimuth_rad += PI;
927 tilted.roll_rad += PI;
928 }
929 tilted
930}
931
932#[derive(Debug, Clone)]
937pub struct DispersedWind {
938 base: Arc<dyn Wind>,
939 speed_scale: f64,
940 turn_rad: f64,
941 turn_sin_cos: (f64, f64),
943}
944
945impl DispersedWind {
946 pub fn new(
953 base: Arc<dyn Wind>,
954 speed_scale: f64,
955 turn_rad: f64,
956 ) -> Result<Self, AnalysisError> {
957 if !(speed_scale.is_finite() && speed_scale >= 0.0) {
958 return Err(AnalysisError::Domain {
959 what: "wind-speed factor",
960 value: speed_scale,
961 });
962 }
963 if !turn_rad.is_finite() {
964 return Err(AnalysisError::Domain {
965 what: "wind turn (rad)",
966 value: turn_rad,
967 });
968 }
969 Ok(Self {
970 base,
971 speed_scale,
972 turn_rad,
973 turn_sin_cos: turn_rad.sin_cos(),
974 })
975 }
976}
977
978impl Wind for DispersedWind {
979 fn wind(&self, height_msl_m: f64) -> Result<WindSample, AtmosError> {
980 let mut sample = self.base.wind(height_msl_m)?;
981 let v = sample.velocity_enu_m_s;
982 let (sin, cos) = self.turn_sin_cos;
983 sample.velocity_enu_m_s =
986 DVec3::new(v.x * cos + v.y * sin, v.y * cos - v.x * sin, v.z) * self.speed_scale;
987 Ok(sample)
988 }
989
990 fn direction_turns(&self) -> Vec<DirectionTurn> {
997 let map = |level: WindLevel| WindLevel {
998 direction_from_rad: (level.direction_from_rad + self.turn_rad)
999 .rem_euclid(std::f64::consts::TAU),
1000 ..level
1001 };
1002 self.base
1003 .direction_turns()
1004 .into_iter()
1005 .map(|turn| DirectionTurn {
1006 lower: map(turn.lower),
1007 upper: map(turn.upper),
1008 })
1009 .collect()
1010 }
1011}
1012
1013#[cfg(test)]
1014pub(crate) mod tests {
1015 use hpr_atmos::ConstantWind;
1016 use hpr_core::frames::LaunchAngles;
1017 use hpr_core::geodesy::Geodetic;
1018 use hpr_sim::{DeviceDrag, Trigger};
1019
1020 use super::*;
1021
1022 pub(crate) const SEED: u64 = 20_261_001;
1023 const GOLDEN_STREAM: u64 = 2_627_254_379_500_910_771;
1025 const GOLDEN_DRAG: f64 = 1.012_497_722_244_850_1;
1029 const GOLDEN_IMPULSE: f64 = 1.020_485_907_939_679_7;
1030
1031 fn valetudo() -> Rocket {
1032 serde_json::from_str(include_str!(
1033 "../../../validation/designs/rocketpy-valetudo.json"
1034 ))
1035 .unwrap()
1036 }
1037
1038 pub(crate) fn nominal() -> FlightInputs {
1041 let site = Geodetic::from_degrees(32.99, -106.97, 1400.0).unwrap();
1042 let environment = Environment::standard(site)
1043 .unwrap()
1044 .with_wind(ConstantWind::new(5.0, 1.5 * PI).unwrap());
1045 let mut rail = Rail::vertical(5.2);
1046 rail.elevation_rad = 85_f64.to_radians();
1047 let mut inputs = FlightInputs::new(valetudo(), "example", environment, rail);
1048 inputs.recovery = vec![
1049 Device::new(
1050 "drogue",
1051 DeviceDrag::DragArea { cd_s_m2: 0.3 },
1052 Trigger::Apogee,
1053 )
1054 .with_lag_s(1.0),
1055 ];
1056 inputs
1057 }
1058
1059 pub(crate) fn every_dispersion() -> Dispersion {
1060 Dispersion {
1061 dry_mass_sd_fraction: 0.02,
1062 cg_sd_m: 0.01,
1063 drag_sd_fraction: 0.05,
1064 impulse_sd_fraction: 0.03,
1065 burn_time_sd_fraction: 0.03,
1066 ejection_delay_sd_s: 0.5,
1067 wind_speed_sd_fraction: 0.2,
1068 wind_heading_sd_rad: 10_f64.to_radians(),
1069 rail_elevation_sd_rad: 1_f64.to_radians(),
1070 rail_azimuth_sd_rad: 2_f64.to_radians(),
1071 deployment_lag_sd_s: 0.3,
1072 }
1073 }
1074
1075 #[test]
1079 fn impulse_dispersion_preserves_specific_impulse() {
1080 let nominal = nominal();
1081 let motor = &nominal.rocket.configurations[0].motors[0].motor.clone();
1082 let impulse = motor.curve().total_impulse_ns();
1083 let exhaust = impulse / motor.propellant_initial_mass_kg();
1084 let burn = motor.curve().burn_time_s();
1085 for (k, s) in [(1.1, 1.0), (0.9, 1.2), (1.05, 0.8)] {
1086 let dispersed = dispersed_motor(motor, k, s).unwrap();
1087 let new_impulse = dispersed.curve().total_impulse_ns();
1088 let new_exhaust = new_impulse / dispersed.propellant_initial_mass_kg();
1089 assert!((new_impulse / impulse - k).abs() < 1e-14, "{k} {s}");
1090 assert!((new_exhaust / exhaust - 1.0).abs() < 1e-14, "{k} {s}");
1091 assert!(
1092 (dispersed.curve().burn_time_s() / burn - s).abs() < 1e-12,
1093 "{k} {s}"
1094 );
1095 assert_eq!(dispersed.dry(), motor.dry());
1096 }
1097 let run = MonteCarlo::new(nominal, every_dispersion()).unwrap();
1099 for index in 0..20 {
1100 let draw = run.draw(SEED, index);
1101 let inputs = run.inputs(&draw).unwrap();
1102 let flown = &inputs.rocket.configurations[0].motors[0].motor;
1103 let flown_exhaust =
1104 flown.curve().total_impulse_ns() / flown.propellant_initial_mass_kg();
1105 assert!((flown_exhaust / exhaust - 1.0).abs() < 1e-14);
1106 let flown_impulse = flown.curve().total_impulse_ns() / impulse;
1108 let flown_burn = flown.curve().burn_time_s() / burn;
1109 assert!((flown_impulse - draw.impulse_scale[0]).abs() < 1e-14);
1110 assert!((flown_burn - draw.burn_time_scale[0]).abs() < 1e-12);
1111 assert_ne!(draw.impulse_scale[0], draw.burn_time_scale[0]);
1112 }
1113 let column =
1115 SolidMotor::from_envelope(motor.curve().clone(), 0.075, 0.6, 2.0, 3.5).unwrap();
1116 assert!(matches!(column.propellant(), Propellant::Column(_)));
1117 let heavier = dispersed_motor(&column, 1.2, 0.9).unwrap();
1118 assert!((heavier.propellant_initial_mass_kg() / 2.0 - 1.2).abs() < 1e-15);
1119 assert_eq!(heavier.dry(), column.dry());
1120 let ratio = |m: &SolidMotor| m.curve().total_impulse_ns() / m.propellant_initial_mass_kg();
1121 assert!((ratio(&heavier) / ratio(&column) - 1.0).abs() < 1e-14);
1122 for bad in [0.0, -0.1, f64::NAN] {
1124 assert!(matches!(
1125 dispersed_motor(motor, bad, 1.0),
1126 Err(AnalysisError::Domain {
1127 what: "impulse factor",
1128 ..
1129 })
1130 ));
1131 assert!(matches!(
1132 dispersed_motor(motor, 1.0, bad),
1133 Err(AnalysisError::Domain {
1134 what: "burn-time factor",
1135 ..
1136 })
1137 ));
1138 }
1139 }
1140
1141 #[test]
1145 fn sample_k_independent_of_n_and_thread_count() {
1146 let run = MonteCarlo::new(nominal(), every_dispersion()).unwrap();
1147 let short = run.run(SEED, 3);
1148 let long = run.run(SEED, 6);
1149 assert_eq!(short.samples[..], long.samples[..3]);
1150 assert_eq!(run.sample(SEED, 4), long.samples[4]);
1151 assert!(short.failed().next().is_none());
1152 assert_ne!(run.draw(SEED + 1, 0), run.draw(SEED, 0));
1154 let without_drag = MonteCarlo::new(
1156 nominal(),
1157 Dispersion {
1158 drag_sd_fraction: 0.0,
1159 ..every_dispersion()
1160 },
1161 )
1162 .unwrap();
1163 let (all, some) = (run.draw(SEED, 2), without_drag.draw(SEED, 2));
1164 assert_eq!(some.drag_scale, 1.0);
1165 assert_eq!(
1166 Draw {
1167 drag_scale: 1.0,
1168 ..all.clone()
1169 },
1170 some
1171 );
1172 #[cfg(feature = "parallel")]
1176 for threads in [1, 2, 5] {
1177 let pool = rayon::ThreadPoolBuilder::new()
1178 .num_threads(threads)
1179 .build()
1180 .unwrap();
1181 assert_eq!(
1182 pool.install(|| run.run_parallel(SEED, 6)),
1183 long,
1184 "{threads}"
1185 );
1186 }
1187 }
1188
1189 #[test]
1193 fn failed_samples_are_counted_and_reported() {
1194 let run = MonteCarlo::new(
1196 nominal(),
1197 Dispersion {
1198 dry_mass_sd_fraction: 0.6,
1199 ..Dispersion::default()
1200 },
1201 )
1202 .unwrap()
1203 .run(SEED, 16);
1204 let failed: Vec<&Sample> = run.failed().collect();
1205 assert!(!failed.is_empty() && failed.len() < 16, "{}", failed.len());
1206 for sample in &failed {
1207 assert!(sample.draw.dry_mass_scale[0] < 0.0, "{sample:?}");
1208 let Outcome::Failed { at, reason } = &sample.outcome else {
1209 unreachable!("filtered on failure")
1210 };
1211 assert_eq!(*at, FailedAt::Flight);
1212 assert!(reason.contains("mass"), "{reason}");
1213 }
1214 let apogee = run.apogee().unwrap();
1215 assert_eq!(apogee.attempted(), 16);
1216 let failed_count = failed.len();
1217 assert_eq!(apogee.missing(), failed.len());
1218 let share = apogee.share_at_least(0.0).unwrap().unwrap();
1220 assert_eq!(share.low, (16 - failed_count) as f64 / 16.0);
1221 assert_eq!(share.high, 1.0);
1222 let landing = run.landing().unwrap();
1224 assert_eq!((landing.attempted(), landing.missing()), (16, failed_count));
1225 let mut points: Vec<[f64; 2]> = run
1226 .samples
1227 .iter()
1228 .filter_map(Sample::summary)
1229 .map(|summary| {
1230 let landing = summary.landing.as_ref().unwrap();
1231 [landing.east_m, landing.north_m]
1232 })
1233 .collect();
1234 points.sort_by(|p, q| p[0].total_cmp(&q[0]).then(p[1].total_cmp(&q[1])));
1235 assert_eq!(landing.points(), points.as_slice());
1236 let run = MonteCarlo::new(
1238 nominal(),
1239 Dispersion {
1240 impulse_sd_fraction: 1.0,
1241 ..Dispersion::default()
1242 },
1243 )
1244 .unwrap()
1245 .run(SEED, 16);
1246 let failed: Vec<&Sample> = run.failed().collect();
1247 assert!(
1248 !failed.is_empty(),
1249 "no impulse factor at or below zero in 16"
1250 );
1251 for sample in failed {
1252 assert!(sample.draw.impulse_scale[0] <= 0.0, "{sample:?}");
1253 assert!(
1254 matches!(&sample.outcome, Outcome::Failed { at: FailedAt::Inputs, reason }
1255 if reason.contains("impulse factor")),
1256 "{sample:?}"
1257 );
1258 }
1259 }
1260
1261 #[test]
1265 fn wind_heading_dispersed_about_nominal() {
1266 let sd = 10_f64.to_radians();
1267 let run = MonteCarlo::new(
1268 nominal(),
1269 Dispersion {
1270 wind_heading_sd_rad: sd,
1271 rail_azimuth_sd_rad: sd,
1272 ..Dispersion::default()
1273 },
1274 )
1275 .unwrap();
1276 let n = 2000;
1277 let mut from = Vec::with_capacity(n);
1278 let mut headings = Vec::with_capacity(n);
1279 for index in 0..n as u64 {
1280 let inputs = run.inputs(&run.draw(SEED, index)).unwrap();
1281 let wind = inputs
1282 .environment
1283 .wind
1284 .wind(1500.0)
1285 .unwrap()
1286 .velocity_enu_m_s;
1287 let bearing = (-wind.x).atan2(-wind.y);
1289 from.push(bearing.rem_euclid(2.0 * PI) - 1.5 * PI);
1290 assert!((wind.truncate().length() - 5.0).abs() < 1e-12);
1291 headings.push(inputs.rail.azimuth_rad);
1292 }
1293 for turns in [from, headings] {
1294 let d = Distribution::new(turns, n).unwrap();
1295 let (mean, spread) = (d.mean().unwrap(), d.standard_deviation().unwrap());
1296 assert!(mean.abs() < 4.0 * sd / (n as f64).sqrt(), "{mean}");
1298 assert!(
1299 (spread / sd - 1.0).abs() < 4.0 / (2.0 * (n as f64 - 1.0)).sqrt(),
1300 "{spread}"
1301 );
1302 }
1303 }
1304
1305 #[test]
1308 fn zero_dispersion_reproduces_nominal_flight() {
1309 let nominal_flight = nominal().fly().unwrap();
1310 let run = MonteCarlo::new(nominal(), Dispersion::default())
1311 .unwrap()
1312 .run(SEED, 3);
1313 for sample in &run.samples {
1314 assert_eq!(sample.summary(), Some(&nominal_flight));
1315 }
1316 let apogee = run.apogee().unwrap();
1317 let nominal_apogee = nominal_flight.apogee.unwrap().height_above_ground_m;
1318 assert_eq!(apogee.mean(), Some(nominal_apogee));
1319 assert_eq!(apogee.standard_deviation(), Some(0.0));
1320 let dispersed = MonteCarlo::new(nominal(), every_dispersion()).unwrap();
1322 let first = dispersed.run(SEED, 2);
1323 assert_eq!(first, dispersed.run(SEED, 2));
1324 let json = serde_json::to_string(&first).unwrap();
1325 assert_eq!(serde_json::from_str::<Run>(&json).unwrap(), first);
1326 }
1327
1328 #[test]
1333 fn samples_share_the_nominal_table_and_fly_as_alone() {
1334 let mut inputs = nominal();
1335 let mounted = &mut inputs.rocket.configurations[0].motors[0];
1336 mounted.motor = dispersed_motor(&mounted.motor, 4.0, 0.25).unwrap();
1337 let monte_carlo = MonteCarlo::new(inputs, every_dispersion()).unwrap();
1338 let tables = &monte_carlo.shared.as_ref().unwrap().tables;
1339 assert!(!tables.supersonic_table_built());
1340 assert!(monte_carlo.sample(SEED, 0).summary().is_some());
1341 assert!(tables.supersonic_table_built());
1343 let table = tables.supersonic_body().unwrap();
1344 for index in 0..2 {
1345 let draw = monte_carlo.draw(SEED, index);
1346 let alone = monte_carlo.inputs(&draw).unwrap();
1347 assert!(alone.simulation().unwrap().share_supersonic_table(tables));
1348 let flight = alone.fly().unwrap();
1349 let max_mach = flight.max_mach.as_ref().unwrap().value;
1351 assert!(table.weight(max_mach) > 0.0, "Mach {max_mach}");
1352 assert_eq!(monte_carlo.sample(SEED, index).summary(), Some(&flight));
1353 assert_eq!(monte_carlo.fly(&draw).unwrap(), flight);
1354 }
1355 #[cfg(feature = "parallel")]
1358 {
1359 let run = monte_carlo.run(SEED, 3);
1360 for threads in [2, 5] {
1361 let fresh =
1362 MonteCarlo::new(monte_carlo.nominal().clone(), every_dispersion()).unwrap();
1363 let pool = rayon::ThreadPoolBuilder::new()
1364 .num_threads(threads)
1365 .build()
1366 .unwrap();
1367 assert_eq!(
1368 pool.install(|| fresh.run_parallel(SEED, 3)),
1369 run,
1370 "{threads}"
1371 );
1372 }
1373 }
1374 }
1375
1376 #[test]
1381 fn a_stage_with_its_parts_in_place_disperses_as_any_other() {
1382 let mut base = nominal();
1383 let stage = &mut base.rocket.stages[0];
1384 stage.override_rule = hpr_design::StageOverrideRule::PartsInPlace;
1385 stage.overrides.inertia = None;
1388 stage.overrides.cg_aft_m = Some(0.9);
1389 let run = MonteCarlo::new(base, every_dispersion()).unwrap();
1390 let draw = run.draw(SEED, 1);
1391 assert!((draw.dry_mass_scale[0] - 1.0).abs() > 1e-3, "{draw:?}");
1392 assert!(draw.cg_shift_m[0].abs() > 1e-4, "{draw:?}");
1393 let before = run.nominal().rocket.layout().unwrap().stages[0].mass;
1394 let after = run.inputs(&draw).unwrap().rocket.layout().unwrap().stages[0].mass;
1395 let mass = after.mass_kg / before.mass_kg;
1396 assert!((mass - draw.dry_mass_scale[0]).abs() < 1e-14, "{mass}");
1397 let shift = before.cg_m.z - after.cg_m.z;
1398 assert!((shift - draw.cg_shift_m[0]).abs() < 1e-14, "{shift}");
1399 for (a, b) in after
1400 .inertia_kg_m2
1401 .to_cols_array()
1402 .iter()
1403 .zip(before.inertia_kg_m2.to_cols_array())
1404 {
1405 assert!(
1406 (a - b * draw.dry_mass_scale[0]).abs() <= 1e-14 * b.abs(),
1407 "{a} {b}"
1408 );
1409 }
1410 }
1411
1412 #[test]
1413 fn each_dispersion_moves_its_input() {
1414 let run = MonteCarlo::new(nominal(), every_dispersion()).unwrap();
1415 let draw = run.draw(SEED, 1);
1416 let inputs = run.inputs(&draw).unwrap();
1417 let base = run.nominal();
1418 let layout = base.rocket.layout().unwrap();
1420 let flown = inputs.rocket.layout().unwrap();
1421 let (before, after) = (&layout.stages[0], &flown.stages[0]);
1422 let mass = after.mass.mass_kg / before.mass.mass_kg;
1423 assert!((mass - draw.dry_mass_scale[0]).abs() < 1e-14, "{mass}");
1424 let shift = before.mass.cg_m.z - after.mass.cg_m.z;
1425 assert!((shift - draw.cg_shift_m[0]).abs() < 1e-14, "{shift}");
1426 let inertia = after.mass.inertia_kg_m2.x_axis.x / before.mass.inertia_kg_m2.x_axis.x;
1427 assert!(
1428 (inertia - draw.dry_mass_scale[0]).abs() < 1e-14,
1429 "{inertia}"
1430 );
1431 assert_eq!(inputs.drag_scale, draw.drag_scale);
1433 assert_eq!(
1435 inputs.rocket.configurations[0].motors[0].delay,
1436 base.rocket.configurations[0].motors[0].delay
1437 );
1438 assert_eq!(
1439 inputs.recovery[0].lag_s,
1440 (1.0 + draw.deployment_lag_offset_s[0]).max(0.0)
1441 );
1442 let speed = |i: &FlightInputs| {
1444 i.environment
1445 .wind
1446 .wind(1500.0)
1447 .unwrap()
1448 .velocity_enu_m_s
1449 .length()
1450 };
1451 assert!((speed(&inputs) / speed(base) - draw.wind_speed_scale).abs() < 1e-14);
1452 assert_eq!(
1454 inputs.rail.elevation_rad,
1455 base.rail.elevation_rad + draw.rail_elevation_offset_rad
1456 );
1457 let flight = run.sample(SEED, 1);
1459 let apogee = |s: &FlightSummary| s.apogee.as_ref().unwrap().height_above_ground_m;
1460 let nominal_apogee = apogee(&base.fly().unwrap());
1461 assert_ne!(apogee(flight.summary().unwrap()), nominal_apogee);
1462 }
1463
1464 #[test]
1465 fn an_ejection_delay_moves_and_stops_at_zero() {
1466 let mut base = nominal();
1467 base.rocket.configurations[0].motors[0].delay = Some(Delay::Seconds(0.3));
1468 let run = MonteCarlo::new(
1469 base,
1470 Dispersion {
1471 ejection_delay_sd_s: 1.0,
1472 deployment_lag_sd_s: 1.0,
1473 ..Dispersion::default()
1474 },
1475 )
1476 .unwrap();
1477 let mut cut = [false; 2];
1478 let mut moved = [false; 2];
1479 for index in 0..40 {
1480 let draw = run.draw(SEED, index);
1481 let inputs = run.inputs(&draw).unwrap();
1482 let delay = draw.ejection_delay_offset_s[0] + 0.3;
1483 let Some(Delay::Seconds(flown)) = inputs.rocket.configurations[0].motors[0].delay
1484 else {
1485 unreachable!("a delay in seconds stays one")
1486 };
1487 assert_eq!(flown, delay.max(0.0));
1488 let lag = draw.deployment_lag_offset_s[0] + 1.0;
1489 assert_eq!(inputs.recovery[0].lag_s, lag.max(0.0));
1490 for (i, value) in [delay, lag].into_iter().enumerate() {
1491 cut[i] |= value < 0.0;
1492 moved[i] |= value > 0.0;
1493 }
1494 }
1495 assert_eq!((cut, moved), ([true; 2], [true; 2]));
1496 }
1497
1498 #[test]
1499 fn a_rail_past_vertical_leans_the_other_way() {
1500 let rail = Rail {
1501 azimuth_rad: 0.4,
1502 roll_rad: 0.1,
1503 ..Rail::vertical(2.0)
1504 };
1505 let leaned = tilted(rail, 0.03, 0.0);
1506 assert!((leaned.elevation_rad - (FRAC_PI_2 - 0.03)).abs() < 1e-15);
1507 let past = LaunchAngles {
1509 azimuth_rad: 0.4,
1510 elevation_rad: FRAC_PI_2 + 0.03,
1511 roll_rad: 0.1,
1512 };
1513 let flown = LaunchAngles {
1514 azimuth_rad: leaned.azimuth_rad,
1515 elevation_rad: leaned.elevation_rad,
1516 roll_rad: leaned.roll_rad,
1517 };
1518 let (a, b) = (past.to_quaternion(), flown.to_quaternion());
1519 assert!(a.dot(b).abs() > 1.0 - 1e-15, "{a:?} {b:?}");
1520 assert!(leaned.validate().is_ok());
1521 let below = tilted(rail, -0.03, 0.2);
1523 assert_eq!(below.roll_rad, 0.1);
1524 assert_eq!(below.azimuth_rad, 0.4 + 0.2);
1525 }
1526
1527 #[test]
1528 fn a_dispersed_wind_turns_clockwise() {
1529 let north = Arc::new(ConstantWind::new(4.0, 0.0).unwrap());
1531 let turned = DispersedWind::new(north, 1.5, FRAC_PI_2).unwrap();
1532 let v = turned.wind(100.0).unwrap().velocity_enu_m_s;
1533 assert!((v - DVec3::new(-6.0, 0.0, 0.0)).length() < 1e-14, "{v:?}");
1534 for (scale, turn) in [(-0.1, 0.0), (f64::NAN, 0.0), (1.0, f64::INFINITY)] {
1535 assert!(matches!(
1536 DispersedWind::new(Arc::new(ConstantWind::calm()), scale, turn),
1537 Err(AnalysisError::Domain { .. })
1538 ));
1539 }
1540 }
1541
1542 #[test]
1547 fn a_dispersed_wind_reports_its_tables_turns_as_it_flies_them() {
1548 use hpr_atmos::{LayeredWind, WindInterpolation};
1549 let level = |height_msl_m, speed_m_s, direction_from_rad| WindLevel {
1550 height_msl_m,
1551 speed_m_s,
1552 direction_from_rad,
1553 };
1554 let table = LayeredWind::new(
1555 vec![level(1400.0, 0.1, 0.0), level(1700.0, 10.0, 1.5 * PI)],
1556 WindInterpolation::SpeedDirection,
1557 )
1558 .unwrap();
1559 let turned = DispersedWind::new(Arc::new(table), 1.5, FRAC_PI_2).unwrap();
1560 let [turn] = turned.direction_turns()[..] else {
1561 panic!("{:?}", turned.direction_turns())
1562 };
1563 assert_eq!(turn.lower.height_msl_m, 1400.0);
1564 assert_eq!(turn.upper.height_msl_m, 1700.0);
1565 assert_eq!(turn.lower.speed_m_s, 0.1);
1566 assert_eq!(turn.upper.speed_m_s, 10.0);
1567 assert_eq!(turn.lower.direction_from_rad, FRAC_PI_2);
1568 assert_eq!(turn.upper.direction_from_rad, 0.0);
1569 let v = turned.wind(1400.0).unwrap().velocity_enu_m_s;
1572 assert!((v - DVec3::new(-0.15, 0.0, 0.0)).length() < 1e-15, "{v:?}");
1573 let calm = DispersedWind::new(Arc::new(ConstantWind::calm()), 1.5, 0.3).unwrap();
1574 assert!(calm.direction_turns().is_empty());
1575 let light = LayeredWind::new(
1578 vec![level(1400.0, 1.2, 0.0), level(1700.0, 10.0, 1.5 * PI)],
1579 WindInterpolation::SpeedDirection,
1580 )
1581 .unwrap();
1582 let scaled = DispersedWind::new(Arc::new(light), 1.5, 0.0).unwrap();
1583 let flown = scaled.wind(1400.0).unwrap().velocity_enu_m_s.length();
1584 assert!((flown - 1.8).abs() < 1e-12, "{flown}");
1585 let turns = scaled.direction_turns();
1586 assert_eq!(turns[0].lower.speed_m_s, 1.2);
1587 let warnings = hpr_sim::issues::wind_issue_warnings(
1588 &turns,
1589 [1400.0, 2000.0],
1590 Some(hpr_sim::metrics::Peak {
1591 value: 0.5,
1592 time_s: 3.0,
1593 height_above_ground_m: 400.0,
1594 }),
1595 );
1596 assert_eq!(
1597 warnings
1598 .iter()
1599 .map(hpr_sim::IssueWarning::number)
1600 .collect::<Vec<_>>(),
1601 [8]
1602 );
1603 assert!(warnings[0].message().contains("from 1.2 m/s (3 mph) at 0°"));
1604 }
1605
1606 #[test]
1609 fn the_drag_scale_is_flown() {
1610 let mut scaled = nominal();
1611 scaled.drag_scale = 1.1;
1612 let by_hand = {
1613 let simulation = nominal()
1614 .simulation()
1615 .unwrap()
1616 .with_drag_scale(1.1)
1617 .unwrap();
1618 let mut metrics = FlightMetrics::new();
1619 let result = simulation.run(&mut metrics).unwrap();
1620 metrics.summary(&result, &scaled.environment).unwrap()
1621 };
1622 assert_eq!(scaled.fly().unwrap(), by_hand);
1623 assert_ne!(nominal().fly().unwrap(), by_hand);
1624 let run = MonteCarlo::new(
1625 scaled,
1626 Dispersion {
1627 drag_sd_fraction: 0.05,
1628 ..Dispersion::default()
1629 },
1630 )
1631 .unwrap();
1632 let draw = run.draw(SEED, 0);
1633 assert_eq!(run.inputs(&draw).unwrap().drag_scale, 1.1 * draw.drag_scale);
1634 }
1635
1636 #[test]
1639 fn a_draw_is_checked_and_flown_as_written() {
1640 let run = MonteCarlo::new(nominal(), Dispersion::default()).unwrap();
1641 let good = run.draw(SEED, 0);
1642 type Field = fn(&mut Draw) -> &mut Vec<f64>;
1644 let fields: [Field; 6] = [
1645 |d| &mut d.dry_mass_scale,
1646 |d| &mut d.cg_shift_m,
1647 |d| &mut d.impulse_scale,
1648 |d| &mut d.burn_time_scale,
1649 |d| &mut d.ejection_delay_offset_s,
1650 |d| &mut d.deployment_lag_offset_s,
1651 ];
1652 for field in fields {
1653 for length in [0, 2] {
1654 let mut draw = good.clone();
1655 field(&mut draw).resize(length, 0.0);
1656 assert!(
1657 matches!(
1658 run.inputs(&draw),
1659 Err(AnalysisError::Length { length: l, expected: 1, .. }) if l == length
1660 ),
1661 "{draw:?}"
1662 );
1663 }
1664 }
1665 let mut draw = good.clone();
1667 draw.rail_elevation_offset_rad = f64::NAN;
1668 assert!(matches!(
1669 run.inputs(&draw),
1670 Err(AnalysisError::Domain { what: "entry of a draw", value }) if value.is_nan()
1671 ));
1672 let mut draw = good;
1675 draw.drag_scale = 1.2;
1676 draw.wind_speed_scale = -0.3;
1677 let inputs = run.inputs(&draw).unwrap();
1678 assert_eq!(inputs.drag_scale, 1.2);
1679 let wind = inputs
1680 .environment
1681 .wind
1682 .wind(1500.0)
1683 .unwrap()
1684 .velocity_enu_m_s;
1685 assert_eq!(wind.length(), 0.0);
1686 }
1687
1688 #[test]
1691 fn a_seed_s_draws_are_pinned() {
1692 assert_eq!(SeededRng::for_stream(42, &[7]).next_u64(), GOLDEN_STREAM);
1693 let draw = MonteCarlo::new(nominal(), every_dispersion())
1694 .unwrap()
1695 .draw(SEED, 0);
1696 for (drawn, golden) in [
1697 (draw.drag_scale, GOLDEN_DRAG),
1698 (draw.impulse_scale[0], GOLDEN_IMPULSE),
1699 ] {
1700 assert!((drawn - golden).abs() < 1e-14, "{drawn:?}");
1701 }
1702 }
1703
1704 #[test]
1705 fn bad_setups_are_refused() {
1706 let error = MonteCarlo::new(
1707 nominal(),
1708 Dispersion {
1709 cg_sd_m: -0.1,
1710 ..Dispersion::default()
1711 },
1712 )
1713 .unwrap_err();
1714 assert!(matches!(
1715 error,
1716 AnalysisError::Domain { what: "center-of-mass standard deviation (m)", value }
1717 if value == -0.1
1718 ));
1719 let mut elsewhere = nominal();
1720 elsewhere.configuration_id = "missing".to_owned();
1721 assert!(matches!(
1722 MonteCarlo::new(elsewhere, Dispersion::default()),
1723 Err(AnalysisError::NoConfiguration(id)) if id == "missing"
1724 ));
1725 }
1726}