Skip to main content

hpr_forensics/synthetic/
truth.rs

1//! A synthetic flight's truth: HPR Sim's flight of the drawn rocket to the ground, sampled every
2//! [`TRUTH_STEP_S`], with its events.
3
4use std::collections::BTreeMap;
5use std::f64::consts::FRAC_PI_2;
6use std::sync::Arc;
7
8use hpr_aero::{AeroError, DragModel, DragQuery};
9use hpr_analysis::montecarlo::{DragOverride, FlightInputs, dispersed_motor};
10use hpr_atmos::{AtmosphereModel, ConstantWind, PowerLawWind, Ussa76};
11use hpr_core::DVec3;
12use hpr_core::earth::Earth;
13use hpr_core::geodesy::Geodetic;
14use hpr_design::{Ignition, Rocket};
15use hpr_motor::{SolidMotor, ThrustCurve};
16use hpr_sim::recorder::{BodyStep, FlightStep, Observer, Sample};
17use hpr_sim::recovery::{Device, DeviceDrag, Separation, Trigger};
18use hpr_sim::{
19    BodyFlight, BodySample, Environment, EventKind, FlightEvent, Phase, Rail, SimError, Simulation,
20};
21use serde::{Deserialize, Serialize};
22
23use super::designs::{DESIGNS, Design, DesignFiles, Opens};
24use super::{Draw, Model, SyntheticError};
25
26/// The truth's sample interval, s: a row every 0.01 s from launch, and one at each event.
27pub const TRUTH_STEP_S: f64 = 0.01;
28/// The rail's length, m: RocketPy's Calisto example's 5.2 m, for every design.
29pub const RAIL_LENGTH_M: f64 = 5.2;
30/// The site's latitude, degrees north: fixed, as nothing here depends on where the field is but
31/// its elevation, which is drawn.
32pub const SITE_LATITUDE_DEG: f64 = 35.0;
33/// The site's longitude, degrees east.
34pub const SITE_LONGITUDE_DEG: f64 = -106.0;
35/// The height at which set B's power-law wind takes the drawn speed, m: NASA/TM-2008-215633's
36/// reference height, as `hpr_atmos::PowerLawWind` cites it.
37pub const SHEAR_REFERENCE_HEIGHT_M: f64 = 18.3;
38/// The sea-level pressure of the drawn air, Pa: the standard's.
39const SEA_LEVEL_PRESSURE_PA: f64 = 101_325.0;
40
41/// The truth at one instant.
42#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
43pub struct TruthSample {
44    /// Time since launch, s.
45    pub time_s: f64,
46    /// The center of mass's height above the ground (the site's ellipsoidal height), m.
47    pub height_m: f64,
48    /// Its rate, m/s, up positive.
49    pub vertical_speed_m_s: f64,
50    /// The specific force along the rocket's axis, nose positive, m/s²: what an accelerometer
51    /// along the axis reads, gravity's reaction included (+9.8 m/s² standing on the pad), at the
52    /// nose tip, where the simulator records the acceleration. Under a canopy the rocket is taken
53    /// to hang along the vertical.
54    pub axial_specific_force_m_s2: f64,
55    /// The Mach number.
56    pub mach: f64,
57    /// The dynamic pressure, Pa.
58    pub dynamic_pressure_pa: f64,
59    /// The center of mass in the launch frame (east, north, up), m.
60    pub position_enu_m: [f64; 3],
61    /// Its velocity in the launch frame, m/s.
62    pub velocity_enu_m_s: [f64; 3],
63}
64
65/// The events of a flight, s since launch.
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct TruthEvents {
68    /// The rocket started to move along the rail.
69    pub liftoff_s: f64,
70    /// The last rail guide left the rail.
71    pub rail_exit_s: f64,
72    /// The motor burned out.
73    pub burnout_s: f64,
74    /// The center of mass's highest point.
75    pub apogee_s: f64,
76    /// Its height there above the ground, m.
77    pub apogee_m: f64,
78    /// Each parachute's charge, by the parachute's name, in the order they fired.
79    pub charges: Vec<(String, f64)>,
80    /// Each parachute's opening, by name, in the order they opened.
81    pub deployments: Vec<(String, f64)>,
82    /// The center of mass reached the ground.
83    pub landing_s: f64,
84}
85
86/// A flight's truth.
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub struct Truth {
89    /// The samples, every [`TRUTH_STEP_S`] from launch and at each event, in time order.
90    pub samples: Vec<TruthSample>,
91    /// The events.
92    pub events: TruthEvents,
93    /// The center of mass's height above the ground at launch, m: where a logger in the rocket
94    /// sat when it set its zero. A reading's truth is a height above it.
95    pub pad_height_m: f64,
96    /// The site's elevation above mean sea level, m.
97    pub site_elevation_m: f64,
98    /// The air's temperature offset from the 1976 standard, K.
99    pub temperature_offset_k: f64,
100}
101
102impl Truth {
103    /// The truth at `t` s since launch, read linearly between samples; before launch the rocket
104    /// stands on the pad, and after landing it lies still on its side. `None` for a truth with no
105    /// samples, or a `t` that isn't a number.
106    pub fn at(&self, t: f64) -> Option<TruthSample> {
107        let (first, last) = (*self.samples.first()?, *self.samples.last()?);
108        if t.is_nan() {
109            return None;
110        }
111        if t <= first.time_s {
112            return Some(TruthSample { time_s: t, ..first });
113        }
114        if t > last.time_s {
115            return Some(TruthSample {
116                time_s: t,
117                height_m: last.height_m.max(0.0),
118                vertical_speed_m_s: 0.0,
119                axial_specific_force_m_s2: 0.0,
120                mach: 0.0,
121                dynamic_pressure_pa: 0.0,
122                velocity_enu_m_s: [0.0; 3],
123                ..last
124            });
125        }
126        // `t` lies in (first, last], so the sample at or before it has one after it.
127        let i = (self.samples.partition_point(|s| s.time_s <= t) - 1).min(self.samples.len() - 2);
128        let (a, b) = (self.samples[i], self.samples[i + 1]);
129        let f = (t - a.time_s) / (b.time_s - a.time_s);
130        let mix = |x: f64, y: f64| x + f * (y - x);
131        let mix3 = |x: [f64; 3], y: [f64; 3]| [mix(x[0], y[0]), mix(x[1], y[1]), mix(x[2], y[2])];
132        Some(TruthSample {
133            time_s: t,
134            height_m: mix(a.height_m, b.height_m),
135            vertical_speed_m_s: mix(a.vertical_speed_m_s, b.vertical_speed_m_s),
136            axial_specific_force_m_s2: mix(
137                a.axial_specific_force_m_s2,
138                b.axial_specific_force_m_s2,
139            ),
140            mach: mix(a.mach, b.mach),
141            dynamic_pressure_pa: mix(a.dynamic_pressure_pa, b.dynamic_pressure_pa),
142            position_enu_m: mix3(a.position_enu_m, b.position_enu_m),
143            velocity_enu_m_s: mix3(a.velocity_enu_m_s, b.velocity_enu_m_s),
144        })
145    }
146
147    /// The true static pressure at the center of mass `t` s since launch, Pa.
148    ///
149    /// # Errors
150    ///
151    /// As [`Ussa76::sample`], for a height it can't take; [`SyntheticError::Invalid`] where
152    /// [`Truth::at`] has no truth.
153    pub fn pressure_pa(&self, t: f64) -> Result<f64, SyntheticError> {
154        let air = self.air()?;
155        let state = self.at(t).ok_or(SyntheticError::Invalid {
156            what: "a truth with no sample at that time",
157        })?;
158        Ok(air
159            .sample(self.site_elevation_m + state.height_m)?
160            .air
161            .pressure_pa)
162    }
163
164    /// The flight's air.
165    ///
166    /// # Errors
167    ///
168    /// As [`Ussa76::with_offset`].
169    pub fn air(&self) -> Result<Ussa76, SyntheticError> {
170        Ok(Ussa76::with_offset(
171            self.temperature_offset_k,
172            SEA_LEVEL_PRESSURE_PA,
173        )?)
174    }
175
176    /// The apogee above where the logger sat on the pad, m.
177    pub fn apogee_above_pad_m(&self) -> f64 {
178        self.events.apogee_m - self.pad_height_m
179    }
180
181    /// The highest vertical speed, m/s, and when; NaN if any sample's speed is NaN, so that a
182    /// census refuses the flight rather than ranking around it.
183    pub fn top_speed(&self) -> (f64, f64) {
184        self.samples
185            .iter()
186            .map(|s| (s.vertical_speed_m_s, s.time_s))
187            .fold((f64::NEG_INFINITY, 0.0), |best, x| {
188                if x.0.is_nan() || best.0.is_nan() {
189                    (f64::NAN, x.1)
190                } else if x.0 > best.0 {
191                    x
192                } else {
193                    best
194                }
195            })
196    }
197
198    /// The highest Mach number; NaN if any sample's is.
199    pub fn top_mach(&self) -> f64 {
200        self.samples.iter().map(|s| s.mach).fold(0.0, |best, m| {
201            if m.is_nan() || best.is_nan() {
202                f64::NAN
203            } else {
204                best.max(m)
205            }
206        })
207    }
208}
209
210/// Set B's drag: HPR Sim's zero-lift drag times `scale · (1 + a·exp(−((M − 1)/0.2)²) + b·M)`, a
211/// transonic rise and a slope shaped differently from HPR Sim's.
212#[derive(Debug, Clone, Copy)]
213pub struct ReshapedDrag {
214    /// The constant factor.
215    pub scale: f64,
216    /// The transonic bump's height.
217    pub bump: f64,
218    /// The slope per unit Mach number.
219    pub slope: f64,
220}
221
222impl ReshapedDrag {
223    /// The factor on HPR Sim's zero-lift drag at Mach `mach`.
224    pub fn factor(&self, mach: f64) -> f64 {
225        let x = (mach - 1.0) / 0.2;
226        self.scale * (1.0 + self.bump * (-x * x).exp() + self.slope * mach)
227    }
228}
229
230impl DragModel for ReshapedDrag {
231    fn zero_lift_drag(&self, query: &DragQuery<'_>) -> Result<f64, AeroError> {
232        Ok(self.factor(query.mach()) * query.buildup()?.zero_lift_coefficient)
233    }
234}
235
236/// `curve` tilted by `1 + tilt·(2t/t_b − 1)` over its burn `t_b` and rescaled to its own
237/// impulse: progressive for a positive tilt, regressive for a negative one.
238///
239/// # Errors
240///
241/// As [`ThrustCurve::new`].
242pub fn tilted(curve: &ThrustCurve, tilt: f64) -> Result<ThrustCurve, SyntheticError> {
243    let times = curve.times_s();
244    let burn = times[times.len() - 1];
245    let thrusts: Vec<f64> = times
246        .iter()
247        .zip(curve.thrusts_n())
248        .map(|(&t, &f)| f * (1.0 + tilt * (2.0 * t / burn - 1.0)))
249        .collect();
250    let raw = ThrustCurve::new(times.to_vec(), thrusts)?;
251    let k = curve.total_impulse_ns() / raw.total_impulse_ns();
252    Ok(ThrustCurve::new(
253        times.to_vec(),
254        raw.thrusts_n().iter().map(|f| f * k).collect(),
255    )?)
256}
257
258/// The draw's design, if its index names one.
259fn design_of(draw: &Draw) -> Result<&'static Design, SyntheticError> {
260    DESIGNS.get(draw.design).ok_or(SyntheticError::Invalid {
261        what: "a draw whose design isn't one of the ten",
262    })
263}
264
265/// The drawn rocket, its motor scaled and, in set B, its thrust tilted.
266fn rocket(draw: &Draw, files: &DesignFiles) -> Result<Rocket, SyntheticError> {
267    let design = design_of(draw)?;
268    let json = files.json(draw.design).ok_or(SyntheticError::Invalid {
269        what: "no file for the draw's design",
270    })?;
271    let mut rocket: Rocket = serde_json::from_str(json)?;
272    let configuration = rocket
273        .configurations
274        .iter_mut()
275        .find(|c| c.id == design.configuration)
276        .ok_or(SyntheticError::Design {
277            design: design.name,
278            what: "has no such configuration",
279        })?;
280    for mounted in &mut configuration.motors {
281        let motor = dispersed_motor(&mounted.motor, draw.impulse_scale, draw.burn_time_scale)?;
282        mounted.motor = match draw.model {
283            Model::Same => motor,
284            Model::Other { thrust_tilt, .. } => SolidMotor::new(
285                tilted(motor.curve(), thrust_tilt)?,
286                motor.propellant().clone(),
287                motor.dry(),
288                motor.nozzle(),
289            )?,
290        };
291    }
292    Ok(rocket)
293}
294
295/// The design's parachutes as HPR Sim's devices, each released by the next.
296fn devices(draw: &Draw) -> Result<Vec<Device>, SyntheticError> {
297    let chutes = design_of(draw)?.chutes;
298    Ok(chutes
299        .iter()
300        .enumerate()
301        .map(|(index, chute)| {
302            let trigger = match chute.opens {
303                Opens::Apogee => Trigger::Apogee,
304                Opens::Below(height_above_ground_m) => Trigger::Altitude {
305                    height_above_ground_m,
306                },
307            };
308            let device = Device::new(
309                chute.name,
310                DeviceDrag::DragArea {
311                    cd_s_m2: chute.cd_s_m2,
312                },
313                trigger,
314            )
315            .with_lag_s(chute.lag_s);
316            if index + 1 < chutes.len() {
317                device.with_release_by(index + 1)
318            } else {
319                device
320            }
321        })
322        .collect())
323}
324
325/// The inputs a draw flies from, its design read from `files`.
326///
327/// # Errors
328///
329/// [`SyntheticError`] for a design that doesn't read, a motor the draw can't scale, or an
330/// environment out of its models' domains.
331pub fn inputs(draw: &Draw, files: &DesignFiles) -> Result<FlightInputs, SyntheticError> {
332    let mut inputs = FlightInputs::new(
333        rocket(draw, files)?,
334        design_of(draw)?.configuration,
335        environment(draw)?,
336        rail(draw),
337    );
338    inputs.recovery = devices(draw)?;
339    match draw.model {
340        Model::Same => inputs.drag_scale = draw.drag_scale,
341        Model::Other {
342            drag_bump,
343            drag_slope,
344            ..
345        } => {
346            inputs.drag = Some(DragOverride::Model(Arc::new(ReshapedDrag {
347                scale: draw.drag_scale,
348                bump: drag_bump,
349                slope: drag_slope,
350            })));
351        }
352    }
353    Ok(inputs)
354}
355
356/// The draw's site, air and wind.
357fn environment(draw: &Draw) -> Result<Environment, SyntheticError> {
358    let site = Geodetic::from_degrees(SITE_LATITUDE_DEG, SITE_LONGITUDE_DEG, draw.elevation_m)?;
359    let air = AtmosphereModel::Standard(Ussa76::with_offset(
360        draw.temperature_offset_k,
361        SEA_LEVEL_PRESSURE_PA,
362    )?);
363    let earth = Earth::wgs84(site)?;
364    Ok(match draw.model {
365        Model::Same => Environment::new(
366            earth,
367            air,
368            ConstantWind::new(draw.wind_speed_m_s, draw.wind_from_rad)?,
369        ),
370        Model::Other { shear_exponent, .. } => Environment::new(
371            earth,
372            air,
373            PowerLawWind::new(
374                draw.wind_speed_m_s,
375                SHEAR_REFERENCE_HEIGHT_M,
376                shear_exponent,
377                draw.wind_from_rad,
378                draw.elevation_m,
379            )?,
380        ),
381    })
382}
383
384/// The draw's rail.
385fn rail(draw: &Draw) -> Rail {
386    Rail {
387        elevation_rad: FRAC_PI_2 - draw.tilt_rad,
388        azimuth_rad: draw.azimuth_rad,
389        ..Rail::vertical(RAIL_LENGTH_M)
390    }
391}
392
393/// Keeps a flight's states every [`TRUTH_STEP_S`] and at each event.
394#[derive(Debug, Default)]
395pub(crate) struct Grid {
396    next: u64,
397    pub(crate) samples: Vec<Sample>,
398    /// Each separated body's truth, by body, every [`TRUTH_STEP_S`] from its start.
399    bodies: BTreeMap<usize, Vec<BodyPoint>>,
400}
401
402impl Observer for Grid {
403    fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
404        let first = (step.start_s() / TRUTH_STEP_S).ceil();
405        if (self.next as f64) < first {
406            self.next = first as u64;
407        }
408        loop {
409            let t = self.next as f64 * TRUTH_STEP_S;
410            if t > step.end_s() {
411                break;
412            }
413            self.samples.push(step.sample(t)?);
414            self.next += 1;
415        }
416        Ok(())
417    }
418
419    fn event(&mut self, event: &FlightEvent) {
420        self.samples.push(event.sample);
421    }
422
423    fn body_step(&mut self, body: usize, step: &dyn BodyStep) -> Result<(), SimError> {
424        let points = self.bodies.entry(body).or_default();
425        let mut next = points
426            .last()
427            .map_or((step.start_s() / TRUTH_STEP_S).ceil(), |p: &BodyPoint| {
428                (p.sample.time_s / TRUTH_STEP_S).round() + 1.0
429            });
430        loop {
431            let t = next * TRUTH_STEP_S;
432            if t > step.end_s() {
433                return Ok(());
434            }
435            points.push(BodyPoint {
436                sample: step.sample(t)?,
437                acceleration_enu_m_s2: step.acceleration_enu_m_s2(t)?,
438            });
439            next += 1.0;
440        }
441    }
442}
443
444/// A separated body at one instant of the truth's grid.
445#[derive(Debug, Clone, Copy)]
446struct BodyPoint {
447    sample: BodySample,
448    acceleration_enu_m_s2: DVec3,
449}
450
451/// One sample's truth.
452pub(crate) fn truth_sample(
453    environment: &Environment,
454    sample: &Sample,
455) -> Result<TruthSample, SimError> {
456    let a = sample.acceleration_enu_m_s2;
457    let gravity = environment
458        .earth
459        .gravity_enu_mps2(sample.state.position_enu_m)?;
460    let specific_force = a - gravity;
461    let axis = match sample.phase {
462        Phase::Descent => DVec3::Z,
463        _ => sample.state.unit_attitude() * DVec3::Z,
464    };
465    Ok(TruthSample {
466        time_s: sample.time_s,
467        height_m: sample.height_above_ground_m,
468        vertical_speed_m_s: sample.vertical_speed_m_s,
469        axial_specific_force_m_s2: specific_force.dot(axis),
470        mach: sample.mach,
471        dynamic_pressure_pa: sample.dynamic_pressure_pa,
472        position_enu_m: sample.cg_enu_m.to_array(),
473        velocity_enu_m_s: sample.cg_velocity_enu_m_s.to_array(),
474    })
475}
476
477/// Flies `simulation`, built from `inputs`, and keeps its truth.
478///
479/// # Errors
480///
481/// [`SyntheticError::Sim`] if HPR Sim refuses the flight, and [`SyntheticError::Flight`] if it
482/// doesn't come down with every event a truth needs.
483pub fn fly(
484    draw: &Draw,
485    inputs: &FlightInputs,
486    simulation: &Simulation,
487) -> Result<Truth, SyntheticError> {
488    let mut grid = Grid::default();
489    let result = simulation.run(&mut grid)?;
490    let mut samples = grid.samples;
491    samples.sort_by(|a, b| a.time_s.total_cmp(&b.time_s));
492    samples.dedup_by(|b, a| a.time_s == b.time_s);
493    let environment = &inputs.environment;
494    let samples = samples
495        .iter()
496        .map(|s| truth_sample(environment, s))
497        .collect::<Result<Vec<_>, _>>()?;
498    let names: Vec<&str> = design_of(draw)?.chutes.iter().map(|c| c.name).collect();
499    assemble(draw, &result, samples, &names)
500}
501
502/// A flight's truth from its samples and its result, `names` naming its parachutes in the order
503/// flown.
504fn assemble(
505    draw: &Draw,
506    result: &hpr_sim::FlightResult,
507    samples: Vec<TruthSample>,
508    names: &[&str],
509) -> Result<Truth, SyntheticError> {
510    let at = |kind: EventKind, what: &'static str| {
511        result
512            .event(kind)
513            .map(|e| e.sample)
514            .ok_or(SyntheticError::Flight { what })
515    };
516    let apogee = at(EventKind::Apogee, "no apogee")?;
517    let by_kind = |kind: fn(usize) -> EventKind| -> Vec<(String, f64)> {
518        let mut events: Vec<(String, f64)> = names
519            .iter()
520            .enumerate()
521            .filter_map(|(i, name)| {
522                result
523                    .event(kind(i))
524                    .map(|e| ((*name).to_owned(), e.sample.time_s))
525            })
526            .collect();
527        events.sort_by(|a, b| a.1.total_cmp(&b.1));
528        events
529    };
530    let pad_height_m = samples.first().map_or(0.0, |s| s.height_m);
531    Ok(Truth {
532        pad_height_m,
533        samples,
534        events: TruthEvents {
535            liftoff_s: at(EventKind::Liftoff, "no liftoff")?.time_s,
536            rail_exit_s: at(EventKind::RailExit, "no rail exit")?.time_s,
537            burnout_s: at(EventKind::Burnout, "no burnout")?.time_s,
538            apogee_s: apogee.time_s,
539            apogee_m: apogee.height_above_ground_m,
540            charges: by_kind(EventKind::Trigger),
541            deployments: by_kind(EventKind::Deployment),
542            landing_s: at(EventKind::GroundHit, "no landing")?.time_s,
543        },
544        site_elevation_m: draw.elevation_m,
545        temperature_offset_k: draw.temperature_offset_k,
546    })
547}
548
549/// The two-stage design's configuration.
550const STAGED_CONFIGURATION: &str = "j760-i175";
551/// Its booster's motor mount.
552const BOOSTER_MOUNT: &str = "booster-motor-mount";
553/// Its sustainer's motor mount.
554const SUSTAINER_MOUNT: &str = "sustainer-motor-mount";
555/// How long after the booster burns out the stack comes apart, s.
556const SEPARATION_DELAY_S: f64 = 0.5;
557/// How long after that the sustainer lights, s.
558const SUSTAINER_DELAY_S: f64 = 0.5;
559/// The sustainer's canopy's drag area, m²: invented, about a 1 m canopy's.
560const STAGE_DRAG_AREA_M2: f64 = 0.6;
561/// The canopy's lag after the sustainer's apogee, s.
562const STAGE_LAG_S: f64 = 1.0;
563/// The devices' names: the sustainer's canopy, then the booster's tumble.
564const STAGE_CHUTES: [&str; 2] = ["sustainer", "booster"];
565
566/// A staged flight's truth, one to a stage.
567#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
568pub struct StagedTruth {
569    /// The stack, then the sustainer.
570    pub sustainer: Truth,
571    /// The stack, then the booster tumbling alone as a point mass (`docs/physics/staging.md`).
572    pub booster: Truth,
573    /// When the stack came apart, s since launch.
574    pub separation_s: f64,
575}
576
577/// Flies `draw` on the two-stage design `json`: the booster burns out, the stack parts half a
578/// second later and the sustainer lights half a second after that. The sustainer comes down under
579/// a canopy, the booster tumbling.
580///
581/// # Errors
582///
583/// As [`fly`], and [`SyntheticError::Flight`] if the stack doesn't part or the booster has no
584/// flight to the ground.
585pub fn fly_staged(draw: &Draw, json: &str) -> Result<StagedTruth, SyntheticError> {
586    let mut rocket: Rocket = serde_json::from_str(json)?;
587    let configuration = rocket
588        .configurations
589        .iter_mut()
590        .find(|c| c.id == STAGED_CONFIGURATION)
591        .ok_or(SyntheticError::Invalid {
592            what: "a two-stage design with no such configuration",
593        })?;
594    for mounted in &mut configuration.motors {
595        mounted.motor = dispersed_motor(&mounted.motor, draw.impulse_scale, draw.burn_time_scale)?;
596        if mounted.mount == SUSTAINER_MOUNT {
597            mounted.ignition = Ignition::Separation {
598                delay_s: SUSTAINER_DELAY_S,
599            };
600        }
601    }
602    let mut inputs =
603        FlightInputs::new(rocket, STAGED_CONFIGURATION, environment(draw)?, rail(draw));
604    inputs.drag_scale = draw.drag_scale;
605    let stack = inputs.simulation()?;
606    let booster_motor = stack
607        .assembly()
608        .motors
609        .iter()
610        .position(|motor| motor.mounted.mount == BOOSTER_MOUNT)
611        .ok_or(SyntheticError::Invalid {
612            what: "a two-stage design with no booster motor",
613        })?;
614    // HPR Sim flies a booster dropped under power with its devices' drag alone, so one must act
615    // from the split: the booster tumbles, as `.ork` files' boosters do (`docs/physics/staging.md`).
616    let tumble = DeviceDrag::tumbling_stages(stack.assembly(), (1, 1))?;
617    inputs.recovery = vec![
618        Device::new(
619            STAGE_CHUTES[0],
620            DeviceDrag::DragArea {
621                cd_s_m2: STAGE_DRAG_AREA_M2,
622            },
623            Trigger::Apogee,
624        )
625        .with_lag_s(STAGE_LAG_S),
626        Device::new(STAGE_CHUTES[1], tumble, Trigger::Time { time_s: 0.0 }).on_body(1),
627    ];
628    inputs.separations = vec![Separation::new(
629        Trigger::Burnout {
630            motor: booster_motor,
631            delay_s: SEPARATION_DELAY_S,
632        },
633        0,
634    )];
635    let simulation = inputs.simulation()?;
636    let mut grid = Grid::default();
637    let result = simulation.run(&mut grid)?;
638    let separation_s = result
639        .event(EventKind::Separation)
640        .map(|event| event.sample.time_s)
641        .ok_or(SyntheticError::Flight {
642            what: "no separation",
643        })?;
644    let flown = result.bodies.first().ok_or(SyntheticError::Flight {
645        what: "no booster flight",
646    })?;
647    let mut samples = std::mem::take(&mut grid.samples);
648    samples.sort_by(|a, b| a.time_s.total_cmp(&b.time_s));
649    samples.dedup_by(|b, a| a.time_s == b.time_s);
650    let environment = &inputs.environment;
651    let stack_and_sustainer = samples
652        .iter()
653        .map(|s| truth_sample(environment, s))
654        .collect::<Result<Vec<_>, _>>()?;
655    let sustainer = assemble(draw, &result, stack_and_sustainer, &STAGE_CHUTES[..1])?;
656    let points = grid.bodies.remove(&flown.body).unwrap_or_default();
657    let booster = booster_truth(&sustainer, flown, &points, environment, separation_s)?;
658    Ok(StagedTruth {
659        sustainer,
660        booster,
661        separation_s,
662    })
663}
664
665/// The booster's truth: the stack's samples before the separation, then its own points and its
666/// events.
667fn booster_truth(
668    stack: &Truth,
669    flown: &BodyFlight,
670    points: &[BodyPoint],
671    environment: &Environment,
672    separation_s: f64,
673) -> Result<Truth, SyntheticError> {
674    let air = stack.air()?;
675    let mut samples: Vec<TruthSample> = stack
676        .samples
677        .iter()
678        .take_while(|s| s.time_s < separation_s)
679        .copied()
680        .collect();
681    let mut own: Vec<(BodySample, Option<DVec3>)> = points
682        .iter()
683        .map(|point| (point.sample, Some(point.acceleration_enu_m_s2)))
684        .collect();
685    own.push((flown.start_sample, None));
686    own.extend(flown.events.iter().map(|event| (event.sample, None)));
687    own.push((flown.final_sample, None));
688    own.sort_by(|a, b| a.0.time_s.total_cmp(&b.0.time_s));
689    for (sample, acceleration) in own {
690        // What an accelerometer hanging along the vertical reads: the point's acceleration less
691        // gravity's, up. An event's sample, on no grid point, takes the weight alone.
692        let gravity = environment.earth.gravity_enu_mps2(sample.cg_enu_m)?;
693        let specific_force = acceleration.map_or(-gravity.z, |a| (a - gravity).z);
694        let state = air
695            .sample(stack.site_elevation_m + sample.height_above_ground_m)?
696            .air;
697        samples.push(TruthSample {
698            time_s: sample.time_s,
699            height_m: sample.height_above_ground_m,
700            vertical_speed_m_s: sample.vertical_speed_m_s,
701            axial_specific_force_m_s2: specific_force,
702            mach: sample.airspeed_m_s / state.speed_of_sound_m_s,
703            dynamic_pressure_pa: 0.5 * state.density_kg_m3 * sample.airspeed_m_s.powi(2),
704            position_enu_m: sample.cg_enu_m.to_array(),
705            velocity_enu_m_s: sample.cg_velocity_enu_m_s.to_array(),
706        });
707    }
708    samples.dedup_by(|b, a| a.time_s == b.time_s);
709    let at = |kind: EventKind, what: &'static str| {
710        flown
711            .event(kind)
712            .map(|event| event.sample)
713            .ok_or(SyntheticError::Flight { what })
714    };
715    let apogee = at(EventKind::Apogee, "no booster apogee")?;
716    let landing = at(EventKind::GroundHit, "no booster landing")?;
717    let named = |kind: EventKind| -> Vec<(String, f64)> {
718        flown
719            .event(kind)
720            .map(|event| vec![(STAGE_CHUTES[1].to_owned(), event.sample.time_s)])
721            .unwrap_or_default()
722    };
723    Ok(Truth {
724        samples,
725        events: TruthEvents {
726            apogee_s: apogee.time_s,
727            apogee_m: apogee.height_above_ground_m,
728            charges: named(EventKind::Trigger(1)),
729            deployments: named(EventKind::Deployment(1)),
730            landing_s: landing.time_s,
731            ..stack.events.clone()
732        },
733        ..stack.clone()
734    })
735}
736
737#[cfg(test)]
738mod tests {
739    use super::*;
740
741    #[test]
742    fn a_truth_with_no_samples_or_a_time_that_isnt_a_number_has_no_sample_there() {
743        let sample = |time_s: f64, height_m: f64| TruthSample {
744            time_s,
745            height_m,
746            vertical_speed_m_s: 0.0,
747            axial_specific_force_m_s2: 0.0,
748            mach: 0.0,
749            dynamic_pressure_pa: 0.0,
750            position_enu_m: [0.0; 3],
751            velocity_enu_m_s: [0.0; 3],
752        };
753        let mut truth = Truth {
754            samples: vec![sample(0.0, 0.0), sample(1.0, 10.0)],
755            events: TruthEvents {
756                liftoff_s: 0.0,
757                rail_exit_s: 0.0,
758                burnout_s: 0.0,
759                apogee_s: 1.0,
760                apogee_m: 10.0,
761                charges: Vec::new(),
762                deployments: Vec::new(),
763                landing_s: 1.0,
764            },
765            pad_height_m: 0.0,
766            site_elevation_m: 0.0,
767            temperature_offset_k: 0.0,
768        };
769        assert_eq!(truth.at(0.25).unwrap().height_m, 2.5);
770        // Before the first sample the first holds; after the last, the last.
771        assert_eq!(truth.at(-1.0).unwrap().height_m, 0.0);
772        assert_eq!(truth.at(f64::INFINITY).unwrap().height_m, 10.0);
773        assert!(truth.at(f64::NAN).is_none());
774        truth.samples.clear();
775        assert!(truth.at(0.5).is_none());
776        assert!(matches!(
777            truth.pressure_pa(0.5),
778            Err(SyntheticError::Invalid { .. })
779        ));
780    }
781
782    #[test]
783    fn a_tilted_curve_keeps_its_impulse_and_leans_the_way_asked() {
784        let curve =
785            ThrustCurve::new(vec![0.0, 0.1, 1.0, 2.0], vec![0.0, 1_000.0, 1_000.0, 0.0]).unwrap();
786        for tilt in [-0.3, 0.0, 0.3] {
787            let t = tilted(&curve, tilt).unwrap();
788            let relative =
789                (t.total_impulse_ns() - curve.total_impulse_ns()).abs() / curve.total_impulse_ns();
790            assert!(relative < 1e-12, "tilt {tilt}: {relative}");
791        }
792        let progressive = tilted(&curve, 0.3).unwrap();
793        // Late thrust rises against early thrust: at 1.0 s over 0.1 s, the ratio 1.0/0.73.
794        let ratio = progressive.thrusts_n()[2] / progressive.thrusts_n()[1];
795        assert!((ratio - (1.0 + 0.3 * 0.0) / (1.0 + 0.3 * (0.1 - 1.0))).abs() < 1e-12);
796        assert!(ratio > 1.0);
797        let regressive = tilted(&curve, -0.3).unwrap();
798        assert!(regressive.thrusts_n()[2] < regressive.thrusts_n()[1]);
799    }
800
801    #[test]
802    fn set_bs_three_reshapes_reach_its_flights_inputs_and_set_as_keep_hpr_sims() {
803        use crate::synthetic::{Set, draw};
804        let files = DesignFiles::committed();
805        let a = draw(Set::A, 0);
806        let b = draw(Set::B, 0);
807        let (ia, ib) = (inputs(&a, &files).unwrap(), inputs(&b, &files).unwrap());
808        // The drag: set B overrides HPR Sim's with its reshaped model, set A doesn't.
809        assert!(ia.drag.is_none());
810        assert!(matches!(ib.drag, Some(DragOverride::Model(_))));
811        // The wind: set A's is the same at every height, set B's grows with it.
812        let speed = |i: &FlightInputs, d: &Draw, above_m: f64| {
813            i.environment
814                .wind
815                .wind(d.elevation_m + above_m)
816                .unwrap()
817                .velocity_enu_m_s
818                .length()
819        };
820        assert!((speed(&ia, &a, 10.0) - speed(&ia, &a, 500.0)).abs() < 1e-12);
821        assert!(speed(&ib, &b, 500.0) > 1.2 * speed(&ib, &b, 10.0));
822        // The thrust: set B's curve is tilted from the scaled motor's, set A's is the scaled one.
823        let curve = |i: &FlightInputs| -> Vec<f64> {
824            let configuration = i
825                .rocket
826                .configurations
827                .iter()
828                .find(|c| c.id == "example")
829                .unwrap();
830            configuration.motors[0].motor.curve().thrusts_n().to_vec()
831        };
832        let Model::Other { thrust_tilt, .. } = b.model else {
833            panic!("set B flies its model")
834        };
835        let mut scaled = rocket(
836            &Draw {
837                model: Model::Same,
838                ..b
839            },
840            &files,
841        )
842        .unwrap();
843        let configuration = scaled
844            .configurations
845            .iter_mut()
846            .find(|c| c.id == "example")
847            .unwrap();
848        let plain = configuration.motors[0].motor.curve().clone();
849        let expect = tilted(&plain, thrust_tilt).unwrap();
850        assert_eq!(curve(&ib), expect.thrusts_n());
851        assert_ne!(curve(&ib), plain.thrusts_n());
852    }
853
854    #[test]
855    fn set_bs_drag_factor_reshapes_around_mach_one() {
856        let flat = ReshapedDrag {
857            scale: 1.1,
858            bump: 0.0,
859            slope: 0.0,
860        };
861        assert_eq!(flat.factor(0.3), 1.1);
862        assert_eq!(flat.factor(2.0), 1.1);
863        let bumped = ReshapedDrag {
864            scale: 1.0,
865            bump: 0.2,
866            slope: 0.0,
867        };
868        assert!((bumped.factor(1.0) - 1.2).abs() < 1e-15);
869        assert!((bumped.factor(1.2) - (1.0 + 0.2 * (-1.0_f64).exp())).abs() < 1e-15);
870        assert!((bumped.factor(0.3) - 1.0).abs() < 1e-4);
871    }
872}