1use 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
26pub const TRUTH_STEP_S: f64 = 0.01;
28pub const RAIL_LENGTH_M: f64 = 5.2;
30pub const SITE_LATITUDE_DEG: f64 = 35.0;
33pub const SITE_LONGITUDE_DEG: f64 = -106.0;
35pub const SHEAR_REFERENCE_HEIGHT_M: f64 = 18.3;
38const SEA_LEVEL_PRESSURE_PA: f64 = 101_325.0;
40
41#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
43pub struct TruthSample {
44 pub time_s: f64,
46 pub height_m: f64,
48 pub vertical_speed_m_s: f64,
50 pub axial_specific_force_m_s2: f64,
55 pub mach: f64,
57 pub dynamic_pressure_pa: f64,
59 pub position_enu_m: [f64; 3],
61 pub velocity_enu_m_s: [f64; 3],
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct TruthEvents {
68 pub liftoff_s: f64,
70 pub rail_exit_s: f64,
72 pub burnout_s: f64,
74 pub apogee_s: f64,
76 pub apogee_m: f64,
78 pub charges: Vec<(String, f64)>,
80 pub deployments: Vec<(String, f64)>,
82 pub landing_s: f64,
84}
85
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub struct Truth {
89 pub samples: Vec<TruthSample>,
91 pub events: TruthEvents,
93 pub pad_height_m: f64,
96 pub site_elevation_m: f64,
98 pub temperature_offset_k: f64,
100}
101
102impl Truth {
103 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 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 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 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 pub fn apogee_above_pad_m(&self) -> f64 {
178 self.events.apogee_m - self.pad_height_m
179 }
180
181 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 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#[derive(Debug, Clone, Copy)]
213pub struct ReshapedDrag {
214 pub scale: f64,
216 pub bump: f64,
218 pub slope: f64,
220}
221
222impl ReshapedDrag {
223 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
236pub 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
258fn 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
265fn 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
295fn 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
325pub 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
356fn 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
384fn 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#[derive(Debug, Default)]
395pub(crate) struct Grid {
396 next: u64,
397 pub(crate) samples: Vec<Sample>,
398 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#[derive(Debug, Clone, Copy)]
446struct BodyPoint {
447 sample: BodySample,
448 acceleration_enu_m_s2: DVec3,
449}
450
451pub(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
477pub 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
502fn 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
549const STAGED_CONFIGURATION: &str = "j760-i175";
551const BOOSTER_MOUNT: &str = "booster-motor-mount";
553const SUSTAINER_MOUNT: &str = "sustainer-motor-mount";
555const SEPARATION_DELAY_S: f64 = 0.5;
557const SUSTAINER_DELAY_S: f64 = 0.5;
559const STAGE_DRAG_AREA_M2: f64 = 0.6;
561const STAGE_LAG_S: f64 = 1.0;
563const STAGE_CHUTES: [&str; 2] = ["sustainer", "booster"];
565
566#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
568pub struct StagedTruth {
569 pub sustainer: Truth,
571 pub booster: Truth,
573 pub separation_s: f64,
575}
576
577pub 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 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
665fn 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 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 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 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 assert!(ia.drag.is_none());
810 assert!(matches!(ib.drag, Some(DragOverride::Model(_))));
811 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 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}