Skip to main content

kinematics_sim/
lib.rs

1//! The Python module `kinematics_sim`: the simulator's machines, configs, runs, analyses, verdicts with their bands
2//! and the catalogue sizing, as `sim-cli` has them, for notebooks and scripts. Results come as NumPy arrays and as
3//! dicts of equal-length columns, which `pandas.DataFrame(result)` takes as they are. The type stubs are in
4//! `python/kinematics_sim/kinematics_sim.pyi`; `docs/python.md` has the guide.
5//!
6//! Every long call releases the GIL, so Python threads can run several at once.
7
8use numpy::{PyArray1, PyArray2};
9use pyo3::exceptions::{PyKeyError, PyOverflowError, PyValueError};
10use pyo3::prelude::*;
11use pyo3::types::{PyBool, PyDict, PyList, PyString};
12use sim_components::analysis::{
13    CycleLoad, SWEEP_POINTS, analyse_cycle_with, analyse_trajectory_with, bounds, default_sweep_amplitude,
14    frequency_sweep, log_spaced, verdict_bands, verdict_bands_sampled,
15};
16use sim_components::identify::{BELT_STIFFNESS_KEY, fit_joints, fit_move_stiffness, fit_rigid, fit_sweep, parse_sweep};
17use sim_components::import::{Imported, Mapping, decode, import};
18use sim_components::motor_fit::{
19    Estimate, Identified, TwoMass, frequency_response, ringing, two_mass, two_mass_from_ringing,
20};
21use sim_components::trace::{Trace, TraceError, per_axis_fit};
22use sim_components::{Command, DriveMode, Sim, load_config};
23use sim_core::{Config, ConfigError, MachineEntry, MotorInfo, Translations};
24use sim_machines::{LANGUAGES, MACHINES, find, translations};
25use std::path::{Path, PathBuf};
26
27fn texts(entry: &MachineEntry) -> Translations {
28    translations("en", entry)
29}
30
31fn config_error(entry: &MachineEntry, e: ConfigError) -> PyErr {
32    PyValueError::new_err(texts(entry).tr_arg(e.key(), e.detail()))
33}
34
35fn machine(id: &str) -> PyResult<&'static MachineEntry> {
36    find(id).ok_or_else(|| {
37        PyKeyError::new_err(format!(
38            "unknown machine: {id}; known: {}",
39            MACHINES.iter().map(|m| m.id).collect::<Vec<_>>().join(", ")
40        ))
41    })
42}
43
44/// A machine's config: its default, or a config file, with values set on top as `sim-cli --set` sets them.
45#[pyclass(name = "Config", module = "kinematics_sim", from_py_object)]
46#[derive(Clone)]
47struct PyConfig {
48    entry: &'static MachineEntry,
49    /// The config as read, with the parts named under `[parts]` (from the text or set since) not yet brought in.
50    base: sim_core::Config,
51    /// Every other value set since, in order.
52    sets: Vec<(String, toml::Value)>,
53    /// What runs: `base` with its parts from the catalogue, then `sets` on top, as `sim-cli` builds a config from
54    /// `--config`, the part options and `--set`, whatever order they are given in.
55    cfg: sim_core::Config,
56    /// The text the config was read from (the machine's default where none was given) and where it came from (none:
57    /// the default), for the report's sources of the values.
58    text: String,
59    source: Option<String>,
60}
61
62impl PyConfig {
63    fn rebuild(&mut self) -> PyResult<()> {
64        let mut cfg =
65            sim_components::catalog::resolve(self.entry, &self.base).map_err(|e| config_error(self.entry, e))?;
66        for (path, value) in &self.sets {
67            sim_components::set_config(self.entry, &mut cfg, path, value.clone())
68                .map_err(|e| config_error(self.entry, e))?;
69        }
70        let schema = sim_components::schema(self.entry, &cfg).map_err(|e| config_error(self.entry, e))?;
71        cfg.check_keys(&schema, &sim_components::analysis::RATINGS_BEYOND_DEFAULT)
72            .map_err(|e| config_error(self.entry, e))?;
73        self.cfg = cfg;
74        Ok(())
75    }
76
77    /// One value set: a part into `base`, anything else onto the list. Nothing changes if the result is refused.
78    fn assign(&mut self, path: &str, value: toml::Value) -> PyResult<()> {
79        let mut next = self.clone();
80        // A drive's installation conditions are read where its part is put in: into `base` with the parts.
81        if path.starts_with("parts.") || sim_components::catalog::DRIVE_CONDITION_KEYS.contains(&path) {
82            sim_components::set_config(self.entry, &mut next.base, path, value)
83                .map_err(|e| config_error(self.entry, e))?;
84        } else {
85            next.sets.push((path.to_string(), value));
86        }
87        next.rebuild()?;
88        *self = next;
89        Ok(())
90    }
91}
92
93#[pymethods]
94impl PyConfig {
95    /// The default config of `machine`, or the config in `text` (TOML), or in the file at `path`. Instead of a
96    /// registered machine, `machine_file` names a machine file (docs/machine-files.md), as `sim-cli --machine-file`.
97    #[new]
98    #[pyo3(signature = (machine=None, text=None, path=None, *, machine_file=None))]
99    fn new(
100        machine: Option<&str>,
101        text: Option<&str>,
102        path: Option<std::path::PathBuf>,
103        machine_file: Option<std::path::PathBuf>,
104    ) -> PyResult<Self> {
105        let entry = match (machine, machine_file) {
106            (Some(id), None) => self::machine(id)?,
107            (None, Some(file)) => sim_machines::load_file(&file).map_err(|e| {
108                let at = e.line.map_or(String::new(), |line| format!(":{line}"));
109                // The core's and the components' messages; any machine brings them.
110                let tr = texts(MACHINES[0]);
111                PyValueError::new_err(format!(
112                    "{}{at}: {}",
113                    e.file.display(),
114                    tr.tr_arg(e.error.key(), e.error.detail())
115                ))
116            })?,
117            _ => return Err(PyValueError::new_err("give machine or machine_file, one of them")),
118        };
119        let (text, source) = match (text, path) {
120            (Some(_), Some(_)) => return Err(PyValueError::new_err("give text or path, not both")),
121            (Some(text), None) => (Some(text.to_string()), Some("text".to_string())),
122            (None, Some(path)) => (
123                Some(
124                    std::fs::read_to_string(&path)
125                        .map_err(|e| PyValueError::new_err(format!("{}: {e}", path.display())))?,
126                ),
127                Some(path.display().to_string()),
128            ),
129            (None, None) => (None, None),
130        };
131        let cfg = match &text {
132            Some(text) => load_config(entry, text).map_err(|e| config_error(entry, e))?,
133            None => entry.config(),
134        };
135        let text = text.unwrap_or_else(|| entry.default_config.to_string());
136        let mut out = Self { entry, base: cfg.clone(), sets: Vec::new(), cfg, text, source };
137        out.rebuild()?;
138        Ok(out)
139    }
140
141    #[getter]
142    fn machine(&self) -> &'static str {
143        self.entry.id
144    }
145
146    /// The value at a dotted path, e.g. `cfg["payload.mass_kg"]`.
147    fn __getitem__(&self, py: Python<'_>, path: &str) -> PyResult<Py<PyAny>> {
148        let value = self.cfg.get(path).map_err(|_| PyKeyError::new_err(path.to_string()))?;
149        from_toml(py, value)
150    }
151
152    /// Sets the value at a dotted path, e.g. `cfg["payload.mass_kg"] = 2.5`, as `sim-cli --set` does: a part named under
153    /// `[parts]` comes in from the catalogue as with `--motor`, under the other values set.
154    fn __setitem__(&mut self, path: &str, value: &Bound<'_, PyAny>) -> PyResult<()> {
155        self.assign(path, to_toml(value)?)
156    }
157
158    /// One `path = value` assignment with the value in TOML syntax, exactly as `sim-cli --set` takes it.
159    fn set(&mut self, assignment: &str) -> PyResult<()> {
160        let (path, value) = assignment
161            .split_once('=')
162            .ok_or_else(|| config_error(self.entry, ConfigError::Parse(assignment.into())))?;
163        let parsed: toml::Table = format!("v = {value}")
164            .parse()
165            .map_err(|_| config_error(self.entry, ConfigError::Parse(assignment.into())))?;
166        self.assign(path.trim(), parsed["v"].clone())
167    }
168
169    /// A copy, for a sweep that changes it.
170    fn copy(&self) -> Self {
171        self.clone()
172    }
173
174    /// Every value with its dotted path.
175    fn leaves(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
176        let out = PyDict::new(py);
177        for (path, value) in self.cfg.leaves() {
178            out.set_item(path, from_toml(py, &value)?)?;
179        }
180        Ok(out.unbind())
181    }
182
183    /// The config as TOML, which `Config(machine, text=...)` reads back.
184    fn to_toml(&self) -> PyResult<String> {
185        self.cfg.to_text().map_err(|e| config_error(self.entry, e))
186    }
187
188    fn __repr__(&self) -> String {
189        format!("Config('{}')", self.entry.id)
190    }
191}
192
193fn to_toml(value: &Bound<'_, PyAny>) -> PyResult<toml::Value> {
194    use toml::Value;
195    // bool before int: a Python bool is an int. The extractions take NumPy's scalars too (numpy.bool_, and integers
196    // through `__index__`); a NumPy array takes none of them and becomes an array below. An integer beyond TOML's
197    // 64 bits is an OverflowError, not a float that has lost its last digits.
198    let integer = value.extract::<i64>();
199    if let Err(e) = &integer
200        && e.is_instance_of::<PyOverflowError>(value.py())
201    {
202        return Err(PyOverflowError::new_err(format!("{value} does not fit a 64-bit integer")));
203    }
204    Ok(if let Ok(b) = value.extract::<bool>() {
205        Value::Boolean(b)
206    } else if let Ok(i) = integer {
207        Value::Integer(i)
208    } else if let Ok(f) = value.extract::<f64>() {
209        Value::Float(f)
210    } else if let Ok(s) = value.cast::<PyString>() {
211        Value::String(s.to_str()?.to_string())
212    } else if let Ok(d) = value.cast::<PyDict>() {
213        let mut table = toml::Table::new();
214        for (k, v) in d.iter() {
215            table.insert(k.extract()?, to_toml(&v)?);
216        }
217        Value::Table(table)
218    } else {
219        Value::Array(value.try_iter()?.map(|item| to_toml(&item?)).collect::<PyResult<_>>()?)
220    })
221}
222
223fn from_toml(py: Python<'_>, value: &toml::Value) -> PyResult<Py<PyAny>> {
224    use toml::Value;
225    Ok(match value {
226        Value::Boolean(b) => PyBool::new(py, *b).to_owned().into_any().unbind(),
227        Value::Integer(i) => i.into_pyobject(py)?.into_any().unbind(),
228        Value::Float(f) => f.into_pyobject(py)?.into_any().unbind(),
229        Value::String(s) => s.into_pyobject(py)?.into_any().unbind(),
230        Value::Datetime(d) => d.to_string().into_pyobject(py)?.into_any().unbind(),
231        Value::Array(items) => {
232            PyList::new(py, items.iter().map(|v| from_toml(py, v)).collect::<PyResult<Vec<_>>>()?)?.into_any().unbind()
233        }
234        Value::Table(table) => {
235            let out = PyDict::new(py);
236            for (k, v) in table {
237                out.set_item(k, from_toml(py, v)?)?;
238            }
239            out.into_any().unbind()
240        }
241    })
242}
243
244/// Every machine of the registry: `[{"id": ..., "name": ...}]`, the names in `lang` ("en" or "de").
245#[pyfunction]
246#[pyo3(signature = (lang="en"))]
247fn machines(py: Python<'_>, lang: &str) -> PyResult<Py<PyList>> {
248    if !LANGUAGES.contains(&lang) {
249        return Err(PyValueError::new_err(format!("unknown language: {lang}")));
250    }
251    let rows = PyList::empty(py);
252    for m in MACHINES {
253        let row = PyDict::new(py);
254        row.set_item("id", m.id)?;
255        row.set_item("name", translations(lang, m).tr(m.key))?;
256        rows.append(row)?;
257    }
258    Ok(rows.unbind())
259}
260
261/// The text of a message key for the config's machine in `lang`, e.g. a verdict's label "check-<check>"; a key with no
262/// text comes back as itself.
263#[pyfunction]
264#[pyo3(signature = (config, key, lang="en"))]
265fn label(config: &PyConfig, key: &str, lang: &str) -> PyResult<String> {
266    if !LANGUAGES.contains(&lang) {
267        return Err(PyValueError::new_err(format!("unknown language: {lang}")));
268    }
269    Ok(translations(lang, config.entry).tr(key).to_string())
270}
271
272/// Every signal of a run of this config, in the order `run` gives them: `{"id": [...], "unit": [...]}`.
273#[pyfunction]
274fn signals(py: Python<'_>, config: &PyConfig) -> PyResult<Py<PyDict>> {
275    let sim = Sim::new(config.entry, &config.cfg).map_err(|e| config_error(config.entry, e))?;
276    let (ids, units): (Vec<String>, Vec<String>) = sim.signal_infos().into_iter().map(|s| (s.id, s.unit)).unzip();
277    let out = PyDict::new(py);
278    out.set_item("id", ids)?;
279    out.set_item("unit", units)?;
280    Ok(out.unbind())
281}
282
283/// What the machine is told to do: the cycle, a move, a path (text of a path file), or poses at times (text of a
284/// trajectory file); at most one.
285fn motion(
286    entry: &MachineEntry,
287    sim: &Sim,
288    cycle: bool,
289    move_to: Option<Vec<f64>>,
290    path: Option<&str>,
291    trajectory: Option<&str>,
292    time_optimal: bool,
293) -> Result<Option<Command>, String> {
294    let given = [cycle, move_to.is_some(), path.is_some(), trajectory.is_some()].iter().filter(|g| **g).count();
295    if given > 1 {
296        return Err("give at most one of cycle, move_to, path, trajectory".into());
297    }
298    Ok(if cycle {
299        Some(Command::StartCycle)
300    } else if let Some(target) = move_to {
301        Some(Command::MoveTo(target))
302    } else {
303        poses(entry, sim, path, trajectory, time_optimal)?.map(Command::Trajectory)
304    })
305}
306
307fn poses(
308    entry: &MachineEntry,
309    sim: &Sim,
310    path: Option<&str>,
311    trajectory: Option<&str>,
312    time_optimal: bool,
313) -> Result<Option<Vec<(f64, Vec<f64>)>>, String> {
314    if let Some(text) = trajectory {
315        return sim_components::path::parse_trajectory(text).map(Some).map_err(|line| format!("trajectory: {line}"));
316    }
317    let Some(text) = path else { return Ok(None) };
318    let pieces = sim_components::path::parse(text).map_err(|line| format!("path: {line}"))?;
319    sim.plan_path(&pieces, time_optimal).map(Some).map_err(|e| texts(entry).tr(e.key).to_string())
320}
321
322/// The longest run `run` takes: 1e8 base steps (some 10^4 s simulated at the usual 0.1 ms, minutes to hours of
323/// computing), and 2.5e8 values sampled (2 GB of arrays). Beyond, it would seem to hang or exhaust the memory.
324const MAX_RUN_STEPS: f64 = 1e8;
325const MAX_RUN_VALUES: f64 = 2.5e8;
326
327/// Simulates `time` seconds and returns every signal, sampled every `every` base steps, as
328/// `{signal id: numpy array}` (the first is "time"). `disable_at` switches the drives off at that time.
329#[pyfunction]
330#[pyo3(signature = (config, *, cycle=false, move_to=None, path=None, trajectory=None, time_optimal=false, time=2.0, every=16, disable_at=None))]
331#[allow(clippy::too_many_arguments)]
332fn run(
333    py: Python<'_>,
334    config: &PyConfig,
335    cycle: bool,
336    move_to: Option<Vec<f64>>,
337    path: Option<String>,
338    trajectory: Option<String>,
339    time_optimal: bool,
340    time: f64,
341    every: i64,
342    disable_at: Option<f64>,
343) -> PyResult<Py<PyDict>> {
344    // `every` as i64, so that a negative one is refused with ValueError like the rest, not OverflowError.
345    if !(time.is_finite() && time >= 0.0) || every < 1 || disable_at.is_some_and(|t| !(t.is_finite() && t >= 0.0)) {
346        return Err(PyValueError::new_err("time and disable_at must be finite and not negative, every at least 1"));
347    }
348    let every = every as u64;
349    let (entry, cfg) = (config.entry, config.cfg.clone());
350    let (ids, columns) = py
351        .detach(|| -> Result<_, String> {
352            let tr = texts(entry);
353            let mut sim = Sim::new(entry, &cfg).map_err(|e| tr.tr_arg(e.key(), e.detail()))?;
354            if let Some(command) =
355                motion(entry, &sim, cycle, move_to, path.as_deref(), trajectory.as_deref(), time_optimal)?
356            {
357                sim.command(command).map_err(|e| tr.tr(e.key).to_string())?;
358            }
359            let ids: Vec<String> = sim.signal_infos().into_iter().map(|s| s.id).collect();
360            let steps = (time / sim.dt).round();
361            let values = (steps / every as f64 + 1.0) * ids.len() as f64;
362            if steps > MAX_RUN_STEPS || values > MAX_RUN_VALUES {
363                return Err(format!(
364                    "time = {time} s is {steps:.3e} base steps of {} s and {values:.3e} values; at most {MAX_RUN_STEPS:.0e} \
365                     steps and {MAX_RUN_VALUES:.0e} values (raise every, or run in pieces)",
366                    sim.dt
367                ));
368            }
369            let mut columns: Vec<Vec<f64>> = vec![Vec::new(); ids.len()];
370            let disable = disable_at.map(|t| (t / sim.dt).round() as u64);
371            let mut sample = Vec::new();
372            for step in 0..=(time / sim.dt).round() as u64 {
373                if step % every == 0 {
374                    sim.sample(&mut sample);
375                    columns.iter_mut().zip(&sample).for_each(|(c, v)| c.push(*v));
376                }
377                if Some(step) == disable {
378                    sim.command(Command::Disable).map_err(|e| tr.tr(e.key).to_string())?;
379                }
380                sim.step();
381            }
382            Ok((ids, columns))
383        })
384        .map_err(PyValueError::new_err)?;
385    let out = PyDict::new(py);
386    for (id, column) in ids.into_iter().zip(columns) {
387        out.set_item(id, PyArray1::from_vec(py, column))?;
388    }
389    Ok(out.unbind())
390}
391
392/// The load per motor over one pass of the cycle, or over a path or trajectory, as `sim-cli analyze` gives it: a dict
393/// of columns, one row per motor. `points=True` adds "points", per motor an (n, 2) array of speed (rad/s) and torque
394/// (N m) at its operating points. The column names are fixed: on a linear motor "*_torque_nm" holds a force in N and
395/// "peak_speed_rad_s" a speed in m/s; the columns "torque_unit" and "speed_unit" give each motor's units.
396#[pyfunction]
397#[pyo3(signature = (config, *, path=None, trajectory=None, time_optimal=false, points=false))]
398fn analyze(
399    py: Python<'_>,
400    config: &PyConfig,
401    path: Option<String>,
402    trajectory: Option<String>,
403    time_optimal: bool,
404    points: bool,
405) -> PyResult<Py<PyDict>> {
406    let (entry, cfg) = (config.entry, config.cfg.clone());
407    let (motors, load) = py
408        .detach(|| -> Result<(Vec<(&'static str, bool)>, CycleLoad), String> {
409            let tr = texts(entry);
410            let mut sim = Sim::new(entry, &cfg).map_err(|e| tr.tr_arg(e.key(), e.detail()))?;
411            let motors = motor_kinds(&sim);
412            let load = match poses(entry, &sim, path.as_deref(), trajectory.as_deref(), time_optimal)? {
413                Some(points) => analyse_trajectory_with(&mut sim, points, false),
414                None => analyse_cycle_with(&mut sim, false),
415            }
416            .map_err(|e| tr.tr(e.key).to_string())?;
417            Ok((motors, load))
418        })
419        .map_err(PyValueError::new_err)?;
420    Ok(load_columns(py, motors, &load, points)?.unbind())
421}
422
423/// Each motor's id and whether it is linear (`Machine::motor_linear`: m/s and N instead of rad/s and N m).
424fn motor_kinds(sim: &Sim) -> Vec<(&'static str, bool)> {
425    sim.machine.motors().iter().enumerate().map(|(k, m)| (m.id, sim.machine.motor_linear(k))).collect()
426}
427
428/// The columns of `analyze`, one row per motor.
429fn load_columns<'py>(
430    py: Python<'py>,
431    motors: Vec<(&'static str, bool)>,
432    load: &CycleLoad,
433    points: bool,
434) -> PyResult<Bound<'py, PyDict>> {
435    let out = PyDict::new(py);
436    let column = |f: fn(&sim_components::analysis::MotorLoad) -> f64| {
437        PyArray1::from_vec(py, load.motors.iter().map(f).collect())
438    };
439    let unit = |rotary: &'static str, linear: &'static str| {
440        motors.iter().map(|m| if m.1 { linear } else { rotary }).collect::<Vec<_>>()
441    };
442    out.set_item("torque_unit", unit("N m", "N"))?;
443    out.set_item("speed_unit", unit("rad/s", "m/s"))?;
444    out.set_item("motor", motors.iter().map(|m| m.0).collect::<Vec<_>>())?;
445    out.set_item("cycle_s", PyArray1::from_vec(py, vec![load.duration; load.motors.len()]))?;
446    out.set_item("peak_torque_nm", column(|m| m.peak_torque))?;
447    out.set_item("rms_torque_nm", column(|m| m.rms_torque))?;
448    out.set_item("cubic_mean_torque_nm", column(|m| m.cubic_mean_torque))?;
449    out.set_item("peak_speed_rad_s", column(|m| m.peak_speed))?;
450    out.set_item("utilisation", column(|m| m.utilisation))?;
451    out.set_item("thermal_utilisation", column(|m| m.thermal_utilisation))?;
452    out.set_item("rms_current_a", column(|m| m.rms_current))?;
453    out.set_item("peak_current_a", column(|m| m.peak_current))?;
454    out.set_item("winding_rise_k", column(|m| m.winding_rise))?;
455    out.set_item("energy_in_j", column(|m| m.energy_in))?;
456    out.set_item("energy_regenerated_j", column(|m| m.energy_regenerated))?;
457    out.set_item("peak_regenerated_power_w", column(|m| m.peak_regenerated_power))?;
458    out.set_item("braking_resistor_energy_j", column(|m| m.resistor_energy))?;
459    out.set_item("dc_link_peak_voltage_v", column(|m| m.peak_dc_link_voltage))?;
460    let (low, high) = load.belt_tension.unwrap_or((f64::NAN, f64::NAN));
461    out.set_item("belt_tension_min_n", PyArray1::from_vec(py, vec![low; load.motors.len()]))?;
462    out.set_item("belt_tension_max_n", PyArray1::from_vec(py, vec![high; load.motors.len()]))?;
463    for (name, value) in [
464        ("path_error_peak_m", load.path_error_peak),
465        ("path_error_rms_m", load.path_error_rms),
466        ("tracking_error_peak_m", load.tracking_error_peak),
467        ("dwell_error_peak_m", load.dwell_error_peak),
468    ] {
469        out.set_item(name, PyArray1::from_vec(py, vec![value; load.motors.len()]))?;
470    }
471    if points {
472        let list = PyList::empty(py);
473        for m in &load.motors {
474            let rows: Vec<Vec<f64>> = m.points.iter().map(|(s, t)| vec![*s, *t]).collect();
475            list.append(if rows.is_empty() {
476                PyArray2::zeros(py, [0, 2], false)
477            } else {
478                PyArray2::from_vec2(py, &rows)?
479            })?;
480        }
481        out.set_item("points", list)?;
482    }
483    Ok(out)
484}
485
486/// The config with `path` (the text of a path file or of robot moves as CSV; with `path_file` a program by that file's
487/// extension, G-code or KRL or RAPID) in place of the cycle, timed as fast as the motors allow with `time_optimal`
488/// (`sim::with_path`), as `sim-cli verdicts`, `search` and `optimise --path FILE` take it. Planned once here, so that a
489/// path that cannot be read or planned is said before any run. The config as it is without `path`.
490fn path_instead(
491    entry: &'static MachineEntry,
492    cfg: sim_core::Config,
493    path: Option<&str>,
494    path_file: Option<&str>,
495    time_optimal: bool,
496) -> PyResult<sim_core::Config> {
497    let Some(text) = path else { return Ok(cfg) };
498    let file = path_file.unwrap_or("path");
499    let cfg = sim_components::sim::with_path(&cfg, file, text, time_optimal).map_err(|e| config_error(entry, e))?;
500    let sim = Sim::new(entry, &cfg).map_err(|e| config_error(entry, e))?;
501    if let Some(Err(e)) = sim.plan_configured_path() {
502        return Err(PyValueError::new_err(format!("path: {}", texts(entry).tr(e.key))));
503    }
504    Ok(cfg)
505}
506
507/// The cycle judged against the motor data and the `[ratings]` of the config, as `sim-cli verdicts` judges it: a dict
508/// of columns, one row per check and motor. `bands=True` adds "low", "high" and "worst_ok" over the parameters with
509/// `[bounds]`, one at a time at their bounds, or with `samples=N` N runs with all of them drawn between their bounds
510/// at once (seed `seed`), which also adds "pass_share". `bands=True, worst=True` searches per check for the worst corner
511/// of the bounds instead, as `sim-cli verdicts --bands --worst`: columns "check", "motor", "worst", "limit", "worst_ok",
512/// "at_high_bound" and "at_low_bound" (per row the parameters at that bound there), and "runs", the cycles simulated.
513/// With `path` (and `path_file`, `time_optimal`, see `path_instead`) the path's run is judged in place of the cycle.
514#[pyfunction]
515#[pyo3(signature = (config, *, bands=false, samples=None, seed=1, worst=false, path=None, path_file=None, time_optimal=false))]
516#[allow(clippy::too_many_arguments)]
517fn verdicts(
518    py: Python<'_>,
519    config: &PyConfig,
520    bands: bool,
521    samples: Option<usize>,
522    seed: u64,
523    worst: bool,
524    path: Option<&str>,
525    path_file: Option<&str>,
526    time_optimal: bool,
527) -> PyResult<Py<PyDict>> {
528    if samples.is_some() && !bands {
529        return Err(PyValueError::new_err("samples needs bands=True"));
530    }
531    if samples == Some(0) {
532        return Err(PyValueError::new_err("samples must be at least 1"));
533    }
534    if worst && (!bands || samples.is_some()) {
535        return Err(PyValueError::new_err("worst needs bands=True and no samples"));
536    }
537    let entry = config.entry;
538    let cfg = path_instead(entry, config.cfg.clone(), path, path_file, time_optimal)?;
539    if worst {
540        let (motors, bounded, (found, runs)) = py
541            .detach(|| -> Result<_, ConfigError> {
542                let motors: Vec<&'static str> = (entry.build)(&cfg)?.motors().iter().map(|m| m.id).collect();
543                let bounded = bounds(&cfg)?;
544                let found = sim_components::analysis::verdict_worst(entry, &cfg, &bounded)?;
545                Ok((motors, bounded, found))
546            })
547            .map_err(|e| config_error(entry, e))?;
548        let at = |w: &sim_components::analysis::Worst, high: bool| -> Vec<String> {
549            bounded.iter().zip(&w.high).filter(|(_, h)| **h == Some(high)).map(|(b, _)| b.0.clone()).collect()
550        };
551        let out = PyDict::new(py);
552        out.set_item("check", found.iter().map(|w| w.verdict.check).collect::<Vec<_>>())?;
553        out.set_item("motor", found.iter().map(|w| w.verdict.motor.map(|k| motors[k])).collect::<Vec<_>>())?;
554        out.set_item("worst", PyArray1::from_vec(py, found.iter().map(|w| w.verdict.value).collect()))?;
555        out.set_item("limit", PyArray1::from_vec(py, found.iter().map(|w| w.verdict.limit).collect()))?;
556        out.set_item("worst_ok", PyArray1::from_vec(py, found.iter().map(|w| w.verdict.ok).collect()))?;
557        out.set_item("at_high_bound", found.iter().map(|w| at(w, true)).collect::<Vec<_>>())?;
558        out.set_item("at_low_bound", found.iter().map(|w| at(w, false)).collect::<Vec<_>>())?;
559        out.set_item("runs", runs)?;
560        return Ok(out.unbind());
561    }
562    let (motors, found) = py
563        .detach(|| -> Result<_, ConfigError> {
564            let motors: Vec<&'static str> = (entry.build)(&cfg)?.motors().iter().map(|m| m.id).collect();
565            let bounded = if bands { bounds(&cfg)? } else { Vec::new() };
566            let found = match samples {
567                Some(n) => verdict_bands_sampled(entry, &cfg, &bounded, n, seed)?,
568                None => verdict_bands(entry, &cfg, &bounded)?,
569            };
570            Ok((motors, found))
571        })
572        .map_err(|e| config_error(entry, e))?;
573    let out = PyDict::new(py);
574    out.set_item("check", found.iter().map(|b| b.verdict.check).collect::<Vec<_>>())?;
575    out.set_item("motor", found.iter().map(|b| b.verdict.motor.map(|k| motors[k])).collect::<Vec<_>>())?;
576    out.set_item("value", PyArray1::from_vec(py, found.iter().map(|b| b.verdict.value).collect()))?;
577    out.set_item("limit", PyArray1::from_vec(py, found.iter().map(|b| b.verdict.limit).collect()))?;
578    out.set_item("ok", PyArray1::from_vec(py, found.iter().map(|b| b.verdict.ok).collect()))?;
579    if bands {
580        out.set_item("low", PyArray1::from_vec(py, found.iter().map(|b| b.low).collect()))?;
581        out.set_item("high", PyArray1::from_vec(py, found.iter().map(|b| b.high).collect()))?;
582        out.set_item("worst_ok", PyArray1::from_vec(py, found.iter().map(|b| b.ok).collect()))?;
583    }
584    if samples.is_some() {
585        out.set_item("pass_share", PyArray1::from_vec(py, found.iter().map(|b| b.share).collect()))?;
586    }
587    Ok(out.unbind())
588}
589
590/// Every motor of the catalogue on the cycle of the config, each with the drive the catalogue pairs with it, the
591/// passing ones first, cheapest first, as `sim-cli search` gives them: a dict of columns, one row per candidate.
592/// `series` keeps article numbers starting with it, `supply` is one of the catalogue's supplies ("230v", "400v", "s120",
593/// "s210new-400v", "beckhoff-400v", ...), `vendor` keeps that maker's supplies ("all": every maker's; all of them where
594/// `supply` is left out; without either the config's own `parts.motor_supply`, else "400v"), `gearboxes` names a gearbox
595/// series to try as well (on a direct drive around the classic optimum ratio), and `axes=True` tries every axis of the
596/// catalogue too. `motor_id` sizes one motor of a machine with several (a machine file's): each candidate becomes that
597/// motor's own `[parts.ID]`, and the cost, the tightest check, the peak torque and the winding rise are that motor's
598/// alone; not with `axes`. The candidates of several supplies are ranked together; `vendor` and `supply` say whose each
599/// is.
600/// together; `vendor` and `supply` say whose each is. `drives` is "paired", "neighbours" (the paired drive and the next
601/// size down and up) or "all"; `rank_by` orders the passing ones as `--rank-by` does ("cost", "margin", "energy",
602/// "error", "thermal", "inertia" or a weighted mix "cost=1,energy=0.5"); `duties` a duty mix, a list of (config,
603/// weight), the first the config searched on. The columns are those of `sim-cli search`: beside the parts "rank",
604/// "front", "cycle_s", "energy_j", "thermal_utilisation", "drive_current_utilisation", "following_error_m",
605/// "settling_error_m", "inertia_ratio", "failing" and "estimated" (lists), and "u_<check>" per check (NaN where a
606/// candidate has no such check). With `path` (and `path_file`, `time_optimal`, see `path_instead`) each candidate runs the
607/// path in place of the cycle, the duties' configs too.
608#[pyfunction]
609#[pyo3(signature = (config, *, supply=None, vendor=None, series="", gearboxes=None, axes=false, motor_id=None, drives="paired", rank_by="cost", duties=None, path=None, path_file=None, time_optimal=false))]
610#[allow(clippy::too_many_arguments)]
611fn sizing(
612    py: Python<'_>,
613    config: &PyConfig,
614    supply: Option<&str>,
615    vendor: Option<&str>,
616    series: &str,
617    gearboxes: Option<&str>,
618    axes: bool,
619    motor_id: Option<&str>,
620    drives: &str,
621    rank_by: &str,
622    duties: Option<Vec<(PyRef<'_, PyConfig>, f64)>>,
623    path: Option<&str>,
624    path_file: Option<&str>,
625    time_optimal: bool,
626) -> PyResult<Py<PyDict>> {
627    use sim_components::catalog::{Candidate, Drives, Options, Parts, SUPPLIES, search, vendor_of};
628    use sim_components::search::{front, parse_ranking, rank_by as ranked};
629    if motor_id.is_some() && axes {
630        return Err(PyValueError::new_err("give motor_id or axes=True, not both"));
631    }
632    let entry = config.entry;
633    let instead = |cfg: sim_core::Config| path_instead(entry, cfg, path, path_file, time_optimal);
634    let cfg = instead(config.cfg.clone())?;
635    let own = Parts::of(&cfg).map(|p| p.supply.to_string()).unwrap_or_default();
636    let supplies: Vec<&str> = match (supply, vendor) {
637        (None, Some(_)) => SUPPLIES.to_vec(),
638        (supply, _) => vec![supply.or(Some(own.as_str()).filter(|s| !s.is_empty())).unwrap_or("400v")],
639    };
640    let maker = vendor.filter(|v| *v != "all");
641    let supplies: Vec<&str> = supplies.into_iter().filter(|s| maker.is_none_or(|v| vendor_of(s) == v)).collect();
642    if supplies.is_empty() || !supplies.iter().all(|s| SUPPLIES.contains(s)) {
643        return Err(PyValueError::new_err(format!("no supply of the catalogue: {supply:?}, vendor {vendor:?}")));
644    }
645    let drives: Drives = drives.parse().map_err(|_| PyValueError::new_err(format!("drives: {drives}")))?;
646    // No price list here: `price` would rank every candidate as unpriced, in the weight order without a word.
647    let by = parse_ranking(rank_by)
648        .filter(|by| by.iter().all(|(c, _)| *c != sim_components::search::Criterion::Price))
649        .ok_or_else(|| PyValueError::new_err(format!("rank_by: {rank_by}")))?;
650    let mix: Vec<(sim_core::Config, f64)> =
651        duties.unwrap_or_default().iter().map(|(c, w)| Ok((instead(c.cfg.clone())?, *w))).collect::<PyResult<_>>()?;
652    if mix.iter().any(|(_, w)| !(*w > 0.0 && w.is_finite())) {
653        return Err(PyValueError::new_err("duties: weights above 0"));
654    }
655    let cfg = mix.first().map_or(cfg, |(first, _)| first.clone());
656    let found = py
657        .detach(|| {
658            let wanted = |article: &str| article.starts_with(series);
659            let options = Options { gearboxes, axes, motor: motor_id, drives, duties: &mix };
660            search(entry, &cfg, &supplies, &wanted, &options).map(|mut found| {
661                ranked(&mut found, &by);
662                found
663            })
664        })
665        .map_err(|e| config_error(entry, e))?;
666    let out = PyDict::new(py);
667    let numbers = |f: &dyn Fn(&Candidate) -> f64| PyArray1::from_vec(py, found.iter().map(f).collect());
668    let figure =
669        |f: &dyn Fn(&sim_components::search::Figures) -> f64| numbers(&|c| c.figures.as_ref().map_or(f64::NAN, f));
670    out.set_item("axis", found.iter().map(|c| c.axis.clone()).collect::<Vec<_>>())?;
671    out.set_item("motor", found.iter().map(|c| c.article).collect::<Vec<_>>())?;
672    out.set_item("gearbox", found.iter().map(|c| c.gearbox.clone()).collect::<Vec<_>>())?;
673    out.set_item("drive", found.iter().map(|c| c.drive).collect::<Vec<_>>())?;
674    out.set_item(
675        "vendor",
676        found.iter().map(|c| if c.supply.is_empty() { "" } else { vendor_of(c.supply) }).collect::<Vec<_>>(),
677    )?;
678    out.set_item("supply", found.iter().map(|c| c.supply).collect::<Vec<_>>())?;
679    out.set_item("mass_kg", numbers(&|c| c.mass))?;
680    out.set_item("cost_kg", numbers(&|c| c.cost))?;
681    out.set_item("passes", PyArray1::from_vec(py, found.iter().map(|c| c.passes()).collect()))?;
682    out.set_item("tightest_check", found.iter().map(|c| c.tightest().map_or(c.refused, |t| t.0)).collect::<Vec<_>>())?;
683    out.set_item("tightest_utilisation", numbers(&|c| c.tightest().map_or(f64::NAN, |t| t.1)))?;
684    // Of the searched motor alone with `motor_id` (the others are the config's, alike for every candidate).
685    let most = |c: &sim_components::catalog::Candidate, f: fn(&sim_components::analysis::MotorLoad) -> f64| {
686        c.result.as_ref().map_or(f64::NAN, |(load, _)| {
687            load.motors.iter().filter(|m| c.motor.is_empty() || m.id == c.motor).map(f).fold(0.0, f64::max)
688        })
689    };
690    out.set_item("peak_torque_nm", numbers(&|c| most(c, |m| m.peak_torque)))?;
691    // N on a machine of linear motors (the first motor's kind), else N m.
692    let unit = if (entry.build)(&cfg).is_ok_and(|m| m.motor_linear(0)) { "N" } else { "N m" };
693    out.set_item("torque_unit", vec![unit; found.len()])?;
694    out.set_item("winding_rise_k", numbers(&|c| most(c, |m| m.winding_rise)))?;
695    out.set_item("rank", PyArray1::from_vec(py, (1..=found.len()).collect()))?;
696    out.set_item("front", PyArray1::from_vec(py, front(&found)))?;
697    out.set_item("cycle_s", figure(&|f| f.cycle_s))?;
698    out.set_item("energy_j", figure(&|f| f.energy_j))?;
699    out.set_item("thermal_utilisation", figure(&|f| f.thermal))?;
700    out.set_item("drive_current_utilisation", figure(&|f| f.drive_current))?;
701    out.set_item("following_error_m", figure(&|f| f.following_error_m))?;
702    out.set_item("settling_error_m", figure(&|f| f.settling_error_m))?;
703    out.set_item("inertia_ratio", figure(&|f| f.inertia_ratio))?;
704    let lists = |f: &dyn Fn(&sim_components::search::Figures) -> Vec<&'static str>| {
705        found.iter().map(|c| c.figures.as_ref().map_or_else(Vec::new, f)).collect::<Vec<_>>()
706    };
707    out.set_item("failing", lists(&|f| f.failing.clone()))?;
708    out.set_item("estimated", lists(&|f| f.estimated.clone()))?;
709    let mut checks: Vec<&str> = Vec::new();
710    for (check, _) in found.iter().filter_map(|c| c.figures.as_ref()).flat_map(|f| &f.checks) {
711        if !checks.contains(check) {
712            checks.push(check);
713        }
714    }
715    for check in checks {
716        let of =
717            |f: &sim_components::search::Figures| f.checks.iter().find(|(c, _)| *c == check).map_or(f64::NAN, |c| c.1);
718        out.set_item(format!("u_{check}"), figure(&of))?;
719    }
720    Ok(out.unbind())
721}
722
723/// The mechanical frequency response from motor `motor`'s torque to its speed, as `sim-cli sweep` gives it: columns
724/// "frequency_hz", "gain_rad_s_per_nm", "phase_deg" at `count` frequencies spaced logarithmically from `from_hz` to
725/// `to_hz`, with a torque amplitude of `amplitude` N m (the default as the command line's). On a linear motor the
726/// amplitude is a force in N and "gain_rad_s_per_nm" is in (m/s)/N.
727#[pyfunction]
728#[pyo3(signature = (config, *, motor=0, from_hz=5.0, to_hz=500.0, count=SWEEP_POINTS, amplitude=None))]
729fn sweep(
730    py: Python<'_>,
731    config: &PyConfig,
732    motor: usize,
733    from_hz: f64,
734    to_hz: f64,
735    count: usize,
736    amplitude: Option<f64>,
737) -> PyResult<Py<PyDict>> {
738    if !(from_hz > 0.0 && to_hz > from_hz && to_hz.is_finite()) || count < 2 {
739        return Err(PyValueError::new_err("from_hz must be above 0 and below to_hz, count at least 2"));
740    }
741    let (entry, cfg) = (config.entry, config.cfg.clone());
742    let points = py
743        .detach(|| -> Result<_, ConfigError> {
744            let amplitude = match amplitude {
745                Some(a) => a,
746                None => default_sweep_amplitude(entry, &cfg)?,
747            };
748            frequency_sweep(entry, &cfg, motor, &log_spaced(from_hz, to_hz, count), amplitude)
749        })
750        .map_err(|e| config_error(entry, e))?;
751    let out = PyDict::new(py);
752    out.set_item("frequency_hz", PyArray1::from_vec(py, points.iter().map(|p| p.frequency).collect()))?;
753    out.set_item("gain_rad_s_per_nm", PyArray1::from_vec(py, points.iter().map(|p| p.gain).collect()))?;
754    out.set_item("phase_deg", PyArray1::from_vec(py, points.iter().map(|p| p.phase_deg).collect()))?;
755    Ok(out.unbind())
756}
757
758/// A shorter cycle that still passes every verdict, as `sim-cli optimise` finds it (`runs` cycles at most; judged in
759/// the error bands of `[bounds]` unless `nominal`, at their worst corner with `worst`): "cycle_s" and
760/// "dwell_error_peak_m" and "dwell_angle_error_peak_rad" as (before, after), "runs", "changes" (columns "setting", "before", "after": the config values
761/// to change, and per changed lift its height and via points), "robust" (what the bands cost, or None) and with
762/// `pareto=True` "pareto", the settings no other beats in cycle time, energy and peak utilisation at once. With `path`
763/// (and `path_file`, `time_optimal`, see `path_instead`) the path's time is shortened in place of the cycle's.
764#[pyfunction]
765#[pyo3(signature = (config, *, runs=40, nominal=false, worst=false, pareto=false, path=None, path_file=None, time_optimal=false))]
766#[allow(clippy::too_many_arguments)]
767fn optimise(
768    py: Python<'_>,
769    config: &PyConfig,
770    runs: usize,
771    nominal: bool,
772    worst: bool,
773    pareto: bool,
774    path: Option<&str>,
775    path_file: Option<&str>,
776    time_optimal: bool,
777) -> PyResult<Py<PyDict>> {
778    let entry = config.entry;
779    let cfg = path_instead(entry, config.cfg.clone(), path, path_file, time_optimal)?;
780    let options = sim_components::analysis::OptimiseOptions { max_runs: runs, robust: !nominal, pareto, worst };
781    let found = py
782        .detach(|| sim_components::analysis::optimise_cycle_with(entry, &cfg, &options))
783        .map_err(|e| config_error(entry, e))?;
784    let out = PyDict::new(py);
785    out.set_item("cycle_s", (found.before.duration, found.after.duration))?;
786    out.set_item("dwell_error_peak_m", (found.before.dwell_error_peak, found.after.dwell_error_peak))?;
787    out.set_item(
788        "dwell_angle_error_peak_rad",
789        (found.before.dwell_angle_error_peak, found.after.dwell_angle_error_peak),
790    )?;
791    out.set_item("runs", found.runs)?;
792    // The new cycle itself is TOML; its lifts say what changed in it, as the command line writes them.
793    let mut rows: Vec<(String, String, String)> =
794        found.changes.iter().filter(|c| c.0 != "cycle.segment").cloned().collect();
795    for lift in &found.lifts {
796        let [a, b, c] = lift.segments;
797        rows.push((
798            format!("cycle.segment[{a}-{b}-{c}].lift_m"),
799            format!("{:.4}", lift.before),
800            format!("{:.4}", lift.after),
801        ));
802        if let Some(via) = &lift.via {
803            let points: Vec<String> =
804                via.iter().map(|p| p.iter().map(|x| format!("{x:.4}")).collect::<Vec<_>>().join(" ")).collect();
805            rows.push((format!("cycle.segment[{a}-{b}-{c}].via_m"), String::new(), points.join("; ")));
806        }
807    }
808    let changes = PyDict::new(py);
809    changes.set_item("setting", rows.iter().map(|r| r.0.clone()).collect::<Vec<_>>())?;
810    changes.set_item("before", rows.iter().map(|r| r.1.clone()).collect::<Vec<_>>())?;
811    changes.set_item("after", rows.iter().map(|r| r.2.clone()).collect::<Vec<_>>())?;
812    out.set_item("changes", changes)?;
813    match &found.robust {
814        Some(r) => {
815            let robust = PyDict::new(py);
816            robust.set_item("judged", if r.worst { "worst" } else { "bands" })?;
817            robust.set_item("fastest_cycle_s", r.nominal_duration)?;
818            robust.set_item("fastest_fails", r.nominal_fails.clone())?;
819            robust.set_item("steps_back", r.steps_back)?;
820            robust.set_item("excused", r.excused.clone())?;
821            robust.set_item("runs", r.runs)?;
822            out.set_item("robust", robust)?;
823        }
824        None => out.set_item("robust", py.None())?,
825    }
826    if pareto {
827        let front = PyDict::new(py);
828        let column = |f: fn(&sim_components::analysis::FrontPoint) -> f64| {
829            PyArray1::from_vec(py, found.front.iter().map(f).collect())
830        };
831        front.set_item("cycle_s", column(|p| p.duration))?;
832        front.set_item("energy_j", column(|p| p.energy))?;
833        front.set_item("peak_utilisation", column(|p| p.utilisation))?;
834        front.set_item("velocity_factor", column(|p| p.factors[0]))?;
835        front.set_item("acceleration_factor", column(|p| p.factors[1]))?;
836        front.set_item("jerk_factor", column(|p| p.factors[2]))?;
837        front.set_item("corner_blending", PyArray1::from_vec(py, found.front.iter().map(|p| p.blending).collect()))?;
838        front.set_item("input_shaping", PyArray1::from_vec(py, found.front.iter().map(|p| p.shaping).collect()))?;
839        out.set_item("pareto", front)?;
840    }
841    Ok(out.unbind())
842}
843
844fn read_text(path: &Path) -> Result<String, String> {
845    std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))
846}
847
848/// A drive trace: through the mapping file `map` (a vendor export, docs/measurement-procedure.md), or without one in the
849/// simulator's own columns for `motors`; with a mapping and `motors`, its motors have to be as many.
850fn load_trace(tr: &Translations, path: &Path, map: Option<&Path>, motors: &[MotorInfo]) -> Result<Imported, String> {
851    let traced = |e: TraceError| tr.tr_arg(e.key, &e.detail).to_string();
852    let text = decode(&std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?);
853    match map {
854        Some(map) => {
855            let imported = import(&text, &Mapping::parse(&read_text(map)?).map_err(traced)?).map_err(traced)?;
856            if !motors.is_empty() && imported.trace.motors.len() != motors.len() {
857                let detail = format!("{} [[motor]] for {} motors", imported.trace.motors.len(), motors.len());
858                return Err(tr.tr_arg("error-import-map", &detail).to_string());
859            }
860            Ok(imported)
861        }
862        None => {
863            let trace = Trace::parse(&text, motors).map_err(traced)?;
864            Ok(Imported {
865                ids: motors.iter().map(|m| m.id.to_string()).collect(),
866                torque_setpoints: vec![None; trace.motors.len()],
867                trace,
868                notes: Vec::new(),
869            })
870        }
871    }
872}
873
874/// Rows of a table of quantities: name, of what, and as many numbers per row as the table has.
875struct Rows<const N: usize> {
876    quantity: Vec<String>,
877    of: Vec<String>,
878    numbers: Vec<[f64; N]>,
879    /// The unit of each row's numbers, "" where none is given (`push_unit`); `fit` hands it out as "units".
880    units: Vec<String>,
881}
882
883impl<const N: usize> Rows<N> {
884    fn new() -> Self {
885        Self { quantity: Vec::new(), of: Vec::new(), numbers: Vec::new(), units: Vec::new() }
886    }
887    fn push(&mut self, quantity: &str, of: &str, numbers: [f64; N]) {
888        self.push_unit(quantity, of, numbers, "");
889    }
890    fn push_unit(&mut self, quantity: &str, of: &str, numbers: [f64; N], unit: &str) {
891        self.quantity.push(quantity.into());
892        self.of.push(of.into());
893        self.numbers.push(numbers);
894        self.units.push(unit.into());
895    }
896    /// The table as a dict of columns: "quantity", "of", then the numbers under `names` (NaN where a row has none).
897    fn into_dict<'py>(self, py: Python<'py>, names: [&str; N]) -> PyResult<Bound<'py, PyDict>> {
898        let out = PyDict::new(py);
899        out.set_item("quantity", self.quantity)?;
900        out.set_item("of", self.of)?;
901        for (k, name) in names.iter().enumerate() {
902            out.set_item(*name, PyArray1::from_vec(py, self.numbers.iter().map(|r| r[k]).collect()))?;
903        }
904        Ok(out)
905    }
906}
907
908/// What a measurement says the config should be, as `sim-cli fit` says it: columns "quantity", "of", "config",
909/// "fitted", "standard_error" (NaN where the command line leaves a cell empty), "units", the unit of each row ("" where
910/// it has none; the rigid values of a rotary axis are kg m², N m s/rad, N m, N m), "advice", what to change in the
911/// config, and "errors": the fits that found nothing (no resonance in the sweep, a stiffness the moves do not tell),
912/// after which the command line goes on with the others and fails at the end. Their rows are missing; an empty list:
913/// every fit asked for is there. What keeps any fit from starting (a config refused, a trace unreadable) raises
914/// ValueError. `trace_file` (through `map_file` for a vendor export) gives the rigid values per axis, or per motor and link
915/// where the motors do not turn in proportion to the axes; `stiffness=True` also the factor on the stiffness at
916/// `stiffness_key` (the belts' by default) from the trace's moves; `sweep_file` (a frequency response as `sweep` writes
917/// it as CSV, taken on motor `sweep_motor` with `amplitude` N m) the load's resonance on the belt.
918#[pyfunction]
919#[pyo3(signature = (config, *, trace_file=None, map_file=None, stiffness=false, stiffness_key=None, sweep_file=None, sweep_motor=0, amplitude=None))]
920#[allow(clippy::too_many_arguments)]
921fn fit(
922    py: Python<'_>,
923    config: &PyConfig,
924    trace_file: Option<PathBuf>,
925    map_file: Option<PathBuf>,
926    stiffness: bool,
927    stiffness_key: Option<String>,
928    sweep_file: Option<PathBuf>,
929    sweep_motor: usize,
930    amplitude: Option<f64>,
931) -> PyResult<Py<PyDict>> {
932    if trace_file.is_none() && sweep_file.is_none() {
933        return Err(PyValueError::new_err("give trace_file or sweep_file"));
934    }
935    if stiffness && trace_file.is_none() {
936        return Err(PyValueError::new_err("stiffness needs trace_file"));
937    }
938    let (entry, cfg) = (config.entry, config.cfg.clone());
939    let (rows, advice, errors) = py
940        .detach(|| -> Result<_, String> {
941            let tr = texts(entry);
942            let refused = |e: ConfigError| tr.tr_arg(e.key(), e.detail()).to_string();
943            let traced = |e: TraceError| tr.tr_arg(e.key, &e.detail).to_string();
944            let machine = (entry.build)(&cfg).map_err(refused)?;
945            let (mut rows, mut advice) = (Rows::<3>::new(), Vec::new());
946            let measured = match &trace_file {
947                Some(path) => Some(load_trace(&tr, path, map_file.as_deref(), machine.motors())?.trace),
948                None => None,
949            };
950            if let Some(measured) = &measured {
951                if !per_axis_fit(machine.as_ref()) {
952                    match fit_joints(entry, &cfg, measured).map_err(traced)? {
953                        Some(fit) => {
954                            for v in &fit.values {
955                                rows.push(v.quantity, &v.of, [v.config, v.fitted, v.error]);
956                            }
957                            for (j, (time, error)) in fit.payload_steps.iter().enumerate() {
958                                let of = if fit.payload_steps.len() == 1 {
959                                    "payload".to_string()
960                                } else {
961                                    format!("payload {}", j + 1)
962                                };
963                                rows.push("payload_step_s", &of, [f64::NAN, *time, *error]);
964                            }
965                            advice.extend(fit.advice().iter().map(|(key, detail)| tr.tr_arg(key, detail).to_string()));
966                        }
967                        None => advice.push(tr.tr("fit-joints-skipped").to_string()),
968                    }
969                } else {
970                    for (axis, fit) in machine.axes().iter().zip(fit_rigid(entry, &cfg, measured).map_err(traced)?) {
971                        let Some(fit) = fit else {
972                            advice.push(tr.tr_arg("fit-axis-skipped", axis.id).to_string());
973                            continue;
974                        };
975                        let names =
976                            ["moved_mass_kg", "viscous_friction_n_s_m", "coulomb_friction_n", "constant_force_n"];
977                        for (q, name) in names.iter().enumerate() {
978                            rows.push_unit(name, axis.id, [fit.config[q], fit.fitted[q], fit.error[q]], fit.units[q]);
979                        }
980                        // The friction beyond its sliding level, where the trace tells it, as the command line.
981                        for d in &fit.details {
982                            rows.push(d.quantity, axis.id, [d.config, d.fitted, d.error]);
983                        }
984                        advice
985                            .extend(fit.advice(axis.id).iter().map(|(key, detail)| tr.tr_arg(key, detail).to_string()));
986                    }
987                }
988            }
989            // A fit that finds nothing is an error beside what the others found, as the command line goes on after it.
990            let mut errors = Vec::new();
991            if let (true, Some(measured)) = (stiffness, &measured) {
992                let key = stiffness_key.as_deref().unwrap_or(BELT_STIFFNESS_KEY);
993                match fit_move_stiffness(entry, &cfg, measured, key) {
994                    Ok(fit) => {
995                        rows.push("stiffness_factor", key, [1.0, fit.factor, fit.error]);
996                        rows.push("ringing_rms_nm", key, [f64::NAN, fit.ringing, f64::NAN]);
997                        rows.push("ringing_left_rms_nm", key, [f64::NAN, fit.residual, f64::NAN]);
998                        let (key, detail) = fit.advice();
999                        advice.push(tr.tr_arg(key, &detail).to_string());
1000                    }
1001                    Err(e) => errors.push(traced(e)),
1002                }
1003            }
1004            if let Some(path) = &sweep_file {
1005                let measured = parse_sweep(&read_text(path)?).map_err(traced)?;
1006                let id = machine.motors().get(sweep_motor).ok_or(format!("sweep_motor {sweep_motor}"))?.id;
1007                let amplitude = match amplitude {
1008                    Some(a) => a,
1009                    None => default_sweep_amplitude(entry, &cfg).map_err(refused)?,
1010                };
1011                match fit_sweep(entry, &cfg, sweep_motor, &measured, amplitude).map_err(refused)? {
1012                    Some(fit) => {
1013                        let (config, fitted) = (fit.config, fit.fitted);
1014                        rows.push("resonance_hz", id, [config.frequency, fitted.frequency, fitted.frequency_error]);
1015                        rows.push("resonance_damping", id, [config.damping, fitted.damping, f64::NAN]);
1016                        let (key, detail) = fit.advice();
1017                        advice.push(tr.tr_arg(key, &detail).to_string());
1018                    }
1019                    None => errors.push(tr.tr("fit-no-resonance").to_string()),
1020                }
1021            }
1022            Ok((rows, advice, errors))
1023        })
1024        .map_err(PyValueError::new_err)?;
1025    let units = rows.units.clone();
1026    let out = rows.into_dict(py, ["config", "fitted", "standard_error"])?;
1027    // The unit of each row in the order of the columns ("" where it has none): kg m², N m s/rad, N m, N m on a rotary
1028    // axis, else kg, N s/m, N, N.
1029    out.set_item("units", units)?;
1030    out.set_item("advice", advice)?;
1031    out.set_item("errors", errors)?;
1032    Ok(out.unbind())
1033}
1034
1035/// One motor's drive train from its own trace, with no machine config, as `sim-cli identify` gives it: columns
1036/// "quantity", "of", "value", "standard_error", "ci95_low", "ci95_high" (NaN for a fit quality, which has no error),
1037/// "notes" (what the trace could not tell) and "overlay" ({"time": ..., measured and modelled signals}). Without
1038/// `map_file` the trace is in the simulator's columns of `config`'s machine. `motor` picks the motor; `from_hz` and
1039/// `to_hz` also fit the two-mass model to the frequency response from the trace, `sweep_file` to a measured one;
1040/// `step_from` (and `step_to`) fits the ringing of the speed after a torque step, and with `motor_inertia` (kg m²) the
1041/// two-mass model from it. "errors" lists the fits that found nothing (no response, no two-mass model, no ringing),
1042/// whose rows are missing, as `fit` has it.
1043#[pyfunction]
1044#[pyo3(signature = (*, trace_file=None, map_file=None, config=None, motor=0, from_hz=None, to_hz=None, step_from=None, step_to=None, motor_inertia=None, sweep_file=None))]
1045#[allow(clippy::too_many_arguments)]
1046fn identify(
1047    py: Python<'_>,
1048    trace_file: Option<PathBuf>,
1049    map_file: Option<PathBuf>,
1050    config: Option<PyConfig>,
1051    motor: usize,
1052    from_hz: Option<f64>,
1053    to_hz: Option<f64>,
1054    step_from: Option<f64>,
1055    step_to: Option<f64>,
1056    motor_inertia: Option<f64>,
1057    sweep_file: Option<PathBuf>,
1058) -> PyResult<Py<PyDict>> {
1059    if trace_file.is_none() && sweep_file.is_none() {
1060        return Err(PyValueError::new_err("give trace_file or sweep_file"));
1061    }
1062    if trace_file.is_some() && map_file.is_none() && config.is_none() {
1063        return Err(PyValueError::new_err(
1064            "a trace without map_file is in the columns of config's machine: give config",
1065        ));
1066    }
1067    if from_hz.is_some() != to_hz.is_some() || from_hz.zip(to_hz).is_some_and(|(f, t)| !(f > 0.0 && t > f)) {
1068        return Err(PyValueError::new_err("give from_hz and to_hz together, 0 < from_hz < to_hz"));
1069    }
1070    let entry = config.as_ref().map_or(MACHINES[0], |c| c.entry);
1071    let (rows, notes, overlay, errors) = py
1072        .detach(|| -> Result<_, String> {
1073            let tr = texts(entry);
1074            let (mut rows, mut notes, mut errors) = (Rows::<4>::new(), Vec::new(), Vec::new());
1075            let estimate = |rows: &mut Rows<4>, name: &str, of: &str, e: Estimate| {
1076                let (low, high) = e.interval();
1077                rows.push(name, of, [e.value, e.error, low, high]);
1078            };
1079            let two_mass_rows = |rows: &mut Rows<4>, of: &str, m: &TwoMass| {
1080                for (name, e) in [
1081                    ("total_inertia_kg_m2", m.total_inertia),
1082                    ("motor_side_inertia_kg_m2", m.motor_inertia),
1083                    ("load_side_inertia_kg_m2", m.load_inertia),
1084                    ("stiffness_nm_rad", m.stiffness),
1085                    ("damping_nm_s_rad", m.damping),
1086                    ("resonance_hz", m.resonance),
1087                    ("anti_resonance_hz", m.anti_resonance),
1088                ] {
1089                    estimate(rows, name, of, e);
1090                }
1091            };
1092            let mut overlay: Vec<(String, Vec<f64>)> = Vec::new();
1093            if let Some(path) = &trace_file {
1094                let motors = match (&map_file, &config) {
1095                    (None, Some(c)) => (c.entry.build)(&c.cfg)
1096                        .map_err(|e| tr.tr_arg(e.key(), e.detail()).to_string())?
1097                        .motors()
1098                        .to_vec(),
1099                    _ => Vec::new(),
1100                };
1101                let imported = load_trace(&tr, path, map_file.as_deref(), &motors)?;
1102                let (Some(m), Some(id)) = (imported.trace.motors.get(motor), imported.ids.get(motor)) else {
1103                    return Err(format!("motor {motor}: the trace has {}", imported.trace.motors.len()));
1104                };
1105                let t = &imported.trace.time;
1106                overlay.push(("time".into(), t.clone()));
1107                let found = Identified::of(t, m, imported.torque_setpoints[motor].as_deref());
1108                for (name, e) in found.estimates() {
1109                    estimate(&mut rows, name, id, e);
1110                }
1111                for (name, value) in found.qualities() {
1112                    rows.push(name, id, [value, f64::NAN, f64::NAN, f64::NAN]);
1113                }
1114                if found.friction.is_none() {
1115                    notes.push(tr.tr_arg("error-identify-friction", id).to_string());
1116                }
1117                if found.position_loop.is_none()
1118                    || (imported.torque_setpoints[motor].is_some() && found.current_loop.is_none())
1119                {
1120                    notes.push(tr.tr_arg("error-identify-lag", id).to_string());
1121                }
1122                if let Some(f) = &found.friction {
1123                    overlay.push(("torque_measured".into(), m.torque.clone()));
1124                    overlay.push(("torque_model".into(), f.model.clone()));
1125                }
1126                for (name, lag, output) in [
1127                    ("current_loop", &found.current_loop, &m.torque),
1128                    ("position_loop", &found.position_loop, &m.angle),
1129                ] {
1130                    if let Some(l) = lag {
1131                        overlay.push((format!("{name}_measured"), output.clone()));
1132                        overlay.push((format!("{name}_model"), l.model.clone()));
1133                    }
1134                }
1135                if let (Some(from), Some(to)) = (from_hz, to_hz) {
1136                    match frequency_response(t, &m.torque, &m.speed, &log_spaced(from, to, SWEEP_POINTS)) {
1137                        Some(response) => {
1138                            let coherence = response.iter().map(|(_, c)| *c).fold(1.0, f64::min);
1139                            rows.push("response_lowest_coherence", id, [coherence, f64::NAN, f64::NAN, f64::NAN]);
1140                            let points: Vec<_> = response.into_iter().map(|(p, _)| p).collect();
1141                            match two_mass(&points) {
1142                                Some(model) => two_mass_rows(&mut rows, id, &model),
1143                                None => errors.push(tr.tr("error-identify-two-mass").to_string()),
1144                            }
1145                        }
1146                        None => errors.push(tr.tr("error-identify-response").to_string()),
1147                    }
1148                }
1149                if let Some(from) = step_from {
1150                    match ringing(t, &m.speed, from, step_to.unwrap_or(t[t.len() - 1])) {
1151                        Some(r) => {
1152                            estimate(&mut rows, "ringing_frequency_hz", id, r.frequency);
1153                            estimate(&mut rows, "ringing_damping_ratio", id, r.damping_ratio);
1154                            rows.push("ringing_fit_percent", id, [r.quality.fit_percent, f64::NAN, f64::NAN, f64::NAN]);
1155                            if let (Some(inertia), Some(total)) =
1156                                (motor_inertia, found.friction.as_ref().map(|f| f.inertia))
1157                            {
1158                                let model = two_mass_from_ringing(&r, total, Estimate { value: inertia, error: 0.0 });
1159                                two_mass_rows(&mut rows, id, &model);
1160                            }
1161                        }
1162                        None => errors.push(tr.tr("error-identify-ringing").to_string()),
1163                    }
1164                }
1165            }
1166            if let Some(path) = &sweep_file {
1167                let points = parse_sweep(&read_text(path)?).map_err(|e| tr.tr_arg(e.key, &e.detail).to_string())?;
1168                match two_mass(&points) {
1169                    Some(model) => two_mass_rows(&mut rows, "sweep", &model),
1170                    None => errors.push(tr.tr("error-identify-two-mass").to_string()),
1171                }
1172            }
1173            Ok((rows, notes, overlay, errors))
1174        })
1175        .map_err(PyValueError::new_err)?;
1176    let out = rows.into_dict(py, ["value", "standard_error", "ci95_low", "ci95_high"])?;
1177    out.set_item("notes", notes)?;
1178    out.set_item("errors", errors)?;
1179    let signals = PyDict::new(py);
1180    for (name, values) in overlay {
1181        signals.set_item(name, PyArray1::from_vec(py, values))?;
1182    }
1183    out.set_item("overlay", signals)?;
1184    Ok(out.unbind())
1185}
1186
1187/// The machine of the config, built: refused as ValueError.
1188fn built(config: &PyConfig) -> PyResult<Box<dyn sim_core::Machine>> {
1189    (config.entry.build)(&config.cfg).map_err(|e| config_error(config.entry, e))
1190}
1191
1192/// `axis_index` checked against the machine's axes, as `sim-cli --axis-index` checks it.
1193fn axis(config: &PyConfig, axis_index: usize) -> PyResult<usize> {
1194    let count = built(config)?.axes().len();
1195    if axis_index < count {
1196        Ok(axis_index)
1197    } else {
1198        Err(PyValueError::new_err(format!("axis_index {axis_index}: the machine has {count} axes")))
1199    }
1200}
1201
1202fn column<'py>(py: Python<'py>, values: impl Iterator<Item = f64>) -> Bound<'py, PyArray1<f64>> {
1203    PyArray1::from_vec(py, values.collect())
1204}
1205
1206/// The answer of axis `axis_index` to a step of `size` (m or rad) of its position setpoint, over `time` seconds, as
1207/// `sim-cli step` gives it: columns "time_s", "setpoint", "response" (the tool position relative to where it was),
1208/// with "rise_time_s", "overshoot" and "settling_time_s" as numbers.
1209#[pyfunction]
1210#[pyo3(signature = (config, *, axis_index=0, size=0.001, time=0.5))]
1211fn step(py: Python<'_>, config: &PyConfig, axis_index: usize, size: f64, time: f64) -> PyResult<Py<PyDict>> {
1212    if !(size.is_finite() && size != 0.0 && time.is_finite() && time > 0.0) {
1213        return Err(PyValueError::new_err("size must be finite and not 0, time finite and above 0"));
1214    }
1215    let (entry, cfg, i) = (config.entry, config.cfg.clone(), axis(config, axis_index)?);
1216    let r = py
1217        .detach(|| sim_components::analysis::step_response(entry, &cfg, i, size, time))
1218        .map_err(|e| config_error(entry, e))?;
1219    let out = PyDict::new(py);
1220    out.set_item("time_s", column(py, r.trace.iter().map(|p| p.0)))?;
1221    out.set_item("setpoint", column(py, r.trace.iter().map(|_| r.size)))?;
1222    out.set_item("response", column(py, r.trace.iter().map(|p| p.1)))?;
1223    out.set_item("rise_time_s", r.rise_time)?;
1224    out.set_item("overshoot", r.overshoot)?;
1225    out.set_item("settling_time_s", r.settling_time)?;
1226    Ok(out.unbind())
1227}
1228
1229/// The closed-loop frequency response of the position loop of axis `axis_index`, as `sim-cli bode` gives it: columns
1230/// "frequency_hz", "gain", "gain_db", "phase_deg" at `count` frequencies from `from_hz` to `to_hz`, spaced
1231/// logarithmically, with a setpoint amplitude of `amplitude` (m or rad).
1232#[pyfunction]
1233#[pyo3(signature = (config, *, axis_index=0, from_hz=1.0, to_hz=200.0, count=40, amplitude=0.0005))]
1234fn bode(
1235    py: Python<'_>,
1236    config: &PyConfig,
1237    axis_index: usize,
1238    from_hz: f64,
1239    to_hz: f64,
1240    count: usize,
1241    amplitude: f64,
1242) -> PyResult<Py<PyDict>> {
1243    if !(from_hz > 0.0 && to_hz > from_hz && to_hz.is_finite()) || count < 2 || !amplitude.is_finite() {
1244        return Err(PyValueError::new_err("from_hz must be above 0 and below to_hz, count at least 2"));
1245    }
1246    let (entry, cfg, i) = (config.entry, config.cfg.clone(), axis(config, axis_index)?);
1247    let points = py
1248        .detach(|| {
1249            sim_components::analysis::closed_loop_response(
1250                entry,
1251                &cfg,
1252                i,
1253                &log_spaced(from_hz, to_hz, count),
1254                amplitude,
1255            )
1256        })
1257        .map_err(|e| config_error(entry, e))?;
1258    let out = PyDict::new(py);
1259    out.set_item("frequency_hz", column(py, points.iter().map(|p| p.frequency)))?;
1260    out.set_item("gain", column(py, points.iter().map(|p| p.gain)))?;
1261    out.set_item("gain_db", column(py, points.iter().map(|p| 20.0 * p.gain.log10())))?;
1262    out.set_item("phase_deg", column(py, points.iter().map(|p| p.phase_deg)))?;
1263    Ok(out.unbind())
1264}
1265
1266/// One row per axis with what its step response (a step of `size`) and its closed-loop frequency response (setpoint
1267/// amplitude `amplitude`) say, as `sim-cli tuning` gives it: columns "axis", "rise_time_s", "overshoot",
1268/// "settling_time_s", "bandwidth_hz" (NaN where the response stays above -3 dB up to 200 Hz).
1269#[pyfunction]
1270#[pyo3(signature = (config, *, size=0.001, amplitude=0.0005))]
1271fn tuning(py: Python<'_>, config: &PyConfig, size: f64, amplitude: f64) -> PyResult<Py<PyDict>> {
1272    use sim_components::analysis::{bandwidth, closed_loop_response, step_response};
1273    if !(size.is_finite() && size != 0.0 && amplitude.is_finite()) {
1274        return Err(PyValueError::new_err("size must be finite and not 0, amplitude finite"));
1275    }
1276    let (entry, cfg) = (config.entry, config.cfg.clone());
1277    let axes: Vec<&'static str> = built(config)?.axes().iter().map(|a| a.id).collect();
1278    let rows = py
1279        .detach(|| -> Result<Vec<[f64; 4]>, ConfigError> {
1280            // As the command line: a batch of frequencies per processor, lowest first, up to the batch with the
1281            // first point below -3 dB.
1282            let batch = std::thread::available_parallelism().map_or(1, |n| n.get());
1283            let mut rows = Vec::new();
1284            for i in 0..axes.len() {
1285                let step = step_response(entry, &cfg, i, size, 0.5)?;
1286                let mut response = Vec::new();
1287                for frequencies in log_spaced(1.0, 200.0, 30).chunks(batch) {
1288                    response.extend(closed_loop_response(entry, &cfg, i, frequencies, amplitude)?);
1289                    if bandwidth(&response).is_some() {
1290                        break;
1291                    }
1292                }
1293                let band = bandwidth(&response).unwrap_or(f64::NAN);
1294                rows.push([step.rise_time, step.overshoot, step.settling_time, band]);
1295            }
1296            Ok(rows)
1297        })
1298        .map_err(|e| config_error(entry, e))?;
1299    let out = PyDict::new(py);
1300    out.set_item("axis", axes)?;
1301    for (k, name) in ["rise_time_s", "overshoot", "settling_time_s", "bandwidth_hz"].iter().enumerate() {
1302        out.set_item(*name, column(py, rows.iter().map(|r| r[k])))?;
1303    }
1304    Ok(out.unbind())
1305}
1306
1307/// Per motor the stability margins of its velocity loop, as `sim-cli margins` gives them: columns "run" ("" for the
1308/// config as it is, "start.pose=[x y ...]" at each other pose the cycle stops at, and with `bands=True` "path=value"
1309/// for each value of `[bounds]` at its low and its high bound), "motor", "crossover_hz",
1310/// "phase_margin_deg", "gain_margin_db", "peak_sensitivity", "peak_frequency_hz" and "ok" (false: the loop is unstable
1311/// or its measurement not valid). Crossover and phase margin are NaN where the loop has no gain crossover in the band
1312/// (not measurable; "ok" is then the gain margin's alone), the CLI's empty cell.
1313#[pyfunction]
1314#[pyo3(signature = (config, *, bands=false))]
1315fn margins(py: Python<'_>, config: &PyConfig, bands: bool) -> PyResult<Py<PyDict>> {
1316    let (entry, cfg) = (config.entry, config.cfg.clone());
1317    let motors: Vec<&'static str> = built(config)?.motors().iter().map(|m| m.id).collect();
1318    let runs = py
1319        .detach(|| {
1320            let bounded = if bands { bounds(&cfg)? } else { Vec::new() };
1321            sim_components::analysis::velocity_loop_margins(entry, &cfg, &bounded)
1322        })
1323        .map_err(|e| config_error(entry, e))?;
1324    let rows: Vec<(&str, &str, &sim_components::analysis::LoopMargins)> = runs
1325        .iter()
1326        .flat_map(|(run, margins)| motors.iter().zip(margins).map(move |(motor, m)| (run.as_str(), *motor, m)))
1327        .collect();
1328    let out = PyDict::new(py);
1329    out.set_item("run", rows.iter().map(|r| r.0).collect::<Vec<_>>())?;
1330    out.set_item("motor", rows.iter().map(|r| r.1).collect::<Vec<_>>())?;
1331    out.set_item("crossover_hz", column(py, rows.iter().map(|r| r.2.crossover_hz)))?;
1332    out.set_item("phase_margin_deg", column(py, rows.iter().map(|r| r.2.phase_margin_deg)))?;
1333    out.set_item("gain_margin_db", column(py, rows.iter().map(|r| r.2.gain_margin_db)))?;
1334    out.set_item("peak_sensitivity", column(py, rows.iter().map(|r| r.2.peak_sensitivity)))?;
1335    out.set_item("peak_frequency_hz", column(py, rows.iter().map(|r| r.2.peak_frequency_hz)))?;
1336    out.set_item("ok", PyArray1::from_vec(py, rows.iter().map(|r| r.2.stable()).collect()))?;
1337    Ok(out.unbind())
1338}
1339
1340/// The static positioning accuracy and repeatability (`sim_components::accuracy::study`), as `sim-cli accuracy` gives
1341/// it: `points` targets per axis, each approached `repeats` times from each side, resting `dwell` seconds. Per axis and
1342/// target the columns "axis", "target", "mean_up", "mean_down", "std_up", "std_down"; per axis "summary", a dict of
1343/// columns "axis", "reversal", "repeatability", "systematic", "mean_range", "accuracy" (ISO 230-2: B, R, E, M, A); at the
1344/// tool "tool_accuracy", "tool_repeatability", "tool_direction_variation" (ISO 9283: AP, RP, vAP); and "verdicts", a
1345/// dict of columns "check", "value", "limit", "ok" for the ratings the config has.
1346#[pyfunction]
1347#[pyo3(signature = (config, *, points=5, repeats=5, dwell=0.3))]
1348fn accuracy(py: Python<'_>, config: &PyConfig, points: usize, repeats: usize, dwell: f64) -> PyResult<Py<PyDict>> {
1349    if points < 2 || repeats < 1 || !(dwell > 0.0 && dwell.is_finite()) {
1350        return Err(PyValueError::new_err("points must be at least 2, repeats at least 1 and dwell above 0"));
1351    }
1352    let (entry, cfg) = (config.entry, config.cfg.clone());
1353    let axes: Vec<&'static str> = built(config)?.axes().iter().map(|a| a.id).collect();
1354    let settings = sim_components::accuracy::Settings { points, repeats, dwell_s: dwell };
1355    let study =
1356        py.detach(|| sim_components::accuracy::study(entry, &cfg, settings)).map_err(|e| config_error(entry, e))?;
1357    let rows: Vec<(usize, usize, &sim_components::accuracy::AxisResult)> =
1358        study.axes.iter().flat_map(|r| (0..r.targets.len()).map(move |j| (r.axis, j, r))).collect();
1359    let out = PyDict::new(py);
1360    out.set_item("axis", rows.iter().map(|r| axes[r.0]).collect::<Vec<_>>())?;
1361    out.set_item("target", column(py, rows.iter().map(|r| r.2.targets[r.1])))?;
1362    out.set_item("mean_up", column(py, rows.iter().map(|r| r.2.mean_up[r.1])))?;
1363    out.set_item("mean_down", column(py, rows.iter().map(|r| r.2.mean_down[r.1])))?;
1364    out.set_item("std_up", column(py, rows.iter().map(|r| r.2.std_up[r.1])))?;
1365    out.set_item("std_down", column(py, rows.iter().map(|r| r.2.std_down[r.1])))?;
1366    let summary = PyDict::new(py);
1367    summary.set_item("axis", study.axes.iter().map(|r| axes[r.axis]).collect::<Vec<_>>())?;
1368    summary.set_item("reversal", column(py, study.axes.iter().map(|r| r.reversal)))?;
1369    summary.set_item("repeatability", column(py, study.axes.iter().map(|r| r.repeatability)))?;
1370    summary.set_item("systematic", column(py, study.axes.iter().map(|r| r.systematic)))?;
1371    summary.set_item("mean_range", column(py, study.axes.iter().map(|r| r.mean_range)))?;
1372    summary.set_item("accuracy", column(py, study.axes.iter().map(|r| r.accuracy)))?;
1373    out.set_item("summary", summary)?;
1374    out.set_item("tool_accuracy", study.tool.accuracy)?;
1375    out.set_item("tool_repeatability", study.tool.repeatability)?;
1376    out.set_item("tool_direction_variation", study.tool.direction_variation)?;
1377    let verdicts = PyDict::new(py);
1378    verdicts.set_item("check", study.verdicts.iter().map(|v| v.check).collect::<Vec<_>>())?;
1379    verdicts.set_item("value", column(py, study.verdicts.iter().map(|v| v.value)))?;
1380    verdicts.set_item("limit", column(py, study.verdicts.iter().map(|v| v.limit)))?;
1381    verdicts.set_item("ok", PyArray1::from_vec(py, study.verdicts.iter().map(|v| v.ok).collect()))?;
1382    out.set_item("verdicts", verdicts)?;
1383    Ok(out.unbind())
1384}
1385
1386/// The modes the machine reports over the stroke of axis `axis_index` at `points` places, the other axes at the start
1387/// pose, as `sim-cli modes` gives them: "position", then per mode, lowest first, "mode<i>_hz" and "mode<i>_damping"
1388/// (NaN where a place does not have it), and where the small-amplitude modes differ (a gearbox's hysteresis) also
1389/// "mode<i>_small_hz".
1390#[pyfunction]
1391#[pyo3(signature = (config, *, axis_index=0, points=21))]
1392fn modes(py: Python<'_>, config: &PyConfig, axis_index: usize, points: usize) -> PyResult<Py<PyDict>> {
1393    if points < 2 {
1394        return Err(PyValueError::new_err("points must be at least 2"));
1395    }
1396    let (entry, cfg, i) = (config.entry, config.cfg.clone(), axis(config, axis_index)?);
1397    let rows = py
1398        .detach(|| -> Result<_, ConfigError> {
1399            let (sim, pose) = (Sim::new(entry, &cfg)?, cfg.f64s("start.pose")?);
1400            let rows = sim_components::analysis::modes_along(sim.machine.as_ref(), &pose, i, points);
1401            let small = sim_components::analysis::small_amplitude_along(sim.machine.as_ref(), &pose, i, &rows);
1402            Ok((rows, small))
1403        })
1404        .map_err(|e| config_error(entry, e))?;
1405    let (rows, small) = rows;
1406    let count = rows.iter().map(|(_, modes)| modes.len()).max().unwrap_or(0);
1407    let out = PyDict::new(py);
1408    out.set_item("position", column(py, rows.iter().map(|r| r.0)))?;
1409    for k in 0..count {
1410        let at = |f: fn(&sim_core::Mode) -> f64| column(py, rows.iter().map(move |r| r.1.get(k).map_or(f64::NAN, f)));
1411        out.set_item(format!("mode{}_hz", k + 1), at(|m| m.hz))?;
1412        out.set_item(format!("mode{}_damping", k + 1), at(|m| m.damping))?;
1413        if let Some(small) = &small {
1414            let hz = column(py, small.iter().map(|s| s.get(k).map_or(f64::NAN, |m| m.hz)));
1415            out.set_item(format!("mode{}_small_hz", k + 1), hz)?;
1416        }
1417    }
1418    Ok(out.unbind())
1419}
1420
1421/// The global sensitivity of the cycle's results to the values of `[bounds]`, all moving at once, as `sim-cli sensitivity
1422/// --method` gives it (`sim_components::sensitivity`): columns "result", "rank", "parameter", and for "morris" "mu_star",
1423/// "mu", "sigma", for "sobol" "first", "first_low", "first_high", "total", "total_low", "total_high". `samples`: Morris
1424/// trajectories (10 by default) or Sobol base rows (64). `groups` limits the bounds to those config tables, `results` the
1425/// rows to those results.
1426#[pyfunction]
1427#[pyo3(signature = (config, *, method="morris", samples=None, seed=1, groups=None, results=None))]
1428fn global_sensitivity(
1429    py: Python<'_>,
1430    config: &PyConfig,
1431    method: &str,
1432    samples: Option<usize>,
1433    seed: u64,
1434    groups: Option<Vec<String>>,
1435    results: Option<Vec<String>>,
1436) -> PyResult<Py<PyDict>> {
1437    use sim_components::sensitivity::{morris, sobol};
1438    let (entry, cfg) = (config.entry, config.cfg.clone());
1439    let (groups, wanted) = (groups.unwrap_or_default(), results.unwrap_or_default());
1440    let bounded = |cfg: &Config| -> Result<Vec<(String, f64, f64)>, ConfigError> {
1441        let mut b = bounds(cfg)?;
1442        b.retain(|(path, ..)| groups.is_empty() || groups.iter().any(|g| path.split('.').next() == Some(g.as_str())));
1443        Ok(b)
1444    };
1445    // Per result its rows: parameter and the method's figures in the order of `names`.
1446    let (names, rankings): (&[&str], Vec<(String, Vec<(String, Vec<f64>)>)>) = match method {
1447        "morris" => {
1448            let r = py
1449                .detach(|| morris(entry, &cfg, &bounded(&cfg)?, samples.unwrap_or(10), seed))
1450                .map_err(|e| config_error(entry, e))?;
1451            let rows = r.into_iter().map(|k| {
1452                (k.result, k.rows.into_iter().map(|w| (w.parameter, vec![w.mu_star, w.mu, w.sigma])).collect())
1453            });
1454            (&["mu_star", "mu", "sigma"], rows.collect())
1455        }
1456        "sobol" => {
1457            let r = py
1458                .detach(|| sobol(entry, &cfg, &bounded(&cfg)?, samples.unwrap_or(64), seed))
1459                .map_err(|e| config_error(entry, e))?;
1460            let rows = r.into_iter().map(|k| {
1461                let figures = |w: &sim_components::sensitivity::SobolRow| {
1462                    vec![w.first, w.first_ci.0, w.first_ci.1, w.total, w.total_ci.0, w.total_ci.1]
1463                };
1464                (k.result, k.rows.iter().map(|w| (w.parameter.clone(), figures(w))).collect())
1465            });
1466            (&["first", "first_low", "first_high", "total", "total_low", "total_high"], rows.collect())
1467        }
1468        _ => return Err(PyValueError::new_err(format!("method must be \"morris\" or \"sobol\", not {method:?}"))),
1469    };
1470    if let Some(missing) = wanted.iter().find(|w| !rankings.iter().any(|(result, _)| result == *w)) {
1471        return Err(PyValueError::new_err(format!("no result {missing:?}")));
1472    }
1473    let rows: Vec<(&str, usize, &str, &[f64])> = rankings
1474        .iter()
1475        .filter(|(result, _)| wanted.is_empty() || wanted.contains(result))
1476        .flat_map(|(result, rows)| {
1477            rows.iter().enumerate().map(move |(k, (p, f))| (result.as_str(), k + 1, p.as_str(), f.as_slice()))
1478        })
1479        .collect();
1480    let out = PyDict::new(py);
1481    out.set_item("result", rows.iter().map(|r| r.0).collect::<Vec<_>>())?;
1482    out.set_item("rank", rows.iter().map(|r| r.1).collect::<Vec<_>>())?;
1483    out.set_item("parameter", rows.iter().map(|r| r.2).collect::<Vec<_>>())?;
1484    for (k, name) in names.iter().enumerate() {
1485        out.set_item(*name, column(py, rows.iter().map(|r| r.3[k])))?;
1486    }
1487    Ok(out.unbind())
1488}
1489
1490/// The cycle with each parameter at its low and at its high bound of the config, or `delta` lower and higher where it
1491/// has none, one at a time, strongest first, as `sim-cli sensitivity` gives it: columns "parameter", "value", "low",
1492/// "high", the relative changes "peak_torque_low", "peak_torque_high", "rms_torque_low", "rms_torque_high",
1493/// "cycle_time_low", "cycle_time_high", and "belt_tension_min_low_n", "belt_tension_min_high_n". `groups` limits it to
1494/// those config tables; without it every table of machine and motor data is varied.
1495#[pyfunction]
1496#[pyo3(signature = (config, *, delta=0.2, groups=None))]
1497fn sensitivity(py: Python<'_>, config: &PyConfig, delta: f64, groups: Option<Vec<String>>) -> PyResult<Py<PyDict>> {
1498    if !(delta.is_finite() && delta > 0.0) {
1499        return Err(PyValueError::new_err("delta must be finite and above 0"));
1500    }
1501    let (entry, cfg) = (config.entry, config.cfg.clone());
1502    let groups = groups.unwrap_or_default();
1503    // As the command line: timing, switches, limits, gains and the cycle are choices, not uncertain machine data.
1504    let fixed = ["sim", "effects", "drive", "profile", "start", "axis", "temperature"];
1505    let paths: Vec<String> = cfg
1506        .leaves()
1507        .into_iter()
1508        .map(|(path, _)| path)
1509        .filter(|path| path.contains('.'))
1510        .filter(|path| {
1511            let group = path.split('.').next().unwrap_or("");
1512            if groups.is_empty() { !fixed.contains(&group) } else { groups.iter().any(|g| g == group) }
1513        })
1514        .collect();
1515    let (nominal, mut rows) = py
1516        .detach(|| sim_components::analysis::sensitivity(entry, &cfg, &paths, delta))
1517        .map_err(|e| config_error(entry, e))?;
1518    rows.sort_by(|a, b| b.strength(&nominal).total_cmp(&a.strength(&nominal)));
1519    let changes: Vec<[f64; 6]> = rows.iter().map(|r| r.changes(&nominal)).collect();
1520    let slack = |load: &CycleLoad| load.belt_tension.map_or(0.0, |t| t.0);
1521    let out = PyDict::new(py);
1522    out.set_item("parameter", rows.iter().map(|r| r.path.clone()).collect::<Vec<_>>())?;
1523    out.set_item("value", column(py, rows.iter().map(|r| r.value)))?;
1524    out.set_item("low", column(py, rows.iter().map(|r| r.bounds.0)))?;
1525    out.set_item("high", column(py, rows.iter().map(|r| r.bounds.1)))?;
1526    let names = ["peak_torque_low", "peak_torque_high", "rms_torque_low", "rms_torque_high", "cycle_time_low"];
1527    for (k, name) in names.iter().chain(&["cycle_time_high"]).enumerate() {
1528        out.set_item(*name, column(py, changes.iter().map(|c| c[k])))?;
1529    }
1530    out.set_item("belt_tension_min_low_n", column(py, rows.iter().map(|r| slack(&r.low))))?;
1531    out.set_item("belt_tension_min_high_n", column(py, rows.iter().map(|r| slack(&r.high))))?;
1532    Ok(out.unbind())
1533}
1534
1535/// The position setpoints of a drive trace run through the simulator, as `sim-cli replay` runs them: per motor how far
1536/// simulated torque and following error are from the measured ones (columns "motor", "torque_rms_nm",
1537/// "torque_peak_nm", "following_error_rms_rad", "following_error_peak_rad"; N and m on a linear motor), and
1538/// "overlay": measured and simulated
1539/// torque, speed and following error side by side ({"time": ..., "motor.<id>.<quantity>_measured": ..., ...}).
1540/// `map_file` maps a vendor export, as for `fit`.
1541#[pyfunction]
1542#[pyo3(signature = (config, *, trace_file, map_file=None))]
1543fn replay(py: Python<'_>, config: &PyConfig, trace_file: PathBuf, map_file: Option<PathBuf>) -> PyResult<Py<PyDict>> {
1544    let (entry, cfg) = (config.entry, config.cfg.clone());
1545    let (ids, measured, simulated) = py
1546        .detach(|| -> Result<_, String> {
1547            let tr = texts(entry);
1548            let machine = (entry.build)(&cfg).map_err(|e| tr.tr_arg(e.key(), e.detail()).to_string())?;
1549            let measured = load_trace(&tr, &trace_file, map_file.as_deref(), machine.motors())?.trace;
1550            let simulated = sim_components::trace::replay(entry, &cfg, &measured)
1551                .map_err(|e| tr.tr_arg(e.key, &e.detail).to_string())?;
1552            let ids: Vec<&'static str> = machine.motors().iter().map(|m| m.id).collect();
1553            Ok((ids, measured, simulated))
1554        })
1555        .map_err(PyValueError::new_err)?;
1556    let found = sim_components::trace::differences(&measured, &simulated);
1557    let out = PyDict::new(py);
1558    out.set_item("motor", ids.clone())?;
1559    let names = ["torque_rms_nm", "torque_peak_nm", "following_error_rms_rad", "following_error_peak_rad"];
1560    for (k, name) in names.iter().enumerate() {
1561        out.set_item(*name, column(py, found.iter().map(|d| d[k])))?;
1562    }
1563    let overlay = PyDict::new(py);
1564    overlay.set_item("time", PyArray1::from_vec(py, measured.time.clone()))?;
1565    for ((id, m), s) in ids.iter().zip(&measured.motors).zip(&simulated.motors) {
1566        let (m_error, s_error) = (m.following_error(), s.following_error());
1567        for (name, a, b) in
1568            [("torque", &m.torque, &s.torque), ("speed", &m.speed, &s.speed), ("following_error", &m_error, &s_error)]
1569        {
1570            overlay.set_item(format!("motor.{id}.{name}_measured"), PyArray1::from_vec(py, a.clone()))?;
1571            overlay.set_item(format!("motor.{id}.{name}_simulated"), PyArray1::from_vec(py, b.clone()))?;
1572        }
1573    }
1574    out.set_item("overlay", overlay)?;
1575    Ok(out.unbind())
1576}
1577
1578/// The cycle run with `effects.<effect>` on and with it off, as `sim-cli compare` runs it: "time" and per signal
1579/// "<id>.on" and "<id>.off", once per millisecond of the measured pass (every signal, or those `signals` names), and
1580/// "differences": columns "signal", "unit", "peak_difference", "rms_difference" of on less off.
1581#[pyfunction]
1582#[pyo3(signature = (config, *, effect, signals=None))]
1583fn compare(py: Python<'_>, config: &PyConfig, effect: &str, signals: Option<Vec<String>>) -> PyResult<Py<PyDict>> {
1584    let (entry, cfg) = (config.entry, config.cfg.clone());
1585    let found = py
1586        .detach(|| sim_components::analysis::compare_effect(entry, &cfg, effect))
1587        .map_err(|e| config_error(entry, e))?;
1588    // Every signal but the time, which is the first column anyway.
1589    let chosen: Vec<usize> = match signals {
1590        None => (1..found.signals.len()).collect(),
1591        Some(ids) => ids
1592            .iter()
1593            .map(|id| found.signals.iter().position(|s| &s.id == id).ok_or_else(|| PyKeyError::new_err(id.clone())))
1594            .collect::<PyResult<_>>()?,
1595    };
1596    let out = PyDict::new(py);
1597    out.set_item("time", column(py, found.on.iter().map(|row| row[0])))?;
1598    for &i in &chosen {
1599        out.set_item(format!("{}.on", found.signals[i].id), column(py, found.on.iter().map(|row| row[i])))?;
1600        out.set_item(format!("{}.off", found.signals[i].id), column(py, found.off.iter().map(|row| row[i])))?;
1601    }
1602    let differences = PyDict::new(py);
1603    let apart: Vec<(f64, f64)> = chosen.iter().map(|&i| found.difference(i)).collect();
1604    differences.set_item("signal", chosen.iter().map(|&i| found.signals[i].id.clone()).collect::<Vec<_>>())?;
1605    differences.set_item("unit", chosen.iter().map(|&i| found.signals[i].unit.clone()).collect::<Vec<_>>())?;
1606    differences.set_item("peak_difference", column(py, apart.iter().map(|d| d.0)))?;
1607    differences.set_item("rms_difference", column(py, apart.iter().map(|d| d.1)))?;
1608    out.set_item("differences", differences)?;
1609    Ok(out.unbind())
1610}
1611
1612/// The sizing report a customer signs, written to `path` as `sim-cli report` writes it: PDF for a path ending in .pdf,
1613/// HTML otherwise, in `lang`; `bands=True` adds the error bands. True where every check passed.
1614#[pyfunction]
1615#[pyo3(signature = (config, path, *, bands=false, lang="en"))]
1616fn report(py: Python<'_>, config: &PyConfig, path: PathBuf, bands: bool, lang: &str) -> PyResult<bool> {
1617    if !LANGUAGES.contains(&lang) {
1618        return Err(PyValueError::new_err(format!("unknown language: {lang}")));
1619    }
1620    let (entry, config) = (config.entry, config.clone());
1621    let lang = lang.to_string();
1622    py.detach(|| -> Result<bool, String> {
1623        let tr = translations(&lang, entry);
1624        let source = config.source.clone().unwrap_or_else(|| tr.tr("report-default-config").to_string());
1625        let report = sim_components::report::make(entry, &config.text, &source, &config.base, &config.cfg, bands, &tr)
1626            .map_err(|e| tr.tr_arg(e.key(), e.detail()).to_string())?;
1627        let pdf = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("pdf"));
1628        let bytes = if pdf { report.pdf() } else { report.html(&lang).into_bytes() };
1629        std::fs::write(&path, bytes).map_err(|e| format!("{}: {e}", path.display()))?;
1630        Ok(report.passed)
1631    })
1632    .map_err(PyValueError::new_err)
1633}
1634
1635/// What keeps the dataset folder `path` from being published (datasets/README.md), as `sim-cli check-dataset` lists it:
1636/// one text per problem, none for a folder that is ready.
1637#[pyfunction]
1638fn check_dataset(py: Python<'_>, path: PathBuf) -> Vec<String> {
1639    py.detach(|| sim_components::dataset::check(&path))
1640}
1641
1642/// The machine with its config as an FMI 2.0 (`fmi=2`) or 3.0 (`fmi=3`) Co-Simulation FMU written to `path`, as
1643/// `sim-cli fmu` writes it, with the descriptions in `lang`. `binaries` are the sim-fmi libraries it carries (a .dll,
1644/// .so or .dylib each, one per platform), which Python has none of beside it: build them with
1645/// `cargo build -p sim-fmi --release`.
1646#[pyfunction]
1647#[pyo3(signature = (config, path, *, binaries, fmi=2, lang="en"))]
1648fn fmu(config: &PyConfig, path: PathBuf, binaries: Vec<PathBuf>, fmi: u8, lang: &str) -> PyResult<()> {
1649    if fmi != 2 && fmi != 3 {
1650        return Err(PyValueError::new_err(format!("fmi {fmi}: 2 or 3")));
1651    }
1652    if !LANGUAGES.contains(&lang) {
1653        return Err(PyValueError::new_err(format!("unknown language: {lang}")));
1654    }
1655    if binaries.is_empty() {
1656        return Err(PyValueError::new_err("give the sim-fmi binaries the FMU carries"));
1657    }
1658    let entry = config.entry;
1659    let text = config.cfg.to_text().map_err(|e| config_error(entry, e))?;
1660    let model = sim_fmi::Model::with_fmi(entry, &text, lang, fmi).map_err(|e| config_error(entry, e))?;
1661    let mut files = model.files();
1662    for binary in &binaries {
1663        let name = binary.file_name().and_then(|n| n.to_str()).unwrap_or("");
1664        let bytes = std::fs::read(binary).map_err(|e| PyValueError::new_err(format!("{}: {e}", binary.display())))?;
1665        let inside = if fmi == 3 { sim_fmi::binary_path3(name, &bytes) } else { sim_fmi::binary_path(name) };
1666        let inside =
1667            inside.ok_or_else(|| PyValueError::new_err(format!("not a sim-fmi binary: {}", binary.display())))?;
1668        // Two binaries for one platform would be two entries of one name in the archive.
1669        if files.iter().any(|(p, _)| *p == inside) {
1670            return Err(PyValueError::new_err(format!("two binaries for {inside}")));
1671        }
1672        files.push((inside, bytes));
1673    }
1674    std::fs::write(&path, sim_fmi::zip(&files)).map_err(|e| PyValueError::new_err(format!("{}: {e}", path.display())))
1675}
1676
1677/// A simulation stepped from Python, for a controller of the user's own: each `step` runs one controller cycle
1678/// (`profile.setpoint_interval_s`, or `time` seconds) with the given torques, speeds or position setpoints held over it
1679/// (`sim_components::DriveMode`), and returns every signal at its end. What it ran is recorded as `analyze` measures a
1680/// cycle, so `analyze()` and `verdicts()` judge it as they judge the built-in controller's run.
1681/// shortcut: a step holds the GIL (a cycle is short); release it if long steps from several threads are wanted.
1682#[pyclass(name = "Sim", module = "kinematics_sim", unsendable)]
1683struct PySim {
1684    entry: &'static MachineEntry,
1685    cfg: sim_core::Config,
1686    sim: Sim,
1687    tally: sim_components::analysis::Tally,
1688    cycle: f64,
1689    ids: Vec<String>,
1690    sample: Vec<f64>,
1691}
1692
1693impl PySim {
1694    fn signal_dict<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
1695        self.sim.sample(&mut self.sample);
1696        let out = PyDict::new(py);
1697        for (id, value) in self.ids.iter().zip(&self.sample) {
1698            out.set_item(id, *value)?;
1699        }
1700        Ok(out)
1701    }
1702
1703    fn refused(&self, key: &str) -> PyErr {
1704        PyValueError::new_err(texts(self.entry).tr(key).to_string())
1705    }
1706
1707    /// One finite value per motor; `what` names them in the message.
1708    fn per_motor(&self, values: &[f64], what: &str) -> PyResult<()> {
1709        let motors = self.sim.machine.motors().len();
1710        if values.len() != motors || values.iter().any(|v| !v.is_finite()) {
1711            return Err(PyValueError::new_err(format!("{what}: {motors} finite values, one per motor")));
1712        }
1713        Ok(())
1714    }
1715
1716    fn load(&self) -> CycleLoad {
1717        self.tally.clone().finish(&self.sim, self.sim.time())
1718    }
1719}
1720
1721#[pymethods]
1722impl PySim {
1723    /// The machine of `config` at rest at its start pose, drives enabled, every motor in position mode.
1724    #[new]
1725    fn new(config: &PyConfig) -> PyResult<Self> {
1726        let (entry, cfg) = (config.entry, config.cfg.clone());
1727        let sim = Sim::new(entry, &cfg).map_err(|e| config_error(entry, e))?;
1728        let cycle = cfg.positive("profile.setpoint_interval_s").map_err(|e| config_error(entry, e))?;
1729        let tally = sim_components::analysis::Tally::new(&sim, false);
1730        let ids = sim.signal_infos().into_iter().map(|s| s.id).collect();
1731        Ok(Self { entry, cfg, sim, tally, cycle, ids, sample: Vec::new() })
1732    }
1733
1734    /// Runs one controller cycle, or `time` seconds (whole base steps), and returns every signal at its end as
1735    /// `{signal id: float}`. At most one of: `torque` (N m per motor, N on a linear motor: torque mode), `velocity`
1736    /// (rad/s per motor, m/s on a linear motor: velocity mode), `setpoint` (per tool axis: position mode,
1737    /// interpolated over `profile.setpoint_interval_s` as from a PLC). With none, the drives keep their modes and setpoints.
1738    #[pyo3(signature = (*, torque=None, velocity=None, setpoint=None, time=None))]
1739    fn step<'py>(
1740        &mut self,
1741        py: Python<'py>,
1742        torque: Option<Vec<f64>>,
1743        velocity: Option<Vec<f64>>,
1744        setpoint: Option<Vec<f64>>,
1745        time: Option<f64>,
1746    ) -> PyResult<Bound<'py, PyDict>> {
1747        if [torque.is_some(), velocity.is_some(), setpoint.is_some()].iter().filter(|g| **g).count() > 1 {
1748            return Err(PyValueError::new_err("give at most one of torque, velocity, setpoint"));
1749        }
1750        let time = time.unwrap_or(self.cycle);
1751        let steps = (time / self.sim.dt).round();
1752        if !(1.0..=MAX_RUN_STEPS).contains(&steps) {
1753            return Err(PyValueError::new_err(format!("time = {time} s: 1 to {MAX_RUN_STEPS:.0e} base steps")));
1754        }
1755        let motors = self.sim.machine.motors().len();
1756        let modes: Option<Vec<DriveMode>> = match (&torque, &velocity) {
1757            (Some(t), _) => {
1758                self.per_motor(t, "torque")?;
1759                Some(t.iter().map(|t| DriveMode::Torque(*t)).collect())
1760            }
1761            (_, Some(v)) => {
1762                self.per_motor(v, "velocity")?;
1763                Some(v.iter().map(|v| DriveMode::Velocity(*v)).collect())
1764            }
1765            _ => setpoint.as_ref().map(|_| vec![DriveMode::Position; motors]),
1766        };
1767        for (k, mode) in modes.into_iter().flatten().enumerate() {
1768            if mode != self.sim.control.drives[k].mode() {
1769                self.sim.set_drive_mode(k, mode).map_err(|e| self.refused(e.key))?;
1770            }
1771        }
1772        if let Some(target) = setpoint
1773            && target != self.sim.control.external_setpoint()
1774        {
1775            self.sim.command(Command::Setpoint(target)).map_err(|e| self.refused(e.key))?;
1776        }
1777        for _ in 0..steps as u64 {
1778            self.sim.step();
1779            self.tally.step(&self.sim);
1780        }
1781        self.signal_dict(py)
1782    }
1783
1784    /// Stops the machine in stop category 0, 1 or 2 (`sim_components::StopCategory`): 0 takes the torque off at
1785    /// once, 1 brakes every drive on its quick-stop ramp and then takes it off, 2 brakes the plan and holds with the
1786    /// torque on. The stop runs in the `step`s that follow; `enable` switches the drives on again.
1787    fn stop(&mut self, category: u8) -> PyResult<()> {
1788        let category = sim_components::StopCategory::from_number(category)
1789            .ok_or_else(|| PyValueError::new_err(format!("category {category}: 0, 1 or 2")))?;
1790        self.sim.command(Command::Halt(category)).map_err(|e| self.refused(e.key))
1791    }
1792
1793    /// Switches the drives on again after a stop, holding where the motors stand.
1794    fn enable(&mut self) -> PyResult<()> {
1795        self.sim.command(Command::Enable).map_err(|e| self.refused(e.key))
1796    }
1797
1798    /// Every signal now, as `{signal id: float}`.
1799    fn signals<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
1800        self.signal_dict(py)
1801    }
1802
1803    /// The simulated time, s.
1804    #[getter]
1805    fn time(&self) -> f64 {
1806        self.sim.time()
1807    }
1808
1809    /// The base step, s.
1810    #[getter]
1811    fn dt(&self) -> f64 {
1812        self.sim.dt
1813    }
1814
1815    /// The controller cycle a `step` runs by default, s (`profile.setpoint_interval_s`).
1816    #[getter]
1817    fn cycle(&self) -> f64 {
1818        self.cycle
1819    }
1820
1821    /// Each motor's mode: "position", "velocity" or "torque".
1822    #[getter]
1823    fn modes(&self) -> Vec<&'static str> {
1824        let name = |d: &sim_components::drive::Drive| match d.mode() {
1825            DriveMode::Position => "position",
1826            DriveMode::Velocity(_) => "velocity",
1827            DriveMode::Torque(_) => "torque",
1828        };
1829        self.sim.control.drives.iter().map(name).collect()
1830    }
1831
1832    /// Back to the start: at rest at the start pose, position mode, time 0, the recording empty.
1833    fn reset(&mut self) -> PyResult<()> {
1834        self.sim = Sim::new(self.entry, &self.cfg).map_err(|e| config_error(self.entry, e))?;
1835        self.tally = sim_components::analysis::Tally::new(&self.sim, false);
1836        Ok(())
1837    }
1838
1839    /// The load per motor over the run since the start or the last `reset`, in the columns of `analyze`
1840    /// ("cycle_s" is the time run).
1841    #[pyo3(signature = (*, points=false))]
1842    fn analyze<'py>(&self, py: Python<'py>, points: bool) -> PyResult<Bound<'py, PyDict>> {
1843        load_columns(py, motor_kinds(&self.sim), &self.load(), points)
1844    }
1845
1846    /// The verdicts on the run since the start or the last `reset`, in the columns of `verdicts`: "check", "motor",
1847    /// "value", "limit", "ok".
1848    fn verdicts<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
1849        let found =
1850            sim_components::analysis::verdicts(&self.cfg, &self.load()).map_err(|e| config_error(self.entry, e))?;
1851        let motors: Vec<&'static str> = self.sim.machine.motors().iter().map(|m| m.id).collect();
1852        let out = PyDict::new(py);
1853        out.set_item("check", found.iter().map(|v| v.check).collect::<Vec<_>>())?;
1854        out.set_item("motor", found.iter().map(|v| v.motor.map(|k| motors[k])).collect::<Vec<_>>())?;
1855        out.set_item("value", PyArray1::from_vec(py, found.iter().map(|v| v.value).collect()))?;
1856        out.set_item("limit", PyArray1::from_vec(py, found.iter().map(|v| v.limit).collect()))?;
1857        out.set_item("ok", PyArray1::from_vec(py, found.iter().map(|v| v.ok).collect()))?;
1858        Ok(out)
1859    }
1860}
1861
1862pyo3::create_exception!(
1863    kinematics_sim,
1864    Cancelled,
1865    pyo3::exceptions::PyException,
1866    "A `Job` was cancelled (`Job.cancel()`) while its callable ran."
1867);
1868
1869/// A long analysis to watch and to stop from another thread: `run(callable)` calls `callable` on this thread, and every
1870/// analysis it calls is counted in `done` / `total` and ends soon after `cancel()` with `Cancelled`. The analyses
1871/// release the GIL but run their batches on worker threads that belong to the job; none hands its work to a thread
1872/// the job does not follow.
1873#[pyclass(name = "Job", module = "kinematics_sim")]
1874struct PyJob {
1875    progress: std::sync::Arc<sim_components::analysis::Progress>,
1876}
1877
1878#[pymethods]
1879impl PyJob {
1880    #[new]
1881    fn new() -> Self {
1882        PyJob { progress: Default::default() }
1883    }
1884
1885    /// Stops the job: no further run starts, and `run` raises `Cancelled` once the runs under way have ended. From
1886    /// any thread; cancelling a job that has ended or never ran does nothing until it is run (then it stops at once).
1887    fn cancel(&self) {
1888        self.progress.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
1889    }
1890
1891    /// Runs finished so far.
1892    #[getter]
1893    fn done(&self) -> usize {
1894        self.progress.done.load(std::sync::atomic::Ordering::Relaxed)
1895    }
1896
1897    /// Runs planned so far; later batches (refinement rounds, the next call of the callable) add to it.
1898    #[getter]
1899    fn total(&self) -> usize {
1900        self.progress.total.load(std::sync::atomic::Ordering::Relaxed)
1901    }
1902
1903    #[getter]
1904    fn cancelled(&self) -> bool {
1905        self.progress.cancel.load(std::sync::atomic::Ordering::Relaxed)
1906    }
1907
1908    /// The result of `callable()`, which belongs to this job while it runs; `Cancelled` where the job was cancelled.
1909    fn run(&self, py: Python<'_>, callable: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
1910        // PyO3 turns an unwind that reaches a `#[pyfunction]` into a `PanicException` and drops its payload, so the
1911        // `Cancelled` unwind of the core arrives here as one: with the cancel flag set, that is what it is. (A real
1912        // panic at the same moment is reported as cancelled, too: the job was being stopped anyway.) Called through the
1913        // C API: PyO3's own fetch of a `PanicException` prints it with a traceback and resumes the unwind, which for
1914        // a cancel is noise; here it is cleared unprinted. Any other error is fetched as PyO3 does.
1915        let call = || {
1916            // SAFETY: the GIL is held (`py`) and `callable` is a live object; a non-null result is a new reference.
1917            let result = unsafe { pyo3::ffi::PyObject_CallNoArgs(callable.as_ptr()) };
1918            if !result.is_null() {
1919                return Ok(unsafe { Bound::from_owned_ptr(py, result) });
1920            }
1921            let panic = py.get_type::<pyo3::panic::PanicException>();
1922            // SAFETY: as above; an exception is set, as the call returned null.
1923            if self.cancelled() && unsafe { pyo3::ffi::PyErr_ExceptionMatches(panic.as_ptr()) } != 0 {
1924                unsafe { pyo3::ffi::PyErr_Clear() };
1925                return Err(Cancelled::new_err("cancelled"));
1926            }
1927            Err(PyErr::fetch(py))
1928        };
1929        match sim_components::analysis::with_progress(&self.progress, call) {
1930            Err(sim_components::analysis::Cancelled) => Err(Cancelled::new_err("cancelled")),
1931            Ok(Err(e)) if self.cancelled() && e.is_instance_of::<pyo3::panic::PanicException>(py) => {
1932                Err(Cancelled::new_err("cancelled"))
1933            }
1934            Ok(result) => result.map(Bound::unbind),
1935        }
1936    }
1937}
1938
1939#[pymodule]
1940fn kinematics_sim(m: &Bound<'_, PyModule>) -> PyResult<()> {
1941    m.add_class::<PyJob>()?;
1942    m.add("Cancelled", m.py().get_type::<Cancelled>())?;
1943    m.add_class::<PyConfig>()?;
1944    m.add_class::<PySim>()?;
1945    m.add_function(wrap_pyfunction!(machines, m)?)?;
1946    m.add_function(wrap_pyfunction!(signals, m)?)?;
1947    m.add_function(wrap_pyfunction!(label, m)?)?;
1948    m.add_function(wrap_pyfunction!(run, m)?)?;
1949    m.add_function(wrap_pyfunction!(analyze, m)?)?;
1950    m.add_function(wrap_pyfunction!(verdicts, m)?)?;
1951    m.add_function(wrap_pyfunction!(sizing, m)?)?;
1952    m.add_function(wrap_pyfunction!(sweep, m)?)?;
1953    m.add_function(wrap_pyfunction!(optimise, m)?)?;
1954    m.add_function(wrap_pyfunction!(fit, m)?)?;
1955    m.add_function(wrap_pyfunction!(identify, m)?)?;
1956    m.add_function(wrap_pyfunction!(step, m)?)?;
1957    m.add_function(wrap_pyfunction!(bode, m)?)?;
1958    m.add_function(wrap_pyfunction!(tuning, m)?)?;
1959    m.add_function(wrap_pyfunction!(margins, m)?)?;
1960    m.add_function(wrap_pyfunction!(modes, m)?)?;
1961    m.add_function(wrap_pyfunction!(sensitivity, m)?)?;
1962    m.add_function(wrap_pyfunction!(global_sensitivity, m)?)?;
1963    m.add_function(wrap_pyfunction!(replay, m)?)?;
1964    m.add_function(wrap_pyfunction!(compare, m)?)?;
1965    m.add_function(wrap_pyfunction!(report, m)?)?;
1966    m.add_function(wrap_pyfunction!(check_dataset, m)?)?;
1967    m.add_function(wrap_pyfunction!(fmu, m)?)?;
1968    m.add_function(wrap_pyfunction!(accuracy, m)?)?;
1969    m.add("__version__", env!("CARGO_PKG_VERSION"))?;
1970    Ok(())
1971}