Skip to main content

sim_components/
catalog.rs

1//! The component catalogue as the simulator uses it: a part named by its article number puts its
2//! catalogue values into a config, and a search tries every motor (and every axis) on a machine's cycle.
3//!
4//! The tables of `catalog/` (schema 1: SI units, see `catalog/README.md`) are compiled in, so a front end needs no
5//! path to them; `use_directory` reads them from another copy of the catalogue instead (`--catalog DIR`).
6
7use crate::analysis::{CycleLoad, Verdict, analyse_cycle_with, verdicts};
8use crate::sim::Sim;
9use sim_core::{Config, ConfigError, Machine, MachineEntry};
10use std::collections::HashMap;
11use std::f64::consts::PI;
12use std::sync::{Mutex, OnceLock, PoisonError};
13
14mod mechanics;
15pub use mechanics::{
16    GUIDE_CARRIAGES, GUIDE_STATIC_SAFETY, guide_carriages, is_linear_motor, linear_motor_articles_for,
17    magnet_track_weight, mech_axes, motor_shaft_diameter,
18};
19
20/// The catalogue's schema version this simulator reads. A catalogue of another version is refused.
21pub const SCHEMA_VERSION: i64 = 1;
22
23macro_rules! tables {
24    ($($name:literal),* $(,)?) => { [$(($name, include_str!(concat!("../../../catalog/", $name)))),*] };
25}
26
27/// The tables the simulator reads, by their path in the catalogue, with the compiled-in copy.
28const TABLES: &[(&str, &str)] = &tables![
29    "siemens/motors_s210.csv",
30    "siemens/motors_s210_oi.csv",
31    "siemens/dynamic_braking_1fk2.csv",
32    "siemens/s1_curves_s210.csv",
33    "siemens/encoders_1fk2_1ft2.csv",
34    "siemens/dc_link_trip_s120.csv",
35    "siemens/derating_s210.csv",
36    "siemens/derating_s120.csv",
37    "siemens/motors_1fk2_s120.csv",
38    "siemens/motors_1ft2_s120.csv",
39    "siemens/motors_s120.csv",
40    "siemens/motors_s120_electrical.csv",
41    "siemens/converters_s210.csv",
42    "siemens/motor_modules_s120.csv",
43    "siemens/braking_s210.csv",
44    "siemens/braking_s120.csv",
45    "siemens/dc_link_measured.csv",
46    "siemens/parameters_s120.csv",
47    "siemens/parameters_s210.csv",
48    "siemens/gearbox_nrb.csv",
49    "siemens/gearbox_nrk.csv",
50    "siemens/gearbox_nlc.csv",
51    "siemens/gearbox_sp.csv",
52    "siemens/gearbox_mass.csv",
53    "megadyne/belts.csv",
54    "megadyne/belt_tooth_load.csv",
55    "festo/belt_axes.csv",
56    "festo/belt_axis_torque_formula.csv",
57    "bahr/belt_axes.csv",
58    "beckhoff/motors_am8000.csv",
59    "beckhoff/drives_ax8000.csv",
60    "beckhoff/drives_ax5000.csv",
61    "br/motors_8ls.csv",
62    "br/drives_acopos_p3.csv",
63    "kollmorgen/motors_akm.csv",
64    "kollmorgen/motors_akm2g.csv",
65    "kollmorgen/drives_akd.csv",
66    "lenze/motors_mcs.csv",
67    "lenze/motors_m850.csv",
68    "lenze/drives_i950.csv",
69    "mitsubishi/motors_j5.csv",
70    "mitsubishi/drives_j5.csv",
71    "rexroth/motors_ms2n.csv",
72    "rexroth/drives_ctrlx.csv",
73    "sew/motors_cmp.csv",
74    "sew/drives_movic.csv",
75    "yaskawa/motors_sigma7.csv",
76    "yaskawa/drives_sigma7.csv",
77    "wittenstein/gearbox_sp.csv",
78    "wittenstein/gearbox_tp.csv",
79    "neugart/gearbox_ple.csv",
80    "neugart/gearbox_pln.csv",
81    "neugart/gearbox_plfe.csv",
82    "apex/gearbox_peii.csv",
83    "apex/gearbox_af.csv",
84    "harmonicdrive/gearbox_csf.csv",
85    "harmonicdrive/gearbox_csg.csv",
86    "harmonicdrive/gearbox_shg.csv",
87    "siemens/motor_shafts.csv",
88    "beckhoff/motor_shafts.csv",
89    "sew/motor_shafts.csv",
90    "yaskawa/motor_shafts.csv",
91    "hiwin/ball_screws.csv",
92    "hiwin/linear_guides.csv",
93    "rexroth/linear_guides.csv",
94    "thk/linear_guides.csv",
95    "siemens/linear_motors_1fn3.csv",
96    "beckhoff/linear_motors_al8000.csv",
97    "festo/belt_axes_egc.csv",
98    "festo/belt_axes_elga.csv",
99    "rexroth/belt_axes_ckr.csv",
100    "catalog.toml",
101];
102
103/// The tables read from a directory by `use_directory`; unset, the compiled-in ones are used.
104static LOADED: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
105
106pub(crate) fn table(name: &str) -> &'static str {
107    let compiled = || TABLES.iter().find(|(n, _)| *n == name).map(|(_, text)| *text).expect("a table of TABLES");
108    LOADED.get().and_then(|t| t.get(name).copied()).unwrap_or_else(compiled)
109}
110
111/// Thermal time constants come from the configuration manuals, which cover most of the same motors.
112/// The same files are the 1FK2 and 1FT2 on a SINAMICS S120.
113fn motor_manuals() -> [&'static str; 2] {
114    [table("siemens/motors_1fk2_s120.csv"), table("siemens/motors_1ft2_s120.csv")]
115}
116
117/// Reads the catalogue from a directory in place of the compiled-in one, for the rest of the process: a copy of
118/// `catalog/` (its own repository, or a newer edition of it). Every table the simulator reads must be there, and
119/// `catalog.toml` must have the `schema_version` this simulator reads. Call it before any part is looked up;
120/// a second call is refused.
121pub fn use_directory(dir: &std::path::Path) -> Result<(), ConfigError> {
122    let read = |name: &str| {
123        std::fs::read_to_string(dir.join(name))
124            .map_err(|e| ConfigError::Part("error-catalog-read", format!("{}: {e}", dir.join(name).display())))
125    };
126    let manifest: toml::Table = read("catalog.toml")?
127        .parse()
128        .map_err(|e| ConfigError::Part("error-catalog-read", format!("catalog.toml: {e}")))?;
129    match manifest.get("schema_version").and_then(toml::Value::as_integer) {
130        Some(SCHEMA_VERSION) => {}
131        other => return Err(ConfigError::Part("error-catalog-version", format!("{other:?}, {}", dir.display()))),
132    }
133    // Checked all before anything is kept, so a refused directory leaks nothing.
134    let mut texts = Vec::new();
135    for &(name, compiled) in TABLES {
136        let text = read(name)?;
137        check_table(name, &text, compiled)?;
138        texts.push((name, text));
139    }
140    let mut loaded = HashMap::new();
141    for (name, text) in texts {
142        // Kept for the life of the process, as the compiled-in tables are.
143        loaded.insert(name, &*Box::leak(text.into_boxed_str()));
144    }
145    LOADED.set(loaded).map_err(|_| ConfigError::Part("error-catalog-read", "the catalogue was already chosen".into()))
146}
147
148/// Refuses a CSV table (not `catalog.toml`) whose header lacks a column of the compiled-in table of the same name, or
149/// that has a row with another number of fields than its header. The readers index rows by column name and panic on
150/// a missing one, so this is the one place that guards them. The required columns are the compiled-in header's, so
151/// they cannot drift from the tables the code was written against; a column the code never reads is required too.
152fn check_table(name: &str, text: &str, compiled: &str) -> Result<(), ConfigError> {
153    if !name.ends_with(".csv") {
154        return Ok(());
155    }
156    let fail = |what: String| ConfigError::Part("error-catalog-read", format!("{name}: {what}"));
157    // As `rows` reads them: notes and blank lines passed over.
158    let mut lines = text.lines().enumerate().filter(|(_, l)| !l.starts_with('#') && !l.trim().is_empty());
159    let header: Vec<&str> = lines.next().map_or(Vec::new(), |(_, l)| l.split(',').collect());
160    let wanted = compiled.lines().find(|l| !l.starts_with('#')).unwrap_or("");
161    if let Some(missing) = wanted.split(',').find(|c| !header.contains(c)) {
162        return Err(fail(format!("missing column \"{missing}\"")));
163    }
164    match lines.find(|(_, l)| l.split(',').count() != header.len()) {
165        Some((i, l)) => {
166            Err(fail(format!("line {}: {} fields, the header has {}", i + 1, l.split(',').count(), header.len())))
167        }
168        None => Ok(()),
169    }
170}
171
172/// The supplies a motor can be named for: the S210 data at 230 V or 400 V, or the motor on a SINAMICS S120
173/// (400 V line). "s120" takes the 1FK7 and 1FT7 of `motors_s120.csv` and the 1FK2 and 1FT2 of their S120 manuals.
174/// "s210new-230v" and "s210new-400v" are the same 1FK2 and 1FT2 data with the "SINAMICS S210 (New)" converters
175/// (6SL5310) the D 32 pairs them with. The others are another maker's motors and drives at a line voltage,
176/// "<vendor>-<volts>v" (`vendor_of`): the rows of `<vendor>/motors_*.csv` and `<vendor>/drives_*.csv` with that
177/// `vendor` and `line_voltage_v`. `every_supply_has_motors_and_every_vendor_table_a_supply` keeps this list and the
178/// tables together.
179pub const SUPPLIES: &[&str] = &[
180    "230v",
181    "400v",
182    "s120",
183    "s210new-230v",
184    "s210new-400v",
185    "beckhoff-400v",
186    "beckhoff-480v",
187    "br-400v",
188    "kollmorgen-240v",
189    "kollmorgen-400v",
190    "lenze-400v",
191    "mitsubishi-200v",
192    "mitsubishi-400v",
193    "rexroth-400v",
194    "sew-400v",
195    "yaskawa-200v",
196    "yaskawa-400v",
197];
198
199/// The maker of a supply's motors and drives (`SUPPLIES`): "siemens" for the Siemens ones, else the part before "-".
200pub fn vendor_of(supply: &str) -> &str {
201    vendor_supply(supply).map_or("siemens", |(vendor, _)| vendor)
202}
203
204/// Another maker's supply, "<vendor>-<volts>v": the vendor and the line voltage in V.
205fn vendor_supply(supply: &str) -> Option<(&str, f64)> {
206    let (vendor, line) = supply.split_once('-')?;
207    if vendor == "s210new" {
208        return None;
209    }
210    Some((vendor, line.strip_suffix('v')?.parse().ok()?))
211}
212
213/// Whether every drive of the maker at that line voltage says in its `supply` column that it is fed single-phase ("1 AC",
214/// "1 x ..."; "1 or 3 AC" is both and counts as three-phase, as a drive on three phases has the lower ripple and the
215/// higher bus of the two).
216fn single_phase_line(vendor: &str, line: f64) -> bool {
217    let drives = vendor_rows("drives_", vendor, line);
218    !drives.is_empty() && drives.iter().all(|d| single_phase(d.get("supply").copied().unwrap_or("")))
219}
220
221/// Whether a drive's `supply` column says single-phase: "1 AC ...", "1 x ...", "1x ...", "single ...".
222fn single_phase(supply: &str) -> bool {
223    let text = supply.to_lowercase();
224    ["1 ac", "1 x", "1x", "single"].iter().any(|p| text.starts_with(p))
225}
226
227/// A supply of the S210 data: the voltage of its rated columns ("230v", "400v") and whether the converters are the
228/// new 6SL5310 ones.
229fn s210_supply(supply: &str) -> Option<(&'static str, bool)> {
230    match supply {
231        "230v" => Some(("230v", false)),
232        "400v" => Some(("400v", false)),
233        "s210new-230v" => Some(("230v", true)),
234        "s210new-400v" => Some(("400v", true)),
235        _ => None,
236    }
237}
238
239/// The text of every other maker's tables of a kind ("motors_" or "drives_"): `<vendor>/<kind>*.csv`.
240fn vendor_tables(kind: &str) -> Vec<&'static str> {
241    TABLES
242        .iter()
243        .map(|(name, _)| *name)
244        .filter(|name| name.split_once('/').is_some_and(|(maker, file)| maker != "siemens" && file.starts_with(kind)))
245        .map(table)
246        .collect()
247}
248
249/// The rows of another maker's tables of a kind (`vendor_tables`) for a vendor and line voltage.
250fn vendor_rows(kind: &str, vendor: &str, line: f64) -> Vec<Row> {
251    vendor_tables(kind)
252        .into_iter()
253        .flat_map(rows)
254        .filter(|r| r.get("vendor") == Some(&vendor) && number(r, "line_voltage_v") == Some(line))
255        .collect()
256}
257
258pub(crate) type Row = &'static HashMap<&'static str, &'static str>;
259
260/// The rows of a catalogue file; lines starting with '#' are notes. Each table is parsed once and kept for the life of
261/// the process, as its text is: a motor search reads the same tables for every motor it tries.
262pub(crate) fn rows(text: &'static str) -> Vec<Row> {
263    type Parsed = Vec<((usize, usize), &'static [HashMap<&'static str, &'static str>])>;
264    static PARSED: Mutex<Parsed> = Mutex::new(Vec::new());
265    let key = (text.as_ptr() as usize, text.len());
266    let mut parsed = PARSED.lock().unwrap_or_else(PoisonError::into_inner);
267    let table = match parsed.iter().find(|(k, _)| *k == key) {
268        Some(&(_, table)) => table,
269        None => {
270            // A blank line (an editor's at the end) is no row: one would lack every column but the first.
271            let mut lines = text.lines().filter(|l| !l.starts_with('#') && !l.trim().is_empty());
272            let header: Vec<&str> = lines.next().unwrap_or("").split(',').collect();
273            let table: &'static [_] =
274                Vec::leak(lines.map(|line| header.iter().copied().zip(line.split(',')).collect()).collect());
275            parsed.push((key, table));
276            table
277        }
278    };
279    table.iter().collect()
280}
281
282fn number(row: &Row, column: &str) -> Option<f64> {
283    row.get(column)?.parse().ok()
284}
285
286/// `what` is "motor", "gearbox", "drive", "belt" or "axis": the kind of part, which the message names in the user's language.
287fn unknown(what: &str, name: &str) -> ConfigError {
288    let key = match what {
289        "motor" => "error-config-part-motor",
290        "gearbox" => "error-config-part-gearbox",
291        "drive" => "error-config-part-drive",
292        "belt" => "error-config-part-belt",
293        _ => "error-config-part-axis",
294    };
295    ConfigError::Part(key, name.into())
296}
297
298/// A catalogue value (SI) in a config's unit, `factor` of them per SI unit, rounded to 12 significant digits: the
299/// catalogue's 0.00022 F is the 220 µF it was printed as, not 219.99999999999997.
300fn in_unit(si: f64, factor: f64) -> f64 {
301    let value = si * factor;
302    format!("{value:.11e}").parse().unwrap_or(value)
303}
304
305/// Puts a part's value into a config. A `[bounds]` entry of that value was written for the config's own value, so it
306/// follows the part's: scaled by the same factor, new over old (the band keeps its width relative to the value). A
307/// bound of a value that was 0 stays as written.
308fn set(cfg: &mut Config, path: &str, value: f64) -> Result<(), ConfigError> {
309    let bound = format!("bounds.{path}");
310    if let (Ok(old), Ok([low, high])) = (cfg.f64(path), cfg.f64s(&bound).as_deref())
311        && old != 0.0
312        && old != value
313    {
314        let (low, high) = (low * value / old, high * value / old);
315        cfg.set_text(&format!("{bound} = [{:?}, {:?}]", low.min(high), low.max(high)))?;
316    }
317    cfg.set_text(&format!("{path} = {value:?}"))
318}
319
320/// The base load current of an S210 converter per its rated current [estimate]: the lowest share of the S120 Motor
321/// Modules of up to 30 A, the range of the S210, in `motor_modules_s120.csv` (15.3 A of 18 A; 0.85 to 0.87 there).
322pub const S210_BASE_LOAD_SHARE: f64 = 0.85;
323
324/// Sets a value only where the config has the key: ratings a config leaves out are not judged.
325fn set_if_present(cfg: &mut Config, path: &str, value: f64) -> Result<(), ConfigError> {
326    if cfg.get(path).is_ok() { set(cfg, path, value) } else { Ok(()) }
327}
328
329/// Article numbers of the SINAMICS S210 motors, e.g. "1FK2205-4AF".
330pub fn motor_articles() -> Vec<&'static str> {
331    rows(table("siemens/motors_s210.csv")).iter().map(|r| r["part_number"]).collect()
332}
333
334/// Article numbers of the motors that can be named for a supply (`SUPPLIES`): the S210 motors for "230v" and
335/// "400v" (not every one is offered at both), and for "s120" the 1FK7 and 1FT7 that have a data sheet and the 1FK2
336/// and 1FT2 of the S120 manuals that have a rotor inertia.
337pub fn motor_articles_for(supply: &str) -> Vec<&'static str> {
338    match supply {
339        "s120" => {
340            let sheets: Vec<&str> =
341                rows(table("siemens/motors_s120_electrical.csv")).iter().map(|r| r["part_number"]).collect();
342            let mut out: Vec<&str> = rows(table("siemens/motors_s120.csv"))
343                .iter()
344                .map(|r| r["part_number"])
345                .filter(|a| sheets.contains(a))
346                .collect();
347            out.extend(
348                motor_manuals()
349                    .into_iter()
350                    .flat_map(|t| rows(t))
351                    .filter(|r| number(r, "rotor_inertia_kgm2").is_some())
352                    .map(|r| r["part_number"]),
353            );
354            out
355        }
356        _ => match vendor_supply(supply) {
357            Some((vendor, line)) => vendor_rows("motors_", vendor, line)
358                .iter()
359                .filter(|r| number(r, "rotor_inertia_kgm2").is_some())
360                .map(|r| r["part_number"])
361                .collect(),
362            None => motor_articles(),
363        },
364    }
365}
366
367/// What a motor brings into a config, from whichever catalogue file has it.
368struct MotorData {
369    rotor_kgm2: f64,
370    /// Rotor inertia and weight with the holding brake, where the catalogue gives them.
371    brake: Option<(f64, f64)>,
372    static_torque: f64,
373    stall_current: f64,
374    max_torque: f64,
375    max_current: f64,
376    rated_current: f64,
377    rated_torque: f64,
378    rated_speed: f64,
379    /// The highest speed: mechanical (S210 table), what the converter allows (1FK2, 1FT2 on S120), or the lower of the
380    /// two (1FK7, 1FT7).
381    max_speed: f64,
382    thermal_seconds: Option<f64>,
383    /// Phase resistance at 20 °C in ohms and rotating field inductance in henries, where a data sheet prints them.
384    winding: Option<(f64, f64)>,
385    /// Pole pairs, where the catalogue prints them (the 1FK7 and 1FT7: half the data sheet's poles, else `motors_s120.csv`).
386    pole_pairs: Option<f64>,
387    mass: f64,
388    /// A linear motor's force constant as printed (N/A), which stands in for the torque constant static over stall.
389    force_constant: Option<f64>,
390    /// A linear motor's magnetic attraction (N) and pole pitch (m).
391    linear: Option<(f64, f64)>,
392    /// The back-EMF constant in the model's one-winding convention (sqrt(3) times the printed line-to-line RMS voltage
393    /// constant, V s/rad), where the table has it and it is not a documented misprint; `None` for kt.
394    emf_constant: Option<f64>,
395}
396
397/// The one-winding back-EMF constant from a printed line-to-line RMS voltage constant. The two documented misprints
398/// (AKM64Q at 240 V, 1FT7044-1AF7; `VENDOR_MISPRINTS` in the checks) are not used; any other printed value is, however far
399/// from the torque constant (Beckhoff AM8000 up to 1.30 times it, Rexroth MS2N 1.18). `line` is the line voltage, 0 for
400/// Siemens.
401fn emf_constant(printed: Option<f64>, article: &str, line: f64) -> Option<f64> {
402    let misprint = (article == "AKM64Q" && line == 240.0) || article == "1FT7044-1AF7";
403    printed.filter(|_| !misprint).map(|ke| 3f64.sqrt() * ke)
404}
405
406fn motor_data(article: &str, supply: &str) -> Result<MotorData, ConfigError> {
407    let missing = || unknown("motor", &format!("{article}, {supply}"));
408    // A linear motor (`mechanics::linear_rows`): forces for torques, the coil's mass for the rotor's inertia, m/s for rad/s.
409    if let Some(m) = mechanics::linear_motor_row(article, supply) {
410        let get = |column: &str| number(&m, column).ok_or_else(missing);
411        let max_speed = get("max_speed_m_s")?;
412        return Ok(MotorData {
413            rotor_kgm2: get("coil_mass_kg")?,
414            brake: None,
415            static_torque: get("continuous_force_n")?,
416            stall_current: get("continuous_current_a")?,
417            max_torque: get("peak_force_n")?,
418            max_current: get("peak_current_a")?,
419            rated_current: get("continuous_current_a")?,
420            rated_torque: get("continuous_force_n")?,
421            // Full force up to the speed the maker gives the peak force at, else up to its highest speed.
422            rated_speed: number(&m, "max_speed_at_peak_force_m_s").unwrap_or(max_speed),
423            max_speed,
424            thermal_seconds: number(&m, "thermal_time_constant_s"),
425            winding: number(&m, "phase_resistance_20c_ohm").zip(number(&m, "phase_inductance_h")),
426            pole_pairs: None,
427            mass: get("coil_mass_kg")?,
428            force_constant: number(&m, "force_constant_n_a"),
429            linear: number(&m, "attraction_force_n").zip(number(&m, "pole_pitch_m")),
430            emf_constant: None,
431        });
432    }
433    if let Some((vendor, line)) = vendor_supply(supply) {
434        let m = vendor_rows("motors_", vendor, line)
435            .into_iter()
436            .find(|r| r["part_number"] == article)
437            .ok_or_else(|| unknown("motor", article))?;
438        let get = |column: &str| number(&m, column).ok_or_else(missing);
439        // shortcut: a maker that prints no standstill values (Yaskawa, Mitsubishi) has its rated ones stand for them,
440        // and one that prints no rated torque (SEW CMP) its standstill one, which overstates what the motor carries at
441        // speed by a few per cent; upgrade with rated data. A missing rated current (Kollmorgen, Beckhoff at 480 V)
442        // is the rated torque over the torque constant.
443        let either = |first: &str, second: &str| number(&m, first).map_or_else(|| get(second), Ok);
444        let (static_torque, stall_current) =
445            (either("static_torque_nm", "rated_torque_nm")?, either("stall_current_a", "rated_current_a")?);
446        let rated_current = match (number(&m, "rated_current_a"), number(&m, "rated_torque_nm")) {
447            (Some(current), _) => current,
448            (None, Some(torque)) => torque * stall_current / static_torque,
449            (None, None) => stall_current,
450        };
451        return Ok(MotorData {
452            rotor_kgm2: get("rotor_inertia_kgm2")?,
453            brake: number(&m, "rotor_inertia_with_brake_kgm2").zip(number(&m, "mass_with_brake_kg")),
454            static_torque,
455            stall_current,
456            max_torque: get("max_torque_nm")?,
457            max_current: get("max_current_a")?,
458            rated_current,
459            rated_torque: either("rated_torque_nm", "static_torque_nm")?,
460            rated_speed: get("rated_speed_rad_s")?,
461            max_speed: get("max_speed_rad_s")?,
462            thermal_seconds: number(&m, "thermal_time_constant_s"),
463            // Terminal to terminal in the tables; one phase of the star is half of it.
464            winding: number(&m, "line_resistance_20c_ohm")
465                .zip(number(&m, "line_inductance_h"))
466                .map(|(r, l)| (r / 2.0, l / 2.0)),
467            pole_pairs: number(&m, "pole_pairs"),
468            mass: get("mass_kg")?,
469            force_constant: None,
470            linear: None,
471            emf_constant: emf_constant(number(&m, "voltage_constant_v_s_rad"), article, line),
472        });
473    }
474    if supply == "s120" {
475        if let Some(m) = rows(table("siemens/motors_s120.csv")).into_iter().find(|r| r["part_number"] == article) {
476            let sheet = rows(table("siemens/motors_s120_electrical.csv"))
477                .into_iter()
478                .find(|r| r["part_number"] == article)
479                .ok_or_else(missing)?;
480            let get = |row: &Row, column: &str| number(row, column).ok_or_else(missing);
481            return Ok(MotorData {
482                rotor_kgm2: get(&m, "rotor_inertia_kgm2")?,
483                // motors_s120.csv has no brake data.
484                brake: None,
485                static_torque: get(&m, "static_torque_nm")?,
486                stall_current: get(&m, "stall_current_a")?,
487                max_torque: get(&sheet, "max_torque_nm")?,
488                max_current: get(&sheet, "max_current_a")?,
489                rated_current: get(&m, "rated_current_a")?,
490                rated_torque: get(&m, "rated_torque_nm")?,
491                // Rated torque and current hold at `rated_values_at_speed_rad_s` where the table fills it (9 rows).
492                rated_speed: number(&m, "rated_values_at_speed_rad_s")
493                    .map_or_else(|| get(&m, "rated_speed_rad_s"), Ok)?,
494                max_speed: get(&sheet, "max_speed_mechanical_rad_s")?.min(get(&sheet, "max_speed_inverter_rad_s")?),
495                thermal_seconds: number(&sheet, "thermal_time_constant_s"),
496                winding: number(&sheet, "phase_resistance_20c_ohm").zip(number(&sheet, "phase_inductance_h")),
497                // The motor's own data sheet before the catalogue's table, which prints 5 for every 1FT7 High Dynamic
498                // where their sheets give 6 and 8 poles (the 150 other motors agree in both).
499                pole_pairs: number(&sheet, "poles").map(|p| p / 2.0).or_else(|| number(&m, "pole_pairs")),
500                mass: get(&m, "mass_kg")?,
501                force_constant: None,
502                linear: None,
503                emf_constant: emf_constant(number(&sheet, "voltage_constant_v_s_rad"), article, 0.0),
504            });
505        }
506        let m = motor_manuals()
507            .into_iter()
508            .flat_map(|t| rows(t))
509            .find(|r| r["part_number"] == article)
510            .ok_or_else(|| unknown("motor", article))?;
511        let get = |column: &str| number(&m, column).ok_or_else(missing);
512        return Ok(MotorData {
513            rotor_kgm2: get("rotor_inertia_kgm2")?,
514            brake: number(&m, "rotor_inertia_with_brake_kgm2").zip(number(&m, "mass_with_brake_kg")),
515            static_torque: get("static_torque_nm")?,
516            stall_current: get("stall_current_a")?,
517            max_torque: get("max_torque_nm")?,
518            max_current: get("max_current_a")?,
519            rated_current: get("rated_current_a")?,
520            rated_torque: get("rated_torque_nm")?,
521            // Three rows print a rated speed that does not fit their rated torque and power (`docs/catalogue.md`): power
522            // over torque gives 4500 and 3000 r/min, as the S210 catalogue has it. The data keep the printed value.
523            rated_speed: if ["1FT2105-4AH", "1FT2206-4AH", "1FT2208-4AF"].contains(&article) {
524                get("rated_power_w")? / get("rated_torque_nm")?
525            } else {
526                get("rated_speed_rad_s")?
527            },
528            max_speed: get("max_speed_inverter_rad_s")?,
529            thermal_seconds: number(&m, "thermal_time_constant_s"),
530            winding: None,
531            pole_pairs: None,
532            mass: get("mass_kg")?,
533            force_constant: None,
534            linear: None,
535            emf_constant: None,
536        });
537    }
538    let motor = rows(table("siemens/motors_s210.csv"))
539        .into_iter()
540        .find(|r| r["part_number"] == article)
541        .ok_or_else(|| unknown("motor", article))?;
542    let get = |column: &str| number(&motor, column).ok_or_else(missing);
543    let voltage = s210_supply(supply).ok_or_else(missing)?.0;
544    let rated = |quantity: &str, unit: &str| get(&format!("rated_{quantity}_{voltage}_{unit}"));
545    let manual = motor_manuals().into_iter().flat_map(|text| rows(text)).find(|r| r["part_number"] == article);
546    // The S210 operating instructions (09/2022) have the 230 V windings and the 1FT2 the manuals lack; where both have a
547    // motor they agree.
548    let instructions = || rows(table("siemens/motors_s210_oi.csv")).into_iter().find(|r| r["part_number"] == article);
549    Ok(MotorData {
550        rotor_kgm2: get("rotor_inertia_kgm2")?,
551        brake: number(&motor, "rotor_inertia_with_brake_kgm2").zip(number(&motor, "mass_with_brake_kg")),
552        static_torque: get("static_torque_nm")?,
553        stall_current: get("stall_current_a")?,
554        max_torque: get("max_torque_nm")?,
555        max_current: get("max_current_a")?,
556        rated_current: rated("current", "a")?,
557        rated_torque: rated("torque", "nm")?,
558        rated_speed: rated("speed", "rad_s")?,
559        max_speed: get("max_speed_rad_s")?,
560        thermal_seconds: manual
561            .as_ref()
562            .and_then(|r| number(r, "thermal_time_constant_s"))
563            .or_else(|| instructions().and_then(|r| number(&r, "thermal_time_constant_s"))),
564        winding: None,
565        pole_pairs: None,
566        mass: get("mass_kg")?,
567        force_constant: None,
568        linear: None,
569        emf_constant: None,
570    })
571}
572
573/// Weight of a motor without brake, for the supply its data is taken for (`SUPPLIES`).
574pub fn motor_mass(article: &str, supply: &str) -> Option<f64> {
575    motor_data(article, supply).ok().map(|m| m.mass)
576}
577
578/// Weight of a motor with the brake option a config chooses (`parts.motor_brake`, see `apply_motor`); `None` for a
579/// motor the catalogue does not have, or has no brake data of where the brake is chosen.
580pub fn motor_mass_for(cfg: &Config, article: &str, supply: &str) -> Option<f64> {
581    let m = motor_data(article, supply).ok()?;
582    if brake_chosen(cfg).ok()? { m.brake.map(|(_, mass)| mass) } else { Some(m.mass) }
583}
584
585/// `parts.motor_brake`: whether the motor has its holding brake; false where the config does not say.
586fn brake_chosen(cfg: &Config) -> Result<bool, ConfigError> {
587    if cfg.get("parts.motor_brake").is_ok() { cfg.bool("parts.motor_brake") } else { Ok(false) }
588}
589
590/// The motor's highest speed in rad/s from the catalogue (the lower of the mechanical limit and what the converter
591/// allows, where both are given); `None` where the catalogue has none.
592pub fn motor_max_speed(article: &str, supply: &str) -> Option<f64> {
593    motor_data(article, supply).ok().map(|m| m.max_speed)
594}
595
596/// Puts a motor of the catalogue into a config, for a supply of `SUPPLIES` ("230v", "400v", "s120", ...): rotor
597/// inertia, torque constant and saturation, rated current, thermal time constant, and the drive's torque and speed
598/// limits. The peak torque stays within what the machine's pulley allows, where the config rates that.
599///
600/// The bus voltage becomes the DC link voltage of that supply, because the catalogue's rated speed and
601/// torque hold on it: 540 V on a 400 V three-phase line (1.35 times the line voltage, the figure the
602/// Siemens line module data in `catalog/siemens/line_modules_s120.csv` is given for; also for "s120", whose motor
603/// data hold for a DC link of 510 to 720 V) and 325 V on a 230 V line (its peak, 230 V times the square root of 2);
604/// another maker's, 1.35 times its line voltage.
605/// A config written for another bus would otherwise run the motor against a back-EMF it was never meant to meet.
606/// The braking threshold and the trip level of the config's DC link are scaled with the bus voltage: left as they
607/// were, those of a config written for a lower bus would lie below the new one.
608///
609/// Winding resistance and inductance: Siemens publishes them only for the 1FK7 and 1FT7 (their data sheets, per
610/// phase). For those they are put in as the model's one winding has them, three times the phase values (its
611/// current is the RMS phase current and its voltage three times the phase voltage, see `drive`), and the current
612/// controller is retuned with them: Kp = L / T for the config's own current loop time constant T (its L over its
613/// Kp), Tn = L / R. For every other motor they stay as the config has them, and so do the current loop's gains.
614/// The velocity gain stays here too; `resolve` and `with_parts` retune it for the new rotor.
615///
616/// Options of the motor, read from `[parts]` where the config has them: `motor_brake = true` takes the inertia and
617/// weight with the holding brake (refused for a motor without brake data), and `motor_encoder` the encoder's counts per
618/// revolution from `encoders_1fk2_1ft2.csv` ("AS22DQC", "AM22DQC"; the 26-bit "AS26DQC", "AM26DQC" for a 1FT2 only).
619/// It sets `drive.max_speed_rad_s` to the catalogue's highest speed (the lower of the mechanical limit and what the
620/// converter allows, where both are given) and `motor.stall_current_a`, where the config has them.
621///
622/// A linear motor (`<maker>/linear_motors_*.csv`: the Siemens 1FN3 at "s120", another maker's at its supply) reads in N
623/// for N m and m for rad, as a linear motor config does: its printed force constant for the torque constant, the
624/// coil's mass for the rotor's inertia, the continuous and peak force and current, the speeds in m/s, the winding's
625/// phase values as the 1FK7's are put in, and its magnetic attraction and pole pitch into `[linear_motor]`.
626pub fn apply_motor(cfg: &mut Config, article: &str, supply: &str) -> Result<(), ConfigError> {
627    if !SUPPLIES.contains(&supply) {
628        return Err(unknown("motor", &format!("{article}, {supply}")));
629    }
630    let m = motor_data(article, supply)?;
631    let kt = m.force_constant.unwrap_or(m.static_torque / m.stall_current);
632    let rated_speed = m.rated_speed;
633    // The holding brake's inertia turns with the rotor (`parts.motor_brake`).
634    let rotor = if brake_chosen(cfg)? {
635        m.brake.map(|(inertia, _)| inertia).ok_or_else(|| unknown("motor", &format!("{article} with brake")))?
636    } else {
637        m.rotor_kgm2
638    };
639    set(cfg, "motor.rotor_inertia_kgm2", rotor)?;
640    // The encoder ordered with the motor (`parts.motor_encoder`, "" for the config's): its counts per revolution.
641    if let Ok(encoder) = cfg.get("parts.motor_encoder").map(|v| v.as_str().unwrap_or("?").to_string())
642        && !encoder.is_empty()
643    {
644        let series = &article[..article.len().min(4)];
645        let row = rows(table("siemens/encoders_1fk2_1ft2.csv"))
646            .into_iter()
647            .find(|r| r["part_number"] == encoder && r["series"].split(' ').any(|s| s == series))
648            .ok_or_else(|| unknown("motor", &format!("{article} with encoder {encoder}")))?;
649        set(cfg, "drive.encoder_counts_per_rev", number(&row, "resolution_counts").unwrap_or(f64::NAN))?;
650    }
651    // effects.iron_loss and the S1 check ("motor-s1") take the stall current: static torque over torque constant.
652    set_if_present(cfg, "motor.stall_current_a", m.stall_current)?;
653    set(cfg, "motor.torque_constant_nm_a", kt)?;
654    set(cfg, "motor.max_current_a", m.max_current)?;
655    // The catalogue's own rated current, up to 18 % above rated torque over the static torque constant.
656    // One row prints a rated current far above the stall current (see the file's header); no other motor's
657    // is more than 5 % above it, so that is where it stops.
658    set(cfg, "motor.rated_current_a", m.rated_current.min(1.05 * m.stall_current))?;
659    set(cfg, "motor.torque_constant_at_max_current_nm_a", (m.max_torque / m.max_current).min(kt))?;
660    if let Some(seconds) = m.thermal_seconds {
661        set(cfg, "motor.thermal_time_constant_s", seconds)?;
662    }
663    if let Some((phase_resistance, phase_inductance)) = m.winding {
664        let time_constant = cfg.positive("motor.inductance_h")? / cfg.positive("drive.current_kp_v_a")?;
665        let (resistance, inductance) = (3.0 * phase_resistance, 3.0 * phase_inductance);
666        set(cfg, "motor.resistance_ohm", resistance)?;
667        set(cfg, "motor.inductance_h", inductance)?;
668        set(cfg, "drive.current_kp_v_a", inductance / time_constant)?;
669        set(cfg, "drive.current_tn_s", inductance / resistance)?;
670        // effects.field_weakening: the data sheet's one rotating field inductance for both axes, as for surface magnets.
671        set_if_present(cfg, "motor.d_inductance_h", inductance)?;
672    }
673    if let Some(pairs) = m.pole_pairs {
674        set_if_present(cfg, "motor.pole_pairs", pairs)?;
675    }
676    // A 1FK2 without a data sheet [estimate]: the inductance from Siemens' armature short-circuit braking table. Shorted,
677    // the winding brakes with R ke^2 w / (R^2 + (p w L)^2), at most ke^2 / (2 p L) where p w L = R: the table's maximum
678    // braking torque gives p L = kt^2 / (2 M_br,max) (the model's ke is its kt). The current controller is retuned as
679    // for a data sheet; the resistance stays the config's.
680    // shortcut: R stays an estimate, and the table's conditions (rated values, no saturation) hold for the peak alone.
681    if m.winding.is_none()
682        && cfg.get("motor.pole_pairs").is_ok()
683        && let Some(peak) = rows(table("siemens/dynamic_braking_1fk2.csv"))
684            .into_iter()
685            .find(|r| r["part_number"] == article)
686            .and_then(|r| number(&r, "max_braking_torque_nm"))
687    {
688        let time_constant = cfg.positive("motor.inductance_h")? / cfg.positive("drive.current_kp_v_a")?;
689        let inductance = kt * kt / (2.0 * cfg.positive("motor.pole_pairs")? * peak);
690        set(cfg, "motor.inductance_h", inductance)?;
691        set(cfg, "drive.current_kp_v_a", inductance / time_constant)?;
692        set(cfg, "drive.current_tn_s", inductance / cfg.positive("motor.resistance_ohm")?)?;
693        set_if_present(cfg, "motor.d_inductance_h", inductance)?;
694    }
695    if let Some((attraction, pitch)) = m.linear {
696        set_if_present(cfg, "linear_motor.attraction_force_n", attraction)?;
697        set_if_present(cfg, "linear_motor.pole_pitch_m", pitch)?;
698    }
699    set_s1_curve(cfg, &s1_curve(article, supply))?;
700    cap_peak_torque(cfg, m.max_torque)?;
701    set(cfg, "drive.rated_torque_nm", m.rated_torque)?;
702    set(cfg, "drive.rated_speed_rad_s", rated_speed)?;
703    set(cfg, "drive.max_speed_rad_s", m.max_speed)?;
704    // A rectified three-phase line gives 1.35 times its voltage, a single-phase one its peak, sqrt(2) times it.
705    let bus = match vendor_supply(supply) {
706        Some((vendor, line)) => (if single_phase_line(vendor, line) { std::f64::consts::SQRT_2 } else { 1.35 }) * line,
707        None if s210_supply(supply).is_some_and(|(voltage, _)| voltage == "230v") => 325.0,
708        None => 540.0,
709    };
710    let scale = bus / cfg.positive("drive.bus_voltage_v")?;
711    for rating in ["ratings.braking_threshold_v", "ratings.dc_link_overvoltage_v"] {
712        if let Ok(voltage) = cfg.f64(rating) {
713            set(cfg, rating, voltage * scale)?;
714        }
715    }
716    set(cfg, "drive.bus_voltage_v", bus)?;
717    // Full torque up to the rated speed; it is gone where the back-EMF uses up what the DC link gives the winding.
718    // A printed voltage constant is the model's back-EMF constant (`drive.back_emf_constant_v_s_rad`, 0 for kt) and sets
719    // the no-load speed with it.
720    let ke = m.emf_constant.unwrap_or(kt);
721    set_if_present(cfg, "drive.back_emf_constant_v_s_rad", m.emf_constant.unwrap_or(0.0))?;
722    set(cfg, "drive.no_load_speed_rad_s", (crate::drive::WINDING_PER_DC_LINK * bus / ke).max(1.1 * rated_speed))
723}
724
725/// The S1 curve Siemens prints as a graph for an S210 motor at a supply (`s1_curves_s210.csv`, digitised: article, speed,
726/// torque, rising speed): the file holds one curve per motor, the 400 V 3 AC one for a motor with a rated point at 400 V
727/// and else the 240 V 3 AC one (its meta file), so it is the motor's only at that voltage, "400v" or "230v" (the 6SL5310
728/// converters, "s210new-...", give the same DC link and so the same curve, as they give the same motor values; not the
729/// S120). Empty where the file has no curve for it.
730fn s1_curve(article: &str, supply: &str) -> Vec<(f64, f64)> {
731    let Some(row) = rows(table("siemens/motors_s210.csv")).into_iter().find(|r| r["part_number"] == article) else {
732        return Vec::new();
733    };
734    let read_for = if number(&row, "rated_speed_400v_rad_s").is_some() { "400v" } else { "230v" };
735    if s210_supply(supply).map(|(voltage, _)| voltage) != Some(read_for) {
736        return Vec::new();
737    }
738    rows(table("siemens/s1_curves_s210.csv"))
739        .into_iter()
740        .filter(|r| r.get("article") == Some(&article))
741        .filter_map(|r| Some((number(&r, "speed_rad_s")?, number(&r, "torque_nm")?)))
742        .collect()
743}
744
745/// Puts a named motor's S1 curve into `motor.s1_curve_speed_rad_s` and `motor.s1_curve_torque_nm`, where it replaces
746/// the straight line between the printed standstill and rated points (`analysis::s1_torque`); without one (fewer than
747/// two points) it takes the keys out, as a curve the config had belongs to the motor it had.
748fn set_s1_curve(cfg: &mut Config, curve: &[(f64, f64)]) -> Result<(), ConfigError> {
749    const KEYS: [&str; 2] = ["s1_curve_speed_rad_s", "s1_curve_torque_nm"];
750    let has = KEYS.iter().any(|k| cfg.get(&format!("motor.{k}")).is_ok());
751    if curve.len() < 2 && !has {
752        return Ok(());
753    }
754    let parse = |e: toml::de::Error| ConfigError::Parse(e.to_string());
755    let mut all = cfg.to_text()?.parse::<toml::Table>().map_err(parse)?;
756    let motor = all.get_mut("motor").and_then(toml::Value::as_table_mut).ok_or(ConfigError::Missing("motor".into()))?;
757    for (key, pick) in KEYS.into_iter().zip([|p: &(f64, f64)| p.0, |p: &(f64, f64)| p.1]) {
758        if curve.len() < 2 {
759            motor.remove(key);
760        } else {
761            motor.insert(key.into(), toml::Value::Array(curve.iter().map(|p| toml::Value::Float(pick(p))).collect()));
762        }
763    }
764    *cfg = Config::parse(&toml::to_string(&all).map_err(|e| ConfigError::Parse(e.to_string()))?)?;
765    Ok(())
766}
767
768/// The motor's peak torque `uncapped` held within the pulley's rating. Braking, the pulley's torque is the motor's times
769/// ratio over efficiency: the tighter of the two directions caps it. `apply_gearbox` calls it too, so the result does not
770/// depend on which of the two came first.
771fn cap_peak_torque(cfg: &mut Config, uncapped: f64) -> Result<(), ConfigError> {
772    set(cfg, "drive.peak_torque_nm", uncapped.min(pulley_allowed(cfg)))
773}
774
775/// The highest motor torque the pulley's rating allows through the config's gearbox; infinite without a rating.
776fn pulley_allowed(cfg: &Config) -> f64 {
777    let ratio = cfg.f64("gearbox.ratio").unwrap_or(1.0);
778    let efficiency = cfg.f64("gearbox.efficiency").unwrap_or(1.0).clamp(f64::MIN_POSITIVE, 1.0);
779    cfg.f64("ratings.pulley_max_torque_nm").map_or(f64::INFINITY, |at_pulley| at_pulley * efficiency / ratio)
780}
781
782/// The drive the catalogue pairs with a motor at a supply: for the S210 the converter the D 32 lists beside the
783/// motor (at 230 V the single-phase one where there is one); for a 1FK7 or 1FT7 on S120 the Single Motor Module
784/// D 21.4 names. The 1FK2 and 1FT2 on S120 have no pairing in their manuals: theirs is the smallest Single Motor
785/// Module whose rated current carries the motor's stall current, the rule D 21.4 pairs the 1FK7 and 1FT7 by
786/// (`siemens_s120_motors_are_plausible_and_their_motor_modules_exist` checks it); of two such, the one with the
787/// higher maximum current. For "s210new-..." the 6SL5310 converter the D 32 lists beside the motor.
788///
789/// Another maker's motor (`vendor_of`): the drive its row names in `paired_drive`, the maker's own pairing, where
790/// the maker's drive table has it at that line voltage; else by the same rule as the 1FK2 on S120, the smallest drive of
791/// the maker at that line voltage whose rated current carries the motor's stall current, a Single Motor Module before a
792/// Double Motor Module. "" where there is none.
793pub fn paired_drive(article: &str, supply: &str) -> &'static str {
794    if let Some((vendor, line)) = vendor_supply(supply) {
795        let drives = vendor_rows("drives_", vendor, line);
796        let named = vendor_rows("motors_", vendor, line).into_iter().find(|r| r["part_number"] == article);
797        if let Some(own) = named.and_then(|m| drives.iter().find(|d| d["part_number"] == m["paired_drive"])) {
798            return own["part_number"];
799        }
800        let stall = motor_data(article, supply).map_or(f64::INFINITY, |m| m.stall_current);
801        let key = |d: &Row| {
802            (
803                d["axes"] != "1",
804                number(d, "rated_output_current_a").unwrap_or(f64::INFINITY),
805                -number(d, "max_output_current_a").unwrap_or(0.0),
806            )
807        };
808        return drives
809            .iter()
810            .filter(|d| number(d, "rated_output_current_a").is_some_and(|i| i >= stall))
811            .min_by(|a, b| key(a).partial_cmp(&key(b)).unwrap_or(std::cmp::Ordering::Equal))
812            .map_or("", |d| d["part_number"]);
813    }
814    match s210_supply(supply) {
815        Some((voltage, new)) => {
816            let Some(motor) = rows(table("siemens/motors_s210.csv")).into_iter().find(|r| r["part_number"] == article)
817            else {
818                return "";
819            };
820            let columns: &[&str] = if voltage == "400v" { &["400v_3ac"] } else { &["230v_1ac", "230v_3ac"] };
821            let series = if new { "paired_drive_new_" } else { "paired_drive_" };
822            columns.iter().map(|c| motor[format!("{series}{c}").as_str()]).find(|a| !a.is_empty()).unwrap_or("")
823        }
824        None => paired_s120(article, supply),
825    }
826}
827
828fn paired_s120(article: &str, supply: &str) -> &'static str {
829    match supply {
830        "s120" => {
831            let modules = rows(table("siemens/motor_modules_s120.csv"));
832            if let Some(motor) =
833                rows(table("siemens/motors_s120.csv")).into_iter().find(|r| r["part_number"] == article)
834            {
835                // "6SL3120-7TE13-0AD.": 7 for Single or Double, the last character open.
836                let pattern = motor["paired_drive"].replacen("6SL3120-7", "6SL3120-1", 1);
837                let stem = &pattern[..pattern.len().saturating_sub(1)];
838                if let Some(m) = modules.iter().find(|m| m["part_number"].starts_with(stem)) {
839                    return m["part_number"];
840                }
841            }
842            let stall = motor_data(article, "s120").map_or(f64::INFINITY, |m| m.stall_current);
843            let mut fits: Vec<&Row> = modules
844                .iter()
845                .filter(|m| m["axes"] == "1" && number(m, "rated_output_current_a").is_some_and(|i| i >= stall))
846                .collect();
847            let key = |m: &&Row| {
848                (
849                    number(m, "rated_output_current_a").unwrap_or(f64::INFINITY),
850                    -number(m, "max_output_current_a").unwrap_or(0.0),
851                )
852            };
853            fits.sort_by(|a, b| key(a).partial_cmp(&key(b)).unwrap_or(std::cmp::Ordering::Equal));
854            fits.first().map_or("", |m| m["part_number"])
855        }
856        _ => "",
857    }
858}
859
860/// Which drives the search tries with each motor: the one the catalogue pairs with it (`paired_drive`), that one and
861/// the next size down and up (`drive_neighbours`), or every drive of the supply (`drives_for`).
862#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
863pub enum Drives {
864    #[default]
865    Paired,
866    Neighbours,
867    All,
868}
869
870impl std::str::FromStr for Drives {
871    type Err = ();
872    fn from_str(text: &str) -> Result<Self, ()> {
873        match text {
874            "paired" => Ok(Drives::Paired),
875            "neighbours" | "neighbors" => Ok(Drives::Neighbours),
876            "all" => Ok(Drives::All),
877            _ => Err(()),
878        }
879    }
880}
881
882/// The drives of a supply (`SUPPLIES`) with their rated and maximum output current, smallest rated current first (of
883/// two alike, the higher maximum current first): the S210 converters for "230v" (1 AC and 3 AC) and "400v" (3 AC), the
884/// new 6SL5310 ones for "s210new-...", the Single and Double Motor Modules for "s120" (a Double, "6SL3120-2...", with its per axis currents), another maker's drives at the line
885/// voltage. A maker that prints no maximum current (Mitsubishi) has NaN there.
886pub fn drives_for(supply: &str) -> Vec<(&'static str, f64, f64)> {
887    let current = |r: &Row| {
888        (r["part_number"], number(r, "rated_output_current_a"), number(r, "max_output_current_a").unwrap_or(f64::NAN))
889    };
890    let rows: Vec<Row> = match (vendor_supply(supply), s210_supply(supply), supply) {
891        (Some((vendor, line)), ..) => vendor_rows("drives_", vendor, line),
892        (_, Some((voltage, new)), _) => rows(table("siemens/converters_s210.csv"))
893            .into_iter()
894            .filter(|r| (r["series"] == "S210 (New)") == new && (voltage == "230v" || r["supply"].ends_with("3 AC")))
895            .collect(),
896        (.., "s120") => rows(table("siemens/motor_modules_s120.csv")),
897        _ => Vec::new(),
898    };
899    let mut out: Vec<(&'static str, f64, f64)> =
900        rows.iter().map(current).filter_map(|(part, rated, max)| Some((part, rated?, max))).collect();
901    out.sort_by(|a, b| a.1.total_cmp(&b.1).then(b.2.total_cmp(&a.2)).then(a.0.cmp(b.0)));
902    out.dedup_by(|a, b| a.0 == b.0);
903    out
904}
905
906/// The paired drive (`paired_drive`) and the next size down and up by rated output current among the supply's drives
907/// (`drives_for`): the largest with a lower rated current and the smallest with a higher one (of two alike, the higher
908/// maximum current). Smallest first; the paired one alone where it is not in the list, none where there is none.
909pub fn drive_neighbours(article: &str, supply: &str) -> Vec<&'static str> {
910    let paired = paired_drive(article, supply);
911    let all = drives_for(supply);
912    let Some(&(_, rated, _)) = all.iter().find(|d| d.0 == paired) else {
913        return [paired].into_iter().filter(|p| !p.is_empty()).collect();
914    };
915    let lower = all.iter().filter(|d| d.1 < rated).map(|d| d.1).reduce(f64::max);
916    let higher = all.iter().find(|d| d.1 > rated).map(|d| d.1);
917    let first_at = |current: Option<f64>| current.and_then(|c| all.iter().find(|d| d.1 == c)).map(|d| d.0);
918    [first_at(lower), Some(paired), first_at(higher)].into_iter().flatten().collect()
919}
920
921/// The drives the search tries with a motor at a supply (`Drives`); "" alone where the catalogue pairs none, and the
922/// config's drive stays.
923fn drives_tried(article: &str, supply: &str, drives: Drives) -> Vec<&'static str> {
924    let out = match drives {
925        Drives::Paired => vec![paired_drive(article, supply)],
926        Drives::Neighbours => drive_neighbours(article, supply),
927        Drives::All => drives_for(supply).into_iter().map(|d| d.0).collect(),
928    };
929    if out.iter().all(|d| d.is_empty()) { vec![""] } else { out }
930}
931
932/// What a motor and drive of the catalogue leave to the config's estimates, by name: "motor-winding" (no phase
933/// resistance and inductance: Siemens prints them for the 1FK7 and 1FT7 only), "motor-thermal-time" (no thermal time
934/// constant), "motor-pole-pairs" (none printed), "drive-max-current" (the maker prints no peak current, the motor's
935/// stands for it), "drive-base-load" (no base load current: `S210_BASE_LOAD_SHARE` of the rated one), and for another
936/// maker's motor "motor-standstill" or "motor-rated" where it prints no standstill or no rated values (the other ones
937/// stand for them, see `motor_data`). Empty: everything from the catalogue.
938pub fn estimated_data(article: &str, supply: &str, drive: &str) -> Vec<&'static str> {
939    let mut out = Vec::new();
940    if let Ok(m) = motor_data(article, supply) {
941        if m.winding.is_none() {
942            out.push("motor-winding");
943        }
944        if m.thermal_seconds.is_none() {
945            out.push("motor-thermal-time");
946        }
947        if m.pole_pairs.is_none() {
948            out.push("motor-pole-pairs");
949        }
950    }
951    if let Some((vendor, line)) = vendor_supply(supply)
952        && let Some(m) = vendor_rows("motors_", vendor, line).into_iter().find(|r| r["part_number"] == article)
953    {
954        if number(&m, "static_torque_nm").is_none() || number(&m, "stall_current_a").is_none() {
955            out.push("motor-standstill");
956        }
957        if number(&m, "rated_torque_nm").is_none() || number(&m, "rated_current_a").is_none() {
958            out.push("motor-rated");
959        }
960    }
961    if !drive.is_empty() {
962        let s120 = rows(table("siemens/motor_modules_s120.csv")).into_iter().any(|r| r["part_number"] == drive);
963        if !s120 {
964            out.push("drive-base-load");
965        }
966        if drives_for(supply).iter().any(|d| d.0 == drive && d.2.is_nan()) {
967            out.push("drive-max-current");
968        }
969    }
970    out
971}
972
973/// Puts a drive into a config: an S210 converter of `converters_s210.csv` or an S120 Motor Module of
974/// `motor_modules_s120.csv`, by article number. It sets the drive's rated and maximum output current as
975/// `ratings.drive_rated_current_a` and `drive_max_current_a`, where the config has them; `verdicts` judges the
976/// cycle's RMS and peak motor current against them (checks `drive-current`, `drive-peak-current`). The currents of
977/// a Double Motor Module are per axis. With effects.drive_current_limit the maximum current also limits the simulated
978/// current (`DriveParams::torque_range`): a cycle that asks more of the drive lags behind and fails the check.
979///
980/// The DC link, where the config has these ratings. An S210 converter (`braking_s210.csv`, from its operating
981/// instructions) sets `dc_link_overvoltage_v` to its trip level (410 V on 1 AC, 820 V on 3 AC) and the powers of its
982/// internal braking resistor, `braking_resistor_continuous_w` and `_peak_w`; not on the `supply` "230v" for a 3 AC
983/// converter, where Siemens requires an external resistor and the config's own values stand for it. Siemens publishes
984/// no switch-on threshold of the braking chopper, so `braking_threshold_v` stays the config's estimate; only where that
985/// is at or above the trip level (a config for a 400 V bus scaled to a 230 V converter's 325 V) it is taken halfway
986/// between the highest line peak the converter is rated for (240 or 480 V + 10 %, times the square root of 2) and the
987/// trip level. Nor does Siemens publish the S210's DC link capacitance, which stays as the config has it unless
988/// `dc_link_measured.csv` has one measured on a real drive of that article. An S120 Motor Module sets
989/// `dc_link_capacitance_uf` from `motor_modules_s120.csv`, half of it per axis for a Double Motor Module. A Motor
990/// Module has no braking resistor of its own: on the S120 the line-up brakes through a Braking Module, so it sets the
991/// braking from the Braking Module row of `braking_s120.csv` (6SL3100-1AE31-0AB1 with its 6SL3100-1BE31-0AA0 resistor:
992/// 1.5 kW continuous, 100 kW peak, switching on at 770 V as `braking_threshold_v`) and `dc_link_overvoltage_v` to the
993/// Active Line Modules' trip at 820 V (`dc_link_trip_s120.csv`, from the booksize equipment manual), and switches
994/// `effects.shared_dc_link` on, where the config has it: the axes of a line-up share its DC link (an S210 converter
995/// switches it off, each has its own). Before 13 November 2026 an S120 drive was
996/// judged against the S210 converter's internal resistor the config had (100 W, 5.7 kW on the EXCT-30). And it sets
997/// `drive.braking_module`, so that `verdicts` judges the axes' braking power together against the one module (an S210
998/// clears it); until the eleventh review each axis was judged against the whole module.
999///
1000/// And `ratings.drive_base_load_current_a`, the current the drive falls back to when its thermal image trips
1001/// (effects.drive_overload): an S120 Motor Module's from `motor_modules_s120.csv`; for an S210 converter, whose base load
1002/// current Siemens does not publish, `S210_BASE_LOAD_SHARE` of its rated current [estimate].
1003///
1004/// The rated and the base load current are those of the drive's rated conditions, derated by `drive_derating` for the
1005/// installation conditions the config gives (`ratings.drive_ambient_c`, `drive_altitude_m`, `drive_pulse_frequency_hz`;
1006/// absent: the rated ones, and every figure as the catalogue has it). The maximum current is not derated. A drive
1007/// of another maker, whose rows state no derating, is refused when the config gives a condition.
1008pub fn apply_drive(cfg: &mut Config, article: &str, supply: &str) -> Result<(), ConfigError> {
1009    // An S210 brakes into a resistor of its own, the axes of an S120 line-up into its one Braking Module.
1010    let braking_module = |cfg: &mut Config, on: bool| {
1011        if cfg.get("drive.braking_module").is_ok() {
1012            cfg.set_text(&format!("drive.braking_module = {on}"))
1013        } else {
1014            Ok(())
1015        }
1016    };
1017    let shared_dc_link = |cfg: &mut Config, on: bool| {
1018        if cfg.get("effects.shared_dc_link").is_ok() {
1019            cfg.set_text(&format!("effects.shared_dc_link = {on}"))
1020        } else {
1021            Ok(())
1022        }
1023    };
1024    let vendor_drive = || {
1025        let all: Vec<Row> = vendor_tables("drives_").into_iter().flat_map(rows).collect();
1026        let line = vendor_supply(supply).map(|(_, line)| line);
1027        // The row at the supply's line voltage, else the drive's first.
1028        let of = all.iter().filter(|r| r["part_number"] == article);
1029        of.clone().find(|r| number(r, "line_voltage_v") == line).or(of.clone().next()).cloned()
1030    };
1031    let (rated, max, base) = if let Some(d) = vendor_drive() {
1032        braking_module(cfg, false)?;
1033        apply_vendor_dc_link(cfg, &d)?;
1034        // shortcut: the makers publish no base load current; the S210's share of the rated current stands in [estimate].
1035        let rated = number(&d, "rated_output_current_a");
1036        // Mitsubishi prints no peak current of its amplifiers; it pairs them for the motor's peak, which the motor put
1037        // into the config before the drive brings [estimate].
1038        let max = number(&d, "max_output_current_a").or_else(|| cfg.f64("motor.max_current_a").ok());
1039        (rated, max, rated.map(|r| S210_BASE_LOAD_SHARE * r))
1040    } else if let Some(c) = rows(table("siemens/converters_s210.csv")).into_iter().find(|r| r["part_number"] == article)
1041    {
1042        braking_module(cfg, false)?;
1043        // Every S210 converter has a DC link of its own.
1044        shared_dc_link(cfg, false)?;
1045        if let Some(b) = rows(table("siemens/braking_s210.csv")).into_iter().find(|r| r["part_number"] == article) {
1046            let trip = number(&b, "dc_link_overvoltage_v").ok_or_else(|| unknown("drive", article))?;
1047            let line = if b["line"] == "1ac" { 240.0 } else { 480.0 };
1048            set_if_present(cfg, "ratings.dc_link_overvoltage_v", trip)?;
1049            if cfg.f64("ratings.braking_threshold_v").is_ok_and(|threshold| threshold >= trip) {
1050                set(cfg, "ratings.braking_threshold_v", (1.1 * line * std::f64::consts::SQRT_2 + trip) / 2.0)?;
1051            }
1052            if !(b["line"] == "3ac" && supply == "230v") {
1053                let (continuous, peak) = number(&b, "continuous_braking_power_w")
1054                    .zip(number(&b, "peak_braking_power_w"))
1055                    .ok_or_else(|| unknown("drive", article))?;
1056                set_if_present(cfg, "ratings.braking_resistor_continuous_w", continuous)?;
1057                set_if_present(cfg, "ratings.braking_resistor_peak_w", peak)?;
1058            }
1059        }
1060        // Siemens publishes no base load current for the S210 (`S210_BASE_LOAD_SHARE`).
1061        let rated = number(&c, "rated_output_current_a");
1062        (rated, number(&c, "max_output_current_a"), rated.map(|r| S210_BASE_LOAD_SHARE * r))
1063    } else {
1064        let m = rows(table("siemens/motor_modules_s120.csv"))
1065            .into_iter()
1066            .find(|r| r["part_number"] == article)
1067            .ok_or_else(|| unknown("drive", article))?;
1068        if let Some(capacitance) = number(&m, "dc_link_capacitance_f").map(|f| in_unit(f, 1e6)) {
1069            set_if_present(
1070                cfg,
1071                "ratings.dc_link_capacitance_uf",
1072                if m["axes"] == "2" { capacitance / 2.0 } else { capacitance },
1073            )?;
1074        }
1075        let module = rows(table("siemens/braking_s120.csv"))
1076            .into_iter()
1077            .find(|r| r["kind"] == "braking_module")
1078            .ok_or_else(|| unknown("drive", article))?;
1079        let (continuous, peak, threshold) = (
1080            number(&module, "continuous_power_w"),
1081            number(&module, "peak_power_w"),
1082            number(&module, "activation_threshold_v"),
1083        );
1084        let ((continuous, peak), threshold) =
1085            continuous.zip(peak).zip(threshold).ok_or_else(|| unknown("drive", article))?;
1086        set_if_present(cfg, "ratings.braking_resistor_continuous_w", continuous)?;
1087        set_if_present(cfg, "ratings.braking_resistor_peak_w", peak)?;
1088        set_if_present(cfg, "ratings.braking_threshold_v", threshold)?;
1089        // The DC link's trip is the Active Line Module's (`dc_link_trip_s120.csv`); all of them trip at the same level.
1090        let trip = rows(table("siemens/dc_link_trip_s120.csv"))
1091            .iter()
1092            .filter_map(|r| number(r, "dc_link_overvoltage_v"))
1093            .reduce(f64::min)
1094            .ok_or_else(|| unknown("drive", article))?;
1095        set_if_present(cfg, "ratings.dc_link_overvoltage_v", trip)?;
1096        braking_module(cfg, true)?;
1097        // The axes of an S120 line-up share one DC link: what one brakes, another can draw.
1098        shared_dc_link(cfg, true)?;
1099        (
1100            number(&m, "rated_output_current_a"),
1101            number(&m, "max_output_current_a"),
1102            number(&m, "base_load_output_current_a"),
1103        )
1104    };
1105    if let Some(capacitance) = rows(table("siemens/dc_link_measured.csv"))
1106        .into_iter()
1107        .find(|r| r["part_number"] == article)
1108        .and_then(|r| number(&r, "dc_link_capacitance_f"))
1109        .map(|f| in_unit(f, 1e6))
1110    {
1111        set_if_present(cfg, "ratings.dc_link_capacitance_uf", capacitance)?;
1112    }
1113    let ((rated, max), base) = rated.zip(max).zip(base).ok_or_else(|| unknown("drive", article))?;
1114    // The maximum current stays as printed: Siemens does not say whether its derating reaches it (`drive_derating`).
1115    let factor = drive_derating(cfg, article)?;
1116    let (rated, base) = (rated * factor, base * factor);
1117    set_if_present(cfg, "ratings.drive_rated_current_a", rated)?;
1118    set_if_present(cfg, "ratings.drive_base_load_current_a", base)?;
1119    set_if_present(cfg, "ratings.drive_max_current_a", max)
1120}
1121
1122/// The keys of a drive's installation conditions in `[ratings]`: the ambient temperature of the drive itself (the
1123/// cabinet's air inlet, not the motor's), the installation altitude and the pulse frequency. A config that lacks one has
1124/// the drive at its rated condition (40 degC, 1000 m, the rated pulse frequency).
1125pub const DRIVE_CONDITION_KEYS: [&str; 3] =
1126    ["ratings.drive_ambient_c", "ratings.drive_altitude_m", "ratings.drive_pulse_frequency_hz"];
1127
1128/// The first installation condition (`DRIVE_CONDITION_KEYS`) a config gives though it names no catalogue drive in
1129/// `[parts]` or a motor's `[parts.<id>]`: its drive is hand-entered, the condition would derate nothing and the drive
1130/// would be judged at its rated condition. Read from the config as written: `resolve` empties the names.
1131pub fn condition_without_drive(cfg: &Config) -> Option<&'static str> {
1132    let named = |v: Option<&toml::Value>| v.and_then(|v| v.as_str()).is_some_and(|name| !name.is_empty());
1133    let parts = cfg.get("parts").ok().and_then(|p| p.as_table());
1134    let any = parts.is_some_and(|p| named(p.get("drive")) || p.values().any(|own| named(own.get("drive"))));
1135    DRIVE_CONDITION_KEYS.into_iter().find(|key| !any && cfg.get(key).is_ok())
1136}
1137
1138/// Linear interpolation through `points` (x, y), the value of the first or last point beyond them; 1 for no points.
1139fn interpolate(mut points: Vec<(f64, f64)>, x: f64) -> f64 {
1140    points.sort_by(|a, b| a.0.total_cmp(&b.0));
1141    let (Some(first), Some(last)) = (points.first().copied(), points.last().copied()) else { return 1.0 };
1142    if x <= first.0 {
1143        return first.1;
1144    }
1145    for pair in points.windows(2) {
1146        if x <= pair[1].0 {
1147            return pair[0].1 + (pair[1].1 - pair[0].1) * (x - pair[0].0) / (pair[1].0 - pair[0].0);
1148        }
1149    }
1150    last.1
1151}
1152
1153/// The y of the first of `points` (x, y) whose x is at least `x`, the last point's beyond them; 1 for no points.
1154fn up_to(mut points: Vec<(f64, f64)>, x: f64) -> f64 {
1155    points.sort_by(|a, b| a.0.total_cmp(&b.0));
1156    points.iter().find(|p| x <= p.0).or(points.last()).map_or(1.0, |p| p.1)
1157}
1158
1159/// The (x, y) points of one `quantity` of a derating table, x from the column `x`, y the output current factor.
1160fn derating_points(table_rows: &[Row], quantity: &str, x: &str) -> Vec<(f64, f64)> {
1161    table_rows
1162        .iter()
1163        .filter(|r| r["quantity"] == quantity)
1164        .filter_map(|r| number(r, x).zip(number(r, "output_current_factor")))
1165        .collect()
1166}
1167
1168fn first_x(points: &[(f64, f64)]) -> f64 {
1169    points.iter().map(|p| p.0).fold(f64::INFINITY, f64::min)
1170}
1171
1172fn last_x(points: &[(f64, f64)]) -> f64 {
1173    points.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max)
1174}
1175
1176/// The share of its rated output current a catalogue drive gives at the installation conditions of the config
1177/// (`DRIVE_CONDITION_KEYS`); 1 for a config that gives none, and for an article that is neither an S210 converter nor an
1178/// S120 Motor Module. A drive of another maker with a condition given is refused (`error-drive-derating-none`): its rows
1179/// state no derating, and silently ignoring the condition would judge it at rated conditions.
1180///
1181/// S210 (`derating_s210.csv`, operating instructions Table 12-9): the table of altitude against ambient temperature,
1182/// an altitude by the row "up to" the next table altitude, the ambient interpolated linearly between the columns (as
1183/// Siemens' rule trades 5 K for 10 % of the current), the pulse frequency fixed at 8 kHz. S120 booksize Motor Module
1184/// (`derating_s120.csv`): the factors of altitude (10 % per 1000 m above 1000 m), ambient temperature (2.67 % per K above
1185/// 40 degC) and pulse frequency (a curve by module group), multiplied. Siemens does not say how they combine; the product is
1186/// this simulator's assumption on the safe side. Of Siemens' two ways to trade altitude (reduce the current by 10 % per
1187/// 1000 m, or the ambient by 5 K per 1000 m) the current reduction is implemented, not both. Refused, naming the key
1188/// (`error-drive-derating-range`): above 4000 m, above the highest ambient (S210 50 degC, S120 55 degC), below 0 degC, an
1189/// S210 pulse frequency other than 8 kHz, an S120 one above 16 kHz or not above 0, and an ambient above 45 degC at 16 kHz.
1190pub fn drive_derating(cfg: &Config, article: &str) -> Result<f64, ConfigError> {
1191    let given = |key: &str| -> Result<Option<f64>, ConfigError> {
1192        if cfg.get(key).is_ok() { cfg.f64(key).map(Some) } else { Ok(None) }
1193    };
1194    let [ambient_key, altitude_key, pulse_key] = DRIVE_CONDITION_KEYS;
1195    let (ambient, altitude, pulse) = (given(ambient_key)?, given(altitude_key)?, given(pulse_key)?);
1196    let refused = |key: &str| ConfigError::Part("error-drive-derating-range", key.into());
1197    if ambient.is_some_and(|a| a < 0.0) {
1198        return Err(refused(ambient_key));
1199    }
1200    if rows(table("siemens/converters_s210.csv")).iter().any(|r| r["part_number"] == article) {
1201        let all = rows(table("siemens/derating_s210.csv"));
1202        let grid: Vec<(f64, f64, f64)> = all
1203            .iter()
1204            .filter(|r| r["quantity"] == "altitude_ambient")
1205            .filter_map(|r| {
1206                Some((number(r, "ambient_c")?, number(r, "altitude_m")?, number(r, "output_current_factor")?))
1207            })
1208            .collect();
1209        let mut ambients: Vec<f64> = grid.iter().map(|g| g.0).collect();
1210        ambients.sort_by(f64::total_cmp);
1211        ambients.dedup();
1212        // The factor by altitude at each ambient temperature of the table.
1213        let columns: Vec<(f64, Vec<(f64, f64)>)> =
1214            ambients.iter().map(|&t| (t, grid.iter().filter(|g| g.0 == t).map(|g| (g.1, g.2)).collect())).collect();
1215        let altitudes: Vec<(f64, f64)> = grid.iter().map(|g| (g.1, g.2)).collect();
1216        let fixed = derating_points(&all, "pulse_frequency", "pulse_frequency_hz").first().map_or(f64::NAN, |p| p.0);
1217        if altitude.is_some_and(|h| h > last_x(&altitudes)) {
1218            return Err(refused(altitude_key));
1219        }
1220        if ambient.is_some_and(|a| ambients.last().is_some_and(|top| a > *top)) {
1221            return Err(refused(ambient_key));
1222        }
1223        if pulse.is_some_and(|p| (p - fixed).abs() > 0.5) {
1224            return Err(refused(pulse_key));
1225        }
1226        let h = altitude.unwrap_or_else(|| first_x(&altitudes));
1227        // The rows are "up to 2000 m" and so on: an altitude takes the row of the next table altitude at or above it.
1228        let across: Vec<(f64, f64)> = columns.into_iter().map(|(t, points)| (t, up_to(points, h))).collect();
1229        return Ok(interpolate(across.clone(), ambient.unwrap_or_else(|| first_x(&across))));
1230    }
1231    if let Some(module) = rows(table("siemens/motor_modules_s120.csv")).iter().find(|r| r["part_number"] == article) {
1232        let all = rows(table("siemens/derating_s120.csv"));
1233        // A module with curve rows of its own (the 200 A one) uses those alone, every other the rows without a part.
1234        let own: Vec<Row> = all.iter().filter(|r| r["part_number"] == module["part_number"]).copied().collect();
1235        let group: Vec<Row> =
1236            if own.is_empty() { all.iter().filter(|r| r["part_number"].is_empty()).copied().collect() } else { own };
1237        let altitudes = derating_points(&all, "altitude", "altitude_m");
1238        let ambients = derating_points(&all, "ambient", "ambient_c");
1239        let pulses = derating_points(&group, "pulse_frequency", "pulse_frequency_hz");
1240        if altitude.is_some_and(|h| h > last_x(&altitudes)) {
1241            return Err(refused(altitude_key));
1242        }
1243        if ambient.is_some_and(|a| a > last_x(&ambients)) {
1244            return Err(refused(ambient_key));
1245        }
1246        if pulse.is_some_and(|p| p <= 0.0 || p > last_x(&pulses)) {
1247            return Err(refused(pulse_key));
1248        }
1249        // At the highest pulse frequency the ambient is limited (the limit row's pulse frequency and ambient).
1250        for limit in all.iter().filter(|r| r["quantity"] == "ambient_limit") {
1251            if let (Some(p), Some(a), Some(at), Some(most)) =
1252                (pulse, ambient, number(limit, "pulse_frequency_hz"), number(limit, "ambient_c"))
1253                && p >= at
1254                && a > most
1255            {
1256                return Err(refused(ambient_key));
1257            }
1258        }
1259        let (h, a, p) = (
1260            altitude.unwrap_or_else(|| first_x(&altitudes)),
1261            ambient.unwrap_or_else(|| first_x(&ambients)),
1262            pulse.unwrap_or_else(|| first_x(&pulses)),
1263        );
1264        return Ok(interpolate(altitudes, h) * interpolate(ambients, a) * interpolate(pulses, p));
1265    }
1266    match DRIVE_CONDITION_KEYS.iter().find(|key| cfg.get(key).is_ok()) {
1267        Some(key) => Err(ConfigError::Part("error-drive-derating-none", (*key).into())),
1268        None => Ok(1.0),
1269    }
1270}
1271
1272/// `estimated_data`'s "drive-derating": the drive's rated and base load current are derated by installation conditions
1273/// that are not the rated ones. Siemens states the factors per condition, not how they combine (they are multiplied),
1274/// and not whether the maximum current is derated too (it is not).
1275pub fn estimated_derating(cfg: &Config, drive: &str) -> Vec<&'static str> {
1276    if drive_derating(cfg, drive).is_ok_and(|factor| factor != 1.0) { vec!["drive-derating"] } else { Vec::new() }
1277}
1278
1279/// The DC link of another maker's drive (`<vendor>/drives_*.csv`), each value only where the row gives it and the config
1280/// has the rating: capacitance, the internal braking resistor's continuous and peak power, the chopper's switch-on
1281/// voltage and the trip level. A row with the resistor's ohms and the switch-on voltage but no peak power gets the
1282/// power the resistor takes at that voltage, U² / R. Where the trip level is given and the config's switch-on voltage
1283/// lies at or above it, the switch-on voltage is taken halfway between the line's peak + 10 % and the trip, as for the
1284/// S210.
1285fn apply_vendor_dc_link(cfg: &mut Config, d: &Row) -> Result<(), ConfigError> {
1286    if let Some(capacitance) = number(d, "dc_link_capacitance_f").map(|f| in_unit(f, 1e6)) {
1287        set_if_present(cfg, "ratings.dc_link_capacitance_uf", capacitance)?;
1288    }
1289    let threshold = number(d, "braking_threshold_v");
1290    let peak = number(d, "braking_resistor_peak_w")
1291        .or_else(|| threshold.zip(number(d, "braking_resistor_internal_ohm")).map(|(u, r)| u * u / r));
1292    for (rating, value) in [
1293        ("braking_resistor_continuous_w", number(d, "braking_resistor_continuous_w")),
1294        ("braking_resistor_peak_w", peak),
1295        ("dc_link_overvoltage_v", number(d, "dc_link_overvoltage_v")),
1296        ("braking_threshold_v", threshold),
1297    ] {
1298        if let Some(value) = value {
1299            set_if_present(cfg, &format!("ratings.{rating}"), value)?;
1300        }
1301    }
1302    if let (None, Some(trip), Some(line)) = (threshold, number(d, "dc_link_overvoltage_v"), number(d, "line_voltage_v"))
1303        && cfg.f64("ratings.braking_threshold_v").is_ok_and(|own| own >= trip)
1304    {
1305        set(cfg, "ratings.braking_threshold_v", (1.1 * line * std::f64::consts::SQRT_2 + trip) / 2.0)?;
1306    }
1307    Ok(())
1308}
1309
1310/// Mass of a gearbox by name (`apply_gearbox`): a Siemens one's from the 01/2023 configuration manual
1311/// (`gearbox_mass.csv`), another maker's from its own row; `None` for a name the catalogue does not have or a gearbox
1312/// whose mass it has not.
1313pub fn gearbox_mass(name: &str) -> Option<f64> {
1314    let base = name.strip_suffix("-r").unwrap_or(name);
1315    let parts: Vec<&str> = base.split('-').collect();
1316    let row = rows(table("siemens/gearbox_mass.csv")).into_iter().find(|r| {
1317        parts.len() == 3
1318            && r["size"] == parts[0]
1319            && r["motor_frames"].split(' ').any(|f| f == parts[1])
1320            && r["ratio"] == parts[2]
1321    });
1322    row.and_then(|r| number(&r, "mass_kg")).or_else(|| mechanics::own_mass(base))
1323}
1324
1325/// Efficiency of a Harmonic Drive strain wave gear row without an `efficiency` value [estimate]: the maker prints it as
1326/// charts only (rated torque, 2000 r/min input, grease); a row whose table has the value read from them uses that, 0.70
1327/// stands for the rest. It is below what such charts show for the CSF/CSG/SHG ratios (about 0.65 at ratio 30 to 0.85 at
1328/// 160, from memory, not verified) so a motor sized with it errs on the safe side.
1329const STRAIN_WAVE_EFFICIENCY: f64 = 0.70;
1330
1331/// The efficiency a gearbox row prints: at full load (`efficiency_full_load`), or a strain wave gear's read from the
1332/// maker's charts (`efficiency`).
1333fn printed_efficiency(row: &Row) -> Option<f64> {
1334    number(row, "efficiency_full_load").or_else(|| number(row, "efficiency"))
1335}
1336
1337fn strain_wave(row: &Row) -> bool {
1338    matches!(row["series"], "CSF" | "CSG" | "SHG")
1339}
1340
1341/// What a gearbox of the catalogue leaves to estimates, by name (see `estimated_data`): "gearbox-efficiency" (a strain wave
1342/// gear: `STRAIN_WAVE_EFFICIENCY`) and "gearbox-mass" (no mass printed; the search ranks by the motor's alone).
1343pub fn estimated_gearbox_data(name: &str) -> Vec<&'static str> {
1344    let mut out = Vec::new();
1345    if let Some((g, _)) = mechanics::find_gearbox(name)
1346        && printed_efficiency(&g.row).is_none()
1347        && strain_wave(&g.row)
1348    {
1349        out.push("gearbox-efficiency");
1350    }
1351    if gearbox_mass(name).is_none() {
1352        out.push("gearbox-mass");
1353    }
1354    out
1355}
1356
1357/// Puts a gearbox of the catalogue into a config. The name is size, motor frame (for the gearboxes fitted through an
1358/// adapter plate the clamping hub's bore in mm) and ratio, e.g. "NRK070-04-5" or "SP+100MF-19-20", with "-r" after it
1359/// for the maker's reduced backlash ("SP100-05-20-r"). Sets ratio, efficiency, torsional stiffness, backlash and the
1360/// gearbox's own inertia, and sets the torque ratings where the config has them. Where the row has them and the config
1361/// the keys: the torque the efficiency holds at (the rated torque: makers give the efficiency at full load), the
1362/// no-load running torque and its speed, and the stiffness curve (a strain wave gear's K1 to K3 with its knees T1 and
1363/// T2 and its hysteresis; a gearbox without one is linear, both knees at its rated torque and K2 = K3 = its stiffness,
1364/// as `docs/config-reference.md` says for a planetary gearbox).
1365pub fn apply_gearbox(cfg: &mut Config, name: &str) -> Result<(), ConfigError> {
1366    let (gearbox, reduced) = mechanics::find_gearbox(name).ok_or_else(|| unknown("gearbox", name))?;
1367    // A peak the old gearbox's cap held may rise to the motor's own; one the config set lower stays its own.
1368    let held_by_cap = cfg.f64("drive.peak_torque_nm").is_ok_and(|peak| peak >= pulley_allowed(cfg) * (1.0 - 1e-12));
1369    let get = |column: &str| number(&gearbox.row, column);
1370    let need = |column: &str| get(column).ok_or_else(|| unknown("gearbox", name));
1371    let curve = get("stiffness_k1_nm_rad").zip(get("stiffness_k2_nm_rad")).zip(get("stiffness_k3_nm_rad"));
1372    let curve = curve.zip(get("stiffness_t1_nm")).zip(get("stiffness_t2_nm"));
1373    set(cfg, "gearbox.ratio", need("ratio")?)?;
1374    if let Some(efficiency) = printed_efficiency(&gearbox.row) {
1375        set(cfg, "gearbox.efficiency", efficiency)?;
1376    } else if strain_wave(&gearbox.row) {
1377        set(cfg, "gearbox.efficiency", STRAIN_WAVE_EFFICIENCY)?;
1378    }
1379    let stiffness = match curve {
1380        Some(((((k1, _), _), _), _)) => k1,
1381        None => need("torsional_stiffness_nm_rad")?,
1382    };
1383    set(cfg, "gearbox.stiffness_nm_rad", stiffness)?;
1384    // The manual leaves backlash and inertia open for a few gearboxes; the config's values stay then.
1385    if reduced {
1386        set(cfg, "gearbox.backlash_rad", need("backlash_reduced_rad")?)?;
1387    } else if let Some(backlash) = get("backlash_rad") {
1388        set(cfg, "gearbox.backlash_rad", backlash)?;
1389    }
1390    // Kept apart from the rotor's: added into it, the next motor put into the config would wipe it out.
1391    if let Some(inertia) = get("inertia_at_input_kgm2") {
1392        set(cfg, "gearbox.inertia_at_input_kgm2", inertia)?;
1393    }
1394    for (rating, column) in
1395        [("gearbox_rated_torque_nm", "rated_output_torque_nm"), ("gearbox_max_torque_nm", "max_output_torque_nm")]
1396    {
1397        if cfg.f64(&format!("ratings.{rating}")).is_ok() {
1398            set(cfg, &format!("ratings.{rating}"), need(column)?)?;
1399        }
1400    }
1401    let rated = need("rated_output_torque_nm")?;
1402    set_if_present(cfg, "gearbox.efficiency_torque_nm", rated)?;
1403    if let (Some(torque), Some(speed)) = (get("no_load_torque_nm"), get("no_load_torque_speed_rad_s")) {
1404        set_if_present(cfg, "gearbox.no_load_torque_nm", torque)?;
1405        set_if_present(cfg, "gearbox.no_load_speed_rpm", in_unit(speed, 30.0 / PI))?;
1406    }
1407    let (t1, t2, k2, k3) = match curve {
1408        Some(((((_, k2), k3), t1), t2)) => (t1, t2, k2, k3),
1409        None => (rated, rated, stiffness, stiffness),
1410    };
1411    for (key, value) in
1412        [("stiffness_t1_nm", t1), ("stiffness_t2_nm", t2), ("stiffness_k2_nm_rad", k2), ("stiffness_k3_nm_rad", k3)]
1413    {
1414        set_if_present(cfg, &format!("gearbox.{key}"), value)?;
1415    }
1416    if let Some(hysteresis) = get("hysteresis_rad") {
1417        set_if_present(cfg, "gearbox.hysteresis_rad", hysteresis)?;
1418    }
1419    // The motor's own peak is what its max current gives at the torque constant at max current (`apply_motor` sets both);
1420    // a peak the old cap held may rise to it; any other peak is the config's own and is only lowered, never raised.
1421    if cfg.f64("ratings.pulley_max_torque_nm").is_ok()
1422        && let (Ok(peak), Ok(current), Ok(constant)) = (
1423            cfg.f64("drive.peak_torque_nm"),
1424            cfg.f64("motor.max_current_a"),
1425            cfg.f64("motor.torque_constant_at_max_current_nm_a"),
1426        )
1427    {
1428        cap_peak_torque(cfg, if held_by_cap { peak.max(current * constant) } else { peak })?;
1429    }
1430    Ok(())
1431}
1432
1433/// A belt's values at a width, from the rows of its profile in `belts.csv`: linear between the standard widths,
1434/// in proportion to the width below the narrowest and above the widest (the cords and the mass go with the width).
1435/// Width in m; (pitch m, mass kg/m, allowable pull N, EA N)
1436fn belt_values(profile: &str, width: f64) -> Option<(f64, f64, f64, f64)> {
1437    let all = rows(table("megadyne/belts.csv"));
1438    let of: Vec<&Row> = all.iter().filter(|r| r["profile"] == profile).collect();
1439    let point = |r: &Row| -> Option<(f64, [f64; 3])> {
1440        let pull = number(r, "max_pull_n")?;
1441        Some((number(r, "width_m")?, [number(r, "mass_kg_m")?, pull, pull / number(r, "elongation_at_max_pull")?]))
1442    };
1443    let points: Vec<(f64, [f64; 3])> = of.iter().map(|r| point(r)).collect::<Option<_>>()?;
1444    let (first, last) = (points.first()?, points.last()?);
1445    let at = |k: usize| -> f64 {
1446        if width <= first.0 {
1447            return first.1[k] * width / first.0;
1448        }
1449        if width >= last.0 {
1450            return last.1[k] * width / last.0;
1451        }
1452        let i = points.iter().position(|p| p.0 >= width).unwrap_or(points.len() - 1);
1453        let (a, b) = (points[i - 1], points[i]);
1454        a.1[k] + (b.1[k] - a.1[k]) * (width - a.0) / (b.0 - a.0)
1455    };
1456    Some((number(of[0], "pitch_m")?, at(0), at(1), at(2)))
1457}
1458
1459/// Puts a belt into a config by profile and width in mm, e.g. "AT5-25": an open-ended Megadyne MEGALINEAR belt
1460/// with standard steel cords (`belts.csv`), profiles T5, AT3, AT5, AT10, MTD3, MTD5, MTD8 (MTD: HTD-compatible).
1461/// Sets the belt's EA (allowable pull over the stretch at it), mass per metre and tooth pitch, and, where the
1462/// config has them, the allowable belt tension (the allowable pull, a quarter of the breaking strength), the
1463/// width and the tooth load table of `ratings`. A width between the standard ones is interpolated (`belt_values`).
1464pub fn apply_belt(cfg: &mut Config, name: &str) -> Result<(), ConfigError> {
1465    let (profile, width) = name.rsplit_once('-').ok_or_else(|| unknown("belt", name))?;
1466    let width: f64 =
1467        width.parse().ok().filter(|w: &f64| *w > 0.0 && w.is_finite()).ok_or_else(|| unknown("belt", name))?;
1468    apply_belt_at(cfg, profile, width / 1000.0).ok_or_else(|| unknown("belt", name))?
1469}
1470
1471/// `apply_belt` for a width in m; `None` for a profile the catalogue does not have.
1472fn apply_belt_at(cfg: &mut Config, profile: &str, width: f64) -> Option<Result<(), ConfigError>> {
1473    let (pitch, mass, pull, ea) = belt_values(profile, width)?;
1474    let teeth: Vec<(f64, f64)> = rows(table("megadyne/belt_tooth_load.csv"))
1475        .iter()
1476        .filter(|r| r["profile"] == profile)
1477        .filter_map(|r| {
1478            number(r, "speed_rad_s")
1479                .map(|w| in_unit(w, 30.0 / PI))
1480                .zip(number(r, "specific_tooth_load_n_m").map(|n| in_unit(n, 1e-2)))
1481        })
1482        .collect();
1483    Some(set_belt(cfg, (pitch, mass, pull, ea), in_unit(width, 1e3), &teeth))
1484}
1485
1486/// Belt values into a config: (pitch m, mass kg/m, allowable pull N, EA N), width mm, tooth load (r/min, N/cm).
1487fn set_belt(
1488    cfg: &mut Config,
1489    (pitch, mass, pull, ea): (f64, f64, f64, f64),
1490    width_mm: f64,
1491    teeth: &[(f64, f64)],
1492) -> Result<(), ConfigError> {
1493    set(cfg, "belt.stiffness_ea_n", ea)?;
1494    set(cfg, "belt.mass_kg_m", mass)?;
1495    set(cfg, "belt.tooth_pitch_m", pitch)?;
1496    set_if_present(cfg, "ratings.belt_max_tension_n", pull)?;
1497    set_if_present(cfg, "ratings.belt_width_mm", width_mm)?;
1498    let list =
1499        |values: Vec<f64>| format!("[{}]", values.iter().map(|v| format!("{v:?}")).collect::<Vec<_>>().join(", "));
1500    if cfg.get("ratings.belt_tooth_load_rpm").is_ok() && cfg.get("ratings.belt_tooth_load_n_cm").is_ok() {
1501        cfg.set_text(&format!("ratings.belt_tooth_load_rpm = {}", list(teeth.iter().map(|t| t.0).collect())))?;
1502        cfg.set_text(&format!("ratings.belt_tooth_load_n_cm = {}", list(teeth.iter().map(|t| t.1).collect())))?;
1503    }
1504    Ok(())
1505}
1506
1507/// The kind of machine a config is for, told by its keys: an X/Z gantry has a Z stroke, a linear axis one stroke.
1508#[derive(Debug, Clone, Copy, PartialEq)]
1509enum Kind {
1510    XzGantry,
1511    Single,
1512}
1513
1514fn kind(cfg: &Config) -> Option<Kind> {
1515    if cfg.get("geometry.stroke_z_m").is_ok() && cfg.get("geometry.stroke_x_m").is_ok() {
1516        Some(Kind::XzGantry)
1517    } else if cfg.get("geometry.stroke_m").is_ok() {
1518        Some(Kind::Single)
1519    } else {
1520        None
1521    }
1522}
1523
1524/// The travel (m) a belt axis's slide load is screened for (`AxisData::slide_load_n`): the 5000 km Festo rates the
1525/// ELGA-TB-KF and EGC-TB-KF for. A row rated for another (`dynamic_load_distance_m`, the RF's 10000 km) is converted to
1526/// it by the cube law; a row without the column (Bahr, Rexroth) is taken as printed.
1527const BELT_AXIS_LOAD_DISTANCE_M: f64 = 5.0e6;
1528
1529/// The catalogue's figures of an axis by name, as `apply_axis` and the axis search use them.
1530#[derive(Debug, Clone)]
1531struct AxisData {
1532    kind: Kind,
1533    /// Stroke limits in m: horizontal (X, or the linear axis's) from and to, and for a gantry the Z strokes
1534    /// offered (Festo) or the longest (Bahr, as one entry).
1535    stroke_x: (f64, f64),
1536    strokes_z: Vec<f64>,
1537    /// Bahr: any Z stroke up to the longest; Festo: only the strokes listed.
1538    z_up_to: bool,
1539    pulley_radius: f64,
1540    /// Megadyne belt that gives the belt's mass, allowable pull and tooth load: profile and width in m. `None` for an
1541    /// axis whose maker names no profile Megadyne has (Festo EGC and ELGA: neoprene with glass cords); the config's belt
1542    /// stays then.
1543    belt: Option<(String, f64)>,
1544    /// EA where the maker states the belt's stretch (Festo), else the belt table's.
1545    ea: Option<f64>,
1546    teeth: f64,
1547    /// Highest torque at the pulley, N m.
1548    pulley_torque: f64,
1549    /// Rated payload in kg (Festo) or the slide's dynamic vertical load in N (Bahr).
1550    payload_kg: Option<f64>,
1551    slide_load_n: Option<f64>,
1552    max_speed: f64,
1553    max_acceleration: Option<f64>,
1554    /// Bahr gantries: moved masses in X and Z. Festo: per Z stroke the torque formula's constant and motor factor
1555    /// (for the carriage) and its gravity mass (the Z axis).
1556    moved: Option<(f64, f64)>,
1557    festo_formula: Vec<(f64, f64, f64, f64)>,
1558    /// Weight at zero stroke and per metre of X and of Z stroke, kg.
1559    weight: (f64, f64, f64),
1560}
1561
1562/// The axes of the catalogue by name: the Festo EXCT sizes ("EXCT-30"), the Bahr axes and X/Z gantries
1563/// ("ELZI-40", "ELZ-60S": series and size) and the other makers' single belt axes (`<maker>/belt_axes_*.csv`: Festo
1564/// "EGC-TB-KF-70", "ELGA-TB-G-80", Rexroth "CKR-110"). The Bahr XY gantries (no machine of that kind) and the DLZPVI (a
1565/// gear unit built in, whose ratio is not extracted) are left out.
1566pub fn axis_names() -> Vec<String> {
1567    let mut out = festo_sizes();
1568    out.extend(belt_axis_rows().iter().map(|(_, r)| format!("{}-{}", r["series"], r["size"])));
1569    out
1570}
1571
1572/// The standard belts of the catalogue as `apply_belt` takes them: profile and width in mm, "AT5-25", one per row of
1573/// `megadyne/belts.csv` (the Gates table is not read by name). Other widths are taken too, interpolated.
1574pub fn belt_names() -> Vec<String> {
1575    rows(table("megadyne/belts.csv"))
1576        .iter()
1577        .filter_map(|r| Some(format!("{}-{}", r["profile"], (number(r, "width_m")? * 1e9).round() / 1e6)))
1578        .collect()
1579}
1580
1581/// The rows of the belt axes other than the EXCT (`festo/belt_axes.csv`, with its torque formula): Bahr's, then the
1582/// other makers' `belt_axes_*.csv`, with the maker; without Bahr's XY gantries and DLZPVI (`axis_names`).
1583fn belt_axis_rows() -> Vec<(&'static str, Row)> {
1584    let mut names: Vec<&str> = TABLES
1585        .iter()
1586        .map(|(name, _)| *name)
1587        .filter(|name| name.split_once('/').is_some_and(|(_, file)| file.starts_with("belt_axes_")))
1588        .collect();
1589    names.insert(0, "bahr/belt_axes.csv");
1590    names
1591        .into_iter()
1592        .flat_map(|name| rows(table(name)).into_iter().map(move |r| (name.split('/').next().unwrap_or(""), r)))
1593        .filter(|(_, r)| r["kind"] != "xy_gantry" && r["series"] != "DLZPVI")
1594        .collect()
1595}
1596
1597/// The Festo sizes by name, in the order of their names.
1598fn festo_sizes() -> Vec<String> {
1599    let mut out: Vec<String> =
1600        rows(table("festo/belt_axes.csv")).iter().map(|r| format!("{}-{}", r["series"], r["size"])).collect();
1601    out.sort();
1602    out
1603}
1604
1605/// Whether a belt axis's stroke limit is its printed module length for want of the length that is not stroke
1606/// (`non_stroke_length_m`: Bahr's other series than the ELZ): the stroke is then overstated by the carriage; `estimated_data`'s
1607/// column names it "axis-stroke".
1608fn axis_stroke_is_module_length(name: &str) -> bool {
1609    belt_axis_rows().iter().any(|(_, r)| {
1610        format!("{}-{}", r["series"], r["size"]) == name
1611            && r["kind"] == "axis"
1612            && number(r, "max_length_one_piece_m").is_some()
1613            && number(r, "non_stroke_length_m").is_none()
1614    })
1615}
1616
1617fn axis_data(name: &str) -> Option<AxisData> {
1618    let festo = rows(table("festo/belt_axes.csv"));
1619    if let Some(f) = festo.iter().find(|r| format!("{}-{}", r["series"], r["size"]) == name) {
1620        let get = |column: &str| number(f, column);
1621        let festo_formula = rows(table("festo/belt_axis_torque_formula.csv"))
1622            .iter()
1623            .filter(|t| t["series"] == f["series"] && t["size"] == f["size"])
1624            .map(|t| {
1625                Some((
1626                    number(t, "stroke_z_m")?,
1627                    number(t, "constant_kg_m")?,
1628                    number(t, "motor_inertia_factor_1_m")?,
1629                    number(t, "gravity_mass_kg")?,
1630                ))
1631            })
1632            .collect::<Option<Vec<_>>>()?;
1633        let diameter = get("pulley_effective_diameter_m")?;
1634        let pitch = get("belt_pitch_m")?;
1635        return Some(AxisData {
1636            kind: Kind::XzGantry,
1637            stroke_x: (get("stroke_x_min_m")?, get("stroke_x_max_m")?),
1638            strokes_z: festo_formula.iter().map(|t| t.0).collect(),
1639            z_up_to: false,
1640            pulley_radius: diameter / 2.0,
1641            // The EXCT belt is steel-cord polyurethane; by its stretch of the AT class (see exct-30.toml).
1642            belt: Some((format!("AT{}", in_unit(pitch, 1e3)), get("belt_width_m")?)),
1643            ea: Some(get("belt_elongation_force_n")? / get("belt_elongation")?),
1644            teeth: (PI * diameter / pitch).round(),
1645            pulley_torque: get("max_pulley_torque_nm")?,
1646            payload_kg: get("rated_payload_kg"),
1647            slide_load_n: None,
1648            max_speed: get("max_speed_m_s")?,
1649            max_acceleration: get("max_acceleration_m_s2"),
1650            moved: None,
1651            festo_formula,
1652            weight: (get("mass_at_zero_stroke_kg")?, get("mass_per_stroke_kg_m")?, get("mass_per_stroke_z_kg_m")?),
1653        });
1654    }
1655    let all = belt_axis_rows();
1656    let (maker, r) = all.iter().find(|(_, r)| format!("{}-{}", r["series"], r["size"]) == name)?;
1657    let bahr = *maker == "bahr";
1658    let kind = if r["kind"] == "xz_gantry" { Kind::XzGantry } else { Kind::Single };
1659    let radius = number(r, "feed_per_rev_m")? / (2.0 * PI);
1660    let m = |column: &str| number(r, column);
1661    let (stroke_x, strokes_z) = match kind {
1662        Kind::XzGantry => (m("max_length_x_m")?, vec![m("max_length_z_m")?]),
1663        // The module length (Rexroth's Lmax, Bahr's "aus einem Stück") is stroke plus the length that is not stroke
1664        // (`non_stroke_length_m`: Rexroth carriage and adapter, Bahr's basic length); a row without it keeps the module
1665        // length and `estimated_axis_data` flags it.
1666        Kind::Single => (
1667            m("max_length_one_piece_m")
1668                .map(|length| length - m("non_stroke_length_m").unwrap_or(0.0))
1669                .or(m("stroke_x_max_m"))
1670                .unwrap_or(f64::INFINITY),
1671            Vec::new(),
1672        ),
1673    };
1674    let moved = match kind {
1675        Kind::XzGantry => Some((number(r, "moved_mass_x_kg")?, number(r, "moved_mass_z_kg")?)),
1676        Kind::Single => None,
1677    };
1678    Some(AxisData {
1679        kind,
1680        stroke_x: (if bahr { 0.0 } else { m("stroke_x_min_m").unwrap_or(0.0) }, stroke_x),
1681        strokes_z,
1682        z_up_to: true,
1683        pulley_radius: radius,
1684        // Bahr's belts are HTD (Megadyne's MTD); Rexroth names its AT profile; Festo's EGC and ELGA name none.
1685        belt: if bahr {
1686            Some((format!("MTD{}", in_unit(number(r, "belt_pitch_m")?, 1e3)), number(r, "belt_width_m")?))
1687        } else {
1688            r.get("belt").filter(|b| b.starts_with("AT")).map(|b| b.to_string()).zip(number(r, "belt_width_m"))
1689        },
1690        // The maker's stretch where it states one (ELGA: at the highest feed force).
1691        ea: number(r, "belt_elongation_force_n").zip(number(r, "belt_elongation")).map(|(f, e)| f / e),
1692        teeth: number(r, "pulley_teeth")?,
1693        // Bahr gives the peak feed force; Festo and Rexroth the torque at the pulley as well, which holds where given.
1694        pulley_torque: number(r, "max_pulley_torque_nm").unwrap_or(number(r, "feed_force_peak_n")? * radius),
1695        payload_kg: None,
1696        // On the 5000 km basis of Festo's KF guides: a load rated for another travel (RF: 10000 km) by the cube law of
1697        // Festo's own graph of the load comparison factor against the service life.
1698        slide_load_n: number(r, "fz_dynamic_n").map(|fz| {
1699            fz * number(r, "dynamic_load_distance_m").map_or(1.0, |d| (d / BELT_AXIS_LOAD_DISTANCE_M).cbrt())
1700        }),
1701        max_speed: number(r, "max_speed_m_s")?,
1702        max_acceleration: if bahr { None } else { number(r, "max_acceleration_m_s2") },
1703        moved,
1704        festo_formula: Vec::new(),
1705        weight: (
1706            number(r, "mass_at_zero_stroke_kg")?,
1707            number(r, "mass_per_stroke_kg_m")?,
1708            number(r, "mass_per_stroke_z_kg_m").unwrap_or(0.0),
1709        ),
1710    })
1711}
1712
1713/// The Z stroke an axis gives a config: its own where the axis allows it, for Festo the shortest stroke offered that
1714/// is at least the config's. `None` where the axis is too short.
1715fn z_stroke(axis: &AxisData, wanted: f64) -> Option<f64> {
1716    if axis.z_up_to {
1717        axis.strokes_z.first().is_some_and(|max| wanted <= *max + 1e-9).then_some(wanted)
1718    } else {
1719        axis.strokes_z.iter().copied().filter(|s| *s >= wanted - 1e-9).reduce(f64::min)
1720    }
1721}
1722
1723/// Why an axis cannot carry a config's machine by its catalogue numbers alone, "" where it can: the stroke is
1724/// longer than the axis has (`axis-stroke`), the payload above its rating (`axis-payload`; Festo's rated load, or
1725/// for Bahr the weight of the Z axis and payload against the slide's dynamic vertical load Fz), or an axis limit
1726/// of the config above its speed or acceleration (`axis-speed`). An axis for another kind of machine is `axis-kind`.
1727fn axis_refusal(cfg: &Config, axis: &AxisData) -> &'static str {
1728    let Some(kind) = kind(cfg) else { return "axis-kind" };
1729    if kind != axis.kind {
1730        return "axis-kind";
1731    }
1732    let x = cfg
1733        .f64(if kind == Kind::XzGantry { "geometry.stroke_x_m" } else { "geometry.stroke_m" })
1734        .unwrap_or(f64::INFINITY);
1735    let z_short =
1736        kind == Kind::XzGantry && cfg.f64("geometry.stroke_z_m").map_or(true, |z| z_stroke(axis, z).is_none());
1737    if x < axis.stroke_x.0 - 1e-9 || x > axis.stroke_x.1 + 1e-9 || z_short {
1738        return "axis-stroke";
1739    }
1740    let payload = cfg.f64("mass.payload_kg").unwrap_or(0.0);
1741    let on_slide = axis.moved.map_or(0.0, |(_, z)| z) + payload;
1742    if axis.payload_kg.is_some_and(|rated| payload > rated + 1e-9)
1743        || axis.slide_load_n.is_some_and(|fz| on_slide * 9.81 > fz)
1744    {
1745        return "axis-payload";
1746    }
1747    let limits =
1748        cfg.get("axis").ok().and_then(|a| a.as_table()).into_iter().flatten().filter_map(|(_, t)| t.as_table());
1749    for limit in limits {
1750        let get = |key: &str| limit.get(key).and_then(|v| v.as_float());
1751        if get("max_velocity_m_s").is_some_and(|v| v > axis.max_speed + 1e-9)
1752            || get("max_acceleration_m_s2").zip(axis.max_acceleration).is_some_and(|(a, max)| a > max + 1e-9)
1753        {
1754            return "axis-speed";
1755        }
1756    }
1757    ""
1758}
1759
1760/// Installed weight of an axis at a config's strokes, kg.
1761fn axis_weight(cfg: &Config, axis: &AxisData) -> f64 {
1762    let (zero, per_x, per_z) = axis.weight;
1763    match axis.kind {
1764        Kind::XzGantry => {
1765            let z = cfg.f64("geometry.stroke_z_m").ok().and_then(|z| z_stroke(axis, z)).unwrap_or(0.0);
1766            zero + per_x * cfg.f64("geometry.stroke_x_m").unwrap_or(0.0) + per_z * z
1767        }
1768        Kind::Single => zero + per_x * cfg.f64("geometry.stroke_m").unwrap_or(0.0),
1769    }
1770}
1771
1772/// Puts an axis of the catalogue into a config (`axis_names`): pulley radius, the belt (as `apply_belt` for the
1773/// Megadyne belt of its profile and width; EA from the maker's own stretch where it states one, Festo), the teeth in
1774/// mesh (half the pulley's), the torque the pulley allows (Festo's maximum torque; Bahr's peak feed force times the
1775/// radius) where the config rates it, and the moved masses. The config's strokes stay, except that an EXCT gets
1776/// the shortest Z stroke Festo offers that holds the config's. A stroke the axis does not have is refused, and so
1777/// is an axis for another kind of machine (an X/Z gantry axis on a config without a Z stroke).
1778///
1779/// Moved masses: Bahr's gantry sheets state them per axis (Z axis: the Z mass; carriage: the X mass less it). Bahr's
1780/// single axes state none, and the config's carriage stays. Festo states the mass its torque formula holds against
1781/// gravity (the Z axis) and the formula's constant, in which carriage, Z axis, pulleys and belt are lumped. With a
1782/// machine at hand (`entry`) the carriage is set so that the machine's own torque at 45 degrees (ax = az, a = 1 m/s²,
1783/// no payload, the gearbox taken out) is Festo's, as the hand-written `exct-30.toml` was; without one (a config only
1784/// read for its ratings) the carriage stays.
1785///
1786/// A mechanical axis (`mech_axes`): ball screws by part number and guide sets as "<part number>x<carriages>", joined by
1787/// "+" (e.g. "R25-20K4-FSC+HGH25CAx4"), as `mechanics::apply_mech_axis` puts them in.
1788pub fn apply_axis(cfg: &mut Config, name: &str, entry: Option<&MachineEntry>) -> Result<(), ConfigError> {
1789    let Some(axis) = axis_data(name) else {
1790        return mechanics::apply_mech_axis(cfg, name).unwrap_or_else(|| Err(unknown("axis", name)));
1791    };
1792    match axis_refusal(cfg, &axis) {
1793        "axis-kind" => return Err(ConfigError::Invalid("parts.axis".into())),
1794        "axis-stroke" => {
1795            return Err(ConfigError::Invalid(
1796                if axis.kind == Kind::XzGantry { "geometry.stroke_x_m" } else { "geometry.stroke_m" }.into(),
1797            ));
1798        }
1799        _ => {}
1800    }
1801    if let Some((profile, width)) = &axis.belt {
1802        apply_belt_at(cfg, profile, *width).ok_or_else(|| unknown("belt", profile))??;
1803    }
1804    if let Some(ea) = axis.ea {
1805        set(cfg, "belt.stiffness_ea_n", ea)?;
1806    }
1807    set(cfg, "geometry.pulley_radius_m", axis.pulley_radius)?;
1808    set_if_present(cfg, "ratings.belt_teeth_in_mesh", axis.teeth / 2.0)?;
1809    set_if_present(cfg, "ratings.pulley_max_torque_nm", axis.pulley_torque)?;
1810    if let Some((x, z)) = axis.moved {
1811        set(cfg, "mass.carriage_kg", x - z)?;
1812        set_if_present(cfg, "mass.z_axis_kg", z)?;
1813    }
1814    if axis.kind == Kind::XzGantry {
1815        let z = z_stroke(&axis, cfg.f64("geometry.stroke_z_m")?)
1816            .ok_or_else(|| ConfigError::Invalid("geometry.stroke_z_m".into()))?;
1817        set(cfg, "geometry.stroke_z_m", z)?;
1818        if let Some(&(_, constant, motor_factor, gravity_mass)) =
1819            axis.festo_formula.iter().find(|f| (f.0 - z).abs() < 1e-9)
1820        {
1821            set(cfg, "mass.z_axis_kg", gravity_mass)?;
1822            if let Some(entry) = entry {
1823                let carriage =
1824                    festo_carriage(entry, cfg, constant + motor_factor * cfg.positive("motor.rotor_inertia_kgm2")?)?;
1825                set(cfg, "mass.carriage_kg", carriage)?;
1826            }
1827        }
1828    }
1829    Ok(())
1830}
1831
1832/// The carriage mass at which the machine of `cfg` needs `target` N m per m/s² of acceleration at 45 degrees (both
1833/// axes a / sqrt(2)) on its busiest motor, payload off and the gearbox taken out: the torque is linear in the mass.
1834fn festo_carriage(entry: &MachineEntry, cfg: &Config, target: f64) -> Result<f64, ConfigError> {
1835    let mut probe = cfg.clone();
1836    for assignment in ["mass.payload_kg = 0.0", "gearbox.ratio = 1.0", "gearbox.inertia_at_input_kgm2 = 0.0"] {
1837        probe.set_text(assignment)?;
1838    }
1839    let torque = |carriage: f64| -> Result<f64, ConfigError> {
1840        let mut c = probe.clone();
1841        set(&mut c, "mass.carriage_kg", carriage)?;
1842        let machine = (entry.build)(&c)?;
1843        let pose = sim_core::testkit::mid_pose(machine.as_ref());
1844        let (axes, motors) = (machine.axes().len(), machine.motors().len());
1845        let (mut holding, mut moving) = (vec![0.0; motors], vec![0.0; motors]);
1846        machine.feedforward_torque(&pose, &vec![0.0; axes], &mut holding);
1847        machine.feedforward_torque(&pose, &vec![std::f64::consts::FRAC_1_SQRT_2; axes], &mut moving);
1848        Ok(moving.iter().zip(&holding).map(|(m, h)| (m - h).abs()).fold(0.0, f64::max))
1849    };
1850    let start = cfg.positive("mass.carriage_kg")?;
1851    let (at, slope) = (torque(start)?, torque(start + 1.0)? - torque(start)?);
1852    let carriage = start + (target - at) / slope;
1853    if carriage > 0.0 && carriage.is_finite() {
1854        Ok(carriage)
1855    } else {
1856        Err(ConfigError::Invalid("mass.carriage_kg".into()))
1857    }
1858}
1859
1860/// The parts a config names in `[parts]`, "" for none: motor and its supply, gearbox, drive, belt and axis.
1861#[derive(Debug, Clone, Copy, Default, PartialEq)]
1862pub struct Parts<'a> {
1863    pub motor: &'a str,
1864    pub supply: &'a str,
1865    pub gearbox: &'a str,
1866    pub drive: &'a str,
1867    pub belt: &'a str,
1868    pub axis: &'a str,
1869}
1870
1871/// The keys of `[parts]`, in the order of `Parts`.
1872pub const PART_KEYS: [&str; 6] = ["motor", "motor_supply", "gearbox", "drive", "belt", "axis"];
1873
1874impl<'a> Parts<'a> {
1875    /// What `[parts]` names; "" where it names nothing or has no such key. A name that is not text (`motor = 5`)
1876    /// is refused: taken as no name, the config would run with other parts than it says.
1877    pub fn of(cfg: &'a Config) -> Result<Self, ConfigError> {
1878        let part = |key: &str| -> Result<&'a str, ConfigError> {
1879            let path = format!("parts.{key}");
1880            cfg.get(&path).map_or(Ok(""), |v| v.as_str().ok_or(ConfigError::Type(path.clone())))
1881        };
1882        let supply = match part("motor_supply")? {
1883            "" => "400v",
1884            supply => supply,
1885        };
1886        Ok(Parts {
1887            motor: part("motor")?,
1888            supply,
1889            gearbox: part("gearbox")?,
1890            drive: part("drive")?,
1891            belt: part("belt")?,
1892            axis: part("axis")?,
1893        })
1894    }
1895
1896    /// Whether a named part changes what the machine moves, so that the velocity loop is retuned for it.
1897    fn moves(&self) -> bool {
1898        !(self.motor.is_empty() && self.gearbox.is_empty() && self.belt.is_empty() && self.axis.is_empty())
1899    }
1900}
1901
1902/// Puts the named parts into a config: the axis first (it sets the pulley rating the motor's peak torque is held
1903/// within), then the belt (it overrides the axis's), the gearbox (its ratio is in effect for the motor), the motor and
1904/// the drive. The names in `[parts]` are emptied, so that doing it again changes nothing.
1905fn apply_parts(cfg: &mut Config, parts: &Parts, entry: Option<&MachineEntry>) -> Result<(), ConfigError> {
1906    if !parts.axis.is_empty() {
1907        apply_axis(cfg, parts.axis, entry)?;
1908    }
1909    if !parts.belt.is_empty() {
1910        apply_belt(cfg, parts.belt)?;
1911    }
1912    if !parts.gearbox.is_empty() {
1913        apply_gearbox(cfg, parts.gearbox)?;
1914    }
1915    if !parts.motor.is_empty() {
1916        apply_motor(cfg, parts.motor, parts.supply)?;
1917    }
1918    if !parts.drive.is_empty() {
1919        apply_drive(cfg, parts.drive, parts.supply)?;
1920    }
1921    for key in ["motor", "gearbox", "drive", "belt", "axis"] {
1922        let _ = cfg.set_text(&format!("parts.{key} = \"\""));
1923    }
1924    Ok(())
1925}
1926
1927/// The config with the catalogue values of the parts it names, and nothing retuned: for the functions
1928/// that read ratings and limits from a config and have no machine to retune for. An EXCT named as axis keeps the
1929/// config's carriage here (see `apply_axis`).
1930pub(crate) fn parts_applied(cfg: &Config) -> Result<Config, ConfigError> {
1931    let mut out = cfg.clone();
1932    apply_parts(&mut out, &Parts::of(cfg)?, None)?;
1933    Ok(out)
1934}
1935
1936/// The tables a config may give one motor its own values in, as `[<table>.<motor id>]` (a machine file's motors
1937/// that differ: a smaller Z motor, another gearbox; an arm's smaller strain wave gear and lighter joint friction in its
1938/// wrist). See `motor_config`.
1939pub const PER_MOTOR_TABLES: [&str; 7] = ["parts", "motor", "gearbox", "drive", "ratings", "strain_wave", "joint"];
1940
1941/// The config one motor sees: each table of `PER_MOTOR_TABLES` with that motor's `[<table>.<id>]` over it, and the
1942/// motor, gearbox and drive its `[parts.<id>]` names applied from the catalogue over that. A key there has to be one
1943/// the shared table has (`motor.<id>.rotor_inertia_kgm2` overrides `motor.rotor_inertia_kgm2`). Without such tables
1944/// the config as it is. The drives, the machine files' drive trains and the per-motor verdicts read their motor's.
1945/// shortcut: the drives' cycle times, the noise seed and a shared DC link stay those of the shared `[drive]`. (The
1946/// velocity gain of a motor with parts of its own is retuned by `retuned_per_motor`.)
1947pub fn motor_config(cfg: &Config, id: &str) -> Result<Config, ConfigError> {
1948    let mut out = cfg.clone();
1949    let mut named = false;
1950    for table in PER_MOTOR_TABLES {
1951        let Some(own) = cfg.get(&format!("{table}.{id}")).ok().filter(|_| !id.is_empty()).and_then(|v| v.as_table())
1952        else {
1953            continue;
1954        };
1955        named |= table == "parts";
1956        for (key, value) in own {
1957            out.set(&format!("{table}.{key}"), value.clone())
1958                .map_err(|_| ConfigError::Invalid(format!("{table}.{id}.{key}")))?;
1959        }
1960    }
1961    if named {
1962        let parts = Parts::of(&out)?;
1963        if !parts.belt.is_empty() || !parts.axis.is_empty() {
1964            return Err(ConfigError::Invalid(format!("parts.{id} (belt and axis are the machine's, not a motor's)")));
1965        }
1966        let own = Parts {
1967            motor: parts.motor,
1968            supply: parts.supply,
1969            gearbox: parts.gearbox,
1970            drive: parts.drive,
1971            belt: "",
1972            axis: "",
1973        };
1974        let mut applied = out.clone();
1975        apply_parts(&mut applied, &own, None)?;
1976        out = applied;
1977    }
1978    Ok(out)
1979}
1980
1981/// The part `key` ("motor", "gearbox" or "drive") that motor `id` of an unresolved config has: the one its own
1982/// `[parts.<id>]` names; else none where it has values of its own for that part (`[motor.<id>]`, `[gearbox.<id>]`: not
1983/// a catalogue part); else `shared`.
1984fn part_of(cfg: &Config, id: &str, key: &str, shared: &str) -> String {
1985    let own = cfg.get(&format!("parts.{id}.{key}")).ok().and_then(|v| v.as_str()).filter(|n| !n.is_empty());
1986    let by_hand = key != "drive" && cfg.get(&format!("{key}.{id}")).is_ok_and(|v| v.is_table());
1987    match own.filter(|_| !id.is_empty()) {
1988        Some(own) => own.to_string(),
1989        None if by_hand && !id.is_empty() => String::new(),
1990        None => shared.to_string(),
1991    }
1992}
1993
1994/// The config with the catalogue values of the parts it names: `[parts]` with `motor = "<article>"`,
1995/// `motor_supply` (`SUPPLIES`), `gearbox = "<size-frame-ratio>"`, `drive = "<article>"`, `belt = "<profile-width>"`
1996/// and `axis = "<name>"`, "" for none. A named part overwrites the numbers the config has for it, and the velocity
1997/// gain is retuned for it (see `with_parts`). `Sim` does this with every config it is given, so every front end gets
1998/// it; the functions that read a config beside a `Sim` do it too.
1999pub fn resolve(entry: &MachineEntry, cfg: &Config) -> Result<Config, ConfigError> {
2000    with_named(entry, cfg, &Parts::of(cfg)?)
2001}
2002
2003/// One combination of parts tried on a machine's cycle: a motor with its drive, with or without a gearbox, on the
2004/// config's axis or one of the catalogue's.
2005#[derive(Debug, Clone, Default)]
2006pub struct Candidate {
2007    /// "" for an axis ruled out before any motor was tried on it.
2008    pub article: &'static str,
2009    /// The gearbox as `apply_gearbox` names it; "" where the config's own gearbox stayed.
2010    pub gearbox: String,
2011    /// The drive the catalogue pairs with the motor (`paired_drive`); "" where there is none, and the config's stayed.
2012    pub drive: &'static str,
2013    /// The supply the motor was tried at (`SUPPLIES`, which says the maker: `vendor_of`); "" for a refused axis.
2014    pub supply: &'static str,
2015    /// The axis of the catalogue the motor was tried on; "" for the config's own.
2016    pub axis: String,
2017    /// The one motor the candidate is for (`search_motor`, its id); "" for every motor that takes the shared one.
2018    pub motor: String,
2019    /// Motor and gearbox of one drive axis, kg.
2020    pub mass: f64,
2021    /// The stand-in for the price, which no catalogue file has: the installed weight of everything the combination
2022    /// names, kg. Motor and gearbox times the number of motors that take it (not those with a motor of their own,
2023    /// `[motor.<id>]` or `[parts.<id>]`; one for `search_motor`), and the axis at the config's strokes.
2024    pub cost: f64,
2025    /// The parts the combination buys, as the search's table spells them, with how many of each: every motor's motor,
2026    /// gearbox and drive (the candidate's where it takes the shared ones, its own `[parts.<id>]` where it has them;
2027    /// none where the config has hand-entered values), the axis and the belt; the parts a config keeps are named too.
2028    /// For one motor (`search_motor`) that motor's alone. Empty for an axis ruled out before any motor was tried.
2029    pub parts: Vec<(String, f64)>,
2030    /// The user's price for `parts` (`apply_prices`); `None` without a price list or where a part has no price in it.
2031    pub price: Option<f64>,
2032    /// The cycle and its verdicts; `None` where the cycle was not run, with the reason in `refused`. With a duty mix
2033    /// (`Options::duties`) the first duty's cycle and the verdicts of the mix (`search::mix_verdicts`).
2034    pub result: Option<(CycleLoad, Vec<Verdict>)>,
2035    pub refused: &'static str,
2036    /// With a duty mix: each duty's weight and cycle, in the order of `Options::duties`; empty for one cycle.
2037    pub duties: Vec<(f64, CycleLoad)>,
2038    /// The figures of the search's table (`search::Figures`), where the cycle ran.
2039    pub figures: Option<crate::search::Figures>,
2040}
2041
2042impl Candidate {
2043    pub fn passes(&self) -> bool {
2044        self.result.as_ref().is_some_and(|(_, verdicts)| verdicts.iter().all(|v| v.ok))
2045    }
2046
2047    /// The check closest to (or furthest beyond) its limit, with value over limit (`analysis::utilisation`: for a
2048    /// life limit over value). The belt's slack does not count while it passes. Two checks of the DC link do not count while they
2049    /// pass, because their ratio is no measure of how close the cycle is to failing: with a braking resistor
2050    /// behind them the capacitors fill to their limit by design, in every cycle that brakes hard enough, and
2051    /// the resistor's checks say what that costs; and the voltage is never below the bus, so its ratio to
2052    /// the trip level starts at 0.6 or so. Nor does the warm start's convergence while it passes: it says how
2053    /// well the run was measured, not how close a part is to its limit.
2054    ///
2055    /// A run whose drives tripped is infinitely far beyond: its figures end at the trip, where the DC link
2056    /// was just past its limit, and by that ratio it would rank as the nearest to passing. For one motor (`search_motor`,
2057    /// `motor`) only its own checks count, and those of the whole machine where they fail: the other motors' are the
2058    /// config's, and a check of the whole machine mostly theirs.
2059    pub fn tightest(&self) -> Option<(&'static str, f64)> {
2060        let (load, verdicts) = self.result.as_ref()?;
2061        if load.tripped {
2062            return Some(("dc-link-overvoltage", f64::INFINITY));
2063        }
2064        // A resistor of the axis, or one for all (an S120 line-up's Braking Module, judged once without a motor).
2065        let resistor = |v: &Verdict| {
2066            verdicts
2067                .iter()
2068                .any(|w| (w.motor == v.motor || w.motor.is_none()) && w.check.starts_with("braking-resistor"))
2069        };
2070        let by_design =
2071            |v: &Verdict| v.ok && (v.check == "dc-link-overvoltage" || v.check == "dc-link-energy" && resistor(v));
2072        // A limit of 0 gives no share while it passes ("collision" at `profile.min_clearance_m` 0); one that fails counts.
2073        verdicts
2074            .iter()
2075            .filter(|v| (v.limit > 0.0 || !v.ok) && !by_design(v))
2076            // Slack while it passes and the warm start's convergence while it passes say nothing of a limit; failing, they count.
2077            .filter(|v| {
2078                !v.ok || !["belt-least-tension", "thermal-warm-start", "thermal-cycle-repeat"].contains(&v.check)
2079            })
2080            // For one motor (`search_motor`): its own checks, and those of the whole machine where they fail.
2081            .filter(|v| {
2082                self.motor.is_empty()
2083                    || v.motor.map_or(!v.ok, |k| load.motors.get(k).is_some_and(|m| m.id == self.motor))
2084            })
2085            .map(|v| (v.check, crate::analysis::utilisation(v)))
2086            .max_by(|a, b| a.1.total_cmp(&b.1))
2087    }
2088}
2089
2090/// In proportion to the inertia the motors turn, rotors and load together: the torque the rigid machine
2091/// needs per unit of acceleration at the middle of its travel, summed over axes and motors, over the gear
2092/// ratio (a motor behind a higher ratio turns faster for the same axis acceleration).
2093fn inertia_seen(entry: &MachineEntry, cfg: &Config) -> Result<f64, ConfigError> {
2094    Ok(inertia_turned(entry, cfg)?.iter().sum())
2095}
2096
2097/// The motor's angle per unit of each axis's travel at the middle of the travel, `[axis][motor]`, from `Machine::inverse`:
2098/// a central difference of a step small against the travel, exact for a linear map, 1e-8 off for the rest.
2099fn motor_rates(machine: &dyn Machine, pose: &[f64]) -> Vec<Vec<f64>> {
2100    let angles = |pose: &[f64]| {
2101        let mut out = vec![0.0; machine.motors().len()];
2102        machine.inverse(pose, &mut out);
2103        out
2104    };
2105    (0..machine.axes().len())
2106        .map(|axis| {
2107            let step = 1e-6 * (machine.axes()[axis].max - machine.axes()[axis].min).abs().max(1e-3);
2108            let (mut ahead, mut behind) = (pose.to_vec(), pose.to_vec());
2109            ahead[axis] += step;
2110            behind[axis] -= step;
2111            angles(&ahead).iter().zip(angles(&behind)).map(|(a, b)| (a - b) / (2.0 * step)).collect()
2112        })
2113        .collect()
2114}
2115
2116/// Per motor, the inertia it turns (rotor, gearbox and load, summed over the axes that move it): the torque the rigid
2117/// machine needs per unit of an axis's acceleration over the motor's angle per unit of that axis's travel
2118/// (`motor_rates`), so a pulley radius, a screw lead or a rack's pinion count as well as the gear ratio.
2119fn inertia_turned(entry: &MachineEntry, cfg: &Config) -> Result<Vec<f64>, ConfigError> {
2120    let torques = torque_per_acceleration(entry, cfg)?;
2121    let machine = (entry.build)(cfg)?;
2122    let rates = motor_rates(machine.as_ref(), &sim_core::testkit::mid_pose(machine.as_ref()));
2123    Ok((0..machine.motors().len())
2124        .map(|k| torques.iter().zip(&rates).filter(|(_, r)| r[k].abs() > 1e-9).map(|(t, r)| (t[k] / r[k]).abs()).sum())
2125        .collect())
2126}
2127
2128/// The torque each motor of the rigid machine needs per unit of each axis's acceleration at the middle of its travel,
2129/// standing: `[axis][motor]`, gravity taken out.
2130pub(crate) fn torque_per_acceleration(entry: &MachineEntry, cfg: &Config) -> Result<Vec<Vec<f64>>, ConfigError> {
2131    let machine = (entry.build)(cfg)?;
2132    let pose = sim_core::testkit::mid_pose(machine.as_ref());
2133    let (axes, motors) = (machine.axes().len(), machine.motors().len());
2134    let (mut holding, mut moving) = (vec![0.0; motors], vec![0.0; motors]);
2135    machine.feedforward_torque(&pose, &vec![0.0; axes], &mut holding);
2136    let mut out = Vec::new();
2137    for axis in 0..axes {
2138        let mut acc = vec![0.0; axes];
2139        acc[axis] = 1.0;
2140        machine.feedforward_torque(&pose, &acc, &mut moving);
2141        out.push(moving.iter().zip(&holding).map(|(m, h)| m - h).collect());
2142    }
2143    Ok(out)
2144}
2145
2146/// The inertia ratio of each motor, load over motor, at the middle of the travel: the inertia the motor turns
2147/// besides its rotor (the load, and the gearbox's own inertia with it) over the rotor's inertia, where the rotor's is
2148/// that of the motor's own config (`motor_config`). Per axis the inertia the motor turns is the torque the rigid machine
2149/// needs per unit of that axis's acceleration (`torque_per_acceleration`) over the motor's acceleration it takes (from
2150/// `Machine::inverse`, standing: no speed, so no term of the speed squared); of the axes that move the motor the
2151/// largest. NaN for a motor no axis moves. Assumes the machine's feedforward has the rotors in, as every machine's has.
2152pub fn inertia_ratios(entry: &MachineEntry, cfg: &Config) -> Result<Vec<f64>, ConfigError> {
2153    let torques = torque_per_acceleration(entry, cfg)?;
2154    let machine = (entry.build)(cfg)?;
2155    let rates = motor_rates(machine.as_ref(), &sim_core::testkit::mid_pose(machine.as_ref()));
2156    let motors = machine.motors().to_vec();
2157    let mut out = Vec::new();
2158    for (k, motor) in motors.iter().enumerate() {
2159        let rotor = motor_config(cfg, motor.id)?.positive("motor.rotor_inertia_kgm2")?;
2160        let mut ratio = f64::NAN;
2161        for (torque, rate) in torques.iter().zip(&rates) {
2162            let rate = rate[k];
2163            if rate.abs() > 1e-9 {
2164                let load = torque[k] / rate - rotor;
2165                ratio = if ratio.is_nan() { load / rotor } else { ratio.max(load / rotor) };
2166            }
2167        }
2168        out.push(ratio);
2169    }
2170    Ok(out)
2171}
2172
2173/// The velocity gain of `before` scaled for the parts of `after` as `with_parts` says: by the square root of the ratio
2174/// of the inertia the motors turn (`inertia_seen`) times that of the rotor's (with the gearbox's), and on an elastic
2175/// machine bounded by `bounded_gain`; the position gain lowered where the cascade needs it (`cascade`, the largest
2176/// spread any motor needs, the keys being shared).
2177fn retuned(entry: &MachineEntry, before: &Config, after: &mut Config) -> Result<(), ConfigError> {
2178    let rotor = |cfg: &Config| {
2179        Ok::<f64, ConfigError>(
2180            cfg.positive("motor.rotor_inertia_kgm2")? + cfg.non_negative("gearbox.inertia_at_input_kgm2")?,
2181        )
2182    };
2183    let rotor_ratio = rotor(after)? / rotor(before)?;
2184    let total_ratio = inertia_seen(entry, after)? / inertia_seen(entry, before)?;
2185    let ratio = total_ratio * rotor(after)? / rotor(before)?;
2186    let old = before.positive("drive.velocity_kp_nm_s_rad")?;
2187    let machine = (entry.build)(after)?;
2188    let elastic = machine.resonance_hz(&sim_core::testkit::mid_pose(machine.as_ref())).is_some();
2189    // A linear motor's coil is the mover itself, joined to the load by no belt or gearbox: the loop sees the whole mass at
2190    // every frequency, so its crossover over that mass is the config's (the geometric mean with the coil's ratio made
2191    // the AL8021-0E's mover loop on the track oscillate, 1592 against 1056 that keeps the config's crossover).
2192    let gain = if is_linear_motor(after) {
2193        old * total_ratio
2194    } else {
2195        bounded_gain(old * ratio.sqrt(), old, rotor_ratio, elastic)
2196    };
2197    set(after, "drive.velocity_kp_nm_s_rad", gain)?;
2198    let (own, new) = (cascade_margins(entry, before)?, cascade_margins(entry, after)?);
2199    let spread = (0..own.len()).map(|k| cascade_spread(own[k], new[k])).fold(1.0, f64::max);
2200    for (key, value) in cascade(after, spread)? {
2201        set(after, key, value)?;
2202    }
2203    Ok(())
2204}
2205
2206/// The least position-cascade margin (`cascade_margins`) a retune leaves a motor [rule chosen from a sweep]: a quarter
2207/// above the edge of stability, or the config's own margin where that is smaller. Swept on 17 November 2026 on the
2208/// cases of `bounded_gain`'s comment (Kv alone lowered; Tn alone or both together settled worse at every floor): 1.0
2209/// left the EXCT-30 with the 1FK2104-5AF warm-start drifts of 0.3 to 2.1 K (not periodic) under Kp x0.9 and x1.1, frame
2210/// compliance or tool flex off; 1.5 took the ELZ-125 with its own motor, which passes at 1.07, to 0.175 mm settling
2211/// (limit 0.1 mm); 1.25 keeps it passing (0.077 mm) and the 1FK2104-5AF calm in every variation.
2212pub const CASCADE_MARGIN: f64 = 1.25;
2213
2214/// Per motor, the position cascade's margin from instability on a rigid inertia: ω (Tn + 1 / Kv), with ω = Kp / J the
2215/// velocity loop's crossover over the inertia the motor turns (`inertia_ratios`: rotor, gearbox and load of the axis
2216/// that gives the largest) and Tn, Kv, Kp the motor's own (`motor_config`). A P position loop (Kv) on a PI velocity
2217/// loop (Kp, Tn) on an inertia J, torque Kp (1 + 1/(Tn s)) (Kv e - s x) with e the position error, has the
2218/// characteristic polynomial s³ + ω s² + ω (1/Tn + Kv) s + ω Kv / Tn; by Routh it is stable while ω (1/Tn + Kv) >
2219/// Kv / Tn, that is while this margin exceeds 1. It assumes a rigid inertia (the belt's resonance and the drive's delays
2220/// left out: those `bounded_gain` holds) and takes the axis with the most inertia, so it errs low. NaN for a motor no
2221/// axis moves.
2222fn cascade_margins(entry: &MachineEntry, cfg: &Config) -> Result<Vec<f64>, ConfigError> {
2223    let ratios = inertia_ratios(entry, cfg)?;
2224    let machine = (entry.build)(cfg)?;
2225    let mut out = Vec::new();
2226    for (motor, ratio) in machine.motors().iter().zip(ratios) {
2227        let own = motor_config(cfg, motor.id)?;
2228        let inertia = own.positive("motor.rotor_inertia_kgm2")? * (1.0 + ratio);
2229        let (tn, kv) = (own.positive("drive.velocity_tn_s")?, own.positive("drive.kv_1_s")?);
2230        out.push(own.positive("drive.velocity_kp_nm_s_rad")? / inertia * (tn + 1.0 / kv));
2231    }
2232    Ok(out)
2233}
2234
2235/// The factor the retuned margin `new` has to grow by to reach its floor: `CASCADE_MARGIN`, or the config's own margin
2236/// `own` where that is smaller; 1 where it is there already (and for a motor no axis moves, NaN).
2237fn cascade_spread(own: f64, new: f64) -> f64 {
2238    let floor = own.min(CASCADE_MARGIN);
2239    if new < floor { floor / new } else { 1.0 }
2240}
2241
2242/// The position gain `drive.kv_1_s` that grows the cascade margin (`cascade_margins`) of `cfg` (the motor's config with
2243/// its retuned gain) by `spread`: 1 / ((Tn + 1/Kv) spread - Tn), Tn as it is. Lowering Kv alone settled best: the
2244/// integral, which holds the axis against friction in the dwell, keeps its speed. Empty for `spread` 1, so a part that
2245/// leaves the margin at its floor or above (the config's own motor among them) leaves the key as the config has it.
2246fn cascade(cfg: &Config, spread: f64) -> Result<Vec<(&'static str, f64)>, ConfigError> {
2247    if spread <= 1.0 {
2248        return Ok(Vec::new());
2249    }
2250    let (tn, kv) = (cfg.positive("drive.velocity_tn_s")?, cfg.positive("drive.kv_1_s")?);
2251    Ok(vec![("drive.kv_1_s", 1.0 / ((tn + 1.0 / kv) * spread - tn))])
2252}
2253
2254/// `retuned`'s gain `scaled` on a machine that reports a resonance (`elastic`): at most `old` times `rotor_ratio`, the
2255/// change of the rotor's inertia with the gearbox's, so that the speed loop's crossover over that inertia, Kp / J_M,
2256/// stays the config's own. On a rigid model the scaled gain stands (the loop sees the whole inertia at every frequency).
2257///
2258/// Above the drive train's resonance the belt or the arm no longer carries the load along and the loop sees the
2259/// rotor-side inertia alone; in every case swept the crossover lies above the first anti-resonance and its limit is
2260/// the drive's delays, not the mechanics. Swept on 16 November 2026 (sim-cli verdicts, margins, analyze with
2261/// `--set drive.velocity_kp_nm_s_rad`): the largest gain that passes every verdict with a phase margin of 45 degrees
2262/// (`velocity_loop_margins`) is Kp / J_M = 870 to 1550 rad/s in all of them, while the same gain is 1.0 to 12 times
2263/// the first resonance (`Machine::resonance_hz`, 20.5 to 160 Hz): no fixed fraction of the resonance fits, a fixed
2264/// crossover over the rotor-side inertia does (the shipped configs sit at 830 to 1330 rad/s).
2265///
2266/// ```text
2267/// case (J_M, J_total kg m2; resonance Hz)          max at 45 deg  best tracking*  before   this rule
2268/// one-axis belt drive (3.0e-5, 1.34e-4; 65.8)       0.036          0.07            0.025    0.025
2269///   pulley radius x0.5 / x2                        0.037 / 0.033  0.07 / 0.07     0.0166 / 0.025   same
2270///   gear ratio x0.5 / x2                           0.040 / 0.037  0.09 / 0.07     0.025 / 0.0162   same
2271///   Bahr ELZ-40 / ELZ-80 / ELZ-125 (r 16/31/48 mm) 0.037 / 0.026 / 0.03  0.07 / 0.055 / 0.037   0.0212 / 0.025 / 0.025   same
2272///   1FK2103-4AH (1.4e-5, 1.18e-4)                  0.019          0.045           0.016    0.0117
2273///   1FK2204-5AF (1.2e-4, 2.24e-4)                  0.127          0.2             0.025    0.0646
2274/// T-shaped gantry (3.0e-5, 1.28e-4; 20.5), own 0.04 0.047          0.08            -        -
2275///   1FK2204-5AF (1.2e-4, 2.18e-4)                  0.13           0.2             0.04     0.108
2276/// three-arm delta (2.4e-4, 3.9e-3; 43.0), own 0.25 0.31           0.6             -        -
2277/// * every verdict passes, any phase margin (the tracking error falls with the gain up to the edge of stability)
2278/// ```
2279///
2280/// The bound replaces a third of the resonance times J_M, which held every grown gain at the config's own (the
2281/// 1FK2204-5AF on the one-axis belt drive at 0.025, crossover 21 Hz below the anti-resonance), and lowers a lighter
2282/// rotor's gain where the geometric mean would raise its crossover (the 1FK2103-4AH from 0.016 to 0.0117, phase margin
2283/// 71 degrees). The ELZ-125 scaled to 0.0573 ran at 2.05 times the motor's peak; bounded it keeps 0.025 and passes.
2284///
2285/// Neither a lower bound nor more gain for a lighter rotor fits, swept on 17 November 2026 (sim-cli verdicts and
2286/// margins, kv 50 1/s, Tn 10 ms, the gains Kp / J_total in rad/s, failing / first passing):
2287///
2288/// ```text
2289/// case (inertia ratio; J_total kg m2)    fails at  passes at  phase margin 45 deg at Kp / J_M
2290/// ELZ-125, 1FK2103-4AH (48; 6.88e-4)    34.9      37.8 only  - (0.027 and above fail again)
2291/// ELZ-125, own motor (22; 7.04e-4)       28.4      35.5       1000
2292/// ELZ-125, 1FK2104-5AF (12; 7.30e-4)     37.0      41.1       - (40 degrees at most)
2293/// ELZ-80, 1FK2103-4AH (18; 2.60e-4)      30.8      38.4       1071
2294/// ELZ-80, 1FK2103-2AH (26; 2.55e-4)      39.2      47.0       1236
2295/// pulley x2, 1FK2103-4AH (29; 4.19e-4)   35.8      43.0       1393
2296/// one-axis belt drive, 1FK2103-4AH (7.4) -         -          1357
2297/// one-axis belt drive, 1FK2103-2AH (11)  -         -          1720
2298/// ```
2299///
2300/// A lower bound Kp >= 0.75 kv J_total (37.5 rad/s) took the ELZ-125 with its own motor from 0.025 (passes) to 0.0264,
2301/// which misses the settling check (0.111 mm against 0.1 mm), and still left the ELZ-125 with the 1FK2103-4AH (0.0258:
2302/// 0.145 mm), the pulley x2 with it (0.0157: 1.5 mm) and the gear ratio x0.5 with it (12 mm) failing. Below their
2303/// windows these motors run at their peak (motor-peak 1.02 to 1.10, drive current over its rating) and the axis drags
2304/// centimetres behind; their windows, where there are any, are a few hundredths of the gain wide and not monotonic
2305/// (the ELZ-125 with the 1FK2103-4AH passes at 0.026 and fails at 0.024 and 0.027): motors too small for this cycle,
2306/// which the verdicts report, not a gain a rule of inertias can find. More gain for a lighter
2307/// rotor (the bound old times the square root of `rotor_ratio`, 0.0171 for the 1FK2103-4AH) would take its phase
2308/// margin on the ELZ-80 to about 37 degrees (44.3 at 0.015, 31.0 at 0.018): the allowed Kp / J_M depends on the load as
2309/// well (1071 to 1720 for the same motor), which the inertias alone do not tell.
2310///
2311/// What those failing cases share is the position cascade: held to the rotor's crossover, a light rotor's Kp over the
2312/// whole inertia falls toward 1 / (Tn + 1/Kv), the edge where the P position loop on the PI velocity loop turns
2313/// unstable (`cascade_margins`). So `retuned` lowers Kv to keep that margin at `CASCADE_MARGIN` at least. Swept again on
2314/// 17 November 2026 (with gravity in the guides' commanded acceleration; margin before, Kv 50 -> after, verdicts):
2315///
2316/// ```text
2317/// case                                   margin  Kv     before                          after
2318/// one-axis belt drive, ELZ-125           1.07    39.7   pass (settling 0.097 mm)        pass (0.077 mm)
2319///   ELZ-125, 1FK2103-4AH                 0.51    15.7   oscillates, 3.1 N m RMS          calm 0.42 N m; settling 0.61 mm
2320///   ELZ-80, 1FK2103-2AH                  0.91    32.1   settling 2.85 mm, warm start    settling 0.16 mm
2321///   pulley x2, 1FK2103-4AH               0.84    28.7   settling 1.50 mm, warm start    settling 0.35 mm
2322/// EXCT-30, 1FK2104-5AF                   0.73    24.1   oscillates, 5.1 N m RMS          calm 1.21 N m; settling 0.15 mm
2323///   Kp x0.9 / x1.1                       0.66/0.80      5.6 N m / calm (warm start)      1.21 / 1.23 N m (x0.9: warm start 1.4 K)
2324///   frame compliance / tool flex / guide friction off   calm / 5.5 / 5.6 N m       1.22 / 1.21 / 1.11 N m
2325/// ```
2326///
2327/// Every other case of the tables above has a margin of 1.35 or more and keeps its Kv and its figures (the 1FK2204-6AF
2328/// on the EXCT-30 1.98, the pulley x2 1.73, the gear ratio x0.5 1.68). The velocity loop's margins (`velocity_loop_margins`)
2329/// move by at most 0.7 dB of gain margin, and the phase margins rise (ELZ-125 from 53.4 to 54.7, with the 1FK2103-4AH
2330/// from 68.7 to 80.5 degrees). The settling misses that stay are motors whose Kp, held
2331/// by the rotor, cannot both hold the cascade and settle within the dwell: what the verdicts are there to report.
2332fn bounded_gain(scaled: f64, old: f64, rotor_ratio: f64, elastic: bool) -> f64 {
2333    if elastic { scaled.min(old * rotor_ratio) } else { scaled }
2334}
2335
2336/// The config with a candidate's parts in it and the velocity loop retuned for them. Without this a
2337/// motor with a much lighter rotor fails by oscillating, not by being too small. `gearbox` "" keeps the
2338/// config's own; the drive, belt and axis the config names are put in as well.
2339///
2340/// The reference of the retuning is the config's own numbers, as they are before a part is put in:
2341/// `drive.velocity_kp_nm_s_rad` is taken to be tuned for the rotor, gearbox and masses the file states.
2342/// So a config that names a part states the gain for its own numbers, not for the part. Putting in
2343/// first one part and then another gives the gain of putting in both at once: the ratios multiply.
2344///
2345/// The gain is scaled with the geometric mean of two ratios: that of the inertia the motors turn, load
2346/// included (`inertia_seen`), and that of the rotor inertia alone (with the gearbox's, which turns with
2347/// it). Below the belt resonance the velocity loop moves rotor and load together, so the first ratio
2348/// keeps its speed; above the resonance the belt no longer carries the load along and the loop sees the
2349/// rotor alone, so the second ratio keeps its stability. The loop's crossover lies near the resonance,
2350/// where neither holds alone. Scaling with the total inertia only left a rotor a quarter as heavy or
2351/// lighter with several times too much gain above the resonance, and it oscillated; scaling with the
2352/// rotor only makes the loop needlessly slow. Where the retuned gain leaves the position cascade too close to its edge
2353/// (`cascade_margins` below `CASCADE_MARGIN` and below the config's own), `drive.kv_1_s` is lowered to keep it there;
2354/// `drive.velocity_tn_s` stays. On the EXCT-30 every 1FK2 runs calmly so.
2355pub fn with_parts(
2356    entry: &MachineEntry,
2357    cfg: &Config,
2358    article: &str,
2359    supply: &str,
2360    gearbox: &str,
2361) -> Result<Config, ConfigError> {
2362    let mut parts = Parts::of(cfg)?;
2363    (parts.motor, parts.supply) = (article, supply);
2364    if !gearbox.is_empty() {
2365        parts.gearbox = gearbox;
2366    }
2367    with_named(entry, cfg, &parts)
2368}
2369
2370/// The config with the parts of `parts` in it, retuned as `with_parts` says.
2371pub fn with_named(entry: &MachineEntry, cfg: &Config, parts: &Parts) -> Result<Config, ConfigError> {
2372    guide_carriages(cfg)?; // refused here, where every front end resolves its config, not only when a guide is searched
2373    let mut out = cfg.clone();
2374    apply_parts(&mut out, parts, Some(entry))?;
2375    if parts.moves() {
2376        retuned(entry, cfg, &mut out)?;
2377    }
2378    retuned_per_motor(entry, cfg, &mut out)?;
2379    Ok(out)
2380}
2381
2382/// The velocity gain of each motor that `[parts.<id>]` names parts for, written to `drive.<id>.velocity_kp_nm_s_rad`
2383/// as `retuned` does for the shared one (the square root of the ratio of the inertia that motor turns times that of its
2384/// rotor, `bounded_gain` on an elastic machine, a linear motor's by the whole mass), from the motor's gain in `cfg`
2385/// without its own parts, and its `drive.<id>.kv_1_s` where its cascade needs it (`cascade`). A gain the config gives
2386/// per motor stays.
2387fn retuned_per_motor(entry: &MachineEntry, cfg: &Config, out: &mut Config) -> Result<(), ConfigError> {
2388    let machine = (entry.build)(out)?;
2389    let ids: Vec<String> = machine.motors().iter().map(|m| m.id.to_string()).collect();
2390    let elastic = machine.resonance_hz(&sim_core::testkit::mid_pose(machine.as_ref())).is_some();
2391    for (index, id) in ids.iter().enumerate() {
2392        let named = !id.is_empty() && cfg.get(&format!("parts.{id}")).ok().is_some_and(|v| v.is_table());
2393        if !named || cfg.get(&format!("drive.{id}.velocity_kp_nm_s_rad")).is_ok() {
2394            continue;
2395        }
2396        // The config as the file states it: without this motor's own parts.
2397        let mut all = cfg.to_text()?.parse::<toml::Table>().map_err(|e| ConfigError::Parse(e.to_string()))?;
2398        if let Some(parts) = all.get_mut("parts").and_then(|p| p.as_table_mut()) {
2399            parts.remove(id.as_str());
2400        }
2401        let bare = Config::parse(&toml::to_string(&all).map_err(|e| ConfigError::Parse(e.to_string()))?)?;
2402        let rotor = |c: &Config| -> Result<f64, ConfigError> {
2403            let m = motor_config(c, id)?;
2404            Ok(m.positive("motor.rotor_inertia_kgm2")? + m.non_negative("gearbox.inertia_at_input_kgm2")?)
2405        };
2406        let (rotor_ratio, total_ratio) =
2407            (rotor(out)? / rotor(&bare)?, inertia_turned(entry, out)?[index] / inertia_turned(entry, &bare)?[index]);
2408        let old = motor_config(&bare, id)?.positive("drive.velocity_kp_nm_s_rad")?;
2409        let gain = if is_linear_motor(&motor_config(out, id)?) {
2410            old * total_ratio
2411        } else {
2412            bounded_gain(old * (total_ratio * rotor_ratio).sqrt(), old, rotor_ratio, elastic)
2413        };
2414        *out = with_own_keys(out, "drive", id, &[("velocity_kp_nm_s_rad", toml::Value::Float(gain))])?;
2415        *out = with_cascade(entry, &bare, out, index, id)?;
2416    }
2417    Ok(())
2418}
2419
2420/// `cfg` with `<table>.<id>.<key>` set for each pair, the motor's table made where the config has none.
2421fn with_own_keys(cfg: &Config, table: &str, id: &str, pairs: &[(&str, toml::Value)]) -> Result<Config, ConfigError> {
2422    let mut all = cfg.to_text()?.parse::<toml::Table>().map_err(|e| ConfigError::Parse(e.to_string()))?;
2423    let shared = all.entry(table).or_insert_with(|| toml::Value::Table(toml::Table::new()));
2424    let shared = shared.as_table_mut().ok_or_else(|| ConfigError::Type(table.into()))?;
2425    let mine = shared.entry(id).or_insert_with(|| toml::Value::Table(toml::Table::new()));
2426    let mine = mine.as_table_mut().ok_or_else(|| ConfigError::Type(format!("{table}.{id}")))?;
2427    for (key, value) in pairs {
2428        mine.insert(key.to_string(), value.clone());
2429    }
2430    Config::parse(&toml::to_string(&all).map_err(|e| ConfigError::Parse(e.to_string()))?)
2431}
2432
2433/// `out` with motor `index`'s (`id`) Kv lowered in its own `drive.<id>` table (`cascade`) so that its cascade margin is
2434/// at least its floor, `own` being the config before the motor's parts.
2435fn with_cascade(
2436    entry: &MachineEntry,
2437    own: &Config,
2438    out: &Config,
2439    index: usize,
2440    id: &str,
2441) -> Result<Config, ConfigError> {
2442    let spread = cascade_spread(cascade_margins(entry, own)?[index], cascade_margins(entry, out)?[index]);
2443    let keys: Vec<(&str, toml::Value)> = cascade(&motor_config(out, id)?, spread)?
2444        .into_iter()
2445        .map(|(key, value)| (key.trim_start_matches("drive."), toml::Value::Float(value)))
2446        .collect();
2447    if keys.is_empty() { Ok(out.clone()) } else { with_own_keys(out, "drive", id, &keys) }
2448}
2449
2450/// A config with one value changed that moves what the motors turn (`gearbox.ratio`, `geometry.pulley_radius_m`), the
2451/// velocity gain retuned for it as `with_parts` retunes it for a part. `cfg` has its parts in (`resolve`).
2452pub fn with_value(entry: &MachineEntry, cfg: &Config, path: &str, value: f64) -> Result<Config, ConfigError> {
2453    let mut out = cfg.clone();
2454    set(&mut out, path, value)?;
2455    retuned(entry, cfg, &mut out)?;
2456    Ok(out)
2457}
2458
2459/// The catalogue gearboxes that fit a motor, at every ratio, named as `apply_gearbox` takes them: the question the
2460/// search asks before it sweeps ratios. `series` picks makers and series: "" all of them, a maker ("wittenstein",
2461/// "neugart", "siemens"), a maker's table ("wittenstein-sp", "neugart-ple", "siemens-nrk", "harmonicdrive-csf"), or a
2462/// prefix of the size ("NRK", "NRK070"). Siemens' NRB, NRK and NLC fit the 1FK2 and 1FT2 of their frame (1FK2104 and
2463/// 1FK2204 have frame "04"), its SP+ the 1FT2 only, as Siemens sells them; another maker's gearbox fits a motor whose
2464/// shaft its clamping hub takes (`motor_shaft_diameter`; one hub per size and ratio, the smallest that does).
2465pub fn gearboxes_for_motor(article: &str, series: &str) -> Vec<String> {
2466    mechanics::fitting(article, series).into_iter().map(|(name, _)| name).collect()
2467}
2468
2469/// `gearboxes_for_motor` with a ratio between half and twice `ratio`.
2470pub fn fitting_gearboxes(article: &str, series: &str, ratio: f64) -> Vec<String> {
2471    let near = |n: f64| n >= 0.5 * ratio && n <= 2.0 * ratio;
2472    mechanics::fitting(article, series).into_iter().filter(|(_, n)| near(*n)).map(|(name, _)| name).collect()
2473}
2474
2475/// The axes of the catalogue a config's machine can be built from, each with why it is refused ("" where it is not)
2476/// by its catalogue numbers alone: the belt axes of its kind (`axis_names`, `axis_refusal`) and the mechanical axes
2477/// (`mech_axes`: ball screws, and guide sets where the config rates guides). The question the search asks before it
2478/// tries motors on them.
2479pub fn axes_for(cfg: &Config) -> Vec<(String, &'static str)> {
2480    let belts = axis_names().into_iter().filter_map(|name| {
2481        let reason = axis_refusal(cfg, &axis_data(&name)?);
2482        (reason != "axis-kind").then_some((name, reason))
2483    });
2484    belts.chain(mech_axes(cfg).into_iter().map(|(name, reason, _)| (name, reason))).collect()
2485}
2486
2487/// One combination to try: motor, gearbox ("" the config's), drive ("" the config's), axis name ("" the config's) and the
2488/// axis's weight.
2489#[derive(Debug, Clone, Default)]
2490struct Job {
2491    article: &'static str,
2492    gearbox: String,
2493    drive: &'static str,
2494    axis: String,
2495    axis_weight: f64,
2496    /// The id of the one motor the candidate is for (`search_motor`); "" for all of them.
2497    motor: String,
2498}
2499
2500/// What a search tries beside the motors (`search`): `gearboxes` a series to try with each motor (`fitting_gearboxes`),
2501/// `axes` every axis of the catalogue (`search_axes`), `motor` one motor of a machine with several (`search_motor`),
2502/// `drives` which drives with each motor (`Drives`), and `duties` the duty mix: each duty's config and weight (how many
2503/// of its cycles to one of weight 1), the first the config searched on; empty for that config alone. With a mix each
2504/// candidate runs every duty and is judged by `search::mix_verdicts`.
2505#[derive(Debug, Clone, Copy, Default)]
2506pub struct Options<'a> {
2507    pub gearboxes: Option<&'a str>,
2508    pub axes: bool,
2509    pub motor: Option<&'a str>,
2510    pub drives: Drives,
2511    pub duties: &'a [(Config, f64)],
2512}
2513
2514/// The gearbox ratio a series' gearboxes are picked around for a machine without one (ratio 1, a direct drive): the
2515/// classic optimum for a pure inertia, the square root of the load's inertia over the rotor's (`search::optimum_ratio`),
2516/// for the motor `article` and the busiest motor of the config. `None` where it cannot be told.
2517fn direct_drive_ratio(entry: &MachineEntry, cfg: &Config, article: &str, supply: &str) -> Option<f64> {
2518    let own = parts_applied(cfg).ok()?;
2519    let rotor = own.positive("motor.rotor_inertia_kgm2").ok()?;
2520    let load = inertia_ratios(entry, &own).ok()?.into_iter().filter(|r| r.is_finite()).reduce(f64::max)? * rotor;
2521    Some(crate::search::optimum_ratio(load, motor_data(article, supply).ok()?.rotor_kgm2))
2522}
2523
2524/// The motors a config's machine can take at a supply: a linear motor machine (`is_linear_motor`) the linear motors
2525/// of the supply (`linear_motor_articles_for`), every other the rotary ones (`motor_articles_for`).
2526fn articles_for(cfg: &Config, supply: &str) -> Vec<&'static str> {
2527    if is_linear_motor(cfg) { linear_motor_articles_for(supply) } else { motor_articles_for(supply) }
2528}
2529
2530/// The jobs of one config: every motor `wanted` takes at the supply, each with the drives `drives` picks and, with a
2531/// series, every fitting gearbox of it: around the config's ratio where the machine has a gearbox (ratio above 1), around
2532/// the classic optimum (`direct_drive_ratio`) where it is a direct drive, which is tried without a gearbox as well.
2533/// A linear motor's magnet track at the config's stroke counts into the axis's weight (`magnet_track_weight`).
2534#[allow(clippy::too_many_arguments)]
2535fn motor_jobs(
2536    entry: &MachineEntry,
2537    cfg: &Config,
2538    supply: &str,
2539    wanted: &dyn Fn(&str) -> bool,
2540    options: &Options,
2541    axis: &str,
2542    axis_weight: f64,
2543    motor: &str,
2544) -> Vec<Job> {
2545    let own = if motor.is_empty() { Ok(cfg.clone()) } else { motor_config(cfg, motor) };
2546    let ratio =
2547        own.and_then(|own| parts_applied(&own)).ok().and_then(|own| own.f64("gearbox.ratio").ok()).unwrap_or(1.0);
2548    let mut out = Vec::new();
2549    for article in articles_for(cfg, supply).into_iter().filter(|a| wanted(a)) {
2550        let axis_weight = axis_weight + magnet_track_weight(cfg, article, supply);
2551        let names = match options.gearboxes {
2552            // A motor no gearbox of the series fits is tried with the config's own (gearbox "").
2553            Some(series) if ratio > 1.0 => Some(fitting_gearboxes(article, series, ratio))
2554                .filter(|g| !g.is_empty())
2555                .unwrap_or_else(|| vec![String::new()]),
2556            // A direct drive: as it is, and with the gearboxes around the optimum.
2557            Some(series) if motor.is_empty() => std::iter::once(String::new())
2558                .chain(
2559                    direct_drive_ratio(entry, cfg, article, supply)
2560                        .map_or_else(Vec::new, |optimum| fitting_gearboxes(article, series, optimum)),
2561                )
2562                .collect(),
2563            _ => vec![String::new()],
2564        };
2565        for gearbox in names {
2566            for drive in drives_tried(article, supply, options.drives) {
2567                out.push(Job {
2568                    article,
2569                    gearbox: gearbox.clone(),
2570                    drive,
2571                    axis: axis.to_string(),
2572                    axis_weight,
2573                    motor: motor.to_string(),
2574                });
2575            }
2576        }
2577    }
2578    out
2579}
2580
2581/// Runs the jobs on all processors and ranks them: the passing ones first, cheapest first (`Candidate::cost`, then
2582/// `mass`), the others after them, nearest to passing first. A motor not offered at the supply is left out.
2583///
2584/// Every candidate is simulated: the axis limits are not a screen (`check_limits` takes every axis at its highest speed
2585/// and acceleration at once, which the cycle need not ask, and so ruled out motors that passed every verdict). What the
2586/// cycle asks of a motor is judged by the verdicts: "motor-peak" against its torque-speed curve, "motor-speed" against
2587/// its maximum speed. A candidate whose config or cycle cannot run is returned with `result` empty and why in `refused`.
2588fn run_jobs(
2589    entry: &MachineEntry,
2590    (cfg, duties): (&Config, &[(Config, f64)]),
2591    supply: &str,
2592    jobs: Vec<Job>,
2593    mut out: Vec<Candidate>,
2594) -> Vec<Candidate> {
2595    // As the analyses' batches: counted in the current job and stopped by its cancel.
2596    let found = crate::analysis::on_all_cores(jobs.len(), |i| try_job(entry, cfg, duties, supply, &jobs[i]));
2597    out.extend(found.into_iter().flatten());
2598    rank(&mut out);
2599    out
2600}
2601
2602/// The order of a search: passing first, by cost, then mass, then motor and gearbox (so that equal weights come
2603/// out the same every run); the rest by how far beyond their tightest check they are.
2604pub fn rank(found: &mut [Candidate]) {
2605    let key = |c: &Candidate| {
2606        (!c.passes(), if c.passes() { c.cost } else { c.tightest().map_or(f64::INFINITY, |t| t.1) }, c.mass)
2607    };
2608    found.sort_by(|a, b| {
2609        let (ka, kb) = (key(a), key(b));
2610        ka.0.cmp(&kb.0)
2611            .then(ka.1.total_cmp(&kb.1))
2612            .then(ka.2.total_cmp(&kb.2))
2613            .then(a.axis.cmp(&b.axis))
2614            .then(a.article.cmp(b.article))
2615            .then(a.gearbox.cmp(&b.gearbox))
2616            .then(a.drive.cmp(b.drive))
2617    });
2618}
2619
2620/// The user's prices by part number (`--prices`): a CSV `part_number,price` with the header, `#` notes and blank lines
2621/// passed over as the catalogue's tables are. The currency is the user's; the file carries none. No shipped table has
2622/// a price (`docs/catalogue.md`).
2623pub struct PriceList(HashMap<String, f64>);
2624
2625impl PriceList {
2626    /// Reads the text; on a fault the line (1-based), the message key and the argument it names (the part number or
2627    /// the field), for the front end to put in words.
2628    pub fn parse(text: &str) -> Result<Self, (usize, &'static str, String)> {
2629        let mut lines = text.lines().enumerate().filter(|(_, l)| !l.starts_with('#') && !l.trim().is_empty());
2630        let (at, header) = lines.next().unwrap_or((0, ""));
2631        if header.split(',').map(str::trim).ne(["part_number", "price"]) {
2632            return Err((at + 1, "cli-error-prices-header", header.to_string()));
2633        }
2634        let mut prices = HashMap::new();
2635        for (i, line) in lines {
2636            let fields: Vec<&str> = line.split(',').map(str::trim).collect();
2637            let [part, price] = fields[..] else { return Err((i + 1, "cli-error-prices-fields", line.to_string())) };
2638            if part.is_empty() {
2639                return Err((i + 1, "cli-error-prices-fields", line.to_string()));
2640            }
2641            let price = price.parse::<f64>().ok().filter(|p| *p > 0.0 && p.is_finite());
2642            let price = price.ok_or_else(|| (i + 1, "cli-error-prices-value", format!("{part}: {}", fields[1])))?;
2643            if prices.insert(part.to_string(), price).is_some() {
2644                return Err((i + 1, "cli-error-prices-duplicate", part.to_string()));
2645            }
2646        }
2647        Ok(Self(prices))
2648    }
2649}
2650
2651/// Sets each candidate's price (`Candidate::price`): the sum over its parts of the count times the list's price, only
2652/// where every part has one. Returns the part numbers the list lacks, each once, in order of first need.
2653pub fn apply_prices(found: &mut [Candidate], list: &PriceList) -> Vec<String> {
2654    let mut missing: Vec<String> = Vec::new();
2655    for c in found {
2656        c.price = c.parts.iter().map(|(name, count)| list.0.get(name).map(|p| p * count)).sum::<Option<f64>>();
2657        c.price = c.price.filter(|_| !c.parts.is_empty());
2658        for (name, _) in c.parts.iter().filter(|(name, _)| !list.0.contains_key(name)) {
2659            if !missing.contains(name) {
2660                missing.push(name.clone());
2661            }
2662        }
2663    }
2664    missing
2665}
2666
2667/// A job's config made from a duty's config `base`: the axis named, then the parts put in as `with_named` (or, for one
2668/// motor, `with_motor_part`) puts them; and how many motors take the shared motor (1 for one motor's job).
2669fn job_config(entry: &MachineEntry, base: &Config, supply: &str, job: &Job) -> Result<(Config, f64), ConfigError> {
2670    let mut cfg = base.clone();
2671    if !job.axis.is_empty() {
2672        cfg.set_text(&format!("parts.axis = {:?}", job.axis))?;
2673    }
2674    if !job.motor.is_empty() {
2675        return Ok((with_motor_part(entry, &cfg, &job.motor, job.article, supply, &job.gearbox, job.drive)?, 1.0));
2676    }
2677    let mut parts = Parts::of(&cfg)?;
2678    (parts.motor, parts.supply) = (job.article, supply);
2679    if !job.gearbox.is_empty() {
2680        parts.gearbox = &job.gearbox;
2681    }
2682    if !job.drive.is_empty() {
2683        parts.drive = job.drive;
2684    }
2685    let with_parts = with_named(entry, &cfg, &parts)?;
2686    // The motors that take the shared motor: not those with a motor of their own (`[motor.<id>]`, `[parts.<id>]`).
2687    let shared = |id: &str| {
2688        cfg.get(&format!("motor.{id}")).is_err()
2689            && cfg.get(&format!("parts.{id}.motor")).ok().and_then(|v| v.as_str()).is_none_or(str::is_empty)
2690    };
2691    let motors = (entry.build)(&with_parts).map_or(1, |m| m.motors().iter().filter(|m| shared(m.id)).count());
2692    Ok((with_parts, motors as f64))
2693}
2694
2695/// The config a candidate of a search on `cfg` ran with (its axis, motor, gearbox and drive put in, the velocity gain
2696/// retuned): for judging it further, in the error bands (`search::robust_ranking`) or on its own.
2697pub fn candidate_config(entry: &MachineEntry, cfg: &Config, c: &Candidate) -> Result<Config, ConfigError> {
2698    let job = Job {
2699        article: c.article,
2700        gearbox: c.gearbox.clone(),
2701        drive: c.drive,
2702        axis: c.axis.clone(),
2703        axis_weight: 0.0,
2704        motor: c.motor.clone(),
2705    };
2706    Ok(job_config(entry, cfg, c.supply, &job)?.0)
2707}
2708
2709/// The cycle of a config judged; the reason where it cannot run.
2710fn judge(entry: &MachineEntry, cfg: &Config) -> Result<(CycleLoad, Vec<Verdict>), &'static str> {
2711    let mut sim = Sim::new(entry, cfg).map_err(|_| "config")?;
2712    let load = analyse_cycle_with(&mut sim, false).map_err(|e| e.key)?;
2713    let v = verdicts(cfg, &load).map_err(|_| "config")?;
2714    Ok((load, v))
2715}
2716
2717fn try_job(entry: &MachineEntry, cfg: &Config, duties: &[(Config, f64)], supply: &str, job: &Job) -> Option<Candidate> {
2718    // Not offered at this supply, or a part the config cannot take.
2719    let (with_parts, motors) = job_config(entry, cfg, supply, job).ok()?;
2720    let shared = Parts::of(cfg).unwrap_or_default();
2721    let or = |candidate: &str, config: &str| if candidate.is_empty() { config } else { candidate }.to_string();
2722    // Each motor's motor, gearbox and drive: the candidate's in place of the shared ones, a motor's own
2723    // `[parts.<id>]` kept; for one motor (`search_motor`) that motor's alone, the candidate's in place of its own.
2724    let trains: Vec<[String; 3]> = if job.motor.is_empty() {
2725        let ids = (entry.build)(&with_parts).map(|m| m.motors().iter().map(|m| m.id.to_string()).collect());
2726        let (gearbox, drive) = (or(&job.gearbox, shared.gearbox), or(job.drive, shared.drive));
2727        let ids: Vec<String> = ids.unwrap_or_default();
2728        ids.iter()
2729            .map(|id| {
2730                [
2731                    part_of(cfg, id, "motor", job.article),
2732                    part_of(cfg, id, "gearbox", &gearbox),
2733                    part_of(cfg, id, "drive", &drive),
2734                ]
2735            })
2736            .collect()
2737    } else {
2738        let id = job.motor.as_str();
2739        let own = |key: &str, candidate: &str, config: &str| or(candidate, &part_of(cfg, id, key, config));
2740        vec![[
2741            job.article.to_string(),
2742            own("gearbox", &job.gearbox, shared.gearbox),
2743            own("drive", job.drive, shared.drive),
2744        ]]
2745    };
2746    // The gearbox the candidate's motor drives through (the shared one where several take it).
2747    let gearbox = match &trains[..] {
2748        [one] if !job.motor.is_empty() => one[1].clone(),
2749        _ => or(&job.gearbox, shared.gearbox),
2750    };
2751    let gearbox = gearbox.as_str();
2752    // The drives the motors run on: the candidate's, or the config's where it keeps that (derated just the same).
2753    let drives: Vec<String> = trains.iter().map(|train| train[2].clone()).collect();
2754    // What the combination buys, for a price list: every motor's parts, and the axis and belt (a candidate's or the
2755    // config's) where every motor is searched; a mechanical axis by its screws and guide carriages.
2756    let axis = or(&job.axis, shared.axis);
2757    let axis = mechanics::mech_axis_parts(&axis).unwrap_or_else(|| vec![(axis, 1.0)]);
2758    let whole = axis.into_iter().chain([(shared.belt.to_string(), 1.0)]).filter(|_| job.motor.is_empty());
2759    let mut parts: Vec<(String, f64)> = Vec::new();
2760    let each = trains.into_iter().flatten().map(|name| (name, 1.0));
2761    for (name, n) in each.chain(whole).filter(|(name, _)| !name.is_empty()) {
2762        match parts.iter_mut().find(|(known, _)| *known == name) {
2763            Some((_, count)) => *count += n,
2764            None => parts.push((name, n)),
2765        }
2766    }
2767    // An unknown mass counts 0 (not NaN, which sorted the row last); `estimated` says so ("gearbox-mass").
2768    let gearbox_mass = if gearbox.is_empty() { 0.0 } else { gearbox_mass(gearbox).unwrap_or(0.0) };
2769    let mass = motor_mass_for(cfg, job.article, supply).unwrap_or(f64::INFINITY) + gearbox_mass;
2770    let mut candidate = Candidate {
2771        article: job.article,
2772        gearbox: job.gearbox.clone(),
2773        drive: job.drive,
2774        supply: SUPPLIES.iter().copied().find(|s| *s == supply).unwrap_or(""),
2775        axis: job.axis.clone(),
2776        motor: job.motor.clone(),
2777        mass,
2778        cost: motors * mass + job.axis_weight,
2779        parts,
2780        ..Candidate::default()
2781    };
2782    // Every duty of the mix, with the same parts; the first is the config searched on.
2783    let mut runs: Vec<(f64, CycleLoad, Vec<Verdict>)> = Vec::new();
2784    let others =
2785        duties.iter().skip(1).map(|(base, weight)| (job_config(entry, base, supply, job).map(|c| c.0), *weight));
2786    for (duty, weight) in std::iter::once((Ok(with_parts.clone()), duties.first().map_or(1.0, |d| d.1))).chain(others) {
2787        match duty.map_err(|_| "config").and_then(|duty| judge(entry, &duty)) {
2788            Ok((load, v)) => runs.push((weight, load, v)),
2789            Err(reason) => {
2790                candidate.refused = reason;
2791                return Some(candidate);
2792            }
2793        }
2794    }
2795    let mut estimated = estimated_data(job.article, supply, job.drive);
2796    if drives.iter().any(|drive| !estimated_derating(&with_parts, drive).is_empty()) {
2797        estimated.push("drive-derating");
2798    }
2799    if !gearbox.is_empty() {
2800        estimated.extend(estimated_gearbox_data(gearbox));
2801    }
2802    if !job.axis.is_empty() && axis_stroke_is_module_length(&job.axis) {
2803        estimated.push("axis-stroke");
2804    }
2805    let Ok(figures) = crate::search::figures(entry, &with_parts, &job.motor, &runs, estimated) else {
2806        candidate.refused = "config";
2807        return Some(candidate);
2808    };
2809    candidate.figures = Some(figures);
2810    if runs.len() == 1 {
2811        let (_, load, v) = runs.pop()?;
2812        candidate.result = Some((load, v));
2813    } else {
2814        let mixed = crate::search::mix_verdicts(&with_parts, &runs).ok()?;
2815        candidate.duties = runs.iter().map(|(w, load, _)| (*w, load.clone())).collect();
2816        candidate.result = Some((runs.swap_remove(0).1, mixed));
2817    }
2818    Some(candidate)
2819}
2820
2821/// Tries every catalogue motor that `wanted` accepts and that is offered at the supply (`SUPPLIES`; "s120" the
2822/// S120 motors) on the cycle of the config, each with the drive the catalogue pairs with it (`paired_drive`) and
2823/// retuned as `with_parts` says, on all processors, and returns them ranked (`rank`): the passing ones first,
2824/// cheapest first, then the others, nearest to passing first. No catalogue file has a price; the weight of motor
2825/// and gearbox stands in for it (`Candidate::cost`).
2826///
2827/// With `gearboxes` (a series, see `fitting_gearboxes`) and a config whose machine has a gearbox (ratio
2828/// above 1), each motor is tried with every fitting gearbox of that series in place of the config's; a motor that none
2829/// fits is tried with the config's own gearbox (`gearbox` "": before, it was left out without a word).
2830///
2831/// Every candidate is simulated (`run_jobs`).
2832pub fn search_motors(
2833    entry: &MachineEntry,
2834    cfg: &Config,
2835    supply: &str,
2836    wanted: &dyn Fn(&str) -> bool,
2837    gearboxes: Option<&str>,
2838) -> Vec<Candidate> {
2839    search_motors_with(entry, cfg, supply, wanted, &Options { gearboxes, ..Options::default() })
2840}
2841
2842fn search_motors_with(
2843    entry: &MachineEntry,
2844    cfg: &Config,
2845    supply: &str,
2846    wanted: &dyn Fn(&str) -> bool,
2847    options: &Options,
2848) -> Vec<Candidate> {
2849    let own_axis = Parts::of(cfg).ok().map(|p| p.axis.to_string()).unwrap_or_default();
2850    let weight = axis_data(&own_axis).map_or(0.0, |axis| axis_weight(cfg, &axis));
2851    let jobs = motor_jobs(entry, cfg, supply, wanted, options, &own_axis, weight, "");
2852    run_jobs(entry, (cfg, options.duties), supply, jobs, Vec::new())
2853}
2854
2855/// The motor search on every axis of the catalogue that is of the config's kind (`axis_names`: the EXCT sizes and
2856/// Bahr's X/Z gantries for a config with a Z stroke, Bahr's single axes for one with one stroke), keeping the
2857/// config's cycle and payload. An axis that cannot carry the machine by its catalogue numbers (`axis_refusal`:
2858/// stroke, payload, speed) is listed once, with `article` "" and the reason in `refused`, and no motor is tried on
2859/// it. The rest are ranked together, cheapest first: the axis's weight counts into `cost`. A screw, rack or linear
2860/// motor machine is tried on the mechanical axes as well (`mech_axes`: every ball screw, with the guide sets where the
2861/// config rates guides), a linear motor machine with the linear motors of the supply in place of rotary motors.
2862pub fn search_axes(
2863    entry: &MachineEntry,
2864    cfg: &Config,
2865    supply: &str,
2866    wanted: &dyn Fn(&str) -> bool,
2867    gearboxes: Option<&str>,
2868) -> Vec<Candidate> {
2869    search_axes_with(entry, cfg, supply, wanted, &Options { gearboxes, ..Options::default() })
2870}
2871
2872fn search_axes_with(
2873    entry: &MachineEntry,
2874    cfg: &Config,
2875    supply: &str,
2876    wanted: &dyn Fn(&str) -> bool,
2877    options: &Options,
2878) -> Vec<Candidate> {
2879    let (mut jobs, mut refused) = (Vec::new(), Vec::new());
2880    let belts = axis_names().into_iter().filter_map(|name| {
2881        let axis = axis_data(&name)?;
2882        let reason = axis_refusal(cfg, &axis);
2883        (reason != "axis-kind").then(|| (name, reason, axis_weight(cfg, &axis)))
2884    });
2885    let all: Vec<(String, &'static str, f64)> = belts.chain(mech_axes(cfg)).collect();
2886    for (name, reason, weight) in all {
2887        if !reason.is_empty() {
2888            refused.push(Candidate {
2889                axis: name,
2890                mass: f64::NAN,
2891                cost: f64::NAN,
2892                refused: reason,
2893                ..Candidate::default()
2894            });
2895            continue;
2896        }
2897        let mut with_axis = cfg.clone();
2898        if with_axis.set_text(&format!("parts.axis = {name:?}")).is_err() {
2899            continue; // a config without `[parts]` names no part
2900        }
2901        jobs.extend(motor_jobs(entry, &with_axis, supply, wanted, options, &name, weight, ""));
2902    }
2903    run_jobs(entry, (cfg, options.duties), supply, jobs, refused)
2904}
2905
2906/// The search at several supplies (`SUPPLIES`; `vendor_of` tells a supply's maker), ranked together (`rank`): with `motor`
2907/// a machine's one motor of that id (`search_motor`), else with `axes` every axis (`search_axes`), else the config's
2908/// (`search_motors`). Each candidate says its supply, and with it its maker (`vendor_of`). An axis refused before any
2909/// motor was tried is listed once.
2910pub fn search_supplies(
2911    entry: &MachineEntry,
2912    cfg: &Config,
2913    supplies: &[&str],
2914    wanted: &dyn Fn(&str) -> bool,
2915    gearboxes: Option<&str>,
2916    axes: bool,
2917    motor: Option<&str>,
2918) -> Result<Vec<Candidate>, ConfigError> {
2919    search(entry, cfg, supplies, wanted, &Options { gearboxes, axes, motor, ..Options::default() })
2920}
2921
2922/// `search_supplies` with every option of `Options`: the drives beside the paired one, and a duty mix. With a mix,
2923/// `cfg` is the first duty's config (`Options::duties`).
2924pub fn search(
2925    entry: &MachineEntry,
2926    cfg: &Config,
2927    supplies: &[&str],
2928    wanted: &dyn Fn(&str) -> bool,
2929    options: &Options,
2930) -> Result<Vec<Candidate>, ConfigError> {
2931    let mut all = Vec::new();
2932    for supply in supplies {
2933        let found = match options.motor {
2934            Some(id) => search_motor_with(entry, cfg, supply, wanted, options, id)?,
2935            None if options.axes => search_axes_with(entry, cfg, supply, wanted, options),
2936            None => search_motors_with(entry, cfg, supply, wanted, options),
2937        };
2938        let refused_before = |c: &Candidate| c.article.is_empty() && all.iter().any(|a: &Candidate| a.axis == c.axis);
2939        let new: Vec<Candidate> = found.into_iter().filter(|c| !refused_before(c)).collect();
2940        all.extend(new);
2941    }
2942    rank(&mut all);
2943    Ok(all)
2944}
2945
2946/// `search_motors` for one motor of a machine with several (a machine file's `machine.motor` of id `motor`): each
2947/// candidate becomes that motor's own parts, `[parts.<motor>]` (`with_motor_part`), and the other motors stay as the
2948/// config has them. With `gearboxes` the motor's own gearbox ratio picks the fitting ones. The cost is that one motor's
2949/// and gearbox's weight; the axis is the config's.
2950pub fn search_motor(
2951    entry: &MachineEntry,
2952    cfg: &Config,
2953    supply: &str,
2954    wanted: &dyn Fn(&str) -> bool,
2955    gearboxes: Option<&str>,
2956    motor: &str,
2957) -> Result<Vec<Candidate>, ConfigError> {
2958    search_motor_with(entry, cfg, supply, wanted, &Options { gearboxes, ..Options::default() }, motor)
2959}
2960
2961fn search_motor_with(
2962    entry: &MachineEntry,
2963    cfg: &Config,
2964    supply: &str,
2965    wanted: &dyn Fn(&str) -> bool,
2966    options: &Options,
2967    motor: &str,
2968) -> Result<Vec<Candidate>, ConfigError> {
2969    if !(entry.build)(cfg)?.motors().iter().any(|m| m.id == motor) {
2970        return Err(ConfigError::Invalid(format!("machine.motor[{motor}] (no motor of the machine has this id)")));
2971    }
2972    parts_applied(&motor_config(cfg, motor)?)?;
2973    let jobs = motor_jobs(entry, cfg, supply, wanted, options, "", 0.0, motor);
2974    Ok(run_jobs(entry, (cfg, options.duties), supply, jobs, Vec::new()))
2975}
2976
2977/// The config with the catalogue motor `article` at `supply`, its drive `drive` and the gearbox `gearbox` ("" each: the
2978/// motor's own) as motor `motor`'s own parts, `[parts.<motor>]` (`motor_config` puts them in), and that motor's velocity
2979/// gain `drive.<motor>.velocity_kp_nm_s_rad` retuned for them as `with_named` retunes the shared one: by the square root
2980/// of the ratio of the inertia that motor turns (`inertia_seen`, its column alone) times that of its rotor's, and its
2981/// `kv_1_s` lowered where its position cascade needs it (`cascade`).
2982pub fn with_motor_part(
2983    entry: &MachineEntry,
2984    cfg: &Config,
2985    motor: &str,
2986    article: &str,
2987    supply: &str,
2988    gearbox: &str,
2989    drive: &str,
2990) -> Result<Config, ConfigError> {
2991    let text = |t: &str| toml::Value::String(t.into());
2992    let mut parts = vec![("motor", text(article)), ("motor_supply", text(supply))];
2993    parts.extend(
2994        [("drive", drive), ("gearbox", gearbox)].into_iter().filter(|(_, t)| !t.is_empty()).map(|(k, t)| (k, text(t))),
2995    );
2996    let out = with_own_keys(cfg, "parts", motor, &parts)?;
2997    let index =
2998        (entry.build)(cfg)?.motors().iter().position(|m| m.id == motor).ok_or_else(|| {
2999            ConfigError::Invalid(format!("machine.motor[{motor}] (no motor of the machine has this id)"))
3000        })?;
3001    let rotor = |cfg: &Config| -> Result<(f64, f64), ConfigError> {
3002        let mine = motor_config(cfg, motor)?;
3003        Ok((
3004            mine.positive("motor.rotor_inertia_kgm2")? + mine.non_negative("gearbox.inertia_at_input_kgm2")?,
3005            mine.f64("gearbox.ratio").unwrap_or(1.0),
3006        ))
3007    };
3008    // The inertia motor `index` turns at the middle of the travel (`inertia_turned`).
3009    let seen = |cfg: &Config| -> Result<f64, ConfigError> { Ok(inertia_turned(entry, cfg)?[index]) };
3010    let ratio = seen(&out)? / seen(cfg)? * rotor(&out)?.0 / rotor(cfg)?.0;
3011    let gain = motor_config(cfg, motor)?.positive("drive.velocity_kp_nm_s_rad")? * ratio.sqrt();
3012    let out = with_own_keys(&out, "drive", motor, &[("velocity_kp_nm_s_rad", toml::Value::Float(gain))])?;
3013    with_cascade(entry, cfg, &out, index, motor)
3014}
3015
3016#[cfg(test)]
3017mod tests {
3018    use super::*;
3019
3020    #[test]
3021    fn the_compiled_in_tables_pass_the_check_of_a_catalogue_directory() {
3022        // Shows the check accepts what the code was written against, and finds a short row and a missing column.
3023        for &(name, text) in TABLES {
3024            check_table(name, text, text).unwrap_or_else(|e| panic!("{name}: {e:?}"));
3025        }
3026        let (name, text) = TABLES[0];
3027        let short = format!("{text}\nx,y\n");
3028        assert!(check_table(name, &short, text).is_err());
3029        // Blank lines, at the end as an editor leaves them or between rows, and Windows line ends are no error.
3030        let blank = format!("{}\n\n", text.replace("\r\n", "\n").replace('\n', "\r\n\r\n"));
3031        assert!(check_table(name, &blank, text).is_ok());
3032        let renamed = text.replacen("part_number", "part_no", 1);
3033        assert!(check_table(name, &renamed, text).is_err());
3034    }
3035
3036    #[test]
3037    fn the_s120_drives_include_the_double_motor_modules_with_their_per_axis_currents() {
3038        // Catalogue D 21.4 N prints the 2 x 9 A Double Motor Module 6SL3120-2TE21-0AD0 with 9 A rated and 27 A maximum
3039        // per axis (the Single's 9 A / 27 A), and the 2 x 18 A, type C, 6SL3120-2TE21-8AC0 with 18 A / 36 A.
3040        let drives = drives_for("s120");
3041        let find = |p: &str| drives.iter().find(|d| d.0 == p).copied().unwrap();
3042        assert_eq!(find("6SL3120-2TE21-0AD0"), ("6SL3120-2TE21-0AD0", 9.0, 27.0));
3043        assert_eq!(find("6SL3120-2TE21-8AC0"), ("6SL3120-2TE21-8AC0", 18.0, 36.0));
3044        assert_eq!(drives.iter().filter(|d| d.0.starts_with("6SL3120-2")).count(), 5);
3045    }
3046
3047    #[test]
3048    fn a_guide_set_has_four_carriages_unless_the_config_says_and_a_rail_length_sets_the_weight() {
3049        // Hand, HGH15CA (0.18 kg a carriage, 1.45 kg/m of rail, 0.0614 m long): rails of the stroke 0.3 m and two
3050        // carriages, 2 x 1.45 x (0.3 + 0.1228) + 4 x 0.18 = 1.94612 kg; rails of 0.5 m, 2 x 1.45 x 0.5 + 0.72 = 2.17 kg.
3051        let row = rows(table("hiwin/linear_guides.csv")).into_iter().find(|r| r["part_number"] == "HGH15CA").unwrap();
3052        let cfg =
3053            Config::parse("format_version = 1\n[ratings]\nguide_max_load_n = 1.0\n[slide]\nstroke_m = 0.3\n").unwrap();
3054        assert_eq!(guide_carriages(&cfg), Ok(4.0));
3055        assert!((mechanics::guide_weight(&cfg, &row, 4.0) - 1.94612).abs() < 1e-12);
3056        let cfg = Config::parse(
3057            "format_version = 1\n[ratings]\nguide_max_load_n = 1.0\nguide_carriages = 2.0\nguide_rail_length_m = 0.5\n\
3058             [slide]\nstroke_m = 0.3\n",
3059        )
3060        .unwrap();
3061        assert_eq!(guide_carriages(&cfg), Ok(2.0));
3062        assert!((mechanics::guide_weight(&cfg, &row, 4.0) - 2.17).abs() < 1e-12);
3063        for bad in ["2.5", "0.0", "-4.0", "\"four\""] {
3064            let cfg = Config::parse(&format!(
3065                "format_version = 1
3066[ratings]
3067guide_carriages = {bad}
3068"
3069            ))
3070            .unwrap();
3071            assert!(guide_carriages(&cfg).is_err(), "{bad}");
3072        }
3073    }
3074
3075    #[test]
3076    fn a_named_guide_set_puts_its_carriages_mass_and_seal_drag_in_place_of_the_configs() {
3077        // HGH15CA: 0.18 kg and 4.7 N of seal drag a carriage, four of them 0.72 kg and 18.8 N. Without the share keys
3078        // the config's carriage (4 kg) and friction (15 N sliding, 20 N breakaway) hold no guide carriages: 4.72 kg,
3079        // 33.8 N, 38.8 N. With 0.5 kg and 2 N of them its own: 4.22 kg, 31.8 N, 36.8 N, and the shares become the new.
3080        let base = "format_version = 1\n[ratings]\nguide_max_load_n = 1.0\nguide_dynamic_load_rating_n = 1.0\n\
3081                    [mass]\ncarriage_kg = 4.0\n";
3082        let friction = "[friction_x]\ncoulomb_n = 15.0\nstiction_n = 20.0\n";
3083        let named = |text: &str| {
3084            let mut cfg = Config::parse(text).unwrap();
3085            mechanics::apply_mech_axis(&mut cfg, "HGH15CAx4").unwrap().unwrap();
3086            cfg
3087        };
3088        let levels = |cfg: &Config| {
3089            ["mass.carriage_kg", "friction_x.coulomb_n", "friction_x.stiction_n"].map(|k| cfg.f64(k).unwrap())
3090        };
3091        let close = |a: [f64; 3], b: [f64; 3]| a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-12);
3092        assert!(close(levels(&named(&format!("{base}{friction}"))), [4.72, 33.8, 38.8]));
3093        let cfg = named(&format!("{base}guide_carriages_kg = 0.5\n{friction}seal_drag_n = 2.0\n"));
3094        assert!(close(levels(&cfg), [4.22, 31.8, 36.8]));
3095        assert!((cfg.f64("mass.guide_carriages_kg").unwrap() - 0.72).abs() < 1e-12);
3096        assert!((cfg.f64("friction_x.seal_drag_n").unwrap() - 18.8).abs() < 1e-12);
3097        // C for 50 km 14700 N and C0 23470 N a carriage: 58800 N and 4 x 23470 / 2 = 46940 N.
3098        assert_eq!(cfg.f64("ratings.guide_dynamic_load_rating_n").unwrap(), 58800.0);
3099        assert_eq!(cfg.f64("ratings.guide_max_load_n").unwrap(), 46940.0);
3100    }
3101
3102    #[test]
3103    fn a_single_phase_supply_is_told_by_its_text_and_no_makers_line_is_single_phase() {
3104        assert!(single_phase("1 AC 200 ... 240 V") && single_phase("1 x 230 V") && single_phase("Single-phase 230 V"));
3105        assert!(!single_phase("1 or 3 AC 100 ... 240 V") && !single_phase("3 AC 240 V") && !single_phase("3x 200 VAC"));
3106        // Every maker's line has a three-phase drive (the AKD's "1 or 3 AC" counts as three): 1.35 times the line.
3107        for (vendor, line) in SUPPLIES.iter().filter_map(|s| vendor_supply(s)) {
3108            assert!(!single_phase_line(vendor, line), "{vendor} {line}");
3109        }
3110    }
3111
3112    #[test]
3113    fn a_missing_rated_current_is_the_rated_torque_over_the_torque_constant() {
3114        // Kollmorgen prints no rated current at 400 V: In = M_N * I0 / M0, below I0 for a motor whose rated torque is below M0.
3115        let row = vendor_rows("motors_", "kollmorgen", 400.0)
3116            .into_iter()
3117            .find(|r| number(r, "rated_current_a").is_none() && number(r, "rated_torque_nm").is_some())
3118            .expect("a row without rated current");
3119        let m = motor_data(row["part_number"], "kollmorgen-400v").unwrap();
3120        assert!((m.rated_current - m.rated_torque * m.stall_current / m.static_torque).abs() < 1e-12);
3121        assert!(m.rated_current < m.stall_current);
3122    }
3123
3124    #[test]
3125    fn the_voltage_constant_is_sqrt3_times_the_printed_one_unless_it_is_a_misprint() {
3126        // 0.5 V s/rad line to line: sqrt(3) * 0.5 = 0.866, however far that is from kt (a genuine row may be 1.3 times it).
3127        assert!((emf_constant(Some(0.5), "AM8051-0J", 400.0).unwrap() - 0.866_025_4).abs() < 1e-6);
3128        // The two documented misprints are left out, the AKM64Q only at 240 V.
3129        assert_eq!(emf_constant(Some(0.0611), "AKM64Q", 240.0), None);
3130        assert!(emf_constant(Some(0.0611), "AKM64Q", 400.0).is_some());
3131        assert_eq!(emf_constant(Some(0.468), "1FT7044-1AF7", 0.0), None);
3132    }
3133
3134    #[test]
3135    fn rated_values_are_paired_with_the_speed_they_hold_at() {
3136        // 1FT7044-5AK7: 3.0 N m at 471.24 rad/s (4500 r/min); the table's rated speed of 628 rad/s is another point.
3137        let m = motor_data("1FT7044-5AK7", "s120").unwrap();
3138        assert!((m.rated_speed - 4500.0 * PI / 30.0).abs() < 1e-6);
3139    }
3140
3141    #[test]
3142    fn a_misprinted_rated_speed_is_rated_power_over_rated_torque() {
3143        // 1FT2105-4AH: 1740 W / 3.7 N m = 470.3 rad/s (4491 r/min), not the printed 3000 r/min.
3144        let m = motor_data("1FT2105-4AH", "s120").unwrap();
3145        assert!((m.rated_speed - 1740.0 / 3.7).abs() < 1e-9);
3146    }
3147
3148    #[test]
3149    fn a_gearbox_without_mass_or_efficiency_is_named_as_estimated_not_ranked_by_nan() {
3150        let name = |series: &str| {
3151            mechanics::all_gearboxes()
3152                .into_iter()
3153                .find(|g| g.row["series"] == series)
3154                .map(|g| mechanics::gearbox_name(&g.row))
3155        };
3156        // The Apex PE II prints no mass; a Harmonic Drive CSF is an estimate unless its row has an `efficiency`.
3157        assert_eq!(estimated_gearbox_data(&name("PEII").unwrap()), ["gearbox-mass"]);
3158        let csf = mechanics::all_gearboxes().into_iter().find(|g| g.row["series"] == "CSF").unwrap();
3159        let flagged = estimated_gearbox_data(&mechanics::gearbox_name(&csf.row)).contains(&"gearbox-efficiency");
3160        assert_eq!(flagged, printed_efficiency(&csf.row).is_none());
3161    }
3162
3163    #[test]
3164    fn a_strain_wave_gears_efficiency_column_is_used_and_the_estimate_stays_for_rows_without() {
3165        // `efficiency` (read from the maker's charts) counts as printed; a row with neither column has the 0.70 estimate.
3166        let with: Row = Box::leak(Box::new(HashMap::from([("series", "CSF"), ("efficiency", "0.83")])));
3167        let without: Row = Box::leak(Box::new(HashMap::from([("series", "CSF")])));
3168        assert_eq!(printed_efficiency(&with), Some(0.83));
3169        assert!(printed_efficiency(&without).is_none() && strain_wave(&without));
3170    }
3171
3172    /// A config with what `apply_motor` and `apply_gearbox` read and a pulley rating, and the first Kollmorgen motor with
3173    /// a voltage constant and the first gearbox with an efficiency and a stiffness.
3174    fn pulley_config(pulley_max: f64) -> Config {
3175        Config::parse(&format!(
3176            "format_version = 1\n[motor]\nrotor_inertia_kgm2 = 1e-4\ntorque_constant_nm_a = 0.5\nmax_current_a = 10.0\nrated_current_a = 5.0\n\
3177             torque_constant_at_max_current_nm_a = 0.5\ninductance_h = 1e-3\nresistance_ohm = 1.0\n\
3178             thermal_time_constant_s = 600.0\n\
3179             [drive]\ncurrent_kp_v_a = 5.0\ncurrent_tn_s = 1e-3\npeak_torque_nm = 1.0\nrated_torque_nm = 1.0\n\
3180             rated_speed_rad_s = 100.0\nmax_speed_rad_s = 200.0\nbus_voltage_v = 540.0\nno_load_speed_rad_s = 300.0\n\
3181             back_emf_constant_v_s_rad = 0.0\n[gearbox]\nratio = 1.0\nefficiency = 1.0\n\
3182             stiffness_nm_rad = 1e4\nbacklash_rad = 0.0\ninertia_at_input_kgm2 = 0.0\n\
3183             [ratings]\npulley_max_torque_nm = {pulley_max}\n"
3184        ))
3185        .unwrap()
3186    }
3187
3188    fn kollmorgen_motor() -> &'static str {
3189        vendor_rows("motors_", "kollmorgen", 400.0)
3190            .into_iter()
3191            .find(|r| number(r, "voltage_constant_v_s_rad").is_some() && r["part_number"] != "AKM64Q")
3192            .map(|r| r["part_number"])
3193            .expect("a motor with a voltage constant")
3194    }
3195
3196    #[test]
3197    fn the_peak_torque_cap_does_not_depend_on_the_order_of_motor_and_gearbox() {
3198        let gearbox = mechanics::all_gearboxes()
3199            .into_iter()
3200            .find(|g| {
3201                number(&g.row, "efficiency_full_load").is_some()
3202                    && number(&g.row, "torsional_stiffness_nm_rad").is_some()
3203                    && number(&g.row, "rated_output_torque_nm").is_some()
3204                    && number(&g.row, "ratio").is_some_and(|r| r > 2.0)
3205            })
3206            .map(|g| mechanics::gearbox_name(&g.row))
3207            .unwrap();
3208        let g = mechanics::find_gearbox(&gearbox).unwrap().0;
3209        let (ratio, efficiency) = (number(&g.row, "ratio").unwrap(), number(&g.row, "efficiency_full_load").unwrap());
3210        let motor = kollmorgen_motor();
3211        let data = motor_data(motor, "kollmorgen-400v").unwrap();
3212        // The pulley takes half the motor's peak at the pulley: allowed = pulley * eta / i = 0.5 * peak, either order.
3213        let mut gearbox_first = pulley_config(0.5 * data.max_torque * ratio / efficiency);
3214        let mut motor_first = gearbox_first.clone();
3215        apply_gearbox(&mut gearbox_first, &gearbox).unwrap();
3216        apply_motor(&mut gearbox_first, motor, "kollmorgen-400v").unwrap();
3217        apply_motor(&mut motor_first, motor, "kollmorgen-400v").unwrap();
3218        apply_gearbox(&mut motor_first, &gearbox).unwrap();
3219        for cfg in [&gearbox_first, &motor_first] {
3220            assert!((cfg.f64("drive.peak_torque_nm").unwrap() - 0.5 * data.max_torque).abs() < 1e-9 * data.max_torque);
3221        }
3222    }
3223
3224    #[test]
3225    fn a_config_peak_below_the_motors_is_not_raised_by_a_gearbox_applied_after_the_motor() {
3226        let gearbox = mechanics::all_gearboxes()
3227            .into_iter()
3228            .find(|g| {
3229                number(&g.row, "ratio").is_some_and(|r| r > 2.0)
3230                    && number(&g.row, "rated_output_torque_nm").is_some()
3231                    && number(&g.row, "torsional_stiffness_nm_rad").is_some()
3232            })
3233            .map(|g| mechanics::gearbox_name(&g.row))
3234            .unwrap();
3235        let g = mechanics::find_gearbox(&gearbox).unwrap().0;
3236        let (ratio, efficiency) = (number(&g.row, "ratio").unwrap(), printed_efficiency(&g.row).unwrap_or(1.0));
3237        let motor = kollmorgen_motor();
3238        let own = motor_data(motor, "kollmorgen-400v").unwrap().max_torque;
3239        let lowered = |pulley: f64| {
3240            let mut cfg = pulley_config(pulley);
3241            apply_motor(&mut cfg, motor, "kollmorgen-400v").unwrap();
3242            cfg.set_text(&format!("drive.peak_torque_nm = {:?}", 0.1 * own)).unwrap();
3243            apply_gearbox(&mut cfg, &gearbox).unwrap();
3244            cfg.f64("drive.peak_torque_nm").unwrap()
3245        };
3246        // A loose pulley: the config's peak, a tenth of the motor's, stays; a pulley that allows a twentieth through
3247        // the gearbox lowers it to that: the lower of the config's value and the cap.
3248        assert_eq!(lowered(1e9), 0.1 * own);
3249        assert!((lowered(0.05 * own * ratio / efficiency) - 0.05 * own).abs() < 1e-9 * own);
3250    }
3251
3252    #[test]
3253    fn a_printed_voltage_constant_becomes_the_models_back_emf_constant() {
3254        // The motor's printed line-to-line RMS constant times sqrt(3), and the no-load speed sqrt(3/2) bus over it, for a
3255        // Kollmorgen AKM and a Beckhoff AM8000 (whose constant is up to 1.30 times its torque constant).
3256        let beckhoff = vendor_rows("motors_", "beckhoff", 400.0)
3257            .into_iter()
3258            .find(|r| r["part_number"].starts_with("AM80") && number(r, "voltage_constant_v_s_rad").is_some())
3259            .map(|r| r["part_number"])
3260            .unwrap();
3261        for (vendor, motor) in [("kollmorgen", kollmorgen_motor()), ("beckhoff", beckhoff)] {
3262            let printed = vendor_rows("motors_", vendor, 400.0)
3263                .into_iter()
3264                .find(|r| r["part_number"] == motor)
3265                .and_then(|r| number(&r, "voltage_constant_v_s_rad"))
3266                .unwrap();
3267            let mut cfg = pulley_config(1e9);
3268            apply_motor(&mut cfg, motor, &format!("{vendor}-400v")).unwrap();
3269            let ke = cfg.f64("drive.back_emf_constant_v_s_rad").unwrap();
3270            assert!((ke - 3f64.sqrt() * printed).abs() < 1e-12, "{motor}: {ke} for {printed}");
3271            let (bus, rated) = (cfg.f64("drive.bus_voltage_v").unwrap(), cfg.f64("drive.rated_speed_rad_s").unwrap());
3272            let no_load = (crate::drive::WINDING_PER_DC_LINK * bus / ke).max(1.1 * rated);
3273            assert_eq!(cfg.f64("drive.no_load_speed_rad_s").unwrap(), no_load, "{motor}");
3274            eprintln!(
3275                "{motor}: printed {printed} V s/rad, kE {ke}, bus {bus} V, no-load {no_load} rad/s, rated {rated}"
3276            );
3277        }
3278    }
3279
3280    #[test]
3281    fn a_belt_axis_stroke_is_the_module_length_less_the_length_that_is_not_stroke() {
3282        // Rexroth CKR-110: L = 5.5 m = s_max + Lca 170 mm + Lad 25 mm, so s_max = 5.305 m.
3283        assert!((axis_data("CKR-110").unwrap().stroke_x.1 - 5.305).abs() < 1e-9);
3284        // Bahr ELZ-60: basic length 290 mm + travel = 6 m total, travel 5.71 m.
3285        assert!((axis_data("ELZ-60").unwrap().stroke_x.1 - 5.71).abs() < 1e-9);
3286        // An ELSZ has no basic length read directly: the module length stays and the row is flagged.
3287        assert!((axis_data("ELSZ-60").unwrap().stroke_x.1 - 6.0).abs() < 1e-9);
3288        assert!(axis_stroke_is_module_length("ELSZ-60") && !axis_stroke_is_module_length("ELZ-60"));
3289        assert!(!axis_stroke_is_module_length("CKR-110"));
3290    }
3291
3292    #[test]
3293    fn a_retuned_gain_keeps_the_crossover_over_the_rotor_side_inertia() {
3294        // A heavier load on the same rotor keeps the config's gain; a rotor 4 times as heavy allows 4 times the gain,
3295        // here more than the scaled one; a rotor half as heavy half the gain, here less than the scaled one.
3296        assert_eq!(bounded_gain(0.0573, 0.025, 1.0, true), 0.025);
3297        assert_eq!(bounded_gain(0.0646, 0.025, 4.0, true), 0.0646);
3298        assert_eq!(bounded_gain(0.016, 0.025, 0.5, true), 0.0125);
3299        // A gain that shrinks below the bound, and any gain of a rigid model, stands.
3300        assert_eq!(bounded_gain(0.016, 0.025, 1.0, true), 0.016);
3301        assert_eq!(bounded_gain(0.0573, 0.025, 1.0, false), 0.0573);
3302    }
3303}