1pub mod census;
33pub mod designs;
34pub mod fits;
35pub mod held;
36pub mod intervals;
37pub mod logger;
38pub mod noise;
39pub mod paired;
40pub mod smoothed;
41pub mod truth;
42
43use std::collections::BTreeMap;
44
45use hpr_core::random::SeededRng;
46use hpr_flightdata::log::FlightLog;
47use hpr_sim::Simulation;
48use serde::{Deserialize, Serialize};
49
50use designs::{DESIGNS, DesignFiles};
51use logger::{LoggerDraw, Profile};
52use noise::between;
53use truth::Truth;
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
57#[serde(rename_all = "kebab-case")]
58pub enum Set {
59 Tuning,
62 A,
64 B,
67 Calibration,
75 PairCalibration,
79 PairA,
81 PairB,
83 Staged,
85}
86
87impl Set {
88 pub const ALL: [Self; 3] = [Self::Tuning, Self::A, Self::B];
90
91 pub fn seed(self) -> u64 {
98 match self {
99 Self::Tuning => 2_026_101_700,
100 Self::A => 2_026_101_701,
101 Self::B => 2_026_101_702,
102 Self::Calibration => 2_026_102_900,
103 Self::PairCalibration => 2_026_103_100,
104 Self::PairA => 2_026_103_101,
105 Self::PairB => 2_026_103_102,
106 Self::Staged => 2_026_103_103,
107 }
108 }
109
110 pub fn count(self) -> u64 {
112 match self {
113 Self::Tuning => 200,
114 Self::A | Self::B | Self::PairA | Self::PairB => 1_000,
115 Self::Calibration | Self::PairCalibration => 2_000,
116 Self::Staged => 200,
117 }
118 }
119
120 pub fn name(self) -> &'static str {
122 match self {
123 Self::Tuning => "tuning",
124 Self::A => "a",
125 Self::B => "b",
126 Self::Calibration => "calibration",
127 Self::PairCalibration => "pair-calibration",
128 Self::PairA => "pair-a",
129 Self::PairB => "pair-b",
130 Self::Staged => "staged",
131 }
132 }
133
134 fn other_model(self, index: u64) -> bool {
136 match self {
137 Self::Tuning | Self::Calibration | Self::PairCalibration => index % 2 == 1,
138 Self::A | Self::PairA | Self::Staged => false,
139 Self::B | Self::PairB => true,
140 }
141 }
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
146#[serde(tag = "model", rename_all = "kebab-case")]
147pub enum Model {
148 Same,
150 Other {
153 drag_bump: f64,
155 drag_slope: f64,
157 shear_exponent: f64,
159 thrust_tilt: f64,
161 },
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
166pub struct Draw {
167 pub set: Set,
169 pub index: u64,
171 pub design: usize,
173 pub impulse_scale: f64,
175 pub burn_time_scale: f64,
177 pub drag_scale: f64,
179 pub wind_speed_m_s: f64,
181 pub wind_from_rad: f64,
183 pub tilt_rad: f64,
185 pub azimuth_rad: f64,
187 pub elevation_m: f64,
189 pub temperature_offset_k: f64,
191 pub model: Model,
193 pub logger: LoggerDraw,
195}
196
197#[derive(Debug, Clone, Copy)]
199#[repr(u64)]
200enum Key {
201 Design = 1,
202 Motor = 2,
203 Drag = 3,
204 Wind = 4,
205 Rail = 5,
206 Site = 6,
207 Model = 7,
208 Logger = 8,
209 BaroCorrelated = 9,
210 BaroWhite = 10,
211 Accel = 11,
212 Gnss = 12,
213 BaroSlow = 13,
214 SecondLogger = 14,
215 Clocks = 15,
216}
217
218pub(crate) const SMOOTHER_MOMENT_KEY: u64 = 14;
222
223fn stream(seed: u64, index: u64, key: Key) -> SeededRng {
225 SeededRng::for_stream(seed, &[index, key as u64])
226}
227
228pub(crate) const WEIGHING_KEY: u64 = 16;
231pub(crate) const NOISE_LOG_KEY: u64 = 17;
233pub(crate) const POSTERIOR_KEY: u64 = 18;
236
237pub const MAX_WIND_M_S: f64 = 20.0 * 0.447_04;
239pub const MAX_TILT_DEG: f64 = 10.0;
241
242pub fn draw(set: Set, index: u64) -> Draw {
244 let seed = set.seed();
245 let turn = std::f64::consts::TAU;
246 let design = {
247 let mut rng = stream(seed, index, Key::Design);
248 ((rng.uniform() * DESIGNS.len() as f64) as usize).min(DESIGNS.len() - 1)
249 };
250 let mut motor = stream(seed, index, Key::Motor);
251 let impulse_scale = between(&mut motor, 0.94, 1.06);
252 let burn_time_scale = between(&mut motor, 0.90, 1.10);
253 let drag_scale = between(&mut stream(seed, index, Key::Drag), 0.8, 1.2);
254 let mut wind = stream(seed, index, Key::Wind);
255 let wind_speed_m_s = between(&mut wind, 0.0, MAX_WIND_M_S);
256 let wind_from_rad = between(&mut wind, 0.0, turn);
257 let mut rail = stream(seed, index, Key::Rail);
258 let tilt_rad = between(&mut rail, 0.0, MAX_TILT_DEG).to_radians();
259 let azimuth_rad = between(&mut rail, 0.0, turn);
260 let mut site = stream(seed, index, Key::Site);
261 let elevation_m = between(&mut site, 0.0, 1_500.0);
262 let temperature_offset_k = between(&mut site, -15.0, 15.0);
263 let model = if set.other_model(index) {
264 let mut rng = stream(seed, index, Key::Model);
265 Model::Other {
266 drag_bump: between(&mut rng, -0.2, 0.2),
267 drag_slope: between(&mut rng, -0.05, 0.05),
268 shear_exponent: between(&mut rng, 0.14, 0.20),
269 thrust_tilt: between(&mut rng, -0.3, 0.3),
270 }
271 } else {
272 Model::Same
273 };
274 let mut logger = stream(seed, index, Key::Logger);
275 let profile = Profile::ALL
276 [((logger.uniform() * Profile::ALL.len() as f64) as usize).min(Profile::ALL.len() - 1)];
277 Draw {
278 set,
279 index,
280 design,
281 impulse_scale,
282 burn_time_scale,
283 drag_scale,
284 wind_speed_m_s,
285 wind_from_rad,
286 tilt_rad,
287 azimuth_rad,
288 elevation_m,
289 temperature_offset_k,
290 model,
291 logger: LoggerDraw::draw(&mut logger, profile),
292 }
293}
294
295#[derive(Debug, thiserror::Error)]
297#[non_exhaustive]
298pub enum SyntheticError {
299 #[error("the flight: {0}")]
301 Sim(#[from] hpr_sim::SimError),
302 #[error("the motor: {0}")]
304 Analysis(#[from] hpr_analysis::AnalysisError),
305 #[error("the motor: {0}")]
307 Motor(#[from] hpr_motor::MotorError),
308 #[error("the air: {0}")]
310 Atmos(#[from] hpr_atmos::AtmosError),
311 #[error("the site: {0}")]
313 Core(#[from] hpr_core::CoreError),
314 #[error("a design: {0}")]
316 Json(#[from] serde_json::Error),
317 #[error("design {design} {what}")]
319 Design {
320 design: &'static str,
322 what: &'static str,
324 },
325 #[error("the flight came down with {what}")]
327 Flight {
328 what: &'static str,
330 },
331 #[error("{what}")]
333 Invalid {
334 what: &'static str,
336 },
337}
338
339#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
341pub struct Flight {
342 pub draw: Draw,
344 pub truth: Truth,
346 pub log: FlightLog,
348}
349
350#[derive(Debug)]
353pub struct Flyer {
354 files: DesignFiles,
355 nominal: BTreeMap<usize, Simulation>,
356}
357
358impl Flyer {
359 pub fn new(files: DesignFiles) -> Self {
361 Self {
362 files,
363 nominal: BTreeMap::new(),
364 }
365 }
366
367 pub fn flight(&mut self, set: Set, index: u64) -> Result<Flight, SyntheticError> {
374 let draw = draw(set, index);
375 let inputs = truth::inputs(&draw, &self.files)?;
376 let mut simulation = inputs.simulation()?;
377 let shared = match self.nominal.get(&draw.design) {
378 Some(nominal) => simulation.share_supersonic_table(nominal.aero()),
379 None => false,
380 };
381 let truth = truth::fly(&draw, &inputs, &simulation);
382 if !shared && !self.nominal.contains_key(&draw.design) {
383 self.nominal.insert(draw.design, simulation);
385 }
386 let truth = truth?;
387 let log = logger::log(&draw.logger, &truth, set.seed(), index)?;
388 Ok(Flight { draw, truth, log })
389 }
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395
396 fn fills(values: &[f64], lo: f64, hi: f64) -> bool {
400 let (least, greatest) = values
401 .iter()
402 .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &v| {
403 (a.min(v), b.max(v))
404 });
405 let slack = 6.0 / values.len() as f64 * (hi - lo);
406 values.iter().all(|v| (lo..=hi).contains(v)) && least < lo + slack && greatest > hi - slack
407 }
408
409 #[test]
410 fn every_draw_stays_inside_its_range_and_fills_it() {
411 for set in Set::ALL.into_iter().chain([
412 Set::Calibration,
413 Set::PairCalibration,
414 Set::PairA,
415 Set::PairB,
416 ]) {
417 let draws: Vec<Draw> = (0..set.count()).map(|k| draw(set, k)).collect();
418 let column = |f: fn(&Draw) -> f64| draws.iter().map(f).collect::<Vec<_>>();
419 assert!(fills(&column(|d| d.impulse_scale), 0.94, 1.06), "{set:?}");
420 assert!(fills(&column(|d| d.burn_time_scale), 0.90, 1.10), "{set:?}");
421 assert!(fills(&column(|d| d.drag_scale), 0.8, 1.2), "{set:?}");
422 assert!(
423 fills(&column(|d| d.wind_speed_m_s), 0.0, MAX_WIND_M_S),
424 "{set:?}"
425 );
426 assert!(
427 fills(&column(|d| d.wind_from_rad), 0.0, std::f64::consts::TAU),
428 "{set:?}"
429 );
430 assert!(
431 fills(&column(|d| d.tilt_rad.to_degrees()), 0.0, MAX_TILT_DEG),
432 "{set:?}"
433 );
434 assert!(
435 fills(&column(|d| d.azimuth_rad), 0.0, std::f64::consts::TAU),
436 "{set:?}"
437 );
438 assert!(fills(&column(|d| d.elevation_m), 0.0, 1_500.0), "{set:?}");
439 assert!(
440 fills(&column(|d| d.temperature_offset_k), -15.0, 15.0),
441 "{set:?}"
442 );
443 for design in 0..DESIGNS.len() {
444 assert!(
445 draws.iter().any(|d| d.design == design),
446 "{set:?} lacks design {design}"
447 );
448 }
449 for profile in Profile::ALL {
450 assert!(
451 draws.iter().any(|d| d.logger.profile == profile),
452 "{set:?} lacks {profile:?}"
453 );
454 }
455 let others: Vec<[f64; 4]> = draws
456 .iter()
457 .filter_map(|d| match d.model {
458 Model::Same => None,
459 Model::Other {
460 drag_bump,
461 drag_slope,
462 shear_exponent,
463 thrust_tilt,
464 } => Some([drag_bump, drag_slope, shear_exponent, thrust_tilt]),
465 })
466 .collect();
467 let other = |k: usize| others.iter().map(|o| o[k]).collect::<Vec<_>>();
468 match set {
469 Set::A | Set::PairA | Set::Staged => assert!(others.is_empty()),
470 Set::B | Set::PairB => assert_eq!(others.len(), draws.len()),
471 Set::Tuning | Set::Calibration | Set::PairCalibration => {
472 let alternate = draws
473 .iter()
474 .all(|d| matches!(d.model, Model::Other { .. }) == (d.index % 2 == 1));
475 assert!(alternate);
476 }
477 }
478 if !others.is_empty() {
479 assert!(fills(&other(0), -0.2, 0.2), "{set:?}");
480 assert!(fills(&other(1), -0.05, 0.05), "{set:?}");
481 assert!(fills(&other(2), 0.14, 0.20), "{set:?}");
482 assert!(fills(&other(3), -0.3, 0.3), "{set:?}");
483 }
484 }
485 }
486
487 #[test]
488 fn the_sets_draw_on_their_own_seeds() {
489 let seeds: Vec<u64> = Set::ALL.iter().map(|s| s.seed()).collect();
490 assert_eq!(seeds, [2_026_101_700, 2_026_101_701, 2_026_101_702]);
491 assert_eq!(Set::ALL.map(Set::count), [200, 1_000, 1_000]);
492 assert_eq!(Set::Calibration.seed(), 2_026_102_900);
493 assert_eq!(Set::Calibration.count(), 2_000);
494 assert!(!Set::ALL.contains(&Set::Calibration));
495 let (a, b) = (draw(Set::A, 3), draw(Set::B, 3));
497 assert_ne!(a.impulse_scale, b.impulse_scale);
498 assert_ne!(a.logger.pad_s, b.logger.pad_s);
499 }
500
501 #[test]
502 fn a_flight_drawn_again_is_bit_identical() {
503 let first = 0;
506 let design = draw(Set::B, first).design;
507 let second = (1..).find(|&k| draw(Set::B, k).design == design).unwrap();
508 let mut flyer = Flyer::new(DesignFiles::committed());
509 let earlier = flyer.flight(Set::B, first).unwrap();
510 let after = flyer.flight(Set::B, second).unwrap();
511 let alone = Flyer::new(DesignFiles::committed())
512 .flight(Set::B, second)
513 .unwrap();
514 let text = |flight: &Flight| serde_json::to_string(flight).unwrap();
515 assert_eq!(text(&after), text(&alone));
516 assert_eq!(
517 text(&earlier),
518 text(
519 &Flyer::new(DesignFiles::committed())
520 .flight(Set::B, first)
521 .unwrap()
522 )
523 );
524 let bits = |flight: &Flight| -> Vec<u64> {
525 let channels = flight.log.channels.iter().flat_map(|c| c.values.iter());
526 let samples = flight.truth.samples.iter().map(|s| &s.height_m);
527 flight
528 .log
529 .altitude_m
530 .iter()
531 .chain(channels)
532 .chain(samples)
533 .map(|v| v.to_bits())
534 .collect()
535 };
536 assert_eq!(bits(&after), bits(&alone));
537 assert_ne!(text(&earlier), text(&after));
539 assert!(!after.log.time_s.is_empty() || !after.log.channels.is_empty());
540 }
541}