Skip to main content

sim_cli/
report.rs

1//! `fit [MACHINE] --dataset DIR --report OUT`: one self-contained report of a dataset folder (datasets/README.md). Every
2//! trace recording is replayed on the dataset's machine and config (`machine.simulator`, `machine.config`, or the
3//! command line's); the first is the one the free values are fitted on, the others are checks nothing was set from.
4//! Every frequency response's resonance is compared with the model's first mode. Written to OUT: `report.md`,
5//! `summary.csv` (torque and following error per recording and motor), `fit.csv` (the table of `fit`), `modes.csv`,
6//! `bounds.csv`, per recording `<file>-overlay.csv` and per motor `<file>-torque-<motor>.svg`.
7
8use super::{Args, Failure, fit_rows, io, machine_and_config, read};
9use sim_components::dataset::contents;
10use sim_components::identify::parse_sweep;
11use sim_components::import::{Mapping, decode, import};
12use sim_components::motor_fit::two_mass;
13use sim_components::report::Plot;
14use sim_components::trace::{differences, overlay_csv, replay};
15use sim_core::Translations;
16use std::path::Path;
17
18pub(super) fn run(args: &Args, tr: &Translations) -> Result<(), Failure> {
19    let (Some(dir), Some(out)) = (args.option("--dataset"), args.option("--report")) else {
20        return Err(Failure("cli-usage", String::new()));
21    };
22    let (dir, out) = (Path::new(dir), Path::new(out));
23    let data = contents(dir).map_err(|e| Failure("dataset-problem", e))?;
24    // The machine and config of the command line, else the dataset's.
25    let mut words = args.0.clone();
26    if args.positional(1).is_none() && args.option("--machine-file").is_none() {
27        if data.simulator.is_empty() {
28            return Err(Failure("cli-usage", String::new()));
29        }
30        // A word after the last option's value is the machine, wherever the command stands.
31        words.push(data.simulator.clone());
32    }
33    let config = if args.option("--config").is_none() && !data.config.is_empty() {
34        words.extend(["--config".into(), dir.join(&data.config).to_string_lossy().into_owned()]);
35        data.config.clone()
36    } else {
37        args.option("--config").map_or("the machine's default".into(), |c| c.to_string())
38    };
39    // The dataset's own settings first, so that the command line's come after them and win.
40    let at = words.iter().position(|w| w == "--set").unwrap_or(words.len());
41    let settings: Vec<String> = data.set.iter().flat_map(|s| ["--set".to_string(), s.clone()]).collect();
42    words.splice(at..at, settings);
43    let base = Args(words);
44    let (entry, cfg) = machine_and_config(&base)?;
45    let machine = (entry.build)(&cfg)?;
46    let motors = machine.motors().to_vec();
47    std::fs::create_dir_all(out).map_err(io)?;
48    let write = |name: &str, text: &str| std::fs::write(out.join(name), text).map_err(io);
49
50    let measured_or_not = if data.synthetic { "synthetic (made by a simulator)" } else { "measured" };
51    let mut md = format!(
52        "# Fit report: {}\n\n{}\n\nDataset `{}`, {measured_or_not}, licence {}. Machine `{}` with the config {config}{}. \
53         Written by `sim-cli fit --dataset datasets/{} --report DIR` (sim-cli {}).\n\n",
54        data.id,
55        data.title,
56        data.id,
57        data.license,
58        entry.id,
59        if data.set.is_empty() { String::new() } else { format!(" and `{}`", data.set.join("`, `")) },
60        data.id,
61        env!("CARGO_PKG_VERSION"),
62    );
63
64    // Each trace replayed: its position setpoints through the simulator, the torques compared.
65    let traces: Vec<_> = data.recordings.iter().filter(|r| r.test != "frequency-response").collect();
66    let mut summary = String::from(
67        "recording,role,motor,rows,peak_torque_nm,torque_rms_nm,torque_worst_nm,following_error_rms_rad,following_error_worst_rad\n",
68    );
69    md += "## Torque, measured against the replay\n\nThe recording's position setpoints replayed (`sim-cli replay`); \
70           the difference between measured and simulated motor torque, as RMS and as the worst single sample, and as a \
71           share of the recording's peak measured torque. The first recording is the one fitted on, the others are \
72           checks: nothing was set from them.\n\n\
73           | Recording | Role | Motor | Rows | Peak torque | RMS difference | Worst difference | Following error, RMS difference |\n\
74           | --- | --- | --- | --- | --- | --- | --- | --- |\n";
75    let mut plots = String::new();
76    for (i, r) in traces.iter().enumerate() {
77        let role = if i == 0 { "fit" } else { "check" };
78        let text =
79            decode(&std::fs::read(dir.join(&r.file)).map_err(|e| Failure("cli-error-io", format!("{}: {e}", r.file)))?);
80        let measured = import(&text, &Mapping::parse(&read(&dir.join(&r.map).to_string_lossy())?)?)?.trace;
81        if measured.motors.len() != motors.len() {
82            return Err(Failure(
83                "error-import-map",
84                format!("{}: {} [[motor]] for {} motors", r.map, measured.motors.len(), motors.len()),
85            ));
86        }
87        let simulated = replay(entry, &cfg, &measured)?;
88        let stem = r.file.rsplit_once('.').map_or(r.file.as_str(), |(s, _)| s);
89        for (k, d) in differences(&measured, &simulated).into_iter().enumerate() {
90            let id = motors[k].id;
91            let peak = measured.motors[k].torque.iter().fold(0.0_f64, |a, v| a.max(v.abs()));
92            let rows = measured.time.len();
93            summary += &format!(
94                "{},{role},{id},{rows},{peak:.6e},{:.6e},{:.6e},{:.6e},{:.6e}
95",
96                r.file, d[0], d[1], d[2], d[3]
97            );
98            let share = |v: f64| 100.0 * v / peak;
99            md += &format!(
100                "| {} | {role} | {id} | {rows} | {peak:.3} N m | {:.3} N m, {:.1} % | {:.3} N m, {:.0} % | {:.2e} rad |\n",
101                r.file,
102                d[0],
103                share(d[0]),
104                d[1],
105                share(d[1]),
106                d[2]
107            );
108            let svg = format!("{stem}-torque-{id}.svg");
109            let series = |name: &str, torque: &[f64]| {
110                (name.to_string(), measured.time.iter().zip(torque).map(|(t, v)| [*t, *v]).collect(), false)
111            };
112            let plot = Plot {
113                title: format!("{}, motor {id}: torque", r.file),
114                x_label: "time [s]".into(),
115                y_label: "torque [N m]".into(),
116                series: vec![
117                    series("measured", &measured.motors[k].torque),
118                    series("simulated", &simulated.motors[k].torque),
119                ],
120            };
121            write(&svg, &plot.svg())?;
122            plots += &format!("![{}, motor {id}]({svg})\n\n", r.file);
123        }
124        let ids: Vec<&str> = motors.iter().map(|m| m.id).collect();
125        write(&format!("{stem}-overlay.csv"), &overlay_csv(&ids, &measured, &simulated))?;
126    }
127    md += "\n";
128    md += &plots;
129    write("summary.csv", &summary)?;
130
131    // The free values fitted on the first recording, against what the config gives on its replay.
132    if let Some(first) = traces.first() {
133        let mut fit_args = base.0.clone();
134        for (option, file) in [("--trace", &first.file), ("--map", &first.map)] {
135            fit_args.extend([option.into(), dir.join(file).to_string_lossy().into_owned()]);
136        }
137        let mut table = Vec::new();
138        let (advice, result, _) = fit_rows(&Args(fit_args), tr, &mut table, None)?;
139        result?;
140        let table = String::from_utf8_lossy(&table).into_owned();
141        write("fit.csv", &table)?;
142        md += &format!(
143            "## Fitted on {}\n\nEach value as the config gives it (the same estimate on the config's replay of the \
144             recording) and as the measurement gives it, with the standard error; the last column is how many standard \
145             errors apart the two are (within 2: the config agrees with the measurement).\n\n\
146             | Quantity | Of | Config | Fitted | Standard error | Apart |\n| --- | --- | --- | --- | --- | --- |\n",
147            first.file
148        );
149        for line in table.lines().skip(1) {
150            let cells: Vec<&str> = line.split(',').collect();
151            // The sixth column is the unit (`fit_rows`); the table was empty while this took five.
152            let [quantity, of, config, fitted, error, _] = cells[..] else { continue };
153            let number = |s: &str| s.parse::<f64>().ok();
154            let shown = |s: &str| number(s).map_or("-".into(), |v| format!("{v:.4}"));
155            let apart = match (number(config), number(fitted), number(error)) {
156                (Some(c), Some(f), Some(e)) if e > 0.0 => format!("{:.1}", (f - c).abs() / e),
157                _ => "-".into(),
158            };
159            md += &format!(
160                "| {quantity} | {of} | {} | {} | {} | {apart} |\n",
161                shown(config),
162                shown(fitted),
163                number(error).map_or("-".into(), |v| format!("{v:.3}"))
164            );
165        }
166        if !advice.is_empty() {
167            md += "\nWhat the fit says to change in the config:\n\n";
168            advice.iter().for_each(|line| md += &format!("- {line}\n"));
169        }
170        md += "\n";
171    }
172
173    // The config's error bands: is each value inside the bounds it claims?
174    let bounds = sim_components::analysis::bounds(&cfg)?;
175    let mut csv = String::from("key,config,low,high,inside\n");
176    md += "## The config's bounds\n\nThe `[bounds]` of the config, the error band each value is claimed to lie in. The \
177           fitted values above are lumped at the axis (several keys in one), so they are not mapped onto these keys.\n\n\
178           | Key | Config | Low | High | Inside |\n| --- | --- | --- | --- | --- |\n";
179    for (key, low, high) in &bounds {
180        let value = cfg.f64(key)?;
181        let inside = if (*low..=*high).contains(&value) { "yes" } else { "**no**" };
182        csv += &format!("{key},{value:e},{low:e},{high:e},{}\n", inside == "yes");
183        md += &format!("| `{key}` | {value} | {low} | {high} | {inside} |\n");
184    }
185    if bounds.is_empty() {
186        md += "| (none) | | | | |\n";
187    }
188    write("bounds.csv", &csv)?;
189    md += "\n";
190
191    // Each measured frequency response's resonance against the model's first mode at the config's start pose.
192    let sweeps: Vec<_> = data.recordings.iter().filter(|r| r.test == "frequency-response").collect();
193    if !sweeps.is_empty() {
194        let model = machine.modes(&cfg.f64s("start.pose")?).first().map(|m| m.hz);
195        let model_text = model.map_or("-".into(), |hz| format!("{hz:.1} Hz"));
196        let mut csv = String::from("recording,measured_hz,measured_error_hz,model_hz\n");
197        md += "## First mode\n\nThe two-mass model fitted to each measured frequency response (`sim-cli identify \
198               --sweep`): its resonance with the standard error, against the model's first mode at the config's start \
199               pose (`sim-cli modes`).\n\n| Recording | Measured | Model | Model − measured |\n| --- | --- | --- | --- |\n";
200        for r in sweeps {
201            let fitted = two_mass(&parse_sweep(&read(&dir.join(&r.file).to_string_lossy())?)?).map(|m| m.resonance);
202            let (hz, error) = fitted.map_or((f64::NAN, f64::NAN), |e| (e.value, e.error));
203            csv += &format!("{},{hz:.6e},{error:.3e},{:.6e}\n", r.file, model.unwrap_or(f64::NAN));
204            let measured = if hz.is_nan() { "no resonance found".into() } else { format!("{hz:.1} ± {error:.1} Hz") };
205            let apart = match model {
206                Some(m) if !hz.is_nan() => format!("{:+.1} %", 100.0 * (m - hz) / hz),
207                _ => "-".into(),
208            };
209            md += &format!("| {} | {measured} | {model_text} | {apart} |\n", r.file);
210        }
211        write("modes.csv", &csv)?;
212        md += "\n";
213    }
214    md += "## Files\n\n`summary.csv` the torque table, `fit.csv` the fit, `bounds.csv` the bounds, `modes.csv` the first \
215           mode (with frequency responses), per recording `*-overlay.csv` measured and simulated torque, speed and \
216           following error row by row, and `*-torque-*.svg` the torque plots.\n";
217    write("report.md", &md)?;
218    println!("{}", tr.tr_arg("fit-report-written", &out.join("report.md").to_string_lossy()));
219    Ok(())
220}