1use crate::analysis::{CycleLoad, MotorLoad, Verdict, supply_energy, utilisation};
8use crate::catalog::{self, Candidate, Options};
9use crate::drive::DriveParams;
10use sim_core::{Config, ConfigError, MachineEntry};
11
12#[derive(Debug, Clone, Default, PartialEq)]
14pub struct Figures {
15 pub checks: Vec<(&'static str, f64)>,
18 pub failing: Vec<&'static str>,
20 pub energy_j: f64,
22 pub thermal: f64,
25 pub drive_current: f64,
27 pub following_error_m: f64,
29 pub settling_error_m: f64,
31 pub inertia_ratio: f64,
33 pub cycle_s: f64,
35 pub estimated: Vec<&'static str>,
37}
38
39fn concerns(load: &CycleLoad, motor: &str, v: &Verdict) -> bool {
41 motor.is_empty() || v.motor.is_none_or(|k| load.motors.get(k).is_some_and(|m| m.id == motor))
42}
43
44pub fn mix_rms(parts: &[(f64, f64, f64)]) -> f64 {
47 let time: f64 = parts.iter().map(|(w, _, t)| w * t).sum();
48 (parts.iter().map(|(w, rms, t)| w * rms * rms * t).sum::<f64>() / time).sqrt()
49}
50
51pub fn mix_mean(parts: &[(f64, f64, f64)]) -> f64 {
53 let time: f64 = parts.iter().map(|(w, _, t)| w * t).sum();
54 parts.iter().map(|(w, x, t)| w * x * t).sum::<f64>() / time
55}
56
57#[derive(Debug, Clone, Copy, PartialEq)]
59pub struct Stretch {
60 pub len: f64,
61 pub a: [[f64; 2]; 2],
62 pub b: [f64; 2],
63}
64
65impl Stretch {
66 pub fn node(len: f64, tau: f64, target: f64) -> Self {
68 Self { len, a: [[-1.0 / tau, 0.0], [0.0, -2.0 / tau]], b: [target / tau, 0.0] }
69 }
70}
71
72fn modes(a: &[[f64; 2]; 2], t: f64) -> (f64, f64, f64, f64) {
76 let m = 0.5 * (a[0][0] + a[1][1]);
77 let d = (m * m - (a[0][0] * a[1][1] - a[0][1] * a[1][0])).max(0.0).sqrt();
78 let (up, down) = (((m + d) * t).exp(), ((m - d) * t).exp());
79 let q = if d * t > 1e-9 { (up - down) / (2.0 * d) } else { t * (m * t).exp() };
80 (m, d, 0.5 * (up + down), q)
81}
82
83pub fn periodic_peak(parts: &[Stretch], out: [f64; 2]) -> f64 {
89 let settled = |s: &Stretch| {
90 let det = s.a[0][0] * s.a[1][1] - s.a[0][1] * s.a[1][0];
91 [(s.a[0][1] * s.b[1] - s.a[1][1] * s.b[0]) / det, (s.a[1][0] * s.b[0] - s.a[0][0] * s.b[1]) / det]
92 };
93 let flow = |s: &Stretch, t: f64| {
94 let (m, _, p, q) = modes(&s.a, t);
95 [[p + q * (s.a[0][0] - m), q * s.a[0][1]], [q * s.a[1][0], p + q * (s.a[1][1] - m)]]
96 };
97 let times = |e: &[[f64; 2]; 2], x: [f64; 2]| [e[0][0] * x[0] + e[0][1] * x[1], e[1][0] * x[0] + e[1][1] * x[1]];
98 let (mut mm, mut v) = ([[1.0, 0.0], [0.0, 1.0]], [0.0, 0.0]);
100 for s in parts {
101 let (e, xs) = (flow(s, s.len), settled(s));
102 let ev = times(&e, [v[0] - xs[0], v[1] - xs[1]]);
103 let column = |j: usize| times(&e, [mm[0][j], mm[1][j]]);
104 let (c0, c1) = (column(0), column(1));
105 (mm, v) = ([[c0[0], c1[0]], [c0[1], c1[1]]], [ev[0] + xs[0], ev[1] + xs[1]]);
106 }
107 let (i00, i01, i10, i11) = (1.0 - mm[0][0], -mm[0][1], -mm[1][0], 1.0 - mm[1][1]);
108 let det = i00 * i11 - i01 * i10;
109 let mut x = [(i11 * v[0] - i01 * v[1]) / det, (i00 * v[1] - i10 * v[0]) / det];
110 let y = |x: [f64; 2]| out[0] * x[0] + out[1] * x[1];
111 let mut peak = if parts.is_empty() { f64::NAN } else { y(x) };
112 for s in parts {
113 let xs = settled(s);
114 let dx = [x[0] - xs[0], x[1] - xs[1]];
115 let (m, d, ..) = modes(&s.a, 0.0);
116 let (u, w) = (y(dx), y(times(&[[s.a[0][0] - m, s.a[0][1]], [s.a[1][0], s.a[1][1] - m]], dx)));
117 let turn = if d > 1e-12 * m.abs() {
119 let (up, down) = (0.5 * (u + w / d) * (m + d), 0.5 * (u - w / d) * (m - d));
120 (up != 0.0 && -down / up > 0.0).then(|| (-down / up).ln() / (2.0 * d))
121 } else {
122 (w != 0.0).then(|| -(m * u + w) / (m * w))
123 };
124 if let Some(t) = turn.filter(|t| *t > 0.0 && *t < s.len) {
125 let at = times(&flow(s, t), dx);
126 peak = peak.max(y([at[0] + xs[0], at[1] + xs[1]]));
127 }
128 let at = times(&flow(s, s.len), dx);
129 x = [at[0] + xs[0], at[1] + xs[1]];
130 peak = peak.max(y(x));
131 }
132 peak
133}
134
135pub fn winding_stretch(p: &DriveParams, len: f64, rise: f64, iron: f64) -> Stretch {
142 let (c, h) = (crate::drive::COPPER, p.iron_heating(iron));
143 match &p.thermal_nodes {
144 None => {
145 let (q, tau) = ((rise - h) / (1.0 + c * rise), p.thermal_time_constant);
146 Stretch { len, a: [[(c * q - 1.0) / tau, 0.0], [0.0, -2.0 / tau]], b: [(q + h) / tau, 0.0] }
147 }
148 Some(n) => {
149 let (s, tw) = (n.winding_share, n.winding_time_constant);
150 let (q, th) = ((rise - (1.0 - s) * h) / (1.0 + c * rise), p.thermal_time_constant - tw / s);
151 Stretch {
152 len,
153 a: [[(s * q * c - 1.0) / tw, 1.0 / tw], [1.0 / (s * th), -(1.0 / s + 1.0 / (1.0 - s)) / th]],
154 b: [s * q / tw, h / th],
155 }
156 }
157 }
158}
159
160#[derive(Debug, Clone)]
165pub struct MixHeat {
166 pub drive: DriveParams,
167 pub image: Option<[f64; 3]>,
168}
169
170impl MixHeat {
171 pub fn of(cfg: &Config, id: &str) -> Result<Self, ConfigError> {
173 let own = catalog::motor_config(cfg, id)?;
174 let image = match own.positive("ratings.drive_overload_time_constant_s") {
175 Ok(tau) if own.get("ratings.drive_chip_share").is_ok() => Some([
176 tau,
177 own.non_negative("ratings.drive_chip_share")?,
178 own.positive("ratings.drive_chip_time_constant_s")?,
179 ]),
180 Ok(tau) => Some([tau, 0.0, tau]),
181 Err(_) => None,
182 };
183 Ok(Self { drive: DriveParams::from_config(&own, 1.0, 1.0)?, image })
184 }
185}
186
187pub fn mix_verdicts(cfg: &Config, runs: &[(f64, CycleLoad, Vec<Verdict>)]) -> Result<Vec<Verdict>, ConfigError> {
190 let Some((_, first, _)) = runs.first() else { return Ok(Vec::new()) };
191 let heats = first.motors.iter().map(|m| MixHeat::of(cfg, &m.id)).collect::<Result<Vec<_>, _>>()?;
192 Ok(mix_verdicts_with(&heats, runs))
193}
194
195fn heat_peak(parts: &[(f64, f64)], tau: f64) -> f64 {
198 let nodes: Vec<Stretch> = parts.iter().map(|&(len, x)| Stretch::node(len, tau, x * x)).collect();
199 periodic_peak(&nodes, [1.0, 0.0]).sqrt()
200}
201
202pub fn mix_verdicts_with(heats: &[MixHeat], runs: &[(f64, CycleLoad, Vec<Verdict>)]) -> Vec<Verdict> {
214 let mut out: Vec<Verdict> = Vec::new();
215 for v in runs.iter().flat_map(|(_, _, verdicts)| verdicts) {
216 let worse = |v: &Verdict, o: &Verdict| (!v.ok && o.ok) || (v.ok == o.ok && utilisation(v) > utilisation(o));
218 match out.iter_mut().find(|o| o.check == v.check && o.motor == v.motor) {
219 Some(o) => {
220 if worse(v, o) {
221 *o = v.clone();
222 }
223 }
224 None => out.push(v.clone()),
225 }
226 }
227 for o in &mut out {
228 let Some((k, heat)) = o.motor.and_then(|k| Some((k, heats.get(k)?))) else { continue };
229 let duties: Vec<(f64, &Verdict, &MotorLoad)> = runs
231 .iter()
232 .filter_map(|(w, load, verdicts)| {
233 let v = verdicts.iter().find(|v| v.check == o.check && v.motor == Some(k))?;
234 Some((w * load.duration, v, load.motors.get(k)?))
235 })
236 .collect();
237 let p = &heat.drive;
238 match o.check {
239 "motor-thermal" => {
240 o.value = if duties.iter().all(|(_, v, _)| v.value.is_finite()) {
241 let parts: Vec<Stretch> =
242 duties.iter().map(|(len, v, m)| winding_stretch(p, *len, v.value, m.iron_loss)).collect();
243 periodic_peak(&parts, [1.0, 0.0])
244 } else {
245 f64::INFINITY
246 };
247 }
248 "drive-current" => {
249 o.value = match heat.image {
250 Some([tau, share, chip]) => {
251 let parts: Vec<Stretch> = duties
252 .iter()
253 .map(|(len, v, _)| {
254 let q = v.value * v.value;
255 Stretch {
256 len: *len,
257 a: [[-1.0 / tau, 0.0], [0.0, -1.0 / chip]],
258 b: [(1.0 - share) * q / tau, share * q / chip],
259 }
260 })
261 .collect();
262 periodic_peak(&parts, [1.0, 1.0]).sqrt()
263 }
264 None => mix_rms(&duties.iter().map(|(len, v, _)| (1.0, v.value, *len)).collect::<Vec<_>>()),
265 };
266 }
267 "motor-s1" => {
268 o.limit = mix_mean(&duties.iter().map(|(len, v, _)| (1.0, v.limit, *len)).collect::<Vec<_>>());
269 let shares: Vec<(f64, f64)> = duties.iter().map(|(len, v, _)| (*len, v.value / v.limit)).collect();
270 o.value = heat_peak(&shares, p.thermal_time_constant) * o.limit;
271 }
272 _ => continue,
273 }
274 o.ok = o.value <= o.limit;
275 }
276 out
277}
278
279pub fn figures(
283 entry: &MachineEntry,
284 cfg: &Config,
285 motor: &str,
286 runs: &[(f64, CycleLoad, Vec<Verdict>)],
287 estimated: Vec<&'static str>,
288) -> Result<Figures, ConfigError> {
289 let Some((_, first, _)) = runs.first() else { return Ok(Figures::default()) };
290 let verdicts = if runs.len() == 1 { runs[0].2.clone() } else { mix_verdicts(cfg, runs)? };
291 let mut out = Figures { estimated, ..Figures::default() };
292 for v in verdicts.iter().filter(|v| concerns(first, motor, v)) {
293 let u = utilisation(v);
294 match out.checks.iter_mut().find(|(check, _)| *check == v.check) {
295 Some((_, most)) => *most = most.max(u),
296 None => out.checks.push((v.check, u)),
297 }
298 if !v.ok && !out.failing.contains(&v.check) {
299 out.failing.push(v.check);
300 }
301 }
302 let ours = |k: &usize| motor.is_empty() || first.motors[*k].id == motor;
303 let weight: f64 = runs.iter().map(|(w, ..)| w).sum();
304 let highest = |values: Vec<f64>| values.into_iter().filter(|x| !x.is_nan()).reduce(f64::max).unwrap_or(f64::NAN);
305 out.energy_j = runs.iter().map(|(w, load, _)| w * supply_energy(cfg, load)).sum::<f64>() / weight;
306 out.cycle_s = runs.iter().map(|(w, load, _)| w * load.duration).sum::<f64>() / weight;
307 let mut thermal = Vec::new();
308 for (k, m) in first.motors.iter().enumerate().filter(|(k, _)| ours(k)) {
309 let tau = catalog::motor_config(cfg, &m.id)?.positive("motor.thermal_time_constant_s")?;
310 let parts: Vec<(f64, f64)> = runs
311 .iter()
312 .filter_map(|(w, load, _)| load.motors.get(k).map(|m| (w * load.duration, m.thermal_utilisation)))
313 .collect();
314 thermal.push(heat_peak(&parts, tau));
315 }
316 out.thermal = highest(thermal);
317 out.drive_current = out.checks.iter().find(|(c, _)| *c == "drive-current").map_or(f64::NAN, |(_, u)| *u);
318 out.following_error_m = runs.iter().map(|(_, load, _)| load.tracking_error_peak).fold(f64::NAN, f64::max);
319 out.settling_error_m = runs.iter().map(|(_, load, _)| load.dwell_error_peak).fold(f64::NAN, f64::max);
320 out.inertia_ratio = catalog::inertia_ratios(entry, cfg).map_or(f64::NAN, |ratios| {
321 highest(ratios.into_iter().enumerate().filter(|(k, _)| ours(k)).map(|r| r.1).collect())
322 });
323 Ok(out)
324}
325
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
331pub enum Criterion {
332 Cost,
333 Margin,
334 Energy,
335 Error,
336 Thermal,
337 Inertia,
338 Drive,
339 Price,
341}
342
343pub const CRITERIA: [(&str, Criterion); 8] = [
345 ("cost", Criterion::Cost),
346 ("margin", Criterion::Margin),
347 ("energy", Criterion::Energy),
348 ("error", Criterion::Error),
349 ("thermal", Criterion::Thermal),
350 ("inertia", Criterion::Inertia),
351 ("drive", Criterion::Drive),
352 ("price", Criterion::Price),
353];
354
355impl Criterion {
356 pub fn of(self, c: &Candidate) -> f64 {
358 let figure = |f: &dyn Fn(&Figures) -> f64| c.figures.as_ref().map_or(f64::INFINITY, f);
359 let value = match self {
360 Criterion::Cost => c.cost,
361 Criterion::Price => c.price.unwrap_or(f64::INFINITY),
362 Criterion::Margin => c.tightest().map_or(f64::INFINITY, |t| t.1),
363 Criterion::Energy => figure(&|f| f.energy_j),
364 Criterion::Error => figure(&|f| f.following_error_m),
365 Criterion::Thermal => figure(&|f| f.thermal),
366 Criterion::Inertia => figure(&|f| f.inertia_ratio),
367 Criterion::Drive => {
368 catalog::drives_for(c.supply).into_iter().find(|d| d.0 == c.drive).map_or(f64::INFINITY, |d| d.1)
369 }
370 };
371 if value.is_nan() { f64::INFINITY } else { value }
372 }
373}
374
375pub fn parse_ranking(text: &str) -> Option<Vec<(Criterion, f64)>> {
378 text.split(',')
379 .map(|part| {
380 let (name, weight) = part.split_once('=').unwrap_or((part, "1"));
381 let criterion = CRITERIA.iter().find(|(n, _)| *n == name.trim())?.1;
382 let weight: f64 = weight.trim().parse().ok().filter(|w: &f64| *w > 0.0 && w.is_finite())?;
383 Some((criterion, weight))
384 })
385 .collect()
386}
387
388pub fn rank_by(found: &mut [Candidate], by: &[(Criterion, f64)]) {
393 catalog::rank(found);
394 let passing = found.iter().take_while(|c| c.passes()).count();
395 let best: Vec<f64> = by
396 .iter()
397 .map(|(criterion, _)| {
398 let low = found[..passing].iter().map(|c| criterion.of(c)).fold(f64::INFINITY, f64::min);
399 if low > 0.0 && low.is_finite() { low } else { 1.0 }
400 })
401 .collect();
402 let score =
403 |c: &Candidate| by.iter().zip(&best).map(|((criterion, w), best)| w * criterion.of(c) / best).sum::<f64>();
404 found[..passing].sort_by(|a, b| score(a).total_cmp(&score(b)));
405}
406
407pub const FRONT: [Criterion; 5] =
409 [Criterion::Cost, Criterion::Drive, Criterion::Margin, Criterion::Energy, Criterion::Error];
410
411pub fn front(found: &[Candidate]) -> Vec<bool> {
414 let passing: Vec<usize> = (0..found.len()).filter(|&i| found[i].passes()).collect();
415 let figures: Vec<Vec<f64>> = passing.iter().map(|&i| FRONT.iter().map(|c| c.of(&found[i])).collect()).collect();
416 let mut out = vec![false; found.len()];
417 for k in crate::analysis::non_dominated_indices(&figures) {
418 out[passing[k]] = true;
419 }
420 out
421}
422
423pub fn optimum_ratio(load: f64, rotor: f64) -> f64 {
426 (load / rotor).sqrt()
427}
428
429#[derive(Debug, Clone, Default)]
434pub struct SweepRow {
435 pub value: f64,
436 pub torque_per_acceleration: f64,
437 pub inertia_ratio: f64,
438 pub tightest: Option<(&'static str, f64)>,
439 pub passes: bool,
440 pub cycle_s: f64,
441 pub refused: &'static str,
442 pub gearbox: String,
444}
445
446#[derive(Debug, Clone, Default)]
452pub struct TransmissionSweep {
453 pub rows: Vec<SweepRow>,
454 pub classic: f64,
455 pub best: f64,
456 pub snapped: Vec<SweepRow>,
457}
458
459fn torque_need(entry: &MachineEntry, cfg: &Config) -> Result<f64, ConfigError> {
461 Ok(catalog::torque_per_acceleration(entry, cfg)?.iter().flatten().map(|t| t.abs()).sum())
462}
463
464fn sweep_row(entry: &MachineEntry, cfg: Result<Config, ConfigError>, value: f64) -> SweepRow {
466 let mut row = SweepRow {
467 value,
468 torque_per_acceleration: f64::NAN,
469 inertia_ratio: f64::NAN,
470 cycle_s: f64::NAN,
471 ..SweepRow::default()
472 };
473 let Ok(cfg) = cfg else {
474 row.refused = "config";
475 return row;
476 };
477 row.torque_per_acceleration = torque_need(entry, &cfg).unwrap_or(f64::NAN);
478 row.inertia_ratio = catalog::inertia_ratios(entry, &cfg)
479 .map_or(f64::NAN, |r| r.into_iter().filter(|x| !x.is_nan()).fold(f64::NAN, f64::max));
480 let judged = crate::sim::Sim::new(entry, &cfg).map_err(|_| "config").and_then(|mut sim| {
481 let load = crate::analysis::analyse_cycle_with(&mut sim, false).map_err(|e| e.key)?;
482 let v = crate::analysis::verdicts(&cfg, &load).map_err(|_| "config")?;
483 Ok((load, v))
484 });
485 match judged {
486 Ok(result) => {
487 row.cycle_s = result.0.duration;
488 let c = Candidate { result: Some(result), ..Candidate::default() };
489 (row.tightest, row.passes) = (c.tightest(), c.passes());
490 }
491 Err(reason) => row.refused = reason,
492 }
493 row
494}
495
496fn pulley_scaled(cfg: &Config, path: &str, value: f64) -> Result<Config, ConfigError> {
501 let mut out = cfg.clone();
502 if let ("geometry.pulley_radius_m", Ok(_)) = (path, cfg.get("pulley.inertia_kgm2")) {
503 let inertia = cfg.positive("pulley.inertia_kgm2")? * (value / cfg.positive(path)?).powi(4);
504 out.set_text(&format!("pulley.inertia_kgm2 = {inertia:?}"))?;
505 }
506 Ok(out)
507}
508
509pub fn transmission_sweep(
516 entry: &MachineEntry,
517 cfg: &Config,
518 path: &str,
519 (from, to, count): (f64, f64, usize),
520 snap: Option<(&str, &str, &str)>,
521) -> Result<TransmissionSweep, ConfigError> {
522 let cfg = &catalog::resolve(entry, cfg)?;
523 if !(from > 0.0 && to > from && count >= 2) {
524 return Err(ConfigError::Invalid(format!("{path} from {from} to {to}, {count} values")));
525 }
526 cfg.positive(path)?;
527 let need = |value: f64| -> Result<f64, ConfigError> {
528 let mut changed = pulley_scaled(cfg, path, value)?;
529 changed.set_text(&format!("{path} = {value:?}"))?;
530 torque_need(entry, &changed)
531 };
532 let (mut low, mut high) = (from.ln(), to.ln());
534 let golden = (5f64.sqrt() - 1.0) / 2.0;
535 while high - low > 1e-7 {
536 let (a, b) = (high - golden * (high - low), low + golden * (high - low));
537 if need(a.exp())? <= need(b.exp())? { high = b } else { low = a }
538 }
539 let classic = ((low + high) / 2.0).exp();
540 let mut values = crate::analysis::log_spaced(from, to, count);
541 values.push(classic);
542 values.sort_by(f64::total_cmp);
543 let rows = crate::analysis::on_all_cores(values.len(), |i| {
544 sweep_row(
545 entry,
546 pulley_scaled(cfg, path, values[i]).and_then(|c| catalog::with_value(entry, &c, path, values[i])),
547 values[i],
548 )
549 });
550 let key = |r: &SweepRow| (!r.passes, r.tightest.map_or(f64::INFINITY, |t| t.1));
551 let best = rows
552 .iter()
553 .min_by(|a, b| key(a).0.cmp(&key(b).0).then(key(a).1.total_cmp(&key(b).1)))
554 .map_or(classic, |r| r.value);
555 let mut snapped = Vec::new();
556 if let (Some((series, article, supply)), "gearbox.ratio") = (snap, path) {
557 let names = catalog::fitting_gearboxes(article, series, best);
558 snapped = crate::analysis::on_all_cores(names.len(), |i| {
559 let parts = catalog::Parts { motor: article, supply, gearbox: &names[i], ..catalog::Parts::default() };
560 let named = catalog::with_named(entry, cfg, &parts);
561 let ratio = named.as_ref().ok().and_then(|c| c.f64("gearbox.ratio").ok()).unwrap_or(f64::NAN);
562 SweepRow { gearbox: names[i].clone(), ..sweep_row(entry, named, ratio) }
563 });
564 }
565 Ok(TransmissionSweep { rows, classic, best, snapped })
566}
567
568#[derive(Debug, Clone, Default)]
572pub struct RobustRow {
573 pub index: usize,
574 pub passes: bool,
575 pub tightest: Option<(&'static str, f64)>,
576 pub runs: usize,
577 pub refused: String,
578}
579
580pub fn robust_ranking(
587 entry: &MachineEntry,
588 cfg: &Config,
589 duties: &[(Config, f64)],
590 found: &[Candidate],
591 top: usize,
592) -> (Vec<RobustRow>, bool) {
593 let bases: Vec<&Config> = if duties.is_empty() { vec![cfg] } else { duties.iter().map(|d| &d.0).collect() };
594 let chosen: Vec<usize> = (0..found.len()).filter(|&i| found[i].passes()).take(top).collect();
595 let mut rows = crate::analysis::on_all_cores(chosen.len(), |n| {
596 let (index, c) = (chosen[n], &found[chosen[n]]);
597 let load = c.result.as_ref().map(|r| r.0.clone()).unwrap_or_else(|| unreachable!("a passing candidate ran"));
598 let judged = || -> Result<RobustRow, ConfigError> {
599 let (mut runs, mut mixed, mut first) = (0, Vec::new(), None);
600 for (i, base) in bases.iter().enumerate() {
601 let own = catalog::candidate_config(entry, base, c)?;
602 let (worst, done) = crate::analysis::verdict_worst(entry, &own, &crate::analysis::bounds(&own)?)?;
603 runs += done;
604 let (weight, cycle) = c.duties.get(i).map_or((1.0, &load), |(w, cycle)| (*w, cycle));
605 mixed.push((weight, cycle.clone(), worst.into_iter().map(|w| w.verdict).collect::<Vec<_>>()));
606 first.get_or_insert(own);
607 }
608 let verdicts = match (&mixed[..], &first) {
609 ([one], _) => one.2.clone(),
610 (_, Some(own)) => mix_verdicts(own, &mixed)?,
611 _ => Vec::new(),
612 };
613 let at_worst = Candidate { result: Some((load.clone(), verdicts)), ..c.clone() };
614 Ok(RobustRow {
615 index,
616 passes: at_worst.passes(),
617 tightest: at_worst.tightest(),
618 runs,
619 refused: String::new(),
620 })
621 };
622 judged().unwrap_or_else(|e| RobustRow {
623 index,
624 refused: format!("{}: {}", e.key(), e.detail()),
625 ..RobustRow::default()
626 })
627 });
628 rows.sort_by_key(|r| (!r.passes, r.index));
629 let changed = rows.iter().map(|r| r.index).ne(chosen.iter().copied());
630 (rows, changed)
631}
632
633#[derive(Debug, Clone, Default, PartialEq)]
639pub struct Task {
640 pub pick: [f64; 3],
641 pub place: [f64; 3],
642 pub via: Vec<[f64; 3]>,
643 pub lift_m: f64,
644 pub dwell_s: f64,
645 pub payload_kg: Option<f64>,
646 pub cycle_time_s: Option<f64>,
647 pub set: Vec<String>,
648 pub origin: Vec<(String, Vec<f64>)>,
649}
650
651#[derive(Debug, Clone, PartialEq)]
656pub struct Refusal {
657 pub key: &'static str,
658 pub detail: String,
659}
660
661impl Task {
662 pub fn parse(text: &str) -> Result<Task, String> {
666 let table: toml::Table = text.parse().map_err(|e: toml::de::Error| e.message().to_string())?;
667 let number = |v: &toml::Value| v.as_float().or_else(|| v.as_integer().map(|i| i as f64));
668 let point = |key: &str, v: &toml::Value| -> Result<[f64; 3], String> {
669 let list = v.as_array().filter(|a| a.len() == 3).ok_or(format!("{key}: three numbers x, y, z"))?;
670 let mut out = [0.0; 3];
671 for (o, v) in out.iter_mut().zip(list) {
672 *o = number(v).filter(|x| x.is_finite()).ok_or(format!("{key}: three numbers x, y, z"))?;
673 }
674 Ok(out)
675 };
676 let scalar = |key: &str| -> Result<Option<f64>, String> {
677 table
678 .get(key)
679 .map(|v| number(v).filter(|x| x.is_finite() && *x >= 0.0).ok_or(format!("{key}: a number")))
680 .transpose()
681 };
682 let known = [
683 "pick",
684 "place",
685 "via",
686 "lift_m",
687 "dwell_s",
688 "payload_kg",
689 "cycle_time_s",
690 "rate_per_min",
691 "set",
692 "origin",
693 ];
694 if let Some(key) = table.keys().find(|k| !known.contains(&k.as_str())) {
695 return Err(format!("{key}: not a key of a task"));
696 }
697 let cycle_time_s = match (scalar("cycle_time_s")?, scalar("rate_per_min")?) {
698 (Some(_), Some(_)) => return Err("cycle_time_s, rate_per_min: one of them".into()),
699 (time, rate) => time.or(rate.map(|r| 60.0 / r)),
700 };
701 Ok(Task {
702 pick: point("pick", table.get("pick").ok_or("pick: missing")?)?,
703 place: point("place", table.get("place").ok_or("place: missing")?)?,
704 via: match table.get("via") {
705 None => Vec::new(),
706 Some(v) => v
707 .as_array()
708 .ok_or("via: a list of points")?
709 .iter()
710 .map(|p| point("via", p))
711 .collect::<Result<_, _>>()?,
712 },
713 lift_m: scalar("lift_m")?.unwrap_or(0.0),
714 dwell_s: scalar("dwell_s")?.unwrap_or(0.0),
715 payload_kg: scalar("payload_kg")?,
716 cycle_time_s,
717 set: match table.get("set") {
718 None => Vec::new(),
719 Some(v) => v
720 .as_array()
721 .ok_or("set: a list of assignments")?
722 .iter()
723 .map(|s| s.as_str().map(str::to_string).ok_or("set: a list of assignments"))
724 .collect::<Result<_, _>>()?,
725 },
726 origin: match table.get("origin") {
727 None => Vec::new(),
728 Some(v) => v
729 .as_table()
730 .ok_or("origin: a table of machine id = [values]")?
731 .iter()
732 .map(|(id, values)| {
733 let values = values.as_array().ok_or(format!("origin.{id}: a list of numbers"))?;
734 let values = values.iter().map(number).collect::<Option<Vec<f64>>>();
735 Ok((id.clone(), values.ok_or(format!("origin.{id}: a list of numbers"))?))
736 })
737 .collect::<Result<_, String>>()?,
738 },
739 })
740 }
741}
742
743pub fn task_config(entry: &MachineEntry, cfg: &Config, task: &Task) -> Result<Config, Refusal> {
750 let refuse = |key: &'static str, detail: String| Refusal { key, detail };
751 let config_error = |e: ConfigError| refuse("task-set", format!("{}: {}", e.key(), e.detail()));
752 let cfg = catalog::resolve(entry, cfg).map_err(config_error)?;
753 let machine = (entry.build)(&cfg).map_err(config_error)?;
754 let axes = machine.axes();
755 let origin = match task.origin.iter().find(|(id, _)| id == entry.id) {
756 Some((_, values)) if values.len() != axes.len() => {
757 return Err(refuse(
758 "task-origin",
759 format!("{}: {} values for {} axes", entry.id, values.len(), axes.len()),
760 ));
761 }
762 Some((_, values)) => values.clone(),
763 None => sim_core::testkit::mid_pose(machine.as_ref()),
764 };
765 let column = |letter: &str| axes.iter().position(|a| a.id == letter && a.unit == "m");
766 let columns: Vec<Option<usize>> = ["x", "y", "z"].iter().map(|l| column(l)).collect();
767 let pose = |p: [f64; 3]| -> Result<Vec<f64>, Refusal> {
768 let mut out = origin.clone();
769 for (i, value) in p.iter().enumerate() {
770 match columns[i] {
771 Some(a) => out[a] += value,
772 None if *value != 0.0 => return Err(refuse("task-axis-missing", ["x", "y", "z"][i].into())),
773 None => {}
774 }
775 }
776 for (a, (value, axis)) in out.iter().zip(axes).enumerate() {
777 if *value < axis.min - 1e-9 || *value > axis.max + 1e-9 {
778 return Err(refuse(
779 "task-out-of-range",
780 format!("{} = {value} {} beyond {} .. {} (axis {a})", axis.id, axis.unit, axis.min, axis.max),
781 ));
782 }
783 }
784 if let Some(key) = machine.unreachable(&out, 0.0) {
785 return Err(refuse(key, format!("{out:?}")));
786 }
787 Ok(out)
788 };
789 let up = |p: [f64; 3]| [p[0], p[1], p[2] + task.lift_m];
790 let (pick, place) = (pose(task.pick)?, pose(task.place)?);
791 let (above_pick, above_place) = (pose(up(task.pick))?, pose(up(task.place))?);
792 let via: Vec<Vec<f64>> = task.via.iter().map(|p| pose(*p)).collect::<Result<_, _>>()?;
793 let list = |pose: &[f64]| toml::Value::Array(pose.iter().map(|v| toml::Value::Float(*v)).collect());
794 let segment = |target: &[f64], dwell: f64, payload: bool, via: &[Vec<f64>]| {
795 let mut s = toml::Table::new();
796 s.insert("target".into(), list(target));
797 s.insert("dwell_s".into(), toml::Value::Float(dwell));
798 s.insert("payload".into(), toml::Value::Boolean(payload));
799 if !via.is_empty() {
800 s.insert("via".into(), toml::Value::Array(via.iter().map(|p| list(p)).collect()));
801 }
802 toml::Value::Table(s)
803 };
804 let back: Vec<Vec<f64>> = via.iter().rev().cloned().collect();
805 let cycle = toml::Value::Array(vec![
806 segment(&pick, task.dwell_s, true, &[]),
807 segment(&above_pick, 0.0, true, &[]),
808 segment(&above_place, 0.0, true, &via),
809 segment(&place, task.dwell_s, false, &[]),
810 segment(&above_place, 0.0, false, &[]),
811 segment(&above_pick, 0.0, false, &back),
812 ]);
813 let mut out = cfg.clone();
814 out.set("start.pose", list(&above_pick)).map_err(config_error)?;
815 out.set("cycle.segment", cycle).map_err(config_error)?;
816 match task.payload_kg {
817 Some(kg) if out.get("mass.payload_kg").is_ok() => {
818 out.set_text(&format!("mass.payload_kg = {kg:?}")).map_err(config_error)?
819 }
820 Some(kg) if kg > 0.0 => return Err(refuse("task-payload", format!("{kg} kg"))),
821 _ => {}
822 }
823 for assignment in &task.set {
824 out.set_text(assignment).map_err(config_error)?;
825 }
826 Ok(out)
827}
828
829#[derive(Debug, Clone)]
833pub struct KinematicsRow {
834 pub machine: String,
835 pub refused: Option<Refusal>,
836 pub best: Option<Candidate>,
837 pub passing: usize,
838 pub tried: usize,
839 pub target_s: Option<f64>,
840}
841
842impl KinematicsRow {
843 pub fn meets(&self) -> bool {
845 let fast =
846 |c: &Candidate| self.target_s.is_none_or(|t| c.figures.as_ref().is_some_and(|f| f.cycle_s <= t + 1e-9));
847 self.best.as_ref().is_some_and(|c| c.passes() && fast(c))
848 }
849}
850
851pub fn compare_kinematics(
855 task: &Task,
856 machines: &[(&MachineEntry, Config)],
857 supplies: &dyn Fn(&Config) -> Vec<&'static str>,
858 wanted: &dyn Fn(&str) -> bool,
859 options: &Options,
860 by: &[(Criterion, f64)],
861) -> Vec<KinematicsRow> {
862 machines
863 .iter()
864 .map(|(entry, cfg)| {
865 let mut row = KinematicsRow {
866 machine: entry.id.to_string(),
867 refused: None,
868 best: None,
869 passing: 0,
870 tried: 0,
871 target_s: task.cycle_time_s,
872 };
873 let mapped = match task_config(entry, cfg, task) {
874 Ok(mapped) => mapped,
875 Err(refusal) => return KinematicsRow { refused: Some(refusal), ..row },
876 };
877 match catalog::search(entry, &mapped, &supplies(&mapped), wanted, options) {
878 Ok(mut found) => {
879 rank_by(&mut found, by);
880 row.passing = found.iter().filter(|c| c.passes()).count();
881 row.tried = found.len();
882 row.best = found.into_iter().next();
883 }
884 Err(e) => {
885 row.refused = Some(Refusal { key: "task-set", detail: format!("{}: {}", e.key(), e.detail()) })
886 }
887 }
888 row
889 })
890 .collect()
891}
892
893#[cfg(test)]
894mod tests {
895 use super::*;
896
897 #[test]
901 fn a_two_cycle_duty_mix_has_the_time_weighted_rms() {
902 let parts = [(3.0, 2.0, 1.0), (1.0, 4.0, 2.0)];
903 assert!((mix_rms(&parts) - (44.0f64 / 5.0).sqrt()).abs() < 1e-12, "{}", mix_rms(&parts));
904 assert!((mix_mean(&[(3.0, 10.0, 1.0), (1.0, 40.0, 2.0)]) - 22.0).abs() < 1e-12);
905 }
906
907 fn heat(tau: f64, image: Option<[f64; 3]>) -> MixHeat {
910 MixHeat { drive: DriveParams { thermal_time_constant: tau, ..crate::drive::tests::params() }, image }
911 }
912
913 #[test]
921 fn a_duty_mix_is_judged_on_the_worst_peak_and_the_heat_of_its_periodic_state() {
922 let load = |duration: f64, rise: f64, current: f64| CycleLoad {
923 duration,
924 motors: vec![MotorLoad { winding_rise: rise, rms_current: current, ..MotorLoad::default() }],
925 ..test_load()
926 };
927 let verdicts = |rise: f64, current: f64, peak: f64| {
928 vec![
929 Verdict { check: "motor-peak", motor: Some(0), value: peak, limit: 1.0, ok: peak <= 1.0 },
930 Verdict { check: "motor-thermal", motor: Some(0), value: rise, limit: 30.0, ok: rise <= 30.0 },
931 Verdict { check: "drive-current", motor: Some(0), value: current, limit: 3.0, ok: current <= 3.0 },
932 ]
933 };
934 let runs = vec![
935 (3.0, load(1.0, 10.0, 2.0), verdicts(10.0, 2.0, 0.5)),
936 (1.0, load(2.0, 40.0, 4.0), verdicts(40.0, 4.0, 0.9)),
937 ];
938 let c = crate::drive::COPPER;
939 let q = |t: f64| t / (1.0 + c * t);
940 let mean = (3.0 * q(10.0) + 2.0 * q(40.0)) / 5.0;
941 assert!((mean / (1.0 - c * mean) - 21.240).abs() < 1e-3);
942 for (tau, rise, current, ok) in
943 [(1e9, mean / (1.0 - c * mean), (44.0f64 / 5.0).sqrt(), true), (1e-6, 40.0, 4.0, false)]
944 {
945 let mixed = mix_verdicts_with(&[heat(tau, Some([tau, 0.0, tau]))], &runs);
946 let get = |check: &str| mixed.iter().find(|v| v.check == check).unwrap().clone();
947 assert_eq!(get("motor-peak").value, 0.9);
948 let (thermal, drive) = (get("motor-thermal"), get("drive-current"));
949 assert!((thermal.value - rise).abs() < 1e-6 && thermal.ok == ok, "{tau}: {thermal:?}");
950 assert!((drive.value - current).abs() < 1e-6 && drive.ok == ok, "{tau}: {drive:?}");
951 }
952 let mixed = mix_verdicts_with(&[heat(1e-6, None)], &runs);
954 assert!((mixed[2].value - (44.0f64 / 5.0).sqrt()).abs() < 1e-12, "{:?}", mixed[2]);
955 }
956
957 #[test]
963 fn a_duty_mix_judges_the_periodic_peak_of_the_winding_node() {
964 let c = crate::drive::COPPER;
965 let e = |t: f64| (-1.0 / (1.0 + c * t)).exp();
966 let (e1, e2) = (e(10.0), e(30.0));
967 let hand = (30.0 * (1.0 - e2) + 10.0 * (1.0 - e1) * e2) / (1.0 - e1 * e2);
968 assert!((hand - 24.017).abs() < 1e-3, "{hand}");
969 let p = heat(1.0, None).drive;
970 let parts = [winding_stretch(&p, 1.0, 10.0, 0.0), winding_stretch(&p, 1.0, 30.0, 0.0)];
971 assert!((periodic_peak(&parts, [1.0, 0.0]) - hand).abs() < 1e-12, "{}", periodic_peak(&parts, [1.0, 0.0]));
972 assert!((periodic_peak(&parts[1..], [1.0, 0.0]) - 30.0).abs() < 1e-12);
974 }
975
976 #[test]
980 fn the_periodic_peak_of_the_two_winding_nodes_matches_the_integrated_nodes() {
981 let p = DriveParams {
982 thermal_nodes: Some(crate::drive::ThermalNodes { winding_share: 0.25, winding_time_constant: 60.0 }),
983 ..heat(1800.0, None).drive
984 };
985 let duties = [(300.0, 2.5), (600.0, 1.0)];
986 let parts: Vec<Stretch> =
987 duties.iter().map(|&(len, i)| winding_stretch(&p, len, p.settled_rise(i, 0.0), 0.0)).collect();
988 let closed = periodic_peak(&parts, [1.0, 0.0]);
989 let (s, tw) = (0.25, 60.0);
990 let th = 1800.0 - tw / s;
991 let f = |[w, h]: [f64; 2], i: f64| {
992 let heating = p.iron_heating(i * i * p.resistance_at(w));
993 [(s * heating - (w - h)) / tw, ((w - h) / s - h / (1.0 - s)) / th]
994 };
995 let (dt, mut x, mut peak) = (0.1, [0.0, 0.0], 0.0f64);
996 for period in 0..30 {
997 for &(len, i) in &duties {
998 for _ in 0..(len / dt) as usize {
999 let add = |x: [f64; 2], k: [f64; 2], h: f64| [x[0] + h * k[0], x[1] + h * k[1]];
1000 let k1 = f(x, i);
1001 let k2 = f(add(x, k1, dt / 2.0), i);
1002 let k3 = f(add(x, k2, dt / 2.0), i);
1003 let k4 = f(add(x, k3, dt), i);
1004 x = [0, 1].map(|j| x[j] + dt / 6.0 * (k1[j] + 2.0 * k2[j] + 2.0 * k3[j] + k4[j]));
1005 if period == 29 {
1006 peak = peak.max(x[0]);
1007 }
1008 }
1009 }
1010 }
1011 assert!((closed - peak).abs() < 1e-5, "closed {closed}, integrated {peak}");
1012 }
1013
1014 #[test]
1019 fn a_duty_mix_judges_the_drives_image_with_its_chips() {
1020 let node = |share: f64, tau: f64| {
1021 let (ea, eb) = ((-10.0 / tau).exp(), (-5.0 / tau).exp());
1022 (share * 16.0 * (1.0 - eb) + share * 4.0 * (1.0 - ea) * eb) / (1.0 - ea * eb)
1023 };
1024 let hand = (node(0.7, 100.0) + node(0.3, 2.0)).sqrt();
1025 assert!((hand - 3.2012).abs() < 1e-4, "{hand}");
1026 let duty = |duration: f64, current: f64| {
1027 let v = Verdict { check: "drive-current", motor: Some(0), value: current, limit: 5.0, ok: true };
1028 (1.0, CycleLoad { duration, ..test_load() }, vec![v])
1029 };
1030 let mixed = mix_verdicts_with(&[heat(1800.0, Some([100.0, 0.3, 2.0]))], &[duty(10.0, 2.0), duty(5.0, 4.0)]);
1031 assert!((mixed[0].value - hand).abs() < 1e-9, "{:?}", mixed[0]);
1032 }
1033
1034 #[test]
1039 fn a_duty_mix_is_judged_on_s1_by_its_utilisation_in_the_winding_node() {
1040 let load = |duration: f64| CycleLoad { duration, ..test_load() };
1041 let verdict = |value: f64, limit: f64| {
1042 vec![Verdict { check: "motor-s1", motor: Some(0), value, limit, ok: value <= limit }]
1043 };
1044 let runs = vec![(3.0, load(1.0), verdict(2.0, 4.5)), (1.0, load(2.0), verdict(4.0, 3.5))];
1045 let u: f64 = ((3.0 * (2.0f64 / 4.5).powi(2) + 2.0 * (4.0f64 / 3.5).powi(2)) / 5.0).sqrt();
1046 assert!((u - 0.80060).abs() < 1e-5);
1047 let s1 = &mix_verdicts_with(&[heat(1e9, None)], &runs)[0];
1048 assert!((s1.value - u * 4.1).abs() < 1e-6 && (s1.limit - 4.1).abs() < 1e-12 && s1.ok, "{s1:?}");
1049 let s1 = &mix_verdicts_with(&[heat(1e-6, None)], &runs)[0];
1050 assert!((s1.value / s1.limit - 4.0 / 3.5).abs() < 1e-9 && !s1.ok, "{s1:?}");
1051 }
1052
1053 #[test]
1056 fn a_swept_pulley_radius_scales_the_pulley_inertia_with_r4() {
1057 let cfg =
1058 Config::parse("format_version = 1\n[geometry]\npulley_radius_m = 0.01\n[pulley]\ninertia_kgm2 = 2.0e-5\n")
1059 .unwrap();
1060 let scaled = pulley_scaled(&cfg, "geometry.pulley_radius_m", 0.02).unwrap();
1061 assert!((scaled.f64("pulley.inertia_kgm2").unwrap() - 3.2e-4).abs() < 1e-15);
1062 assert_eq!(pulley_scaled(&cfg, "gearbox.ratio", 0.02).unwrap().f64("pulley.inertia_kgm2").unwrap(), 2.0e-5);
1063 let bare = Config::parse("format_version = 1\n[geometry]\npulley_radius_m = 0.01\n").unwrap();
1064 assert!(pulley_scaled(&bare, "geometry.pulley_radius_m", 0.02).unwrap().get("pulley.inertia_kgm2").is_err());
1065 }
1066
1067 #[test]
1069 fn the_optimum_ratio_of_a_pure_inertia_is_the_root_of_the_inertia_ratio() {
1070 assert!((optimum_ratio(0.0025, 0.3e-4) - 9.128709).abs() < 1e-6);
1071 }
1072
1073 #[test]
1075 fn a_ranking_is_one_criterion_or_a_weighted_mix() {
1076 assert_eq!(parse_ranking("energy"), Some(vec![(Criterion::Energy, 1.0)]));
1077 assert_eq!(parse_ranking("cost=1, error=0.5"), Some(vec![(Criterion::Cost, 1.0), (Criterion::Error, 0.5)]));
1078 assert_eq!(parse_ranking("price"), Some(vec![(Criterion::Price, 1.0)]));
1079 assert_eq!(parse_ranking("weight"), None);
1080 assert_eq!(parse_ranking("cost=-1"), None);
1081 }
1082
1083 #[test]
1088 fn a_search_ranks_by_any_criterion_and_marks_its_front() {
1089 let pass = vec![Verdict { check: "motor-peak", motor: Some(0), value: 0.5, limit: 1.0, ok: true }];
1090 let candidate = |cost: f64, energy: f64| Candidate {
1091 cost,
1092 result: Some((test_load(), pass.clone())),
1093 figures: Some(Figures { energy_j: energy, following_error_m: 1e-4, ..Figures::default() }),
1094 ..Candidate::default()
1095 };
1096 let mut found = vec![candidate(30.0, 150.0), candidate(10.0, 300.0), candidate(20.0, 100.0)];
1097 let costs = |found: &[Candidate]| found.iter().map(|c| c.cost).collect::<Vec<_>>();
1098 rank_by(&mut found, &[(Criterion::Cost, 1.0)]);
1099 assert_eq!(costs(&found), [10.0, 20.0, 30.0]);
1100 rank_by(&mut found, &[(Criterion::Energy, 1.0)]);
1101 assert_eq!(costs(&found), [20.0, 30.0, 10.0]);
1102 rank_by(&mut found, &parse_ranking("cost=1,energy=1").unwrap());
1103 assert_eq!(costs(&found), [20.0, 10.0, 30.0]);
1104 assert_eq!(front(&found), [true, true, false]);
1105 }
1106
1107 fn test_load() -> CycleLoad {
1108 CycleLoad { duration: 1.0, motors: vec![MotorLoad::default()], ..CycleLoad::default() }
1109 }
1110}