1use 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
11pub(super) struct Gearbox {
13 pub maker: &'static str,
14 pub series: &'static str,
15 pub row: Row,
16}
17
18fn 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
28pub(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
35pub(super) fn gearbox_name(r: &Row) -> String {
37 format!("{}-{}-{}", r["size"], r["motor_frame"], r["ratio"])
38}
39
40pub(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
47pub 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
59fn 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
70pub(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 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
121pub(super) fn own_mass(name: &str) -> Option<f64> {
124 find_gearbox(name).and_then(|(g, _)| number(&g.row, "mass_kg"))
125}
126
127fn 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
136fn 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
154pub(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
159pub 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
177pub fn is_linear_motor(cfg: &Config) -> bool {
179 cfg.get("linear_motor.attraction_force_n").is_ok()
180}
181
182fn 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
203pub const GUIDE_CARRIAGES: f64 = 4.0;
206
207const 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
215pub 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
226pub const GUIDE_STATIC_SAFETY: f64 = 2.0;
229
230const 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
238fn 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
245fn 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
254fn 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
291fn 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
333pub(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
357pub(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
367fn 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
383fn 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 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
416fn 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
428fn 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
436fn 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
447pub(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
456pub 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
464const GUIDE_SIZES_TRIED: usize = 2;
467
468pub 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 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 #[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 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 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}