Skip to main content

sim_components/catalog/
mechanics.rs

1//! The catalogue's mechanics beyond the belts and belt axes: every maker's gearboxes and which motor each fits (by
2//! the motor's frame for the Siemens geared motors, by its shaft for the gearboxes fitted through an adapter plate),
3//! the motors' shafts, ball screws, profile rail guides and linear motors, and the axes a screw, rack or linear motor
4//! machine can be built from (`mech_axes`).
5
6use super::{Row, TABLES, number, rows, set, set_if_present, table, unknown, vendor_supply};
7use crate::transmission::BallScrew;
8use sim_core::{Config, ConfigError};
9use std::collections::HashMap;
10
11/// A gearbox row with its maker and series: the folder and the file name after `gearbox_` ("siemens", "nrk").
12pub(super) struct Gearbox {
13    pub maker: &'static str,
14    pub series: &'static str,
15    pub row: Row,
16}
17
18/// The gearbox tables, `<maker>/gearbox_<series>.csv`, as (maker, series, path); Siemens' `gearbox_mass.csv` holds
19/// masses, not gearboxes.
20fn gearbox_tables() -> impl Iterator<Item = (&'static str, &'static str, &'static str)> {
21    TABLES.iter().filter_map(|(name, _)| {
22        let (maker, file) = name.split_once('/')?;
23        let series = file.strip_prefix("gearbox_")?.strip_suffix(".csv")?;
24        (series != "mass").then_some((maker, series, *name))
25    })
26}
27
28/// Every gearbox of the catalogue.
29pub(super) fn all_gearboxes() -> Vec<Gearbox> {
30    gearbox_tables()
31        .flat_map(|(maker, series, name)| rows(table(name)).into_iter().map(move |row| Gearbox { maker, series, row }))
32        .collect()
33}
34
35/// The name of a gearbox as `apply_gearbox` takes it: size, motor frame (or clamping hub, see the schema) and ratio.
36pub(super) fn gearbox_name(r: &Row) -> String {
37    format!("{}-{}-{}", r["size"], r["motor_frame"], r["ratio"])
38}
39
40/// A gearbox by name, "<size>-<frame>-<ratio>", with "-r" after it for the maker's reduced backlash option; and
41/// whether that option is asked for.
42pub(super) fn find_gearbox(name: &str) -> Option<(Gearbox, bool)> {
43    let (base, reduced) = name.strip_suffix("-r").map_or((name, false), |base| (base, true));
44    all_gearboxes().into_iter().find(|g| gearbox_name(&g.row) == base).map(|g| (g, reduced))
45}
46
47/// The shaft diameter of a motor in m: the row of the `<maker>/motor_shafts.csv` tables with the longest
48/// `part_number_prefix` the article starts with; `None` where no table has it.
49pub fn motor_shaft_diameter(article: &str) -> Option<f64> {
50    TABLES
51        .iter()
52        .filter(|(name, _)| name.ends_with("/motor_shafts.csv"))
53        .flat_map(|(name, _)| rows(table(name)))
54        .filter(|r| !r["part_number_prefix"].is_empty() && article.starts_with(r["part_number_prefix"]))
55        .max_by_key(|r| r["part_number_prefix"].len())
56        .and_then(|r| number(&r, "shaft_diameter_m"))
57}
58
59/// Whether Siemens builds one of its gearboxes (`siemens/gearbox_*.csv`) onto a motor: the NRB, NRK and NLC onto the
60/// 1FK2 and 1FT2 of the frame the row names (1FK2104 and 1FT2204 have frame "04"), the SP+ and TP+ (made by
61/// WITTENSTEIN alpha) onto the 1FT2 only (the equipment manual, chapter 3.1: "Coaxial precision gearbox only for
62/// 1FT2"). The geared motor is what Siemens sells; another frame or a 1FK2 with an SP+ it does not.
63fn siemens_fits(article: &str, g: &Gearbox) -> bool {
64    let precision = matches!(g.series, "sp" | "tp");
65    article.get(3..4) == Some("2")
66        && article.get(5..7) == Some(g.row["motor_frame"])
67        && (!precision || article.starts_with("1FT2"))
68}
69
70/// The gearboxes that fit a motor, at every ratio, as (name, ratio). `series` picks them: "" every maker's; a maker's
71/// folder ("wittenstein", "neugart") all its tables; "<maker>-<series>" one table, by its file name
72/// (`wittenstein-sp` is `wittenstein/gearbox_sp.csv`, `neugart-ple`, `siemens-nrk`; any case); anything else a prefix of
73/// the size, as the search took it before (`NRK`, `NRK070`, `SP+100MF`).
74///
75/// Siemens' gearboxes fit as Siemens sells them (`siemens_fits`). Another maker's fit any motor whose shaft
76/// (`motor_shaft_diameter`) the input's clamping hub takes, through the adapter plate the maker makes for the motor's
77/// flange: a hub bore at least the shaft's (a smaller shaft takes a bushing). Of the bores a size and ratio comes with,
78/// the smallest that takes the shaft (its inertia is the lowest). A motor whose shaft no table has gets none of them.
79/// shortcut: the flange is taken to have an adapter plate (the makers list them for every common servo motor) and the
80/// shaft's length is not checked; upgrade with the makers' motor-specific adapter lists, which need their configurators.
81pub(super) fn fitting(article: &str, series: &str) -> Vec<(String, f64)> {
82    let wanted = series.to_ascii_lowercase();
83    let picked = |g: &Gearbox| {
84        series.is_empty()
85            || wanted == g.maker
86            || wanted == format!("{}-{}", g.maker, g.series)
87            || g.row["size"].starts_with(series)
88    };
89    let shaft = motor_shaft_diameter(article);
90    let mut out = Vec::new();
91    // Per maker, size and ratio of the adapter gearboxes: the smallest hub that takes the shaft, its place in `out`.
92    let mut smallest: HashMap<(&str, &str, &str), (f64, usize)> = HashMap::new();
93    for g in all_gearboxes().into_iter().filter(picked) {
94        let Some(ratio) = number(&g.row, "ratio") else { continue };
95        if g.maker == "siemens" {
96            if siemens_fits(article, &g) {
97                out.push((gearbox_name(&g.row), ratio));
98            }
99            continue;
100        }
101        let (Some(shaft), Some(hub)) = (shaft, number(&g.row, "clamping_hub_diameter_m")) else { continue };
102        if hub + 1e-9 < shaft {
103            continue;
104        }
105        let key = (g.maker, g.row["size"], g.row["ratio"]);
106        match smallest.get(&key) {
107            Some(&(best, at)) if hub < best => {
108                out[at] = (gearbox_name(&g.row), ratio);
109                smallest.insert(key, (hub, at));
110            }
111            Some(_) => {}
112            None => {
113                smallest.insert(key, (hub, out.len()));
114                out.push((gearbox_name(&g.row), ratio));
115            }
116        }
117    }
118    out
119}
120
121/// The mass of a gearbox in kg from its own row, where the table has one (the other makers'; Siemens' are in
122/// `gearbox_mass.csv`).
123pub(super) fn own_mass(name: &str) -> Option<f64> {
124    find_gearbox(name).and_then(|(g, _)| number(&g.row, "mass_kg"))
125}
126
127/// The tables of a part class over every maker: `<maker>/<file>` for the given file name.
128fn rows_of(file: &str) -> Vec<Row> {
129    TABLES
130        .iter()
131        .filter(|(name, _)| name.ends_with(&format!("/{file}")))
132        .flat_map(|(name, _)| rows(table(name)))
133        .collect()
134}
135
136/// The linear motors a supply runs (`SUPPLIES`): the Siemens 1FN3 on "s120" (their Motor Modules), another maker's on
137/// its supply, at the supply's line voltage where the row names one.
138fn linear_rows(supply: &str) -> Vec<Row> {
139    let (maker, line) = match (supply, vendor_supply(supply)) {
140        ("s120", _) => ("siemens", None),
141        (_, Some((maker, line))) => (maker, Some(line)),
142        _ => return Vec::new(),
143    };
144    TABLES
145        .iter()
146        .filter(|(name, _)| {
147            name.split_once('/').is_some_and(|(m, file)| m == maker && file.starts_with("linear_motors_"))
148        })
149        .flat_map(|(name, _)| rows(table(name)))
150        .filter(|r| line.is_none() || number(r, "line_voltage_v").is_none_or(|v| Some(v) == line))
151        .collect()
152}
153
154/// A linear motor of a supply by part number (`linear_rows`).
155pub(super) fn linear_motor_row(article: &str, supply: &str) -> Option<Row> {
156    linear_rows(supply).into_iter().find(|r| r["part_number"] == article)
157}
158
159/// The part numbers of the linear motors a supply runs (`linear_rows`) that have a coil mass, force constant, forces
160/// and currents: what a linear motor machine's search tries in place of rotary motors.
161pub fn linear_motor_articles_for(supply: &str) -> Vec<&'static str> {
162    let complete = |r: &Row| {
163        [
164            "coil_mass_kg",
165            "continuous_force_n",
166            "continuous_current_a",
167            "peak_force_n",
168            "peak_current_a",
169            "max_speed_m_s",
170        ]
171        .iter()
172        .all(|c| number(r, c).is_some())
173    };
174    linear_rows(supply).into_iter().filter(complete).map(|r| r["part_number"]).collect()
175}
176
177/// Whether a config is a linear motor machine: it has `[linear_motor]` (a linear motor axis).
178pub fn is_linear_motor(cfg: &Config) -> bool {
179    cfg.get("linear_motor.attraction_force_n").is_ok()
180}
181
182/// The tables of a config with the same keys as one of its tables, e.g. those with `lead_m` and `root_diameter_m`:
183/// `[screw]` of a screw axis, `[screw_z]` of a machine file.
184fn tables_with(cfg: &Config, keys: &[&str]) -> Vec<String> {
185    let mut found: HashMap<String, usize> = HashMap::new();
186    for (path, _) in cfg.leaves() {
187        if let Some((table, key)) = path.split_once('.')
188            && !key.contains('.')
189            && keys.contains(&key)
190        {
191            *found.entry(table.to_string()).or_default() += 1;
192        }
193    }
194    let mut out: Vec<String> = found.into_iter().filter(|(_, n)| *n == keys.len()).map(|(t, _)| t).collect();
195    out.sort();
196    out
197}
198
199fn screw_tables(cfg: &Config) -> Vec<String> {
200    tables_with(cfg, &["lead_m", "root_diameter_m", "dynamic_load_rating_n"])
201}
202
203/// The carriages a guide set has when the config does not say (`guide_carriages`): two rails with two carriages each, the
204/// layout every shipped screw, rack and linear motor config states.
205pub const GUIDE_CARRIAGES: f64 = 4.0;
206
207/// The tables a machine's guide friction is in, with its sliding and breakaway levels, of which `apply_guides` takes the
208/// first the config has: a gantry's or one-axis machine's X guide (LuGre), each carriage's guide of a linear delta, a slide.
209const GUIDE_FRICTION: [(&str, [&str; 2]); 3] = [
210    ("friction_x", ["coulomb_n", "stiction_n"]),
211    ("friction", ["coulomb_n", "stiction_n"]),
212    ("slide", ["friction_coulomb_n", "friction_breakaway_n"]),
213];
214
215/// The carriages of a config's guide set: `ratings.guide_carriages`, else `GUIDE_CARRIAGES`. A value that is not a whole
216/// number of at least 1 is refused.
217pub fn guide_carriages(cfg: &Config) -> Result<f64, ConfigError> {
218    const KEY: &str = "ratings.guide_carriages";
219    if cfg.get(KEY).is_err() {
220        return Ok(GUIDE_CARRIAGES);
221    }
222    let n = cfg.f64(KEY)?;
223    if n >= 1.0 && n.fract() == 0.0 { Ok(n) } else { Err(ConfigError::Invalid(KEY.into())) }
224}
225
226/// The static safety factor a guide set's highest load is held to, C0 / P: HIWIN's catalogue asks 1.0 to 3.5 for
227/// normal loading and 2.0 to 5.0 with vibration or impact [estimate: the middle of normal loading].
228pub const GUIDE_STATIC_SAFETY: f64 = 2.0;
229
230/// The distance a guide's dynamic load rating C is given for when `guide_life_km` takes it: 50 km (the formula
231/// L10 = (C / P)^3 50 km). A rating for 100 km is 2^(1/3) times smaller.
232const GUIDE_RATING_DISTANCE_M: f64 = 50e3;
233
234fn screw_row(name: &str) -> Option<Row> {
235    rows_of("ball_screws.csv").into_iter().find(|r| r["part_number"] == name)
236}
237
238/// A guide set by name, "<part_number>x<carriages>" (e.g. "HGH25CAx4"): the row and the number of carriages.
239fn guide_set(name: &str) -> Option<(Row, f64)> {
240    let (part, count) = name.rsplit_once('x')?;
241    let count: f64 = count.parse().ok().filter(|n: &f64| *n >= 1.0 && n.fract() == 0.0)?;
242    Some((rows_of("linear_guides.csv").into_iter().find(|r| r["part_number"] == part)?, count))
243}
244
245/// A guide's dynamic load rating for 50 km: the printed C converted from the distance the maker gives it for, by the
246/// cube root of the distances (the life goes with C cubed). `None` without both.
247fn guide_rating_50km(r: &Row) -> Option<f64> {
248    Some(
249        number(r, "dynamic_load_rating_n")?
250            * (number(r, "dynamic_load_rating_distance_m")? / GUIDE_RATING_DISTANCE_M).cbrt(),
251    )
252}
253
254/// Puts a ball screw into each screw table of a config (`screw_tables`): lead, nominal and root diameter, the load
255/// ratings, and where the row has them the nut's stiffness, preload, efficiency and the d n its ball return takes.
256/// Length and mounting stay the config's; a screw longer than the maker makes is refused.
257fn apply_screw(cfg: &mut Config, r: &Row) -> Result<(), ConfigError> {
258    let name = r["part_number"];
259    let need = |column: &str| number(r, column).ok_or_else(|| unknown("axis", name));
260    let tables = screw_tables(cfg);
261    if tables.is_empty() {
262        return Err(ConfigError::Invalid("parts.axis (the machine has no ball screw)".into()));
263    }
264    for t in tables {
265        if number(r, "max_length_m").is_some_and(|max| cfg.f64(&format!("{t}.length_m")).is_ok_and(|l| l > max)) {
266            return Err(ConfigError::Invalid(format!("{t}.length_m")));
267        }
268        for (key, column) in [
269            ("lead_m", "lead_m"),
270            ("nominal_diameter_m", "nominal_diameter_m"),
271            ("root_diameter_m", "root_diameter_m"),
272            ("dynamic_load_rating_n", "dynamic_load_rating_n"),
273            ("static_load_rating_n", "static_load_rating_n"),
274        ] {
275            set(cfg, &format!("{t}.{key}"), need(column)?)?;
276        }
277        for (key, column) in [
278            ("nut_stiffness_n_m", "axial_stiffness_n_m"),
279            ("preload_n", "preload_n"),
280            ("efficiency", "efficiency"),
281            ("max_dn", "max_dn"),
282        ] {
283            if let Some(value) = number(r, column) {
284                set_if_present(cfg, &format!("{t}.{key}"), value)?;
285            }
286        }
287    }
288    Ok(())
289}
290
291/// Puts a guide set into a config's ratings: `guide_dynamic_load_rating_n` the carriages' C (for 50 km) together, and
292/// `guide_max_load_n` their C0 together over `GUIDE_STATIC_SAFETY`, each where the config rates it. A config that rates
293/// neither is refused: the guide would change nothing it judges.
294/// The load is taken to share equally between the carriages. The carriages' mass (per carriage times `count`) takes the
295/// place of the config's guide carriages in the moved mass `mass.carriage_kg`, and their seals' drag that of the config's
296/// in the guide's friction levels (`GUIDE_FRICTION`: Coulomb and breakaway, as the seals drag at any speed): the share of
297/// the config's own carriages is `mass.guide_carriages_kg` and `<friction table>.seal_drag_n`, absent = 0 (the config's
298/// numbers hold no guide carriages, and the named ones are added). Each only where the config has the key it changes and
299/// the row the column; the share keys, where the config has them, then hold the named carriages'.
300fn apply_guides(cfg: &mut Config, r: &Row, count: f64) -> Result<(), ConfigError> {
301    let name = r["part_number"];
302    let dynamic = guide_rating_50km(r).ok_or_else(|| unknown("axis", name))?;
303    let stat = number(r, "static_load_rating_n").ok_or_else(|| unknown("axis", name))?;
304    if !rates_guides(cfg) {
305        return Err(ConfigError::Invalid("parts.axis (the config rates no guides)".into()));
306    }
307    fn swap(cfg: &mut Config, share: &str, targets: &[String], new: f64) -> Result<(), ConfigError> {
308        let old = cfg.f64(share).unwrap_or(0.0);
309        for key in targets {
310            if let Ok(value) = cfg.f64(key) {
311                set(cfg, key, value - old + new)?;
312            }
313        }
314        set_if_present(cfg, share, new)
315    }
316    if let Some(each) = number(r, "carriage_mass_kg") {
317        swap(cfg, "mass.guide_carriages_kg", &["mass.carriage_kg".into()], count * each)?;
318    }
319    if let (Some(each), Some((table, levels))) =
320        (number(r, "seal_drag_n"), GUIDE_FRICTION.iter().find(|(t, l)| cfg.get(&format!("{t}.{}", l[0])).is_ok()))
321    {
322        let targets: Vec<String> = levels.iter().map(|l| format!("{table}.{l}")).collect();
323        swap(cfg, &format!("{table}.seal_drag_n"), &targets, count * each)?;
324    }
325    set_if_present(cfg, "ratings.guide_dynamic_load_rating_n", count * dynamic)?;
326    set_if_present(cfg, "ratings.guide_max_load_n", count * stat / GUIDE_STATIC_SAFETY)
327}
328
329fn rates_guides(cfg: &Config) -> bool {
330    cfg.get("ratings.guide_dynamic_load_rating_n").is_ok() || cfg.get("ratings.guide_max_load_n").is_ok()
331}
332
333/// Puts a mechanical axis into a config: its parts by name, joined by "+": ball screws (`ball_screws.csv`, part
334/// number) and guide sets ("<part number>x<carriages>" of `linear_guides.csv`). `None` where a part is in no table.
335pub(super) fn apply_mech_axis(cfg: &mut Config, name: &str) -> Option<Result<(), ConfigError>> {
336    let mut screws = Vec::new();
337    let mut guides = Vec::new();
338    for part in name.split('+') {
339        if let Some(s) = screw_row(part) {
340            screws.push(s);
341        } else {
342            guides.push(guide_set(part)?);
343        }
344    }
345    let mut apply = || -> Result<(), ConfigError> {
346        for s in &screws {
347            apply_screw(cfg, s)?;
348        }
349        for (g, count) in &guides {
350            apply_guides(cfg, g, *count)?;
351        }
352        Ok(())
353    };
354    Some(apply())
355}
356
357/// The parts a mechanical axis's name (`apply_mech_axis`) buys, by part number with how many: each screw once, each
358/// guide's carriages. `None` for another name.
359pub(super) fn mech_axis_parts(name: &str) -> Option<Vec<(String, f64)>> {
360    let piece = |part: &str| match screw_row(part) {
361        Some(_) => Some((part.to_string(), 1.0)),
362        None => guide_set(part).map(|(row, count)| (row["part_number"].to_string(), count)),
363    };
364    name.split('+').map(piece).collect()
365}
366
367/// The highest speed and acceleration a config's axes allow ([axis.<id>]): of the axis `id` where it has one, else of
368/// all of them.
369fn axis_limits(cfg: &Config, id: Option<&str>) -> (f64, f64) {
370    let get = |key: &str| {
371        let own = id.and_then(|id| cfg.f64(&format!("axis.{id}.{key}")).ok());
372        own.unwrap_or_else(|| {
373            cfg.leaves()
374                .into_iter()
375                .filter(|(p, _)| p.starts_with("axis.") && p.ends_with(&format!(".{key}")))
376                .filter_map(|(_, v)| v.as_float())
377                .fold(0.0, f64::max)
378        })
379    };
380    (get("max_velocity_m_s"), get("max_acceleration_m_s2"))
381}
382
383/// Why a ball screw cannot carry a config's axis by its catalogue numbers alone, "" where it can: at the axis's highest
384/// speed it would turn above `critical_speed_factor` times its critical speed or above the d n its nut takes
385/// (`axis-speed`); the force to accelerate carriage and payload at the axis's highest acceleration (and to lift them
386/// on an inclined axis) is above its static rating over `static_safety_factor` (`axis-payload`); or it is longer than
387/// the maker makes it (`axis-stroke`). "config" where the screw does not make a valid `[screw]`.
388fn screw_refusal(cfg: &Config, r: &Row) -> &'static str {
389    let mut with = cfg.clone();
390    if let Err(e) = apply_screw(&mut with, r) {
391        return if e.key() == "error-config-invalid" { "axis-stroke" } else { "config" };
392    }
393    let mass = with.f64("mass.carriage_kg").unwrap_or(0.0) + with.f64("mass.payload_kg").unwrap_or(0.0);
394    let lift = with.f64("slide.incline_deg").unwrap_or(0.0).to_radians().sin().abs() * 9.81;
395    for t in screw_tables(&with) {
396        // `BallScrew` reads `[screw]`: the config with this table copied there.
397        let shell = with.to_text().ok().and_then(|text| text.parse::<toml::Table>().ok()).and_then(|mut all| {
398            let own = all.get(&t)?.clone();
399            all.insert("screw".into(), own);
400            Config::parse(&toml::to_string(&all).ok()?).ok()
401        });
402        let Some(Ok(screw)) = shell.map(|c| BallScrew::from_config(&c)) else { return "config" };
403        let (speed, acceleration) = axis_limits(&with, t.strip_prefix("screw_"));
404        let rpm = speed / screw.lead * 60.0;
405        if rpm > screw.allowed_speed_rpm() || (screw.max_dn > 0.0 && screw.nominal_diameter * 1e3 * rpm > screw.max_dn)
406        {
407            return "axis-speed";
408        }
409        if mass * (acceleration + lift) > screw.static_rating / screw.static_safety {
410            return "axis-payload";
411        }
412    }
413    ""
414}
415
416/// Why a guide set cannot carry a config's machine by its catalogue numbers alone: the weight of carriage and payload
417/// and the linear motor's magnetic attraction (where there is one) above its C0 over `GUIDE_STATIC_SAFETY`
418/// (`axis-payload`); "" where it can.
419fn guide_refusal(cfg: &Config, r: &Row, count: f64) -> &'static str {
420    let mass = cfg.f64("mass.carriage_kg").unwrap_or(0.0) + cfg.f64("mass.payload_kg").unwrap_or(0.0);
421    let load = mass * 9.81 + cfg.f64("linear_motor.attraction_force_n").unwrap_or(0.0);
422    match number(r, "static_load_rating_n") {
423        Some(c0) if load <= count * c0 / GUIDE_STATIC_SAFETY => "",
424        _ => "axis-payload",
425    }
426}
427
428/// The stroke of a config's machine for the weights of rails and magnet tracks: `slide.stroke_m`, else the longest
429/// screw.
430fn stroke(cfg: &Config) -> f64 {
431    cfg.f64("slide.stroke_m").unwrap_or_else(|_| {
432        screw_tables(cfg).iter().filter_map(|t| cfg.f64(&format!("{t}.length_m")).ok()).fold(0.0, f64::max)
433    })
434}
435
436/// The installed weight of a ball screw at a config's lengths, kg: shaft and nut. A shaft whose mass per metre the
437/// maker does not print is a steel cylinder of its nominal diameter, as `BallScrew::inertia` takes it.
438fn screw_weight(cfg: &Config, r: &Row) -> f64 {
439    let per_m = number(r, "mass_per_length_kg_m").unwrap_or_else(|| {
440        let d = number(r, "nominal_diameter_m").unwrap_or(0.0);
441        crate::transmission::STEEL_DENSITY * std::f64::consts::PI * d * d / 4.0
442    });
443    let length: f64 = screw_tables(cfg).iter().filter_map(|t| cfg.f64(&format!("{t}.length_m")).ok()).sum();
444    per_m * length + number(r, "nut_mass_kg").unwrap_or(0.0)
445}
446
447/// The installed weight of a guide set, kg: the carriages and two rails as long as `ratings.guide_rail_length_m`, else as
448/// the stroke and two carriages.
449pub(super) fn guide_weight(cfg: &Config, r: &Row, count: f64) -> f64 {
450    let rail = cfg
451        .f64("ratings.guide_rail_length_m")
452        .unwrap_or_else(|_| stroke(cfg) + 2.0 * number(r, "carriage_length_m").unwrap_or(0.0));
453    count * number(r, "carriage_mass_kg").unwrap_or(0.0) + 2.0 * rail * number(r, "rail_mass_kg_m").unwrap_or(0.0)
454}
455
456/// The weight of a linear motor's magnet track at a config's stroke, kg: the stroke and the coil's length of track.
457pub fn magnet_track_weight(cfg: &Config, article: &str, supply: &str) -> f64 {
458    linear_motor_row(article, supply).map_or(0.0, |r| {
459        let length = stroke(cfg) + number(&r, "coil_length_m").unwrap_or(0.0);
460        number(&r, "magnet_track_mass_kg_m").unwrap_or(0.0) * length
461    })
462}
463
464/// How many guide sizes of a series and carriage type the axis search tries: the smallest that carry the machine by
465/// their static rating and the next one up (a bigger one only adds weight unless the cycle's life needs it).
466const GUIDE_SIZES_TRIED: usize = 2;
467
468/// The mechanical axes of the catalogue a config's machine can be built from, as (name for `parts.axis`, why it is
469/// refused, "" where it is not; installed weight in kg): for a machine with ball screws every catalogue screw
470/// (`screw_refusal`), and where the config rates guides (a screw, rack or linear motor machine with
471/// `ratings.guide_*`) with each guide set (`guide_carriages` carriages; per series and carriage type the
472/// `GUIDE_SIZES_TRIED` smallest that pass `guide_refusal`). A screw refused is listed once on its own. Empty for a
473/// machine of another kind. A linear motor machine's motors are the linear motors (`linear_motor_articles_for`).
474pub fn mech_axes(cfg: &Config) -> Vec<(String, &'static str, f64)> {
475    let screws: Vec<Row> = if screw_tables(cfg).is_empty() { Vec::new() } else { rows_of("ball_screws.csv") };
476    let mech = !screws.is_empty() || is_linear_motor(cfg) || !tables_with(cfg, &["module_m", "teeth"]).is_empty();
477    let mut guides: Vec<(String, f64)> = Vec::new();
478    // (A config with an invalid carriage count is refused by `resolve`, so every candidate on it is: no guide is offered.)
479    if let (true, Ok(carriages)) = (mech && rates_guides(cfg), guide_carriages(cfg)) {
480        let mut all: Vec<Row> = rows_of("linear_guides.csv")
481            .into_iter()
482            .filter(|r| guide_rating_50km(r).is_some() && guide_refusal(cfg, r, carriages).is_empty())
483            .collect();
484        all.sort_by(|a, b| number(a, "static_load_rating_n").partial_cmp(&number(b, "static_load_rating_n")).unwrap());
485        let mut tried: HashMap<(&str, &str), usize> = HashMap::new();
486        for r in &all {
487            let n = tried
488                .entry((r.get("series").copied().unwrap_or(""), r.get("carriage_type").copied().unwrap_or("")))
489                .or_default();
490            if *n < GUIDE_SIZES_TRIED {
491                *n += 1;
492                guides.push((format!("{}x{}", r["part_number"], carriages), guide_weight(cfg, r, carriages)));
493            }
494        }
495    }
496    let mut out = Vec::new();
497    for s in &screws {
498        let (name, reason) = (s["part_number"].to_string(), screw_refusal(cfg, s));
499        let weight = screw_weight(cfg, s);
500        if !reason.is_empty() || guides.is_empty() {
501            out.push((name, reason, weight));
502            continue;
503        }
504        out.extend(guides.iter().map(|(g, w)| (format!("{name}+{g}"), "", weight + w)));
505    }
506    if screws.is_empty() {
507        out.extend(guides.into_iter().map(|(g, w)| (g, "", w)));
508    }
509    out
510}
511
512#[cfg(test)]
513mod tests {
514    use super::*;
515
516    fn row(cells: &[(&'static str, &'static str)]) -> Row {
517        Box::leak(Box::new(cells.iter().copied().collect::<HashMap<_, _>>()))
518    }
519
520    fn rated() -> Config {
521        Config::parse("format_version = 1\n[ratings]\nguide_max_load_n = 1.0\nguide_dynamic_load_rating_n = 1.0\n")
522            .unwrap()
523    }
524
525    /// A guide row with an empty cell gives "not available" for the figure that needs it, and no other figure: an empty C
526    /// (or a C without the distance it is for) is no rating, so there is no life and no set; an empty C0 leaves the set
527    /// without a static rating (the search refuses it); an empty seal drag or mass leaves the config's own friction and
528    /// carriage mass alone, never zero.
529    #[test]
530    fn an_empty_cell_of_a_guide_row_is_not_available_never_zero_or_unlimited() {
531        let full = [
532            ("part_number", "T1"),
533            ("dynamic_load_rating_n", "30000"),
534            ("dynamic_load_rating_distance_m", "100000"),
535            ("static_load_rating_n", "40000"),
536        ];
537        // 30000 N for 100 km is 30000 x 2^(1/3) for 50 km.
538        assert!((guide_rating_50km(&row(&full)).unwrap() - 30000.0 * 2.0_f64.cbrt()).abs() < 1e-9);
539        for empty in ["dynamic_load_rating_n", "dynamic_load_rating_distance_m", "static_load_rating_n"] {
540            let cells: Vec<_> = full.iter().copied().map(|(k, v)| if k == empty { (k, "") } else { (k, v) }).collect();
541            let r = row(&cells);
542            let mut cfg = rated();
543            assert!(apply_guides(&mut cfg, &r, 4.0).is_err(), "{empty}");
544            assert_eq!(cfg.f64("ratings.guide_dynamic_load_rating_n").unwrap(), 1.0, "{empty}");
545            assert_eq!(cfg.f64("ratings.guide_max_load_n").unwrap(), 1.0, "{empty}");
546        }
547        assert!(guide_rating_50km(&row(&[("part_number", "T1"), ("dynamic_load_rating_n", "30000")])).is_none());
548        // No seal drag and no mass in the row: the config's friction and carriage mass are not touched.
549        let mut cfg = Config::parse(
550            "format_version = 1\n[ratings]\nguide_max_load_n = 1.0\nguide_dynamic_load_rating_n = 1.0\n\
551             [mass]\ncarriage_kg = 4.0\n[friction_x]\ncoulomb_n = 15.0\nstiction_n = 20.0\n",
552        )
553        .unwrap();
554        apply_guides(&mut cfg, &row(&full), 4.0).unwrap();
555        assert_eq!(cfg.f64("mass.carriage_kg").unwrap(), 4.0);
556        assert_eq!(cfg.f64("friction_x.coulomb_n").unwrap(), 15.0);
557        assert_eq!(cfg.f64("friction_x.stiction_n").unwrap(), 20.0);
558        assert!(
559            (cfg.f64("ratings.guide_dynamic_load_rating_n").unwrap() - 4.0 * 30000.0 * 2.0_f64.cbrt()).abs() < 1e-6
560        );
561        assert_eq!(cfg.f64("ratings.guide_max_load_n").unwrap(), 4.0 * 40000.0 / GUIDE_STATIC_SAFETY);
562    }
563}