Skip to main content

hpr_analysis/
table.rs

1//! A Monte Carlo [`Run`] as a table: one row a sample, in index order, and one column an input it
2//! drew or a number its flight came to. `hpr mc` writes it as CSV ([`RunTable::csv`]), each
3//! number in the shortest form that reads back to the same bits, so a program reading the file
4//! gets the run's own numbers.
5//!
6//! The columns, in order:
7//!
8//! - `index`, a whole number, then `outcome` (`flown` or `failed`), `failed_at` (`inputs` or `flight`, empty for
9//!   a flown sample) and `reason` (the error, empty for a flown sample): [`Sample`], [`Outcome`].
10//! - What the sample drew ([`Draw`]): `drag_scale`, `wind_speed_scale`, `wind_turn_rad`,
11//!   `rail_elevation_offset_rad` and `rail_azimuth_offset_rad`; then for each stage `n`, counted
12//!   from 1 at the nose, `stage_n_dry_mass_scale` and `stage_n_cg_shift_m`; for each motor of the
13//!   flown configuration, `motor_n_impulse_scale`, `motor_n_burn_time_scale` and
14//!   `motor_n_ejection_delay_offset_s`; for each recovery device, `device_n_deployment_lag_offset_s`.
15//! - What a flown sample's flight came to ([`FlightSummary`]), empty for a failed sample or a
16//!   number its flight doesn't have: `termination`; `apogee_m` (height above the ground) and
17//!   `apogee_time_s`; the peaks' values `rail_exit_speed_m_s`, `max_speed_m_s`, `max_mach`,
18//!   `max_dynamic_pressure_pa`, `max_acceleration_m_s2`, `max_descent_acceleration_m_s2` (the
19//!   opening shock), `max_deployment_airspeed_m_s`, `min_static_margin_cal`,
20//!   `min_flight_margin_cal` and `max_angle_of_attack_rad`; the landing of the part that keeps
21//!   the nose ([`FlightSummary::nose_landing`]), `landing_time_s`,
22//!   `landing_east_m`, `landing_north_m`, `landing_distance_m`, `landing_latitude_deg`,
23//!   `landing_longitude_deg` and `ground_hit_speed_m_s`; for each part `n` that a separation
24//!   dropped, `part_n_landing_time_s`, `part_n_landing_east_m`, `part_n_landing_north_m` and
25//!   `part_n_ground_hit_speed_m_s`; and `flags`, the flags the flight raised ([`EnvelopeFlag`]:
26//!   the operating envelope's, and one for a rocket unstable under power), by name, separated by
27//!   `;`.
28
29use 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
36/// One of a draw's lists, by stage, motor or device.
37type DrawList = fn(&Draw) -> &Vec<f64>;
38
39/// One number of a landing.
40type LandingField = fn(&Landing) -> f64;
41
42/// One column of a [`RunTable`]: its name, with its unit where it has one, and a value for each
43/// sample.
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45pub struct Column {
46    /// The column's name, such as `apogee_m`.
47    pub name: String,
48    /// Its values, one a sample in index order.
49    pub values: Values,
50}
51
52/// A column's values.
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54#[serde(tag = "kind", content = "values", rename_all = "snake_case")]
55pub enum Values {
56    /// Whole numbers: the samples' indices.
57    Integers(Vec<u64>),
58    /// Numbers, `None` where a sample has none.
59    Numbers(Vec<Option<f64>>),
60    /// Words, empty where a sample has none.
61    Text(Vec<String>),
62}
63
64/// A run as a table: the module's docs list its columns.
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66pub struct RunTable {
67    rows: usize,
68    columns: Vec<Column>,
69}
70
71impl RunTable {
72    /// `run` as a table. The lists of a draw (stages, motors, devices) take their lengths from the
73    /// first sample, as every sample of a run draws the same; the parts' landings run to the
74    /// highest part that landed in any sample.
75    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        // Stage by stage, each stage's two lists together; then motor by motor.
138        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    /// The number of rows: the run's samples.
282    pub fn rows(&self) -> usize {
283        self.rows
284    }
285
286    /// The columns, in the module docs' order.
287    pub fn columns(&self) -> &[Column] {
288        &self.columns
289    }
290
291    /// The column called `name`, if there is one.
292    pub fn column(&self, name: &str) -> Option<&Column> {
293        self.columns.iter().find(|column| column.name == name)
294    }
295
296    /// The table as CSV (RFC 4180): a header of the columns in words with their units in
297    /// brackets, as a recording's ([`hpr_sim::export::csv_header`]: `apogee [m]` for the column
298    /// `apogee_m`), then one line a sample, lines ending in CRLF. A number is written in the shortest form that reads back to the same
299    /// bits (Rust's `{:?}`, which Python's `float` and every IEEE-correct reader read exactly);
300    /// a missing number is an empty cell. Words are quoted where they hold a comma, a quote or
301    /// a line break, a quote doubled.
302    ///
303    /// # Errors
304    ///
305    /// [`AnalysisError::Domain`] for a number that isn't finite.
306    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
341/// `text` as a CSV cell: quoted, its quotes doubled, where it holds a comma, a quote or a line
342/// break (RFC 4180 ยง2).
343fn quoted(text: &str) -> String {
344    if text.contains([',', '"', '\r', '\n']) {
345        format!("\"{}\"", text.replace('"', "\"\""))
346    } else {
347        text.to_owned()
348    }
349}
350
351/// A Rust name in snake case: `GroundHit` is `ground_hit`. Only the name before any `{` or `(`
352/// of a variant's fields is kept.
353fn 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
372/// A flag's name, as it is serialized.
373fn 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    /// The cells of RFC 4180 `text`, line by line: quoted cells unquoted, their quotes undoubled.
391    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    /// A run with flown and failed samples, its every dispersion on.
420    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    /// M4.6a's bullet: every number of the run reads back from the CSV to the same bits, a
431    /// missing one is an empty cell, and every word reads back as it was, quoted or not.
432    #[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        // The header gives each column in words with its unit in brackets, as the product
443        // system's `data.md` writes one; written out by hand, so a unit read wrongly fails.
444        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        // The values are the run's own.
481        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        // One stage, one motor, one device, and no part dropped.
537        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    /// A cell as the table should hold it, worked out from the sample's own fields.
542    #[derive(Debug, PartialEq)]
543    enum Cell {
544        Integer(u64),
545        Number(Option<u64>),
546        Word(String),
547    }
548
549    /// Every column of `sample`'s row, by name, read field by field from the sample, not through
550    /// the table's code; `parts` is how many dropped parts the run has.
551    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        // A split with nothing left to burn leaves the flight's landing empty: part 0's is the
671        // nose's.
672        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    /// The table's row `row`, by name.
731    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    /// M4.6a, found in review: every column holds its own field, in the documented order, on a
747    /// run with two stages, two motors, two devices, two dropped parts with their own landings,
748    /// a flight split with nothing left to burn (its landing part 0's), envelope flags, and
749    /// failed flights. Each part's and each list's values differ, so a swap of two columns fails.
750    #[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                // Split with nothing left to burn: part 0's landing is the nose's, and the
778                // second part landed too.
779                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    /// A cell with a comma, a quote or a line break is quoted, its quotes doubled; a number that
808    /// isn't finite is refused, not written.
809    #[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    /// A Rust name in snake case, its fields dropped.
829    #[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}