1use hpr_sim::metrics::Landing;
30use hpr_sim::{EnvelopeFlag, FlightSummary};
31use serde::{Deserialize, Serialize};
32
33use crate::error::AnalysisError;
34use crate::montecarlo::{Draw, FailedAt, Outcome, Run, Sample};
35
36type DrawList = fn(&Draw) -> &Vec<f64>;
38
39type LandingField = fn(&Landing) -> f64;
41
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45pub struct Column {
46 pub name: String,
48 pub values: Values,
50}
51
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54#[serde(tag = "kind", content = "values", rename_all = "snake_case")]
55pub enum Values {
56 Integers(Vec<u64>),
58 Numbers(Vec<Option<f64>>),
60 Text(Vec<String>),
62}
63
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66pub struct RunTable {
67 rows: usize,
68 columns: Vec<Column>,
69}
70
71impl RunTable {
72 pub fn new(run: &Run) -> Self {
76 let samples = &run.samples;
77 let mut columns = Vec::new();
78 columns.push(Column {
79 name: "index".to_owned(),
80 values: Values::Integers(samples.iter().map(|sample| sample.index).collect()),
81 });
82 let mut text = |name: &str, value: &dyn Fn(&Sample) -> String| {
83 columns.push(Column {
84 name: name.to_owned(),
85 values: Values::Text(samples.iter().map(value).collect()),
86 });
87 };
88 text("outcome", &|sample| match sample.outcome {
89 Outcome::Flown { .. } => "flown".to_owned(),
90 Outcome::Failed { .. } => "failed".to_owned(),
91 });
92 text("failed_at", &|sample| match &sample.outcome {
93 Outcome::Flown { .. } => String::new(),
94 Outcome::Failed { at, .. } => match at {
95 FailedAt::Inputs => "inputs".to_owned(),
96 FailedAt::Flight => "flight".to_owned(),
97 },
98 });
99 text("reason", &|sample| match &sample.outcome {
100 Outcome::Flown { .. } => String::new(),
101 Outcome::Failed { reason, .. } => reason.clone(),
102 });
103
104 let mut add = |name: String, value: &dyn Fn(&Sample) -> Option<f64>| {
105 columns.push(Column {
106 name,
107 values: Values::Numbers(samples.iter().map(value).collect()),
108 });
109 };
110 let drawn = |pick: fn(&Draw) -> f64| move |sample: &Sample| Some(pick(&sample.draw));
111 add("drag_scale".to_owned(), &drawn(|d| d.drag_scale));
112 add(
113 "wind_speed_scale".to_owned(),
114 &drawn(|d| d.wind_speed_scale),
115 );
116 add("wind_turn_rad".to_owned(), &drawn(|d| d.wind_turn_rad));
117 add(
118 "rail_elevation_offset_rad".to_owned(),
119 &drawn(|d| d.rail_elevation_offset_rad),
120 );
121 add(
122 "rail_azimuth_offset_rad".to_owned(),
123 &drawn(|d| d.rail_azimuth_offset_rad),
124 );
125 let lists: [(&str, &str, DrawList); 6] = [
126 ("stage", "dry_mass_scale", |d| &d.dry_mass_scale),
127 ("stage", "cg_shift_m", |d| &d.cg_shift_m),
128 ("motor", "impulse_scale", |d| &d.impulse_scale),
129 ("motor", "burn_time_scale", |d| &d.burn_time_scale),
130 ("motor", "ejection_delay_offset_s", |d| {
131 &d.ejection_delay_offset_s
132 }),
133 ("device", "deployment_lag_offset_s", |d| {
134 &d.deployment_lag_offset_s
135 }),
136 ];
137 for kind in ["stage", "motor", "device"] {
139 let of_kind: Vec<_> = lists.iter().filter(|(k, _, _)| *k == kind).collect();
140 let count = of_kind
141 .first()
142 .and_then(|(_, _, list)| samples.first().map(|s| list(&s.draw).len()))
143 .unwrap_or(0);
144 for copy in 0..count {
145 for (_, name, list) in &of_kind {
146 add(format!("{kind}_{}_{name}", copy + 1), &|sample| {
147 list(&sample.draw).get(copy).copied()
148 });
149 }
150 }
151 }
152
153 columns.push(Column {
154 name: "termination".to_owned(),
155 values: Values::Text(
156 samples
157 .iter()
158 .map(|sample| {
159 sample.summary().map_or_else(String::new, |s| {
160 snake_name(&format!("{:?}", s.termination))
161 })
162 })
163 .collect(),
164 ),
165 });
166 let mut flown = |name: &str, value: fn(&FlightSummary) -> Option<f64>| {
167 columns.push(Column {
168 name: name.to_owned(),
169 values: Values::Numbers(
170 samples
171 .iter()
172 .map(|sample| sample.summary().and_then(value))
173 .collect(),
174 ),
175 });
176 };
177 flown("apogee_m", |s| {
178 s.apogee.as_ref().map(|a| a.height_above_ground_m)
179 });
180 flown("apogee_time_s", |s| s.apogee.as_ref().map(|a| a.time_s));
181 flown("rail_exit_speed_m_s", |s| {
182 s.rail_exit_speed_m_s.as_ref().map(|p| p.value)
183 });
184 flown("max_speed_m_s", |s| {
185 s.max_speed_m_s.as_ref().map(|p| p.value)
186 });
187 flown("max_mach", |s| s.max_mach.as_ref().map(|p| p.value));
188 flown("max_dynamic_pressure_pa", |s| {
189 s.max_dynamic_pressure_pa.as_ref().map(|p| p.value)
190 });
191 flown("max_acceleration_m_s2", |s| {
192 s.max_acceleration_m_s2.as_ref().map(|p| p.value)
193 });
194 flown("max_descent_acceleration_m_s2", |s| {
195 s.max_descent_acceleration_m_s2.as_ref().map(|p| p.value)
196 });
197 flown("max_deployment_airspeed_m_s", |s| {
198 s.max_deployment_airspeed_m_s.as_ref().map(|p| p.value)
199 });
200 flown("min_static_margin_cal", |s| {
201 s.min_static_margin_cal.as_ref().map(|p| p.value)
202 });
203 flown("min_flight_margin_cal", |s| {
204 s.min_flight_margin_cal.as_ref().map(|p| p.value)
205 });
206 flown("max_angle_of_attack_rad", |s| {
207 s.max_angle_of_attack_rad.as_ref().map(|p| p.value)
208 });
209 flown("landing_time_s", |s| s.nose_landing().map(|l| l.time_s));
210 flown("landing_east_m", |s| s.nose_landing().map(|l| l.east_m));
211 flown("landing_north_m", |s| s.nose_landing().map(|l| l.north_m));
212 flown("landing_distance_m", |s| {
213 s.nose_landing().map(|l| l.distance_m)
214 });
215 flown("landing_latitude_deg", |s| {
216 s.nose_landing().map(|l| l.latitude_deg)
217 });
218 flown("landing_longitude_deg", |s| {
219 s.nose_landing().map(|l| l.longitude_deg)
220 });
221 flown("ground_hit_speed_m_s", |s| {
222 s.nose_landing().map(|l| l.ground_hit_speed_m_s)
223 });
224
225 let parts = samples
226 .iter()
227 .filter_map(Sample::summary)
228 .flat_map(|s| s.body_landings.iter().filter_map(|l| l.body))
229 .filter(|body| *body > 0)
230 .max()
231 .unwrap_or(0);
232 let fields: [(&str, LandingField); 4] = [
233 ("landing_time_s", |l| l.time_s),
234 ("landing_east_m", |l| l.east_m),
235 ("landing_north_m", |l| l.north_m),
236 ("ground_hit_speed_m_s", |l| l.ground_hit_speed_m_s),
237 ];
238 for part in 1..=parts {
239 for (name, field) in fields {
240 columns.push(Column {
241 name: format!("part_{part}_{name}"),
242 values: Values::Numbers(
243 samples
244 .iter()
245 .map(|sample| {
246 let landing = sample
247 .summary()?
248 .body_landings
249 .iter()
250 .find(|l| l.body == Some(part))?;
251 Some(field(landing))
252 })
253 .collect(),
254 ),
255 });
256 }
257 }
258 columns.push(Column {
259 name: "flags".to_owned(),
260 values: Values::Text(
261 samples
262 .iter()
263 .map(|sample| {
264 sample.summary().map_or_else(String::new, |s| {
265 s.envelope_flags()
266 .iter()
267 .map(flag_name)
268 .collect::<Vec<_>>()
269 .join(";")
270 })
271 })
272 .collect(),
273 ),
274 });
275 Self {
276 rows: samples.len(),
277 columns,
278 }
279 }
280
281 pub fn rows(&self) -> usize {
283 self.rows
284 }
285
286 pub fn columns(&self) -> &[Column] {
288 &self.columns
289 }
290
291 pub fn column(&self, name: &str) -> Option<&Column> {
293 self.columns.iter().find(|column| column.name == name)
294 }
295
296 pub fn csv(&self) -> Result<String, AnalysisError> {
307 let header: Vec<String> = self
308 .columns
309 .iter()
310 .map(|c| quoted(&hpr_sim::export::csv_header(&c.name)))
311 .collect();
312 let mut out = header.join(",");
313 out.push_str("\r\n");
314 for row in 0..self.rows {
315 let mut cells = Vec::with_capacity(self.columns.len());
316 for column in &self.columns {
317 cells.push(match &column.values {
318 Values::Numbers(values) => match values.get(row).copied().flatten() {
319 Some(value) if value.is_finite() => format!("{value:?}"),
320 Some(value) => {
321 return Err(AnalysisError::Domain {
322 what: "number in a run's table",
323 value,
324 });
325 }
326 None => String::new(),
327 },
328 Values::Integers(values) => {
329 values.get(row).map_or_else(String::new, u64::to_string)
330 }
331 Values::Text(values) => values.get(row).map_or_else(String::new, |v| quoted(v)),
332 });
333 }
334 out.push_str(&cells.join(","));
335 out.push_str("\r\n");
336 }
337 Ok(out)
338 }
339}
340
341fn quoted(text: &str) -> String {
344 if text.contains([',', '"', '\r', '\n']) {
345 format!("\"{}\"", text.replace('"', "\"\""))
346 } else {
347 text.to_owned()
348 }
349}
350
351fn snake_name(debug: &str) -> String {
354 let name = debug
355 .split(|c: char| c == '{' || c == '(' || c.is_whitespace())
356 .next()
357 .unwrap_or_default();
358 let mut out = String::with_capacity(name.len() + 4);
359 for (i, c) in name.chars().enumerate() {
360 if c.is_ascii_uppercase() {
361 if i > 0 {
362 out.push('_');
363 }
364 out.push(c.to_ascii_lowercase());
365 } else {
366 out.push(c);
367 }
368 }
369 out
370}
371
372fn flag_name(flag: &EnvelopeFlag) -> String {
374 flag.name().to_owned()
375}
376
377#[cfg(test)]
378mod tests {
379 #![allow(
380 clippy::unwrap_used,
381 clippy::expect_used,
382 clippy::panic,
383 reason = "tests state their expectations by unwrapping and panicking"
384 )]
385
386 use super::*;
387 use crate::montecarlo::tests::{SEED, every_dispersion, nominal};
388 use crate::montecarlo::{Dispersion, MonteCarlo};
389
390 fn cells(text: &str) -> Vec<Vec<String>> {
392 let mut lines = Vec::new();
393 let mut line = Vec::new();
394 let mut cell = String::new();
395 let mut chars = text.chars().peekable();
396 let mut quoted = false;
397 while let Some(c) = chars.next() {
398 match (quoted, c) {
399 (true, '"') if chars.peek() == Some(&'"') => {
400 chars.next();
401 cell.push('"');
402 }
403 (true, '"') => quoted = false,
404 (true, c) => cell.push(c),
405 (false, '"') => quoted = true,
406 (false, ',') => line.push(std::mem::take(&mut cell)),
407 (false, '\r') => {
408 assert_eq!(chars.next(), Some('\n'), "a line ends in CRLF");
409 line.push(std::mem::take(&mut cell));
410 lines.push(std::mem::take(&mut line));
411 }
412 (false, c) => cell.push(c),
413 }
414 }
415 assert!(cell.is_empty() && line.is_empty(), "the text ends in CRLF");
416 lines
417 }
418
419 fn run() -> Run {
421 let dispersion = Dispersion {
422 dry_mass_sd_fraction: 0.6,
423 ..every_dispersion()
424 };
425 MonteCarlo::new(nominal(), dispersion)
426 .unwrap()
427 .run(SEED, 16)
428 }
429
430 #[test]
433 fn the_csv_reads_back_to_the_runs_bits() {
434 let run = run();
435 let failed = run.failed().count();
436 assert!(failed > 0 && failed < 16, "{failed} failed");
437 let table = RunTable::new(&run);
438 assert_eq!(table.rows(), 16);
439 let lines = cells(&table.csv().unwrap());
440 assert_eq!(lines.len(), 17);
441 let names: Vec<&str> = table.columns().iter().map(|c| c.name.as_str()).collect();
442 assert_eq!(
445 lines[0].join(","),
446 "index,outcome,failed at,reason,drag scale,wind speed scale,wind turn [rad],\
447 rail elevation offset [rad],rail azimuth offset [rad],stage 1 dry mass scale,\
448 stage 1 cg shift [m],motor 1 impulse scale,motor 1 burn time scale,\
449 motor 1 ejection delay offset [s],device 1 deployment lag offset [s],termination,\
450 apogee [m],apogee time [s],rail exit speed [m/s],max speed [m/s],max mach,\
451 max dynamic pressure [Pa],max acceleration [m/s^2],\
452 max descent acceleration [m/s^2],max deployment airspeed [m/s],min static margin [cal],\
453 min flight margin [cal],max angle of attack [rad],landing time [s],landing east [m],\
454 landing north [m],landing distance [m],landing latitude [deg],\
455 landing longitude [deg],ground hit speed [m/s],flags"
456 );
457 let headers: Vec<String> = names
458 .iter()
459 .map(|name| hpr_sim::export::csv_header(name))
460 .collect();
461 assert_eq!(lines[0], headers);
462 for (row, line) in lines[1..].iter().enumerate() {
463 assert_eq!(line.len(), names.len());
464 for (column, cell) in table.columns().iter().zip(line) {
465 match &column.values {
466 Values::Numbers(values) => match values[row] {
467 Some(value) => assert_eq!(
468 cell.parse::<f64>().unwrap().to_bits(),
469 value.to_bits(),
470 "{} of row {row}",
471 column.name
472 ),
473 None => assert!(cell.is_empty(), "{} of row {row}", column.name),
474 },
475 Values::Integers(values) => assert_eq!(*cell, values[row].to_string()),
476 Values::Text(values) => assert_eq!(*cell, values[row], "{}", column.name),
477 }
478 }
479 }
480 let number = |name: &str, row: usize| match &table.column(name).unwrap().values {
482 Values::Numbers(values) => values[row],
483 Values::Text(_) | Values::Integers(_) => panic!("{name} isn't numbers"),
484 };
485 let word = |name: &str, row: usize| match &table.column(name).unwrap().values {
486 Values::Text(values) => values[row].clone(),
487 Values::Numbers(_) | Values::Integers(_) => panic!("{name} isn't words"),
488 };
489 for (row, sample) in run.samples.iter().enumerate() {
490 assert_eq!(
491 table.column("index").unwrap().values,
492 Values::Integers((0..16).collect())
493 );
494 assert_eq!(sample.index, row as u64);
495 let draw = &sample.draw;
496 assert_eq!(number("drag_scale", row), Some(draw.drag_scale));
497 assert_eq!(number("wind_turn_rad", row), Some(draw.wind_turn_rad));
498 assert_eq!(
499 number("stage_1_dry_mass_scale", row),
500 Some(draw.dry_mass_scale[0])
501 );
502 assert_eq!(number("stage_1_cg_shift_m", row), Some(draw.cg_shift_m[0]));
503 assert_eq!(
504 number("motor_1_burn_time_scale", row),
505 Some(draw.burn_time_scale[0])
506 );
507 assert_eq!(
508 number("device_1_deployment_lag_offset_s", row),
509 Some(draw.deployment_lag_offset_s[0])
510 );
511 match &sample.outcome {
512 Outcome::Flown { summary } => {
513 assert_eq!(word("outcome", row), "flown");
514 assert_eq!(word("failed_at", row), "");
515 assert_eq!(word("termination", row), "ground_hit");
516 let apogee = summary.apogee.as_ref().unwrap();
517 assert_eq!(number("apogee_m", row), Some(apogee.height_above_ground_m));
518 let landing = summary.landing.as_ref().unwrap();
519 assert_eq!(number("landing_east_m", row), Some(landing.east_m));
520 assert_eq!(number("landing_north_m", row), Some(landing.north_m));
521 assert_eq!(
522 number("ground_hit_speed_m_s", row),
523 Some(landing.ground_hit_speed_m_s)
524 );
525 }
526 Outcome::Failed { at, reason } => {
527 assert_eq!(word("outcome", row), "failed");
528 assert_eq!(word("failed_at", row), "flight");
529 assert_eq!(*at, FailedAt::Flight);
530 assert_eq!(word("reason", row), *reason);
531 assert_eq!(number("apogee_m", row), None);
532 assert_eq!(word("termination", row), "");
533 }
534 }
535 }
536 assert_eq!(names.iter().filter(|n| n.starts_with("stage_")).count(), 2);
538 assert!(!names.iter().any(|n| n.starts_with("part_")));
539 }
540
541 #[derive(Debug, PartialEq)]
543 enum Cell {
544 Integer(u64),
545 Number(Option<u64>),
546 Word(String),
547 }
548
549 fn expected_row(sample: &Sample, parts: usize) -> Vec<(String, Cell)> {
552 use hpr_sim::Termination;
553 let number = |value: Option<f64>| Cell::Number(value.map(f64::to_bits));
554 let word = |text: &str| Cell::Word(text.to_owned());
555 let draw = &sample.draw;
556 let summary = sample.summary();
557 let (outcome, failed_at, reason) = match &sample.outcome {
558 Outcome::Flown { .. } => ("flown", "", String::new()),
559 Outcome::Failed { at, reason } => (
560 "failed",
561 match at {
562 FailedAt::Inputs => "inputs",
563 FailedAt::Flight => "flight",
564 },
565 reason.clone(),
566 ),
567 };
568 let mut row = vec![
569 ("index".to_owned(), Cell::Integer(sample.index)),
570 ("outcome".to_owned(), word(outcome)),
571 ("failed_at".to_owned(), word(failed_at)),
572 ("reason".to_owned(), Cell::Word(reason)),
573 ("drag_scale".to_owned(), number(Some(draw.drag_scale))),
574 (
575 "wind_speed_scale".to_owned(),
576 number(Some(draw.wind_speed_scale)),
577 ),
578 ("wind_turn_rad".to_owned(), number(Some(draw.wind_turn_rad))),
579 (
580 "rail_elevation_offset_rad".to_owned(),
581 number(Some(draw.rail_elevation_offset_rad)),
582 ),
583 (
584 "rail_azimuth_offset_rad".to_owned(),
585 number(Some(draw.rail_azimuth_offset_rad)),
586 ),
587 ];
588 for (i, (mass, cg)) in draw.dry_mass_scale.iter().zip(&draw.cg_shift_m).enumerate() {
589 row.push((
590 format!("stage_{}_dry_mass_scale", i + 1),
591 number(Some(*mass)),
592 ));
593 row.push((format!("stage_{}_cg_shift_m", i + 1), number(Some(*cg))));
594 }
595 for i in 0..draw.impulse_scale.len() {
596 row.push((
597 format!("motor_{}_impulse_scale", i + 1),
598 number(Some(draw.impulse_scale[i])),
599 ));
600 row.push((
601 format!("motor_{}_burn_time_scale", i + 1),
602 number(Some(draw.burn_time_scale[i])),
603 ));
604 row.push((
605 format!("motor_{}_ejection_delay_offset_s", i + 1),
606 number(Some(draw.ejection_delay_offset_s[i])),
607 ));
608 }
609 for (i, lag) in draw.deployment_lag_offset_s.iter().enumerate() {
610 row.push((
611 format!("device_{}_deployment_lag_offset_s", i + 1),
612 number(Some(*lag)),
613 ));
614 }
615 let termination = summary.map_or("", |s| match s.termination {
616 Termination::GroundHit => "ground_hit",
617 Termination::Separated => "separated",
618 other => panic!("{other:?} isn't flown here"),
619 });
620 row.push(("termination".to_owned(), word(termination)));
621 let peak = |pick: fn(&FlightSummary) -> Option<f64>| number(summary.and_then(pick));
622 row.push((
623 "apogee_m".to_owned(),
624 number(summary.and_then(|s| s.apogee.map(|a| a.height_above_ground_m))),
625 ));
626 row.push((
627 "apogee_time_s".to_owned(),
628 number(summary.and_then(|s| s.apogee.map(|a| a.time_s))),
629 ));
630 row.push((
631 "rail_exit_speed_m_s".to_owned(),
632 peak(|s| s.rail_exit_speed_m_s.as_ref().map(|p| p.value)),
633 ));
634 row.push((
635 "max_speed_m_s".to_owned(),
636 peak(|s| s.max_speed_m_s.as_ref().map(|p| p.value)),
637 ));
638 row.push((
639 "max_mach".to_owned(),
640 peak(|s| s.max_mach.as_ref().map(|p| p.value)),
641 ));
642 row.push((
643 "max_dynamic_pressure_pa".to_owned(),
644 peak(|s| s.max_dynamic_pressure_pa.as_ref().map(|p| p.value)),
645 ));
646 row.push((
647 "max_acceleration_m_s2".to_owned(),
648 peak(|s| s.max_acceleration_m_s2.as_ref().map(|p| p.value)),
649 ));
650 row.push((
651 "max_descent_acceleration_m_s2".to_owned(),
652 peak(|s| s.max_descent_acceleration_m_s2.as_ref().map(|p| p.value)),
653 ));
654 row.push((
655 "max_deployment_airspeed_m_s".to_owned(),
656 peak(|s| s.max_deployment_airspeed_m_s.as_ref().map(|p| p.value)),
657 ));
658 row.push((
659 "min_static_margin_cal".to_owned(),
660 peak(|s| s.min_static_margin_cal.as_ref().map(|p| p.value)),
661 ));
662 row.push((
663 "min_flight_margin_cal".to_owned(),
664 peak(|s| s.min_flight_margin_cal.as_ref().map(|p| p.value)),
665 ));
666 row.push((
667 "max_angle_of_attack_rad".to_owned(),
668 peak(|s| s.max_angle_of_attack_rad.as_ref().map(|p| p.value)),
669 ));
670 let landing_of = |body: usize| {
673 summary.and_then(|s| s.body_landings.iter().find(|l| l.body == Some(body)))
674 };
675 let nose = summary.and_then(|s| match s.termination {
676 Termination::Separated => landing_of(0),
677 _ => s.landing.as_ref(),
678 });
679 let field = |pick: fn(&Landing) -> f64| number(nose.map(pick));
680 row.push(("landing_time_s".to_owned(), field(|l| l.time_s)));
681 row.push(("landing_east_m".to_owned(), field(|l| l.east_m)));
682 row.push(("landing_north_m".to_owned(), field(|l| l.north_m)));
683 row.push(("landing_distance_m".to_owned(), field(|l| l.distance_m)));
684 row.push(("landing_latitude_deg".to_owned(), field(|l| l.latitude_deg)));
685 row.push((
686 "landing_longitude_deg".to_owned(),
687 field(|l| l.longitude_deg),
688 ));
689 row.push((
690 "ground_hit_speed_m_s".to_owned(),
691 field(|l| l.ground_hit_speed_m_s),
692 ));
693 for part in 1..=parts {
694 let landing = landing_of(part);
695 let field = |pick: fn(&Landing) -> f64| number(landing.map(pick));
696 row.push((format!("part_{part}_landing_time_s"), field(|l| l.time_s)));
697 row.push((format!("part_{part}_landing_east_m"), field(|l| l.east_m)));
698 row.push((format!("part_{part}_landing_north_m"), field(|l| l.north_m)));
699 row.push((
700 format!("part_{part}_ground_hit_speed_m_s"),
701 field(|l| l.ground_hit_speed_m_s),
702 ));
703 }
704 let flags: Vec<&str> = summary.map_or_else(Vec::new, |s| {
705 let mach = s.max_mach.map_or(0.0, |p| p.value);
706 let aoa = s.max_angle_of_attack_rad.map_or(0.0, |p| p.value);
707 let powered = s.min_powered_static_margin_cal.map_or(0.0, |p| p.value);
708 let moment = s.max_powered_moment_slope_per_rad.map_or(0.0, |p| p.value);
709 let mut flags = Vec::new();
710 if powered < 0.0 {
711 flags.push("unstable_under_power");
712 } else if moment > 0.0 {
713 flags.push("unstable_without_margin");
714 }
715 if mach > hpr_sim::envelope::VALIDATED_MACH {
716 flags.push("beyond_validated_range");
717 }
718 if aoa > hpr_sim::envelope::HIGH_ANGLE_OF_ATTACK_RAD {
719 flags.push("high_angle_of_attack");
720 }
721 if mach > hpr_sim::envelope::CORE_BAND_MACH {
722 flags.push("outside_core_band");
723 }
724 flags
725 });
726 row.push(("flags".to_owned(), Cell::Word(flags.join(";"))));
727 row
728 }
729
730 fn table_row(table: &RunTable, row: usize) -> Vec<(String, Cell)> {
732 table
733 .columns()
734 .iter()
735 .map(|column| {
736 let cell = match &column.values {
737 Values::Integers(values) => Cell::Integer(values[row]),
738 Values::Numbers(values) => Cell::Number(values[row].map(f64::to_bits)),
739 Values::Text(values) => Cell::Word(values[row].clone()),
740 };
741 (column.name.clone(), cell)
742 })
743 .collect()
744 }
745
746 #[test]
751 fn every_column_is_its_own_field() {
752 let mut run = run();
753 let mut flown = 0;
754 for sample in &mut run.samples {
755 let draw = &mut sample.draw;
756 draw.dry_mass_scale.push(1.11);
757 draw.cg_shift_m.push(-0.012);
758 draw.impulse_scale.push(0.97);
759 draw.burn_time_scale.push(1.04);
760 draw.ejection_delay_offset_s.push(0.3);
761 draw.deployment_lag_offset_s.push(0.21);
762 let Outcome::Flown { summary } = &mut sample.outcome else {
763 continue;
764 };
765 flown += 1;
766 let landing = summary.landing.unwrap();
767 let part = |body: usize, shift: f64| Landing {
768 body: Some(body),
769 time_s: landing.time_s + 10.0 * shift,
770 east_m: landing.east_m + shift,
771 north_m: landing.north_m - 2.0 * shift,
772 ground_hit_speed_m_s: landing.ground_hit_speed_m_s + 0.5 * shift,
773 ..landing
774 };
775 summary.body_landings = vec![part(1, 1.0)];
776 if flown % 2 == 0 {
777 summary.termination = hpr_sim::Termination::Separated;
780 summary.landing = None;
781 summary.body_landings = vec![part(0, 3.0), part(1, 1.0), part(2, 2.0)];
782 }
783 if flown == 1 {
784 summary.max_mach.as_mut().unwrap().value = 3.0;
785 }
786 if flown == 3 {
787 summary.max_angle_of_attack_rad.as_mut().unwrap().value = 0.5;
788 }
789 }
790 assert!(flown >= 4, "{flown} flown");
791 let table = RunTable::new(&run);
792 for (row, sample) in run.samples.iter().enumerate() {
793 assert_eq!(table_row(&table, row), expected_row(sample, 2), "row {row}");
794 }
795 let flags = table.column("flags").unwrap();
796 let Values::Text(flags) = &flags.values else {
797 panic!("flags aren't words");
798 };
799 assert!(
800 flags
801 .iter()
802 .any(|f| f == "beyond_validated_range;outside_core_band")
803 );
804 assert!(flags.iter().any(|f| f == "high_angle_of_attack"));
805 }
806
807 #[test]
810 fn words_are_quoted_and_non_finite_numbers_refused() {
811 assert_eq!(quoted("plain words"), "plain words");
812 assert_eq!(quoted("a, b"), "\"a, b\"");
813 assert_eq!(quoted("say \"hi\""), "\"say \"\"hi\"\"\"");
814 assert_eq!(quoted("two\r\nlines"), "\"two\r\nlines\"");
815 let table = RunTable {
816 rows: 1,
817 columns: vec![Column {
818 name: "x".to_owned(),
819 values: Values::Numbers(vec![Some(f64::NAN)]),
820 }],
821 };
822 assert!(matches!(
823 table.csv(),
824 Err(AnalysisError::Domain { what, value }) if what.contains("run's table") && value.is_nan()
825 ));
826 }
827
828 #[test]
830 fn names_are_in_snake_case() {
831 assert_eq!(snake_name("GroundHit"), "ground_hit");
832 assert_eq!(
833 snake_name("BeyondEnvelope { mach: 3.6 }"),
834 "beyond_envelope"
835 );
836 assert_eq!(snake_name("Separated"), "separated");
837 }
838}