Skip to main content

sim_cli/
main.rs

1//! Batch front end: runs the core as fast as the CPU allows and writes CSV.
2//! Every message comes from the translation files; see `cli-help-*` there for the commands.
3
4use sim_components::analysis::{
5    SWEEP_POINTS, analyse_cycle_with, analyse_trajectory_with, bandwidth, closed_loop_response,
6    default_sweep_amplitude, frequency_sweep, log_spaced, step_response,
7};
8use sim_components::identify::{BELT_STIFFNESS_KEY, fit_joints, fit_move_stiffness, fit_rigid, fit_sweep, parse_sweep};
9use sim_components::import::{Imported, Mapping, decode, import};
10use sim_components::motor_fit::{
11    Estimate, Identified, TwoMass, frequency_response, ringing, two_mass, two_mass_from_ringing,
12};
13use sim_components::trace::{Trace, TraceError, differences, overlay_csv};
14use sim_components::{Command, Sim};
15use sim_core::{Bound, Config, ConfigError, ConfigHint, MachineEntry, Translations};
16use sim_machines::{LANGUAGES, MACHINES, find, translations};
17use std::io::Write;
18use std::sync::atomic::{AtomicBool, Ordering};
19
20mod help;
21mod report;
22
23static I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
24
25/// A failure as a translation key and its argument.
26struct Failure(&'static str, String);
27
28impl From<ConfigError> for Failure {
29    fn from(e: ConfigError) -> Self {
30        if let ConfigError::Bounded(bound, path) = &e {
31            *BOUNDED.lock().unwrap_or_else(|p| p.into_inner()) = Some((*bound, path.clone()));
32        }
33        Failure(e.key(), e.detail().into())
34    }
35}
36
37/// The limit and path of the last value a shared reader refused, wherever it was read (the machine, the analyses, the
38/// verdicts), for `config_help`: a `Failure` carries key and path only.
39static BOUNDED: std::sync::Mutex<Option<(Bound, String)>> = std::sync::Mutex::new(None);
40
41impl From<TraceError> for Failure {
42    fn from(e: TraceError) -> Self {
43        Failure(e.key, e.detail)
44    }
45}
46
47fn texts(lang: &str, entry: &MachineEntry) -> Translations {
48    let mut tr = translations(lang, entry);
49    I18N.iter().filter(|(l, _)| *l == lang).for_each(|(_, text)| tr.add(text));
50    tr
51}
52
53/// Command-line arguments: positional words, and `--name value` options that may repeat.
54struct Args(Vec<String>);
55
56/// Options every command takes, each with a value.
57const COMMON: [&str; 12] = [
58    "--machine-file",
59    "--config",
60    "--catalog",
61    "--motor",
62    "--supply",
63    "--gearbox",
64    "--drive",
65    "--belt",
66    "--axis",
67    "--set",
68    "--out",
69    "--lang",
70];
71/// Options without a value.
72const FLAGS: [&str; 10] = [
73    "--cycle",
74    "--time-optimal",
75    "--bands",
76    "--worst",
77    "--axes",
78    "--nominal",
79    "--stiffness",
80    "--shapes",
81    "--no-notch",
82    "--help",
83];
84/// The ways to say what the machine should do: one at most.
85const MOTIONS: [&str; 4] = ["--cycle", "--move", "--trajectory", "--path"];
86
87impl Args {
88    /// Refuses what would otherwise be ignored without a word: an option the command does not know (a
89    /// misspelt one), an option without its value, and two motions at once. `known` are the command's own
90    /// options beside the common ones.
91    fn check(&self, known: &[&str]) -> Result<(), Failure> {
92        let mut words = self.0.iter().map(String::as_str).peekable();
93        while let Some(word) = words.next() {
94            if !word.starts_with("--") {
95                continue;
96            }
97            if !COMMON.contains(&word) && !known.contains(&word) {
98                return Err(Failure("cli-error-unknown-option", word.into()));
99            }
100            if !FLAGS.contains(&word) && words.next_if(|value| !value.starts_with("--")).is_none() {
101                return Err(Failure("cli-error-missing-value", word.into()));
102            }
103        }
104        let motions: Vec<&str> = MOTIONS.into_iter().filter(|motion| self.flag(motion)).collect();
105        if motions.len() > 1 {
106            return Err(Failure("cli-error-conflict", motions.join(" ")));
107        }
108        match self.option("--lang") {
109            Some(lang) if !LANGUAGES.contains(&lang) => {
110                Err(Failure("cli-error-bad-argument", format!("--lang {lang}")))
111            }
112            _ => Ok(()),
113        }
114    }
115
116    fn options(&self, name: &str) -> Vec<&str> {
117        self.0.windows(2).filter(|w| w[0] == name).map(|w| w[1].as_str()).collect()
118    }
119    fn option(&self, name: &str) -> Option<&str> {
120        self.options(name).pop()
121    }
122    fn flag(&self, name: &str) -> bool {
123        self.0.iter().any(|a| a == name)
124    }
125    fn number(&self, name: &str) -> Result<Option<f64>, Failure> {
126        // "inf" and "nan" parse as numbers, and a run for an infinite time never returns.
127        let finite = |v: &str| v.parse().ok().filter(|number: &f64| number.is_finite());
128        self.option(name)
129            .map(|v| finite(v).ok_or_else(|| Failure("cli-error-bad-argument", format!("{name} {v}"))))
130            .transpose()
131    }
132    /// The n-th word that is neither an option nor an option's value.
133    fn positional(&self, n: usize) -> Option<&str> {
134        let mut words = Vec::new();
135        let mut i = 0;
136        while i < self.0.len() {
137            if self.0[i].starts_with("--") {
138                i += if FLAGS.contains(&self.0[i].as_str()) { 1 } else { 2 };
139            } else {
140                words.push(self.0[i].as_str());
141                i += 1;
142            }
143        }
144        words.get(n).copied()
145    }
146}
147
148fn main() {
149    let args = Args(std::env::args().skip(1).collect());
150    if args.flag("--version") || args.flag("-V") {
151        println!("sim-cli {}", env!("CARGO_PKG_VERSION"));
152        return;
153    }
154    let lang = args.option("--lang").filter(|l| LANGUAGES.contains(l)).unwrap_or("en");
155    // `help [TOPIC]`, `COMMAND --help` and `--help`: the help of the command, or the overview, on standard output.
156    let command = args.positional(0).filter(|word| !word.starts_with('-'));
157    if command == Some("help") || args.flag("--help") || args.flag("-h") {
158        let tr = texts(lang, MACHINES[0]);
159        let topic = if command == Some("help") { args.positional(1) } else { command };
160        match help::text(&tr, topic) {
161            Some(text) => println!("{text}"),
162            None => {
163                eprintln!("{}", tr.tr_arg("cli-usage-unknown", topic.unwrap_or_default()));
164                std::process::exit(2);
165            }
166        }
167        return;
168    }
169    let entry = machine(&args).unwrap_or(MACHINES[0]);
170    let tr = texts(lang, entry);
171    if let Err(Failure(key, arg)) = dispatch(&args, &tr) {
172        if key == "cli-usage" {
173            // Not everything: the help of the command that was meant, or with no command the overview.
174            match command {
175                Some(name) if help::COMMANDS.contains(&name) => eprintln!("{}", tr.tr_arg("cli-usage-hint", name)),
176                Some(name) => eprintln!("{}", tr.tr_arg("cli-usage-unknown", name)),
177                None => eprintln!("{}", help::text(&tr, None).unwrap_or_default()),
178            }
179        } else {
180            eprintln!("{}{}", tr.tr_arg(key, &arg), config_help(&args, &tr, key, &arg));
181        }
182        std::process::exit(2);
183    }
184    // The table is printed in full first; the exit code then says that a check failed (2 stays for usage and config).
185    if CHECK_FAILED.load(Ordering::Relaxed) {
186        std::process::exit(1);
187    }
188}
189
190/// What `Config::hint` has to add to a config error, as a suffix of its message: the nearest path (a misspelt `--set`
191/// path) or the value of the refused one. The config is built again for it, with the assignments that apply; an empty
192/// suffix where there is nothing to add or the config cannot be built.
193fn config_help(args: &Args, tr: &Translations, key: &str, arg: &str) -> String {
194    let error = match key {
195        "error-config-missing" => ConfigError::Missing(arg.into()),
196        "error-config-unknown" => ConfigError::Unknown(arg.into()),
197        "error-config-invalid" => ConfigError::Invalid(arg.into()),
198        "error-config-type" => ConfigError::Type(arg.into()),
199        _ => return String::new(),
200    };
201    let Ok((entry, named)) = named_config(args) else { return String::new() };
202    let Ok(mut cfg) = sim_components::catalog::resolve(entry, &named) else {
203        return String::new();
204    };
205    for assignment in args.options("--set") {
206        // The refused one is what the error is about.
207        let _ = sim_components::set_config_text(entry, &mut cfg, assignment);
208    }
209    // With the limit it broke where a shared reader refused it (a check made elsewhere keeps the plain value).
210    let error = match BOUNDED.lock().unwrap_or_else(|p| p.into_inner()).take() {
211        Some((bound, path)) if key == "error-config-invalid" && path == arg => ConfigError::Bounded(bound, path),
212        _ => error,
213    };
214    match sim_components::config_hint(entry, &cfg, &error) {
215        Some(ConfigHint::Nearest(path)) => format!(" {}", tr.tr_arg("cli-hint-nearest", &path)),
216        Some(ConfigHint::Value(value)) => format!(" {}", tr.tr_arg("cli-hint-value", &value)),
217        Some(ConfigHint::Bounded(value, bound)) => {
218            let key = match bound {
219                Bound::Positive => "cli-hint-positive",
220                Bound::NonNegative => "cli-hint-non-negative",
221                Bound::Number => "cli-hint-number",
222            };
223            format!(" {}", tr.tr_arg(key, &value))
224        }
225        None => String::new(),
226    }
227}
228
229/// Set by `judged` when a command that judges printed a failing row.
230static CHECK_FAILED: AtomicBool = AtomicBool::new(false);
231
232/// The result word of a judged row; a failing one makes the exit code 1.
233fn judged(ok: bool) -> &'static str {
234    if !ok {
235        CHECK_FAILED.store(true, Ordering::Relaxed);
236    }
237    if ok { "ok" } else { "FAIL" }
238}
239
240/// On the error stream, after a table of verdicts: that a result of it is not finite, and what to run to see the loop.
241fn tell_not_finite<'a>(tr: &Translations, verdicts: impl IntoIterator<Item = &'a sim_components::analysis::Verdict>) {
242    if sim_components::analysis::any_not_finite(verdicts) {
243        eprintln!("{}", tr.tr("verdict-not-finite"));
244    }
245}
246
247/// The options of a command beside the common ones.
248fn command_options(command: Option<&str>) -> &'static [&'static str] {
249    match command {
250        Some("run") => &[
251            "--move",
252            "--cycle",
253            "--trajectory",
254            "--path",
255            "--time-optimal",
256            "--time",
257            "--disable-at",
258            "--stop-at",
259            "--stop-category",
260            "--every",
261        ],
262        Some("stop") => &["--category", "--points", "--path", "--time-optimal"],
263        Some("accuracy") => &["--points", "--repeats", "--dwell"],
264        Some("analyze") => &["--trajectory", "--path", "--time-optimal", "--points", "--breakdown", "--budget"],
265        Some("sweep") => &["--from", "--to", "--count", "--amplitude"],
266        Some("optimise") => &["--runs", "--nominal", "--pareto", "--worst", "--path", "--time-optimal"],
267        Some("search") => &[
268            "--vendor",
269            "--series",
270            "--gearboxes",
271            "--axes",
272            "--motor-id",
273            "--drives",
274            "--rank-by",
275            "--prices",
276            "--weights",
277            "--robust",
278            "--path",
279            "--time-optimal",
280        ],
281        Some("transmission") => &["--key", "--from", "--to", "--count", "--gearboxes"],
282        Some("compare-kinematics") => &["--machines", "--vendor", "--series", "--gearboxes", "--drives", "--rank-by"],
283        Some("verdicts") => &["--bands", "--samples", "--seed", "--worst", "--path", "--time-optimal"],
284        Some("sensitivity") => &["--delta", "--group", "--method", "--samples", "--seed", "--result"],
285        Some("step") => &["--axis-index", "--size", "--time"],
286        Some("bode") => &["--axis-index", "--from", "--to", "--count", "--amplitude"],
287        Some("tuning") => &["--size", "--amplitude"],
288        Some("margins") => &["--bands"],
289        Some("tune") => &["--phase-margin", "--gain-margin", "--no-notch"],
290        Some("modes") => &["--axis-index", "--points", "--shapes"],
291        Some("workspace") => &["--z", "--points"],
292        Some("replay") => &["--trace", "--map", "--tolerance"],
293        Some("fit") => &[
294            "--trace",
295            "--map",
296            "--sweep",
297            "--sweep-motor",
298            "--amplitude",
299            "--stiffness",
300            "--stiffness-key",
301            "--dataset",
302            "--report",
303            "--within",
304            "--write",
305            "--sigmas",
306        ],
307        Some("identify") => &[
308            "--trace",
309            "--map",
310            "--from",
311            "--to",
312            "--sweep",
313            "--step-from",
314            "--step-to",
315            "--motor-inertia",
316            "--overlay",
317        ],
318        Some("compare") => &["--effect", "--signal", "--differences"],
319        Some("fmu") => &["--binary", "--fmi"],
320        Some("parameters") => &["--family"],
321        Some("report") => &["--bands"],
322        _ => &[],
323    }
324}
325
326fn dispatch(args: &Args, tr: &Translations) -> Result<(), Failure> {
327    args.check(command_options(args.positional(0)))?;
328    if let Some(dir) = args.option("--catalog") {
329        sim_components::catalog::use_directory(std::path::Path::new(dir))?;
330    }
331    match args.positional(0) {
332        Some("list") => {
333            let lang = args.option("--lang").unwrap_or("en");
334            let mut out = std::io::stdout().lock();
335            for entry in MACHINES {
336                // A closed pipe (`list | head`) ends the listing quietly.
337                if writeln!(out, "{}\t{}", entry.id, translations(lang, entry).tr(entry.key)).is_err() {
338                    break;
339                }
340            }
341            Ok(())
342        }
343        Some("run") => run(args, tr),
344        Some("analyze") => analyze(args, tr),
345        Some("sweep") => sweep(args),
346        Some("sensitivity") => sensitivity(args, tr),
347        Some("verdicts") => verdicts(args, tr),
348        Some("search") => search(args, tr),
349        Some("transmission") => transmission(args, tr),
350        Some("compare-kinematics") => compare_kinematics(args, tr),
351        Some("optimise") => optimise(args, tr),
352        Some("step") => step(args),
353        Some("bode") => bode(args),
354        Some("tuning") => tuning(args),
355        Some("margins") => margins(args, tr),
356        Some("tune") => tune(args, tr),
357        Some("modes") => modes(args),
358        Some("workspace") => workspace(args),
359        Some("replay") => replay(args, tr),
360        Some("fit") => fit(args, tr),
361        Some("identify") => identify(args, tr),
362        Some("check-dataset") => check_dataset(args, tr),
363        Some("compare") => compare(args),
364        Some("fmu") => fmu(args),
365        Some("parameters") => parameters(args, tr),
366        Some("report") => report(args, tr),
367        Some("stop") => stop(args, tr),
368        Some("accuracy") => accuracy(args, tr),
369        _ => Err(Failure("cli-usage", String::new())),
370    }
371}
372
373/// The machine `--machine-file FILE` defines (docs/machine-files.md), or else the registered one named after the
374/// command. A file's errors name the file and the line.
375fn machine(args: &Args) -> Result<&'static MachineEntry, Failure> {
376    if let Some(path) = args.option("--machine-file") {
377        return sim_machines::load_file(std::path::Path::new(path)).map_err(|e| {
378            let at = e.line.map_or(String::new(), |line| format!(":{line}"));
379            Failure(e.error.key(), format!("{}{at}: {}", e.file.display(), e.error.detail()))
380        });
381    }
382    let id = args.positional(1).ok_or(Failure("cli-usage", String::new()))?;
383    find(id).ok_or(Failure("cli-error-unknown-machine", id.into()))
384}
385
386/// The machine named on the command line with its config: the default, or `--config FILE`, with the
387/// parts it names or `--motor`, `--supply`, `--gearbox`, `--drive`, `--belt` and `--axis` name put in from the catalogue, then every
388/// `--set path=value` applied on top.
389fn machine_and_config(args: &Args) -> Result<(&'static MachineEntry, Config), Failure> {
390    let (entry, mut cfg) = named_config(args)?;
391    before_parts(args, entry, &mut cfg)?;
392    // Only a catalogue drive is derated; the search puts one in for every candidate. After `before_parts`, which sets
393    // the installation conditions `--set` names.
394    if args.positional(0) != Some("search")
395        && let Some(key) = sim_components::catalog::condition_without_drive(&cfg)
396    {
397        return Err(Failure("error-drive-derating-none", key.to_string()));
398    }
399    // Parts by name from the catalogue, here and not only in the simulator, so that single values can be set on top.
400    let mut cfg = sim_components::catalog::resolve(entry, &cfg)?;
401    for assignment in args.options("--set") {
402        sim_components::set_config_text(entry, &mut cfg, assignment)?;
403    }
404    Ok((entry, cfg))
405}
406
407/// The `--set` assignments of a drive's installation conditions, which are read where its part is put in (it is derated
408/// there): set before the parts are resolved, as the others are after.
409fn before_parts(args: &Args, entry: &MachineEntry, cfg: &mut Config) -> Result<(), Failure> {
410    for assignment in args.options("--set") {
411        let path = assignment.split('=').next().unwrap_or("").trim();
412        if sim_components::catalog::DRIVE_CONDITION_KEYS.contains(&path) {
413            sim_components::set_config_text(entry, cfg, assignment)?;
414        }
415    }
416    Ok(())
417}
418
419/// The machine and its config with the parts the command line names in `[parts]`, before they are resolved.
420fn named_config(args: &Args) -> Result<(&'static MachineEntry, Config), Failure> {
421    let entry = machine(args)?;
422    let mut cfg = match args.option("--config") {
423        Some(path) => sim_components::load_config(entry, &read(path)?)?,
424        None => entry.config(),
425    };
426    // `sweep --motor N` picks a motor of the machine by number; an article number is never a plain number.
427    let motor = args.option("--motor").filter(|m| m.parse::<usize>().is_err());
428    let named = [
429        ("motor", motor),
430        ("motor_supply", args.option("--supply")),
431        ("gearbox", args.option("--gearbox")),
432        ("drive", args.option("--drive")),
433        ("belt", args.option("--belt")),
434        ("axis", args.option("--axis")),
435    ];
436    for (key, name) in named {
437        if let Some(name) = name {
438            cfg.set_text(&format!("parts.{key} = {name:?}"))?;
439        }
440    }
441    Ok((entry, cfg))
442}
443
444fn start(args: &Args, tr: &Translations) -> Result<Sim, Failure> {
445    let (entry, cfg) = machine_and_config(args)?;
446    let mut sim = Sim::new(entry, &cfg)?;
447    for v in &sim.limit_violations {
448        let motor = tr.tr(sim.machine.motors()[v.motor].key);
449        eprintln!("{}", tr.tr_arg(v.key, &format!("{motor}: {:.4} > {:.4}", v.needed, v.allowed)));
450    }
451    let command = if args.flag("--cycle") {
452        Some(Command::StartCycle)
453    } else if let Some(target) = args.option("--move") {
454        let bad = || Failure("cli-error-bad-argument", format!("--move {target}"));
455        Some(Command::MoveTo(target.split(',').map(|v| v.trim().parse().map_err(|_| bad())).collect::<Result<_, _>>()?))
456    } else {
457        poses(args, &sim, &cfg, tr)?.map(Command::Trajectory)
458    };
459    // Where the config has obstacles: what the motion keeps from them as planned, before it runs.
460    let planned = match &command {
461        Some(Command::StartCycle) => sim_components::collision::check_cycle(entry, &cfg)?,
462        Some(Command::MoveTo(target)) => sim.check_plan(&[sim.control.planned_pos().to_vec(), target.clone()]),
463        Some(Command::Trajectory(points)) => {
464            sim.check_plan(&points.iter().map(|(_, pose)| pose.clone()).collect::<Vec<_>>())
465        }
466        _ => None,
467    };
468    tell_plan(tr, planned, sim.min_clearance);
469    if let Some(command) = command {
470        sim.command(command).map_err(|e| Failure(e.key, String::new()))?;
471    }
472    Ok(sim)
473}
474
475/// With `--path FILE` (and `--time-optimal`) of `verdicts`, `search` and `optimise`: the config with that path in place
476/// of the cycle (`sim::with_path`), so that every run they make runs the path. The path is planned once here, so that a
477/// file that cannot be read or a path that cannot be planned is said with its line before any run.
478fn path_instead(args: &Args, entry: &MachineEntry, cfg: Config) -> Result<Config, Failure> {
479    let Some(file) = args.option("--path") else { return Ok(cfg) };
480    let text = read(file)?;
481    let sim = Sim::new(entry, &cfg)?;
482    let speed = sim_components::program::orientation_speed_of(&cfg)?;
483    sim_components::program::read_with(file, &text, sim.machine.axes(), sim.control.planned_pos(), speed)
484        .map_err(|e| Failure(e.key, format!("{file}:{}: {}", e.line, e.detail)))?;
485    let cfg = sim_components::sim::with_path(&cfg, file, &text, args.flag("--time-optimal"))?;
486    Sim::new(entry, &cfg)?.plan_configured_path().transpose().map_err(|e| Failure(e.key, file.to_string()))?;
487    Ok(cfg)
488}
489
490/// The poses at times to run: those of `--trajectory FILE`, or the lines and arcs of `--path FILE` (format:
491/// see `sim_components::path`; or a G-code, KRL, RAPID or robot CSV program, see `sim_components::program`) with their
492/// timing planned here, within the axis limits or with `--time-optimal` as fast as the motors allow. Where transition
493/// curves or an arc beside its stated end take the planned path off the lines and arcs of the file
494/// (`profile.path_tolerance_m`), the error stream says by how much (for a program of moves at one feed).
495fn poses(args: &Args, sim: &Sim, cfg: &Config, tr: &Translations) -> Result<Option<Vec<(f64, Vec<f64>)>>, Failure> {
496    let unreadable = |file: &str, line: String| Failure("cli-error-bad-argument", format!("{file}: {line}"));
497    if let Some(file) = args.option("--trajectory") {
498        return sim_components::path::parse_trajectory(&read(file)?).map(Some).map_err(|line| unreadable(file, line));
499    }
500    let Some(file) = args.option("--path") else { return Ok(None) };
501    let speed = sim_components::program::orientation_speed_of(cfg)?;
502    let runs =
503        sim_components::program::read_with(file, &read(file)?, sim.machine.axes(), sim.control.planned_pos(), speed)
504            .map_err(|e| Failure(e.key, format!("{file}:{}: {}", e.line, e.detail)))?;
505    let refused = |e: sim_components::CommandError| Failure(e.key, String::new());
506    // A program with feeds is planned run by run (`Sim::plan_program`); one run at the axes' limits as a path file is.
507    let Some(pieces) = sim_components::program::as_path(&runs) else {
508        return sim.plan_program(&runs, args.flag("--time-optimal")).map(Some).map_err(refused);
509    };
510    let deviation = sim.path_deviation(pieces, args.flag("--time-optimal")).map_err(refused)?;
511    // Not below what the figure can show: an arc with decimally rounded end coordinates is some 10 nm off.
512    let shown = format!("{:.4}", deviation * 1e3);
513    if shown != "0.0000" {
514        eprintln!("{}", tr.tr_arg("path-deviation", &shown));
515    }
516    sim.plan_path(pieces, args.flag("--time-optimal")).map(Some).map_err(refused)
517}
518
519fn pose_text(pose: &[f64]) -> String {
520    pose.iter().map(|x| format!("{x:.4}")).collect::<Vec<_>>().join(" ")
521}
522
523/// On the error stream: how the cycle's measured pass was started (effects.thermal_warm_start), by the largest change of
524/// a rise over it (`analysis::WarmStart::change`); `None`: from cold. Not converged, with `repeat`
525/// (`analysis::WarmStart::repeat`) beyond the tolerance, the cause: the cycle's motion does not repeat itself.
526fn tell_start(tr: &Translations, change: Option<f64>, repeat: Option<f64>) {
527    let tolerance = sim_components::analysis::WARM_START_TOLERANCE_K;
528    let (key, arg) = match (change, repeat) {
529        (None, _) => ("cli-thermal-start-cold", String::new()),
530        (Some(c), _) if c <= tolerance => ("cli-thermal-start-warm", format!("{c:.3}")),
531        (Some(_), Some(r)) if r > tolerance => ("cli-thermal-start-aperiodic", format!("{r:.3}")),
532        (Some(c), _) => ("cli-thermal-start-unsettled", format!("{c:.3}")),
533    };
534    eprintln!("{}", tr.tr_arg(key, &arg));
535}
536
537/// On the error stream: the least clearance of a planned path to the obstacles, in mm, and its first pose in contact.
538/// Nothing without obstacles. Then, apart from it, the least clearance between the machine's own parts that are not
539/// joined, in mm, which two and at which pose, and (when it is below the clearance or a contact) that it fails; nothing
540/// where the machine has no two parts to look at.
541fn tell_plan(tr: &Translations, check: Option<sim_components::collision::PlanCheck>, limit: f64) {
542    use sim_components::collision::Body;
543    let Some(check) = check else { return };
544    if check.nearest.is_some() {
545        eprintln!("{}", tr.tr_arg("cli-planned-clearance", &format!("{:.1}", check.clearance * 1e3)));
546    }
547    if let Some(pose) = &check.contact {
548        eprintln!("{}", tr.tr_arg("cli-planned-contact", &pose_text(pose)));
549    }
550    if let Some(own) = &check.own {
551        let name = |body: Body| match body {
552            Body::Box(i) => tr.tr_arg("cli-part-box", &(i + 1).to_string()),
553            Body::Capsule(i) => tr.tr_arg("cli-part-capsule", &(i + 1).to_string()),
554        };
555        let detail = format!(
556            "{:.1} mm, {} / {}, {}",
557            own.clearance * 1e3,
558            name(own.bodies[0]),
559            name(own.bodies[1]),
560            pose_text(&own.pose)
561        );
562        let key = if check.own_fails(limit) { "cli-planned-own-fails" } else { "cli-planned-own" };
563        eprintln!("{}", tr.tr_arg(key, &detail));
564    }
565}
566
567/// On the error stream: the least clearance of the run so far to the obstacles, in mm, and its first contact with one,
568/// with effects.crash its largest contact force and its impact energy; and the drives' first trip (effects.
569/// drive_monitoring): which monitor of which motor when, each drive's fault reaction, and the stopping distances.
570fn tell_run(tr: &Translations, sim: &Sim) {
571    if !sim.obstacles.is_empty() {
572        eprintln!("{}", tr.tr_arg("cli-run-clearance", &format!("{:.1}", sim.least_clearance * 1e3)));
573    }
574    if let Some(c) = &sim.contact {
575        let detail =
576            format!("{}: {:.4} s, {:.4} /s, {}", sim.obstacles[c.obstacle].name, c.time, c.speed, pose_text(&c.pose));
577        eprintln!("{}", tr.tr_arg("cli-run-contact", &detail));
578        if sim.crash {
579            let detail = format!("{:.1} N, {:.1} N, {:.4} J", c.peak_force, sim.contact_force, c.impact_energy);
580            eprintln!("{}", tr.tr_arg("cli-run-impact", &detail));
581        }
582    }
583    if let Some(f) = &sim.control.fault {
584        let motors = sim.machine.motors();
585        let reactions: Vec<String> =
586            (0..motors.len()).map(|k| tr.tr_arg(sim.control.fault_reaction(k).key(), motors[k].id)).collect();
587        let detail =
588            format!("{}: {}, {:.4} s; {}", tr.tr(f.monitor.key()), motors[f.drive].id, f.time, reactions.join(", "));
589        eprintln!("{}", tr.tr_arg("cli-run-fault", &detail));
590        let stopped = f.stopped.map_or_else(|| "-".to_string(), |t| format!("{t:.4} s"));
591        eprintln!("{}", tr.tr_arg("cli-run-stopping", &format!("{} ({stopped})", pose_text(&f.stopping))));
592    }
593}
594
595fn read(path: &str) -> Result<String, Failure> {
596    std::fs::read_to_string(path).map_err(|e| Failure("cli-error-io", format!("{path}: {e}")))
597}
598
599/// `replay <machine> --trace FILE`: the position setpoints of a drive trace run through the simulator.
600/// Prints per motor how far simulated torque and following error are from the measured ones; `--out FILE`
601/// also writes measured and simulated torque, speed and following error side by side, one line per row
602/// of the trace. With `--tolerance NAME=LIMIT,...` (the names are the table's columns) the twin is judged instead: one
603/// row per motor and limit, `motor,quantity,value,limit,result`, exit code 1 where a value is above its limit.
604fn replay(args: &Args, tr: &Translations) -> Result<(), Failure> {
605    const QUANTITIES: [&str; 4] =
606        ["torque_rms_nm", "torque_peak_nm", "following_error_rms_rad", "following_error_peak_rad"];
607    let limits = match args.option("--tolerance") {
608        None => None,
609        Some(text) => {
610            let bad = || Failure("cli-error-bad-argument", format!("--tolerance {text}"));
611            let mut limits = [None; 4];
612            for part in text.split(',') {
613                let (name, value) = part.split_once('=').ok_or_else(bad)?;
614                let at = QUANTITIES.iter().position(|q| *q == name.trim()).ok_or_else(bad)?;
615                limits[at] =
616                    Some(value.trim().parse::<f64>().ok().filter(|v| v.is_finite() && *v >= 0.0).ok_or_else(bad)?);
617            }
618            Some(limits)
619        }
620    };
621    let (entry, cfg) = machine_and_config(args)?;
622    let machine = (entry.build)(&cfg)?;
623    let motors = machine.motors().to_vec();
624    let measured = load_trace(args, &motors, tr)?.trace;
625    let simulated = sim_components::trace::replay(entry, &cfg, &measured)?;
626    match limits {
627        None => {
628            println!("motor,torque_rms_nm,torque_peak_nm,following_error_rms_rad,following_error_peak_rad");
629            for (motor, d) in motors.iter().zip(differences(&measured, &simulated)) {
630                println!("{},{:.6e},{:.6e},{:.6e},{:.6e}", motor.id, d[0], d[1], d[2], d[3]);
631            }
632        }
633        Some(limits) => {
634            println!("motor,quantity,value,limit,result");
635            for (motor, d) in motors.iter().zip(differences(&measured, &simulated)) {
636                for (q, name) in QUANTITIES.iter().enumerate() {
637                    // A difference that is not a number is no pass.
638                    if let Some(limit) = limits[q] {
639                        println!("{},{name},{:.6e},{limit:.6e},{}", motor.id, d[q], judged(d[q] <= limit));
640                    }
641                }
642            }
643        }
644    }
645    if args.option("--out").is_some() {
646        let mut out = output(args, "--out")?;
647        let ids: Vec<&str> = motors.iter().map(|m| m.id).collect();
648        out.write_all(overlay_csv(&ids, &measured, &simulated).as_bytes()).map_err(io)?;
649        out.flush().map_err(io)?;
650    }
651    Ok(())
652}
653
654/// `fit <machine>`: what a measurement says the config should be, as a table of the config's value, the
655/// fitted one and its standard error, and on the error stream what to change in the config. With
656/// `--trace FILE` the rigid values of each axis, or on a machine whose motors do not turn in proportion to its
657/// axes or whose inertia changes with the pose (`trace::per_axis_fit`: the delta, the SCARA, the arm) the payload's
658/// factor and per motor added inertia, friction and constant torque, on an arm or SCARA per link its mass factor and
659/// first moment where the trace tells them from the motors' values, with what each value combines, what the trace
660/// hardly excites and the pairs it cannot tell apart, and where the payload was picked or dropped during the trace
661/// (`payload_step_s`) its factor before and after;
662/// with `--stiffness` also the factor on the stiffness at `--stiffness-key` (the belts' by default) from the trace's
663/// own moves; with `--sweep FILE` (a frequency response as `sweep` writes it, taken on motor `--sweep-motor` with
664/// `--amplitude`) the load's resonance on the belt.
665/// With `--dataset DIR --report OUT` the whole report of a dataset folder instead (`report::run`).
666/// With `--within N` the twin is judged: each row whose fitted value is more than N standard errors from the config's
667/// says FAIL (columns `apart` and `result`), exit code 1. With `--write FILE` the config is written with the fitted
668/// values that are one key of it, and `[bounds]` of `--sigmas` standard errors (2 by default) about them.
669fn fit(args: &Args, tr: &Translations) -> Result<(), Failure> {
670    let positive = |name: &str| -> Result<Option<f64>, Failure> {
671        let value = args.number(name)?;
672        match value.filter(|v| *v <= 0.0) {
673            Some(v) => Err(Failure("cli-error-bad-argument", format!("{name} {v}"))),
674            None => Ok(value),
675        }
676    };
677    let (within, sigmas) = (positive("--within")?, positive("--sigmas")?);
678    if args.option("--dataset").is_some() || args.option("--report").is_some() {
679        // The report has no judgement or file of its own to write.
680        if within.is_some() || sigmas.is_some() || args.option("--write").is_some() {
681            return Err(Failure("cli-usage", String::new()));
682        }
683        return report::run(args, tr);
684    }
685    if sigmas.is_some() && args.option("--write").is_none() {
686        return Err(Failure("cli-error-missing-value", "--write".into()));
687    }
688    let mut out = output(args, "--out")?;
689    let (advice, result, rows) = fit_rows(args, tr, &mut *out, within)?;
690    out.flush().map_err(io)?;
691    advice.iter().for_each(|line| eprintln!("{line}"));
692    // Nothing is written from a fit that failed.
693    match args.option("--write") {
694        Some(path) if result.is_ok() => write_fit(args, tr, &rows, path, sigmas.unwrap_or(2.0)),
695        _ => result,
696    }
697}
698
699/// One value of `fit` that has a config counterpart and a standard error: what `--within` judges and `--write` writes.
700struct FitRow {
701    quantity: String,
702    of: String,
703    config: f64,
704    fitted: f64,
705    error: f64,
706}
707
708/// The table of `fit` as it is written: with `--within` two columns more, how many standard errors the fitted value is
709/// from the config's and the result (`ok`, `FAIL`, or `not judged` where the row has no standard error or no config's value).
710struct FitTable<'a> {
711    out: &'a mut dyn Write,
712    within: Option<f64>,
713    rows: Vec<FitRow>,
714}
715
716impl FitTable<'_> {
717    fn header(&mut self) -> Result<(), Failure> {
718        // "units" is the last of the six columns: the unit of the row's numbers, empty where there is none to name.
719        let columns = if self.within.is_some() { ",apart,result" } else { "" };
720        writeln!(self.out, "quantity,of,config,fitted,standard_error,units{columns}").map_err(io)
721    }
722
723    /// `line` is the row's six columns; `values` its config's value, the fitted one and the standard error, where it has them.
724    fn row(&mut self, line: String, quantity: &str, of: &str, values: Option<[f64; 3]>) -> Result<(), Failure> {
725        self.note(quantity, of, values);
726        let Some(limit) = self.within else { return writeln!(self.out, "{line}").map_err(io) };
727        let apart = values.filter(|[c, f, e]| c.is_finite() && f.is_finite() && *e > 0.0 && e.is_finite());
728        let judgement = match apart {
729            Some([c, f, e]) => {
730                let apart = (f - c).abs() / e;
731                format!("{apart:.2},{}", judged(apart <= limit))
732            }
733            None => ",not judged".into(),
734        };
735        writeln!(self.out, "{line},{judgement}").map_err(io)
736    }
737
738    fn note(&mut self, quantity: &str, of: &str, values: Option<[f64; 3]>) {
739        if let Some([config, fitted, error]) = values {
740            self.rows.push(FitRow { quantity: quantity.into(), of: of.into(), config, fitted, error });
741        }
742    }
743}
744
745/// The table of `fit` written to `out`, what to change in the config, the failure that came after the table, and the
746/// values the table has a config counterpart and standard error for.
747fn fit_rows(
748    args: &Args,
749    tr: &Translations,
750    out: &mut dyn Write,
751    within: Option<f64>,
752) -> Result<(Vec<String>, Result<(), Failure>, Vec<FitRow>), Failure> {
753    let (entry, cfg) = machine_and_config(args)?;
754    let machine = (entry.build)(&cfg)?;
755    if args.option("--trace").is_none() && args.option("--sweep").is_none() {
756        return Err(Failure("cli-usage", String::new()));
757    }
758    let (mut advice, mut result) = (Vec::new(), Ok(()));
759    let mut table = FitTable { out, within, rows: Vec::new() };
760    table.header()?;
761    if args.option("--trace").is_some() && !sim_components::trace::per_axis_fit(machine.as_ref()) {
762        let measured = load_trace(args, machine.motors(), tr)?.trace;
763        match fit_joints(entry, &cfg, &measured)? {
764            Some(fit) => {
765                for v in &fit.values {
766                    let line = format!("{},{},{:.6e},{:.6e},{:.3e},", v.quantity, v.of, v.config, v.fitted, v.error);
767                    table.row(line, v.quantity, &v.of, Some([v.config, v.fitted, v.error]))?;
768                }
769                // One step's row is of `payload`, several are numbered as their factors after them are.
770                for (j, (time, error)) in fit.payload_steps.iter().enumerate() {
771                    let of =
772                        if fit.payload_steps.len() == 1 { "payload".to_string() } else { format!("payload {}", j + 1) };
773                    table.row(format!("payload_step_s,{of},,{time:.6e},{error:.3e},s"), "payload_step_s", &of, None)?;
774                }
775                advice.extend(fit.advice().iter().map(|(key, detail)| tr.tr_arg(key, detail)));
776            }
777            None => advice.push(tr.tr("fit-joints-skipped").to_string()),
778        }
779    } else if args.option("--trace").is_some() {
780        let measured = load_trace(args, machine.motors(), tr)?.trace;
781        for (axis, fit) in machine.axes().iter().zip(fit_rigid(entry, &cfg, &measured)?) {
782            let Some(fit) = fit else {
783                advice.push(tr.tr_arg("fit-axis-skipped", axis.id));
784                continue;
785            };
786            for (q, name) in
787                ["moved_mass_kg", "viscous_friction_n_s_m", "coulomb_friction_n", "constant_force_n"].iter().enumerate()
788            {
789                let line = format!(
790                    "{name},{},{:.6e},{:.6e},{:.3e},{}",
791                    axis.id, fit.config[q], fit.fitted[q], fit.error[q], fit.units[q]
792                );
793                table.row(line, name, axis.id, Some([fit.config[q], fit.fitted[q], fit.error[q]]))?;
794            }
795            // The friction beyond its sliding level, where the trace shows it (`identify::friction_details`).
796            for d in &fit.details {
797                let line = format!("{},{},{:.6e},{:.6e},{:.3e},", d.quantity, axis.id, d.config, d.fitted, d.error);
798                table.row(line, d.quantity, axis.id, Some([d.config, d.fitted, d.error]))?;
799            }
800            // A payload picked or dropped: its time, then the change of the payload's factor there (a change, not a
801            // value of the config: not judged).
802            for (time, time_error, change, error) in &fit.payload_steps {
803                let line = format!("payload_step_s,{},,{time:.6e},{time_error:.3e},s", axis.id);
804                table.row(line, "payload_step_s", axis.id, None)?;
805                let line = format!("payload_factor_change,{},0,{change:.6e},{error:.3e},", axis.id);
806                table.row(line, "payload_factor_change", axis.id, None)?;
807            }
808            advice.extend(fit.advice(axis.id).iter().map(|(key, detail)| tr.tr_arg(key, detail)));
809        }
810    }
811    if args.flag("--stiffness") {
812        let measured = load_trace(args, machine.motors(), tr)?.trace;
813        let key = args.option("--stiffness-key").unwrap_or(BELT_STIFFNESS_KEY);
814        match fit_move_stiffness(entry, &cfg, &measured, key) {
815            Ok(fit) => {
816                let line = format!("stiffness_factor,{key},{:.6e},{:.6e},{:.3e},", 1.0, fit.factor, fit.error);
817                table.row(line, "stiffness_factor", key, Some([1.0, fit.factor, fit.error]))?;
818                table.row(format!("ringing_rms_nm,{key},,{:.6e},,", fit.ringing), "ringing_rms_nm", key, None)?;
819                let line = format!("ringing_left_rms_nm,{key},,{:.6e},,", fit.residual);
820                table.row(line, "ringing_left_rms_nm", key, None)?;
821                let (key, detail) = fit.advice();
822                advice.push(tr.tr_arg(key, &detail));
823            }
824            // A failure like any other, after what else the trace gave has been written.
825            Err(e) => result = Err(Failure(e.key, e.detail)),
826        }
827    }
828    if let Some(path) = args.option("--sweep") {
829        let measured = parse_sweep(&read(path)?)?;
830        let motor = number(args, "--sweep-motor", 0.0)? as usize;
831        match fit_sweep(
832            entry,
833            &cfg,
834            motor,
835            &measured,
836            number(args, "--amplitude", default_sweep_amplitude(entry, &cfg)?)?,
837        )? {
838            Some(fit) => {
839                let (id, (config, fitted)) = (machine.motors()[motor].id, (fit.config, fit.fitted));
840                let line = format!(
841                    "resonance_hz,{id},{:.6e},{:.6e},{:.3e},Hz",
842                    config.frequency, fitted.frequency, fitted.frequency_error
843                );
844                table.row(
845                    line,
846                    "resonance_hz",
847                    id,
848                    Some([config.frequency, fitted.frequency, fitted.frequency_error]),
849                )?;
850                let line = format!("resonance_damping,{id},{:.6e},{:.6e},,", config.damping, fitted.damping);
851                table.row(line, "resonance_damping", id, None)?;
852                let (key, detail) = fit.advice();
853                advice.push(tr.tr_arg(key, &detail));
854            }
855            // A failure like any other, after what the trace gave has been written.
856            None => result = Err(Failure("fit-no-resonance", String::new())),
857        }
858    }
859    Ok((advice, result, table.rows))
860}
861
862/// `fit --write FILE`: the config as the command line gives it, with each fitted quantity that is exactly one key of it
863/// set to the fitted value and a `[bounds]` entry of `sigmas` standard errors either side of it. Only the factor on a
864/// stiffness (`--stiffness`) is one key; every other quantity of the table is the trace's value of what several keys
865/// make up (the moved mass of an axis, a friction that the motor, gearbox and guide share) or of none, and is named on
866/// the error stream with the reason, as is a key the file cannot take. The payload's factor of a joint fit is not
867/// written either: on a cycle that picks and places, the trace holds the payload part of the time, and the factor is a
868/// share of that time as much as of the mass (the delta's cycle with 4 kg against its 3 kg came out at 0.72 times the
869/// config's). Comments of the written file are not kept and its keys come in alphabetical order (`Config::to_text`).
870fn write_fit(args: &Args, tr: &Translations, rows: &[FitRow], path: &str, sigmas: f64) -> Result<(), Failure> {
871    let (entry, resolved) = machine_and_config(args)?;
872    // What the file holds: the config before the parts it names are put in, so that those stay named.
873    let (_, mut file) = named_config(args)?;
874    for assignment in args.options("--set") {
875        sim_components::set_config_text(entry, &mut file, assignment)?;
876    }
877    let mut written = Vec::new();
878    for row in rows {
879        let name = format!("{} {}", row.quantity, row.of);
880        if row.quantity != "stiffness_factor" {
881            eprintln!("{}", tr.tr_arg("cli-fit-write-lumped", &name));
882            continue;
883        }
884        // The factor and its error relative to the config's own, which is 1.
885        let (factor, error) = (row.fitted / row.config, row.error / row.config.abs());
886        match fitted_band(entry, &file, &resolved, &row.of, factor, error, sigmas) {
887            Ok(band) => written.push((row.of.clone(), band)),
888            Err(reason) => eprintln!("{}", tr.tr_arg(reason, &name)),
889        }
890    }
891    if written.is_empty() {
892        return Err(Failure("cli-fit-write-nothing", path.into()));
893    }
894    for (key, [value, low, high]) in &written {
895        sim_components::analysis::set_bounded(&mut file, key, *value)?;
896        let bound = format!("bounds.{key}");
897        // A bound the file has not got yet is added.
898        file.set_text_within(&format!("{bound} = [{low:?}, {high:?}]"), &file.clone(), &[bound.as_str()])?;
899    }
900    let text = file.to_text()?;
901    // What is written has to load again, with its bounds read.
902    let loaded = sim_components::load_config(entry, &text)?;
903    sim_components::analysis::bounds(&loaded)?;
904    std::fs::write(path, text).map_err(|e| Failure("cli-error-io", format!("{path}: {e}")))?;
905    eprintln!("{}", tr.tr_arg("cli-fit-write-done", path));
906    Ok(())
907}
908
909/// The value `factor` times that of `key` and its band `[low, high]` of `sigmas` times `error` (relative) either side,
910/// or the translation key of why it is not written: the file has no such key (`cli-fit-write-no-key`), a named part
911/// sets it (the file's value is not the one the fit used: `cli-fit-write-by-part`), or the fitted value or its error is
912/// not usable (`cli-fit-write-refused`). A value or bound the machine's readers refuse (a stiffness at or below 0) is
913/// pulled in to the nearest one they take.
914fn fitted_band(
915    entry: &'static MachineEntry,
916    file: &Config,
917    resolved: &Config,
918    key: &str,
919    factor: f64,
920    error: f64,
921    sigmas: f64,
922) -> Result<[f64; 3], &'static str> {
923    let (Ok(base), Ok(own)) = (resolved.f64(key), file.f64(key)) else { return Err("cli-fit-write-no-key") };
924    if (own - base).abs() > 1e-9 * base.abs() {
925        return Err("cli-fit-write-by-part");
926    }
927    let builds = |v: f64| {
928        let mut at = file.clone();
929        sim_components::analysis::set_bounded(&mut at, key, v).is_ok()
930            && sim_components::catalog::resolve(entry, &at).and_then(|r| (entry.build)(&r)).is_ok()
931    };
932    let value = base * factor;
933    if !(error.is_finite() && error > 0.0 && value.is_finite() && builds(value)) {
934        return Err("cli-fit-write-refused");
935    }
936    // Halving between the value and the bound found refused: the bound is the nearest one that builds.
937    let taken = |bound: f64| {
938        if builds(bound) {
939            return bound;
940        }
941        let (mut good, mut bad) = (value, bound);
942        for _ in 0..60 {
943            let middle = 0.5 * (good + bad);
944            if builds(middle) { good = middle } else { bad = middle }
945        }
946        good
947    };
948    let half = sigmas * base.abs() * error;
949    Ok([value, taken(value - half), taken(value + half)])
950}
951
952/// The trace named by `--trace`: through the mapping file `--map` (a vendor export; see
953/// docs/measurement-procedure.md), or without one in the simulator's own columns for `motors`. Where a
954/// machine is replayed or fitted, the mapping's motors have to be the machine's, in its order. How the export was
955/// read other than it says (lines skipped, a time without unit taken as ms) goes to stderr.
956fn load_trace(args: &Args, motors: &[sim_core::MotorInfo], tr: &Translations) -> Result<Imported, Failure> {
957    let path = args.option("--trace").ok_or(Failure("cli-usage", String::new()))?;
958    let text = decode(&std::fs::read(path).map_err(|e| Failure("cli-error-io", format!("{path}: {e}")))?);
959    Ok(match args.option("--map") {
960        Some(map) => {
961            let imported = import(&text, &Mapping::parse(&read(map)?)?)?;
962            if !motors.is_empty() && imported.trace.motors.len() != motors.len() {
963                return Err(Failure(
964                    "error-import-map",
965                    format!("{} [[motor]] for {} motors", imported.trace.motors.len(), motors.len()),
966                ));
967            }
968            imported.notes.iter().for_each(|(key, detail)| eprintln!("{}", tr.tr_arg(key, detail)));
969            imported
970        }
971        None => {
972            let trace = Trace::parse(&text, motors)?;
973            Imported {
974                ids: motors.iter().map(|m| m.id.to_string()).collect(),
975                torque_setpoints: vec![None; trace.motors.len()],
976                notes: Vec::new(),
977                trace,
978            }
979        }
980    })
981}
982
983/// One line of the `identify` table: quantity, motor, value, standard error and the 95 % interval.
984fn estimate_row(out: &mut dyn Write, name: &str, of: &str, e: Estimate) -> Result<(), Failure> {
985    let (low, high) = e.interval();
986    writeln!(out, "{name},{of},{:.6e},{:.3e},{low:.6e},{high:.6e}", e.value, e.error).map_err(io)
987}
988
989/// A value without an error (a fit quality), in the same table.
990fn value_row(out: &mut dyn Write, name: &str, of: &str, value: f64) -> Result<(), Failure> {
991    writeln!(out, "{name},{of},{value:.6e},,,").map_err(io)
992}
993
994fn two_mass_rows(out: &mut dyn Write, of: &str, m: &TwoMass) -> Result<(), Failure> {
995    let rows = [
996        ("total_inertia_kg_m2", m.total_inertia),
997        ("motor_side_inertia_kg_m2", m.motor_inertia),
998        ("load_side_inertia_kg_m2", m.load_inertia),
999        ("stiffness_nm_rad", m.stiffness),
1000        ("damping_nm_s_rad", m.damping),
1001        ("resonance_hz", m.resonance),
1002        ("anti_resonance_hz", m.anti_resonance),
1003    ];
1004    rows.into_iter().try_for_each(|(name, e)| estimate_row(out, name, of, e))
1005}
1006
1007/// `identify [MACHINE] --trace FILE [--map FILE]`: one motor's drive train from its own trace, with no
1008/// machine config: inertia, friction (Coulomb, viscous, Stribeck, LuGre presliding stiffness), constant
1009/// torque, and the lag and dead time from torque setpoint to torque (where mapped) and from position
1010/// setpoint to position. `--motor N` picks the motor (default 0). `--from HZ --to HZ` also computes the
1011/// frequency response torque to speed from the trace (which needs an excitation in it) and fits the
1012/// two-mass model to it; `--sweep FILE` fits it to a measured response instead. `--step-from S [--step-to S]`
1013/// fits the ringing of the speed after a torque step, and with `--motor-inertia KGM2` (rotor and what sits on
1014/// it) and the fitted total inertia the two-mass model. Every value with its standard error and 95 %
1015/// interval, and how well each model reproduces the trace; `--overlay FILE` writes measured and modelled
1016/// signals side by side. Without `--map` the trace is in the simulator's columns of MACHINE.
1017fn identify(args: &Args, tr: &Translations) -> Result<(), Failure> {
1018    if args.option("--trace").is_none() && args.option("--sweep").is_none() {
1019        return Err(Failure("cli-usage", String::new()));
1020    }
1021    let mut out = output(args, "--out")?;
1022    writeln!(out, "quantity,of,value,standard_error,ci95_low,ci95_high").map_err(io)?;
1023    let mut result = Ok(());
1024    let mut overlay: Vec<(String, Vec<f64>)> = Vec::new();
1025    let mut time = Vec::new();
1026    if args.option("--trace").is_some() {
1027        let motors = match args.option("--map") {
1028            Some(_) => Vec::new(),
1029            None => {
1030                let (entry, cfg) = machine_and_config(args)?;
1031                (entry.build)(&cfg)?.motors().to_vec()
1032            }
1033        };
1034        let imported = load_trace(args, &motors, tr)?;
1035        let k = number(args, "--motor", 0.0)? as usize;
1036        let (Some(m), Some(id)) = (imported.trace.motors.get(k), imported.ids.get(k)) else {
1037            return Err(Failure("cli-error-bad-argument", format!("--motor {k}")));
1038        };
1039        let t = &imported.trace.time;
1040        time.clone_from(t);
1041        let found = Identified::of(t, m, imported.torque_setpoints[k].as_deref());
1042        for (name, e) in found.estimates() {
1043            estimate_row(&mut *out, name, id, e)?;
1044        }
1045        for (name, value) in found.qualities() {
1046            value_row(&mut *out, name, id, value)?;
1047        }
1048        let has_setpoint = imported.torque_setpoints[k].is_some();
1049        if found.friction.is_none() {
1050            eprintln!("{}", tr.tr_arg("error-identify-friction", id));
1051        }
1052        if found.position_loop.is_none() || (has_setpoint && found.current_loop.is_none()) {
1053            eprintln!("{}", tr.tr_arg("error-identify-lag", id));
1054        }
1055        let total_inertia = found.friction.as_ref().map(|f| f.inertia);
1056        if let Some(f) = &found.friction {
1057            overlay.push(("torque_measured".into(), m.torque.clone()));
1058            overlay.push(("torque_model".into(), f.model.clone()));
1059        }
1060        for (name, lag, output) in
1061            [("current_loop", &found.current_loop, &m.torque), ("position_loop", &found.position_loop, &m.angle)]
1062        {
1063            if let Some(l) = lag {
1064                overlay.push((format!("{name}_measured"), output.clone()));
1065                overlay.push((format!("{name}_model"), l.model.clone()));
1066            }
1067        }
1068        if let (Some(from), Some(to)) = (args.number("--from")?, args.number("--to")?) {
1069            if !(from > 0.0 && to > from) {
1070                return Err(Failure("cli-error-bad-argument", format!("--from {from} --to {to}")));
1071            }
1072            match frequency_response(t, &m.torque, &m.speed, &log_spaced(from, to, SWEEP_POINTS)) {
1073                Some(response) => {
1074                    value_row(
1075                        &mut *out,
1076                        "response_lowest_coherence",
1077                        id,
1078                        response.iter().map(|(_, c)| *c).fold(1.0, f64::min),
1079                    )?;
1080                    let points: Vec<_> = response.into_iter().map(|(p, _)| p).collect();
1081                    match two_mass(&points) {
1082                        Some(model) => two_mass_rows(&mut *out, id, &model)?,
1083                        None => result = Err(Failure("error-identify-two-mass", String::new())),
1084                    }
1085                }
1086                None => result = Err(Failure("error-identify-response", String::new())),
1087            }
1088        }
1089        if let Some(from) = args.number("--step-from")? {
1090            match ringing(t, &m.speed, from, number(args, "--step-to", t[t.len() - 1])?) {
1091                Some(r) => {
1092                    estimate_row(&mut *out, "ringing_frequency_hz", id, r.frequency)?;
1093                    estimate_row(&mut *out, "ringing_damping_ratio", id, r.damping_ratio)?;
1094                    value_row(&mut *out, "ringing_fit_percent", id, r.quality.fit_percent)?;
1095                    if let (Some(motor), Some(total)) = (args.number("--motor-inertia")?, total_inertia) {
1096                        two_mass_rows(
1097                            &mut *out,
1098                            id,
1099                            &two_mass_from_ringing(&r, total, Estimate { value: motor, error: 0.0 }),
1100                        )?;
1101                    }
1102                }
1103                None => result = Err(Failure("error-identify-ringing", String::new())),
1104            }
1105        }
1106    }
1107    if let Some(path) = args.option("--sweep") {
1108        match two_mass(&parse_sweep(&read(path)?)?) {
1109            Some(model) => two_mass_rows(&mut *out, "sweep", &model)?,
1110            None => result = Err(Failure("error-identify-two-mass", String::new())),
1111        }
1112    }
1113    out.flush().map_err(io)?;
1114    if let Some(path) = args.option("--overlay") {
1115        let mut file = std::io::BufWriter::new(std::fs::File::create(path).map_err(io)?);
1116        let names: Vec<&str> = overlay.iter().map(|(n, _)| n.as_str()).collect();
1117        writeln!(file, "time,{}", names.join(",")).map_err(io)?;
1118        for (row, t) in time.iter().enumerate() {
1119            let values: Vec<String> = overlay.iter().map(|(_, v)| format!("{:.9e}", v[row])).collect();
1120            writeln!(file, "{t:.9e},{}", values.join(",")).map_err(io)?;
1121        }
1122        file.flush().map_err(io)?;
1123    }
1124    result
1125}
1126
1127/// `check-dataset DIR`: what keeps a dataset folder from being published (datasets/README.md).
1128fn check_dataset(args: &Args, tr: &Translations) -> Result<(), Failure> {
1129    let dir = args.positional(1).ok_or(Failure("cli-usage", String::new()))?;
1130    let problems = sim_components::dataset::check(std::path::Path::new(dir));
1131    if problems.is_empty() {
1132        println!("{}", tr.tr_arg("dataset-ok", dir));
1133        return Ok(());
1134    }
1135    problems.iter().for_each(|p| println!("{}", tr.tr_arg("dataset-problem", p)));
1136    Err(Failure("dataset-problem", format!("{} problems in {dir}", problems.len())))
1137}
1138
1139/// `parameters <machine>`: per motor, the drive settings of the config with the SINAMICS parameter that takes each, and its
1140/// value in that parameter's unit (`sim_components::parameters`). The config is read as the file states it, with
1141/// `--set` applied: the drive part is read before the parts are resolved.
1142fn parameters(args: &Args, tr: &Translations) -> Result<(), Failure> {
1143    use sim_components::parameters::{Error, Family, list_resolved};
1144    // The drive part is read from the config as named (the parts are emptied once resolved); the values come from the
1145    // resolved one with `--set` on top, as in every command.
1146    let (entry, named) = named_config(args)?;
1147    let (_, cfg) = machine_and_config(args)?;
1148    let family = match args.option("--family") {
1149        Some(text) => {
1150            Some(Family::parse(text).ok_or_else(|| Failure("cli-error-bad-argument", format!("--family {text}")))?)
1151        }
1152        None => None,
1153    };
1154    let rows = list_resolved(entry, &named, &cfg, family).map_err(|e| match e {
1155        Error::Config(e) => e.into(),
1156        Error::NoDrive(motor) => Failure("cli-error-parameters-no-drive", motor),
1157        Error::UnknownDrive(article) => Failure("cli-error-parameters-unknown-drive", article),
1158        Error::NotRotaryServo(motor) => Failure("cli-error-parameters-not-servo", motor),
1159    })?;
1160    // Six significant digits, without the trailing zeros of a fixed notation.
1161    let number = |x: f64| {
1162        if x != 0.0 && !(1e-4..1e7).contains(&x.abs()) {
1163            return format!("{x:.5e}");
1164        }
1165        let text = format!("{x:.6}");
1166        text.trim_end_matches('0').trim_end_matches('.').to_string()
1167    };
1168    let mut out = output(args, "--out")?;
1169    writeln!(out, "motor,key,value,unit,parameter,name,parameter_value,parameter_unit,basis").map_err(io)?;
1170    for r in &rows {
1171        let converted = r.parameter_value.map_or(String::new(), number);
1172        writeln!(
1173            out,
1174            "{},{},{},{},{},{},{converted},{},{}",
1175            r.motor,
1176            r.key,
1177            number(r.value),
1178            r.unit,
1179            r.parameter,
1180            r.name,
1181            r.parameter_unit,
1182            r.basis.name()
1183        )
1184        .map_err(io)?;
1185    }
1186    eprintln!("{}", tr.tr("cli-parameters-note"));
1187    Ok(())
1188}
1189
1190fn io(e: std::io::Error) -> Failure {
1191    Failure("cli-error-io", e.to_string())
1192}
1193
1194/// Where the CSV goes: the file named by `option`, or standard output.
1195fn output(args: &Args, option: &str) -> Result<Box<dyn Write>, Failure> {
1196    Ok(match args.option(option) {
1197        Some(path) => Box::new(std::io::BufWriter::new(std::fs::File::create(path).map_err(io)?)),
1198        None => Box::new(std::io::stdout().lock()),
1199    })
1200}
1201
1202/// `optimise <machine>`: a shorter cycle that still passes every verdict, found by trying corner blending
1203/// and higher axis limits, with input shaping where a faster setting fails on settling alone, lower lifts down to
1204/// `profile.min_clearance_m` and lifts rounded through a via point (`--runs N` cycles at most, 40 by default). Prints
1205/// the cycle time and what to change in the config; per changed lift its segments, height before and after, and via point.
1206/// The result passes every verdict in the error bands of the config's `[bounds]` too: where the fastest setting found
1207/// fails there, the search's steps are gone back to the fastest that passes (rows `bands_*`, and on the error stream
1208/// what the bands cost). `--worst` judges at the worst corner of all bounds at once instead (`verdict_worst`, rows
1209/// `worst_*`), judging the search's steps from the fastest down. `--nominal` judges the config as written alone. `--pareto FILE`
1210/// writes the settings that no other beats in cycle time, energy per cycle from the supply and peak motor utilisation at once, as CSV.
1211fn optimise(args: &Args, tr: &Translations) -> Result<(), Failure> {
1212    let (entry, cfg) = machine_and_config(args)?;
1213    let cfg = path_instead(args, entry, cfg)?;
1214    let runs = args.number("--runs")?.unwrap_or(40.0) as usize;
1215    let options = sim_components::analysis::OptimiseOptions {
1216        max_runs: runs,
1217        robust: !args.flag("--nominal"),
1218        pareto: args.option("--pareto").is_some(),
1219        worst: args.flag("--worst"),
1220    };
1221    // The failing checks of a cycle that fails as configured by their labels, a linear motor's speed in m/s.
1222    let found = sim_components::analysis::optimise_cycle_with(entry, &cfg, &options).map_err(|e| match e.key() {
1223        key @ "error-cycle-fails-already" => {
1224            let linear = (entry.build)(&cfg).is_ok_and(|m| m.motor_linear(0));
1225            Failure(key, sim_components::report::check_labels(e.detail(), linear, tr))
1226        }
1227        _ => Failure::from(e),
1228    })?;
1229    let mut out = output(args, "--out")?;
1230    writeln!(out, "setting,before,after").map_err(io)?;
1231    writeln!(out, "cycle_s,{:.4},{:.4}", found.before.duration, found.after.duration).map_err(io)?;
1232    writeln!(out, "dwell_error_peak_m,{:.3e},{:.3e}", found.before.dwell_error_peak, found.after.dwell_error_peak)
1233        .map_err(io)?;
1234    let (before, after) = (found.before.dwell_angle_error_peak, found.after.dwell_angle_error_peak);
1235    writeln!(out, "dwell_angle_error_peak_rad,{before:.3e},{after:.3e}").map_err(io)?;
1236    if let Some(robust) = &found.robust {
1237        // The fastest setting on the verdicts as written, what it fails in the bands (or at the worst corner), and how
1238        // far the result went back.
1239        let judged = if robust.worst { "worst" } else { "bands" };
1240        writeln!(out, "{judged}_fastest_cycle_s,,{:.4}", robust.nominal_duration).map_err(io)?;
1241        writeln!(out, "{judged}_fastest_fails,,{}", robust.nominal_fails.join(" ")).map_err(io)?;
1242        writeln!(out, "{judged}_steps_back,,{}", robust.steps_back).map_err(io)?;
1243        // Failed by the cycle as configured already: the result is not judged on them.
1244        writeln!(out, "{judged}_excused,,{}", robust.excused.join(" ")).map_err(io)?;
1245        let key = if robust.worst { "cli-optimise-runs-worst" } else { "cli-optimise-runs" };
1246        eprintln!("{}", tr.tr_arg(key, &format!("{} + {}", found.runs, robust.runs)));
1247    }
1248    if let Some(path) = args.option("--pareto") {
1249        let mut front = std::io::BufWriter::new(std::fs::File::create(path).map_err(io)?);
1250        writeln!(front, "cycle_s,energy_j,peak_utilisation,velocity_factor,acceleration_factor,jerk_factor,corner_blending,input_shaping").map_err(io)?;
1251        for p in &found.front {
1252            let [v, a, j] = p.factors;
1253            writeln!(
1254                front,
1255                "{:.4},{:.3},{:.4},{v:.4},{a:.4},{j:.4},{},{}",
1256                p.duration, p.energy, p.utilisation, p.blending, p.shaping
1257            )
1258            .map_err(io)?;
1259        }
1260        front.flush().map_err(io)?;
1261    }
1262    // The new cycle itself is TOML with commas; its lifts say what changed in it.
1263    for (path, before, after) in found.changes.iter().filter(|c| c.0 != "cycle.segment") {
1264        writeln!(out, "{path},{before},{after}").map_err(io)?;
1265    }
1266    for lift in &found.lifts {
1267        let [a, b, c] = lift.segments;
1268        writeln!(out, "cycle.segment[{a}-{b}-{c}].lift_m,{:.4},{:.4}", lift.before, lift.after).map_err(io)?;
1269        if let Some(via) = &lift.via {
1270            // Points apart by "; " (several for a height profile), axes by spaces.
1271            let point: Vec<String> =
1272                via.iter().map(|point| point.iter().map(|x| format!("{x:.4}")).collect::<Vec<_>>().join(" ")).collect();
1273            writeln!(out, "cycle.segment[{a}-{b}-{c}].via_m,,{}", point.join("; ")).map_err(io)?;
1274        }
1275        if let Some(corner) = lift.corners {
1276            writeln!(out, "cycle.segment[{a}-{b}-{c}].corners_m,,{corner:.6}").map_err(io)?;
1277        }
1278    }
1279    out.flush().map_err(io)
1280}
1281
1282/// `search <machine>`: every motor of the catalogue on the cycle of the config, each with the drive the catalogue
1283/// pairs with it, the passing ones first, cheapest first (installed weight stands in for the price). `--series
1284/// PREFIX` limits it to article numbers starting that way, `--supply` picks 230v or 400v (S210) or s120 (the S120
1285/// motors and Motor Modules), by default the config's own `parts.motor_supply`, else 400v; or any other of
1286/// `catalog::SUPPLIES` (another maker's at a line voltage, or the S210 with the new 6SL5310 converters). `--vendor NAME`
1287/// keeps the supplies of that maker (`vendor_of`; "all" every maker), all of them where `--supply` names none; the
1288/// candidates of several supplies are ranked together, each with its supply. `--gearboxes SERIES` also tries each motor
1289/// with the fitting gearboxes of that series, on a machine that has a gearbox; a motor none fits with the config's own
1290/// gearbox. SERIES is a maker (`wittenstein`), a maker's series (`wittenstein-sp`, `neugart-ple`, `siemens-nrk`), "" for
1291/// all, or a prefix of the size (`NRK`, as before); see `catalog::gearboxes_for_motor`. `--axes` tries every motor on
1292/// every axis of the catalogue of the machine's kind as well, the axis's weight in the cost: belt axes, and for a screw,
1293/// rack or linear motor machine the ball screws and guide sets (`catalog::mech_axes`; a linear motor machine's motors
1294/// are the supply's linear motors). `--motor-id ID` sizes one motor of a machine with several (a
1295/// machine file's): each candidate becomes that motor's own `[parts.ID]`, the other motors stay as the config has them,
1296/// and the cost, the tightest check, the peak torque and the winding rise are that motor's alone (`catalog::search_motor`);
1297/// not with `--axes`. Says on the error stream how many candidates could not be simulated (the reason is in the table),
1298/// with `--gearboxes` how many motors no gearbox of the series fits, and how long the search
1299/// took on how many processors.
1300///
1301/// The wide table (`search::Figures`) follows the parts and the tightest check: rank, front (`search::front`), cycle
1302/// time, energy, thermal and drive current utilisation, following and settling error, inertia ratio, the failing checks,
1303/// what is estimated, and one column `u_<check>` per check. `--rank-by` orders the passing ones (`search::rank_by`),
1304/// `--drives paired|neighbours|all` the drives tried with each motor (`catalog::Drives`), several `--config FILE` with
1305/// `--weights` a duty mix (`catalog::Options::duties`), and `--robust N` judges the first N passing ones at the worst
1306/// corner of their bounds (`search::robust_ranking`), with four columns more and on the error stream whether the order
1307/// changes.
1308/// The supplies a search on `cfg` runs at: `--supply`, else the config's own (`parts.motor_supply`), else 400 V; with
1309/// `--vendor` that maker's supplies ("all": every one), all of them unless `--supply` names one.
1310fn search_supplies_of(args: &Args, cfg: &Config) -> Result<Vec<&'static str>, Failure> {
1311    use sim_components::catalog::{Parts, SUPPLIES, vendor_of};
1312    let own_supply = Parts::of(cfg).map(|p| p.supply.to_string()).unwrap_or_default();
1313    let supply = args.option("--supply").or(Some(own_supply.as_str()).filter(|s| !s.is_empty())).unwrap_or("400v");
1314    let vendor = args.option("--vendor").filter(|v| *v != "all");
1315    let every = args.option("--supply").is_none() && args.option("--vendor").is_some();
1316    let supplies: Vec<&'static str> = SUPPLIES
1317        .iter()
1318        .copied()
1319        .filter(|s| (every || *s == supply) && vendor.is_none_or(|v| vendor_of(s) == v))
1320        .collect();
1321    if supplies.is_empty() {
1322        let given = [args.option("--vendor"), args.option("--supply")].into_iter().flatten().collect::<Vec<_>>();
1323        return Err(Failure("cli-error-bad-argument", given.join(" ")));
1324    }
1325    Ok(supplies)
1326}
1327
1328/// `--drives paired|neighbours|all` and `--rank-by CRITERIA` of `search` and `compare-kinematics`. With a price list
1329/// (`--prices` of `search`) the default ranking is by price; `price` without one is refused.
1330fn search_choices(
1331    args: &Args,
1332    prices: bool,
1333) -> Result<(sim_components::catalog::Drives, Vec<(sim_components::search::Criterion, f64)>), Failure> {
1334    use sim_components::search::Criterion;
1335    let drives = args.option("--drives").unwrap_or("paired");
1336    let drives = drives.parse().map_err(|_| Failure("cli-error-bad-argument", format!("--drives {drives}")))?;
1337    let by = args.option("--rank-by").unwrap_or(if prices { "price" } else { "cost" });
1338    let by = sim_components::search::parse_ranking(by)
1339        .ok_or_else(|| Failure("cli-error-bad-argument", format!("--rank-by {by}")))?;
1340    if !prices && by.iter().any(|(c, _)| *c == Criterion::Price) {
1341        return Err(Failure("cli-error-prices-needed", String::new()));
1342    }
1343    Ok((drives, by))
1344}
1345
1346/// `--prices FILE` of `search`: the user's price list (`catalog::PriceList`).
1347fn price_list(args: &Args) -> Result<Option<sim_components::catalog::PriceList>, Failure> {
1348    let Some(file) = args.option("--prices") else { return Ok(None) };
1349    let list = sim_components::catalog::PriceList::parse(&read(file)?);
1350    list.map(Some).map_err(|(line, key, arg)| Failure(key, format!("{file}:{line}: {arg}")))
1351}
1352
1353/// The duty mix of `search`: with several `--config FILE`, each file's config (with the parts and `--set` of the command
1354/// line, as `machine_and_config` makes them) and its weight from `--weights W1,W2,...` (1 each without); empty for one.
1355fn duties(args: &Args, entry: &'static MachineEntry) -> Result<Vec<(Config, f64)>, Failure> {
1356    let files = args.options("--config");
1357    let weights: Vec<f64> = match args.option("--weights") {
1358        None => vec![1.0; files.len()],
1359        Some(text) => text
1360            .split(',')
1361            .map(|w| w.trim().parse().ok().filter(|w: &f64| *w > 0.0 && w.is_finite()))
1362            .collect::<Option<_>>()
1363            .filter(|w: &Vec<f64>| w.len() == files.len())
1364            .ok_or_else(|| Failure("cli-error-bad-argument", format!("--weights {text}")))?,
1365    };
1366    if files.len() < 2 {
1367        return Ok(Vec::new());
1368    }
1369    let mut out = Vec::new();
1370    for (file, weight) in files.into_iter().zip(weights) {
1371        let mut cfg = sim_components::load_config(entry, &read(file)?)?;
1372        let named = [
1373            ("motor", "--motor"),
1374            ("motor_supply", "--supply"),
1375            ("gearbox", "--gearbox"),
1376            ("drive", "--drive"),
1377            ("belt", "--belt"),
1378            ("axis", "--axis"),
1379        ];
1380        for (key, option) in named {
1381            if let Some(name) = args.option(option) {
1382                cfg.set_text(&format!("parts.{key} = {name:?}"))?;
1383            }
1384        }
1385        before_parts(args, entry, &mut cfg)?;
1386        let mut cfg = sim_components::catalog::resolve(entry, &cfg)?;
1387        for assignment in args.options("--set") {
1388            sim_components::set_config_text(entry, &mut cfg, assignment)?;
1389        }
1390        out.push((cfg, weight));
1391    }
1392    Ok(out)
1393}
1394
1395/// A list for one CSV cell: the names joined with ";".
1396fn cell(names: &[&str]) -> String {
1397    names.join(";")
1398}
1399
1400fn search(args: &Args, tr: &Translations) -> Result<(), Failure> {
1401    use sim_components::catalog::{motor_config, resolve};
1402    use sim_components::search::{front, rank_by, robust_ranking};
1403    let (entry, cfg) = machine_and_config(args)?;
1404    let cfg = path_instead(args, entry, cfg)?;
1405    let duties: Vec<(Config, f64)> = duties(args, entry)?
1406        .into_iter()
1407        .map(|(c, w)| Ok((path_instead(args, entry, c)?, w)))
1408        .collect::<Result<_, Failure>>()?;
1409    // With a duty mix the first file's config is searched on.
1410    let cfg = duties.first().map_or(cfg, |(first, _)| first.clone());
1411    let prefix = args.option("--series").unwrap_or("");
1412    let (gearboxes, wanted) = (args.option("--gearboxes"), |article: &str| article.starts_with(prefix));
1413    use sim_components::catalog::vendor_of;
1414    let supplies = search_supplies_of(args, &cfg)?;
1415    let (motor, axes) = (args.option("--motor-id"), args.flag("--axes"));
1416    if motor.is_some() && axes {
1417        return Err(Failure("cli-usage", String::new()));
1418    }
1419    let prices = price_list(args)?;
1420    let (drives, by) = search_choices(args, prices.is_some())?;
1421    let robust: Option<usize> = args
1422        .option("--robust")
1423        .map(|n| n.parse().map_err(|_| Failure("cli-error-bad-argument", format!("--robust {n}"))))
1424        .transpose()?;
1425    let started = std::time::Instant::now();
1426    let options = sim_components::catalog::Options { gearboxes, axes, motor, drives, duties: &duties };
1427    let mut found = sim_components::catalog::search(entry, &cfg, &supplies, &wanted, &options)?;
1428    if let Some(list) = &prices {
1429        let missing = sim_components::catalog::apply_prices(&mut found, list);
1430        let unpriced = found.iter().filter(|c| !c.parts.is_empty() && c.price.is_none()).count();
1431        if unpriced > 0 {
1432            let names = missing.iter().take(10).cloned().collect::<Vec<_>>().join(", ");
1433            eprintln!("{}", tr.tr_arg("cli-search-unpriced", &format!("{unpriced}: {names}")));
1434        }
1435        // A mix cannot weigh a candidate without a figure; a single price puts those last.
1436        let passing_unpriced = found.iter().filter(|c| c.passes() && c.price.is_none()).count();
1437        if by.len() > 1
1438            && by.iter().any(|(c, _)| *c == sim_components::search::Criterion::Price)
1439            && passing_unpriced > 0
1440        {
1441            return Err(Failure("cli-error-prices-mix", passing_unpriced.to_string()));
1442        }
1443    }
1444    rank_by(&mut found, &by);
1445    let on_front = front(&found);
1446    let robust = robust.map(|top| robust_ranking(entry, &cfg, &duties, &found, top));
1447    if let Some((_, changed)) = &robust {
1448        eprintln!("{}", tr.tr(if *changed { "cli-search-robust-changed" } else { "cli-search-robust-same" }));
1449    }
1450    let threads = std::thread::available_parallelism().map_or(1, |n| n.get());
1451    let tried = found.iter().filter(|c| !c.article.is_empty());
1452    eprintln!(
1453        "{}",
1454        tr.tr_arg(
1455            "cli-search-screened",
1456            &format!("{} / {}", found.iter().filter(|c| c.result.is_none()).count(), found.len())
1457        )
1458    );
1459    // With a series of gearboxes, on a machine (or motor) that has a gearbox: the motors none of them fits.
1460    let own = motor.map_or(Ok(cfg.clone()), |id| motor_config(&cfg, id))?;
1461    if gearboxes.is_some() && resolve(entry, &own)?.f64("gearbox.ratio").unwrap_or(1.0) > 1.0 {
1462        let count = tried.filter(|c| c.gearbox.is_empty()).count();
1463        eprintln!("{}", tr.tr_arg("cli-search-own-gearbox", &count.to_string()));
1464    }
1465    eprintln!("{}", tr.tr_arg("cli-search-time", &format!("{threads}: {:.1} s", started.elapsed().as_secs_f64())));
1466    let mut out = output(args, "--out")?;
1467    // Every check of any candidate, one column of utilisation each, in the order they first come up.
1468    let mut checks: Vec<&str> = Vec::new();
1469    for (check, _) in found.iter().filter_map(|c| c.figures.as_ref()).flat_map(|f| &f.checks) {
1470        if !checks.contains(check) {
1471            checks.push(check);
1472        }
1473    }
1474    let columns: String = checks.iter().map(|c| format!(",u_{c}")).collect();
1475    let robust_columns =
1476        if robust.is_some() { ",robust_rank,robust_result,robust_check,robust_utilisation" } else { "" };
1477    let price_header = if prices.is_some() { ",price" } else { "" };
1478    writeln!(out, "axis,motor,gearbox,drive,vendor,supply,mass_kg,cost_kg{price_header},result,tightest_check,tightest_utilisation,peak_torque_nm,winding_rise_k,rank,front,cycle_s,energy_j,thermal_utilisation,drive_current_utilisation,following_error_m,settling_error_m,inertia_ratio,failing,estimated{robust_columns}{columns},torque_unit").map_err(io)?;
1479    // The unit of peak_torque_nm: N on a machine of linear motors (the first motor's kind), else N m.
1480    let torque_unit = if (entry.build)(&cfg).is_ok_and(|m| m.motor_linear(0)) { "N" } else { "N m" };
1481    for (rank, c) in found.iter().enumerate() {
1482        let (check, utilisation) = c.tightest().unwrap_or((c.refused, f64::NAN));
1483        // Of the searched motor alone with --motor-id (the others are the config's, alike for every candidate).
1484        let (peak, rise) = c.result.as_ref().map_or((f64::NAN, f64::NAN), |(load, _)| {
1485            let searched = || load.motors.iter().filter(|m| c.motor.is_empty() || m.id == c.motor);
1486            (
1487                searched().map(|m| m.peak_torque).fold(0.0, f64::max),
1488                searched().map(|m| m.winding_rise).fold(0.0, f64::max),
1489            )
1490        });
1491        let result = if c.passes() { "ok" } else { "FAIL" };
1492        // Empty where the candidate has no price.
1493        let price = if prices.is_some() {
1494            format!(",{}", c.price.map_or(String::new(), |p| format!("{p:.2}")))
1495        } else {
1496            String::new()
1497        };
1498        write!(
1499            out,
1500            "{},{},{},{},{},{},{:.2},{:.2}{price},{result},{check},{utilisation:.4},{peak:.4},{rise:.2}",
1501            c.axis,
1502            c.article,
1503            c.gearbox,
1504            c.drive,
1505            if c.supply.is_empty() { "" } else { vendor_of(c.supply) },
1506            c.supply,
1507            c.mass,
1508            c.cost
1509        )
1510        .map_err(io)?;
1511        let f = c.figures.clone().unwrap_or_else(|| sim_components::search::Figures {
1512            energy_j: f64::NAN,
1513            thermal: f64::NAN,
1514            drive_current: f64::NAN,
1515            following_error_m: f64::NAN,
1516            settling_error_m: f64::NAN,
1517            inertia_ratio: f64::NAN,
1518            cycle_s: f64::NAN,
1519            ..Default::default()
1520        });
1521        write!(
1522            out,
1523            ",{},{},{:.4},{:.2},{:.4},{:.4},{:.4e},{:.4e},{:.3},{},{}",
1524            rank + 1,
1525            on_front[rank],
1526            f.cycle_s,
1527            f.energy_j,
1528            f.thermal,
1529            f.drive_current,
1530            f.following_error_m,
1531            f.settling_error_m,
1532            f.inertia_ratio,
1533            cell(&f.failing),
1534            cell(&f.estimated)
1535        )
1536        .map_err(io)?;
1537        if let Some((rows, _)) = &robust {
1538            match rows.iter().position(|r| r.index == rank) {
1539                Some(at) => {
1540                    let r = &rows[at];
1541                    let (check, u) = r.tightest.unwrap_or(("", f64::NAN));
1542                    let result = if !r.refused.is_empty() {
1543                        r.refused.replace(',', ";")
1544                    } else if r.passes {
1545                        "ok".into()
1546                    } else {
1547                        "FAIL".into()
1548                    };
1549                    write!(out, ",{},{result},{check},{u:.4}", at + 1).map_err(io)?;
1550                }
1551                None => write!(out, ",,,,").map_err(io)?,
1552            }
1553        }
1554        for check in &checks {
1555            match f.checks.iter().find(|(c, _)| c == check) {
1556                Some((_, u)) => write!(out, ",{u:.4}").map_err(io)?,
1557                None => write!(out, ",").map_err(io)?,
1558            }
1559        }
1560        writeln!(out, ",{torque_unit}").map_err(io)?;
1561    }
1562    out.flush().map_err(io)
1563}
1564
1565/// `transmission <machine>`: sweeps the gearbox ratio (`--key gearbox.ratio`, the default) or the pulley radius (`--key
1566/// geometry.pulley_radius_m`) of the config from `--from` to `--to` in `--count` values (by default half to twice the
1567/// config's, 9 values), each with the velocity gain retuned and run on the cycle, and the classic optimum (the least
1568/// torque per unit acceleration; for a pure inertia sqrt(J_load / J_motor)) beside them
1569/// (`search::transmission_sweep`). Per row: the value, the torque per unit acceleration, the inertia ratio, the cycle
1570/// time, and the result with its tightest check. With `--gearboxes SERIES` and a motor (`--motor` or the config's
1571/// `parts.motor`), the series' gearboxes that fit it around the best ratio are run as well, as rows "catalogue". The
1572/// error stream says the classic optimum and the best value for the cycle.
1573fn transmission(args: &Args, tr: &Translations) -> Result<(), Failure> {
1574    let (entry, named) = named_config(args)?;
1575    let parts = sim_components::catalog::Parts::of(&named)?;
1576    let (motor, supply) = (parts.motor.to_string(), parts.supply.to_string());
1577    let (entry, cfg) = (entry, machine_and_config(args)?.1);
1578    let key = args.option("--key").unwrap_or("gearbox.ratio");
1579    if !["gearbox.ratio", "geometry.pulley_radius_m"].contains(&key) {
1580        return Err(Failure("cli-error-bad-argument", format!("--key {key}")));
1581    }
1582    let own = cfg.positive(key)?;
1583    let (from, to) = (args.number("--from")?.unwrap_or(own / 2.0), args.number("--to")?.unwrap_or(own * 2.0));
1584    let count = match args.number("--count")? {
1585        Some(n) if n >= 2.0 && n.fract() == 0.0 => n as usize,
1586        Some(n) => return Err(Failure("cli-error-bad-argument", format!("--count {n}"))),
1587        None => 9,
1588    };
1589    let snap = args
1590        .option("--gearboxes")
1591        .filter(|_| !motor.is_empty())
1592        .map(|series| (series, motor.as_str(), supply.as_str()));
1593    let sweep = sim_components::search::transmission_sweep(entry, &cfg, key, (from, to, count), snap)?;
1594    eprintln!("{}", tr.tr_arg("cli-transmission-optimum", &format!("{key}: {:.4}, {:.4}", sweep.classic, sweep.best)));
1595    let mut out = output(args, "--out")?;
1596    writeln!(
1597        out,
1598        "kind,value,gearbox,torque_per_acceleration,inertia_ratio,cycle_s,result,tightest_check,tightest_utilisation,torque_unit"
1599    )
1600    .map_err(io)?;
1601    // The unit of the torque in torque_per_acceleration, as `search` names it: N on a machine of linear motors.
1602    let torque_unit = if (entry.build)(&cfg).is_ok_and(|m| m.motor_linear(0)) { "N" } else { "N m" };
1603    let rows = sweep.rows.iter().map(|r| (if r.value == sweep.classic { "classic" } else { "sweep" }, r));
1604    for (kind, r) in rows.chain(sweep.snapped.iter().map(|r| ("catalogue", r))) {
1605        let (check, u) = r.tightest.unwrap_or((r.refused, f64::NAN));
1606        let result = if r.passes { "ok" } else { "FAIL" };
1607        writeln!(
1608            out,
1609            "{kind},{:.6},{},{:.6},{:.4},{:.4},{result},{check},{u:.4},{torque_unit}",
1610            r.value, r.gearbox, r.torque_per_acceleration, r.inertia_ratio, r.cycle_s
1611        )
1612        .map_err(io)?;
1613    }
1614    out.flush().map_err(io)
1615}
1616
1617/// `compare-kinematics TASK.toml --machines ID,ID,...`: the task (`search::Task`: pick and place in tool space, payload,
1618/// target cycle time) mapped onto each machine's own cycle (`search::task_config`; a machine the task cannot be mapped
1619/// onto is listed with the reason), the catalogue search run on each (with `--supply`, `--vendor`, `--series`,
1620/// `--gearboxes`, `--drives` and `--rank-by` as `search` takes them), and per machine the best combination and its
1621/// figures side by side. Machines by id, and every `--machine-file FILE` as well; each with its default config and
1622/// `--set`.
1623fn compare_kinematics(args: &Args, _tr: &Translations) -> Result<(), Failure> {
1624    let file = args.positional(1).ok_or(Failure("cli-usage", String::new()))?;
1625    let task = sim_components::search::Task::parse(&read(file)?)
1626        .map_err(|e| Failure("cli-error-bad-argument", format!("{file}: {e}")))?;
1627    let mut machines: Vec<(&'static MachineEntry, Config)> = Vec::new();
1628    let ids = args.option("--machines").map(|m| m.split(',').map(str::trim).collect::<Vec<_>>()).unwrap_or_default();
1629    let entries: Vec<&'static MachineEntry> = ids
1630        .iter()
1631        .map(|id| find(id).ok_or(Failure("cli-error-unknown-machine", id.to_string())))
1632        .chain(args.options("--machine-file").into_iter().map(|path| {
1633            sim_machines::load_file(std::path::Path::new(path))
1634                .map_err(|e| Failure(e.error.key(), format!("{path}: {}", e.error.detail())))
1635        }))
1636        .collect::<Result<_, _>>()?;
1637    if entries.is_empty() {
1638        return Err(Failure("cli-usage", String::new()));
1639    }
1640    for entry in entries {
1641        let mut cfg = entry.config();
1642        for assignment in args.options("--set") {
1643            sim_components::set_config_text(entry, &mut cfg, assignment)?;
1644        }
1645        machines.push((entry, cfg));
1646    }
1647    let prefix = args.option("--series").unwrap_or("");
1648    let (drives, by) = search_choices(args, false)?;
1649    let options =
1650        sim_components::catalog::Options { gearboxes: args.option("--gearboxes"), drives, ..Default::default() };
1651    // Each machine at its own supply, unless the command line names one.
1652    let supplies = |cfg: &Config| search_supplies_of(args, cfg).unwrap_or_default();
1653    for (_, cfg) in &machines {
1654        search_supplies_of(args, cfg)?;
1655    }
1656    let rows = sim_components::search::compare_kinematics(
1657        &task,
1658        &machines,
1659        &supplies,
1660        &|article: &str| article.starts_with(prefix),
1661        &options,
1662        &by,
1663    );
1664    let mut out = output(args, "--out")?;
1665    writeln!(out, "machine,result,refused,motor,gearbox,drive,supply,cost_kg,cycle_s,target_s,meets,energy_j,tightest_check,tightest_utilisation,thermal_utilisation,following_error_m,inertia_ratio,passing,tried,estimated").map_err(io)?;
1666    for row in &rows {
1667        let nan = f64::NAN;
1668        let target = row.target_s.map_or(String::new(), |t| format!("{t:.4}"));
1669        match (&row.refused, &row.best) {
1670            (Some(r), _) => writeln!(
1671                out,
1672                "{},refused,{} {},,,,,,,{target},false,,,,,,,0,0,",
1673                row.machine,
1674                r.key,
1675                r.detail.replace(',', ";")
1676            )
1677            .map_err(io)?,
1678            (None, None) => writeln!(out, "{},none,,,,,,,,{target},false,,,,,,,0,0,", row.machine).map_err(io)?,
1679            (None, Some(c)) => {
1680                let f = c.figures.clone().unwrap_or_default();
1681                let (check, u) = c.tightest().unwrap_or((c.refused, nan));
1682                writeln!(
1683                    out,
1684                    "{},{},,{},{},{},{},{:.2},{:.4},{target},{},{:.2},{check},{u:.4},{:.4},{:.4e},{:.3},{},{},{}",
1685                    row.machine,
1686                    if c.passes() { "ok" } else { "FAIL" },
1687                    c.article,
1688                    c.gearbox,
1689                    c.drive,
1690                    c.supply,
1691                    c.cost,
1692                    f.cycle_s,
1693                    row.meets(),
1694                    f.energy_j,
1695                    f.thermal,
1696                    f.following_error_m,
1697                    f.inertia_ratio,
1698                    row.passing,
1699                    row.tried,
1700                    cell(&f.estimated)
1701                )
1702                .map_err(io)?
1703            }
1704        }
1705    }
1706    out.flush().map_err(io)
1707}
1708
1709/// A value with four significant digits and no exponent: the checks range from fractions of a millimetre
1710/// to thousands of r/min, and a fixed number of decimals shows the small ones as 0.0000.
1711fn significant(value: f64) -> String {
1712    let decimals = if value == 0.0 || !value.is_finite() { 0 } else { (3 - value.abs().log10().floor() as i32).max(0) };
1713    format!("{value:.*}", decimals as usize)
1714}
1715
1716/// `verdicts <machine>`: the cycle judged against the motor data and the `[ratings]` of the config, one
1717/// line per check and motor. `--bands` adds the lowest and highest value each check takes when the
1718/// parameters with `[bounds]` in the config are at their bounds, one at a time, and the worst-case result.
1719/// `--bands --samples N` runs the cycle N times with all of them between their bounds at once instead (see
1720/// `verdict_bands_sampled`; `--seed S` picks another set of samples, 1 by default) and adds the share of
1721/// the runs in which each check passed. `--bands --worst` searches per check for the worst corner of the bounds
1722/// instead (`verdict_worst`) and prints its value, its result and which parameters are at their high and which at
1723/// their low bound there; the number of cycles it simulated goes to the error stream. Where the config has obstacles,
1724/// the error stream first says what the cycle as planned keeps from them (`collision::check_cycle`), and the check
1725/// "collision" judges the run.
1726fn verdicts(args: &Args, tr: &Translations) -> Result<(), Failure> {
1727    use sim_components::analysis::{bounds, verdict_bands, verdict_bands_sampled, verdict_worst};
1728    let (entry, cfg) = machine_and_config(args)?;
1729    let motors = (entry.build)(&cfg)?.motors().to_vec();
1730    // A path's clearance is in its run's verdict "collision"; the configured cycle's is told here.
1731    if args.option("--path").is_none() {
1732        let limit = cfg.non_negative("profile.min_clearance_m")?;
1733        tell_plan(tr, sim_components::collision::check_cycle(entry, &cfg)?, limit);
1734    }
1735    let cfg = path_instead(args, entry, cfg)?;
1736    if args.flag("--worst") {
1737        if !args.flag("--bands") || args.option("--samples").is_some() || args.option("--seed").is_some() {
1738            return Err(Failure("cli-error-worst", String::new()));
1739        }
1740        let bounded = bounds(&cfg)?;
1741        let (worst, runs) = verdict_worst(entry, &cfg, &bounded)?;
1742        eprintln!("{}", tr.tr_arg("cli-worst-runs", &runs.to_string()));
1743        let mut out = output(args, "--out")?;
1744        writeln!(out, "check,motor,worst,limit,worst_case,at_high_bound,at_low_bound").map_err(io)?;
1745        for w in &worst {
1746            let v = &w.verdict;
1747            let at = |high: bool| {
1748                bounded
1749                    .iter()
1750                    .zip(&w.high)
1751                    .filter(|(_, h)| **h == Some(high))
1752                    .map(|(b, _)| b.0.as_str())
1753                    .collect::<Vec<_>>()
1754                    .join(";")
1755            };
1756            let result = judged(v.ok);
1757            writeln!(
1758                out,
1759                "{},{},{},{},{result},{},{}",
1760                v.check,
1761                v.motor.map_or("", |k| motors[k].id),
1762                significant(v.value),
1763                significant(v.limit),
1764                at(true),
1765                at(false)
1766            )
1767            .map_err(io)?;
1768        }
1769        tell_not_finite(tr, worst.iter().map(|w| &w.verdict));
1770        tell_own_unchecked(tr, worst.iter().map(|w| &w.verdict));
1771        return out.flush().map_err(io);
1772    }
1773    // Whole numbers: at least one sample, and any seed from 0 on.
1774    let whole = |name: &str, least: f64| -> Result<Option<f64>, Failure> {
1775        let value = args.number(name)?;
1776        let bad = |v: &f64| v.fract() != 0.0 || *v < least || *v > 1e9 || !args.flag("--bands");
1777        if let Some(v) = value.filter(bad) {
1778            Err(Failure("cli-error-bad-argument", format!("{name} {v}")))
1779        } else {
1780            Ok(value)
1781        }
1782    };
1783    let (samples, seed) = (whole("--samples", 1.0)?, whole("--seed", 0.0)?);
1784    if seed.is_some() && samples.is_none() {
1785        return Err(Failure("cli-error-missing-value", "--samples".into()));
1786    }
1787    let bands = match samples {
1788        Some(samples) => {
1789            verdict_bands_sampled(entry, &cfg, &bounds(&cfg)?, samples as usize, seed.unwrap_or(1.0) as u64)?
1790        }
1791        None => verdict_bands(entry, &cfg, &if args.flag("--bands") { bounds(&cfg)? } else { Vec::new() })?,
1792    };
1793    let row = |check: &str| bands.iter().find(|b| b.verdict.check == check).map(|b| b.verdict.value);
1794    tell_start(tr, row("thermal-warm-start"), row("thermal-cycle-repeat"));
1795    let result = judged;
1796    let mut out = output(args, "--out")?;
1797    let share = if samples.is_some() { ",pass_share" } else { "" };
1798    writeln!(
1799        out,
1800        "check,motor,value,limit,result{}{share}",
1801        if args.flag("--bands") { ",low,high,worst_case" } else { "" }
1802    )
1803    .map_err(io)?;
1804    for band in &bands {
1805        let v = &band.verdict;
1806        let motor = v.motor.map_or("", |k| motors[k].id);
1807        let worst = if args.flag("--bands") {
1808            format!(",{},{},{}", significant(band.low), significant(band.high), result(band.ok))
1809        } else {
1810            String::new()
1811        };
1812        let share = if samples.is_some() { format!(",{:.3}", band.share_shown(3)) } else { String::new() };
1813        writeln!(
1814            out,
1815            "{},{motor},{},{},{}{worst}{share}",
1816            v.check,
1817            significant(v.value),
1818            significant(v.limit),
1819            result(v.ok)
1820        )
1821        .map_err(io)?;
1822    }
1823    tell_not_finite(tr, bands.iter().map(|b| &b.verdict));
1824    tell_own_unchecked(tr, bands.iter().map(|b| &b.verdict));
1825    out.flush().map_err(io)
1826}
1827
1828/// On the error stream, where the verdicts have no row "self-collision": the machine's own parts were not checked (it
1829/// has no two parts not joined at its start pose), which is not "clear", as "collision" is left out without obstacles.
1830fn tell_own_unchecked<'a>(
1831    tr: &Translations,
1832    mut verdicts: impl Iterator<Item = &'a sim_components::analysis::Verdict>,
1833) {
1834    if !verdicts.any(|v| v.check == "self-collision") {
1835        eprintln!("{}", tr.tr("cli-planned-own-none"));
1836    }
1837}
1838
1839/// `sensitivity <machine>`: the cycle with each parameter at its low and at its high bound of the config,
1840/// or 20 % (or `--delta`) lower and higher where the config gives it no bounds, one at a
1841/// time, as relative changes of the results, strongest first. `--group NAME` (repeatable) limits it to
1842/// config tables; without it every table of machine and motor data is varied.
1843///
1844/// `--method morris|sobol` moves all values of `[bounds]` at once instead (`global_sensitivity`).
1845fn sensitivity(args: &Args, tr: &Translations) -> Result<(), Failure> {
1846    let (entry, cfg) = machine_and_config(args)?;
1847    let groups = args.options("--group");
1848    if let Some(method) = args.option("--method") {
1849        if args.option("--delta").is_some() {
1850            return Err(Failure("cli-error-conflict", "--delta --method".into()));
1851        }
1852        return global_sensitivity(args, tr, entry, &cfg, method, &groups);
1853    }
1854    if let Some(name) = ["--samples", "--seed", "--result"].into_iter().find(|name| args.option(name).is_some()) {
1855        return Err(Failure("cli-error-missing-value", format!("--method ({name})")));
1856    }
1857    let delta = args.number("--delta")?.unwrap_or(0.2);
1858    // Timing, switches, limits, gains and the cycle itself are choices, not uncertain machine data.
1859    let fixed = ["sim", "effects", "drive", "profile", "start", "axis", "temperature", "path"];
1860    let paths: Vec<String> = cfg
1861        .leaves()
1862        .into_iter()
1863        .map(|(path, _)| path)
1864        .filter(|path| path.contains('.'))
1865        .filter(|path| {
1866            let group = path.split('.').next().unwrap();
1867            if groups.is_empty() { !fixed.contains(&group) } else { groups.contains(&group) }
1868        })
1869        .collect();
1870    let (nominal, mut rows) = sim_components::analysis::sensitivity(entry, &cfg, &paths, delta)?;
1871    // A value of 0 without a range in [bounds] has nothing to scale and is not ranked: named on the error stream.
1872    let bounded = sim_components::analysis::bounds(&cfg)?;
1873    for path in paths.iter().filter(|p| cfg.f64(p).ok() == Some(0.0) && !bounded.iter().any(|b| &b.0 == *p)) {
1874        eprintln!("{}", tr.tr_arg("cli-sensitivity-zero", path));
1875    }
1876    let slack = |load: &sim_components::analysis::CycleLoad| load.belt_tension.map_or(0.0, |t| t.0);
1877    rows.sort_by(|a, b| b.strength(&nominal).total_cmp(&a.strength(&nominal)));
1878    let mut out = output(args, "--out")?;
1879    writeln!(out, "parameter,value,low,high,peak_torque_low,peak_torque_high,rms_torque_low,rms_torque_high,cycle_time_low,cycle_time_high,belt_tension_min_low_n,belt_tension_min_high_n")
1880        .map_err(io)?;
1881    for row in &rows {
1882        let n = row.changes(&nominal);
1883        writeln!(
1884            out,
1885            "{},{:?},{:?},{:?},{:+.4},{:+.4},{:+.4},{:+.4},{:+.4},{:+.4},{:.2},{:.2}",
1886            row.path,
1887            row.value,
1888            row.bounds.0,
1889            row.bounds.1,
1890            n[0],
1891            n[1],
1892            n[2],
1893            n[3],
1894            n[4],
1895            n[5],
1896            slack(&row.low),
1897            slack(&row.high)
1898        )
1899        .map_err(io)?;
1900    }
1901    out.flush().map_err(io)
1902}
1903
1904/// `sensitivity <machine> --method morris|sobol`: the global sensitivity of the cycle's results to the values of
1905/// `[bounds]` (only those of the tables `--group` names, where it is given), all moving at once
1906/// (`sim_components::sensitivity`). Morris: `--samples` trajectories (10 by default), (k + 1) cycles each; one row per
1907/// result and parameter with mu*, mu and sigma. Sobol: `--samples` base rows (64 by default), (k + 2) cycles each; S_i
1908/// and S_Ti with their bootstrap 95 % intervals. Rows ranked per result, strongest first; `--result NAME` (repeatable)
1909/// keeps only those results. `--seed S` (1 by default) picks other samples. The error stream says how many cycles ran
1910/// and, per result, the three parameters to measure first.
1911fn global_sensitivity(
1912    args: &Args,
1913    tr: &Translations,
1914    entry: &'static MachineEntry,
1915    cfg: &Config,
1916    method: &str,
1917    groups: &[&str],
1918) -> Result<(), Failure> {
1919    use sim_components::sensitivity::{morris, sobol};
1920    let whole = |name: &str, default: f64, least: f64| -> Result<usize, Failure> {
1921        let v = args.number(name)?.unwrap_or(default);
1922        if v.fract() != 0.0 || v < least || v > 1e9 {
1923            return Err(Failure("cli-error-bad-argument", format!("{name} {v}")));
1924        }
1925        Ok(v as usize)
1926    };
1927    let mut bounded = sim_components::analysis::bounds(cfg)?;
1928    if !groups.is_empty() {
1929        bounded.retain(|(path, ..)| groups.contains(&path.split('.').next().unwrap_or("")));
1930    }
1931    let (k, seed, wanted) = (bounded.len(), whole("--seed", 1.0, 0.0)? as u64, args.options("--result"));
1932    // Per result its rows as CSV fields after the rank, and the parameters in their order.
1933    let (header, runs, rankings): (&str, usize, Vec<(String, Vec<(String, String)>)>) = match method {
1934        "morris" => {
1935            let r = whole("--samples", 10.0, 1.0)?;
1936            let rankings = morris(entry, cfg, &bounded, r, seed)?;
1937            let rows = rankings.into_iter().map(|ranking| {
1938                let rows = ranking.rows.into_iter().map(|row| {
1939                    let fields =
1940                        format!("{},{},{}", significant(row.mu_star), significant(row.mu), significant(row.sigma));
1941                    (row.parameter, fields)
1942                });
1943                (ranking.result, rows.collect())
1944            });
1945            ("result,rank,parameter,mu_star,mu,sigma", r * (k + 1), rows.collect())
1946        }
1947        "sobol" => {
1948            let n = whole("--samples", 64.0, 2.0)?;
1949            let rankings = sobol(entry, cfg, &bounded, n, seed)?;
1950            let rows = rankings.into_iter().map(|ranking| {
1951                let rows = ranking.rows.into_iter().map(|row| {
1952                    let fields = format!(
1953                        "{:.3},{:.3},{:.3},{:.3},{:.3},{:.3}",
1954                        row.first, row.first_ci.0, row.first_ci.1, row.total, row.total_ci.0, row.total_ci.1
1955                    );
1956                    (row.parameter, fields)
1957                });
1958                (ranking.result, rows.collect())
1959            });
1960            ("result,rank,parameter,first,first_low,first_high,total,total_low,total_high", n * (k + 2), rows.collect())
1961        }
1962        _ => return Err(Failure("cli-error-bad-argument", format!("--method {method}"))),
1963    };
1964    if let Some(missing) = wanted.iter().find(|w| !rankings.iter().any(|(result, _)| result == *w)) {
1965        return Err(Failure("cli-error-bad-argument", format!("--result {missing}")));
1966    }
1967    eprintln!("{}", tr.tr_arg("cli-sensitivity-runs", &runs.to_string()));
1968    let mut out = output(args, "--out")?;
1969    writeln!(out, "{header}").map_err(io)?;
1970    for (result, rows) in rankings.iter().filter(|(result, _)| wanted.is_empty() || wanted.contains(&result.as_str())) {
1971        let first: Vec<&str> = rows.iter().take(3).map(|(parameter, _)| parameter.as_str()).collect();
1972        eprintln!("{}", tr.tr_arg("cli-measure-first", &format!("{result}: {}", first.join(", "))));
1973        for (rank, (parameter, fields)) in rows.iter().enumerate() {
1974            writeln!(out, "{result},{},{parameter},{fields}", rank + 1).map_err(io)?;
1975        }
1976    }
1977    out.flush().map_err(io)
1978}
1979
1980/// `analyze <machine>`: peak and RMS torque, peak speed and use of the torque-speed curve per motor
1981/// over one pass of the cycle, or over a trajectory or path (see `poses`). `--points FILE` also writes the operating points,
1982/// `--breakdown FILE` the peak and RMS of each part of each motor's torque (inertia, gravity, friction, rest, and the
1983/// torque itself), `--budget FILE` where the energy drawn from the supply went, in joules and as a share of it.
1984fn analyze(args: &Args, tr: &Translations) -> Result<(), Failure> {
1985    let (entry, cfg) = machine_and_config(args)?;
1986    let mut sim = Sim::new(entry, &cfg)?;
1987    // The effect views cost a machine evaluation per step: only when they are written.
1988    let views = args.option("--breakdown").is_some() || args.option("--budget").is_some();
1989    let load = match poses(args, &sim, &cfg, tr)? {
1990        Some(points) => analyse_trajectory_with(&mut sim, points, views),
1991        None => analyse_cycle_with(&mut sim, views),
1992    }
1993    .map_err(|e| Failure(e.key, String::new()))?;
1994    tell_start(tr, load.warm_start.map(|w| w.change), load.warm_start.and_then(|w| w.repeat));
1995    if let Some(w) = load.warm_start.filter(|w| w.period > 1) {
1996        eprintln!("{}", tr.tr_arg("cli-thermal-start-period", &w.period.to_string()));
1997    }
1998    if let Some(c) = load.conveyor {
1999        let detail = format!(
2000            "{:.2} / min, {:.3} mm, {:.2} / min",
2001            c.picks_per_minute,
2002            c.tracking_peak * 1e3,
2003            c.missed_per_minute
2004        );
2005        eprintln!("{}", tr.tr_arg("cli-conveyor", &detail));
2006    }
2007    let mut out = output(args, "--out")?;
2008    writeln!(out, "motor,cycle_s,peak_torque_nm,rms_torque_nm,peak_speed_rad_s,utilisation,thermal_utilisation,belt_tension_min_n,belt_tension_max_n,rms_current_a,winding_rise_k,energy_in_j,energy_regenerated_j,peak_regenerated_power_w,largest_regeneration_j,path_error_peak_m,path_error_rms_m,tracking_error_peak_m,dwell_error_peak_m,path_angle_error_peak_rad,path_angle_error_rms_rad,tracking_angle_error_peak_rad,dwell_angle_error_peak_rad,cubic_mean_torque_nm,braking_resistor_energy_j,braking_resistor_mean_power_w,dc_link_peak_voltage_v,belt_slack_time_s,radial_load_peak_n,guide_load_peak_n,guide_life_km,mains_energy_j,guide_life_h,pulley_bearing_life_h,gearbox_life_h,belt_tooth_utilisation,gearbox_gearing_life_h,motor_bearing_life_h,housing_rise_k,drive_overload,torque_unit,speed_unit").map_err(io)?;
2009    // The units of the motor's torque and speed columns (also of the points and the breakdown): N m and rad/s, N and m/s on a linear motor.
2010    let units = |k: usize| if sim.machine.motor_linear(k) { ("N", "m/s") } else { ("N m", "rad/s") };
2011    // Empty where the machine does not report the signal or the config has no load rating for the guide.
2012    let or_empty = |value: Option<f64>| value.map_or(String::new(), |v| format!("{v:.4e}"));
2013    let machine_wide = format!(
2014        "{},{},{},{}",
2015        or_empty(load.belt_slack_time),
2016        or_empty(load.radial_load_peak),
2017        or_empty(load.guide_load.map(|g| g.0)),
2018        or_empty(sim_components::analysis::guide_life_km(&cfg, &load))
2019    );
2020    for (k, (motor, m)) in sim.machine.motors().iter().zip(&load.motors).enumerate() {
2021        let belt = load.belt_tension.map_or(String::from(","), |(low, high)| format!("{low:.2},{high:.2}"));
2022        let electrical = format!(
2023            "{:.4},{:.2},{:.3},{:.3},{:.2},{:.3}",
2024            m.rms_current,
2025            m.winding_rise,
2026            m.energy_in,
2027            m.energy_regenerated,
2028            m.peak_regenerated_power,
2029            m.largest_regeneration
2030        );
2031        let electrical = format!(
2032            "{electrical},{:.3e},{:.3e},{:.3e},{:.3e},{:.3e},{:.3e},{:.3e},{:.3e}",
2033            load.path_error_peak,
2034            load.path_error_rms,
2035            load.tracking_error_peak,
2036            load.dwell_error_peak,
2037            load.path_angle_error_peak,
2038            load.path_angle_error_rms,
2039            load.tracking_angle_error_peak,
2040            load.dwell_angle_error_peak
2041        );
2042        let electrical = format!(
2043            "{electrical},{:.6},{:.3},{:.3},{:.2},{machine_wide},{:.3}",
2044            m.cubic_mean_torque,
2045            m.resistor_energy,
2046            m.resistor_energy / load.duration,
2047            m.peak_dc_link_voltage,
2048            m.mains_energy
2049        );
2050        // Lives in hours and the belt's tooth load; empty where the machine or the config lacks what they need.
2051        let tooth = sim_components::analysis::belt_tooth_utilisation(&cfg, m)?;
2052        let lives = [
2053            sim_components::analysis::guide_life_h(&cfg, &load),
2054            sim_components::analysis::pulley_bearing_life_h(&cfg, m),
2055            sim_components::analysis::gearbox_life_h(&cfg, m),
2056            tooth,
2057            sim_components::analysis::gearbox_gearing_life_h(&cfg, m),
2058            sim_components::analysis::motor_bearing_life_h(&cfg, m),
2059        ];
2060        let electrical = format!("{electrical},{}", lives.map(or_empty).join(","));
2061        // effects.motor_thermal_nodes and effects.drive_overload; 0 with them off.
2062        let electrical = format!("{electrical},{:.2},{:.4}", m.housing_rise, m.drive_overload);
2063        writeln!(
2064            out,
2065            "{},{:.6},{:.6},{:.6},{:.4},{:.4},{:.4},{belt},{electrical},{},{}",
2066            motor.id,
2067            load.duration,
2068            m.peak_torque,
2069            m.rms_torque,
2070            m.peak_speed,
2071            m.utilisation,
2072            m.thermal_utilisation,
2073            units(k).0,
2074            units(k).1
2075        )
2076        .map_err(io)?;
2077    }
2078    out.flush().map_err(io)?;
2079    if args.option("--points").is_some() {
2080        let mut out = output(args, "--points")?;
2081        writeln!(out, "motor,speed_rad_s,torque_nm,speed_unit,torque_unit").map_err(io)?;
2082        for (k, (motor, m)) in sim.machine.motors().iter().zip(&load.motors).enumerate() {
2083            for (speed, torque) in &m.points {
2084                writeln!(out, "{},{speed:.6e},{torque:.6e},{},{}", motor.id, units(k).1, units(k).0).map_err(io)?;
2085            }
2086        }
2087        out.flush().map_err(io)?;
2088    }
2089    if args.option("--breakdown").is_some() {
2090        let mut out = output(args, "--breakdown")?;
2091        writeln!(out, "motor,part,peak_torque_nm,rms_torque_nm,torque_unit").map_err(io)?;
2092        for (k, (motor, m)) in sim.machine.motors().iter().zip(&load.motors).enumerate() {
2093            for (part, (peak, rms)) in sim_core::TORQUE_PARTS.iter().zip(m.torque_parts.iter().flatten()) {
2094                writeln!(out, "{},{part},{peak:.6e},{rms:.6e},{}", motor.id, units(k).0).map_err(io)?;
2095            }
2096            writeln!(out, "{},torque,{:.6e},{:.6e},{}", motor.id, m.peak_torque, m.rms_torque, units(k).0)
2097                .map_err(io)?;
2098        }
2099        out.flush().map_err(io)?;
2100    }
2101    if args.option("--budget").is_some() {
2102        let mut out = output(args, "--budget")?;
2103        writeln!(out, "item,energy_j,share").map_err(io)?;
2104        if let Some(budget) = &load.budget {
2105            let rows = budget.rows.iter().map(|r| (r.id.as_str(), r.energy));
2106            for (item, energy) in
2107                std::iter::once(("supply", budget.supply)).chain(rows).chain([("unaccounted", budget.unaccounted())])
2108            {
2109                writeln!(out, "{item},{energy:.6e},{:.6}", energy / budget.supply).map_err(io)?;
2110            }
2111        }
2112        out.flush().map_err(io)?;
2113    }
2114    Ok(())
2115}
2116
2117/// `sweep <machine>`: mechanical frequency response from one motor's torque to its speed.
2118fn sweep(args: &Args) -> Result<(), Failure> {
2119    let (entry, cfg) = machine_and_config(args)?;
2120    let number = |name: &str, default: f64| args.number(name).map(|v| v.unwrap_or(default));
2121    let frequencies =
2122        log_spaced(number("--from", 5.0)?, number("--to", 500.0)?, number("--count", SWEEP_POINTS as f64)? as usize);
2123    let points = frequency_sweep(
2124        entry,
2125        &cfg,
2126        number("--motor", 0.0)? as usize,
2127        &frequencies,
2128        number("--amplitude", default_sweep_amplitude(entry, &cfg)?)?,
2129    )?;
2130    let mut out = output(args, "--out")?;
2131    writeln!(out, "frequency_hz,gain_rad_s_per_nm,phase_deg").map_err(io)?;
2132    for p in points {
2133        writeln!(out, "{:.4},{:.6e},{:.3}", p.frequency, p.gain, p.phase_deg).map_err(io)?;
2134    }
2135    out.flush().map_err(io)
2136}
2137
2138fn number(args: &Args, name: &str, default: f64) -> Result<f64, Failure> {
2139    args.number(name).map(|v| v.unwrap_or(default))
2140}
2141
2142/// `--axis-index N` of `step` and `bode`: a whole number naming one of the machine's axes, from 0. A float read
2143/// and cast took -1 as 0 and 1.7 as 1.
2144fn axis_index(args: &Args, entry: &MachineEntry, cfg: &Config) -> Result<usize, Failure> {
2145    let count = (entry.build)(cfg)?.axes().len();
2146    match args.option("--axis-index").map(|v| v.parse::<usize>()) {
2147        None => Ok(0),
2148        Some(Ok(i)) if i < count => Ok(i),
2149        _ => Err(Failure("cli-error-axis-index", (count - 1).to_string())),
2150    }
2151}
2152
2153/// `step <machine>`: the answer of one axis to a small step of its position setpoint.
2154fn step(args: &Args) -> Result<(), Failure> {
2155    let (entry, cfg) = machine_and_config(args)?;
2156    let response = step_response(
2157        entry,
2158        &cfg,
2159        axis_index(args, entry, &cfg)?,
2160        number(args, "--size", 0.001)?,
2161        number(args, "--time", 0.5)?,
2162    )?;
2163    let mut out = output(args, "--out")?;
2164    writeln!(out, "time_s,setpoint,response").map_err(io)?;
2165    for (t, y) in &response.trace {
2166        writeln!(out, "{t:.6},{:.9e},{y:.9e}", response.size).map_err(io)?;
2167    }
2168    out.flush().map_err(io)
2169}
2170
2171/// `bode <machine>`: closed-loop frequency response of the position loop of one axis.
2172fn bode(args: &Args) -> Result<(), Failure> {
2173    let (entry, cfg) = machine_and_config(args)?;
2174    let frequencies =
2175        log_spaced(number(args, "--from", 1.0)?, number(args, "--to", 200.0)?, number(args, "--count", 40.0)? as usize);
2176    let points = closed_loop_response(
2177        entry,
2178        &cfg,
2179        axis_index(args, entry, &cfg)?,
2180        &frequencies,
2181        number(args, "--amplitude", 0.0005)?,
2182    )?;
2183    let mut out = output(args, "--out")?;
2184    writeln!(out, "frequency_hz,gain,gain_db,phase_deg").map_err(io)?;
2185    for p in points {
2186        writeln!(out, "{:.4},{:.6e},{:.3},{:.3}", p.frequency, p.gain, 20.0 * p.gain.log10(), p.phase_deg)
2187            .map_err(io)?;
2188    }
2189    out.flush().map_err(io)
2190}
2191
2192/// `tuning <machine>`: one line per axis with what the step and frequency responses say.
2193fn tuning(args: &Args) -> Result<(), Failure> {
2194    let (entry, cfg) = machine_and_config(args)?;
2195    let axes: Vec<&str> = (entry.build)(&cfg)?.axes().iter().map(|a| a.id).collect();
2196    let mut out = output(args, "--out")?;
2197    writeln!(out, "axis,rise_time_s,overshoot,settling_time_s,bandwidth_hz").map_err(io)?;
2198    // The bandwidth needs the response up to its first point below -3 dB: measured a batch of frequencies at a time, as
2199    // many as there are processors, lowest first, up to the batch that has that point.
2200    let batch = std::thread::available_parallelism().map_or(1, |n| n.get());
2201    for (i, axis) in axes.iter().enumerate() {
2202        let step = step_response(entry, &cfg, i, number(args, "--size", 0.001)?, 0.5)?;
2203        let mut response = Vec::new();
2204        for frequencies in log_spaced(1.0, 200.0, 30).chunks(batch) {
2205            response.extend(closed_loop_response(entry, &cfg, i, frequencies, number(args, "--amplitude", 0.0005)?)?);
2206            if bandwidth(&response).is_some() {
2207                break;
2208            }
2209        }
2210        let band = bandwidth(&response).map_or(String::new(), |f| format!("{f:.3}"));
2211        writeln!(out, "{axis},{:.5},{:.4},{:.5},{band}", step.rise_time, step.overshoot, step.settling_time)
2212            .map_err(io)?;
2213    }
2214    out.flush().map_err(io)
2215}
2216
2217/// `margins <machine> [--bands]`: per motor the stability margins of its velocity loop (`velocity_loop_margins`), for
2218/// the config as it is at each pose its cycle stops at (`margin_poses`; the start pose's run is named "") and with
2219/// `--bands` with each value of `[bounds]` at its low and at its high bound at the start pose. With several poses each
2220/// motor's least phase margin, gain margin and margin across the play over them is named on stderr with its pose. A row whose
2221/// loop is unstable, whose measurement is not valid or that hammers across its gearbox's play (`LoopMargins::stable`)
2222/// says FAIL; one that hammers is named on stderr with the frequency and the torque's peak. The column before it is the
2223/// describing function's gain margin across the play (`LoopMargins::play_margin_db`, dB; empty where no play acts on the
2224/// loop), told and not judged.
2225fn margins(args: &Args, tr: &Translations) -> Result<(), Failure> {
2226    use sim_components::analysis::{bounds, velocity_loop_margins};
2227    let (entry, cfg) = machine_and_config(args)?;
2228    let motors = (entry.build)(&cfg)?.motors().to_vec();
2229    let runs = velocity_loop_margins(entry, &cfg, &if args.flag("--bands") { bounds(&cfg)? } else { Vec::new() })?;
2230    let mut out = output(args, "--out")?;
2231    writeln!(out, "run,motor,crossover_hz,phase_margin_deg,gain_margin_db,peak_sensitivity,peak_frequency_hz,play_margin_db,result")
2232        .map_err(io)?;
2233    for (run, margins) in &runs {
2234        for (motor, m) in motors.iter().zip(margins) {
2235            let result = judged(m.stable());
2236            if let Some(h) = m.hammering {
2237                let at = format!("{:.0} Hz, {:.2} N m", h.frequency_hz, h.torque_nm);
2238                let run = if run.is_empty() { String::new() } else { format!("{run}, ") };
2239                eprintln!("{run}{}: {}", tr.tr(motor.key), tr.tr_arg("loop-hammers", &at));
2240            }
2241            // No gain crossover in the band (or no valid measurement): crossover and phase margin left empty, as a
2242            // missing band in `tuning`; the result is then the gain margin's alone.
2243            let cell = |x: f64| if x.is_nan() { String::new() } else { format!("{x:.1}") };
2244            let play = if m.play_margin_db.is_nan() { String::new() } else { format!("{:.2}", m.play_margin_db) };
2245            writeln!(
2246                out,
2247                "{run},{},{},{},{:.2},{:.3},{:.1},{play},{result}",
2248                motor.id,
2249                cell(m.crossover_hz),
2250                cell(m.phase_margin_deg),
2251                m.gain_margin_db,
2252                m.peak_sensitivity,
2253                m.peak_frequency_hz
2254            )
2255            .map_err(io)?;
2256        }
2257    }
2258    // The poses' runs come first (`velocity_loop_margins`): where over them each margin is least.
2259    let poses = runs.iter().take_while(|(run, _)| run.is_empty() || run.starts_with("start.pose=")).count();
2260    for (k, motor) in motors.iter().enumerate().filter(|_| poses > 1) {
2261        let least = |of: fn(&sim_components::analysis::LoopMargins) -> f64, unit: &str| {
2262            let (value, run) = runs[..poses]
2263                .iter()
2264                .map(|(run, m)| (of(&m[k]), run))
2265                .filter(|(x, _)| !x.is_nan())
2266                .min_by(|a, b| a.0.total_cmp(&b.0))?;
2267            Some(format!("{value:.2} {unit} {}", if run.is_empty() { "start.pose" } else { run }))
2268        };
2269        let found: Vec<String> = [
2270            least(|m| m.phase_margin_deg, "deg"),
2271            least(|m| m.gain_margin_db, "dB"),
2272            least(|m| m.play_margin_db, "dB"),
2273        ]
2274        .into_iter()
2275        .flatten()
2276        .collect();
2277        eprintln!("{}: {}", tr.tr(motor.key), tr.tr_arg("loop-least-over-poses", &found.join(", ")));
2278    }
2279    out.flush().map_err(io)
2280}
2281
2282/// `tune <machine> [--phase-margin DEG] [--gain-margin DB] [--no-notch]`: per motor the largest velocity gain at which
2283/// the least phase and gain margin over the cycle's poses meet the targets (35 degrees and 6 dB by default), with Tn and
2284/// Kv following (`tune::velocity_loops`). One row per key (motor, key, before, after) with the least margins over the
2285/// poses before and after, each with its pose; a row of a motor whose targets are not met says FAIL (exit code 1). On
2286/// stderr: what the tuning did beyond the gain (a notch, a gain lowered by the joint check) and the `--set` words that
2287/// make the tuned config. Nothing is written to a file.
2288fn tune(args: &Args, tr: &Translations) -> Result<(), Failure> {
2289    let (entry, cfg) = machine_and_config(args)?;
2290    let defaults = sim_components::tune::Targets::default();
2291    let targets = sim_components::tune::Targets {
2292        phase_margin_deg: number(args, "--phase-margin", defaults.phase_margin_deg)?,
2293        gain_margin_db: number(args, "--gain-margin", defaults.gain_margin_db)?,
2294        notch: !args.flag("--no-notch"),
2295    };
2296    let tuned = sim_components::tune::velocity_loops(entry, &cfg, &targets)?;
2297    let mut out = output(args, "--out")?;
2298    writeln!(
2299        out,
2300        "motor,key,before,after,phase_before_deg,phase_before_pose,gain_before_db,gain_before_pose,\
2301         phase_after_deg,phase_after_pose,gain_after_db,gain_after_pose,result"
2302    )
2303    .map_err(io)?;
2304    let pose = |p: &str| if p.is_empty() { "start.pose".to_string() } else { p.to_string() };
2305    let cell = |x: f64| if x.is_nan() { String::new() } else { format!("{x:.2}") };
2306    for m in &tuned.motors {
2307        let (b, a) = (&m.before_least, &m.after_least);
2308        let margins = format!(
2309            "{},{},{},{},{},{},{},{}",
2310            cell(b.phase_deg),
2311            pose(&b.phase_pose),
2312            cell(b.gain_db),
2313            pose(&b.gain_pose),
2314            cell(a.phase_deg),
2315            pose(&a.phase_pose),
2316            cell(a.gain_db),
2317            pose(&a.gain_pose)
2318        );
2319        let result = judged(m.met);
2320        writeln!(out, "{},{},{:?},{:?},{margins},{result}", m.id, m.kp_key, m.before.kp, m.after.kp).map_err(io)?;
2321        if m.after.kv != m.before.kv {
2322            writeln!(out, "{},{},{:?},{:?},{margins},{result}", m.id, m.kv_key, m.before.kv, m.after.kv).map_err(io)?;
2323        }
2324        if m.lowered_in_joint_check {
2325            eprintln!("{}", tr.tr_arg("tune-lowered", &m.id));
2326        }
2327    }
2328    for n in &tuned.notches {
2329        let id = &tuned.motors[n.motor].id;
2330        let at = format!("{id}: {:.1} Hz, {:.1} Hz, {:.2}", n.frequency_hz, n.bandwidth_hz, n.gain_factor);
2331        eprintln!("{}", tr.tr_arg("tune-notch", &at));
2332    }
2333    if !tuned.met {
2334        eprintln!("{}", tr.tr("tune-not-met"));
2335    }
2336    let words: Vec<String> = tuned.settings().iter().flat_map(|s| ["--set".to_string(), s.clone()]).collect();
2337    eprintln!("{}", words.join(" "));
2338    out.flush().map_err(io)
2339}
2340
2341/// `modes <machine>`: the modes the machine reports over the stroke of one axis (`--axis-index`, the first by default) at
2342/// `--points` places (21 by default), the other axes at the start pose: position, then frequency and damping ratio of
2343/// each mode, lowest first; a mode a place does not have is left empty. Where the machine's small-amplitude modes
2344/// (`Machine::modes_small_amplitude`, a gearbox's hysteresis stiffness) differ, each mode has a third column with that
2345/// frequency, `mode<i>_small_hz`.
2346fn modes(args: &Args) -> Result<(), Failure> {
2347    let (entry, cfg) = machine_and_config(args)?;
2348    if args.flag("--shapes") {
2349        return mode_shapes(args, entry, &cfg);
2350    }
2351    let (axis, points) = (axis_index(args, entry, &cfg)?, number(args, "--points", 21.0)?);
2352    if points < 2.0 || points.fract() != 0.0 {
2353        return Err(Failure("cli-error-bad-argument", format!("--points {points}")));
2354    }
2355    let sim = Sim::new(entry, &cfg)?;
2356    // At the configured start pose, where the tool stands, not the plan at rest (the motors' pose by the rigid
2357    // kinematics, off it by the belt's stretch).
2358    let pose = cfg.f64s("start.pose")?;
2359    let rows = sim_components::analysis::modes_along(sim.machine.as_ref(), &pose, axis, points as usize);
2360    let small = sim_components::analysis::small_amplitude_along(sim.machine.as_ref(), &pose, axis, &rows);
2361    let count = rows.iter().map(|(_, modes)| modes.len()).max().unwrap_or(0);
2362    let mut out = output(args, "--out")?;
2363    let extra = |i: usize| if small.is_some() { format!(",mode{i}_small_hz") } else { String::new() };
2364    let header: String = (1..=count).map(|i| format!(",mode{i}_hz,mode{i}_damping{}", extra(i))).collect();
2365    writeln!(out, "position{header}").map_err(io)?;
2366    for (k, (position, modes)) in rows.iter().enumerate() {
2367        let cells: String = (0..count)
2368            .map(|i| {
2369                let large = modes.get(i).map_or(",,".into(), |m| format!(",{:.4},{:.5}", m.hz, m.damping));
2370                let small = small
2371                    .as_ref()
2372                    .map_or(String::new(), |s| s[k].get(i).map_or(",".into(), |m| format!(",{:.4}", m.hz)));
2373                large + &small
2374            })
2375            .collect();
2376        writeln!(out, "{position:.6}{cells}").map_err(io)?;
2377    }
2378    out.flush().map_err(io)
2379}
2380
2381/// `modes <machine> --shapes`: the modes at the start pose as the app's mode list has them (`shapes::mode_views`): per
2382/// mode its frequency and damping as the machine reports them, those of the linearised model's mode its shape is of,
2383/// where the shape comes from (`machine` or `linearised`), the share of its strain energy per kind of stiffness, and
2384/// the shape itself, per entry of the state its real and imaginary part.
2385fn mode_shapes(args: &Args, entry: &'static MachineEntry, cfg: &Config) -> Result<(), Failure> {
2386    let views = sim_components::shapes::mode_views(entry, cfg, &cfg.f64s("start.pose")?)?;
2387    let n = views.first().map_or(0, |v| v.shape.re.len());
2388    let mut out = output(args, "--out")?;
2389    let states: String = (0..n).map(|i| format!(",s{i}_re,s{i}_im")).collect();
2390    writeln!(out, "mode,hz,damping,linear_hz,linear_damping,shape,stiffness{states}").map_err(io)?;
2391    for (i, v) in views.iter().enumerate() {
2392        let linear = v.linear.map_or(",".into(), |l| format!("{:.4},{:.5}", l.hz, l.damping));
2393        let stiffness: Vec<String> = v.stiffness.iter().map(|(kind, share)| format!("{kind}={share:.4}")).collect();
2394        let shape: String = v.shape.re.iter().zip(&v.shape.im).map(|(re, im)| format!(",{re:.6e},{im:.6e}")).collect();
2395        let source = if v.from_machine { "machine" } else { "linearised" };
2396        writeln!(out, "{},{:.4},{:.5},{linear},{source},{}{shape}", i + 1, v.hz, v.damping, stiffness.join(";"))
2397            .map_err(io)?;
2398    }
2399    out.flush().map_err(io)
2400}
2401
2402/// `workspace <machine>`: the app's workspace map as CSV (`shapes::workspace_slice`): a horizontal slice at `--z` (the
2403/// middle of the third axis's range by default) with `--points` nodes a side (61): per node x, y, the condition number
2404/// (inf out of reach), whether the machine goes there (1) and the largest tool acceleration in the worst direction in
2405/// m/s^2, with each motor's peak torque.
2406fn workspace(args: &Args) -> Result<(), Failure> {
2407    let (entry, cfg) = machine_and_config(args)?;
2408    let points = number(args, "--points", 61.0)?;
2409    if points < 2.0 || points.fract() != 0.0 {
2410        return Err(Failure("cli-error-bad-argument", format!("--points {points}")));
2411    }
2412    let sim = Sim::new(entry, &cfg)?;
2413    let axes = sim.machine.axes();
2414    let none = || Failure("cli-error-no-workspace", entry.id.to_string());
2415    let third = axes.get(2).ok_or_else(none)?;
2416    let z = number(args, "--z", (third.min + third.max) / 2.0)?.clamp(third.min, third.max);
2417    let peak: Vec<f64> = (0..sim.machine.motors().len()).map(|k| sim.control.drive_params_of(k).peak_torque).collect();
2418    let slice =
2419        sim_components::shapes::workspace_slice(sim.machine.as_ref(), z, points as usize, &peak).ok_or_else(none)?;
2420    let mut out = output(args, "--out")?;
2421    writeln!(out, "x,y,condition,goes,acceleration_m_s2").map_err(io)?;
2422    let at = |(low, high): (f64, f64), i: usize| low + (high - low) * i as f64 / (slice.n - 1) as f64;
2423    for k in 0..slice.n * slice.n {
2424        let (x, y) = (at(slice.x, k % slice.n), at(slice.y, k / slice.n));
2425        let (condition, acceleration) = (slice.condition[k], slice.acceleration[k]);
2426        writeln!(out, "{x:.6},{y:.6},{condition:.6},{},{acceleration:.4}", u8::from(slice.goes[k])).map_err(io)?;
2427    }
2428    out.flush().map_err(io)
2429}
2430
2431/// `run <machine>`: simulate a move or the cycle and write every signal as CSV. `--disable-at SECONDS`
2432/// switches the drives off at that time, to show the axes held by the brakes, coasting or falling; `--stop-at SECONDS`
2433/// stops them in the category of `--stop-category` (`Command::Halt`). Where the config has
2434/// obstacles, the error stream says what the motion keeps from them as planned before the run, and the least clearance
2435/// and first contact of the run after it.
2436fn run(args: &Args, tr: &Translations) -> Result<(), Failure> {
2437    let mut sim = start(args, tr)?;
2438    let seconds = args.number("--time")?.unwrap_or(2.0);
2439    let every = args.number("--every")?.unwrap_or(16.0).max(1.0) as u64;
2440    let disable_at = args.number("--disable-at")?.map(|seconds| (seconds / sim.dt).round() as u64);
2441    let stop_at = args.number("--stop-at")?.map(|seconds| (seconds / sim.dt).round() as u64);
2442    let category = stop_category(args, "--stop-category")?;
2443    let mut out = output(args, "--out")?;
2444    let header: Vec<String> = sim.signal_infos().iter().map(|s| format!("{}[{}]", s.id, s.unit)).collect();
2445    writeln!(out, "{}", header.join(",")).map_err(io)?;
2446    let mut sample = Vec::new();
2447    for step in 0..=(seconds / sim.dt).round() as u64 {
2448        if step % every == 0 {
2449            sim.sample(&mut sample);
2450            for (i, v) in sample.iter().enumerate() {
2451                write!(out, "{}{v:.9e}", if i == 0 { "" } else { "," }).map_err(io)?;
2452            }
2453            writeln!(out).map_err(io)?;
2454        }
2455        if Some(step) == disable_at {
2456            sim.command(Command::Disable).map_err(|e| Failure(e.key, String::new()))?;
2457        }
2458        if Some(step) == stop_at {
2459            sim.command(Command::Halt(category)).map_err(|e| Failure(e.key, String::new()))?;
2460        }
2461        sim.step();
2462    }
2463    tell_run(tr, &sim);
2464    out.flush().map_err(io)
2465}
2466
2467/// The stop category of `option` (0, 1 or 2; 0 without it).
2468fn stop_category(args: &Args, option: &str) -> Result<sim_components::StopCategory, Failure> {
2469    let Some(text) = args.option(option) else { return Ok(sim_components::StopCategory::Zero) };
2470    text.parse()
2471        .ok()
2472        .and_then(sim_components::StopCategory::from_number)
2473        .ok_or_else(|| Failure("cli-error-bad-argument", format!("{option} {text}")))
2474}
2475
2476/// `stop <machine> [--category N] [--points N]`: the stopping distance (`sim_components::stop::study`): the cycle, or the
2477/// path of `--path FILE`, run once and stopped in category N (0 without it) at the moments each axis is fastest, the
2478/// energy is largest, and at N moments evenly over the pass (20 without `--points`). One CSV line per stop, then the
2479/// worst again; its moment and the verdicts on it to the error stream.
2480fn stop(args: &Args, tr: &Translations) -> Result<(), Failure> {
2481    use sim_components::stop::{Moment, Stop};
2482    let (entry, cfg) = machine_and_config(args)?;
2483    let cfg = path_instead(args, entry, cfg)?;
2484    let category = stop_category(args, "--category")?;
2485    let points = match args.number("--points")? {
2486        Some(n) if n.fract() != 0.0 || !(0.0..=10_000.0).contains(&n) => {
2487            return Err(Failure("cli-error-bad-argument", format!("--points {n}")));
2488        }
2489        Some(n) => n as usize,
2490        None => 20,
2491    };
2492    let study = sim_components::stop::study(entry, &cfg, category, points)?;
2493    let axes = (entry.build)(&cfg)?.axes().to_vec();
2494    let mut out = output(args, "--out")?;
2495    let distances: Vec<String> = axes.iter().map(|a| format!("{}_distance[{}]", a.id, a.unit)).collect();
2496    // As `stop::study` measures: over the axes in m, or over all of them where none is (then rad).
2497    let unit = if axes.iter().any(|a| a.unit == "m") { "m" } else { "rad" };
2498    writeln!(
2499        out,
2500        "moment,trigger[s],tool_distance[{unit}],stop_time[s],peak_deceleration[{unit}/s2],hard_stop,peak_dc_link[V],\
2501         braking_resistor_energy[J],tripped,{}",
2502        distances.join(",")
2503    )
2504    .map_err(io)?;
2505    let row = |s: &Stop, moment: String| {
2506        let axes: Vec<String> = s.axis_distance.iter().map(|d| format!("{d:.6}")).collect();
2507        format!(
2508            "{moment},{:.4},{:.6},{:.4},{:.3},{},{:.2},{:.4},{},{}",
2509            s.at,
2510            s.tool_distance,
2511            s.time,
2512            s.peak_deceleration,
2513            s.hard_stop,
2514            s.peak_dc_voltage,
2515            s.resistor_energy,
2516            s.tripped,
2517            axes.join(",")
2518        )
2519    };
2520    let moment = |m: Moment| match m {
2521        Moment::Grid => "grid".to_string(),
2522        Moment::Fastest(k) => format!("fastest_{}", axes[k].id),
2523        Moment::Energy => "energy".to_string(),
2524    };
2525    for s in &study.stops {
2526        writeln!(out, "{}", row(s, moment(s.moment))).map_err(io)?;
2527    }
2528    if let Some(worst) = study.stops.get(study.worst) {
2529        writeln!(out, "{}", row(worst, "worst".into())).map_err(io)?;
2530        eprintln!("{}", tr.tr_arg("cli-stop-worst", &format!("{:.4} s ({})", worst.at, moment(worst.moment))));
2531    }
2532    for v in &study.verdicts {
2533        let result = judged(v.ok);
2534        let detail = format!("{}: {} / {} {result}", v.check, significant(v.value), significant(v.limit));
2535        eprintln!("{}", tr.tr_arg("cli-stop-verdict", &detail));
2536    }
2537    tell_not_finite(tr, &study.verdicts);
2538    out.flush().map_err(io)
2539}
2540
2541/// `accuracy <machine> [--points N] [--repeats N] [--dwell SECONDS]`: the static positioning accuracy and repeatability
2542/// (`sim_components::accuracy::study`), N targets per axis (5), each approached N times from each side (5), resting
2543/// `--dwell` seconds at each (0.3). One CSV line per axis and target with the mean deviations and their standard
2544/// deviations from below and above; per axis the ISO 230-2 figures, at the tool the ISO 9283 ones, and the verdicts to
2545/// the error stream.
2546fn accuracy(args: &Args, tr: &Translations) -> Result<(), Failure> {
2547    let (entry, cfg) = machine_and_config(args)?;
2548    let defaults = sim_components::accuracy::Settings::default();
2549    let count = |option: &str, default: usize, least: f64| match args.number(option)? {
2550        Some(n) if n.fract() != 0.0 || !(least..=1000.0).contains(&n) => {
2551            Err(Failure("cli-error-bad-argument", format!("{option} {n}")))
2552        }
2553        Some(n) => Ok(n as usize),
2554        None => Ok(default),
2555    };
2556    let dwell_s = match args.number("--dwell")? {
2557        Some(d) if !(d > 0.0 && d <= 60.0) => return Err(Failure("cli-error-bad-argument", format!("--dwell {d}"))),
2558        Some(d) => d,
2559        None => defaults.dwell_s,
2560    };
2561    let settings = sim_components::accuracy::Settings {
2562        points: count("--points", defaults.points, 2.0)?,
2563        repeats: count("--repeats", defaults.repeats, 1.0)?,
2564        dwell_s,
2565    };
2566    let study = sim_components::accuracy::study(entry, &cfg, settings)?;
2567    let axes = (entry.build)(&cfg)?.axes().to_vec();
2568    let mut out = output(args, "--out")?;
2569    writeln!(out, "axis,unit,target,mean_up,mean_down,std_up,std_down,reversal").map_err(io)?;
2570    for r in &study.axes {
2571        let a = &axes[r.axis];
2572        for j in 0..r.targets.len() {
2573            writeln!(
2574                out,
2575                "{},{},{:.6},{:.4e},{:.4e},{:.4e},{:.4e},{:.4e}",
2576                a.id,
2577                a.unit,
2578                r.targets[j],
2579                r.mean_up[j],
2580                r.mean_down[j],
2581                r.std_up[j],
2582                r.std_down[j],
2583                r.mean_up[j] - r.mean_down[j]
2584            )
2585            .map_err(io)?;
2586        }
2587        let detail = format!(
2588            "{} [{}]: B {:.3e}, R {:.3e}, E {:.3e}, M {:.3e}, A {:.3e}",
2589            a.id, a.unit, r.reversal, r.repeatability, r.systematic, r.mean_range, r.accuracy
2590        );
2591        eprintln!("{}", tr.tr_arg("cli-accuracy-axis", &detail));
2592    }
2593    let t = &study.tool;
2594    let detail = format!("AP {:.3e}, RP {:.3e}, vAP {:.3e}", t.accuracy, t.repeatability, t.direction_variation);
2595    eprintln!("{}", tr.tr_arg("cli-accuracy-tool", &detail));
2596    for v in &study.verdicts {
2597        let result = judged(v.ok);
2598        let detail = format!("{}: {} / {} {result}", v.check, significant(v.value), significant(v.limit));
2599        eprintln!("{}", tr.tr_arg("cli-accuracy-verdict", &detail));
2600    }
2601    tell_not_finite(tr, &study.verdicts);
2602    out.flush().map_err(io)
2603}
2604
2605/// `fmu <machine> --out FILE.fmu [--fmi 2|3]`: the machine with its config as an FMI 2.0 (the default) or 3.0
2606/// Co-Simulation FMU (see `sim_fmi`), with the descriptions in the language of `--lang`. Its binaries are the files
2607/// `--binary` names (it may repeat: for FMI 2.0 a .dll goes to win64, a .so to linux64, a .dylib to darwin64; for
2608/// FMI 3.0 to `<architecture>-<system>`, the architecture read from the binary), or else the sim-fmi library built
2609/// next to this program. A machine file (`--machine-file`) goes into the FMU's resources, which builds its machine from it.
2610fn fmu(args: &Args) -> Result<(), Failure> {
2611    let (entry, cfg) = machine_and_config(args)?;
2612    let path = args.option("--out").ok_or(Failure("cli-error-missing-value", "--out".into()))?;
2613    let fmi = match args.option("--fmi") {
2614        None | Some("2") => 2,
2615        Some("3") => 3,
2616        Some(other) => return Err(Failure("cli-error-bad-argument", format!("--fmi {other}"))),
2617    };
2618    let model = sim_fmi::Model::with_fmi(entry, &cfg.to_text()?, args.option("--lang").unwrap_or("en"), fmi)?;
2619    let mut binaries: Vec<std::path::PathBuf> = args.options("--binary").into_iter().map(Into::into).collect();
2620    if binaries.is_empty() {
2621        let name =
2622            format!("{}{}{}", std::env::consts::DLL_PREFIX, sim_fmi::MODEL_IDENTIFIER, std::env::consts::DLL_SUFFIX);
2623        let beside = std::env::current_exe().map_err(io)?.with_file_name(name);
2624        binaries.push(beside);
2625    }
2626    let mut files = model.files();
2627    let mut platforms: Vec<(String, &std::path::PathBuf)> = Vec::new();
2628    for binary in &binaries {
2629        let file_name = binary.file_name().and_then(|n| n.to_str()).unwrap_or("");
2630        let bad = || Failure("cli-error-bad-argument", format!("--binary {}", binary.display()));
2631        let inside = sim_fmi::binary_path(file_name).ok_or_else(bad)?;
2632        let bytes =
2633            std::fs::read(binary).map_err(|e| Failure("cli-error-fmu-binary", format!("{}: {e}", binary.display())))?;
2634        let inside = if fmi == 3 { sim_fmi::binary_path3(file_name, &bytes).ok_or_else(bad)? } else { inside };
2635        // Two binaries for one platform would be two entries of one name in the archive.
2636        if let Some((_, other)) = platforms.iter().find(|(path, _)| *path == inside) {
2637            return Err(Failure(
2638                "cli-error-conflict",
2639                format!("--binary {} --binary {}", other.display(), binary.display()),
2640            ));
2641        }
2642        platforms.push((inside.clone(), binary));
2643        files.push((inside, bytes));
2644    }
2645    std::fs::write(path, sim_fmi::zip(&files)).map_err(|e| Failure("cli-error-io", format!("{path}: {e}")))
2646}
2647
2648/// `report <machine> --out FILE`: the sizing report a customer signs (`sim_components::report`): the machine, plots of
2649/// the cycle, every verdict with value, limit and margin, where each input comes from, and a sign-off block. PDF for a
2650/// file ending in .pdf, HTML otherwise; `--bands` adds the error bands. The result goes to the error stream.
2651fn report(args: &Args, tr: &Translations) -> Result<(), Failure> {
2652    let path = args.option("--out").ok_or(Failure("cli-error-missing-value", "--out".into()))?;
2653    let ((entry, named), (_, cfg)) = (named_config(args)?, machine_and_config(args)?);
2654    let (text, source) = match args.option("--config") {
2655        Some(file) => (read(file)?, file.to_string()),
2656        None => (entry.default_config.to_string(), tr.tr("report-default-config").to_string()),
2657    };
2658    let report = sim_components::report::make(entry, &text, &source, &named, &cfg, args.flag("--bands"), tr)?;
2659    let bytes = if path.to_lowercase().ends_with(".pdf") {
2660        report.pdf()
2661    } else {
2662        report.html(args.option("--lang").unwrap_or("en")).into_bytes()
2663    };
2664    std::fs::write(path, bytes).map_err(|e| Failure("cli-error-io", format!("{path}: {e}")))?;
2665    eprintln!("{}", tr.tr_arg(if judged(report.passed) == "ok" { "cli-report-pass" } else { "cli-report-fail" }, path));
2666    Ok(())
2667}
2668
2669/// `compare <machine> --effect NAME`: the cycle run with `effects.NAME` on and with it off (`compare_effect`). Writes
2670/// every signal, or those `--signal ID` names (it may repeat), once per millisecond of the measured pass, on and off
2671/// side by side; `--differences FILE` the peak and the RMS of on less off per signal.
2672fn compare(args: &Args) -> Result<(), Failure> {
2673    let (entry, cfg) = machine_and_config(args)?;
2674    let effect = args.option("--effect").ok_or(Failure("cli-error-missing-value", "--effect".into()))?;
2675    let found = sim_components::analysis::compare_effect(entry, &cfg, effect)?;
2676    let named = args.options("--signal");
2677    let place = |id: &str| {
2678        found.signals.iter().position(|s| s.id == id).ok_or(Failure("cli-error-bad-argument", format!("--signal {id}")))
2679    };
2680    // Every signal but the time, which is the first column anyway.
2681    let chosen: Vec<usize> = if named.is_empty() {
2682        (1..found.signals.len()).collect()
2683    } else {
2684        named.into_iter().map(place).collect::<Result<_, _>>()?
2685    };
2686    let mut out = output(args, "--out")?;
2687    let header: Vec<String> =
2688        chosen.iter().map(|&i| &found.signals[i]).map(|s| format!("{0}.on[{1}],{0}.off[{1}]", s.id, s.unit)).collect();
2689    writeln!(out, "time[s],{}", header.join(",")).map_err(io)?;
2690    for (on, off) in found.on.iter().zip(&found.off) {
2691        let cells: Vec<String> = chosen.iter().map(|&i| format!("{:.9e},{:.9e}", on[i], off[i])).collect();
2692        writeln!(out, "{:.4},{}", on[0], cells.join(",")).map_err(io)?;
2693    }
2694    out.flush().map_err(io)?;
2695    if args.option("--differences").is_some() {
2696        let mut out = output(args, "--differences")?;
2697        writeln!(out, "signal,unit,peak_difference,rms_difference").map_err(io)?;
2698        for &i in &chosen {
2699            let (peak, rms) = found.difference(i);
2700            writeln!(out, "{},{},{peak:.6e},{rms:.6e}", found.signals[i].id, found.signals[i].unit).map_err(io)?;
2701        }
2702        out.flush().map_err(io)?;
2703    }
2704    Ok(())
2705}