1use 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
20pub const SCHEMA_VERSION: i64 = 1;
22
23macro_rules! tables {
24 ($($name:literal),* $(,)?) => { [$(($name, include_str!(concat!("../../../catalog/", $name)))),*] };
25}
26
27const 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
103static 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
111fn motor_manuals() -> [&'static str; 2] {
114 [table("siemens/motors_1fk2_s120.csv"), table("siemens/motors_1ft2_s120.csv")]
115}
116
117pub 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 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 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
148fn 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 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
172pub 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
199pub fn vendor_of(supply: &str) -> &str {
201 vendor_supply(supply).map_or("siemens", |(vendor, _)| vendor)
202}
203
204fn 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
213fn 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
221fn 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
227fn 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
239fn 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
249fn 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
260pub(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 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
286fn 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
298fn in_unit(si: f64, factor: f64) -> f64 {
301 let value = si * factor;
302 format!("{value:.11e}").parse().unwrap_or(value)
303}
304
305fn 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
320pub const S210_BASE_LOAD_SHARE: f64 = 0.85;
323
324fn 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
329pub fn motor_articles() -> Vec<&'static str> {
331 rows(table("siemens/motors_s210.csv")).iter().map(|r| r["part_number"]).collect()
332}
333
334pub 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
367struct MotorData {
369 rotor_kgm2: f64,
370 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 max_speed: f64,
382 thermal_seconds: Option<f64>,
383 winding: Option<(f64, f64)>,
385 pole_pairs: Option<f64>,
387 mass: f64,
388 force_constant: Option<f64>,
390 linear: Option<(f64, f64)>,
392 emf_constant: Option<f64>,
395}
396
397fn 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 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 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 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 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 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_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 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 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 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
573pub fn motor_mass(article: &str, supply: &str) -> Option<f64> {
575 motor_data(article, supply).ok().map(|m| m.mass)
576}
577
578pub 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
585fn 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
590pub fn motor_max_speed(article: &str, supply: &str) -> Option<f64> {
593 motor_data(article, supply).ok().map(|m| m.max_speed)
594}
595
596pub 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 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 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 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 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 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 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 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 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
725fn 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
745fn 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
768fn cap_peak_torque(cfg: &mut Config, uncapped: f64) -> Result<(), ConfigError> {
772 set(cfg, "drive.peak_torque_nm", uncapped.min(pulley_allowed(cfg)))
773}
774
775fn 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
782pub 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 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#[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
882pub 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
906pub 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
921fn 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
932pub 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
973pub fn apply_drive(cfg: &mut Config, article: &str, supply: &str) -> Result<(), ConfigError> {
1009 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 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 let rated = number(&d, "rated_output_current_a");
1036 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 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 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 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 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 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
1122pub const DRIVE_CONDITION_KEYS: [&str; 3] =
1126 ["ratings.drive_ambient_c", "ratings.drive_altitude_m", "ratings.drive_pulse_frequency_hz"];
1127
1128pub 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
1138fn 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
1153fn 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
1159fn 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
1176pub 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 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 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 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 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
1272pub 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
1279fn 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
1310pub 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
1325const STRAIN_WAVE_EFFICIENCY: f64 = 0.70;
1330
1331fn 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
1341pub 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
1357pub 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 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 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 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 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
1433fn 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
1459pub 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
1471fn 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
1486fn 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#[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
1524const BELT_AXIS_LOAD_DISTANCE_M: f64 = 5.0e6;
1528
1529#[derive(Debug, Clone)]
1531struct AxisData {
1532 kind: Kind,
1533 stroke_x: (f64, f64),
1536 strokes_z: Vec<f64>,
1537 z_up_to: bool,
1539 pulley_radius: f64,
1540 belt: Option<(String, f64)>,
1544 ea: Option<f64>,
1546 teeth: f64,
1547 pulley_torque: f64,
1549 payload_kg: Option<f64>,
1551 slide_load_n: Option<f64>,
1552 max_speed: f64,
1553 max_acceleration: Option<f64>,
1554 moved: Option<(f64, f64)>,
1557 festo_formula: Vec<(f64, f64, f64, f64)>,
1558 weight: (f64, f64, f64),
1560}
1561
1562pub 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
1572pub 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
1581fn 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
1597fn 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
1605fn 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 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 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 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 ea: number(r, "belt_elongation_force_n").zip(number(r, "belt_elongation")).map(|(f, e)| f / e),
1692 teeth: number(r, "pulley_teeth")?,
1693 pulley_torque: number(r, "max_pulley_torque_nm").unwrap_or(number(r, "feed_force_peak_n")? * radius),
1695 payload_kg: None,
1696 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
1713fn 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
1723fn 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
1760fn 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
1772pub 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
1832fn 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#[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
1871pub const PART_KEYS: [&str; 6] = ["motor", "motor_supply", "gearbox", "drive", "belt", "axis"];
1873
1874impl<'a> Parts<'a> {
1875 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 fn moves(&self) -> bool {
1898 !(self.motor.is_empty() && self.gearbox.is_empty() && self.belt.is_empty() && self.axis.is_empty())
1899 }
1900}
1901
1902fn 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
1927pub(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
1936pub const PER_MOTOR_TABLES: [&str; 7] = ["parts", "motor", "gearbox", "drive", "ratings", "strain_wave", "joint"];
1940
1941pub 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
1981fn 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
1994pub fn resolve(entry: &MachineEntry, cfg: &Config) -> Result<Config, ConfigError> {
2000 with_named(entry, cfg, &Parts::of(cfg)?)
2001}
2002
2003#[derive(Debug, Clone, Default)]
2006pub struct Candidate {
2007 pub article: &'static str,
2009 pub gearbox: String,
2011 pub drive: &'static str,
2013 pub supply: &'static str,
2015 pub axis: String,
2017 pub motor: String,
2019 pub mass: f64,
2021 pub cost: f64,
2025 pub parts: Vec<(String, f64)>,
2030 pub price: Option<f64>,
2032 pub result: Option<(CycleLoad, Vec<Verdict>)>,
2035 pub refused: &'static str,
2036 pub duties: Vec<(f64, CycleLoad)>,
2038 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 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 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 verdicts
2074 .iter()
2075 .filter(|v| (v.limit > 0.0 || !v.ok) && !by_design(v))
2076 .filter(|v| {
2078 !v.ok || !["belt-least-tension", "thermal-warm-start", "thermal-cycle-repeat"].contains(&v.check)
2079 })
2080 .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
2090fn inertia_seen(entry: &MachineEntry, cfg: &Config) -> Result<f64, ConfigError> {
2094 Ok(inertia_turned(entry, cfg)?.iter().sum())
2095}
2096
2097fn 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
2116fn 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
2128pub(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
2146pub 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
2173fn 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 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
2206pub const CASCADE_MARGIN: f64 = 1.25;
2213
2214fn 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
2235fn 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
2242fn 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
2254fn bounded_gain(scaled: f64, old: f64, rotor_ratio: f64, elastic: bool) -> f64 {
2333 if elastic { scaled.min(old * rotor_ratio) } else { scaled }
2334}
2335
2336pub 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
2370pub fn with_named(entry: &MachineEntry, cfg: &Config, parts: &Parts) -> Result<Config, ConfigError> {
2372 guide_carriages(cfg)?; 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
2382fn 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 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
2420fn 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
2433fn 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
2450pub 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
2459pub fn gearboxes_for_motor(article: &str, series: &str) -> Vec<String> {
2466 mechanics::fitting(article, series).into_iter().map(|(name, _)| name).collect()
2467}
2468
2469pub 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
2475pub 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#[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 motor: String,
2498}
2499
2500#[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
2514fn 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
2524fn 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#[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 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 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
2581fn 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 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
2602pub 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
2620pub struct PriceList(HashMap<String, f64>);
2624
2625impl PriceList {
2626 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
2651pub 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
2667fn 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 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
2695pub 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
2709fn 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 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 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 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 let drives: Vec<String> = trains.iter().map(|train| train[2].clone()).collect();
2754 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 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 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
2821pub 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
2855pub 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; }
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
2906pub 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
2922pub 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
2946pub 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
2977pub 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 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 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 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 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 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 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 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 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 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 assert!((emf_constant(Some(0.5), "AM8051-0J", 400.0).unwrap() - 0.866_025_4).abs() < 1e-6);
3128 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 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 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 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 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 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 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 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 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 assert!((axis_data("CKR-110").unwrap().stroke_x.1 - 5.305).abs() < 1e-9);
3284 assert!((axis_data("ELZ-60").unwrap().stroke_x.1 - 5.71).abs() < 1e-9);
3286 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 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 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}