Skip to main content

hpr_analysis/
montecarlo.rs

1//! Monte Carlo dispersion: one rocket flown many times, each time with its uncertain inputs drawn
2//! afresh, to see how far its apogee and landing spread.
3//!
4//! **Guide:** [Monte Carlo dispersion][guide] explains what each dispersion does, with a worked
5//! run, and how far to trust the spread it gives.
6//!
7//! [guide]: https://hpr.fusionspace.co/monte-carlo.html
8//!
9//! A [`MonteCarlo`] holds the nominal flight ([`FlightInputs`]) and a [`Dispersion`]: a standard
10//! deviation for each uncertain input. Each sample draws every dispersed input from a normal
11//! distribution about its nominal value, as RocketPy's stochastic classes do by default
12//! (RocketPy 1.13.0's `rocketpy/stochastic/stochastic_model.py:190-199`, a `(nominal, standard deviation)` pair is a normal
13//! distribution), flies the flight, and keeps what it drew and what the flight came to
14//! ([`Sample`]). A [`Run`] is the samples in order; [`Run::apogee`] is the spread of their
15//! apogees, with the samples that failed counted, not dropped, and [`Run::landing`] where they
16//! landed, whose ellipses are in [`crate::ellipse`].
17//!
18//! # Reproducibility
19//!
20//! Every number a sample draws comes from its own stream, keyed by the run's seed, the sample's
21//! index, the input and, for an input with several copies, which copy
22//! ([`SeededRng::for_stream`]). So sample `k` is the same flight whatever the number of samples,
23//! however they are spread over threads (`MonteCarlo::run_parallel`, with the `parallel`
24//! feature), and whichever other inputs are dispersed: turning on a drag dispersion doesn't
25//! change the wind a sample flies. On one platform a run is bit for bit the same every time.
26//!
27//! # What each dispersion does
28//!
29//! Each is a standard deviation, zero (the default) for an input left at its nominal value. A
30//! dispersion of zero draws nothing and changes nothing, so a run with no dispersion flies the
31//! nominal flight in every sample, bit for bit.
32//!
33//! | Field | Each sample flies |
34//! |---|---|
35//! | `dry_mass_sd_fraction` | each stage's mass without motors times `1 + σ z`, its inertia scaled with it ([`hpr_design::Overrides`]) |
36//! | `cg_sd_m` | each stage's center of mass moved `σ z` aft (forward when negative), its inertia about the center kept |
37//! | `drag_sd_fraction` | the rocket's zero-lift drag coefficient times `1 + σ z` ([`Simulation::with_drag_scale`]) |
38//! | `impulse_sd_fraction` | each motor's thrust and propellant mass both times `1 + σ z`, so its specific impulse is kept ([`dispersed_motor`]) |
39//! | `burn_time_sd_fraction` | each motor's thrust curve stretched in time by `1 + σ z`, its thrust divided by the same, so its impulse is kept |
40//! | `ejection_delay_sd_s` | each motor's ejection delay plus `σ z` seconds, not below zero |
41//! | `wind_speed_sd_fraction` | the wind at every height times `1 + σ z`, calm below zero ([`DispersedWind`]) |
42//! | `wind_heading_sd_rad` | the wind at every height turned `σ z` clockwise, about the nominal (forecast) direction |
43//! | `rail_elevation_sd_rad` | the rail's angle above the horizon plus `σ z`; past vertical it leans the other way |
44//! | `rail_azimuth_sd_rad` | the rail's heading plus `σ z`, about the nominal heading |
45//! | `deployment_lag_sd_s` | each recovery device's lag after its trigger plus `σ z` seconds, not below zero; a tumble ([`DeviceDrag::Tumble`]), which starts at the split, keeps its own |
46//!
47//! `z` is a standard normal deviate drawn for that sample, input and copy: a stage, a motor in the
48//! flown configuration (a cluster's motors share one), or a recovery device. A draw that leaves
49//! an input impossible (a negative mass, a rail below the horizon) fails that sample, which is
50//! counted in the run ([`Outcome::Failed`]). The two delays and the wind's speed are cut at zero
51//! instead, since a charge can't fire before its event and a wind can't blow at less than calm: a
52//! normal tail past zero becomes zero.
53//!
54//! # Speed
55//!
56//! Every sample flies a simulation of its own, built from its draw. None of the dispersed inputs
57//! changes the rocket's shape, so the samples share two things with the nominal design, and a run
58//! flies the same either way, bit for bit:
59//!
60//! - its parts as laid out ([`hpr_design::LaidOut::relay`]): a sample lays out only its stages
61//!   again, with their dispersed masses;
62//! - its supersonic table ([`hpr_aero::AeroModel::share_supersonic_table`]): a design that flies
63//!   past Mach 1.2 builds it once for the run, not once a flight.
64//!
65//! [`MonteCarlo::fly`] shares them too, for draws made by hand; [`FlightInputs::fly`] builds its
66//! own every time. A sustainer lit at a powered separation builds its own table in every flight.
67//!
68//! # Left out
69//!
70//! Dispersions are independent normals: no correlations between inputs, no other
71//! distributions. The rail's elevation is dispersed in the plane of its heading, so a vertical
72//! rail with only its elevation dispersed leans along one line, as RocketPy's does (an inclination
73//! and a heading, `rocketpy/stochastic/stochastic_flight.py:21-24`); a draw past vertical leans
74//! it the other way, so its [`Draw`] entry is not then the elevation flown. A cluster's motors are dispersed as one. Moving a stage's center of mass keeps
75//! its inertia about the center. The drag scale multiplies the zero-lift drag only, not the
76//! normal force or the moments. A thrust curve stretched in time keeps its shape. Nothing is
77//! dispersed in the atmosphere's temperature or pressure, a motor's ignition time, a recovery
78//! device's drag, a separation's trigger or delay, or anything of a flight's events that
79//! [`FlightInputs`] doesn't hold. A staged flight's separations fly in every sample as the nominal
80//! has them ([`FlightInputs::separations`]): a split timed in seconds stays at its time while the
81//! burn time moves, so a sample whose booster still burns then stops with the flight's error and
82//! counts as failed, unless the split may drop a burning motor ([`Separation::drops_burning`]).
83//! A part dropped on the way up with nothing left to burn, its device fired by the split but
84//! waiting out a drawn lag, would climb through the lag with no drag: the flight refuses it, and
85//! the sample counts as failed.
86
87use 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/// A drag override for the whole flight, in place of HPR Sim's drag buildup: another tool's table or
109/// a model of your own ([`Simulation::with_drag_table`], [`Simulation::with_shared_drag_model`]).
110#[derive(Debug, Clone)]
111#[non_exhaustive]
112pub enum DragOverride {
113    /// A `C_D0(M)` table.
114    Table(DragTable),
115    /// A drag model.
116    Model(Arc<dyn DragModel>),
117}
118
119/// Everything one flight is flown from: the inputs of [`Simulation::new`] and the options a
120/// Monte Carlo run disperses. `hpr::FlightBuilder::inputs` makes one from the facade's builder.
121#[derive(Debug, Clone)]
122pub struct FlightInputs {
123    /// The design.
124    pub rocket: Rocket,
125    /// The id of the configuration flown: which motors are in it.
126    pub configuration_id: String,
127    /// The atmosphere and the wind.
128    pub environment: Environment,
129    /// The launch rail.
130    pub rail: Rail,
131    /// The integrator's settings.
132    pub settings: FlightSettings,
133    /// The recovery devices, none for a ballistic flight ([`Simulation::with_recovery`]).
134    pub recovery: Vec<Device>,
135    /// A drag table or model in place of HPR Sim's drag buildup, if any.
136    pub drag: Option<DragOverride>,
137    /// The factor on the rocket's zero-lift drag ([`Simulation::with_drag_scale`]); 1 leaves it.
138    pub drag_scale: f64,
139    /// The stack's separations, in the order they fire, none for a flight that stays whole
140    /// ([`Simulation::with_separations`]).
141    pub separations: Vec<Separation>,
142}
143
144impl FlightInputs {
145    /// The inputs of a flight of `rocket`'s configuration `configuration_id`, with the default
146    /// integrator, no recovery, HPR Sim's own drag and no drag scale.
147    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    /// The simulation these inputs fly.
167    ///
168    /// # Errors
169    ///
170    /// As [`Simulation::new`], [`Simulation::with_drag_scale`] (a scale that is negative or not
171    /// finite), [`Simulation::with_recovery`] and [`Simulation::with_separations`].
172    pub fn simulation(&self) -> Result<Simulation, SimError> {
173        self.simulation_on(self.rocket.lay_out()?)
174    }
175
176    /// As [`FlightInputs::simulation`], on `laid_out`, which is this design laid out.
177    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    /// Flies the flight to the ground and gives its metrics.
208    ///
209    /// # Errors
210    ///
211    /// As [`FlightInputs::simulation`], [`Simulation::run`] and
212    /// [`FlightMetrics::summary`].
213    pub fn fly(&self) -> Result<FlightSummary, SimError> {
214        self.fly_on(self.simulation()?)
215    }
216
217    /// As [`FlightInputs::fly`], on what a run's flights share with its nominal one, when it has
218    /// it: the design laid out from the nominal's ([`LaidOut::relay`]) and the nominal's
219    /// supersonic table ([`Simulation::share_supersonic_table`]). The flight is the same, bit for
220    /// bit.
221    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    /// Flies `simulation`, built from these inputs, to the ground and gives its metrics.
231    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/// What a run's flights share with its nominal flight: the nominal design laid out, which each
239/// flight's layout starts from, and its aerodynamic model, whose supersonic table they fly on.
240#[derive(Debug, Clone)]
241struct Shared {
242    laid_out: LaidOut,
243    tables: AeroModel,
244}
245
246/// The standard deviation of each dispersed input; zero, the default, leaves an input at its
247/// nominal value. The module's docs say what each does to a flight.
248#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
249#[serde(default, deny_unknown_fields)]
250pub struct Dispersion {
251    /// Each stage's mass without motors, as a fraction of it (0.02 is 2%).
252    pub dry_mass_sd_fraction: f64,
253    /// Each stage's center of mass along the axis, m.
254    pub cg_sd_m: f64,
255    /// The rocket's zero-lift drag coefficient, as a fraction of it.
256    pub drag_sd_fraction: f64,
257    /// Each motor's total impulse, as a fraction of it, its propellant mass with it.
258    pub impulse_sd_fraction: f64,
259    /// Each motor's burn time, as a fraction of it, at the same impulse.
260    pub burn_time_sd_fraction: f64,
261    /// Each motor's ejection delay, s.
262    pub ejection_delay_sd_s: f64,
263    /// The wind's speed at every height, as a fraction of it.
264    pub wind_speed_sd_fraction: f64,
265    /// The wind's direction, rad, about the nominal one.
266    pub wind_heading_sd_rad: f64,
267    /// The rail's angle above the horizon, rad.
268    pub rail_elevation_sd_rad: f64,
269    /// The rail's heading, rad.
270    pub rail_azimuth_sd_rad: f64,
271    /// Each recovery device's lag after its trigger, s.
272    pub deployment_lag_sd_s: f64,
273}
274
275impl Dispersion {
276    /// The fields with their names, for checks.
277    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    /// Checks that every standard deviation is finite and not negative.
309    ///
310    /// # Errors
311    ///
312    /// [`AnalysisError::Domain`] naming the first that isn't.
313    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/// The dispersed inputs, each with its own stream ([`SeededRng::for_stream`]). The numbers are
324/// part of every seeded result: changing one changes the samples drawn.
325#[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/// What one sample drew: the factor or offset for each dispersed input, and its nominal value
341/// (1 or 0) for one left alone. The lists run over the design's stages, the flown
342/// configuration's motors and the recovery devices, in order. [`MonteCarlo::inputs`] turns a
343/// draw into the flight it flies.
344#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
345pub struct Draw {
346    /// Each stage's mass factor.
347    pub dry_mass_scale: Vec<f64>,
348    /// Each stage's center-of-mass shift, m aft.
349    pub cg_shift_m: Vec<f64>,
350    /// The drag factor.
351    pub drag_scale: f64,
352    /// Each motor's impulse factor.
353    pub impulse_scale: Vec<f64>,
354    /// Each motor's burn-time factor.
355    pub burn_time_scale: Vec<f64>,
356    /// Each motor's ejection-delay offset, s, before the cut at zero.
357    pub ejection_delay_offset_s: Vec<f64>,
358    /// The wind-speed factor, before the cut at zero.
359    pub wind_speed_scale: f64,
360    /// The wind's turn, rad clockwise.
361    pub wind_turn_rad: f64,
362    /// The rail's elevation offset, rad.
363    pub rail_elevation_offset_rad: f64,
364    /// The rail's heading offset, rad clockwise.
365    pub rail_azimuth_offset_rad: f64,
366    /// Each recovery device's lag offset, s, before the cut at zero.
367    pub deployment_lag_offset_s: Vec<f64>,
368}
369
370/// What a sample's flight came to.
371#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
372#[serde(tag = "outcome", rename_all = "snake_case")]
373pub enum Outcome {
374    /// It flew: to the ground, or to a split with nothing left to burn, each part then to the
375    /// ground.
376    Flown {
377        /// Its metrics.
378        summary: Box<FlightSummary>,
379    },
380    /// Its inputs were refused or the flight stopped with an error.
381    Failed {
382        /// Where: making its inputs from the draw, or flying them.
383        at: FailedAt,
384        /// The error.
385        reason: String,
386    },
387}
388
389/// Where a sample failed.
390#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
391#[serde(rename_all = "snake_case")]
392pub enum FailedAt {
393    /// Making its inputs: the draw left one impossible, such as a motor with no impulse
394    /// ([`MonteCarlo::inputs`]).
395    Inputs,
396    /// Flying them: the flight refused them, such as a negative mass or a rail below the
397    /// horizon, or stopped with an error ([`FlightInputs::fly`]).
398    Flight,
399}
400
401/// One sample of a run: its index, what it drew, and its outcome.
402#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
403pub struct Sample {
404    /// Its index in the run, from 0.
405    pub index: u64,
406    /// What it drew.
407    pub draw: Draw,
408    /// What its flight came to.
409    pub outcome: Outcome,
410}
411
412impl Sample {
413    /// The flight's metrics, `None` for a sample that failed.
414    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/// The samples of a run, in order.
423#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
424pub struct Run {
425    /// The seed.
426    pub seed: u64,
427    /// The samples, by index.
428    pub samples: Vec<Sample>,
429}
430
431impl Run {
432    /// The samples that failed.
433    pub fn failed(&self) -> impl Iterator<Item = &Sample> {
434        self.samples
435            .iter()
436            .filter(|sample| matches!(sample.outcome, Outcome::Failed { .. }))
437    }
438
439    /// The distribution of `value` over every sample: a failed sample, or one for which `value`
440    /// gives `None`, counts as tried with no value.
441    ///
442    /// # Errors
443    ///
444    /// [`AnalysisError::Domain`] for a value that isn't finite.
445    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    /// The distribution of the apogee's height above the ground, m.
458    ///
459    /// # Errors
460    ///
461    /// As [`Run::distribution`].
462    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    /// Where the flights landed, east and north of the pad (m): the part that keeps the nose,
472    /// the stack, after a powered separation the sustainer, or after a split with nothing left to
473    /// burn part 0 ([`FlightSummary::nose_landing`]). A failed sample, or one that never landed,
474    /// counts as tried with no point. Its ellipses are in [`crate::ellipse`].
475    ///
476    /// # Errors
477    ///
478    /// [`AnalysisError::Domain`] for a coordinate that isn't finite, or is more than
479    /// [`Scatter::MAX_COORDINATE_M`] from the pad.
480    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/// A stage's nominal mass without motors, its center and its inertia, as the layout places them.
492#[derive(Debug, Clone, Copy)]
493struct StageMass {
494    mass_kg: f64,
495    /// Aft of the stage's forward end, m: what [`hpr_design::Overrides::cg_aft_m`] sets.
496    cg_aft_m: f64,
497    /// About the center, kg·m².
498    inertia_kg_m2: DMat3,
499}
500
501/// A rocket's nominal flight and the dispersion of its inputs, ready to fly samples.
502#[derive(Debug, Clone)]
503pub struct MonteCarlo {
504    nominal: FlightInputs,
505    dispersion: Dispersion,
506    stages: Vec<StageMass>,
507    configuration: usize,
508    /// What the samples share with the nominal flight; `None` when the nominal design can't be
509    /// laid out or its aerodynamic model built, and then every sample fails on its own.
510    shared: Option<Shared>,
511}
512
513impl MonteCarlo {
514    /// A run of `nominal` dispersed by `dispersion`.
515    ///
516    /// # Errors
517    ///
518    /// - As [`Dispersion::validate`].
519    /// - [`AnalysisError::NoConfiguration`] if the design has no configuration of that id.
520    /// - [`AnalysisError::Design`] if the design can't be laid out.
521    /// - [`AnalysisError::Unsupported`] for a dispersed impulse or burn time on a motor whose
522    ///   propellant model [`dispersed_motor`] doesn't know.
523    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                // Stations run aft from the nose; body z runs forward ([`hpr_design::Overrides`]).
538                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    /// The nominal flight.
561    pub fn nominal(&self) -> &FlightInputs {
562        &self.nominal
563    }
564
565    /// The dispersion.
566    pub fn dispersion(&self) -> &Dispersion {
567        &self.dispersion
568    }
569
570    /// What sample `index` of a run seeded with `seed` draws.
571    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                // Cast: a copy's index is far below 2⁶⁴.
576                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        // A tumble isn't deployed, so it has no lag to disperse: its entry stays 0, and its
592        // stream is never drawn.
593        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    /// The flight inputs `draw` gives: the nominal ones, with each input whose entry isn't its
619    /// nominal value (a factor of 1, an offset of 0) changed as the module's docs say. An entry at
620    /// its nominal value leaves its input as it is, so a draw with no dispersion flies the
621    /// nominal flight bit for bit; any other entry is applied, whatever the dispersion, so a
622    /// draw read back or written by hand flies as it says.
623    ///
624    /// # Errors
625    ///
626    /// - [`AnalysisError::Count`] for a list whose length isn't the design's number of stages,
627    ///   the configuration's number of motors or the number of recovery devices.
628    /// - [`AnalysisError::Domain`] for an entry that isn't finite, and from
629    ///   [`dispersed_motor`] for an impulse or burn-time factor at or below zero.
630    /// - [`AnalysisError::Unsupported`] and [`AnalysisError::Motor`] as [`dispersed_motor`].
631    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                // An inertia the design sets replaces the scaled one, so it scales too.
644                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            // A stage whose overrides leave its parts in place (ADR-340) would keep its parts'
661            // inertia under a new mass and add to it with a new center. The dispersion scales the
662            // nominal inertia and keeps it about the center whatever the stage's rule, so it is
663            // stated.
664            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    /// Checks that `draw` has an entry for each stage, motor and recovery device, and that every
725    /// entry is finite.
726    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    /// Flies `draw` ([`MonteCarlo::inputs`]) to the ground and gives its metrics, on what the
797    /// run's flights share (the module's *Speed*): as [`FlightInputs::fly`] on the same inputs,
798    /// bit for bit, but without laying out the parts or building a supersonic table again. For
799    /// flights drawn by hand, as a sensitivity analysis's ([`crate::sensitivity`]).
800    ///
801    /// # Errors
802    ///
803    /// As [`MonteCarlo::inputs`], and [`AnalysisError::Sim`] around the errors of
804    /// [`FlightInputs::fly`].
805    pub fn fly(&self, draw: &Draw) -> Result<FlightSummary, AnalysisError> {
806        Ok(self.inputs(draw)?.fly_sharing(self.shared.as_ref())?)
807    }
808
809    /// Draws and flies sample `index` of a run seeded with `seed`. A draw that makes an input
810    /// impossible, or a flight that stops with an error, is a failed sample, not an error.
811    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    /// Flies samples `0..count` of a run seeded with `seed`, one after another.
836    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    /// As [`MonteCarlo::run`], with the samples spread over the threads of the current rayon
844    /// pool: the global one, or one a caller's `rayon::ThreadPool::install` sets up to choose
845    /// how many. The run is the same, bit for bit, whatever the number of threads.
846    #[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
859/// `motor` with its total impulse times `impulse_scale` and its burn time times
860/// `burn_time_scale`: thrust `F′(t) = (k/s) F(t/s)` and propellant mass `k m_p`, with `k` and `s`
861/// the two factors. The impulse is `k I` and the effective exhaust velocity `I/m_p` (the specific
862/// impulse) is kept, as a motor of the same propellant burning more or less of it would; the dry
863/// mass, the nozzle and the propellant's shape are kept. A column's mass is scaled; BATES grains'
864/// density, so their geometry and regression are kept.
865///
866/// # Errors
867///
868/// - [`AnalysisError::Domain`] for a factor that isn't finite and positive.
869/// - [`AnalysisError::Unsupported`] for a propellant model this doesn't know.
870/// - As [`SolidMotor::new`].
871pub 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
917/// `rail` with its elevation and heading moved by the offsets. An elevation past vertical leans
918/// the other way: `E′ = π − E`, the heading and roll turned half a turn, the same attitude
919/// (`R_z(−A) R_x(E − π/2) R_z(φ)`, `hpr_core::frames::LaunchAngles`).
920fn 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/// A wind model's wind, scaled and turned: at every height the velocity is `speed_scale` times
933/// the base model's, its horizontal part turned `turn_rad` clockwise seen from above. Turning
934/// the velocity turns the direction the wind blows from by the same angle, so a dispersed heading
935/// stays about the forecast's.
936#[derive(Debug, Clone)]
937pub struct DispersedWind {
938    base: Arc<dyn Wind>,
939    speed_scale: f64,
940    turn_rad: f64,
941    /// `turn_rad.sin_cos()`, taken once rather than at every call of `wind`.
942    turn_sin_cos: (f64, f64),
943}
944
945impl DispersedWind {
946    /// `base` scaled by `speed_scale` and turned `turn_rad` clockwise.
947    ///
948    /// # Errors
949    ///
950    /// [`AnalysisError::Domain`] for a scale that is negative or not finite, or a turn that isn't
951    /// finite.
952    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        // A bearing θ clockwise from north is (sin θ, cos θ) in east and north; turning it to
984        // θ + δ gives these.
985        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    /// The base model's turns, turned as its wind is: each level's direction turned clockwise by
991    /// the turn, so a flight warns of the directions it flies ([`Wind::direction_turns`]). Each
992    /// level's speed is the base table's, not scaled: whether a level is near calm, so that its
993    /// reported direction means little, is a matter of what was measured there, and a dispersed
994    /// speed doesn't make the measured direction any better. The warning quotes the speed the
995    /// table reports.
996    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    /// `SeededRng::for_stream(42, &[7]).next_u64()`.
1024    const GOLDEN_STREAM: u64 = 2_627_254_379_500_910_771;
1025    /// Sample 0's drag and impulse factors with `every_dispersion()` and `SEED`, as macOS
1026    /// computes them: a normal deviate takes a logarithm, which another platform's library may
1027    /// round differently in the last bit, so these are held to 1e-14.
1028    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    /// Valetudo in a 5 m/s wind from the west, off a 5.2 m rail at 85° heading north, with a
1039    /// drogue at apogee.
1040    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    /// Loft lesson L52: Loft scaled the thrust but not the propellant mass, so its dispersed
1076    /// motors burned with a different specific impulse. Here both scale, and the effective
1077    /// exhaust velocity `I/m_p` is the nominal motor's.
1078    #[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        // And in a run: every sample's motor keeps it.
1098        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            // Each factor where it belongs: swapped, `I/m_p` would still hold.
1107            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        // A motor known only by its envelope holds its propellant as a column; its mass scales.
1114        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        // A factor at or below zero is refused.
1123        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    /// Loft lesson L53: Loft drew every sample from one stream, so adding a draw reshuffled every
1142    /// later sample and parallel runs weren't reproducible. Here sample `k` is the same whatever
1143    /// the run's length or thread count, and turning another dispersion on leaves its draws.
1144    #[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        // Another seed, other samples.
1153        assert_ne!(run.draw(SEED + 1, 0), run.draw(SEED, 0));
1154        // Each input has its own stream: with the drag dispersion off, the rest draw the same.
1155        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        // The run's first samples are a shorter run's, but one shared stream would give that
1173        // too: what a shared stream can't give is sample 4 flown on its own, above, or the same
1174        // draws with the drag dispersion off.
1175        #[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    /// Loft lesson L54: Loft dropped impossible samples silently and computed its probabilities
1190    /// over the survivors. Here a sample whose draw the flight refuses is kept as failed, with
1191    /// its reason, and the apogee's distribution counts it as tried with no value.
1192    #[test]
1193    fn failed_samples_are_counted_and_reported() {
1194        // A 60% mass spread draws a negative mass now and then.
1195        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        // A share over every sample tried, bounded by the failures both ways.
1219        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        // The landings likewise: every flown sample's point, in order, the failures missing.
1223        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        // A draw that leaves a motor with no impulse fails before it flies.
1237        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    /// Loft lesson L55: Loft drew wind and rail bearings uniformly at random, throwing the
1262    /// forecast heading away. Here the wind turns about the nominal direction, and the rail about
1263    /// its nominal heading, by normal deviates of the standard deviation asked for.
1264    #[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            // The direction it blows from, clockwise from north, about the nominal west (270°).
1288            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            // Within four standard errors of 0 and of the deviation asked for.
1297            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    /// Loft lesson L96: the same seed gives the same samples, and no dispersion gives the
1306    /// nominal flight in every sample, so a spread of exactly zero.
1307    #[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        // The same seed, the same run, to the bit; it serializes and reads back whole.
1321        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    /// Valetudo's motor at four times its impulse in a quarter of its time takes it past Mach
1329    /// 1.2, where its flights need the supersonic table: the samples build the nominal's and
1330    /// share it, and each flies as the same inputs flown alone, on a table of their own, bit for
1331    /// bit.
1332    #[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        // The sample built the nominal's table.
1342        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            // The table carries the flow at the flight's peak, so it shapes the flight.
1350            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        // A fresh run on two and five threads, whose flights build the shared table on whichever
1356        // thread first needs it, is the run flown on one.
1357        #[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    /// A stage whose overrides leave its parts in place (ADR-340) disperses as any other: its
1377    /// mass and inertia scale together and a moved center keeps the inertia about it. Without the
1378    /// stated inertia, the parts' inertia would stay as it was under the new mass, and gain the
1379    /// parallel-axis term of the move.
1380    #[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        // Valetudo's design states its stage's inertia, which the dispersion scales under
1386        // either rule: without it, the stage's parts carry the inertia.
1387        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        // Mass and center: the stage's override, from the layout's nominal values.
1419        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        // Drag.
1432        assert_eq!(inputs.drag_scale, draw.drag_scale);
1433        // Delays: the motor's (Valetudo's has none) and the drogue's lag.
1434        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        // Wind: scaled.
1443        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        // Rail.
1453        assert_eq!(
1454            inputs.rail.elevation_rad,
1455            base.rail.elevation_rad + draw.rail_elevation_offset_rad
1456        );
1457        // The flight flies, and its apogee isn't the nominal one.
1458        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        // The same attitude as the angles taken past vertical.
1508        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        // Below vertical, nothing turns.
1522        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        // From the north at 4 m/s, turned a quarter turn clockwise: from the east, blowing west.
1530        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    /// A dispersed wind reports its base table's direction turns as it flies them (issue #8):
1543    /// each level's direction turned clockwise, its speed and height the table's; a base with
1544    /// none gives none. A level the table reports near calm stays near calm when the scale lifts
1545    /// its flown speed past the limit, so it still warns.
1546    #[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        // It flies the direction it reports, at the scaled speed: at the lower level, 0.15 m/s
1570        // from the east.
1571        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        // A 1.2 m/s level, near calm, flown at 1.8 m/s by a scale of 1.5: still reported at
1576        // 1.2 m/s, so the flight's warning still counts it.
1577        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    /// The drag scale reaches the flight: `FlightInputs` flies it as
1607    /// `Simulation::with_drag_scale` does, and a sample's factor multiplies a nominal scale.
1608    #[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    /// A draw is checked against the rocket before it flies, and every entry that isn't at its
1637    /// nominal value is flown, whatever the dispersion: a draw written by hand flies as it says.
1638    #[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        // Every list is checked against the rocket: one stage, one motor, one recovery device.
1643        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        // An entry that isn't a number is refused before it reaches a model that might not.
1666        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        // No dispersion asked for, but the draw says 20% more drag and a calm wind (a factor
1673        // below zero is cut to calm).
1674        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    /// The numbers a seed gives are part of every seeded result: these pin the stream key's fold
1689    /// and the order of a draw's inputs, so a change to either shows here first.
1690    #[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}