Skip to main content

sim_components/
search.rs

1//! The catalogue search as a workflow: which drive works best with which path and kinematics. `catalog::search` tries
2//! the parts; this module gives each candidate the figures of a wide table (`Figures`), judges it over a duty mix
3//! (`mix_verdicts`), ranks by one criterion or a weighted mix of them (`rank_by`), marks the non-dominated ones
4//! (`front`), sweeps a gear ratio or pulley radius for the optimum (`transmission_sweep`), ranks the best again in the
5//! error bands (`robust_ranking`), and runs one tool-space task on several kinematics (`compare_kinematics`).
6
7use 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/// One candidate's figures beside its parts, the columns of the search's table. A figure the run does not give is NaN.
13#[derive(Debug, Clone, Default, PartialEq)]
14pub struct Figures {
15    /// Per check (verdict id) its utilisation (`analysis::utilisation`, above 1 it fails), the highest over the motors
16    /// (for one motor's search, `Candidate::motor`, that motor's and the machine's), in the order they come up.
17    pub checks: Vec<(&'static str, f64)>,
18    /// The checks that fail, in that order.
19    pub failing: Vec<&'static str>,
20    /// Energy from the supply per cycle, J (`analysis::supply_energy`); over a duty mix per cycle of the mix, weighted.
21    pub energy_j: f64,
22    /// RMS torque over continuous torque (`MotorLoad::thermal_utilisation`), the highest of the motors; over a duty mix
23    /// the highest the motor's node takes it to (`mix_verdicts_with`, as "motor-s1").
24    pub thermal: f64,
25    /// The drive's RMS current over its rated current ("drive-current"; over a mix as `mix_verdicts_with` has it).
26    pub drive_current: f64,
27    /// The most the tool lagged behind its setpoint (`CycleLoad::tracking_error_peak`), m; the worst duty's.
28    pub following_error_m: f64,
29    /// The most the tool was off its target late in a dwell (`CycleLoad::dwell_error_peak`), m; the worst duty's.
30    pub settling_error_m: f64,
31    /// Load over rotor inertia (`catalog::inertia_ratios`), the highest of the motors (or the one motor's).
32    pub inertia_ratio: f64,
33    /// Cycle time, s; over a duty mix the mean per cycle, weighted.
34    pub cycle_s: f64,
35    /// What the motor and drive leave to the config's estimates (`catalog::estimated_data`); empty: all from the catalogue.
36    pub estimated: Vec<&'static str>,
37}
38
39/// Whether a verdict concerns the motor `motor` of a load (by id), or the machine; every one for `motor` "".
40fn 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
44/// The time-weighted RMS of a figure over a duty mix: (weight, the figure's RMS over the cycle, the cycle's time) per
45/// duty, sqrt(sum w RMS^2 t / sum w t). Each duty runs its cycle w times as often as one of weight 1. NaN for no time.
46pub 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
51/// The time-weighted mean of a figure over a duty mix, (weight, figure, time) per duty: sum w x t / sum w t.
52pub 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/// One stretch of a sequence that repeats, on a linear model of two states: held for `len`, x' = a x + b.
58#[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    /// A first-order node of time constant `tau` that settles at `target` (the second state is not used).
67    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
72/// The two eigenvalues m + d and m - d of `a` (real, as a thermal network's are; d clamped at 0), and the weights of
73/// e^{a t} = p I + q (a - m I) at `t`: p = (e^{(m+d) t} + e^{(m-d) t}) / 2, q = (e^{(m+d) t} - e^{(m-d) t}) / (2 d),
74/// which is t e^{m t} for d t near 0 (Cayley-Hamilton).
75fn 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
83/// The peak of `out` . x over the periodic state of a linear model of two states driven through `parts` in order, over
84/// and over (each a `Stretch`). Over a stretch x = x* + e^{a t} (x0 - x*), x* = -a^-1 b, so a period maps x0 to
85/// M x0 + v and the periodic state is (I - M)^-1 v. Within a stretch out . x = y* + c+ e^{(m+d) t} + c- e^{(m-d) t}
86/// (`modes`), which has at most one turning point, where e^{2 d t} = -c- (m-d) / (c+ (m+d)); the peak is at a stretch's
87/// end or there. NaN for no stretch.
88pub 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    // Over one period x_end = mm x0 + v.
99    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        // The turning point of y* + p u + q w (`modes`), where it lies within the stretch.
118        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
135/// The winding's model (`Drive::warm`) held for `len` at a duty that settles it at `rise` with the mean iron loss `iron`
136/// (W, effects.iron_loss): in rises it would settle at alone, q the copper heating at no rise and h the iron's, the
137/// copper's resistance rising by c per kelvin: one node tau T' = q (1 + c T) + h - T, or with effects.motor_thermal_nodes
138/// the winding tau_w T_w' = s q (1 + c T_w) - (T_w - T_h) and the housing tau_h T_h' = (T_w - T_h) / s - T_h / (1 - s) + h,
139/// tau_h = tau - tau_w / s. Both settle at T_w = (q + h_w) / (1 - c q) (`DriveParams::settled_rise`; h_w = h, or (1 - s) h
140/// with two nodes), so q = (rise - h_w) / (1 + c rise).
141pub 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/// What the heat of a duty mix is worked out with, per motor: its drive model (the winding's nodes, `winding_stretch`)
161/// and the drive's thermal image as `drive::Overload` has it, [tau, chip share, chip tau]
162/// (`ratings.drive_overload_time_constant_s`, `drive_chip_share`, `drive_chip_time_constant_s`; no chips where the
163/// config lacks the share), `None` where the config has no time constant for it.
164#[derive(Debug, Clone)]
165pub struct MixHeat {
166    pub drive: DriveParams,
167    pub image: Option<[f64; 3]>,
168}
169
170impl MixHeat {
171    /// Motor `id`'s (`catalog::motor_config`).
172    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
187/// The verdicts of a duty mix on `cfg` (the first duty's; the motors and drives are the same in all), (weight, cycle,
188/// verdicts) per duty: `mix_verdicts_with` each motor's `MixHeat`.
189pub 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
195/// A figure of a mix whose square is a heat that a first-order node of time constant `tau` takes up, (duration, the
196/// figure) per duty: the root of the node's periodic peak (`periodic_peak`). One duty: its own figure.
197fn 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
202/// The verdicts of a duty mix, (weight, cycle, verdicts) per duty, each motor's heat with `heats` (in the order of the
203/// cycles' motors): per check and motor the worst duty's (failing before passing, then the highest utilisation), but the
204/// heat over the mix, as the duties take turns, each for its weight times its cycle time and in the order given, over
205/// and over (the periodic state, `periodic_peak`): "motor-thermal" the highest winding rise, the winding's model driven
206/// by each duty's (`winding_stretch`, with its iron loss); "drive-current" the root of the highest of the drive's
207/// thermal image driven by each duty's mean square current, where the config has its time constant (else the
208/// time-weighted RMS, `mix_rms`); "motor-s1" the highest S1 utilisation, each duty's RMS torque over its S1 limit
209/// squared into the motor's one node (`motor.thermal_time_constant_s`), shown as that share of the time-weighted mean
210/// of the duties' limits. Duties much shorter than the time constants give the heat of the mix's mean, much longer
211/// ones the worst duty's own. The values are the duties' verdicts', so worst-corner verdicts mix the same way
212/// (`robust_ranking`).
213pub 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        // Failing before passing, then the higher utilisation.
217        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        // Per duty that judged this check: (duration, its verdict, the motor's load).
230        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
279/// The figures of a candidate that ran: `cfg` its config (the first duty's), `motor` the one motor searched ("" all),
280/// `runs` (weight, cycle, verdicts) per duty, `estimated` from `catalog::estimated_data`. Over a mix the verdicts are
281/// `mix_verdicts`, and the thermal utilisation goes into each motor's one node as the S1 check's does.
282pub 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/// What a search can be ranked by (`rank_by`), lower better: the cost (`Candidate::cost`), the margin (the tightest
327/// check's utilisation, `Candidate::tightest`), the energy per cycle, the following error, the thermal utilisation, the
328/// inertia ratio (`Figures`), and the drive's size, its rated output current (`catalog::drives_for`; the catalogue
329/// has no weight of a drive, so the cost leaves it out).
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
331pub enum Criterion {
332    Cost,
333    Margin,
334    Energy,
335    Error,
336    Thermal,
337    Inertia,
338    Drive,
339    /// The user's price (`Candidate::price`, from `--prices`); infinite for a candidate without one.
340    Price,
341}
342
343/// The criteria by the names `--rank-by` takes.
344pub 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    /// The candidate's figure for it; infinite where it has none.
357    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
375/// A ranking as `--rank-by` names it: one criterion of `CRITERIA` ("energy"), or a weighted mix ("cost=1,energy=0.5";
376/// a name alone weighs 1). `None` for a name it does not know or a weight that is no positive number.
377pub 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
388/// Ranks a search (`catalog::rank`: passing first, the others nearest to passing first) and orders the passing ones by
389/// `by`: the sum of each criterion's weight times its figure over the best (lowest) figure of the passing ones, so
390/// that criteria of different units weigh as their weights say (a figure at or below 0 is taken over 1, as it is). For
391/// one criterion its figure; ties keep the cost order.
392pub 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
407/// The criteria the search's front is drawn over: cost, the drive's size, margin, energy and following error.
408pub const FRONT: [Criterion; 5] =
409    [Criterion::Cost, Criterion::Drive, Criterion::Margin, Criterion::Energy, Criterion::Error];
410
411/// Which candidates are on the search's front: passing, and no other passing one is as good in every criterion of
412/// `FRONT` and better in one (`analysis::non_dominated_indices`). One of two alike is on it.
413pub 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
423/// The gear ratio at which a motor of rotor inertia `rotor` accelerates a pure inertia `load` (at the gearbox output)
424/// with the least torque: the torque J_m i a + J_L a / i is least at i = sqrt(J_L / J_m), the classic optimum.
425pub fn optimum_ratio(load: f64, rotor: f64) -> f64 {
426    (load / rotor).sqrt()
427}
428
429/// One value of a sweep of a gear ratio or pulley radius (`transmission_sweep`): the value; the torque the motors need
430/// per unit of acceleration of every axis in turn, summed (`catalog::torque_per_acceleration`, the rigid machine at
431/// mid travel); the inertia ratio (`Figures::inertia_ratio`); and the cycle run with it, its tightest check and whether
432/// it passes; `refused` the reason where it did not run.
433#[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    /// For a catalogue gearbox snapped to (`TransmissionSweep::snapped`): its name; "" for a swept value.
443    pub gearbox: String,
444}
445
446/// A sweep of one value of the config (`gearbox.ratio` or `geometry.pulley_radius_m`): the rows of the values swept
447/// and of the two optima, in the order of their value; the classic optimum, the value at which the motors need the
448/// least torque per unit of acceleration (for a pure inertia `optimum_ratio`); the best value for the cycle, the row
449/// that passes with the lowest tightest check (else the lowest tightest check); and the catalogue gearboxes around the
450/// best ratio, each run on the cycle (with a motor and a series given).
451#[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
459/// The torque per unit acceleration of every axis in turn, summed over axes and motors.
460fn 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
464/// A row of the sweep: `cfg` with its parts in, judged on its cycle.
465fn 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
496/// `cfg` for a swept `value` of `path`: where that is the pulley radius (`geometry.pulley_radius_m`) the pulley's inertia
497/// (`pulley.inertia_kgm2`) goes with it as a disc of the same width and material: J = pi rho w r^4 / 2, so J
498/// scales as (r / r0)^4 from the config's pulley (radius r0). Any other path, or a config without a pulley inertia:
499/// `cfg` as it is.
500fn 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
509/// Sweeps `path` (`gearbox.ratio` or `geometry.pulley_radius_m`) of a config over `count` values spaced logarithmically
510/// from `from` to `to`, each with the velocity gain retuned for it (`catalog::with_value`) and run on the cycle; finds the
511/// classic optimum by a golden-section search of the torque the motors need per unit acceleration over the same range
512/// (unimodal for inertia: J_m i / r + J_L r / i), and runs it too. With `snap` = (series, motor article, supply) and
513/// `path` the gear ratio: the catalogue gearboxes of that series that fit the motor around the best ratio
514/// (`catalog::fitting_gearboxes`), each run as a row of `snapped`. The runs share the processors.
515pub 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    // Golden section on the logarithm of the value, to a millionth of the range's ratio.
533    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/// A candidate judged at the worst corner of its config's bounds (`robust_ranking`): its place in the ranking given,
569/// whether it passes there, its tightest check there, and the cycles the search for the corners took; `refused` where
570/// its config could not be judged so.
571#[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
580/// The first `top` passing candidates of a ranked search on `cfg` judged again at the worst corner of the bounds of
581/// their config (`analysis::verdict_worst`; the bounds follow a part put in, see `catalog::set`): the rows in the robust
582/// order, the ones that pass there first, each group in the order given; and whether that order differs from the one
583/// given. With a duty mix (`duties`, each duty's config and weight; empty: `cfg` alone) every duty is judged at its own
584/// worst corner and those verdicts are mixed as the search mixes the duties' own (`mix_verdicts`), with each duty's
585/// cycle as the search ran it; the runs add up.
586pub 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/// A task in tool space for comparing kinematics (`compare_kinematics`), read from a task file (`Task::parse`): pick and
634/// place positions and via points of the way between them, x y z in m relative to each machine's origin (`origin`, by
635/// default the middle of its axis ranges), z up; the lift above pick and place; the dwell of the gripper; the payload;
636/// the target cycle time (or rate); assignments made to every machine's config (`set`, e.g. `cycle.timing = ...`); and
637/// per machine id an origin of its own, in its tool coordinates (one value per axis).
638#[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/// Why a task cannot be mapped onto a machine: a key ("task-axis-missing": the task moves along an axis the machine has
652/// not; "task-out-of-range": a pose beyond an axis's range; "task-origin": an origin of the wrong length;
653/// "task-payload": a payload on a machine whose config has none; "task-set": an assignment the config refuses; or the
654/// machine's own reason from `Machine::unreachable`) and what it concerns.
655#[derive(Debug, Clone, PartialEq)]
656pub struct Refusal {
657    pub key: &'static str,
658    pub detail: String,
659}
660
661impl Task {
662    /// A task file (TOML): `pick = [x, y, z]`, `place = [x, y, z]`, optional `via = [[x, y, z], ...]`, `lift_m`,
663    /// `dwell_s`, `payload_kg`, `cycle_time_s` or `rate_per_min`, `set = ["path = value", ...]` and a table `[origin]`
664    /// of machine id = [one value per axis]. The error names the key that is wrong.
665    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
743/// The config of a machine with a task's cycle in it: the start above the pick, then down to the pick (the gripper
744/// closes: `payload` true, the dwell), up, across through the via points to above the place, down (it opens), up, and
745/// back across. Each task position goes to the machine's axis of id "x", "y" or "z" in m, from the origin; the other
746/// axes stay at the origin. Refused (`Refusal`) where a pose moves along an axis the machine has not, lies beyond an axis's
747/// range, or is one the machine cannot go to (`Machine::unreachable`); and the payload set where the config has
748/// `mass.payload_kg`. The assignments of `set` come last.
749pub 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/// One machine of a kinematics comparison: its id, why the task cannot be mapped onto it (`task_config`), else the
830/// search's best candidate (the first of the ranking, passing or not), how many passed and how many were tried, and the
831/// task's target cycle time.
832#[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    /// Whether the best candidate passes and its cycle (the mean of a mix) meets the target cycle time, where there is one.
844    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
851/// Runs a task on each machine (with its config): maps it (`task_config`), runs the catalogue search on it at its
852/// supplies (`supplies` gives them per config, e.g. the config's own), ranked by `by` (`rank_by`), and reports per
853/// machine the best combination.
854pub 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    /// Two cycles of one motor: 2 N m RMS for 1 s run three times as often as 4 N m RMS for 2 s. sqrt((3 * 4 * 1 + 1 *
898    /// 16 * 2) / (3 * 1 + 1 * 2)) = sqrt(44 / 5) = 2.9665 N m, below the 4 N m of the worse cycle alone: the heat of the
899    /// mix, not of its worst cycle. The mean of 10 K and 40 K rises the same way: (3 * 10 + 80) / 5 = 22 K.
900    #[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    /// A motor of the drive tests' round numbers (rated rise 100 K, no iron loss) with the winding's time constant `tau`
908    /// and the drive's image (`MixHeat`).
909    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    /// The mix's verdicts: per check the worst duty's, but the winding rise and the drive's RMS current over the mix.
914    /// Duty A (weight 3, 1 s): rise 10 K, 2 A RMS, peak utilisation 0.5; duty B (weight 1, 2 s): rise 40 K, 4 A RMS, peak
915    /// 0.9. Far shorter than the time constants the mix heats as its mean: the copper heating at no rise of a duty is
916    /// q = T / (1 + c T) (c = 0.0039 /K), the mean q = (3 * 1 * q_A + 1 * 2 * q_B) / 5 settles at q / (1 - c q) = 21.240 K
917    /// (the mean of the rises, 22 K, leaves out that the resistance follows the mean's temperature), against 30 K it
918    /// passes though B alone (40 K) fails; the current sqrt(44 / 5) = 2.966 A against 3 A passes. Far longer: B's own,
919    /// 40 K and 4 A, and both fail. motor-peak is B's 0.9 either way.
920    #[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        // No time constant for the drive's image: the time-weighted RMS.
953        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    /// Two duties of 1 s each, settling at T1 = 10 K and T2 = 30 K, on one node of time constant tau = 1 s: the copper's
958    /// resistance follows the temperature, so a duty settling at T approaches it at the rate (1 - c q) / tau =
959    /// 1 / (tau (1 + c T)), e_i = exp(-L / (tau (1 + c T_i))). The periodic state ends duty 2 at
960    /// x2 = (T2 (1 - e2) + T1 (1 - e1) e2) / (1 - e1 e2) = 24.017 K, its peak; without the copper's rise (c = 0) it would
961    /// be (30 + 10 e) / (1 + e) = 24.621 K.
962    #[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        // A single duty: its own rise.
973        assert!((periodic_peak(&parts[1..], [1.0, 0.0]) - 30.0).abs() < 1e-12);
974    }
975
976    /// effects.motor_thermal_nodes (winding share 0.25, 60 s against the housing, 1800 s in all): duties of 300 s at
977    /// 2.5 A and 600 s at 1 A, against the two nodes integrated step by step as `Drive::warm` has them (copper loss
978    /// I^2 R(T_w), RK4 at 0.1 s over 30 periods, the peak sampled in the last): the closed form agrees within 1e-5 K.
979    #[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    /// The drive's image with chips (share 0.3, 2 s) on a heat sink of 100 s: duty A 2 A for 10 s, B 4 A for 5 s. Each
1015    /// node is first order and rises in B, falls in A, so the image peaks at B's end, the sum of the nodes there: with
1016    /// Q = share I^2 and e = exp(-L / tau) per node, x = (Q_B (1 - e_B) + Q_A (1 - e_A) e_B) / (1 - e_A e_B); the verdict
1017    /// is the root of the sum, 3.2012 A.
1018    #[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    /// The S1 check over a mix: duty A (weight 3, 1 s) 2 N m RMS against a limit of 4.5 N m at its mean speed, duty B
1035    /// (weight 1, 2 s) 4 N m against 3.5 N m. B alone fails. Far shorter than the winding's time constant the mix's
1036    /// utilisation is sqrt((3 * (2 / 4.5)^2 + 2 * (4 / 3.5)^2) / 5) = 0.80060 of the time-weighted mean limit
1037    /// (3 * 4.5 * 1 + 1 * 3.5 * 2) / 5 = 4.1 N m, and passes; far longer, B's 4 / 3.5, and fails.
1038    #[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    /// A swept pulley radius takes the pulley's inertia with it as r^4: twice the radius, 16 times the inertia; a config
1054    /// without a pulley inertia, and any other path, stay as they are.
1055    #[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    /// The classic optimum: J_L = 0.0025 kg m^2 at the output, J_m = 0.3e-4 kg m^2: sqrt(83.33) = 9.129.
1068    #[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    /// `--rank-by` takes one name, or names with weights; anything else is refused.
1074    #[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    /// Ranking by a weighted mix: three passing candidates, cost 10/20/30 kg and energy 300/100/150 J. By cost: 10, 20,
1084    /// 30. By energy: 100, 150, 300. By cost=1,energy=1, each over the best (10 kg, 100 J): 1 + 3 = 4, 2 + 1 = 3,
1085    /// 3 + 1.5 = 4.5, so 20, 10, 30. The front over cost, margin, energy and error: 10 (cheapest) and 20 (least energy);
1086    /// 30 is beaten by 20 in both.
1087    #[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}