Skip to main content

sim_components/
analysis.rs

1//! Analysis for motor sizing: peak and RMS torque per cycle, operating points against the
2//! torque-speed curve, and the mechanical frequency response.
3
4use crate::control::{Command, CommandError};
5use crate::sim::Sim;
6use sim_core::{
7    Config, ConfigError, LOSS_PREFIX, Machine, MachineEntry, Mode, RatingCheck, Rk4, SignalInfo, TORQUE_PARTS,
8    ThermalPart, advance,
9};
10
11/// The load on one motor over one pass of the cycle.
12#[derive(Debug, Clone, Default)]
13pub struct MotorLoad {
14    /// The motor's id, whose own values (`catalog::motor_config`) its verdicts are judged with; "" for the shared ones.
15    pub id: String,
16    pub peak_torque: f64,
17    pub rms_torque: f64,
18    /// The torque gearbox makers size a gearbox's continuous rating with: the cube root of the mean of the
19    /// torque cubed, weighted with the speed, so that a turn under load counts and standing still does not.
20    pub cubic_mean_torque: f64,
21    pub peak_speed: f64,
22    /// Highest ratio of the torque the velocity loop asks for to the torque the drive has available at
23    /// that speed. Above 1 the cycle asks for more than the torque-speed curve gives.
24    pub utilisation: f64,
25    /// RMS torque over the torque the motor can give continuously. Above 1 the motor overheats on this cycle.
26    pub thermal_utilisation: f64,
27    pub rms_current: f64,
28    /// Highest |current| over the pass, A: against the drive's maximum output current. With the drive's limit
29    /// simulated (effects.drive_current_limit) the current the velocity loop's torque asks for (`Drive::torque_demand`)
30    /// where that is higher: a drive held at its limit delivers no more, and the check would never see the cycle beyond
31    /// it ("motor-peak" judges the demand for the same reason).
32    pub peak_current: f64,
33    /// Temperature rise the winding settles at when the cycle repeats for long.
34    pub winding_rise: f64,
35    /// RMS of the current that heats the winding (Drive::thermal_current): the phase current's, an induction motor's
36    /// with its rotor's copper loss.
37    pub thermal_current: f64,
38    /// A stepper's highest |load angle| over the pass, electrical rad (drive::Phases::load_angle): beyond pi / 2 it
39    /// is past its pull-out angle, beyond pi it has lost steps. None for the other motors.
40    pub load_angle: Option<f64>,
41    /// With effects.iron_loss: the stator's mean iron loss over the pass, W (`DriveParams::iron_loss_at`); 0 without.
42    pub iron_loss: f64,
43    /// With effects.motor_thermal_nodes: the rise the stator and housing settle at, K, the winding's times the housing's
44    /// share of the thermal resistance (`drive::ThermalNodes`); 0 without.
45    pub housing_rise: f64,
46    /// With effects.drive_overload: the highest the drive's thermal image reaches when the cycle repeats for long
47    /// (`drive::Overload`, 1 at the rated current held), judged against its trip level ("drive-overload"); 0 without.
48    pub drive_overload: f64,
49    /// Electrical energy over the cycle: drawn from the DC link, and fed back into it while braking.
50    pub energy_in: f64,
51    pub energy_regenerated: f64,
52    /// Highest power fed back, and the most energy fed back in one go: what the DC link capacitors or a
53    /// braking resistor have to take.
54    pub peak_regenerated_power: f64,
55    pub largest_regeneration: f64,
56    /// The cycle's electrical energy in stretches of one sign, J, in their order: positive for a braking event (one run of
57    /// negative power) fed back, negative for the energy drawn between two, which empties the DC link's capacitors first.
58    /// What the resistor takes above the link's room (`resistor_excess`), where the link is not simulated. For a load
59    /// built by hand: a run keeps its account online instead (`dc_link_account`) and leaves this empty.
60    pub regeneration_events: Vec<f64>,
61    /// A run's running account of these stretches for the motor's DC link room (`LinkAccount`), where its config gives
62    /// the capacitance and the braking threshold; judged instead of `regeneration_events` where the room is the same.
63    pub dc_link_account: Option<LinkAccount>,
64    /// With the DC link simulated: the energy the braking resistor burned (over the cycle's duration its
65    /// mean power), the most power it took and the highest DC link voltage. For a drive that tripped on
66    /// overvoltage, the voltage it tripped at.
67    pub resistor_energy: f64,
68    pub peak_resistor_power: f64,
69    pub peak_dc_link_voltage: f64,
70    /// With the regenerative supply (effects.regenerative_supply): the energy fed back into the mains (what arrives
71    /// there), and the line module's load: the energy through it either way (drawn into the DC link, and fed back as
72    /// the DC link gives it) and its highest power either way.
73    pub mains_energy: f64,
74    pub line_module_energy: f64,
75    pub peak_line_module_power: f64,
76    /// With the DC link simulated: what the drive's bleeder took out of the DC link while disabled (`Drive::disabled_step`;
77    /// each drive its own share of a shared link), J.
78    pub discharge_energy: f64,
79    /// The torque at the gearbox output, where the machine reports it (signal `gearbox.<motor>.output_torque`): its
80    /// peak, and its cubic mean weighted with the speed. Not the motor torque times the ratio: the rotor's
81    /// own acceleration does not pass through the gearbox, and its losses come off or on top.
82    pub gearbox_torque: Option<(f64, f64)>,
83    /// Mean of the motor's |speed| over the pass, rad/s: for the lives in hours.
84    pub mean_speed: f64,
85    /// Where the machine reports the gearbox output torque: its mean with the exponent 10/3, weighted with the
86    /// speed, the equivalent torque of Siemens' life formula for the planet bearings (`gearbox_life_h`).
87    pub gearbox_life_torque: Option<f64>,
88    /// Where the machine reports the gearbox output torque: its peak in each band of `SPEED_BAND` rad/s of the motor's
89    /// |speed| (band i from i to i + 1 times it), every step. For the belt's tooth load, whose rating falls with speed.
90    pub gearbox_torque_by_speed: Vec<f64>,
91    /// Where the machine reports the gearbox output torque: the gearing's load spectrum, the motor's |speed| in rad/s
92    /// while the output torque was in each band (band i from `torque_band_floor(i)` to `torque_band_floor(i + 1)`),
93    /// summed every step over the steps: what each band adds to `mean_speed`. For `gearbox_gearing_life_h`.
94    pub gearbox_torque_spectrum: Vec<f64>,
95    /// Where the machine reports the radial load on this motor's pulley shaft (`pulley.<motor>.radial_load`): its cubic
96    /// mean weighted with the speed, the equivalent load P of the bearings' rating life (ISO 281), once per millisecond.
97    pub radial_load_equivalent: Option<f64>,
98    /// Where the machine reports that radial load: its highest over the pass, N, sampled as `CycleLoad::radial_load_peak`
99    /// is. Judged per motor against that motor's `ratings.shaft_max_radial_load_n` ("gearbox-radial-load").
100    pub radial_load_peak: Option<f64>,
101    /// With effects.belt_wrap, where the machine gives its belt geometry (`Machine::belt_wraps`): the smallest angle by
102    /// which the belt wrapped this motor's pulley over the pass, rad, once per millisecond. For the teeth in mesh.
103    pub belt_wrap: Option<f64>,
104    /// Peak and RMS of each part of the motor torque, in the order of `TORQUE_PARTS`, where the machine reports
105    /// them (signals `motor.<id>.torque_<part>`). Looked at every step. The parts add up to the torque at every
106    /// moment; their peaks and RMS values do not add up, as they come at different times.
107    pub torque_parts: Option<[(f64, f64); 4]>,
108    /// (speed, torque) once per millisecond, for plotting over the torque-speed curve.
109    pub points: Vec<(f64, f64)>,
110}
111
112/// One line of an energy budget.
113#[derive(Debug, Clone, PartialEq)]
114pub struct BudgetRow {
115    /// `copper.<motor>`, `emf.<motor>` (only with a back-EMF constant other than the torque constant), `resistor`, `mains`, `line_module`, a machine's loss signal (`power.<place>`), `windings`,
116    /// `capacitors`, a machine's energy signal (`energy.<part>`) or `payload`.
117    pub id: String,
118    /// The label, as two translation keys like a signal's.
119    pub owner_key: String,
120    pub quantity_key: String,
121    /// Energy over the measured pass, J: lost, or for a store what it holds more at the end than at the start.
122    pub energy: f64,
123}
124
125/// Where the energy drawn from the supply over the measured pass went (see `analyse_cycle`).
126#[derive(Debug, Clone, PartialEq)]
127pub struct EnergyBudget {
128    /// Energy from the supply. Without the DC link simulated, what the drives drew less what they fed back; with it,
129    /// what the rectifier (or the line module) drew from the line into the DC link.
130    pub supply: f64,
131    pub rows: Vec<BudgetRow>,
132    /// The work the motor torques did on the mechanics, integrated with the windings: where the electrical side hands
133    /// over to the machine. Not a row: the machine's rows say where it went.
134    pub shaft_work: f64,
135}
136
137impl EnergyBudget {
138    /// What the rows leave of the supply. Below `BUDGET_TOLERANCE` of the supply on every shipped machine and
139    /// config (`the_energy_budget_closes_on_every_machine_and_config`).
140    pub fn unaccounted(&self) -> f64 {
141        self.supply - self.rows.iter().map(|r| r.energy).sum::<f64>()
142    }
143
144    /// The electrical side on its own: the supply less copper loss, braking resistor, bleeder discharge, mains and line module, the
145    /// windings' and the capacitors' stored energy and the shaft work. Below `ELECTRICAL_TOLERANCE` of the supply on
146    /// every machine and config with the back-EMF on, loss-free ones included; the rest of `unaccounted` is the
147    /// machine's own balance.
148    pub fn electrical_unaccounted(&self) -> f64 {
149        let electrical = |id: &str| {
150            id.starts_with("copper.")
151                || id.starts_with("emf.")
152                || matches!(id, "resistor" | "discharge" | "mains" | "line_module" | "windings" | "capacitors")
153        };
154        self.supply - self.shaft_work - self.rows.iter().filter(|r| electrical(&r.id)).map(|r| r.energy).sum::<f64>()
155    }
156}
157
158/// How far an energy budget may be off, as a share of the supply. The electrical side closes to
159/// `ELECTRICAL_TOLERANCE`, so what is left is the machine's own balance: its losses are taken at the end of each
160/// step and summed times the step, the trapezoid rule but for the ends (see `testkit::loss_budget`).
161pub const BUDGET_TOLERANCE: f64 = 1e-3;
162
163/// How far the electrical side of an energy budget may be off (`EnergyBudget::electrical_unaccounted`), as a share
164/// of the supply: the error of the fourth-order integration of the winding's energy over a base step.
165pub const ELECTRICAL_TOLERANCE: f64 = 1e-6;
166
167/// One guide's load over the cycle (`CycleLoad::guides`).
168#[derive(Debug, Clone, Default, PartialEq)]
169pub struct GuideLoad {
170    /// Its highest load, N.
171    pub peak: f64,
172    /// Its equivalent load: the cubic mean over the distance, N.
173    pub equivalent: f64,
174    /// The mean |speed| of its axis, m/s; `None` where the axis is not known.
175    pub speed: Option<f64>,
176}
177
178#[derive(Debug, Clone, Default)]
179pub struct CycleLoad {
180    pub duration: f64,
181    /// Lowest and highest tension of any belt section during the cycle, for machines that report
182    /// belt tensions. A lowest tension of zero means a section went slack.
183    pub belt_tension: Option<(f64, f64)>,
184    /// Seconds any belt section spent without tension, where the machine counts them.
185    pub belt_slack_time: Option<f64>,
186    /// With effects.belt_tooth_jump: how often the belt's teeth jumped over a driven pulley during the cycle.
187    pub belt_tooth_jumps: Option<f64>,
188    /// With effects.belt_span_vibration: how close any free belt span's first sideways mode came to an excitation of
189    /// the drive while the axes ran at a steady speed (the signal `belt.span_detuning`, sampled once per millisecond);
190    /// 1 where they never did.
191    pub belt_span_detuning: Option<f64>,
192    /// The highest radial load a belt put on a pulley shaft, where the machine reports it.
193    pub radial_load_peak: Option<f64>,
194    /// The highest condition number of the kinematics' Jacobian during the cycle, where the machine reports it (the
195    /// signal `kinematics.condition`, sampled once per millisecond): how near the tool came to a singularity.
196    pub condition_peak: Option<f64>,
197    /// Of the guide with the highest load, where the machine reports guide loads: its highest load and
198    /// its cubic mean over the cycle, the equivalent load of the guide makers' life formula.
199    pub guide_load: Option<(f64, f64)>,
200    /// The mean |speed| of the axis of that guide over the cycle, m/s: the distance it runs per hour.
201    pub guide_speed: Option<f64>,
202    /// Every guide the machine reports, each with its own figures: `guide_life_km` and `guide_life_h` take the lowest
203    /// life over them. `guide_load` and `guide_speed` above are those of the one that wears out first.
204    pub guides: Vec<GuideLoad>,
205    /// How far the tool was from the path its setpoint drew: the most and the RMS. And the most it was
206    /// from where the setpoint was at the same moment, which also counts lagging behind along the path. Of the
207    /// axes in m alone (its place); the axes in rad (its turn, an arm's orientation, a turning table) have their own
208    /// figures below, in rad, so that metres and radians are never added.
209    pub path_error_peak: f64,
210    pub path_error_rms: f64,
211    pub tracking_error_peak: f64,
212    /// The most the tool was from its target in the second half of a dwell: by then it should have settled,
213    /// because that is when the gripper acts. Of the axes in m.
214    pub dwell_error_peak: f64,
215    /// The same four of the axes in rad, rad: 0 on a machine without one.
216    pub path_angle_error_peak: f64,
217    pub path_angle_error_rms: f64,
218    pub tracking_angle_error_peak: f64,
219    pub dwell_angle_error_peak: f64,
220    /// The tool's distance to the path every millisecond of the measured pass, of which `path_error_peak` is the most:
221    /// [time from the pass's start in s, place in m, turn in rad], for the error views (`charts::tool_error`).
222    pub path_error_series: Vec<[f64; 3]>,
223    /// A drive tripped on DC link overvoltage and took all drives off: the run ended there, and the figures
224    /// are those up to the trip.
225    /// A drive tripped on DC link overvoltage, or a drive's monitoring tripped (effects.drive_monitoring), and took all
226    /// drives off: the run ended there, and the figures are those up to the trip and the stop.
227    pub tripped: bool,
228    pub motors: Vec<MotorLoad>,
229    /// Where the energy drawn from the supply went, for a machine that reports its losses. `None` also where the
230    /// effect views were not asked for (`analyse_cycle_with`).
231    pub budget: Option<EnergyBudget>,
232    /// With effects.part_heating, each part that warms with its loss (`Sim::heated`) and the rise it settles at when
233    /// the cycle repeats for long: its thermal resistance times its mean loss over the measured pass. Empty without.
234    pub part_rises: Vec<(ThermalPart, f64)>,
235    /// The machine's own rating checks (`Machine::rating_checks`) and what the pass reached in each: the highest
236    /// |signal|, or for a life check the life in hours, 1 / the mean damage rate (infinite where nothing wore).
237    pub checks: Vec<(RatingCheck, f64)>,
238    /// Where the config has obstacles: the least clearance to them over the whole run, the way to the cycle and its
239    /// first pass included (`Sim::least_clearance`), m; and the run's first contact with one.
240    pub clearance: Option<f64>,
241    pub contact: Option<crate::Contact>,
242    /// Where the machine has two parts not joined at its start pose: the least clearance between such parts over the
243    /// whole run, as `clearance` (`Sim::own_parts`), m.
244    pub own_clearance: Option<f64>,
245    /// The highest braking power of all drives at once, W: with the DC link simulated, what the braking resistors
246    /// took (a shared one counted once); without, the power the drives fed back. For an S120 line-up, which brakes
247    /// through one Braking Module (`verdicts`).
248    pub braking_power_peak: f64,
249    /// With effects.thermal_warm_start, and windings or parts whose warmth acts back on the run: how the measured pass
250    /// was started warm. `None`: from cold.
251    pub warm_start: Option<WarmStart>,
252    /// With `[conveyor]`: what the measured pass, one pick, did on the belt.
253    pub conveyor: Option<ConveyorLoad>,
254    /// While the gripper held the payload (and was not closing or opening): the tool's acceleration upwards (along z)
255    /// and sideways (|a_x, a_y|), m/s^2, once per millisecond from its speed a millisecond apart, for the verdict
256    /// "gripper-hold" (`gripper::demand`). Empty on a machine without tool axes x, y or z in m.
257    pub held_accelerations: Vec<[f64; 2]>,
258}
259
260/// With an electronic cam (`Machine::cam`): per slave axis what its cam asks at the master's steady speed against the
261/// axis limits, as rating checks "cam-speed", "cam-acceleration" and "cam-jerk" (signal: the axis's id); the motor is
262/// the axis's, where there are as many motors as axes. A cam that asks more than its slave may do fails them.
263fn cam_checks(machine: &dyn sim_core::Machine) -> Vec<(RatingCheck, f64)> {
264    let (axes, motors) = (machine.axes(), machine.motors().len());
265    let checks = ["cam-speed", "cam-acceleration", "cam-jerk"];
266    crate::control::cam_peaks(machine)
267        .into_iter()
268        .zip(axes)
269        .enumerate()
270        .flat_map(|(i, (peak, axis))| {
271            let limits = [axis.max_vel, axis.max_acc, axis.max_jerk];
272            (0..3).map(move |k| {
273                let motor = (axes.len() == motors).then_some(i);
274                (
275                    RatingCheck { check: checks[k], signal: axis.id.to_string(), motor, limit: limits[k], life: false },
276                    peak[k],
277                )
278            })
279        })
280        .collect()
281}
282
283/// One pick from the conveyor (`[conveyor]`), the measured pass of the cycle.
284#[derive(Debug, Clone, Copy, PartialEq)]
285pub struct ConveyorLoad {
286    /// 60 / the pass's duration: one part per pass.
287    pub picks_per_minute: f64,
288    /// The most the tool was from the part along the belt while the gripper closed, m (the verdict `pick-tracking`).
289    pub tracking_peak: f64,
290    /// The parts that left the window unpicked from the measured pick's plan to the next's.
291    pub missed: u64,
292    /// Parts a minute that pass the window unpicked (the verdict `parts-missed`): those the belt brings beyond the picks a
293    /// minute, which one pass cannot see when the misses come in bursts, or those missed in the pass, whichever is more.
294    pub missed_per_minute: f64,
295}
296
297/// How far the rises a warm pass starts at may lie from those it settles at for the warm start to count as converged,
298/// K: a tenth of a kelvin moves a winding's resistance by 0.04 % and a guide's viscosity by 0.5 %.
299pub const WARM_START_TOLERANCE_K: f64 = 0.1;
300
301/// The most warm passes of a warm start (`analyse_cycle_with`) before the last is measured, converged or not; as many
302/// again of periods, where the passes it took repeat every few (`period_of`).
303pub const WARM_START_PASSES: usize = 4;
304
305/// The most passes a cycle's period may span for the warm start to find it (`period_of`).
306pub const WARM_START_PERIOD_MOST: usize = 3;
307
308/// A cycle analysis started warm (effects.thermal_warm_start): the measured pass ran with the windings (with
309/// effects.winding_heating) and the heated parts (with effects.thermal_feedback) at the rises the pass before settled
310/// at, by `passes` passes of cold → settled → warm → settled; `change` is the most a rise the measured pass started at
311/// lies from the one it settles at, K (infinite where a rise does not settle, or the run stopped). `period`: the passes
312/// the measured span covers, more than one where the cycle repeats only every so many passes (a pick that alternates
313/// between two places loads the motors differently pass by pass): the rises then settle over the period, not per pass.
314/// `repeat`: where the passes converged neither per pass nor over a period, how far apart (K) the rises settle of two
315/// passes started at the same rises, the measured one and one more run after it (`None` where not measured). Beyond the
316/// tolerance the cycle's motion does not repeat itself: what one pass leaves moving (a load still swinging) carries into
317/// the next and loads the motors differently, which no start temperature can settle.
318#[derive(Debug, Clone, Copy, PartialEq)]
319pub struct WarmStart {
320    pub passes: usize,
321    pub change: f64,
322    pub period: usize,
323    pub repeat: Option<f64>,
324}
325
326impl WarmStart {
327    pub fn converged(&self) -> bool {
328        self.change <= WARM_START_TOLERANCE_K
329    }
330}
331
332/// The rises that act back on the run: per winding with effects.winding_heating (its resistance), per heated part
333/// with effects.thermal_feedback (friction and losses).
334fn fed_back_rises(sim: &Sim) -> Vec<f64> {
335    let windings = if sim.control.drive_params().heating { &sim.control.drives[..] } else { &[] };
336    let parts = if sim.thermal_feedback { &sim.heated[..] } else { &[] };
337    windings.iter().map(|d| d.temperature_rise).chain(parts.iter().map(|h| h.rise)).collect()
338}
339
340/// The same rises where the cycle of `load` settles them (`MotorLoad::winding_rise`, `CycleLoad::part_rises`).
341fn settled_rises(sim: &Sim, load: &CycleLoad) -> Vec<f64> {
342    let windings = if sim.control.drive_params().heating { &load.motors[..] } else { &[] };
343    let parts = if sim.thermal_feedback { &load.part_rises[..] } else { &[] };
344    windings.iter().map(|m| m.winding_rise).chain(parts.iter().map(|(_, rise)| *rise)).collect()
345}
346
347/// Puts the windings and parts at `rises` (in the order of `fed_back_rises`).
348fn set_rises(sim: &mut Sim, rises: &[f64]) {
349    let mut rises = rises.iter();
350    if sim.control.drive_params().heating {
351        let shares: Vec<f64> = (0..sim.control.drives.len())
352            .map(|k| sim.control.drive_params_of(k).thermal_nodes.map_or(1.0, |n| n.winding_share))
353            .collect();
354        for ((drive, rise), share) in sim.control.drives.iter_mut().zip(&mut rises).zip(shares) {
355            drive.temperature_rise = *rise;
356            // With effects.motor_thermal_nodes the housing where that rise settles it (0 without).
357            drive.housing_rise = rise * (1.0 - share);
358        }
359    }
360    if sim.thermal_feedback {
361        for (part, rise) in sim.heated.iter_mut().zip(rises) {
362            part.rise = *rise;
363        }
364    }
365    sim.feed_temperatures_back();
366}
367
368/// The warm start's next move after a measured span (one period of `period` passes) that began at `started_at` and
369/// settles where `load` says: `None` to measure another span from the next rises (already set), or the result.
370/// `before` is the span before's start and settled rises, which this one replaces; `settled` the settled rises of every
371/// span so far of one pass, from which, where the passes do not converge, `period_of` finds a period of a few passes:
372/// the spans then cover it, from the mean of its passes' settled rises, again up to `WARM_START_PASSES` of them.
373///
374/// The next start is a secant step per rise: s(r), the rise a pass settles at for the rise it starts at, falls with r
375/// where the warmth thins a lubricant (a warmer guide loses less), so plain substitution r = s oscillates and converges
376/// slowly (about -0.4 on the EXCT-30's guide: still 0.3 K off after four passes). With the slope m of the last two passes the
377/// fixed point lies at r + (s - r) / (1 - m); m is clamped to [-20, 0.5], and taken as 0 (substitution) on the first
378/// warm pass and where the start did not move. A winding's settled rise depends on its current alone: m = 0.
379///
380/// Where the spans converge neither per pass nor over a period, and `repeat` is given (a cycle that runs on from pass to
381/// pass), one more span is measured from the rises the last one started at (`repeat` holds the last one's settled rises
382/// and result meanwhile): the result is the last one's, with `WarmStart::repeat` how far apart the two settle, the
383/// temperatures alike, what differs being the motion. The caller keeps the last span's load as the measured one.
384#[allow(clippy::too_many_arguments)]
385fn warm_pass(
386    sim: &mut Sim,
387    started_at: &[f64],
388    load: &CycleLoad,
389    passes: usize,
390    before: &mut Option<(Vec<f64>, Vec<f64>)>,
391    period: &mut usize,
392    history: &mut Vec<Vec<f64>>,
393    mut repeat: Option<&mut Option<(Vec<f64>, WarmStart)>>,
394) -> Option<WarmStart> {
395    let settled = settled_rises(sim, load);
396    if let Some((first, done)) = repeat.as_mut().and_then(|r| r.take()) {
397        // This span started where the one before did: how far apart the two settle.
398        let apart = settled.iter().zip(&first).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
399        return Some(WarmStart { repeat: Some(apart), ..done });
400    }
401    let change = settled
402        .iter()
403        .zip(started_at)
404        .map(|(s, r)| if s.is_finite() { (s - r).abs() } else { f64::INFINITY })
405        .fold(0.0, f64::max);
406    let done = WarmStart { passes, change, period: *period, repeat: None };
407    // A rise that does not settle (a winding loaded beyond what its copper can shed) cannot be started at.
408    if done.converged() || change.is_infinite() {
409        return Some(done);
410    }
411    if *period == 1 {
412        history.push(settled.clone());
413    }
414    if passes == WARM_START_PASSES {
415        let found = (*period == 1).then(|| period_of(history)).flatten();
416        let Some(p) = found else {
417            let Some(r) = repeat else { return Some(done) };
418            // No period: one more span from the same rises tells whether the passes repeat at all.
419            *r = Some((settled, done));
420            set_rises(sim, started_at);
421            return None;
422        };
423        // The next span covers the period, from the mean of its passes' settled rises.
424        let last = &history[history.len() - p..];
425        let mean: Vec<f64> = (0..settled.len()).map(|i| last.iter().map(|s| s[i]).sum::<f64>() / p as f64).collect();
426        (*period, *before) = (p, None);
427        set_rises(sim, &mean);
428        return None;
429    }
430    let next: Vec<f64> = (0..settled.len())
431        .map(|i| {
432            let (r, s) = (started_at[i], settled[i]);
433            let slope = before
434                .as_ref()
435                .filter(|(r0, _)| (r - r0[i]).abs() > 1e-9)
436                .map_or(0.0, |(r0, s0)| ((s - s0[i]) / (r - r0[i])).clamp(-20.0, 0.5));
437            (r + (s - r) / (1.0 - slope)).max(0.0)
438        })
439        .collect();
440    *before = Some((started_at.to_vec(), settled));
441    set_rises(sim, &next);
442    None
443}
444
445/// The period, in passes, of a warm start whose passes do not converge: from the settled rises of its passes in order
446/// (the first from cold), the fewest passes p (2 to `WARM_START_PERIOD_MOST`) such that the last pass settles within a
447/// quarter as far from the one p before as from the one before it, the rises it starts at being about the same. `None`
448/// where none does: the passes drift or alternate as a convergence would, with no period.
449fn period_of(settled: &[Vec<f64>]) -> Option<usize> {
450    let apart = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0, f64::max);
451    let (k, warm) = (settled.len().checked_sub(1)?, 1);
452    let next = apart(&settled[k], &settled[k.checked_sub(1)?]);
453    (2..=WARM_START_PERIOD_MOST).find(|&p| k >= warm + p && apart(&settled[k], &settled[k - p]) < 0.25 * next)
454}
455
456/// The highest a drive's thermal image (`drive::Overload`) reaches when a pass repeats for long. The pass ran from the
457/// nodes [slow, chips] `start` and ended at `end` (time, nodes), with `samples` (time, nodes) between. Each node is linear
458/// in its start: one started at x0 lies (x0 - start) exp(-t / tau) above the pass's at every t. The start a repeating
459/// pass returns to is x0 = f / (1 - exp(-T / tau)), where f = end - start exp(-T / tau) is what the pass itself added.
460/// The image is the nodes' sum.
461///
462/// shortcut: where the image tripped in the pass the drive lowered its current and the image is no longer linear in its
463/// start; the peak is then that of the pass as it ran, corrected as if it were. It is at or above the trip anyway.
464pub fn repeating_peak(
465    o: &crate::drive::Overload,
466    start: [f64; 2],
467    samples: &[(f64, [f64; 2])],
468    (t_end, end): (f64, [f64; 2]),
469) -> f64 {
470    let decay = |node: usize, t: f64| (-t / o.node_time_constant(node)).exp();
471    let x0: [f64; 2] = std::array::from_fn(|n| {
472        let added = end[n] - start[n] * decay(n, t_end);
473        if t_end > 0.0 { added / (1.0 - decay(n, t_end)) } else { start[n] }
474    });
475    let at = |t: f64, x: [f64; 2]| (0..2).map(|n| x[n] + (x0[n] - start[n]) * decay(n, t)).sum::<f64>();
476    samples.iter().chain([(t_end, end)].iter()).map(|&(t, x)| at(t, x)).fold(x0[0] + x0[1], f64::max)
477}
478
479/// What a run adds up step by step, for a cycle or a trajectory, or for any run stepped from outside (a controller of
480/// the user's own, `kinematics_sim.Sim`): `step` after each `Sim::step`, then `finish` gives the load the verdicts judge.
481/// The path, tracking and dwell errors are measured against the controller's plan.
482#[derive(Clone)]
483pub struct Tally {
484    loads: Vec<MotorLoad>,
485    pos: Vec<f64>,
486    speed: Vec<f64>,
487    steps: u64,
488    /// Steps per millisecond: belt tensions, operating points and the path are sampled that often.
489    every: u64,
490    /// Per motor with effects.drive_overload: its drive's thermal image when the pass began, and (time, image) once per
491    /// millisecond, for `repeating_peak`.
492    overload: Vec<([f64; 2], Vec<(f64, [f64; 2])>)>,
493    tensions: Vec<usize>,
494    /// Signals of the pulley shafts' radial loads and of the guide loads, and the slack-time counter.
495    radial: Vec<usize>,
496    guides: Vec<usize>,
497    slack: Option<usize>,
498    /// The jump counters of the driven pulleys and their sum when the measurement began; the spans' detuning signal
499    /// and its lowest value at steady speed.
500    jumps: Vec<usize>,
501    jumps_start: f64,
502    detuning: Option<usize>,
503    /// The signal of the Jacobian's condition number, and its highest value.
504    condition: Option<usize>,
505    condition_peak: f64,
506    lowest_detuning: f64,
507    /// The machine's rating checks, the places of their signals, and per check the highest |signal| and the sum of the
508    /// signal, one per sample.
509    checks: Vec<(RatingCheck, usize, f64, f64)>,
510    /// The checks on `plan.<signal>` (a limit the plan keeps: an arm's flange spin), their places among
511    /// `Machine::rating_checks` (and so in `Machine::rigid_checks`), and the highest |value| on the setpoint's rigid
512    /// motion, once per sample.
513    plan_checks: Vec<(RatingCheck, usize, f64)>,
514    sample: Vec<f64>,
515    /// Every signal looked at in `sample` is one of `Sim::sample_base`: the effect views need not be sampled.
516    base_only: bool,
517    belt_tension: Option<(f64, f64)>,
518    radial_peak: f64,
519    /// Per guide: highest load and the sum of the load cubed times its axis's |speed| (rolling damage goes with distance;
520    /// time where the axis is unknown), one per sample; and the sum of that weight.
521    guide_loads: Vec<(f64, f64)>,
522    guide_weights: Vec<f64>,
523    /// Per guide the place of its axis among the machine's axes, and the sum of that axis's |speed|, one per sample.
524    guide_axes: Vec<Option<usize>>,
525    guide_speeds: Vec<f64>,
526    /// Per motor the signal of its pulley shaft's radial load, and the sums of load^3 |speed| and |speed| per sample.
527    pulley_radial: Vec<Option<usize>>,
528    radial_sums: Vec<(f64, f64)>,
529    /// Per motor the highest radial load on its pulley shaft, sampled as `radial_peak`.
530    radial_peaks: Vec<f64>,
531    /// Per motor with a gearbox output torque: the sum of |torque|^(10/3) |speed|, and its peak per speed band.
532    gear_life: Vec<f64>,
533    gear_bands: Vec<Vec<f64>>,
534    /// Per motor with a gearbox output torque: the sum of |speed| per torque band (`MotorLoad::gearbox_torque_spectrum`).
535    gear_spectrum: Vec<Vec<f64>>,
536    /// The slack-time counter when the measurement began.
537    slack_start: f64,
538    /// Per motor: sums of |torque|^3 |speed| and of |speed|.
539    cubic: Vec<(f64, f64)>,
540    /// Per motor, where the machine reports the torque at the gearbox output: its place among the machine's
541    /// own signals, its peak and the sum of |torque|^3 |speed|. Looked at every step: a gear rings faster
542    /// than once per millisecond.
543    gear: Vec<Option<(usize, f64, f64)>>,
544    machine_signals: Vec<f64>,
545    /// Per motor, where the machine reports the parts of its torque: their places among the machine's own signals,
546    /// and per part its peak and the sum of its square.
547    parts: Vec<Option<[usize; 4]>>,
548    part_sums: Vec<[(f64, f64); 4]>,
549    /// The energy budget: the places of the machine's loss and energy signals, the energy lost in each, the energy
550    /// parts, the windings' and the DC link's stored energy and the payload energy when the measurement began, and
551    /// the drives' electrical energy, copper loss per motor, the energies of resistor, rectifier, mains and line module
552    /// since. The first `budget_skip` steps are not counted.
553    losses: Vec<usize>,
554    lost: Vec<f64>,
555    energies: Vec<usize>,
556    start: (Vec<f64>, f64, f64, f64),
557    /// The windings', capacitors' and payload energy after the last step counted, where the budget ends: the stores
558    /// are read where the flows stop (the machine's from `machine_signals` of that step).
559    end: (f64, f64, f64),
560    /// `Sim::crash_energy` when the measurement began and after the last step counted.
561    crash: (f64, f64),
562    supply: f64,
563    copper: Vec<f64>,
564    /// What each servo winding took beyond copper, shaft and stored energy where its back-EMF constant is not its torque
565    /// constant (`Drive::emf_loss`).
566    emf: Vec<f64>,
567    resistor: f64,
568    /// What the DC links of drives switched off lost through their bleeders (`Drive::discharge_power`).
569    discharge: f64,
570    drawn: f64,
571    mains: f64,
572    line_loss: f64,
573    /// The work of the motor torques on the mechanics, as the drives integrated it.
574    work: f64,
575    budget_skip: u64,
576    /// Per heated part the energy it lost since the measurement began, while the parts warm (effects.part_heating).
577    heat: Vec<f64>,
578    /// Whether the effect views (torque breakdown, energy budget) are added up: they need the machine's
579    /// `effect_signals` every step.
580    views: bool,
581    /// Energy fed back (positive) since each motor last drew power, or drawn (negative) since it last fed back.
582    braking: Vec<f64>,
583    /// `CycleLoad::braking_power_peak`.
584    braking_peak: f64,
585    /// The setpoints of the last half second: the piece of the path the tool can be near.
586    path: std::collections::VecDeque<Vec<f64>>,
587    /// Of the axes in m and of those in rad (`groups`): peak, sum of squares and count; tracking; dwell.
588    path_error: [(f64, f64, u64); 2],
589    /// [time, place, turn] per sample (`CycleLoad::path_error_series`), the time as the simulation counts it.
590    path_series: Vec<[f64; 3]>,
591    tracking_error: [f64; 2],
592    dwell_error: [f64; 2],
593    /// The tool's axes in m and those in rad, by index.
594    groups: [Vec<usize>; 2],
595    /// With `[conveyor]`: the most the tool was from the gripped part along the belt, and the parts missed before.
596    pick_tracking: f64,
597    missed_before: u64,
598    /// The tool axes x, y, z in m (by index; `None` where the machine lacks one), the tool's speed along them at the
599    /// last sample, and `CycleLoad::held_accelerations`.
600    cartesian: [Option<usize>; 3],
601    last_speed: Option<[f64; 3]>,
602    held: Vec<[f64; 2]>,
603}
604
605/// Distance from `p` to the piece of line between `a` and `b`, in the axes `axes` alone.
606fn distance_to_piece(p: &[f64], a: &[f64], b: &[f64], axes: &[usize]) -> f64 {
607    // Without closures behind references: the path error asks this 500 times per millisecond.
608    let (ab, ap) = (|i: usize| b[i] - a[i], |i: usize| p[i] - a[i]);
609    let length = axes.iter().map(|&i| ab(i) * ab(i)).sum::<f64>();
610    let along =
611        if length > 0.0 { (axes.iter().map(|&i| ap(i) * ab(i)).sum::<f64>() / length).clamp(0.0, 1.0) } else { 0.0 };
612    // (+ 0: an empty sum is -0.)
613    axes.iter().map(|&i| (ap(i) - along * ab(i)).powi(2)).sum::<f64>().sqrt() + 0.0
614}
615
616impl Tally {
617    pub fn new(sim: &Sim, views: bool) -> Self {
618        let motors = sim.machine.motors().len();
619        let infos = sim.signal_infos();
620        let named = |start: &str, end: &str| -> Vec<usize> {
621            infos
622                .iter()
623                .enumerate()
624                .filter(|(_, s)| s.id.starts_with(start) && s.id.ends_with(end))
625                .map(|(i, _)| i)
626                .collect()
627        };
628        let guides = named("axis.", ".guide_load");
629        let own = sim.machine.signal_infos();
630        let gear = |motor: &sim_core::MotorInfo| {
631            Some((own.iter().position(|s| s.id == format!("gearbox.{}.output_torque", motor.id))?, 0.0, 0.0))
632        };
633        let parts = |motor: &sim_core::MotorInfo| -> Option<[usize; 4]> {
634            let found: Vec<usize> = TORQUE_PARTS
635                .iter()
636                .filter_map(|part| own.iter().position(|s| s.id == format!("motor.{}.torque_{part}", motor.id)))
637                .collect();
638            found.try_into().ok()
639        };
640        // Without the views, only what `base_signals` gives is looked at.
641        let own_named = |prefix: &str| {
642            own.iter()
643                .enumerate()
644                .filter(|(_, s)| views && s.id.starts_with(prefix))
645                .map(|(i, _)| i)
646                .collect::<Vec<_>>()
647        };
648        let (losses, energies) = (own_named(LOSS_PREFIX), own_named("energy."));
649        let mut machine_signals = Vec::new();
650        if views {
651            sim.machine.signals(&sim.state, &sim.machine_torque(), &mut machine_signals);
652        } else {
653            sim.machine.base_signals(&sim.state, &sim.machine_torque(), &mut machine_signals);
654        }
655        let (windings, capacitors) = stored_electrically(sim);
656        let (tensions, radial, slack, jumps, detuning) = (
657            named("belt.", ".tension"),
658            named("pulley.", ".radial_load"),
659            infos.iter().position(|s| s.id == "belt.slack_time"),
660            named("pulley.", ".tooth_jumps"),
661            infos.iter().position(|s| s.id == "belt.span_detuning"),
662        );
663        let mut base = Vec::new();
664        sim.sample_base(&mut base);
665        let condition = infos.iter().position(|s| s.id == "kinematics.condition");
666        let checks: Vec<(RatingCheck, usize, f64, f64)> = sim
667            .machine
668            .rating_checks()
669            .into_iter()
670            .filter_map(|c| Some((infos.iter().position(|s| s.id == c.signal)?, c)))
671            .map(|(i, c)| (c, i, 0.0, 0.0))
672            .collect();
673        let check_places: Vec<usize> = checks.iter().map(|c| c.1).collect();
674        let plan_checks = sim
675            .machine
676            .rating_checks()
677            .into_iter()
678            .enumerate()
679            .filter(|(_, c)| c.signal.starts_with("plan.") && !c.life)
680            .map(|(i, c)| (c, i, 0.0))
681            .collect();
682        let base_only = tensions
683            .iter()
684            .chain(&radial)
685            .chain(&guides)
686            .chain(&jumps)
687            .chain(&slack)
688            .chain(&detuning)
689            .chain(&condition)
690            .chain(&check_places)
691            .all(|&i| i < base.len());
692        Self {
693            gear: sim.machine.motors().iter().map(gear).collect(),
694            parts: sim.machine.motors().iter().map(|m| if views { parts(m) } else { None }).collect(),
695            part_sums: vec![[(0.0, 0.0); 4]; motors],
696            lost: vec![0.0; losses.len()],
697            start: (energies.iter().map(|&i| machine_signals[i]).collect(), windings, capacitors, sim.payload_energy),
698            end: (windings, capacitors, sim.payload_energy),
699            crash: (sim.crash_energy, sim.crash_energy),
700            losses,
701            energies,
702            supply: 0.0,
703            copper: vec![0.0; motors],
704            emf: vec![0.0; motors],
705            resistor: 0.0,
706            discharge: 0.0,
707            drawn: 0.0,
708            mains: 0.0,
709            line_loss: 0.0,
710            work: 0.0,
711            budget_skip: 0,
712            heat: vec![0.0; if sim.part_heating { sim.heated.len() } else { 0 }],
713            views,
714            machine_signals,
715            radial,
716            slack,
717            jumps,
718            jumps_start: 0.0,
719            detuning,
720            lowest_detuning: 1.0,
721            condition,
722            condition_peak: 0.0,
723            checks,
724            plan_checks,
725            radial_peak: 0.0,
726            guide_loads: vec![(0.0, 0.0); guides.len()],
727            guide_weights: vec![0.0; guides.len()],
728            guide_axes: guides
729                .iter()
730                .map(|&i| sim.machine.axes().iter().position(|a| infos[i].id == format!("axis.{}.guide_load", a.id)))
731                .collect(),
732            guide_speeds: vec![0.0; guides.len()],
733            pulley_radial: sim
734                .machine
735                .motors()
736                .iter()
737                .map(|m| infos.iter().position(|s| s.id == format!("pulley.{}.radial_load", m.id)))
738                .collect(),
739            radial_sums: vec![(0.0, 0.0); motors],
740            radial_peaks: vec![0.0; motors],
741            gear_life: vec![0.0; motors],
742            gear_bands: vec![Vec::new(); motors],
743            gear_spectrum: vec![Vec::new(); motors],
744            guides,
745            slack_start: 0.0,
746            cubic: vec![(0.0, 0.0); motors],
747            loads: sim
748                .machine
749                .motors()
750                .iter()
751                .enumerate()
752                .map(|(k, m)| MotorLoad {
753                    id: m.id.to_string(),
754                    dc_link_account: sim.control.dc_link_room(k).map(LinkAccount::new),
755                    ..MotorLoad::default()
756                })
757                .collect(),
758            pos: {
759                let (mut pos, mut speed) = (vec![0.0; motors], vec![0.0; motors]);
760                sim.machine.motor_state(&sim.state, &mut pos, &mut speed);
761                pos
762            },
763            speed: vec![0.0; motors],
764            steps: 0,
765            every: (1e-3 / sim.dt).round().max(1.0) as u64,
766            overload: sim.control.drives.iter().map(|d| (d.overload_nodes(), Vec::new())).collect(),
767            tensions,
768            sample: Vec::new(),
769            base_only,
770            belt_tension: None,
771            braking: vec![0.0; motors],
772            braking_peak: 0.0,
773            path: std::collections::VecDeque::new(),
774            path_error: [(0.0, 0.0, 0); 2],
775            path_series: Vec::new(),
776            tracking_error: [0.0; 2],
777            dwell_error: [0.0; 2],
778            groups: [false, true].map(|turn| {
779                sim.machine
780                    .axes()
781                    .iter()
782                    .enumerate()
783                    .filter(|(_, a)| (a.unit == "rad") == turn)
784                    .map(|(i, _)| i)
785                    .collect()
786            }),
787            pick_tracking: 0.0,
788            missed_before: sim.control.conveyor().map_or(0, |(c, _)| c.missed),
789            cartesian: ["x", "y", "z"].map(|id| sim.machine.axes().iter().position(|a| a.id == id && a.unit == "m")),
790            last_speed: None,
791            held: Vec::new(),
792        }
793    }
794
795    fn sample_now(&mut self, sim: &Sim) {
796        if self.base_only { sim.sample_base(&mut self.sample) } else { sim.sample(&mut self.sample) }
797    }
798
799    /// Adds the step the simulation has just made.
800    pub fn step(&mut self, sim: &Sim) {
801        sim.machine.motor_state(&sim.state, &mut self.pos, &mut self.speed);
802        if let Some((conveyor, Some(pass))) = sim.control.conveyor()
803            && let Some(part) = conveyor.gripping(pass, sim.time())
804        {
805            let n = part.len();
806            let (mut tool, mut vel) = (vec![0.0; n], vec![0.0; n]);
807            sim.machine.tool_state(&sim.state, &mut tool, &mut vel);
808            let along: f64 = tool.iter().zip(&part).zip(&conveyor.direction).map(|((t, p), d)| (t - p) * d).sum();
809            self.pick_tracking = self.pick_tracking.max(along.abs());
810        }
811        let sampled = self.steps.is_multiple_of(self.every);
812        if sampled {
813            self.sample_now(sim);
814            for &i in &self.tensions {
815                let (low, high) = self.belt_tension.unwrap_or((self.sample[i], self.sample[i]));
816                self.belt_tension = Some((low.min(self.sample[i]), high.max(self.sample[i])));
817            }
818            for &i in &self.radial {
819                self.radial_peak = self.radial_peak.max(self.sample[i]);
820            }
821            for (peak, signal) in self.radial_peaks.iter_mut().zip(&self.pulley_radial) {
822                if let Some(i) = *signal {
823                    *peak = peak.max(self.sample[i]);
824                }
825            }
826            if let Some(i) = self.condition {
827                self.condition_peak = self.condition_peak.max(self.sample[i]);
828            }
829            let axes = sim.machine.axes().len();
830            let (mut tool, mut rate) = (vec![0.0; axes], vec![0.0; axes]);
831            sim.machine.tool_state(&sim.state, &mut tool, &mut rate);
832            // A motor that drives no belt has no wrap (NaN).
833            for (load, wrap) in self.loads.iter_mut().zip(sim.machine.belt_wraps(&tool)).filter(|(_, w)| w.is_finite())
834            {
835                load.belt_wrap = Some(load.belt_wrap.map_or(wrap, |least| least.min(wrap)));
836            }
837            for (_, i, peak, sum) in &mut self.checks {
838                (*peak, *sum) = (peak.max(self.sample[*i].abs()), *sum + self.sample[*i]);
839            }
840            // A limit of the plan on the setpoint as the rigid model moves along it: the simulated machine's own
841            // signal counts what the plan cannot hold (the gears' ringing, the servo's steps).
842            if !self.plan_checks.is_empty() {
843                let mut rigid = Vec::new();
844                let c = &sim.control;
845                sim.machine.rigid_checks(&c.set_pos, &c.set_vel, &c.set_acc, &mut rigid);
846                for (_, i, peak) in &mut self.plan_checks {
847                    if let Some(v) = rigid.get(*i).filter(|v| v.is_finite()) {
848                        *peak = peak.max(v.abs());
849                    }
850                }
851            }
852            for (k, (&i, (peak, cubed))) in self.guides.iter().zip(&mut self.guide_loads).enumerate() {
853                let weight = self.guide_axes[k].map_or(1.0, |a| rate[a].abs());
854                (*peak, *cubed) = (peak.max(self.sample[i]), *cubed + self.sample[i].powi(3) * weight);
855                self.guide_weights[k] += weight;
856            }
857            if let (0, Some(i)) = (self.steps, self.slack) {
858                self.slack_start = self.sample[i];
859            }
860            if self.steps == 0 {
861                self.jumps_start = self.jumps.iter().map(|&i| self.sample[i]).sum();
862            }
863            // Steady speed: no axis accelerates by its setpoint, and one moves. A sweep through a resonance while
864            // speeding up is passed in moments; a cruise on it is not.
865            let steady = sim.control.set_acc.iter().all(|a| a.abs() <= 1e-9)
866                && sim.control.set_vel.iter().any(|v| v.abs() > 1e-9);
867            if let (true, Some(i)) = (steady, self.detuning) {
868                self.lowest_detuning = self.lowest_detuning.min(self.sample[i]);
869            }
870            // Path error: how far the tool is from the path the setpoint has drawn, wherever along it.
871            // Tracking error: how far it is from where the setpoint is right now.
872            let axes = sim.machine.axes().len();
873            let (mut tool, mut rate) = (vec![0.0; axes], vec![0.0; axes]);
874            sim.machine.tool_state(&sim.state, &mut tool, &mut rate);
875            for (axis, sum) in self.guide_axes.iter().zip(&mut self.guide_speeds) {
876                *sum += axis.map_or(0.0, |a| rate[a].abs());
877            }
878            if self.cartesian.iter().any(Option::is_some) {
879                let speed = self.cartesian.map(|i| i.map_or(0.0, |i| rate[i]));
880                let held = sim.control.payload_attached && !sim.control.gripper_acting();
881                if let (true, Some(last)) = (held, self.last_speed) {
882                    let a: [f64; 3] = std::array::from_fn(|k| (speed[k] - last[k]) / (self.every as f64 * sim.dt));
883                    self.held.push([a[2], a[0].hypot(a[1])]);
884                }
885                self.last_speed = Some(speed);
886            }
887            for (k, (signal, (cubed, weight))) in self.pulley_radial.iter().zip(&mut self.radial_sums).enumerate() {
888                if let Some(i) = *signal {
889                    (*cubed, *weight) =
890                        (*cubed + self.sample[i].powi(3) * self.speed[k].abs(), *weight + self.speed[k].abs());
891                }
892            }
893            // The oldest setpoint's place is reused for the newest: the plan at this moment, not the setpoint held from
894            // the last profile cycle, which would count a tool where the plan is now as off it by up to a cycle's way.
895            let mut newest =
896                if self.path.len() >= 500 { self.path.pop_front().unwrap_or_default() } else { Vec::new() };
897            newest.resize(axes, 0.0);
898            sim.control.plan_now(sim.time(), &mut newest);
899            self.path.push_back(newest);
900            let now = self.path.back().unwrap();
901            // The nearest piece, newest first. A piece is at least as far as the tool is beyond its extent along any one
902            // axis; one that is further than the nearest so far by more than a picometre (far above rounding) cannot be
903            // the nearest, and is skipped. The smallest distance is the same as over all pieces. The place (axes in m)
904            // and the turn (axes in rad) each by itself: each its own nearest piece.
905            let dwelling = sim.control.dwell_progress().is_some_and(|done| done >= 0.5);
906            let mut series = [sim.time(), 0.0, 0.0];
907            for (g, group) in self.groups.iter().enumerate() {
908                let mut off_path = distance_to_piece(&tool, now, now, group);
909                for (b, a) in self.path.iter().rev().zip(self.path.iter().rev().skip(1)) {
910                    let beyond = group
911                        .iter()
912                        .map(|&i| (tool[i] - a[i]).abs() - (b[i] - a[i]).abs())
913                        .fold(f64::NEG_INFINITY, f64::max);
914                    if !(beyond > off_path + 1e-12) {
915                        off_path = off_path.min(distance_to_piece(&tool, a, b, group));
916                    }
917                }
918                let (peak, squares, count) = self.path_error[g];
919                self.path_error[g] = (peak.max(off_path), squares + off_path * off_path, count + 1);
920                series[g + 1] = off_path;
921                self.tracking_error[g] = self.tracking_error[g].max(distance_to_piece(&tool, now, now, group));
922                if dwelling {
923                    let target = sim.control.planned_pos();
924                    self.dwell_error[g] = self.dwell_error[g].max(distance_to_piece(&tool, target, target, group));
925                }
926            }
927            self.path_series.push(series);
928        }
929        if self.views && (self.parts.iter().any(Option::is_some) || !self.losses.is_empty()) {
930            self.machine_signals.clear();
931            sim.machine.signals(&sim.state, &sim.machine_torque(), &mut self.machine_signals);
932        } else if self.gear.iter().any(Option::is_some) {
933            self.machine_signals.clear();
934            sim.machine.base_signals(&sim.state, &sim.machine_torque(), &mut self.machine_signals);
935        }
936        for (places, sums) in self.parts.iter().zip(&mut self.part_sums).filter_map(|(p, s)| Some((p.as_ref()?, s))) {
937            for (&i, (peak, squares)) in places.iter().zip(sums) {
938                let value = self.machine_signals[i];
939                (*peak, *squares) = (peak.max(value.abs()), *squares + value * value);
940            }
941        }
942        if self.steps >= self.budget_skip {
943            for (&i, lost) in self.losses.iter().zip(&mut self.lost) {
944                *lost += self.machine_signals[i] * sim.dt;
945            }
946            // `Sim::step` has worked out the parts' losses of this step already.
947            for (part, heat) in sim.heated.iter().zip(&mut self.heat) {
948                *heat += part.loss_power * sim.dt;
949            }
950            let drives = &sim.control.drives;
951            self.supply += drives.iter().map(|d| d.power).sum::<f64>() * sim.dt;
952            self.work += drives.iter().map(|d| d.shaft_power).sum::<f64>() * sim.dt;
953            for ((copper, emf), d) in self.copper.iter_mut().zip(&mut self.emf).zip(drives) {
954                *copper += d.copper_loss * sim.dt;
955                *emf += d.emf_loss * sim.dt;
956            }
957            // A shared DC link has one resistor, rectifier and line module, which every drive reports as its own.
958            let shared = sim.control.drive_params().shared_dc_link;
959            let link = |power: fn(&crate::drive::Drive) -> f64| -> f64 {
960                let total: f64 =
961                    if shared { drives.first().map_or(0.0, power) } else { drives.iter().map(power).sum() };
962                total * sim.dt
963            };
964            self.resistor += link(|d| d.resistor_power);
965            // Each drive discharges its own share of a shared link (`Drive::disabled_step`), so these add up.
966            self.discharge += drives.iter().map(|d| d.discharge_power).sum::<f64>() * sim.dt;
967            self.drawn += link(|d| d.rectifier_power);
968            self.mains += link(|d| d.mains_power);
969            self.line_loss += link(|d| d.line_loss);
970            if !self.losses.is_empty() {
971                let (windings, capacitors) = stored_electrically(sim);
972                self.end = (windings, capacitors, sim.payload_energy);
973                self.crash.1 = sim.crash_energy;
974            }
975        }
976        for (k, (i, peak, cubed)) in self.gear.iter_mut().enumerate().filter_map(|(k, gear)| Some((k, gear.as_mut()?)))
977        {
978            let (torque, speed) = (self.machine_signals[*i].abs(), self.speed[k].abs());
979            (*peak, *cubed) = (peak.max(torque), *cubed + torque.powi(3) * speed);
980            self.gear_life[k] += torque.powf(10.0 / 3.0) * speed;
981            // Capped, so that a run gone unstable cannot ask for a band per rad/s up to infinity.
982            let (bands, band) = (&mut self.gear_bands[k], ((speed / SPEED_BAND) as usize).min(4000));
983            if bands.len() <= band {
984                bands.resize(band + 1, 0.0);
985            }
986            bands[band] = bands[band].max(torque);
987            if torque >= TORQUE_FLOOR && speed > 0.0 {
988                let (spectrum, band) = (
989                    &mut self.gear_spectrum[k],
990                    (((torque / TORQUE_FLOOR).ln() / TORQUE_BAND.ln()) as usize).min(4000),
991                );
992                if spectrum.len() <= band {
993                    spectrum.resize(band + 1, 0.0);
994                }
995                spectrum[band] += speed;
996            }
997        }
998        for (k, load) in self.loads.iter_mut().enumerate() {
999            let torque = sim.control.drives[k].torque;
1000            load.peak_torque = load.peak_torque.max(torque.abs());
1001            // The RMS phase current: with field weakening the d current flows too.
1002            let (current, power) = (sim.control.drives[k].phase_current(), sim.control.drives[k].power);
1003            load.rms_current += current * current;
1004            let heating = sim.control.drives[k].thermal_current(sim.control.drive_params_of(k));
1005            load.thermal_current += heating * heating;
1006            if let crate::drive::Motor::Stepper(_) = sim.control.drive_params_of(k).motor {
1007                let angle = sim.control.drives[k].phases.load_angle.abs();
1008                load.load_angle = Some(load.load_angle.unwrap_or(0.0).max(angle));
1009            }
1010            load.peak_current = load.peak_current.max(current.abs());
1011            // Each motor's own drive and motor (`[drive.<id>]`, `[motor.<id>]`, `[parts.<id>]`).
1012            let own = sim.control.drive_params_of(k);
1013            if own.drive_max_current.is_finite() {
1014                load.peak_current = load.peak_current.max(own.current_for(sim.control.drives[k].torque_demand).abs());
1015            }
1016            // The running stretch: energy fed back (positive) or drawn (negative), pushed as one event when the sign turns.
1017            let fed = -power * sim.dt;
1018            if self.braking[k] * fed < 0.0 {
1019                if let Some(account) = &mut load.dc_link_account {
1020                    account.push(self.braking[k]);
1021                }
1022                self.braking[k] = 0.0;
1023            }
1024            self.braking[k] += fed;
1025            if power >= 0.0 {
1026                load.energy_in += power * sim.dt;
1027            } else {
1028                load.energy_regenerated -= power * sim.dt;
1029                load.peak_regenerated_power = load.peak_regenerated_power.max(-power);
1030                load.largest_regeneration = load.largest_regeneration.max(self.braking[k]);
1031            }
1032            load.rms_torque += torque * torque;
1033            load.iron_loss += sim.control.drives[k].iron_loss;
1034            self.cubic[k] =
1035                (self.cubic[k].0 + torque.abs().powi(3) * self.speed[k].abs(), self.cubic[k].1 + self.speed[k].abs());
1036            let drive = &sim.control.drives[k];
1037            load.resistor_energy += drive.resistor_power * sim.dt;
1038            load.discharge_energy += drive.discharge_power * sim.dt;
1039            load.peak_resistor_power = load.peak_resistor_power.max(drive.resistor_power);
1040            load.peak_dc_link_voltage = load.peak_dc_link_voltage.max(drive.dc_voltage);
1041            // The line module's load either way, on the DC link's side: drawn into it (the line gives 1 / efficiency of
1042            // that, `rectifier_power`), or fed back as the DC link gives it (before its losses).
1043            let efficiency = sim.control.drive_params_of(k).line_efficiency;
1044            let through = efficiency * drive.rectifier_power + drive.mains_power / efficiency;
1045            load.mains_energy += drive.mains_power * sim.dt;
1046            load.line_module_energy += through * sim.dt;
1047            load.peak_line_module_power = load.peak_line_module_power.max(through);
1048            load.peak_speed = load.peak_speed.max(self.speed[k].abs());
1049            // What the velocity loop asks for, not what the drive delivers: a drive on its torque limit
1050            // delivers the curve and no more, so the delivered torque would never show a cycle beyond it.
1051            let (low, high) = sim.control.motor_torque_curve(k, self.speed[k]);
1052            let demand = drive.torque_demand;
1053            let available = if demand >= 0.0 { high } else { -low };
1054            load.utilisation = load.utilisation.max(demand.abs() / available.max(1e-9));
1055            if sampled {
1056                load.points.push((self.speed[k], torque));
1057                if sim.control.drive_params_of(k).overload.is_some() {
1058                    self.overload[k].1.push(((self.steps + 1) as f64 * sim.dt, drive.overload_nodes()));
1059                }
1060            }
1061        }
1062        let (drives, p) = (&sim.control.drives, sim.control.drive_params());
1063        let braking: f64 = match (p.dc_link, p.shared_dc_link) {
1064            (true, true) => drives.first().map_or(0.0, |d| d.resistor_power),
1065            (true, false) => drives.iter().map(|d| d.resistor_power).sum(),
1066            (false, _) => drives.iter().map(|d| (-d.power).max(0.0)).sum(),
1067        };
1068        self.braking_peak = self.braking_peak.max(braking);
1069        self.steps += 1;
1070    }
1071
1072    pub fn finish(mut self, sim: &Sim, duration: f64) -> CycleLoad {
1073        let steps = self.steps.max(1) as f64;
1074        for (k, load) in self.loads.iter_mut().enumerate() {
1075            load.rms_torque = (load.rms_torque / steps).sqrt();
1076            load.rms_current = (load.rms_current / steps).sqrt();
1077            if let (Some(account), true) = (&mut load.dc_link_account, self.braking[k] != 0.0) {
1078                account.push(self.braking[k]);
1079            }
1080            load.thermal_current = (load.thermal_current / steps).sqrt();
1081            load.iron_loss /= steps;
1082            load.cubic_mean_torque =
1083                if self.cubic[k].1 > 0.0 { (self.cubic[k].0 / self.cubic[k].1).cbrt() } else { 0.0 };
1084            load.gearbox_torque = self.gear[k].map(|(_, peak, cubed)| {
1085                (peak, if self.cubic[k].1 > 0.0 { (cubed / self.cubic[k].1).cbrt() } else { 0.0 })
1086            });
1087            load.mean_speed = self.cubic[k].1 / steps;
1088            load.gearbox_life_torque = self.gear[k]
1089                .map(|_| if self.cubic[k].1 > 0.0 { (self.gear_life[k] / self.cubic[k].1).powf(0.3) } else { 0.0 });
1090            load.gearbox_torque_by_speed = std::mem::take(&mut self.gear_bands[k]);
1091            load.gearbox_torque_spectrum = self.gear_spectrum[k].iter().map(|speed| speed / steps).collect();
1092            let (cubed, weight) = self.radial_sums[k];
1093            load.radial_load_equivalent =
1094                self.pulley_radial[k].map(|_| if weight > 0.0 { (cubed / weight).cbrt() } else { 0.0 });
1095            load.radial_load_peak = self.pulley_radial[k].map(|_| self.radial_peaks[k]);
1096            let p = sim.control.drive_params_of(k);
1097            load.winding_rise = p.settled_rise(load.thermal_current, load.iron_loss);
1098            // The housing carries all of the loss through its share of the resistance: the winding's rise less what the
1099            // winding's own share adds to it of the copper loss, which is the winding's rise less the iron's part.
1100            if let (true, Some(n)) = (p.heating, &p.thermal_nodes) {
1101                let (s, iron) = (n.winding_share, p.iron_heating(load.iron_loss));
1102                load.housing_rise = load.winding_rise - s * (load.winding_rise - (1.0 - s) * iron);
1103            }
1104            if let Some(o) = &p.overload {
1105                let (start, samples) = &self.overload[k];
1106                let end = (self.steps as f64 * sim.dt, sim.control.drives[k].overload_nodes());
1107                load.drive_overload = repeating_peak(o, *start, samples, end);
1108            }
1109            load.thermal_utilisation = load.rms_torque / sim.control.drive_params_of(k).rated_torque;
1110            load.torque_parts =
1111                self.parts[k].map(|_| self.part_sums[k].map(|(peak, squares)| (peak, (squares / steps).sqrt())));
1112            // A tripped drive's DC link stays where it tripped, also when that was before the measured pass.
1113            load.peak_dc_link_voltage = load.peak_dc_link_voltage.max(sim.control.drives[k].dc_voltage);
1114        }
1115        self.sample_now(sim);
1116        let budget = self.budget(sim);
1117        let part_rises = sim
1118            .heated
1119            .iter()
1120            .zip(&self.heat)
1121            .map(|(h, heat)| (h.part.clone(), h.resistance * heat / duration))
1122            .collect();
1123        let samples = self.path_error[0].2.max(1) as f64;
1124        // Per guide: its equivalent load (cubic mean over distance) and mean speed. The life estimate is about the guide
1125        // that wears out first: life in hours goes with 1/(P^3 v); the peak is the highest of all guides.
1126        let equivalent = |g: usize| equivalent_load(self.guide_loads[g].1, self.guide_weights[g]);
1127        let speed = |g: usize| self.guide_axes[g].map(|_| self.guide_speeds[g] / samples);
1128        let wear = |g: usize| equivalent(g).powi(3) * speed(g).unwrap_or(1.0);
1129        let guide = (0..self.guide_loads.len()).max_by(|&a, &b| wear(a).total_cmp(&wear(b)));
1130        let peak = self.guide_loads.iter().map(|g| g.0).reduce(f64::max);
1131        let guide_load = guide.zip(peak).map(|(g, peak)| (peak, equivalent(g)));
1132        let guide_speed = guide.and_then(speed);
1133        let guides = (0..self.guide_loads.len())
1134            .map(|g| GuideLoad { peak: self.guide_loads[g].0, equivalent: equivalent(g), speed: speed(g) })
1135            .collect();
1136        CycleLoad {
1137            duration,
1138            belt_tension: self.belt_tension,
1139            belt_slack_time: self.slack.map(|i| self.sample[i] - self.slack_start),
1140            belt_tooth_jumps: (!self.jumps.is_empty())
1141                .then(|| self.jumps.iter().map(|&i| self.sample[i]).sum::<f64>() - self.jumps_start),
1142            belt_span_detuning: self.detuning.map(|_| self.lowest_detuning),
1143            radial_load_peak: (!self.radial.is_empty()).then_some(self.radial_peak),
1144            condition_peak: self.condition.map(|_| self.condition_peak),
1145            guide_load,
1146            guide_speed,
1147            guides,
1148            path_error_peak: self.path_error[0].0,
1149            path_error_rms: (self.path_error[0].1 / self.path_error[0].2.max(1) as f64).sqrt(),
1150            tracking_error_peak: self.tracking_error[0],
1151            dwell_error_peak: self.dwell_error[0],
1152            // + 0.0: a machine without turning axes keeps the peaks' start of -0.0, which printed as "-0.000e0".
1153            path_angle_error_peak: self.path_error[1].0 + 0.0,
1154            path_angle_error_rms: (self.path_error[1].1 / self.path_error[1].2.max(1) as f64).sqrt(),
1155            tracking_angle_error_peak: self.tracking_error[1] + 0.0,
1156            dwell_angle_error_peak: self.dwell_error[1] + 0.0,
1157            path_error_series: {
1158                let start = self.path_series.first().map_or(0.0, |s| s[0]);
1159                self.path_series.iter().map(|&[t, place, turn]| [t - start, place, turn]).collect()
1160            },
1161            tripped: sim.control.drives.iter().any(|d| d.tripped) || sim.control.fault.is_some(),
1162            motors: self.loads,
1163            budget,
1164            part_rises,
1165            checks: std::mem::take(&mut self.checks)
1166                .into_iter()
1167                .map(|(c, _, peak, sum)| {
1168                    let value = if c.life { samples / sum } else { peak };
1169                    (c, value)
1170                })
1171                .chain(std::mem::take(&mut self.plan_checks).into_iter().map(|(c, _, peak)| (c, peak)))
1172                .chain(cam_checks(sim.machine.as_ref()))
1173                .collect(),
1174            clearance: (!sim.obstacles.is_empty()).then_some(sim.least_clearance),
1175            contact: sim.contact.clone(),
1176            own_clearance: sim.own_parts.own.as_ref().map(|own| own.clearance),
1177            braking_power_peak: self.braking_peak,
1178            warm_start: None,
1179            conveyor: sim.control.conveyor().map(|(c, _)| {
1180                let missed = c.missed - self.missed_before;
1181                ConveyorLoad {
1182                    picks_per_minute: 60.0 / duration,
1183                    tracking_peak: self.pick_tracking,
1184                    missed,
1185                    missed_per_minute: (missed as f64 * 60.0 / duration)
1186                        .max(c.offered_per_minute() - 60.0 / duration)
1187                        .max(0.0),
1188                }
1189            }),
1190            held_accelerations: self.held,
1191        }
1192    }
1193
1194    /// The energy budget of the steps counted, where the machine reports its losses.
1195    fn budget(&self, sim: &Sim) -> Option<EnergyBudget> {
1196        if self.losses.is_empty() {
1197            return None;
1198        }
1199        let own = sim.machine.signal_infos();
1200        // The stores where the flows stop, after the last step counted: a cycle's measured pass ends with the step in
1201        // which the next pass begins, which is not counted, as the step in which it began is not.
1202        let (now, (windings, capacitors, payload)) = (&self.machine_signals, self.end);
1203        let row = |id: &str, owner_key: &str, quantity_key: &str, energy: f64| BudgetRow {
1204            id: id.into(),
1205            owner_key: owner_key.into(),
1206            quantity_key: quantity_key.into(),
1207            energy,
1208        };
1209        let mut rows: Vec<BudgetRow> = sim
1210            .machine
1211            .motors()
1212            .iter()
1213            .zip(&self.copper)
1214            .map(|(m, copper)| row(&format!("copper.{}", m.id), m.key, "budget-copper", *copper))
1215            .collect();
1216        // The magnets' and iron's share of a back-EMF constant that is not the torque constant: only where there is one.
1217        rows.extend(
1218            sim.machine
1219                .motors()
1220                .iter()
1221                .zip(&self.emf)
1222                .filter(|(_, emf)| **emf != 0.0)
1223                .map(|(m, emf)| row(&format!("emf.{}", m.id), m.key, "budget-emf", *emf)),
1224        );
1225        let p = sim.control.drive_params();
1226        if p.dc_link {
1227            rows.push(row("resistor", "group-drive", "budget-resistor", self.resistor));
1228            rows.push(row("discharge", "group-drive", "budget-discharge", self.discharge));
1229        }
1230        if p.regenerative {
1231            rows.push(row("mains", "group-drive", "budget-mains", self.mains));
1232        }
1233        // The line module (or an S210's rectifier) loses its share of what it draws whether or not it feeds back.
1234        if p.dc_link {
1235            rows.push(row("line_module", "group-drive", "budget-line-module", self.line_loss));
1236        }
1237        rows.extend(
1238            self.losses
1239                .iter()
1240                .zip(&self.lost)
1241                .map(|(&i, lost)| row(&own[i].id, &own[i].owner_key, &own[i].quantity_key, *lost)),
1242        );
1243        rows.push(row("windings", "group-drive", "budget-windings", windings - self.start.1));
1244        if p.dc_link {
1245            rows.push(row("capacitors", "group-drive", "budget-capacitors", capacitors - self.start.2));
1246        }
1247        rows.extend(
1248            self.energies
1249                .iter()
1250                .zip(&self.start.0)
1251                .map(|(&i, start)| row(&own[i].id, &own[i].owner_key, &own[i].quantity_key, now[i] - start)),
1252        );
1253        // A payload picked up brings energy into the machine, one put down takes it away.
1254        rows.push(row("payload", "group-energy", "budget-payload", self.start.3 - payload));
1255        // What the stops at obstacles took out of the machine (effects.crash).
1256        if sim.crash {
1257            rows.push(row("crash", "group-energy", "budget-crash", self.crash.1 - self.crash.0));
1258        }
1259        // With the DC link simulated the supply is what the rectifier drew, counted on its own: that the capacitors,
1260        // the resistor, the line module and the drives account for it is the check of `electrical_unaccounted`.
1261        let supply = if p.dc_link { self.drawn } else { self.supply };
1262        Some(EnergyBudget { supply, rows, shaft_work: self.work })
1263    }
1264}
1265
1266/// Energy in the windings' inductance, and in the DC link capacitors where the DC link is simulated.
1267fn stored_electrically(sim: &Sim) -> (f64, f64) {
1268    let p = sim.control.drive_params();
1269    let drives = &sim.control.drives;
1270    let windings = drives.iter().enumerate().map(|(k, d)| d.magnetic_energy(sim.control.drive_params_of(k))).sum();
1271    // A link of its own has its drive's capacitance (a drive named per motor brings its own); a shared one each drive's
1272    // share of the shared `[drive]`'s, as `drive::shared_dc_link` steps it.
1273    let capacitance =
1274        |k: usize| if p.shared_dc_link { p.dc_capacitance } else { sim.control.drive_params_of(k).dc_capacitance };
1275    let capacitors = drives.iter().enumerate().map(|(k, d)| 0.5 * capacitance(k) * d.dc_voltage * d.dc_voltage).sum();
1276    (windings, if p.dc_link { capacitors } else { 0.0 })
1277}
1278
1279/// Runs the configured cycle and measures its second pass, when the machine has settled into it. If a
1280/// drive trips before, the cycle never gets there: what is measured then is the run up to the trip.
1281///
1282/// With effects.thermal_warm_start, where windings (effects.winding_heating) or parts (effects.thermal_feedback) act
1283/// back on the run with their warmth: the cycle repeats from cold until a pass that starts with them at the rises it
1284/// settles at, within `WARM_START_TOLERANCE_K`; each pass ends with them put at the rises it settles at, and the pass
1285/// after it is measured. At most `WARM_START_PASSES` warm passes; the last is the measured one, converged or not
1286/// (`CycleLoad::warm_start`). With thermal time constants of minutes to an hour, a cycle of seconds would otherwise
1287/// see every part at the temperature it started with.
1288///
1289/// Where the config gives a path in place of the cycle (`[path]`, `sim::with_path`), that path is planned and measured
1290/// instead, as `analyse_trajectory` measures it: so the verdicts, the catalogue search and the optimiser judge the path's
1291/// run, repeated with the windings and parts at the rises it settles at under effects.thermal_warm_start.
1292pub fn analyse_cycle(sim: &mut Sim) -> Result<CycleLoad, CommandError> {
1293    analyse_cycle_with(sim, true)
1294}
1295
1296/// `analyse_cycle`, with the effect views (`MotorLoad::torque_parts`, `CycleLoad::budget`) only where `views` asks
1297/// for them: they cost one more evaluation of the machine per step, and no verdict needs them.
1298pub fn analyse_cycle_with(sim: &mut Sim, views: bool) -> Result<CycleLoad, CommandError> {
1299    // Every sequential batch of cycles (searches, the sweeps below) goes through here: where a job is cancelled.
1300    check_cancelled();
1301    if let Some(points) = sim.plan_configured_path() {
1302        return analyse_trajectory_with(sim, points?, views);
1303    }
1304    sim.command(Command::StartCycle)?;
1305    let warm = sim.warm_start && !fed_back_rises(sim).is_empty();
1306    let mut tally = Tally::new(sim, views);
1307    let (mut passes, mut last, mut start) = (0usize, sim.control.cycle_passes(), 0.0);
1308    let (mut started_at, mut before) = (Vec::new(), None);
1309    // The warm spans measured so far, of `period` passes each, from the pass `span_from`; the settled rises per pass.
1310    let (mut spans, mut period, mut span_from, mut history) = (0usize, 1usize, 2usize, Vec::new());
1311    let (mut repeat, mut measured) = (None, None);
1312    loop {
1313        sim.step();
1314        // The controller counts the passes: a cycle of one segment never changes its segment index.
1315        let now = sim.control.cycle_passes();
1316        if now != last {
1317            passes += 1;
1318            let span_ends = passes == span_from + period;
1319            if warm && passes >= 3 && span_ends {
1320                // A measured span ended: it is the result, or the next starts at the rises it settles at.
1321                let load = std::mem::replace(&mut tally, Tally::new(sim, views)).finish(sim, sim.time() - start);
1322                let was = period;
1323                let next = warm_pass(
1324                    sim,
1325                    &started_at,
1326                    &load,
1327                    spans,
1328                    &mut before,
1329                    &mut period,
1330                    &mut history,
1331                    Some(&mut repeat),
1332                );
1333                if let Some(warm_start) = next {
1334                    let _ = sim.command(Command::Stop);
1335                    // After the repeat span (`warm_pass`) the span before it is the measured one.
1336                    let load = if warm_start.repeat.is_some() { measured.take().unwrap_or(load) } else { load };
1337                    return Ok(CycleLoad { warm_start: Some(warm_start), ..load });
1338                }
1339                if repeat.is_some() {
1340                    measured = Some(load);
1341                }
1342                spans = if period == was { spans + 1 } else { 0 };
1343                span_from = passes;
1344            }
1345            if passes == 2 || warm && passes > 2 && span_from == passes {
1346                started_at = fed_back_rises(sim);
1347                // The measured pass begins: what was added up on the way here goes. The energy budget starts from
1348                // the state after this step, so it leaves the step out.
1349                (start, tally) = (sim.time(), Tally::new(sim, views));
1350                tally.budget_skip = 1;
1351            } else if passes == 3 {
1352                break;
1353            }
1354        }
1355        last = now;
1356        if sim.time() > 600.0 {
1357            return Err(CommandError { key: "error-cycle-timeout" });
1358        }
1359        // A conveyor cycle ends where no part can be picked any more.
1360        if !sim.control.busy() && sim.control.enabled() {
1361            return Err(CommandError { key: "error-conveyor-unreachable" });
1362        }
1363        tally.step(sim);
1364        // Drives that tripped on DC link overvoltage never finish the cycle; the verdicts say why.
1365        if !sim.control.enabled() {
1366            break;
1367        }
1368    }
1369    let _ = sim.command(Command::Stop);
1370    // Stopped in the repeat span: the span before it stays the measured one, the repeat not told.
1371    if let (Some((_, done)), Some(load)) = (repeat, measured) {
1372        return Ok(CycleLoad { warm_start: Some(done), ..load });
1373    }
1374    let duration = sim.time() - start;
1375    // Stopped before a measured pass ended (a trip, or a crash): not converged, where a warm pass had begun; before
1376    // that the run was measured from cold.
1377    let warm_start =
1378        (warm && passes > 2).then(|| WarmStart { passes: passes - 2, change: f64::INFINITY, period: 1, repeat: None });
1379    Ok(CycleLoad { warm_start, ..tally.finish(sim, duration) })
1380}
1381
1382/// Runs a path given as poses at times (see `Command::Trajectory`) and measures it, with 0.3 s of rest
1383/// after its end so that the settling of the tool counts. With effects.thermal_warm_start as `analyse_cycle`: the
1384/// path counts as a cycle that repeats, and every pass starts from a copy of the machine's start state
1385/// (`Sim::snapshot`) with the rises the previous pass settled, so nothing that still rings carries over.
1386pub fn analyse_trajectory(sim: &mut Sim, points: Vec<(f64, Vec<f64>)>) -> Result<CycleLoad, CommandError> {
1387    analyse_trajectory_with(sim, points, true)
1388}
1389
1390/// `analyse_trajectory`, with the effect views only where `views` asks for them (see `analyse_cycle_with`).
1391pub fn analyse_trajectory_with(
1392    sim: &mut Sim,
1393    points: Vec<(f64, Vec<f64>)>,
1394    views: bool,
1395) -> Result<CycleLoad, CommandError> {
1396    let end = points.last().map_or(0.0, |p| p.0) + 0.3;
1397    let warm = sim.warm_start && !fed_back_rises(sim).is_empty();
1398    // Every pass starts from the machine's start state (a copy taken here), with the rises the previous one settled.
1399    let start_state = sim.snapshot();
1400    let mut before = None;
1401    for passes in 0.. {
1402        let started_at = fed_back_rises(sim);
1403        sim.command(Command::Trajectory(points.clone()))?;
1404        let (mut tally, start) = (Tally::new(sim, views), sim.time());
1405        while sim.time() - start < end {
1406            sim.step();
1407            tally.step(sim);
1408        }
1409        let load = tally.finish(sim, end);
1410        if !warm {
1411            return Ok(load);
1412        }
1413        if !sim.control.enabled() {
1414            return Ok(CycleLoad {
1415                warm_start: (passes > 0).then_some(WarmStart {
1416                    passes,
1417                    change: f64::INFINITY,
1418                    period: 1,
1419                    repeat: None,
1420                }),
1421                ..load
1422            });
1423        }
1424        // Every pass starts from the same state: the passes cannot differ but by their rises, so there is no period.
1425        let (mut period, mut history) = (1, Vec::new());
1426        if let Some(warm_start) =
1427            warm_pass(sim, &started_at, &load, passes, &mut before, &mut period, &mut history, None)
1428        {
1429            return Ok(CycleLoad { warm_start: Some(warm_start), ..load });
1430        }
1431        let rises = fed_back_rises(sim);
1432        sim.restore(&start_state).expect("a snapshot of this very simulation");
1433        set_rises(sim, &rises);
1434    }
1435    unreachable!()
1436}
1437
1438/// The motor's S1 torque at a speed, as Siemens sizes a cycle (RMS torque at the mean speed against it): from the static
1439/// torque kt I_0 at standstill (`motor.stall_current_a`) straight to the rated torque at the rated speed, and on along
1440/// that line above it. `None` where the config has no stall current. Where it has the maker's printed curve
1441/// (`motor.s1_curve_speed_rad_s` and `motor.s1_curve_torque_nm`, digitised from the graph) the torque is read from it,
1442/// linearly between its points (`drive::s1_interpolated`), with the bend the voltage limit gives above the rated speed.
1443pub fn s1_torque(cfg: &Config, speed: f64) -> Result<Option<f64>, ConfigError> {
1444    let curve = crate::drive::s1_curve_of(cfg)?;
1445    if !curve.is_empty() {
1446        return Ok(Some(crate::drive::s1_interpolated(&curve, speed)));
1447    }
1448    if cfg.get("motor.stall_current_a").is_err() {
1449        return Ok(None);
1450    }
1451    let still = cfg.positive("motor.torque_constant_nm_a")? * cfg.positive("motor.stall_current_a")?;
1452    let (rated, rated_speed) = (cfg.positive("drive.rated_torque_nm")?, cfg.positive("drive.rated_speed_rad_s")?);
1453    Ok(Some(crate::drive::s1_line(still, rated, rated_speed, speed)))
1454}
1455
1456/// One judgement of a cycle: a value the cycle reached against what a part allows.
1457#[derive(Debug, Clone, PartialEq)]
1458pub struct Verdict {
1459    /// What is judged, e.g. "motor-thermal" or "belt-tension".
1460    pub check: &'static str,
1461    /// The motor it concerns, where it concerns one.
1462    pub motor: Option<usize>,
1463    pub value: f64,
1464    pub limit: f64,
1465    pub ok: bool,
1466}
1467
1468/// Whether a value or a limit of these verdicts is NaN or infinite: what an unstable, diverging loop leaves behind
1469/// (a result that is not a number is not a pass either). Front ends say so (`verdict-not-finite`).
1470pub fn any_not_finite<'a>(verdicts: impl IntoIterator<Item = &'a Verdict>) -> bool {
1471    verdicts.into_iter().any(|v| !v.value.is_finite() || !v.limit.is_finite())
1472}
1473
1474/// Keys that no default config has and a config file may add (see `load_config`): ratings that `verdicts` judges, the
1475/// `[conveyor]` table (`conveyor::Conveyor`), whose cycle picks from a belt, the `[gripper]` table and the motor kinds'
1476/// own keys (`drive::Motor`: a stepper's and an induction motor's).
1477pub const RATINGS_BEYOND_DEFAULT: [&str; 92] = [
1478    // A guide's moment ratings (Mx, My, Mz), which its equivalent load takes where a machine gives the moments.
1479    "ratings.guide_moment_x_nm",
1480    "ratings.guide_moment_y_nm",
1481    "ratings.guide_moment_z_nm",
1482    // Optional end stops of a joint that turns on without stops of its own.
1483    "joint.stop_min_deg",
1484    "joint.stop_max_deg",
1485    // A guide set's carriages and rail length for the catalogue's guides, and the share of the moved mass and of the guide
1486    // friction that the config's own guide carriages are (`catalog::mechanics`).
1487    "ratings.guide_carriages",
1488    "ratings.guide_rail_length_m",
1489    "mass.guide_carriages_kg",
1490    "friction_x.seal_drag_n",
1491    "friction.seal_drag_n",
1492    "slide.seal_drag_n",
1493    // The gear's presliding stiffnesses over K1 and the rack's pressure angle (`mech::Gearbox`, `transmission::RackPinion`).
1494    "gearbox.hysteresis_stiffness_factor",
1495    "gearbox.mesh_stiffness_factor",
1496    "rack.pressure_angle_deg",
1497    // The housing's highest rise (`charts::utilisation`).
1498    "ratings.housing_max_rise_k",
1499    // The maker's printed S1 curve (`s1_torque`).
1500    "motor.s1_curve_speed_rad_s",
1501    "motor.s1_curve_torque_nm",
1502    // What `stop::study` judges the worst stop against.
1503    "ratings.max_stopping_distance_m",
1504    "ratings.max_stopping_angle_rad",
1505    // The gripper's time and hold (`gripper::Gripper`), and the hold's safety factor.
1506    "effects.gripper_time",
1507    "gripper",
1508    "gripper.kind",
1509    "gripper.close_s",
1510    "gripper.open_s",
1511    "gripper.cup_volume_m3",
1512    "gripper.generator_flow_m3_s",
1513    "gripper.vacuum_pa",
1514    "gripper.holding_pressure_pa",
1515    "gripper.vent_flow_m3_s",
1516    "gripper.release_pressure_pa",
1517    "gripper.cup_area_m2",
1518    "gripper.friction_coefficient",
1519    "ratings.gripper_safety_factor",
1520    // A path in place of the cycle (`sim::with_path`).
1521    "path",
1522    "path.file",
1523    "path.program",
1524    "path.time_optimal",
1525    // How fast a robot program turns the tool (`program::read_with`).
1526    "program",
1527    "program.orientation_speed_rad_s",
1528    // The factor on a program's programmed feeds, 1 without it (`control::Controller::feed_override`).
1529    "profile.feed_override",
1530    "ratings.settling_tolerance_rad",
1531    // The tool's error while it moves ("tracking", "tracking-angle"): no shipped config asks a limit for it.
1532    "ratings.tracking_tolerance_m",
1533    "ratings.tracking_tolerance_rad",
1534    "ratings.pulley_max_torque_nm",
1535    "ratings.motor_bearing_load_rating_n",
1536    // Where the 3D view finds CAD meshes of the parts (`<id>.glb`), a directory relative to the config file (sim-app).
1537    "scene",
1538    "scene.meshes_dir",
1539    "conveyor",
1540    "conveyor.enabled",
1541    "conveyor.direction",
1542    "conveyor.speed_m_s",
1543    "conveyor.ramp_s",
1544    "conveyor.origin",
1545    "conveyor.length_m",
1546    "conveyor.pitch_s",
1547    "conveyor.arrivals_s",
1548    "conveyor.window_m",
1549    "conveyor.lift",
1550    "conveyor.grip_s",
1551    "conveyor.release_s",
1552    "conveyor.place",
1553    "conveyor.place_direction",
1554    "conveyor.place_speed_m_s",
1555    "conveyor.tracking_tolerance_m",
1556    "motor.kind",
1557    "motor.rotor_teeth",
1558    "motor.detent_torque_nm",
1559    "effects.detent_torque",
1560    "drive.microsteps",
1561    "drive.stepper_current_a",
1562    "motor.rotor_resistance_ohm",
1563    "motor.magnetizing_inductance_h",
1564    "motor.stator_leakage_inductance_h",
1565    "motor.rotor_leakage_inductance_h",
1566    "motor.rated_voltage_v",
1567    "motor.rated_frequency_hz",
1568    "drive.induction_control",
1569    "drive.vf_boost_v",
1570    "drive.vf_slip_compensation",
1571    // The positioning accuracy test (`accuracy::study`): its two effects, the axes they act on, and its ratings.
1572    "effects.thermal_growth",
1573    "effects.lead_error",
1574    "accuracy",
1575    "accuracy.axes",
1576    "accuracy.screw_expansion_per_k",
1577    "accuracy.belt_expansion_per_k",
1578    "ratings.max_positioning_error_m",
1579    "ratings.max_repeatability_m",
1580    "ratings.max_positioning_error_rad",
1581    "ratings.max_repeatability_rad",
1582    // The installation conditions of a catalogue drive, which derate its currents (`catalog::drive_derating`).
1583    "ratings.drive_ambient_c",
1584    "ratings.drive_altitude_m",
1585    "ratings.drive_pulse_frequency_hz",
1586];
1587
1588fn at_most(check: &'static str, motor: Option<usize>, value: f64, limit: f64) -> Verdict {
1589    Verdict { check, motor, value, limit, ok: value <= limit }
1590}
1591
1592fn at_least(check: &'static str, motor: Option<usize>, value: f64, limit: f64) -> Verdict {
1593    Verdict { check, motor, value, limit, ok: value >= limit }
1594}
1595
1596/// The checks whose value has to stay at or above its limit ("belt-least-tension": above); every other check's value has to
1597/// stay at or below it.
1598pub const AT_LEAST: [&str; 11] = [
1599    "belt-least-tension",
1600    "pulley-bearing-life",
1601    "gearbox-life",
1602    "gearbox-gearing-life",
1603    "motor-bearing-life",
1604    "guide-life",
1605    "belt-span-resonance",
1606    "screw-life",
1607    "strain-wave-life",
1608    "collision",
1609    "self-collision",
1610];
1611
1612/// Above 1 it fails (but "belt-least-tension" at exactly 1). A check of `AT_LEAST` at or below zero (a contact, "collision" at no
1613/// clearance; a belt section pushed, "belt-least-tension" with a negative tension) is infinitely far over: limit over value would
1614/// be negative there, and read as a margin above 100 %.
1615pub fn utilisation(v: &Verdict) -> f64 {
1616    if AT_LEAST.contains(&v.check) && v.value <= 0.0 {
1617        return f64::INFINITY;
1618    }
1619    if AT_LEAST.contains(&v.check) { v.limit / v.value } else { v.value / v.limit }
1620}
1621
1622/// Judges a cycle against the motor and drive data and the `[ratings]` of the config. A rating that the
1623/// config leaves out is not judged. Gearbox and pulley torques are those the machine reports at the gearbox
1624/// output (`MotorLoad::gearbox_torque`), so what the rotor's own inertia takes is not in them, and a load
1625/// that drives the gearbox back counts with what it puts on the output. On a machine that does not report
1626/// them, these three checks are not made.
1627///
1628/// "motor-peak" judges the torque the velocity loop asks for before the torque limit (`Drive::torque_demand`),
1629/// so a cycle that sits on the limit fails it.
1630///
1631/// "gearbox-thermal" and "guide-thermal" judge, with effects.part_heating (or thermal_feedback, which warms the parts
1632/// too), the hottest gearbox and guide where they settle on the cycle (`CycleLoad::part_rises`) against
1633/// `thermal.<kind>_max_rise_k`. Without either they are not judged.
1634///
1635/// "gearbox-continuous" judges the cubic mean of that torque against the gearbox's rated torque, as gearbox
1636/// makers do; it used to judge the RMS torque, which is for motors and their heat.
1637/// "belt-least-tension" also fails when any belt section spent time without tension.
1638/// With `effects.dc_link` the braking checks judge the simulated DC link: what the capacitors held at the
1639/// highest voltage, the mean and peak power the resistor burned, and the highest voltage against the trip
1640/// level. Without it they are estimated from the energy the motor fed back, as before.
1641///
1642/// "line-module-continuous" and "line-module-peak" judge, with effects.regenerative_supply (and the DC link), the line
1643/// module's mean and highest power either way against `ratings.line_module_rated_power_w` and `_max_power_w`.
1644///
1645/// "pulley-bearing-life", "gearbox-life", "gearbox-gearing-life", "motor-bearing-life" and "guide-life" judge
1646/// `pulley_bearing_life_h`, `gearbox_life_h`, `gearbox_gearing_life_h`, `motor_bearing_life_h` and `guide_life_h` against
1647/// `ratings.required_life_h` (they pass at or above it); "belt-tooth-load" judges `belt_tooth_utilisation` against 1.
1648///
1649/// "singularity" judges the highest condition number of the kinematics' Jacobian in the cycle
1650/// (`CycleLoad::condition_peak`, where the machine reports it) against `ratings.max_condition_number`: near a singularity
1651/// the motors' torques and speeds for a tool force or speed grow without bound, and a tool force or speed for the motors'
1652/// shrinks.
1653///
1654/// "belt-tooth-jump" judges, with effects.belt_tooth_jump, the jumps of the belt's teeth during the cycle against 0;
1655/// "belt-span-resonance", with effects.belt_span_vibration, how close a span's first sideways mode came to an
1656/// excitation at steady speed (`CycleLoad::belt_span_detuning`) against `ratings.belt_span_resonance_band` (it passes
1657/// at or above it).
1658///
1659/// "collision" judges, where the config has obstacles, the least clearance of the run to them (`CycleLoad::clearance`)
1660/// against `profile.min_clearance_m`: it passes at or above it, never at a contact. Without obstacles it is not judged,
1661/// as a rating left out is not, so it cannot fail there. "self-collision" judges the least clearance between the
1662/// machine's own parts that are not joined at its start pose (`CycleLoad::own_clearance`) against the same limit, as
1663/// "collision" does; where the machine has no such two parts it is not judged.
1664pub fn verdicts(cfg: &Config, load: &CycleLoad) -> Result<Vec<Verdict>, ConfigError> {
1665    let cfg = &crate::catalog::parts_applied(cfg)?;
1666    // A rating that is no number (NaN) would otherwise count as left out, and not be judged.
1667    // The belt's tooth load table is two arrays; `belt_tooth_utilisation` checks them.
1668    // A table there is a motor's own ratings (`catalog::motor_config`), checked with that motor.
1669    for (name, value) in cfg.get("ratings").ok().and_then(|ratings| ratings.as_table()).into_iter().flatten() {
1670        if !value.is_array() && !value.is_table() {
1671            cfg.f64(&format!("ratings.{name}"))?;
1672        }
1673    }
1674    let rating = |name: &str| cfg.f64(&format!("ratings.{name}")).ok();
1675    let simulated = cfg.bool("effects.dc_link")?;
1676    let mut out = Vec::new();
1677    // An S120 line-up brakes through one Braking Module for all its axes (`drive.braking_module`): their braking power
1678    // is judged together, after the axes. An S210 has a resistor of its own and is judged per axis.
1679    let line_up = cfg.get("drive.braking_module").is_ok() && cfg.bool("drive.braking_module")?;
1680    let mut line_up_brakes = false;
1681    let mut regenerated_excess = 0.0;
1682    let shared = cfg;
1683    for (k, m) in load.motors.iter().enumerate() {
1684        // Each motor against its own motor, drive and ratings.
1685        let cfg = &crate::catalog::motor_config(shared, &m.id)?;
1686        let rating = |name: &str| cfg.f64(&format!("ratings.{name}")).ok();
1687        let (bus, rated_rise) = (cfg.positive("drive.bus_voltage_v")?, cfg.positive("motor.rated_temperature_rise_k")?);
1688        // Peak torque against the torque-speed curve, and the settled winding temperature against the rated rise.
1689        out.push(at_most("motor-peak", Some(k), m.utilisation, 1.0));
1690        out.push(at_most("motor-thermal", Some(k), m.winding_rise, rated_rise));
1691        // A stepper's load angle against its pull-out angle, pi / 2 electrical: beyond it the rotor falls out of step.
1692        if let Some(angle) = m.load_angle {
1693            out.push(at_most("stepper-synchronism", Some(k), angle, std::f64::consts::FRAC_PI_2));
1694        }
1695        // Siemens' S1 check: the RMS torque at the mean speed against the S1 curve (`s1_torque`), for a servo motor; a
1696        // stepper's and an induction motor's heat is judged by "motor-thermal" alone.
1697        let servo = cfg.get("motor.kind").ok().and_then(|v| v.as_str()).is_none_or(|kind| kind == "servo");
1698        if let (true, Some(limit)) = (servo, s1_torque(cfg, m.mean_speed)?) {
1699            out.push(at_most("motor-s1", Some(k), m.rms_torque, limit));
1700        }
1701        // The peak speed against the motor's maximum speed, where the config gives it (a catalogue motor does).
1702        if cfg.get("drive.max_speed_rad_s").is_ok() {
1703            out.push(at_most("motor-speed", Some(k), m.peak_speed, cfg.positive("drive.max_speed_rad_s")?));
1704        }
1705        // The drive's output current: the cycle's RMS against its rated current (a cycle of seconds against a power
1706        // unit that warms in seconds to minutes), its peak against the maximum current.
1707        if let Some(limit) = rating("drive_rated_current_a") {
1708            out.push(at_most("drive-current", Some(k), m.rms_current, limit));
1709        }
1710        if let Some(limit) = rating("drive_max_current_a") {
1711            out.push(at_most("drive-peak-current", Some(k), m.peak_current, limit));
1712        }
1713        // effects.drive_overload: the thermal image's peak, the cycle repeated, against the level at which the drive
1714        // lowers its current to the base load current.
1715        if let Some(o) = crate::drive::Overload::from_config(cfg)? {
1716            out.push(at_most("drive-overload", Some(k), m.drive_overload, o.trip));
1717        }
1718        if let (Some((peak, _)), Some(limit)) = (m.gearbox_torque, rating("pulley_max_torque_nm")) {
1719            out.push(at_most("pulley-torque", Some(k), peak, limit));
1720        }
1721        // The radial load on this motor's shaft against its own gearbox's rating (a smaller Z gearbox has its own).
1722        if let (Some(peak), Some(limit)) = (m.radial_load_peak, rating("shaft_max_radial_load_n")) {
1723            out.push(at_most("gearbox-radial-load", Some(k), peak, limit));
1724        }
1725        if let (Some((_, cubic_mean)), Some(limit)) = (m.gearbox_torque, rating("gearbox_rated_torque_nm")) {
1726            out.push(at_most("gearbox-continuous", Some(k), cubic_mean, limit));
1727        }
1728        if let Some(limit) = rating("gearbox_max_input_speed_rpm") {
1729            out.push(at_most("gearbox-input-speed", Some(k), m.peak_speed * 30.0 / std::f64::consts::PI, limit));
1730        }
1731        if let (Some((peak, _)), Some(limit)) = (m.gearbox_torque, rating("gearbox_max_torque_nm")) {
1732            out.push(at_most("gearbox-peak", Some(k), peak, limit));
1733        }
1734        // Lives against the required life, and the belt's teeth against their speed-dependent rating.
1735        if reliability_factor(cfg).is_none() {
1736            return Err(ConfigError::Invalid("ratings.bearing_reliability_percent".into()));
1737        }
1738        lubrication(cfg)?;
1739        if let Some(required) = rating("required_life_h") {
1740            if let Some(life) = pulley_bearing_life_h(cfg, m) {
1741                out.push(at_least("pulley-bearing-life", Some(k), life, required));
1742            }
1743            if let Some(life) = gearbox_life_h(cfg, m) {
1744                out.push(at_least("gearbox-life", Some(k), life, required));
1745            }
1746            if let Some(life) = gearbox_gearing_life_h(cfg, m) {
1747                out.push(at_least("gearbox-gearing-life", Some(k), life, required));
1748            }
1749            if let Some(life) = motor_bearing_life_h(cfg, m) {
1750                out.push(at_least("motor-bearing-life", Some(k), life, required));
1751            }
1752        }
1753        if let Some(utilisation) = belt_tooth_utilisation(cfg, m)? {
1754            out.push(at_most("belt-tooth-load", Some(k), utilisation, 1.0));
1755        }
1756        // Braking: what the DC link capacitors take between the bus voltage and the threshold. If one
1757        // braking gives back more, the braking resistor has to take the mean and the peak power.
1758        if let (Some(capacitance), Some(threshold)) = (rating("dc_link_capacitance_uf"), rating("braking_threshold_v"))
1759        {
1760            // A threshold at or below the bus is a rating for another bus, not a DC link without room.
1761            if threshold <= bus {
1762                return Err(ConfigError::Invalid("ratings.braking_threshold_v".into()));
1763            }
1764            let room = 0.5 * capacitance * 1e-6 * (threshold * threshold - bus * bus);
1765            let (continuous, peak) = (rating("braking_resistor_continuous_w"), rating("braking_resistor_peak_w"));
1766            // (energy in the capacitors above the bus level, whether the resistor is needed, its mean and peak power)
1767            let (stored, resistor, mean_power, peak_power) = if simulated {
1768                let stored = 0.5 * capacitance * 1e-6 * (m.peak_dc_link_voltage.powi(2) - bus * bus);
1769                (stored, m.resistor_energy > 0.0, m.resistor_energy / load.duration, m.peak_resistor_power)
1770            } else {
1771                // The capacitors take the braking up to their room; only what is above it goes to the resistor.
1772                // The run's own account where it kept one for this room, else the stretches of a load built by hand.
1773                let (excess, fill) = match &m.dc_link_account {
1774                    Some(account) if account.room == room => account.finish(),
1775                    _ => resistor_excess(&m.regeneration_events, room),
1776                };
1777                regenerated_excess += excess;
1778                (fill, fill > room, excess / load.duration, m.peak_regenerated_power)
1779            };
1780            // With a resistor to fall back on, a full DC link is no failure in itself.
1781            out.push(Verdict {
1782                check: "dc-link-energy",
1783                motor: Some(k),
1784                value: stored,
1785                limit: room,
1786                ok: !resistor || continuous.is_some(),
1787            });
1788            line_up_brakes |= resistor;
1789            if resistor && !line_up {
1790                if let Some(limit) = continuous {
1791                    out.push(at_most("braking-resistor-continuous", Some(k), mean_power, limit));
1792                }
1793                if let Some(limit) = peak {
1794                    out.push(at_most("braking-resistor-peak", Some(k), peak_power, limit));
1795                }
1796            }
1797        }
1798        // The simulated resistor never takes more than its peak power; what it cannot take shows here.
1799        if let (true, Some(limit)) = (simulated, rating("dc_link_overvoltage_v")) {
1800            out.push(at_most("dc-link-overvoltage", Some(k), m.peak_dc_link_voltage, limit));
1801        }
1802        // The line module of a regenerative supply, through which the drive draws and feeds back: its mean power
1803        // either way against its rated power, its highest against its maximum power.
1804        if simulated && cfg.bool("effects.regenerative_supply")? {
1805            if let Some(limit) = rating("line_module_rated_power_w") {
1806                out.push(at_most("line-module-continuous", Some(k), m.line_module_energy / load.duration, limit));
1807            }
1808            if let Some(limit) = rating("line_module_max_power_w") {
1809                out.push(at_most("line-module-peak", Some(k), m.peak_line_module_power, limit));
1810            }
1811        }
1812    }
1813    // The line-up's mean braking power is the sum of the axes' means; its peak the peak of their sum at each step.
1814    if line_up && line_up_brakes {
1815        let shared = simulated && cfg.bool("effects.shared_dc_link")?;
1816        let energy: f64 = match (simulated, shared) {
1817            (true, true) => load.motors.first().map_or(0.0, |m| m.resistor_energy),
1818            (true, false) => load.motors.iter().map(|m| m.resistor_energy).sum(),
1819            (false, _) => regenerated_excess,
1820        };
1821        if let Some(limit) = rating("braking_resistor_continuous_w") {
1822            out.push(at_most("braking-resistor-continuous", None, energy / load.duration, limit));
1823        }
1824        if let Some(limit) = rating("braking_resistor_peak_w") {
1825            out.push(at_most("braking-resistor-peak", None, load.braking_power_peak, limit));
1826        }
1827    }
1828    if let Some(limit) = rating("settling_tolerance_m") {
1829        out.push(at_most("settling", None, load.dwell_error_peak, limit));
1830    }
1831    // The turn's (an arm's orientation, a turning tool or table), on its own: no metres and radians added.
1832    if let Some(limit) = rating("settling_tolerance_rad") {
1833        out.push(at_most("settling-angle", None, load.dwell_angle_error_peak, limit));
1834    }
1835    // The tool's error while it moves, from where its setpoint was at the same moment, where the config asks a limit
1836    // for it: the drives' following error window (p2546) trips a drive at its motor, this judges the tool.
1837    if let Some(limit) = rating("tracking_tolerance_m") {
1838        out.push(at_most("tracking", None, load.tracking_error_peak, limit));
1839    }
1840    if let Some(limit) = rating("tracking_tolerance_rad") {
1841        out.push(at_most("tracking-angle", None, load.tracking_angle_error_peak, limit));
1842    }
1843    // A vacuum gripper (effects.gripper_time): the most the held part asked of the cup against its hold over the
1844    // safety factor (`gripper`).
1845    if let (Some(crate::gripper::Gripper { hold: Some((hold, mu)), .. }), Some(factor)) =
1846        (crate::gripper::Gripper::from_config(cfg)?, rating("gripper_safety_factor"))
1847    {
1848        let (mass, g) = (crate::gripper::payload_mass(cfg)?, crate::gripper::gravity(cfg)?);
1849        let asked = load
1850            .held_accelerations
1851            .iter()
1852            .map(|&[up, side]| crate::gripper::demand(mass, [side, 0.0, up], g, mu))
1853            .fold(0.0, f64::max);
1854        out.push(at_most("gripper-hold", None, asked, hold / factor));
1855    }
1856    if let Some((slackest, tightest)) = load.belt_tension {
1857        if let Some(limit) = rating("belt_max_tension_n") {
1858            out.push(Verdict { check: "belt-tension", motor: None, value: tightest, limit, ok: tightest <= limit });
1859        }
1860        if let Some(limit) = rating("belt_min_tension_n") {
1861            // The one check where the value has to stay above its limit. The tension is looked at once per
1862            // millisecond; the slack time also counts what falls between.
1863            let never_slack = load.belt_slack_time.is_none_or(|time| time <= 0.0);
1864            out.push(Verdict {
1865                check: "belt-least-tension",
1866                motor: None,
1867                value: slackest,
1868                limit,
1869                ok: slackest > limit && never_slack,
1870            });
1871        }
1872    }
1873    if let Some(jumps) = load.belt_tooth_jumps {
1874        out.push(at_most("belt-tooth-jump", None, jumps, 0.0));
1875    }
1876    if let (Some(detuning), Some(band)) = (load.belt_span_detuning, rating("belt_span_resonance_band")) {
1877        out.push(at_least("belt-span-resonance", None, detuning, band));
1878    }
1879    // The machine's own parts (`Machine::rating_checks`): a peak at most its limit, a life (an L10) times the life
1880    // factor a1 at least its required life.
1881    for (check, value) in &load.checks {
1882        let a1 = reliability_factor(cfg)
1883            .ok_or_else(|| ConfigError::Invalid("ratings.bearing_reliability_percent".into()))?;
1884        out.push(if check.life {
1885            at_least(check.check, check.motor, value * a1, check.limit)
1886        } else {
1887            at_most(check.check, check.motor, *value, check.limit)
1888        });
1889    }
1890    // The least clearance to the obstacles against `profile.min_clearance_m`; a contact fails whatever the limit.
1891    if let Some(clearance) = load.clearance {
1892        let limit = cfg.non_negative("profile.min_clearance_m")?;
1893        out.push(Verdict {
1894            check: "collision",
1895            motor: None,
1896            value: clearance,
1897            limit,
1898            ok: clearance >= limit && clearance > 0.0,
1899        });
1900    }
1901    if let Some(clearance) = load.own_clearance {
1902        let limit = cfg.non_negative("profile.min_clearance_m")?;
1903        out.push(Verdict {
1904            check: "self-collision",
1905            motor: None,
1906            value: clearance,
1907            limit,
1908            ok: clearance >= limit && clearance > 0.0,
1909        });
1910    }
1911    if let (Some(value), Some(limit)) = (load.condition_peak, rating("max_condition_number")) {
1912        out.push(at_most("singularity", None, value, limit));
1913    }
1914    // Once for the machine only where no motor's shaft reports its own (judged per motor above); before 14 November 2026
1915    // always so, the highest of all shafts against the shared rating.
1916    let per_motor = load.motors.iter().any(|m| m.radial_load_peak.is_some());
1917    if let (Some(value), Some(limit), false) = (load.radial_load_peak, rating("shaft_max_radial_load_n"), per_motor) {
1918        out.push(at_most("gearbox-radial-load", None, value, limit));
1919    }
1920    if let (Some((peak, _)), Some(limit)) = (load.guide_load, rating("guide_max_load_n")) {
1921        out.push(at_most("guide-load", None, peak, limit));
1922    }
1923    if let (Some(life), Some(required)) = (guide_life_h(cfg, load), rating("required_life_h")) {
1924        out.push(at_least("guide-life", None, life, required));
1925    }
1926    // The hottest part of each kind where it settles (`CycleLoad::part_rises`), against its rated rise; only where
1927    // the parts warm, as a rating left out is not judged either.
1928    if crate::sim::heats(cfg)? {
1929        for (kind, check) in [("gearbox", "gearbox-thermal"), ("guide", "guide-thermal")] {
1930            let hottest =
1931                load.part_rises.iter().filter(|(part, _)| part.kind == kind).map(|(_, rise)| *rise).reduce(f64::max);
1932            if let Some(rise) = hottest {
1933                out.push(at_most(check, None, rise, cfg.positive(&format!("thermal.{kind}_max_rise_k"))?));
1934            }
1935        }
1936    }
1937    // How the measured pass was started (effects.thermal_warm_start): the most a rise it started at lies from the one it
1938    // settles at, against the warm start's tolerance. No row: from cold, or a change without a value (a run that stopped,
1939    // a winding that does not settle), whose cause fails a verdict of its own (the trip's, the crash's, motor-thermal).
1940    if let Some(warm) = load.warm_start.filter(|w| w.change.is_finite()) {
1941        out.push(at_most("thermal-warm-start", None, warm.change, WARM_START_TOLERANCE_K));
1942        // Where it did not converge: whether two passes started at the same rises settle alike (`WarmStart::repeat`).
1943        if let Some(apart) = warm.repeat {
1944            out.push(at_most("thermal-cycle-repeat", None, apart, WARM_START_TOLERANCE_K));
1945        }
1946    }
1947    // A pick from the conveyor: the tool on the part along the belt while the gripper closes, and no part left unpicked.
1948    if let Some(c) = load.conveyor {
1949        out.push(at_most("pick-tracking", None, c.tracking_peak, cfg.positive("conveyor.tracking_tolerance_m")?));
1950        out.push(at_most("parts-missed", None, c.missed_per_minute, 0.0));
1951    }
1952    Ok(out)
1953}
1954
1955/// The equivalent load of a guide: the cubic mean cbrt(sum F^3 w / sum w) with the weight w (|speed|: over distance);
1956/// 0 where nothing moved.
1957fn equivalent_load(cubed_sum: f64, weight_sum: f64) -> f64 {
1958    if weight_sum > 0.0 { (cubed_sum / weight_sum).cbrt() } else { 0.0 }
1959}
1960
1961/// The energy a braking resistor takes per cycle, J, and the most the DC link's capacitors would have to hold, J, from the
1962/// cycle's stretches `events` (`MotorLoad::regeneration_events`: fed back positive, drawn negative) when the capacitors
1963/// hold `room` J above the bus: the link fills with what is fed back, spills what is above its room into the resistor and
1964/// empties by what is drawn (to the bus, no lower; its own losses left out, so the estimate errs high). Braking events
1965/// with too little drawn between them add up. The cycle repeats: the link enters it as the cycle before left it, so the
1966/// figures are those of a second pass.
1967fn resistor_excess(events: &[f64], room: f64) -> (f64, f64) {
1968    let mut account = LinkAccount::new(room);
1969    events.iter().for_each(|&e| account.push(e));
1970    account.finish()
1971}
1972
1973/// The DC link's running account of `resistor_excess`, kept as the stretches come (`Tally`, where the motor's room is
1974/// known at the run: `Controller::dc_link_room`). Only the stretches until the link's fill no longer depends on how full
1975/// it entered the cycle are kept: until the pass entered empty and the one entered full meet, which they do the first
1976/// time the link empties or fills whatever it held (a hanging axis at rest draws, so empties it at once). After that one
1977/// fill stands for every entry, and what it spills and the most it holds are summed as they come. At most the stretches
1978/// up to that point, so on a run at rest with noisy power the list stays at the few stretches before the link first
1979/// emptied, where before it grew by one per sign change of the power (about 90 per cycle). Same figures as the two passes
1980/// over the whole list, to rounding (the spills are summed in another order).
1981///
1982/// A link that neither empties nor fills (what is fed back and drawn stays within less than its room for the whole run)
1983/// never lets the passes meet. Past `LINK_PREFIX_CAP` stretches the account keeps, instead of them, `LINK_GRID` passes
1984/// entered at fills spread evenly over the voltage window, 0 to the room, and reads the cycle's figures between the two
1985/// next to its entry: fill, spill and most are each at most 1:1 in the entry fill (what one enters with more is spilled,
1986/// drawn less or held), so the figures are off by at most half the grid's step, room / (2 (LINK_GRID − 1)).
1987#[derive(Debug, Clone, Default, PartialEq)]
1988pub struct LinkAccount {
1989    /// The room it was kept for, J.
1990    pub room: f64,
1991    /// The stretches before the passes entered empty and full met.
1992    prefix: Vec<f64>,
1993    /// Past `LINK_PREFIX_CAP` stretches in `prefix`: per entry fill j room / (LINK_GRID − 1) its fill, spill and most
1994    /// over the stretches until the passes met, in place of them.
1995    grid: Vec<[f64; 3]>,
1996    /// The fill of the pass entered empty, and of the one entered full, J; one fill once they have met.
1997    low: f64,
1998    high: f64,
1999    met: bool,
2000    /// After they met: what the link spilled into the resistor, J, and the most it would have held.
2001    spilled: f64,
2002    most: f64,
2003}
2004
2005impl LinkAccount {
2006    pub fn new(room: f64) -> Self {
2007        Self { room, high: room, ..Default::default() }
2008    }
2009
2010    /// One stretch: fed back positive, drawn negative, J.
2011    pub fn push(&mut self, e: f64) {
2012        let room = self.room;
2013        if self.met {
2014            let fill = (self.low + e).max(0.0);
2015            (self.spilled, self.most, self.low) =
2016                (self.spilled + (fill - room).max(0.0), self.most.max(fill), fill.min(room));
2017            return;
2018        }
2019        if self.grid.is_empty() {
2020            self.prefix.push(e);
2021            if self.prefix.len() > LINK_PREFIX_CAP {
2022                self.grid = (0..LINK_GRID)
2023                    .map(|j| {
2024                        let mut pass = [j as f64 * room / (LINK_GRID - 1) as f64, 0.0, 0.0];
2025                        self.prefix.iter().for_each(|&e| link_step(&mut pass, e, room));
2026                        pass
2027                    })
2028                    .collect();
2029                self.prefix = Vec::new();
2030            }
2031        } else {
2032            self.grid.iter_mut().for_each(|pass| link_step(pass, e, room));
2033        }
2034        let step = |fill: f64| (fill + e).max(0.0).min(room);
2035        (self.low, self.high) = (step(self.low), step(self.high));
2036        // Both at 0 or both at the room, exactly.
2037        self.met = self.low == self.high;
2038    }
2039
2040    /// What the resistor takes per cycle, J, and the most the link would have to hold, J (`resistor_excess`): the cycle
2041    /// entered as it left, which is as the pass entered empty left it.
2042    pub fn finish(&self) -> (f64, f64) {
2043        let mut pass = [self.low, self.spilled, self.most];
2044        self.prefix.iter().for_each(|&e| link_step(&mut pass, e, self.room));
2045        if self.grid.len() >= 2 {
2046            // Between the two passes of the grid next to the entry fill.
2047            let at = self.low / self.room * (self.grid.len() - 1) as f64;
2048            let j = (at.floor() as usize).min(self.grid.len() - 2);
2049            let (u, [a, b]) = (at - j as f64, [self.grid[j], self.grid[j + 1]]);
2050            let between = |q: usize| a[q] + u * (b[q] - a[q]);
2051            (pass[1], pass[2]) = (pass[1] + between(1), pass[2].max(between(2)));
2052        }
2053        (pass[1], pass[2])
2054    }
2055}
2056
2057/// Stretches a link account keeps before it keeps passes over the voltage window in their place (`LinkAccount`): some
2058/// 1500 cycles of a machine at rest whose power changes sign about 90 times per cycle.
2059pub const LINK_PREFIX_CAP: usize = 1 << 17;
2060
2061/// Entry fills over the voltage window a link account keeps passes for past `LINK_PREFIX_CAP` (`LinkAccount`).
2062pub const LINK_GRID: usize = 257;
2063
2064/// One stretch `e` on a pass of a link of `room` J: its fill, what it spilled and the most it held, J.
2065fn link_step(pass: &mut [f64; 3], e: f64, room: f64) {
2066    let fill = (pass[0] + e).max(0.0);
2067    pass[2] = pass[2].max(fill);
2068    pass[1] += (fill - room).max(0.0);
2069    pass[0] = fill.min(room);
2070}
2071
2072/// Nominal life of the guide that has the least, in km, where the machine reports guide loads and the config has
2073/// `ratings.guide_dynamic_load_rating_n`: L10 = (C / P)^3 * 50 km, the catalogue formula for ball guides,
2074/// with the dynamic load rating C and for P the cubic mean of the guide load over the cycle's distance (weighted by
2075/// the axis's |speed|, as the pulley's radial load is; over time where the guide's axis is unknown). The lowest over
2076/// all guides (`CycleLoad::guides`).
2077///
2078/// This is the catalogue formula and nothing more, and it is not validated: no load factors for shock,
2079/// temperature or hardness, no moments on single blocks,
2080/// and a guide load that is itself an estimate from the rigid model.
2081pub fn guide_life_km(cfg: &Config, load: &CycleLoad) -> Option<f64> {
2082    let rating = cfg.f64("ratings.guide_dynamic_load_rating_n").ok()?;
2083    guides_of(load).iter().map(|g| (rating / g.equivalent).powi(3) * 50.0).reduce(f64::min)
2084}
2085
2086/// `guide_life_km` in hours: the distance over the mean speed of the guide's axis over the cycle (`GuideLoad::speed`),
2087/// times the reliability factor a1 as every other life (`reliability_factor`); the lowest over the guides whose axis is
2088/// known.
2089pub fn guide_life_h(cfg: &Config, load: &CycleLoad) -> Option<f64> {
2090    let rating = cfg.f64("ratings.guide_dynamic_load_rating_n").ok()?;
2091    let a1 = reliability_factor(cfg)?;
2092    let hours = |g: &GuideLoad| -> Option<f64> {
2093        Some((rating / g.equivalent).powi(3) * 50.0 * 1e3 / (g.speed? * 3600.0) * a1)
2094    };
2095    guides_of(load).iter().filter_map(hours).reduce(f64::min)
2096}
2097
2098/// The guides of a load: `CycleLoad::guides`, or the one pair of `guide_load` and `guide_speed` where a load was built
2099/// without them.
2100fn guides_of(load: &CycleLoad) -> Vec<GuideLoad> {
2101    if !load.guides.is_empty() {
2102        return load.guides.clone();
2103    }
2104    load.guide_load
2105        .map(|(peak, equivalent)| GuideLoad { peak, equivalent, speed: load.guide_speed })
2106        .into_iter()
2107        .collect()
2108}
2109
2110/// The width of the speed bands of `MotorLoad::gearbox_torque_by_speed`, rad/s of the motor.
2111pub const SPEED_BAND: f64 = 5.0;
2112
2113/// The basic rating life of a ball bearing in hours (ISO 281): L10h = (C / P)^3 · 10^6 / (60 n), with the dynamic load
2114/// rating C and the equivalent load P in the same unit and the mean speed n in r/min.
2115pub fn rating_life_h(c: f64, p: f64, rpm: f64) -> f64 {
2116    (c / p).powi(3) * 1e6 / (60.0 * rpm)
2117}
2118
2119/// The life factor a1 of ISO 281 for the reliability R of `ratings.bearing_reliability_percent`, which turns the L10 of
2120/// a bearing into the life R % of bearings reach: a1 = 0.95 · (ln(100 / R) / ln(100 / 90))^(2/3) + 0.05, the Weibull
2121/// form behind the standard's table (1 at 90 %, 0.64 at 95 %, 0.25 at 99 %). 1 where the config has no reliability;
2122/// `None` for one outside 90 to 99.95 %, where the standard gives no factor.
2123pub fn reliability_factor(cfg: &Config) -> Option<f64> {
2124    let Ok(r) = cfg.f64("ratings.bearing_reliability_percent") else { return Some(1.0) };
2125    (90.0..=99.95).contains(&r).then(|| 0.95 * ((100.0 / r).ln() / (100.0_f64 / 90.0).ln()).powf(2.0 / 3.0) + 0.05)
2126}
2127
2128/// This motor's own `gearbox.ratio` (`catalog::motor_config`: a `[gearbox.<id>]` table over the shared one), so a machine
2129/// whose motors have different ratios gets each gearbox's own speed. Applying it to a config that is already the
2130/// motor's own changes nothing.
2131fn own_ratio(cfg: &Config, m: &MotorLoad) -> f64 {
2132    let own = crate::catalog::motor_config(cfg, &m.id);
2133    own.as_ref().ok().unwrap_or(cfg).f64("gearbox.ratio").unwrap_or(1.0)
2134}
2135
2136/// The mean speed of the gearbox output (the pulley) in r/min: the motor's over its own `gearbox.ratio`.
2137fn output_rpm(cfg: &Config, m: &MotorLoad) -> f64 {
2138    m.mean_speed * 30.0 / std::f64::consts::PI / own_ratio(cfg, m)
2139}
2140
2141/// The rating life of the bearing that takes the belt's pull on this motor's pulley shaft, in hours, where the machine
2142/// reports that radial load and the config has `ratings.pulley_bearing_load_rating_n`: `rating_life_h` with that C, P the
2143/// cubic mean of the radial load weighted with the speed (`MotorLoad::radial_load_equivalent`) and the pulley's mean
2144/// speed, times the life factor a1 (`reliability_factor`) and, where the config has the lubrication (`lubrication`),
2145/// the life modification factor a_ISO (`life_modification_factor`): L_nm = a1 · a_ISO · L10. One bearing, all of the
2146/// pull on it, no axial load.
2147pub fn pulley_bearing_life_h(cfg: &Config, m: &MotorLoad) -> Option<f64> {
2148    let c = cfg.f64("ratings.pulley_bearing_load_rating_n").ok()?;
2149    let (p, rpm) = (m.radial_load_equivalent?, output_rpm(cfg, m));
2150    Some(reliability_factor(cfg)? * pulley_bearing_a_iso(cfg, p, rpm)? * rating_life_h(c, p, rpm))
2151}
2152
2153/// a_ISO of the pulley shaft bearing at the equivalent load `p` and the mean speed `rpm`: `life_modification_factor` of
2154/// κ = ν / ν1 (`reference_viscosity`) and e_C · C_u / P. 1 where the config has no `lubrication`; `None` where it is
2155/// invalid. κ is that of the mean speed.
2156pub fn pulley_bearing_a_iso(cfg: &Config, p: f64, rpm: f64) -> Option<f64> {
2157    Some(match lubrication(cfg).ok()? {
2158        Some(l) => life_modification_factor(
2159            l.viscosity / reference_viscosity(rpm, l.mean_diameter_mm),
2160            l.contamination * l.fatigue_limit / p,
2161        ),
2162        None => 1.0,
2163    })
2164}
2165
2166/// What a_ISO of the pulley shaft bearing is worked out from: the lubricant's kinematic viscosity at operating
2167/// temperature ν (mm²/s), the contamination factor e_C (ISO 281:2007, Table 13, for a mean diameter below 100 mm:
2168/// 1 extreme cleanliness, 0.8 to 0.6 high (typical of bearings sealed and greased for life), 0.6 to 0.5 normal, 0.5 to
2169/// 0.3 slight, 0.3 to 0.1 typical, 0.1 to 0 severe, 0 very severe contamination), the bearing's fatigue load limit C_u
2170/// (N) and its mean diameter D_pw (mm).
2171#[derive(Debug, Clone, Copy, PartialEq)]
2172pub struct Lubrication {
2173    pub viscosity: f64,
2174    pub contamination: f64,
2175    pub fatigue_limit: f64,
2176    pub mean_diameter_mm: f64,
2177}
2178
2179/// The keys of `Lubrication`, in its order.
2180pub const LUBRICATION_KEYS: [&str; 4] = [
2181    "ratings.bearing_lubricant_viscosity_mm2_s",
2182    "ratings.bearing_contamination_factor",
2183    "ratings.pulley_bearing_fatigue_limit_n",
2184    "ratings.pulley_bearing_mean_diameter_mm",
2185];
2186
2187/// The pulley shaft bearing's `Lubrication`, `None` where the config has none of its keys (then a_ISO is 1). A config
2188/// with some of them must have all: ν and D_pw above 0, e_C from 0 to 1, C_u not negative.
2189pub fn lubrication(cfg: &Config) -> Result<Option<Lubrication>, ConfigError> {
2190    if LUBRICATION_KEYS.iter().all(|key| cfg.get(key).is_err()) {
2191        return Ok(None);
2192    }
2193    let contamination = cfg.non_negative(LUBRICATION_KEYS[1])?;
2194    if contamination > 1.0 {
2195        return Err(ConfigError::Invalid(LUBRICATION_KEYS[1].into()));
2196    }
2197    let (viscosity, fatigue_limit, mean_diameter_mm) = (
2198        cfg.positive(LUBRICATION_KEYS[0])?,
2199        cfg.non_negative(LUBRICATION_KEYS[2])?,
2200        cfg.positive(LUBRICATION_KEYS[3])?,
2201    );
2202    Ok(Some(Lubrication { viscosity, contamination, fatigue_limit, mean_diameter_mm }))
2203}
2204
2205/// The rated viscosity ν1 of ISO 281:2007 (section 6.3.3.2), mm²/s: what the lubricant needs at operating temperature
2206/// for a bearing of mean diameter D_pw (`mean_diameter_mm`) at n (`rpm`, r/min): 45000 · n^-0.83 · D_pw^-0.5 below
2207/// 1000 r/min, 4500 · n^-0.5 · D_pw^-0.5 from 1000 r/min. The viscosity ratio is κ = ν / ν1.
2208pub fn reference_viscosity(rpm: f64, mean_diameter_mm: f64) -> f64 {
2209    if rpm < 1000.0 {
2210        45000.0 * rpm.powf(-0.83) / mean_diameter_mm.sqrt()
2211    } else {
2212        4500.0 / rpm.sqrt() / mean_diameter_mm.sqrt()
2213    }
2214}
2215
2216/// The life modification factor a_ISO of ISO 281:2007 (section 6.3.3.3, radial ball bearings) for the viscosity ratio κ
2217/// and `load_ratio` = e_C · C_u / P: a_ISO = 0.1 · [1 - x · (e_C · C_u / P)^(1/3)]^-9.3, x = (2.5671 - 2.2649 /
2218/// κ^0.054381)^0.83 for 0.1 <= κ < 0.4, (2.5671 - 1.9987 / κ^0.19087)^0.83 for 0.4 <= κ < 1 and
2219/// (2.5671 - 1.9987 / κ^0.071739)^0.83 for 1 <= κ <= 4; at most 50, as the standard limits it.
2220pub fn life_modification_factor(kappa: f64, load_ratio: f64) -> f64 {
2221    // shortcut: κ below 0.1, where the standard gives no factor, is taken as 0.1 (a_ISO 0.1); above 4 as 4, as the
2222    // standard says. Upgrade if a machine runs its bearings that slowly with that thin a lubricant.
2223    let kappa = kappa.clamp(0.1, 4.0);
2224    let x = if kappa < 0.4 {
2225        2.5671 - 2.2649 / kappa.powf(0.054381)
2226    } else if kappa < 1.0 {
2227        2.5671 - 1.9987 / kappa.powf(0.19087)
2228    } else {
2229        2.5671 - 1.9987 / kappa.powf(0.071739)
2230    };
2231    let inner = 1.0 - x.max(0.0).powf(0.83) * load_ratio.cbrt();
2232    if inner <= 0.0 { 50.0 } else { (0.1 * inner.powf(-9.3)).min(50.0) }
2233}
2234
2235/// The life of a planetary gearbox's planet bearings in hours by Siemens' formula (configuration manual "Planetary
2236/// gearboxes for S-1FK2 and S-1FT2 servomotors", 01/2023, section 6.3.3): L10h = 20000 h · (n2B / n2) · (M2N / M2eq)^(10/3),
2237/// with the rated torque M2N (`ratings.gearbox_rated_torque_nm`), the reference output speed n2B
2238/// (`ratings.gearbox_reference_speed_rpm`), the mean output speed n2 and M2eq the mean of the output torque with the
2239/// exponent 10/3 weighted with the speed (`MotorLoad::gearbox_life_torque`). Where the machine reports the output torque
2240/// and the config has both ratings. Times the life factor a1 (`reliability_factor`): Siemens' figure is an L10 too.
2241pub fn gearbox_life_h(cfg: &Config, m: &MotorLoad) -> Option<f64> {
2242    let (rated, reference) =
2243        (cfg.f64("ratings.gearbox_rated_torque_nm").ok()?, cfg.f64("ratings.gearbox_reference_speed_rpm").ok()?);
2244    Some(
2245        reliability_factor(cfg)? * 20000.0 * reference / output_rpm(cfg, m)
2246            * (rated / m.gearbox_life_torque?).powf(10.0 / 3.0),
2247    )
2248}
2249
2250/// The lowest torque of `MotorLoad::gearbox_torque_spectrum`, N m, and the ratio of a band's upper torque to its lower:
2251/// bands 1 % wide, each judged at its upper torque, which overstates its damage by at most 1.01^k - 1 (9 % at k = 8.7).
2252const TORQUE_FLOOR: f64 = 0.1;
2253const TORQUE_BAND: f64 = 1.01;
2254
2255/// The lower torque of band `i` of `MotorLoad::gearbox_torque_spectrum`, N m: 0.1 N m · 1.01^i.
2256pub fn torque_band_floor(i: usize) -> f64 {
2257    TORQUE_FLOOR * TORQUE_BAND.powi(i as i32)
2258}
2259
2260/// The output revolutions a Siemens planetary gearbox takes at its maximum torque M2max (NRB, NRK, NLC: "for at most
2261/// 30 000 output revolutions", equipment manual 04/2025, chapter 6; `catalog/siemens/gearbox_nrb.meta.toml`).
2262pub const MAX_TORQUE_REVOLUTIONS: f64 = 30000.0;
2263
2264/// The life of a gearing in hours by Palmgren and Miner's damage sum over a load spectrum of (output torque, output
2265/// revolutions per hour), on a Wöhler line through the maximum torque M2max at `MAX_TORQUE_REVOLUTIONS` with the
2266/// exponent k: a torque M above the rated torque M2N allows N = 30000 · (M2max / M)^k revolutions, one at or below M2N
2267/// any number (the knee of the line at M2N). The damage per hour is the sum of the revolutions over the allowed ones, the
2268/// life its inverse; infinite where no torque is above M2N.
2269pub fn gearing_life_h(spectrum: impl IntoIterator<Item = (f64, f64)>, rated: f64, max: f64, exponent: f64) -> f64 {
2270    // A fold, not `sum`: an empty sum of f64 is -0.0, whose inverse is -inf.
2271    1.0 / spectrum
2272        .into_iter()
2273        .filter(|&(torque, _)| torque > rated)
2274        .map(|(torque, revolutions)| revolutions / (MAX_TORQUE_REVOLUTIONS * (max / torque).powf(exponent)))
2275        .fold(0.0, |sum, d| sum + d)
2276}
2277
2278/// The fatigue life of the gearbox's gearing in hours, where the machine reports the output torque and the config has
2279/// `ratings.gearbox_rated_torque_nm` (M2N), `ratings.gearbox_max_torque_nm` (M2max) and
2280/// `ratings.gearbox_gearing_wohler_exponent` (k): `gearing_life_h` over the cycle's load spectrum
2281/// (`MotorLoad::gearbox_torque_spectrum`), each band at its upper torque, with the output's revolutions per hour in it.
2282/// Siemens' own damage sum over overload partial cycles is in its gearbox configuration manual, which is not in the
2283/// repository; this is the textbook method on Siemens' two figures (M2N continuous, M2max for 30000 revolutions) with an
2284/// estimated exponent (the configs' comments say how). Torque at or below M2N does no damage: a cycle that never exceeds
2285/// it has no figure (`None`), as a rating left out is not judged; the life would be infinite.
2286pub fn gearbox_gearing_life_h(cfg: &Config, m: &MotorLoad) -> Option<f64> {
2287    let rating = |key: &str| cfg.f64(&format!("ratings.{key}")).ok();
2288    let (rated, max, exponent) = (
2289        rating("gearbox_rated_torque_nm")?,
2290        rating("gearbox_max_torque_nm")?,
2291        rating("gearbox_gearing_wohler_exponent")?,
2292    );
2293    m.gearbox_torque?;
2294    let per_hour = 3600.0 / (2.0 * std::f64::consts::PI) / own_ratio(cfg, m);
2295    let life = gearing_life_h(
2296        m.gearbox_torque_spectrum.iter().enumerate().map(|(i, speed)| (torque_band_floor(i + 1), speed * per_hour)),
2297        rated,
2298        max,
2299        exponent,
2300    );
2301    life.is_finite().then_some(life)
2302}
2303
2304/// The rating life of the motor's own bearings in hours, where the belt's pulley sits on the motor shaft: where the
2305/// config has `ratings.motor_bearing_load_rating_n` and no gearbox (`gearbox.ratio` 1), `rating_life_h` with that C, the
2306/// pulley shaft's radial load (`MotorLoad::radial_load_equivalent`) and the motor's mean speed, times a1. Behind a
2307/// gearbox the motor's bearings carry no belt pull, the gearbox's output bearing takes it (`pulley_bearing_life_h`), and
2308/// there is no figure. Siemens gives no load rating for the 1FK2's bearings, only the radial force they allow for
2309/// L10h = 25000 h at a mean speed; C is worked out from that by the same formula (`catalog/siemens/motor_bearings_1fk2.csv`).
2310/// No a_ISO: Siemens' 25000 h are for its own grease and seals.
2311pub fn motor_bearing_life_h(cfg: &Config, m: &MotorLoad) -> Option<f64> {
2312    let c = cfg.f64("ratings.motor_bearing_load_rating_n").ok()?;
2313    if own_ratio(cfg, m) != 1.0 {
2314        return None;
2315    }
2316    Some(reliability_factor(cfg)? * rating_life_h(c, m.radial_load_equivalent?, output_rpm(cfg, m)))
2317}
2318
2319/// The tooth load of the belt on this motor's pulley against its rating, by the method of Megadyne's MEGALINEAR handbook
2320/// (02.2026, page 9): the effective pull Fu = output torque / `geometry.pulley_radius_m` times the service factor
2321/// `ratings.belt_service_factor`, against the specific tooth load the teeth allow at the pulley's speed
2322/// (`ratings.belt_tooth_load_n_cm` at `ratings.belt_tooth_load_rpm`, interpolated, held beyond the ends) times the width in
2323/// cm (`ratings.belt_width_mm` / 10) and the teeth in mesh (at most 12): `ratings.belt_teeth_in_mesh`, or with
2324/// effects.belt_wrap those of the smallest wrap over the pass (`MotorLoad::belt_wrap`), wrap r / `belt.tooth_pitch_m`
2325/// (wrap / (2 pi) of the pulley's 2 pi r / p teeth). The highest ratio
2326/// over the cycle, each speed band (`MotorLoad::gearbox_torque_by_speed`) at its upper speed, where the rating is lowest.
2327/// `None` where the machine reports no output torque or the config lacks one of these values, and for a motor that turns
2328/// no pulley (the machine reports neither its pulley's radial load nor its wrap: a screw, rack or linear motor in a
2329/// machine file whose other motors drive belts). A rating, not a life: no belt maker publishes a life in hours or load
2330/// cycles for these belts.
2331pub fn belt_tooth_utilisation(cfg: &Config, m: &MotorLoad) -> Result<Option<f64>, ConfigError> {
2332    let Ok(rpm) = cfg.f64s("ratings.belt_tooth_load_rpm") else { return Ok(None) };
2333    let get = |key: &str| cfg.f64(key).ok();
2334    let (Some(width), Some(teeth), Some(factor), Some(radius)) = (
2335        get("ratings.belt_width_mm"),
2336        get("ratings.belt_teeth_in_mesh"),
2337        get("ratings.belt_service_factor"),
2338        get("geometry.pulley_radius_m"),
2339    ) else {
2340        return Ok(None);
2341    };
2342    let load = cfg.f64s("ratings.belt_tooth_load_n_cm")?;
2343    if load.len() != rpm.len() || rpm.is_empty() || rpm.windows(2).any(|w| w[0] >= w[1]) {
2344        return Err(ConfigError::Invalid("ratings.belt_tooth_load_rpm".into()));
2345    }
2346    if m.gearbox_torque.is_none() || (m.radial_load_equivalent.is_none() && m.belt_wrap.is_none()) {
2347        return Ok(None);
2348    }
2349    let allowed = |n: f64| -> f64 {
2350        let i = rpm.partition_point(|&r| r <= n);
2351        if i == 0 {
2352            load[0]
2353        } else if i == rpm.len() {
2354            load[i - 1]
2355        } else {
2356            load[i - 1] + (load[i] - load[i - 1]) * (n - rpm[i - 1]) / (rpm[i] - rpm[i - 1])
2357        }
2358    };
2359    let ratio = own_ratio(cfg, m);
2360    let teeth = match m.belt_wrap {
2361        Some(wrap) => wrap * radius / cfg.positive("belt.tooth_pitch_m")?,
2362        None => teeth,
2363    };
2364    let capacity = |n: f64| allowed(n) * width / 10.0 * teeth.min(12.0);
2365    let band_rpm = |i: usize| (i + 1) as f64 * SPEED_BAND * 30.0 / std::f64::consts::PI / ratio;
2366    Ok(Some(
2367        m.gearbox_torque_by_speed
2368            .iter()
2369            .enumerate()
2370            .map(|(i, torque)| torque / radius * factor / capacity(band_rpm(i)))
2371            .fold(0.0, f64::max),
2372    ))
2373}
2374
2375/// The low and high bound of every uncertain parameter of a config, as (path, low, high).
2376///
2377/// The table `[bounds]` mirrors the config: where the config has `[friction_x] coulomb_n = 15.0`, it has
2378/// `friction_x.coulomb_n = [10.0, 20.0]`, in the unit of the value. A pair and not a relative width,
2379/// because the parameter panel and the translation check skip arrays (`Config::leaves`), so bounds need
2380/// no labels, and because a value of zero can have bounds this way. A bound on a value the config does
2381/// not have, or one that is not a low and a high number, is refused. A bound on a value that only an effect that
2382/// is off uses (`PATH_EFFECTS`, e.g. `thermal.*` without effects.part_heating), or that no cycle uses (the DC link's
2383/// discharge while disabled), is checked and left out.
2384/// A part by name (`[parts]`, `--motor`, `--drive`, ...) re-centres the bounds of the values it puts in: they are/// scaled by the part's value over the config's own (`catalog::set`), so that a band written for the config's motor and/// drive keeps its relative width around the named part's value. A list taken from a config before its parts were/// applied is read anew from the resolved config by the functions that run the bounds (`followed`).
2385pub fn bounds(cfg: &Config) -> Result<Vec<(String, f64, f64)>, ConfigError> {
2386    fn walk(
2387        path: &str,
2388        value: &toml::Value,
2389        cfg: &Config,
2390        out: &mut Vec<(String, f64, f64)>,
2391    ) -> Result<(), ConfigError> {
2392        if let Some(table) = value.as_table() {
2393            return table.iter().try_for_each(|(key, v)| {
2394                walk(&if path.is_empty() { key.clone() } else { format!("{path}.{key}") }, v, cfg, out)
2395            });
2396        }
2397        cfg.f64(path)?;
2398        // A value written as an integer is a count (pole pairs, teeth): its bounds are whole numbers too.
2399        let whole = |v: f64| !cfg.get(path).is_ok_and(toml::Value::is_integer) || v.fract() == 0.0;
2400        match cfg.f64s(&format!("bounds.{path}"))?[..] {
2401            [low, high] if low <= high && whole(low) && whole(high) => out.push((path.into(), low, high)),
2402            _ => return Err(ConfigError::Invalid(format!("bounds.{path}"))),
2403        }
2404        Ok(())
2405    }
2406    let mut out = Vec::new();
2407    if let Ok(table) = cfg.get("bounds") {
2408        walk("", table, cfg, &mut out)?;
2409    }
2410    out.retain(|(path, ..)| !effect_off(cfg, path));
2411    Ok(out)
2412}
2413
2414/// `bounds` as the config resolved from `cfg` has them, where they are `cfg`'s own `[bounds]`: a part by name has
2415/// re-centred those of the values it set (see `bounds`). A bound given otherwise (the caller's own range), or one the
2416/// resolved config has none for, is kept.
2417pub(crate) fn followed(cfg: &Config, resolved: &Config, bounds: &[(String, f64, f64)]) -> Vec<(String, f64, f64)> {
2418    let own = |c: &Config, path: &str| match c.f64s(&format!("bounds.{path}")).as_deref() {
2419        Ok([low, high]) => Some((*low, *high)),
2420        _ => None,
2421    };
2422    bounds
2423        .iter()
2424        .map(|(path, low, high)| {
2425            let (low, high) = match (own(cfg, path), own(resolved, path)) {
2426                (Some(given), Some(now)) if given == (*low, *high) => now,
2427                _ => (*low, *high),
2428            };
2429            (path.clone(), low, high)
2430        })
2431        .collect()
2432}
2433
2434/// Sets a bounded value in the type its key has. `set_text("{path} = {value:?}")` wrote a float, which an integer key
2435/// refused with a Type error that ended the whole band run. An integer key takes the value rounded (`bounds` keeps its
2436/// bounds whole; a sampled value between them is rounded to a count).
2437pub fn set_bounded(cfg: &mut Config, path: &str, value: f64) -> Result<(), ConfigError> {
2438    let value = if cfg.get(path)?.is_integer() {
2439        toml::Value::Integer(value.round() as i64)
2440    } else {
2441        toml::Value::Float(value)
2442    };
2443    cfg.set(path, value)
2444}
2445
2446/// Values (by the start of their path) that only some effects use, and those effects: they change nothing while all
2447/// of them are off. None: a value no cycle uses, the discharge of a disabled drive's DC link. The parts warm with
2448/// effects.thermal_feedback too (`sim::heats`).
2449const PATH_EFFECTS: [(&str, &[&str]); 38] = [
2450    ("follower.roller_width_m", &["follower_lift_off"]),
2451    ("follower.contact_", &["follower_lift_off"]),
2452    ("follower.guide_friction_n", &["follower_lift_off"]),
2453    ("thermal.", &["part_heating", "thermal_feedback"]),
2454    ("motor.pole_pairs", &["field_weakening"]),
2455    ("motor.d_inductance_h", &["field_weakening"]),
2456    ("motor.winding_resistance_share", &["motor_thermal_nodes"]),
2457    ("motor.winding_time_constant_s", &["motor_thermal_nodes"]),
2458    ("ratings.drive_base_load_current_a", &["drive_overload"]),
2459    ("ratings.drive_overload_time_constant_s", &["drive_overload"]),
2460    ("ratings.drive_max_current_time_s", &["drive_overload"]),
2461    ("ratings.drive_chip_", &["drive_overload"]),
2462    ("motor.magnet_temperature_coefficient_1_k", &["magnet_temperature"]),
2463    ("motor.stall_current_a", &["iron_loss"]),
2464    ("ratings.braking_resistor_time_constant_s", &["braking_resistor_heating"]),
2465    ("ratings.braking_resistor_rated_rise_k", &["braking_resistor_heating"]),
2466    ("thermal_feedback.", &["thermal_feedback"]),
2467    ("belt.tooth_jump_factor", &["belt_tooth_jump"]),
2468    ("ratings.line_module_efficiency", &["dc_link"]),
2469    ("ratings.dc_link_discharge_", &[]),
2470    // The brakes' delays act only while the drives stop or start, which a cycle never does.
2471    ("brake.", &[]),
2472    ("motor.friction_breakaway_nm", &["motor_stiction"]),
2473    ("motor.friction_stribeck_rad_s", &["motor_stiction"]),
2474    ("slide.friction_breakaway_n", &["slide_presliding"]),
2475    ("slide.friction_stribeck_m_s", &["slide_presliding"]),
2476    ("slide.presliding_stiffness_n_m", &["slide_presliding"]),
2477    ("screw.friction_coefficient", &["screw_lead_efficiency"]),
2478    ("screw.fixed_bearing_at_m", &["screw_stiffness_with_position"]),
2479    ("gearbox.no_load_", &["gearbox_drag"]),
2480    ("gearbox.lost_motion_band_rad", &["gearbox_lost_motion"]),
2481    ("gearbox.hysteresis_rad", &["gearbox_lost_motion"]),
2482    // The knees and the upper stiffnesses; not stiffness_nm_rad, which every model uses.
2483    ("gearbox.stiffness_t", &["gearbox_stiffness_curve"]),
2484    ("gearbox.stiffness_k", &["gearbox_stiffness_curve"]),
2485    ("base.", &["base_compliance"]),
2486    ("link_bending.", &["link_bending"]),
2487    ("beam.", &["beam_sag"]),
2488    ("tool_flex.z_axis_bending_stiffness_nm2", &["z_axis_bending"]),
2489    ("mass.elbow_twist_inertia_kgm2", &["arm_tube_inertia"]),
2490];
2491
2492/// Whether `path` is a value only an effect uses (`PATH_EFFECTS`), and that effect is off in `cfg`, or a value no cycle
2493/// uses: varying it would only run the cycle again for nothing.
2494fn effect_off(cfg: &Config, path: &str) -> bool {
2495    PATH_EFFECTS.iter().any(|(start, effects)| {
2496        path.starts_with(start) && !effects.iter().any(|effect| cfg.bool(&format!("effects.{effect}")).unwrap_or(false))
2497    })
2498}
2499
2500/// A verdict with what the uncertain parameters do to it: the lowest and the highest value it took, and
2501/// whether it passed every time. `verdict` is the one of the config as it is; for a check that only a
2502/// bound brings up (the braking resistor, once the DC link is full) it is the first one seen.
2503#[derive(Debug, Clone, PartialEq)]
2504pub struct Band {
2505    pub verdict: Verdict,
2506    pub low: f64,
2507    pub high: f64,
2508    /// The worst case passes. Only then does the verdict pass with margin.
2509    pub ok: bool,
2510    /// The share of the runs in which the check passed, the config as it is among them. A run in which the
2511    /// check did not come up has passed it.
2512    pub share: f64,
2513}
2514
2515impl Band {
2516    /// `share` for showing with this many decimals: cut off, not rounded, so that a share below 1 never
2517    /// reads as 1 (one failed run in 2001 is 0.999, not 1.000).
2518    pub fn share_shown(&self, decimals: i32) -> f64 {
2519        // The 1e-9 keeps a share of whole digits whose product comes out a rounding below them on its digit.
2520        let scale = 10f64.powi(decimals);
2521        (self.share * scale + 1e-9).floor() / scale
2522    }
2523}
2524
2525/// The cycle of a config, judged.
2526fn judged(entry: &MachineEntry, cfg: &Config) -> Result<Vec<Verdict>, ConfigError> {
2527    let load = analyse_cycle_with(&mut Sim::new(entry, cfg)?, false).map_err(|e| ConfigError::Invalid(e.key.into()))?;
2528    verdicts(cfg, &load)
2529}
2530
2531/// The cycle of each config `make(0..count)` makes, judged; the runs are independent, so they share the processors.
2532/// In the order of `make`.
2533fn judge_each(
2534    entry: &MachineEntry,
2535    count: usize,
2536    make: impl Fn(usize) -> Result<Config, ConfigError> + Sync,
2537) -> Vec<Result<Vec<Verdict>, ConfigError>> {
2538    on_all_cores(count, |run| make(run).and_then(|cfg| judged(entry, &cfg)))
2539}
2540
2541/// The most threads `on_all_cores` starts; 0: one per processor.
2542static MAX_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2543
2544/// Limits the threads the analyses run their cycles on to `count` (0: one per processor, as by default). The results
2545/// do not depend on it, only the time they take.
2546pub fn set_max_threads(count: usize) {
2547    MAX_THREADS.store(count, std::sync::atomic::Ordering::Relaxed);
2548}
2549
2550/// How many threads `on_all_cores` starts at most: one per processor, or `set_max_threads`.
2551fn threads() -> usize {
2552    match MAX_THREADS.load(std::sync::atomic::Ordering::Relaxed) {
2553        0 => std::thread::available_parallelism().map_or(1, |n| n.get()),
2554        count => count,
2555    }
2556}
2557
2558thread_local! {
2559    /// The job this thread works for (`with_progress`); `on_all_cores` hands it on to its worker threads.
2560    static JOB: std::cell::RefCell<Option<std::sync::Arc<Progress>>> = const { std::cell::RefCell::new(None) };
2561}
2562
2563/// The payload of the unwind that ends a cancelled job: it is raised with `resume_unwind`, so no panic message is
2564/// printed, and `with_progress` turns it back into `Err(Cancelled)`.
2565#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2566pub struct Cancelled;
2567
2568/// Puts a job in as this thread's current one and puts the previous one back when dropped, also when unwinding.
2569struct JobGuard(Option<std::sync::Arc<Progress>>);
2570
2571impl JobGuard {
2572    fn install(job: Option<std::sync::Arc<Progress>>) -> Self {
2573        JobGuard(JOB.with(|slot| slot.replace(job)))
2574    }
2575}
2576
2577impl Drop for JobGuard {
2578    fn drop(&mut self) {
2579        JOB.with(|slot| *slot.borrow_mut() = self.0.take());
2580    }
2581}
2582
2583fn current_job() -> Option<std::sync::Arc<Progress>> {
2584    JOB.with(|slot| slot.borrow().clone())
2585}
2586
2587/// Runs `job` as the job `progress` describes: every batch of runs it starts (`on_all_cores`) is counted in `progress`
2588/// and stops once `progress.cancel` is set, which ends `job` with `Err(Cancelled)`. A panic of `job` stays a panic.
2589pub fn with_progress<T>(progress: &std::sync::Arc<Progress>, job: impl FnOnce() -> T) -> Result<T, Cancelled> {
2590    let _guard = JobGuard::install(Some(progress.clone()));
2591    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)) {
2592        Ok(value) => Ok(value),
2593        Err(payload) if payload.is::<Cancelled>() => Err(Cancelled),
2594        Err(payload) => std::panic::resume_unwind(payload),
2595    }
2596}
2597
2598/// Ends the current job at once (an unwind to `with_progress`) where it was cancelled; does nothing outside a job. For
2599/// the long loops that do not go through `on_all_cores`.
2600pub fn check_cancelled() {
2601    if current_job().is_some_and(|job| job.cancel.load(std::sync::atomic::Ordering::Relaxed)) {
2602        std::panic::resume_unwind(Box::new(Cancelled));
2603    }
2604}
2605
2606/// Adds `count` planned steps to the current job's total (none outside a job), for sequential work.
2607pub(crate) fn plan_steps(count: usize) {
2608    if let Some(job) = current_job() {
2609        job.total.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
2610    }
2611}
2612
2613/// Counts one step of sequential work as done in the current job (none outside a job).
2614pub(crate) fn step_done() {
2615    if let Some(job) = current_job() {
2616        job.done.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2617    }
2618}
2619
2620/// `work(0..count)` on all processors, in the order of the index: for runs that do not depend on each other. Inside a
2621/// job (`with_progress`) the runs are counted, no new run starts once the job is cancelled, and the call then ends the
2622/// job with the `Cancelled` unwind.
2623pub(crate) fn on_all_cores<T: Send>(count: usize, work: impl Fn(usize) -> T + Sync) -> Vec<T> {
2624    use std::sync::atomic::Ordering::Relaxed;
2625    let job = current_job();
2626    plan_steps(count);
2627    let cancelled = || job.as_ref().is_some_and(|job| job.cancel.load(Relaxed));
2628    let next = std::sync::atomic::AtomicUsize::new(0);
2629    let worker = || -> Vec<(usize, T)> {
2630        // A nested `on_all_cores` in a run sees the job from this worker thread, too.
2631        let _guard = JobGuard::install(job.clone());
2632        let mut done = Vec::new();
2633        loop {
2634            if cancelled() {
2635                return done;
2636            }
2637            let run = next.fetch_add(1, Relaxed);
2638            if run >= count {
2639                return done;
2640            }
2641            done.push((run, work(run)));
2642            step_done();
2643        }
2644    };
2645    let threads = threads().min(count.max(1));
2646    // One processor, or none known (WebAssembly, which cannot start threads): on this thread.
2647    let mut runs: Vec<_> = if threads <= 1 {
2648        worker()
2649    } else {
2650        std::thread::scope(|scope| {
2651            let workers: Vec<_> = (0..threads).map(|_| scope.spawn(worker)).collect();
2652            // All joined before one is passed on: a worker left to the scope would replace the payload.
2653            let joined: Vec<_> = workers.into_iter().map(|worker| worker.join()).collect();
2654            let mut runs = Vec::new();
2655            for result in joined {
2656                match result {
2657                    Ok(done) => runs.extend(done),
2658                    Err(payload) if payload.is::<Cancelled>() => std::panic::resume_unwind(payload),
2659                    Err(_) => panic!("a run of the cycle panicked"),
2660                }
2661            }
2662            runs
2663        })
2664    };
2665    if cancelled() {
2666        std::panic::resume_unwind(Box::new(Cancelled));
2667    }
2668    runs.sort_by_key(|(run, _)| *run);
2669    runs.into_iter().map(|(_, run)| run).collect()
2670}
2671
2672/// The bands of the cycle of `cfg` (already with its parts in) and of the configs `changed(0..count)` makes of
2673/// it. The runs are independent, so they share the processors; the bands come out the same in any case.
2674fn envelope(
2675    entry: &MachineEntry,
2676    cfg: &Config,
2677    count: usize,
2678    changed: impl Fn(usize) -> Result<Config, ConfigError> + Sync,
2679) -> Result<Vec<Band>, ConfigError> {
2680    // Run 0 is the config as it is.
2681    bands_of(judge_each(entry, count + 1, |run| if run == 0 { Ok(cfg.clone()) } else { changed(run - 1) }))
2682}
2683
2684/// The bands of these judged runs: per check the envelope, whether every run passed, and the share that did.
2685fn bands_of(runs: Vec<Result<Vec<Verdict>, ConfigError>>) -> Result<Vec<Band>, ConfigError> {
2686    // The failed runs are counted and divided once: subtracting 1 / total per failure left -5e-16 where all failed.
2687    let (total, mut bands, mut failed) = (runs.len(), Vec::<Band>::new(), Vec::<usize>::new());
2688    for run in runs {
2689        for v in run? {
2690            let fails = usize::from(!v.ok);
2691            match bands.iter().position(|b| b.verdict.check == v.check && b.verdict.motor == v.motor) {
2692                Some(k) => {
2693                    let b = &mut bands[k];
2694                    (b.low, b.high, b.ok) = (b.low.min(v.value), b.high.max(v.value), b.ok && v.ok);
2695                    failed[k] += fails;
2696                }
2697                None => {
2698                    bands.push(Band { low: v.value, high: v.value, ok: v.ok, share: 1.0, verdict: v });
2699                    failed.push(fails);
2700                }
2701            }
2702        }
2703    }
2704    for (band, failed) in bands.iter_mut().zip(failed) {
2705        band.share = (total - failed) as f64 / total as f64;
2706    }
2707    Ok(bands)
2708}
2709
2710/// The verdicts of the cycle with error bands: the cycle is run with the config as it is and with each
2711/// parameter of `bounds` (path, low, high; see `bounds`) at its low and at its high value, one at a
2712/// time, two runs per parameter. A band is the envelope of all these runs.
2713///
2714/// One at a time ignores interactions: two parameters that are both off can take a verdict beyond its
2715/// band. The band says which verdicts are safe against any single uncertain value, no more;
2716/// `verdict_bands_sampled` moves them all at once.
2717pub fn verdict_bands(
2718    entry: &MachineEntry,
2719    cfg: &Config,
2720    bounds: &[(String, f64, f64)],
2721) -> Result<Vec<Band>, ConfigError> {
2722    let resolved = &crate::catalog::resolve(entry, cfg)?;
2723    let (bounds, cfg) = (&followed(cfg, resolved, bounds), resolved);
2724    envelope(entry, cfg, 2 * bounds.len(), |run| {
2725        let ((path, low, high), mut changed) = (&bounds[run / 2], cfg.clone());
2726        set_bounded(&mut changed, path, if run % 2 == 0 { *low } else { *high })?;
2727        Ok(changed)
2728    })
2729}
2730
2731/// The verdicts of the cycle with error bands that count interactions: the cycle is run with the config as
2732/// it is and `samples` times with every parameter of `bounds` somewhere between its bounds, all at once. A
2733/// band is the envelope of these runs, and `Band::share` says in how many of them the check passed.
2734///
2735/// The values are a Latin hypercube: the range of each parameter is cut into `samples` equal parts, each
2736/// part is used in exactly one run (at a random place inside it), and each parameter has its parts in a
2737/// random order of its own. So every parameter is spread evenly over its range however few the runs, and
2738/// reaches to within a `samples`-th of the range of both bounds. Pseudo-random from `seed`: the same call
2739/// gives the same bands.
2740///
2741/// What it does not do: put a parameter exactly on a bound (`verdict_bands` does), or search for the worst
2742/// corner (`verdict_worst` does). With n parameters there are 2^n corners, and a few dozen runs meet none of
2743/// them: a check that fails only with several values near their bounds at once can pass every sample.
2744pub fn verdict_bands_sampled(
2745    entry: &MachineEntry,
2746    cfg: &Config,
2747    bounds: &[(String, f64, f64)],
2748    samples: usize,
2749    seed: u64,
2750) -> Result<Vec<Band>, ConfigError> {
2751    if samples == 0 {
2752        return Err(ConfigError::Invalid("samples".into()));
2753    }
2754    let resolved = &crate::catalog::resolve(entry, cfg)?;
2755    let (bounds, cfg) = (&followed(cfg, resolved, bounds), resolved);
2756    let mut random = sim_core::testkit::Noise(seed);
2757    let columns: Vec<Vec<f64>> = bounds
2758        .iter()
2759        .map(|(_, low, high)| {
2760            let mut values: Vec<f64> = (0..samples)
2761                .map(|part| low + (high - low) * (part as f64 + random.uniform()) / samples as f64)
2762                .collect();
2763            for i in (1..samples).rev() {
2764                values.swap(i, (random.uniform() * (i + 1) as f64) as usize);
2765            }
2766            values
2767        })
2768        .collect();
2769    envelope(entry, cfg, samples, |run| {
2770        let mut changed = cfg.clone();
2771        for ((path, ..), values) in bounds.iter().zip(&columns) {
2772            set_bounded(&mut changed, path, values[run])?;
2773        }
2774        Ok(changed)
2775    })
2776}
2777
2778/// The worst combination of the bounds found for one verdict: the verdict as judged there, and per parameter of the
2779/// bounds (in their order) whether it is at its high bound (`Some(true)`), its low one (`Some(false)`) or as
2780/// configured (`None`: where a run with one parameter alone at a bound, or the config as it is, was the worst).
2781#[derive(Debug, Clone, PartialEq)]
2782pub struct Worst {
2783    pub verdict: Verdict,
2784    pub high: Vec<Option<bool>>,
2785}
2786
2787/// How many passes of flipping one parameter at a time `verdict_worst` makes at most.
2788pub const WORST_PASSES: usize = 3;
2789
2790/// How bad a verdict is: how far its value is beyond its limit, or how much room it leaves below as a negative
2791/// number (for the checks of `AT_LEAST` the value has to stay above its limit). The margin and not the value,
2792/// because some limits are bounded themselves (the DC link's capacitance and threshold): a corner that raises the
2793/// threshold raises the highest voltage too, but leaves more room.
2794///
2795/// Not so "dc-link-energy": it fails only where the braking resistor is needed and has no rating, and with a resistor
2796/// the link fills up to its room at every corner that brakes hard (the margin is 0 at all of them). It is ranked by the
2797/// energy in the capacitors, any failing run above any passing one.
2798fn badness(v: &Verdict) -> f64 {
2799    match v.check {
2800        // J: no braking stores a gigajoule.
2801        "dc-link-energy" => v.value + if v.ok { 0.0 } else { 1e9 },
2802        _ if AT_LEAST.contains(&v.check) => v.limit - v.value,
2803        _ => v.value - v.limit,
2804    }
2805}
2806
2807/// A search for the worst combination of the uncertain parameters, per verdict. With n parameters the bounds have
2808/// 2^n corners, too many to run; the search looks at few of them:
2809///
2810/// 1. The cycle with each parameter alone at its low and its high bound (as `verdict_bands`, 2 n runs).
2811/// 2. Per verdict the corner where each parameter is at the bound that made that verdict worse alone (a parameter
2812///    that moved it not at all goes to its high bound). Where the verdict is a sum of effects that do not depend on
2813///    each other (a monotone function of each parameter), this is the worst corner.
2814/// 3. Up to `WORST_PASSES` passes per verdict: from its corner every parameter that moved the verdict alone is
2815///    flipped to its other bound, one at a time; the flips that made it worse are taken together, and the worse of
2816///    that corner and the best single flip becomes the corner, if it is worse than before. The search ends when a
2817///    pass finds nothing worse. This catches parameters whose sign changes with the others (interactions).
2818///
2819/// The same corner is run once for all verdicts that land on it, and the runs share the processors. What is
2820/// reported per verdict is the worst value it took in any run, the runs of step 1 included, with where the parameters
2821/// were: never better than `verdict_bands`. Returns the
2822/// verdicts in the order they came up (as `verdict_bands`) and the number of cycles simulated.
2823///
2824/// It is a search, not a proof: a verdict that is worst at a corner which no single flip from the sign corner
2825/// leads to, or inside the bounds and not at a corner at all (a resonance hit by a stiffness between its bounds),
2826/// can be missed. `verdict_bands_sampled` looks inside.
2827pub fn verdict_worst(
2828    entry: &MachineEntry,
2829    cfg: &Config,
2830    bounds: &[(String, f64, f64)],
2831) -> Result<(Vec<Worst>, usize), ConfigError> {
2832    verdict_worst_and_bands(entry, cfg, bounds).map(|(worst, _, runs)| (worst, runs))
2833}
2834
2835/// `verdict_worst`, and `verdict_bands` of the same bounds from the runs the search starts with, which are those of the
2836/// bands (the config as it is, then each parameter at its low and at its high bound): the bands cost no cycle more.
2837pub fn verdict_worst_and_bands(
2838    entry: &MachineEntry,
2839    cfg: &Config,
2840    bounds: &[(String, f64, f64)],
2841) -> Result<(Vec<Worst>, Vec<Band>, usize), ConfigError> {
2842    worst_search(entry, cfg, bounds, &[], &|_| false)
2843}
2844
2845/// `verdict_worst_and_bands`, started from the worst corners `from` found for another config with the same bounds (the
2846/// optimiser's previous step): per verdict, where `from` has one, its corner (a parameter it left as configured at the
2847/// sign corner's bound) is run beside the sign corner, and the worse of the two starts the passes. And the search ends
2848/// after the first batch of runs in which a verdict `stop` picks out came up: the worst it reports is then only what was
2849/// found so far (enough to say that a check fails).
2850fn worst_search(
2851    entry: &MachineEntry,
2852    cfg: &Config,
2853    bounds: &[(String, f64, f64)],
2854    from: &[Worst],
2855    stop: &(dyn Fn(&Verdict) -> bool + Sync),
2856) -> Result<(Vec<Worst>, Vec<Band>, usize), ConfigError> {
2857    let resolved = &crate::catalog::resolve(entry, cfg)?;
2858    let (bounds, cfg) = (&followed(cfg, resolved, bounds), resolved);
2859    let n = bounds.len();
2860    let set = |cfg: &mut Config, i: usize, high: bool| {
2861        set_bounded(cfg, &bounds[i].0, if high { bounds[i].2 } else { bounds[i].1 })
2862    };
2863    // Run 0 is the config as it is, then each parameter at its low and at its high bound.
2864    let alone = judge_each(entry, 2 * n + 1, |run| {
2865        let mut changed = cfg.clone();
2866        if run > 0 {
2867            set(&mut changed, (run - 1) / 2, run % 2 == 0)?;
2868        }
2869        Ok(changed)
2870    });
2871    let bands = bands_of(alone.clone())?;
2872    let alone = alone.into_iter().collect::<Result<Vec<_>, _>>()?;
2873    let mut ids: Vec<(&'static str, Option<usize>)> = Vec::new();
2874    for v in alone.iter().flatten() {
2875        if !ids.contains(&(v.check, v.motor)) {
2876            ids.push((v.check, v.motor));
2877        }
2878    }
2879    // How bad a verdict is in a run; a run in which it did not come up counts as the best.
2880    let bad = |run: &[Verdict], id: (&str, Option<usize>)| {
2881        run.iter().find(|v| (v.check, v.motor) == id).map_or(f64::NEG_INFINITY, badness)
2882    };
2883    let mut corners: Vec<Vec<bool>> = ids
2884        .iter()
2885        .map(|&id| (0..n).map(|i| bad(&alone[2 * i + 2], id) >= bad(&alone[2 * i + 1], id)).collect())
2886        .collect();
2887    let moves: Vec<Vec<usize>> = ids
2888        .iter()
2889        .map(|&id| (0..n).filter(|&i| bad(&alone[2 * i + 2], id) != bad(&alone[2 * i + 1], id)).collect())
2890        .collect();
2891
2892    // The previous worst corners, where there are any: a parameter left as configured there takes the sign corner's bound.
2893    let warm: Vec<Option<Vec<bool>>> = ids
2894        .iter()
2895        .zip(&corners)
2896        .map(|(&id, sign)| {
2897            let w = from.iter().find(|w| (w.verdict.check, w.verdict.motor) == id && w.high.len() == n)?;
2898            Some(w.high.iter().zip(sign).map(|(h, s)| h.unwrap_or(*s)).collect())
2899        })
2900        .collect();
2901
2902    let mut seen: std::collections::HashMap<Vec<bool>, Vec<Verdict>> = std::collections::HashMap::new();
2903    let mut runs = alone.len();
2904    let mut stopped = alone.iter().flatten().any(stop);
2905    // Runs the corners not run before; whether one of them has a verdict `stop` picks out.
2906    let mut run_corners = |wanted: Vec<Vec<bool>>,
2907                           seen: &mut std::collections::HashMap<Vec<bool>, Vec<Verdict>>|
2908     -> Result<bool, ConfigError> {
2909        let mut new: Vec<Vec<bool>> = Vec::new();
2910        for corner in wanted {
2911            if !seen.contains_key(&corner) && !new.contains(&corner) {
2912                new.push(corner);
2913            }
2914        }
2915        let judged = judge_each(entry, new.len(), |k| {
2916            let mut changed = cfg.clone();
2917            for (i, high) in new[k].iter().enumerate() {
2918                set(&mut changed, i, *high)?;
2919            }
2920            Ok(changed)
2921        });
2922        runs += new.len();
2923        let mut hit = false;
2924        for (corner, verdicts) in new.into_iter().zip(judged) {
2925            let verdicts = verdicts?;
2926            hit |= verdicts.iter().any(stop);
2927            seen.insert(corner, verdicts);
2928        }
2929        Ok(hit)
2930    };
2931    if !stopped {
2932        stopped = run_corners(corners.iter().cloned().chain(warm.iter().flatten().cloned()).collect(), &mut seen)?;
2933        for (k, warm) in warm.into_iter().enumerate() {
2934            if let Some(warm) = warm.filter(|w| bad(&seen[w], ids[k]) > bad(&seen[&corners[k]], ids[k])) {
2935                corners[k] = warm;
2936            }
2937        }
2938    }
2939    let flipped = |corner: &[bool], flips: &[usize]| {
2940        let mut out = corner.to_vec();
2941        for &i in flips {
2942            out[i] = !out[i];
2943        }
2944        out
2945    };
2946    for _ in 0..WORST_PASSES {
2947        if stopped {
2948            break;
2949        }
2950        let singles: Vec<Vec<bool>> = (0..ids.len())
2951            .flat_map(|k| moves[k].iter().map(|&i| flipped(&corners[k], &[i])).collect::<Vec<_>>())
2952            .collect();
2953        if run_corners(singles, &mut seen)? {
2954            break;
2955        }
2956        // Per verdict the flips that made it worse, and all of them together.
2957        let worse: Vec<Vec<usize>> = (0..ids.len())
2958            .map(|k| {
2959                moves[k]
2960                    .iter()
2961                    .copied()
2962                    .filter(|&i| bad(&seen[&flipped(&corners[k], &[i])], ids[k]) > bad(&seen[&corners[k]], ids[k]))
2963                    .collect()
2964            })
2965            .collect();
2966        stopped = run_corners(
2967            (0..ids.len()).filter(|&k| worse[k].len() > 1).map(|k| flipped(&corners[k], &worse[k])).collect(),
2968            &mut seen,
2969        )?;
2970        let mut changed = false;
2971        for k in 0..ids.len() {
2972            let candidates = worse[k]
2973                .iter()
2974                .map(|&i| flipped(&corners[k], &[i]))
2975                .chain((worse[k].len() > 1).then(|| flipped(&corners[k], &worse[k])));
2976            if let Some(best) = candidates.max_by(|a, b| bad(&seen[a], ids[k]).total_cmp(&bad(&seen[b], ids[k]))) {
2977                corners[k] = best;
2978                changed = true;
2979            }
2980        }
2981        if !changed {
2982            break;
2983        }
2984    }
2985    // Per verdict the worst it was in any run: at a corner, or with one parameter at a bound or none (so that the worst
2986    // is never better than `verdict_bands` reports).
2987    let alone_at = |run: usize| -> Vec<Option<bool>> {
2988        (0..n).map(|i| (run > 0 && (run - 1) / 2 == i).then_some(run.is_multiple_of(2))).collect()
2989    };
2990    let worst = ids
2991        .iter()
2992        .filter_map(|&id| {
2993            let corners = seen.iter().map(|(corner, run)| (corner.iter().map(|&h| Some(h)).collect::<Vec<_>>(), run));
2994            let candidates = corners.chain(alone.iter().enumerate().map(|(r, run)| (alone_at(r), run)));
2995            let (high, run) =
2996                candidates.max_by(|a, b| bad(a.1, id).total_cmp(&bad(b.1, id)).then_with(|| b.0.cmp(&a.0)))?;
2997            let verdict = run.iter().find(|v| (v.check, v.motor) == id)?.clone();
2998            Some(Worst { verdict, high })
2999        })
3000        .collect();
3001    Ok((worst, bands, runs))
3002}
3003
3004/// A cycle made faster: the cycle before and after, the settings that changed (path, before, after) and
3005/// the number of cycles that were simulated on the way. Where the optimiser changed the cycle's geometry, `changes`
3006/// has the whole new cycle as the entry "cycle.segment" (TOML, for `Config::set_text`), and `lifts` says what changed.
3007/// `runs` counts the search's cycles, the sweep of `OptimiseOptions::pareto` among them; the bands' are in `robust`.
3008#[derive(Debug, Clone)]
3009pub struct Optimised {
3010    pub before: CycleLoad,
3011    pub after: CycleLoad,
3012    pub changes: Vec<(String, String, String)>,
3013    pub lifts: Vec<LiftChange>,
3014    pub runs: usize,
3015    /// With `OptimiseOptions::robust`: how the result stands in the error bands.
3016    pub robust: Option<Robust>,
3017    /// With `OptimiseOptions::pareto`: the settings run that passed every verdict and that no other one beats in cycle
3018    /// time, energy and peak utilisation at once, fastest first. Empty without.
3019    pub front: Vec<FrontPoint>,
3020}
3021
3022/// What to optimise for: at most `max_runs` cycles in the search; `robust`: the result has to pass every verdict in the
3023/// error bands too (`verdict_bands`, one bound of `[bounds]` at a time), not only as configured; `pareto`: the
3024/// non-dominated set of cycle time, energy and peak utilisation (`Optimised::front`), with a sweep of slower settings;
3025/// `worst` (with `robust`): judged at the worst corner of all bounds at once (`verdict_worst`) instead of the bands.
3026#[derive(Debug, Clone, Copy, PartialEq)]
3027pub struct OptimiseOptions {
3028    pub max_runs: usize,
3029    pub robust: bool,
3030    pub pareto: bool,
3031    pub worst: bool,
3032}
3033
3034/// The fastest setting the search found on the verdicts as configured, judged in the error bands: its cycle time and
3035/// the checks it fails there (none where it passes); the checks the cycle as configured fails in the bands already,
3036/// which the result is not judged on (it cannot take back a margin the config does not have); how many accepted steps
3037/// the result went back from the fastest to the fastest one that passes the other checks in the bands; and the cycles
3038/// the bands took (2 n + 1 per setting judged, n the bounds). With `worst`, all of it at the worst corner instead: there
3039/// the search stops at the first batch of runs that fails a check judged on, so `nominal_fails` are the checks found
3040/// failing by then (not every one), and `runs` counts the worst-corner searches' cycles.
3041#[derive(Debug, Clone, PartialEq)]
3042pub struct Robust {
3043    pub nominal_duration: f64,
3044    pub nominal_fails: Vec<&'static str>,
3045    pub excused: Vec<&'static str>,
3046    pub steps_back: usize,
3047    pub runs: usize,
3048    pub worst: bool,
3049}
3050
3051/// A setting on the energy-against-time front: cycle time (s), energy per cycle from the supply (`supply_energy`, J),
3052/// the highest utilisation of any motor's torque-speed curve (`MotorLoad::utilisation`), and the setting: factors on the
3053/// axes' speed, acceleration and jerk, corner blending and input shaping. The lifts are not shown.
3054#[derive(Debug, Clone, PartialEq)]
3055pub struct FrontPoint {
3056    pub duration: f64,
3057    pub energy: f64,
3058    pub utilisation: f64,
3059    pub factors: [f64; 3],
3060    pub blending: bool,
3061    pub shaping: bool,
3062}
3063
3064/// The energy a cycle takes from the supply, J: what the drives drew less what they fed back, plus what the braking
3065/// resistor burned of what they fed back (with the DC link simulated; a shared one counted once). What the capacitors
3066/// hold more at the end than at the start counts as fed back. With the DC link simulated also what the bleeders took
3067/// out of it and the line module's (or an S210's rectifier's) own loss, `effects.dc_link`'s
3068/// `ratings.line_module_efficiency` eta both ways: it draws `drawn / eta` from the line for the `drawn` it puts into the
3069/// DC link and gives the mains `eta * fed` of the `fed` it takes out (`effects.regenerative_supply`), so it loses
3070/// `(1/eta - 1) drawn + (1 - eta) fed`; with the load's `line_module_energy = drawn + fed` and `mains_energy = eta * fed`,
3071/// `fed = mains_energy / eta`. The DC link's balance, drawn - fed = net + burned + bleeders (+ what the capacitors gain),
3072/// makes this the energy drawn from the line less what the mains got back. A shared link is counted once, with the
3073/// shared config's efficiency; a link of its own with its motor's (`catalog::motor_config`).
3074pub fn supply_energy(cfg: &Config, load: &CycleLoad) -> f64 {
3075    let net: f64 = load.motors.iter().map(|m| m.energy_in - m.energy_regenerated).sum();
3076    let shared = cfg.bool("effects.shared_dc_link").unwrap_or(false);
3077    // Every drive of a shared link reports the link's resistor and line module as its own.
3078    let links: Vec<&MotorLoad> =
3079        if shared { load.motors.iter().take(1).collect() } else { load.motors.iter().collect() };
3080    let burned: f64 = links.iter().map(|m| m.resistor_energy).sum();
3081    if !cfg.bool("effects.dc_link").unwrap_or(false) {
3082        return net + burned;
3083    }
3084    let bled: f64 = load.motors.iter().map(|m| m.discharge_energy).sum();
3085    let line: f64 = links
3086        .iter()
3087        .map(|m| {
3088            let own = if shared { None } else { crate::catalog::motor_config(cfg, &m.id).ok() };
3089            let eta = own.as_ref().unwrap_or(cfg).positive("ratings.line_module_efficiency").unwrap_or(1.0);
3090            let fed = m.mains_energy / eta;
3091            (1.0 / eta - 1.0) * (m.line_module_energy - fed) + (1.0 - eta) * fed
3092        })
3093        .sum();
3094    net + burned + bled + line
3095}
3096
3097/// The points that no other one beats: none other is as good in all three figures and better in one. Fastest first;
3098/// a point that is there twice is kept once.
3099pub fn non_dominated(points: &[FrontPoint]) -> Vec<FrontPoint> {
3100    let figures: Vec<Vec<f64>> = points.iter().map(|p| vec![p.duration, p.energy, p.utilisation]).collect();
3101    let mut front: Vec<FrontPoint> = non_dominated_indices(&figures).into_iter().map(|i| points[i].clone()).collect();
3102    front.sort_by(|a, b| a.duration.total_cmp(&b.duration));
3103    front
3104}
3105
3106/// The indices of the rows of figures (each the same number of figures, lower better) that no other row beats: none
3107/// other is as good in every figure and better in one. A row that is there twice is kept once, the first; in the order
3108/// of the rows. For the optimiser's front (`non_dominated`) and the catalogue search's (`search::front`).
3109pub fn non_dominated_indices(figures: &[Vec<f64>]) -> Vec<usize> {
3110    let beats = |a: &[f64], b: &[f64]| a.iter().zip(b).all(|(x, y)| x <= y) && a != b;
3111    let mut front: Vec<usize> = Vec::new();
3112    for (i, p) in figures.iter().enumerate() {
3113        if !figures.iter().any(|q| beats(q, p)) && !front.iter().any(|&k| figures[k] == *p) {
3114            front.push(i);
3115        }
3116    }
3117    front
3118}
3119
3120/// A lift, traverse and lower of the cycle that the optimiser changed: the three segments of the configured cycle
3121/// (counted from 0), the height of the traverse (the last axis) before and after, and the via points the path is rounded
3122/// through, where it took them (then the three segments are one: a path up, through the via points and down, see
3123/// `control::via_pieces`): one over the middle or over the nearest obstacle, or two per obstacle in the way, the height
3124/// profile (`lift_profiles`).
3125#[derive(Debug, Clone, PartialEq)]
3126pub struct LiftChange {
3127    pub segments: [usize; 3],
3128    pub before: f64,
3129    pub after: f64,
3130    pub via: Option<Vec<Vec<f64>>>,
3131    /// Where the lift's corners are rounded instead (`corners_m` of the segment, `control::lines_through`): the corner
3132    /// tolerance, its via points then none but the two corners at the lift's height.
3133    pub corners: Option<f64>,
3134}
3135
3136/// A lift, traverse and lower of a configured cycle (`lifts`): segment `lift` goes from `from` straight along the last
3137/// axis to `height`, `traverse` along the other axes at that height, `lower` straight along the last axis to `to`.
3138/// `up` is the side (+1 or -1 on the last axis) both ends lie away from; `lowest` the height nearest them that keeps
3139/// `profile.min_clearance_m` to the farther of the two. `needed` is the lowest height at which the traverse keeps that
3140/// clearance to the obstacles as well (`over_obstacles`; `lowest` without obstacles in the way, the height as configured
3141/// where none clears them), `over` the pose on the traverse nearest to an obstacle there, where one raised it. `payload`:
3142/// whether the payload is on during the three segments.
3143struct Lift {
3144    segments: [usize; 3],
3145    from: Vec<f64>,
3146    to: Vec<f64>,
3147    height: f64,
3148    up: f64,
3149    lowest: f64,
3150    needed: f64,
3151    over: Option<Vec<f64>>,
3152    profile: Option<Vec<Vec<f64>>>,
3153    payload: bool,
3154}
3155
3156/// The lifts of a cycle: three segments in a row (round the end of the cycle too) of which the first moves along the
3157/// last axis only, away from both the start and the end of the three, the second along the other axes only, at that
3158/// height, and the third along the last axis only. The first two neither dwell nor change the payload, none has via
3159/// points. A lift already as low as the clearance allows is a lift all the same (it can still be rounded).
3160fn lifts(cfg: &Config, clearance: f64) -> Result<Vec<Lift>, ConfigError> {
3161    let segments = cfg.array("cycle.segment")?;
3162    let n = segments.len();
3163    let target = |i: usize| -> Option<Vec<f64>> {
3164        segments[i]
3165            .get("target")?
3166            .as_array()?
3167            .iter()
3168            .map(|v| v.as_float().or_else(|| v.as_integer().map(|i| i as f64)))
3169            .collect()
3170    };
3171    let plain = |i: usize| segments[i].get("via").is_none();
3172    let quiet = |i: usize| {
3173        segments[i].get("dwell_s").and_then(|d| d.as_float().or_else(|| d.as_integer().map(|i| i as f64))) == Some(0.0)
3174            && segments[i].get("payload") == segments[(i + n - 1) % n].get("payload")
3175    };
3176    let mut out = Vec::new();
3177    if n < 3 {
3178        return Ok(out);
3179    }
3180    for a in 0..n {
3181        let (b, c) = ((a + 1) % n, (a + 2) % n);
3182        let (Some(from), Some(lift), Some(traverse), Some(to)) =
3183            (target((a + n - 1) % n), target(a), target(b), target(c))
3184        else {
3185            continue;
3186        };
3187        let z = from.len().wrapping_sub(1);
3188        if from.len() < 2 || [&lift, &traverse, &to].iter().any(|p| p.len() != from.len()) {
3189            continue;
3190        }
3191        let along_z = |p: &[f64], q: &[f64]| p[..z] == q[..z] && p[z] != q[z];
3192        let height = lift[z];
3193        let up = (height - from[z]).signum();
3194        if !(along_z(&from, &lift)
3195            && traverse[z] == height
3196            && traverse[..z] != lift[..z]
3197            && along_z(&traverse, &to)
3198            && (height - to[z]).signum() == up)
3199        {
3200            continue;
3201        }
3202        if !(quiet(a) && quiet(b) && plain(a) && plain(b) && plain(c)) {
3203            continue;
3204        }
3205        let lowest = if up > 0.0 { from[z].max(to[z]) + clearance } else { from[z].min(to[z]) - clearance };
3206        // A clearance that is the lift as configured, but for rounding (0.05 + 0.3 is 0.35 and a bit), is that lift.
3207        let lowest = if (lowest - height).abs() < 1e-9 { height } else { lowest };
3208        // A lift that is lower than the clearance asks for as configured is left as it is.
3209        if up * (height - lowest) >= 0.0 {
3210            // The segments run with the payload as the one before left it, which `quiet` keeps.
3211            let payload = segments[a].get("payload").and_then(|p| p.as_bool()).unwrap_or(true);
3212            out.push(Lift {
3213                segments: [a, b, c],
3214                from,
3215                to,
3216                height,
3217                up,
3218                lowest,
3219                needed: lowest,
3220                over: None,
3221                profile: None,
3222                payload,
3223            });
3224        }
3225    }
3226    Ok(out)
3227}
3228
3229/// The lowest height of a lift's traverse at which the machine's collision bodies keep `clearance` to the obstacles, at
3230/// rest at every millimetre of it (`collision::check_path`), with the pose nearest to an obstacle there where one raised
3231/// it above `lowest`. From `lowest`, the height is moved each time by what the clearance lacks (up) or has too much
3232/// (down, never below `lowest`) until it is the clearance to 1 nm. The bodies move with the last axis, so the clearance
3233/// changes by no more than the height: a box across the traverse is cleared in one step, to the clearance exactly. `None`
3234/// where 40 steps within the axis's range find no height that clears (a box beside the traverse that reaches above it).
3235fn over_obstacles(
3236    machine: &mut dyn sim_core::Machine,
3237    obstacles: &[sim_core::Obstacle],
3238    lift: &Lift,
3239    clearance: f64,
3240    axis: &sim_core::AxisInfo,
3241) -> Option<(f64, Option<Vec<f64>>)> {
3242    let z = lift.from.len() - 1;
3243    machine.set_payload_attached(lift.payload);
3244    let machine: &dyn sim_core::Machine = machine;
3245    let gap_at = |height: f64| {
3246        let at = |p: &[f64]| -> Vec<f64> { p[..z].iter().copied().chain([height]).collect() };
3247        let mut check = crate::collision::PlanCheck::default();
3248        crate::collision::check_path(machine, obstacles, &[at(&lift.from), at(&lift.to)], &mut check);
3249        (check.clearance, check.nearest)
3250    };
3251    let (mut height, mut best) = (lift.lowest, None::<(f64, Option<Vec<f64>>)>);
3252    for _ in 0..40 {
3253        let (gap, nearest) = gap_at(height);
3254        if gap >= clearance - 1e-9 && best.as_ref().is_none_or(|(b, _)| lift.up * (height - b) < 0.0) {
3255            best = Some((height, nearest));
3256        }
3257        // How far beyond `lowest` the next height is (on the side `up`): what it is now, plus what the clearance lacks.
3258        let next = lift.lowest + lift.up * (lift.up * (height - lift.lowest) + clearance - gap).max(0.0);
3259        if !gap.is_finite()
3260            || (gap - clearance).abs() <= 1e-9
3261            || next == height
3262            || !(axis.min..=axis.max).contains(&next)
3263        {
3264            break;
3265        }
3266        height = next;
3267    }
3268    best.map(|(height, nearest)| (height, if height == lift.lowest { None } else { nearest }))
3269}
3270
3271/// The height profile of a lift over the obstacles in its way: per obstacle that raises the traverse (`over_obstacles`
3272/// with it alone), two via points at its own height, where the traverse at `lowest` begins and ends to come nearer to it
3273/// than `clearance` (looked at every millimetre, the collision bodies at rest with the payload as the lift carries it).
3274/// Obstacles whose stretches overlap are passed as one, at the higher of their heights. `None` with fewer than two such
3275/// stretches (one box: the lift at `needed`, as without a profile), or where an obstacle cannot be cleared.
3276fn profile(
3277    machine: &mut dyn sim_core::Machine,
3278    obstacles: &[sim_core::Obstacle],
3279    lift: &Lift,
3280    clearance: f64,
3281    axis: &sim_core::AxisInfo,
3282) -> Option<Vec<Vec<f64>>> {
3283    let z = lift.from.len() - 1;
3284    let at = |s: f64, height: f64| -> Vec<f64> {
3285        (0..z).map(|i| lift.from[i] + s * (lift.to[i] - lift.from[i])).chain([height]).collect()
3286    };
3287    let width = (0..z).map(|i| (lift.to[i] - lift.from[i]).powi(2)).sum::<f64>().sqrt();
3288    let steps = (width / 1e-3).ceil().max(1.0) as usize;
3289    let mut stretches: Vec<(f64, f64, f64)> = Vec::new();
3290    for one in obstacles.chunks(1) {
3291        let (height, over) = over_obstacles(machine, one, lift, clearance, axis)?;
3292        if over.is_none() {
3293            continue;
3294        }
3295        machine.set_payload_attached(lift.payload);
3296        let near = (0..=steps).map(|k| k as f64 / steps as f64).filter(|&s| {
3297            let mut check = crate::collision::PlanCheck::default();
3298            crate::collision::check_path(&*machine, one, &[at(s, lift.lowest)], &mut check);
3299            check.clearance < clearance - 1e-9
3300        });
3301        let (first, last) = near.fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), s| (a.min(s), b.max(s)));
3302        if first <= last {
3303            stretches.push((first, last, height));
3304        }
3305    }
3306    stretches.sort_by(|a, b| a.0.total_cmp(&b.0));
3307    let mut merged: Vec<(f64, f64, f64)> = Vec::new();
3308    for (first, last, height) in stretches {
3309        match merged.last_mut() {
3310            Some(m) if first <= m.1 => {
3311                (m.1, m.2) = (m.1.max(last), if lift.up > 0.0 { m.2.max(height) } else { m.2.min(height) })
3312            }
3313            _ => merged.push((first, last, height)),
3314        }
3315    }
3316    (merged.len() >= 2)
3317        .then(|| merged.iter().flat_map(|&(first, last, height)| [at(first, height), at(last, height)]).collect())
3318}
3319
3320/// The points with the last axis moved by `by`.
3321fn raised(points: &[Vec<f64>], by: f64) -> Vec<Vec<f64>> {
3322    points
3323        .iter()
3324        .map(|p| p.iter().enumerate().map(|(i, x)| if i + 1 == p.len() { x + by } else { *x }).collect())
3325        .collect()
3326}
3327
3328/// A lift's height profile (`profile`) and how far its points have to be raised (on the side `up`) for the planner's
3329/// spline through them to keep the clearance: the spline sags between the points, so they are raised by what the
3330/// planned path lacks and 1 um, three times at most. `None` where there is no profile or it still does not clear.
3331/// `planned`: the axes, the profile cycle and the path tolerance the planner times it with.
3332fn smoothed_profile(
3333    machine: &mut dyn sim_core::Machine,
3334    obstacles: &[sim_core::Obstacle],
3335    lift: &Lift,
3336    clearance: f64,
3337    planned: (&[sim_core::AxisInfo], f64, f64),
3338) -> Option<(Vec<Vec<f64>>, f64)> {
3339    let (axes, cycle, tolerance) = planned;
3340    let points = profile(machine, obstacles, lift, clearance, &axes[lift.from.len() - 1])?;
3341    let mut by = 0.0;
3342    for _ in 0..4 {
3343        let via = raised(&points, lift.up * by);
3344        let at = (lift.lowest, None);
3345        let gap = planned_clearance(axes, cycle, tolerance, lift, at, &via, (&mut *machine, obstacles, clearance))?;
3346        if gap >= clearance - 1e-9 {
3347            return Some((points, by));
3348        }
3349        by += clearance - gap + 1e-6;
3350    }
3351    None
3352}
3353
3354/// Per lift of the cycle with two or more obstacles in its way (as the optimiser finds them, `optimise_cycle_with`): its
3355/// three segments, its height profile as `profile` builds it, and how far the optimiser raises those points for the
3356/// planned spline through them to keep the clearance (`smoothed_profile`). Empty without obstacles; lifts with fewer
3357/// than two obstacles in the way, or whose profile does not clear, are left out.
3358pub fn lift_profiles(entry: &MachineEntry, cfg: &Config) -> Result<Vec<([usize; 3], Vec<Vec<f64>>, f64)>, ConfigError> {
3359    let mut probe = Sim::new(entry, cfg)?;
3360    let clearance = cfg.non_negative("profile.min_clearance_m")?;
3361    let (cycle, tolerance) = (cfg.positive("profile.cycle_s")?, cfg.non_negative("profile.path_tolerance_m")?);
3362    let (axes, obstacles) = (probe.machine.axes().to_vec(), probe.obstacles.clone());
3363    let mut out = Vec::new();
3364    for lift in lifts(cfg, clearance)?.iter().filter(|_| !obstacles.is_empty()) {
3365        let planned = (axes.as_slice(), cycle, tolerance);
3366        if let Some((points, by)) = smoothed_profile(probe.machine.as_mut(), &obstacles, lift, clearance, planned) {
3367            out.push((lift.segments, points, by));
3368        }
3369    }
3370    Ok(out)
3371}
3372
3373/// The cycle with each lift at `heights` and, where `vias` has some, rounded through those via points, or where
3374/// `corners` has a tolerance, its two corners rounded within it (see `LiftChange`).
3375fn cycle_with(
3376    cfg: &Config,
3377    lifts: &[Lift],
3378    heights: &[f64],
3379    vias: &[Option<Vec<Vec<f64>>>],
3380    corners: &[Option<f64>],
3381) -> Result<toml::Value, ConfigError> {
3382    let mut segments = cfg.array("cycle.segment")?.clone();
3383    let number_list = |p: &[f64]| toml::Value::Array(p.iter().map(|x| toml::Value::Float(*x)).collect());
3384    let mut dropped = Vec::new();
3385    for (((lift, &height), via), corner) in lifts.iter().zip(heights).zip(vias).zip(corners) {
3386        let [a, b, c] = lift.segments;
3387        let at_height = |p: &[f64]| {
3388            let mut p = p.to_vec();
3389            *p.last_mut().unwrap_or(&mut 0.0) = height;
3390            p
3391        };
3392        match via {
3393            None => {
3394                for i in [a, b] {
3395                    let old = segments[i].get("target").and_then(|t| t.as_array()).cloned().unwrap_or_default();
3396                    let pose: Vec<f64> =
3397                        old.iter().filter_map(|v| v.as_float().or_else(|| v.as_integer().map(|i| i as f64))).collect();
3398                    if let Some(t) = segments[i].as_table_mut() {
3399                        t.insert("target".into(), number_list(&at_height(&pose)));
3400                    }
3401                }
3402            }
3403            Some(points) => {
3404                let via = toml::Value::Array(
3405                    std::iter::once(at_height(&lift.from))
3406                        .chain(points.iter().cloned())
3407                        .chain([at_height(&lift.to)])
3408                        .map(|p| number_list(&p))
3409                        .collect(),
3410                );
3411                if let Some(t) = segments[c].as_table_mut() {
3412                    t.insert("via".into(), via);
3413                    if let Some(corner) = corner {
3414                        t.insert("corners_m".into(), toml::Value::Float(*corner));
3415                    }
3416                }
3417                dropped.extend([a, b]);
3418            }
3419        }
3420    }
3421    let kept = segments.into_iter().enumerate().filter(|(i, _)| !dropped.contains(i)).map(|(_, s)| s).collect();
3422    Ok(toml::Value::Array(kept))
3423}
3424
3425/// Whether the path of a lift rounded through `via` keeps its clearance: every planned pose that lies between the two
3426/// ends along the other axes is at `lowest` or beyond, less the path tolerance the transition curves may use; and where
3427/// there are obstacles, the machine's collision bodies keep `clearance` to them along the whole path, at rest at each
3428/// planned pose (`collision::check_path`).
3429fn clears(
3430    axes: &[sim_core::AxisInfo],
3431    cycle: f64,
3432    tolerance: f64,
3433    lift: &Lift,
3434    height: (f64, Option<f64>),
3435    via: &[Vec<f64>],
3436    bodies: (&mut dyn sim_core::Machine, &[sim_core::Obstacle], f64),
3437) -> bool {
3438    let clearance = bodies.2;
3439    planned_clearance(axes, cycle, tolerance, lift, height, via, bodies).is_some_and(|gap| gap >= clearance - 1e-9)
3440}
3441
3442/// The least clearance to the obstacles of the planned path of a lift rounded through `via` (infinite without
3443/// obstacles); `None` where it is not planned or comes nearer to pick and place than `lowest` (see `clears`). `height`:
3444/// the lift's, and the corner tolerance where its corners are rounded (lines through the via points,
3445/// `control::lines_through`) instead of a curve through them.
3446fn planned_clearance(
3447    axes: &[sim_core::AxisInfo],
3448    cycle: f64,
3449    tolerance: f64,
3450    lift: &Lift,
3451    (height, corner): (f64, Option<f64>),
3452    via: &[Vec<f64>],
3453    bodies: (&mut dyn sim_core::Machine, &[sim_core::Obstacle], f64),
3454) -> Option<f64> {
3455    let points = lift_path(axes, cycle, tolerance, lift, (height, corner), via)?;
3456    let (machine, obstacles, _) = bodies;
3457    if obstacles.is_empty() {
3458        return Some(f64::INFINITY);
3459    }
3460    machine.set_payload_attached(lift.payload);
3461    let mut check = crate::collision::PlanCheck::default();
3462    let poses: Vec<Vec<f64>> =
3463        std::iter::once(lift.from.clone()).chain(points.into_iter().map(|(_, pose)| pose)).collect();
3464    crate::collision::check_path(&*machine, obstacles, &poses, &mut check);
3465    Some(check.clearance)
3466}
3467
3468/// The planned path of a lift rounded through `via` (or with its corners rounded, see `planned_clearance`), `None`
3469/// where it is not planned or comes nearer to pick and place than `lowest` (see `clears`).
3470fn lift_path(
3471    axes: &[sim_core::AxisInfo],
3472    cycle: f64,
3473    tolerance: f64,
3474    lift: &Lift,
3475    (height, corner): (f64, Option<f64>),
3476    via: &[Vec<f64>],
3477) -> Option<Vec<(f64, Vec<f64>)>> {
3478    let z = lift.from.len() - 1;
3479    let at_height = |p: &[f64]| {
3480        let mut p = p.to_vec();
3481        p[z] = height;
3482        p
3483    };
3484    let via: Vec<Vec<f64>> =
3485        std::iter::once(at_height(&lift.from)).chain(via.iter().cloned()).chain([at_height(&lift.to)]).collect();
3486    let (pieces, rounded) = match corner {
3487        Some(corner) => {
3488            (crate::control::lines_through(&via, &lift.to), crate::path::Tolerance { path: tolerance, corner })
3489        }
3490        None => (crate::control::via_pieces(&via, &lift.to), tolerance.into()),
3491    };
3492    let points = crate::path::plan(axes, &lift.from, &pieces, cycle, rounded, crate::path::ARC_SLACK).ok()?;
3493    let across: Vec<f64> = (0..z).map(|i| lift.to[i] - lift.from[i]).collect();
3494    let width = across.iter().map(|d| d * d).sum::<f64>();
3495    let above = points.iter().all(|(_, pose)| {
3496        let along = (0..z).map(|i| (pose[i] - lift.from[i]) * across[i]).sum::<f64>() / width;
3497        along <= 0.0 || along >= 1.0 || lift.up * (pose[z] - lift.lowest) >= -tolerance - 1e-9
3498    });
3499    above.then_some(points)
3500}
3501
3502/// Shortens the cycle of a config without breaking a verdict. Tries corner blending, then raises speed,
3503/// acceleration and jerk of all axes together in steps for as long as the cycle gets shorter and every
3504/// verdict of `verdicts` still passes, among them the settling tolerance, so a faster move that leaves
3505/// the tool swinging at the pick does not count. Input shaping makes no cycle shorter by itself (every
3506/// stop waits one period of the shaper), so it is tried where it can help: a faster setting that fails
3507/// on "settling" alone is run again with the shaper, and with the shaper following the pose where the
3508/// machine reports a resonance, and is taken if it then passes and is shorter. A setting with the shaper that still
3509/// fails on "settling" alone is run again with a second shaper convolved with it, at `profile.shaper2_frequency_hz`
3510/// where the config has one, else at the machine's second mode at the start pose (`Machine::modes`), else at the one
3511/// resonance it reports there where that is more than 10 % off the first shaper's frequency (no second shaper is tried
3512/// where none of these is). Where a shaper is on already,
3513/// switching it off is tried too. Simulates at most `max_runs` cycles.
3514///
3515/// The geometry of the cycle is a variable too. Each lift, traverse and lower (see `lifts`) is tried first with all
3516/// lifts as low as `profile.min_clearance_m` allows (that far beyond the farther of pick and place), then each alone at
3517/// that height and halfway down to it. Last, once no other step helps, the corners of a lift are rounded: the three
3518/// segments become one path up to the lift height, through a via point and down (`control::via_pieces`, timed by the
3519/// path planner with the transition curves of `profile.path_tolerance_m`), the via point at the middle and a half, a
3520/// quarter and an eighth of the width above the lift height; then moved by an eighth and a thirty-second of the width
3521/// along each axis, or the rounding dropped. A via point whose planned path comes nearer to pick and place than the
3522/// clearance between them is not run. Where the config has obstacles, a setting whose run comes nearer to one than the
3523/// clearance fails the verdict "collision" and is not taken; the cycle as configured is refused if it does.
3524///
3525/// A search by trial, not a proof of the optimum: it stops at the first setting from which no single step
3526/// is an improvement. Judged on the verdicts as configured, at most `max_runs` cycles: `optimise_cycle_with` for the
3527/// error bands and the energy front.
3528pub fn optimise_cycle(entry: &MachineEntry, cfg: &Config, max_runs: usize) -> Result<Optimised, ConfigError> {
3529    optimise_cycle_with(entry, cfg, &OptimiseOptions { max_runs, robust: false, pareto: false, worst: false })
3530}
3531
3532/// The fastest of the steps 1 to `top` that passes, judged by `pass` from the fastest down and the first that passes
3533/// taken; `None` where none does (step 0, the cycle as configured, passes by definition and is not judged). Pass and fail
3534/// need not follow the steps (a faster step may pass where a slower one fails), so no step above the result is left out:
3535/// the cost is one judgement per step above the result and the result's own, never more than a bisection followed by
3536/// judging the steps above its result would take.
3537fn fastest_passing<T, E>(
3538    top: usize,
3539    mut pass: impl FnMut(usize) -> Result<Option<T>, E>,
3540) -> Result<Option<(usize, T)>, E> {
3541    for k in (1..=top).rev() {
3542        if let Some(passed) = pass(k)? {
3543            return Ok(Some((k, passed)));
3544        }
3545    }
3546    Ok(None)
3547}
3548
3549/// The second input shaper's frequency the cycle optimiser tries (Hz) with the plan at `pose`: `profile.shaper2_frequency_hz`
3550/// where set (above 0); otherwise the second of the modes the shaper acts on (`Machine::sway_modes`: a crane's upper swing
3551/// with the hook block, not the load's bounce on its rope), or, where the machine tells only one, its resonance where
3552/// that is more than 10 % off `profile.shaper_frequency_hz`. `None`: no second shaper to try.
3553pub fn second_shaper_frequency(machine: &dyn Machine, pose: &[f64], cfg: &Config) -> Result<Option<f64>, ConfigError> {
3554    let (first, configured) =
3555        (cfg.positive("profile.shaper_frequency_hz")?, cfg.non_negative("profile.shaper2_frequency_hz")?);
3556    if configured > 0.0 {
3557        return Ok(Some(configured));
3558    }
3559    let second = machine.sway_modes(pose).get(1).map(|mode| mode.hz);
3560    Ok(second.or(machine.resonance_hz(pose).filter(|f| (f / first - 1.0).abs() > 0.1)))
3561}
3562
3563/// `optimise_cycle`, and with `options.robust` a result that passes in the error bands: the fastest setting found is
3564/// judged with `verdict_bands` over the config's `[bounds]`; where it fails, the accepted steps of the search are gone
3565/// back one at a time, each judged in the bands, until one passes (2 n + 1 cycles each, n the bounds). With
3566/// `options.pareto`, every setting run that passes every verdict, and a sweep of slower ones from the result (its
3567/// acceleration and jerk, and all three limits, at 0.8, 0.6 and 0.4 times: six cycles more), give the front of cycle
3568/// time against energy and peak utilisation (`Optimised::front`).
3569///
3570/// Where the config has obstacles, a lift is lowered no further than its traverse keeps the clearance to them
3571/// (`over_obstacles`): a box under the traverse puts the lift at its top plus the clearance plus how far the machine's
3572/// lowest collision body reaches below the tool. A lift that an obstacle raises is tried rounded through a via point
3573/// over that obstacle as well, its ends at the clearance above pick and place; every via point's path is checked
3574/// against the obstacles before it runs.
3575///
3576/// With `options.worst` the accepted steps are judged at the worst corner from the fastest down (`fastest_passing`).
3577pub fn optimise_cycle_with(
3578    entry: &MachineEntry,
3579    cfg: &Config,
3580    options: &OptimiseOptions,
3581) -> Result<Optimised, ConfigError> {
3582    let max_runs = options.max_runs;
3583    let mut probe = Sim::new(entry, cfg)?;
3584    let clearance = cfg.non_negative("profile.min_clearance_m")?;
3585    // A conveyor's cycle picks from the belt (`[conveyor]`), and a path runs in place of the cycle (`[path]`):
3586    // `[[cycle.segment]]` does not run, so its lifts are left.
3587    let conveyor = probe.control.conveyor().is_some() || probe.path.is_some();
3588    let mut lifts = if conveyor { Vec::new() } else { lifts(cfg, clearance)? };
3589    // How far a path may leave the given one: the larger of the path and the corner tolerance as configured. With a
3590    // `[path]` the search tries both at it (transition curves and corners rounded within it, `path::geometry`).
3591    let corner_s = cfg.non_negative("profile.corner_tolerance_m")?;
3592    let allowed = if probe.path.is_some() { cfg.non_negative("profile.path_tolerance_m")?.max(corner_s) } else { 0.0 };
3593    let (cycle_s, tolerance) = (cfg.positive("profile.cycle_s")?, cfg.non_negative("profile.path_tolerance_m")?);
3594    let axis_infos = probe.machine.axes().to_vec();
3595    let obstacles = probe.obstacles.clone();
3596    if !obstacles.is_empty() {
3597        for lift in &mut lifts {
3598            let axis = &axis_infos[lift.from.len() - 1];
3599            (lift.needed, lift.over) = over_obstacles(probe.machine.as_mut(), &obstacles, lift, clearance, axis)
3600                .unwrap_or((lift.height, None));
3601            let planned = (axis_infos.as_slice(), cycle_s, tolerance);
3602            lift.profile = smoothed_profile(probe.machine.as_mut(), &obstacles, lift, clearance, planned)
3603                .map(|(points, by)| raised(&points, lift.up * by));
3604        }
3605    }
3606    let resonance = probe.machine.resonance_hz(probe.control.planned_pos());
3607    let configured = cfg.non_negative("profile.shaper2_frequency_hz")?;
3608    let second_frequency = second_shaper_frequency(probe.machine.as_ref(), probe.control.planned_pos(), cfg)?;
3609    // In the axis's own unit: `axis.x.max_velocity_m_s`, `axis.c.max_velocity_rad_s` (with metres alone, a machine with an
3610    // axis in rad could not be built and its cycle was said to fail a verdict).
3611    let limits = ["max_velocity_{unit}_s", "max_acceleration_{unit}_s2", "max_jerk_{unit}_s3"];
3612    // A candidate: the factor on each of the three limits, the switches, and per lift its height and via point.
3613    #[derive(Clone, PartialEq)]
3614    struct Setting {
3615        factors: [f64; 3],
3616        blending: bool,
3617        shaping: bool,
3618        follows: bool,
3619        second: bool,
3620        heights: Vec<f64>,
3621        vias: Vec<Option<Vec<Vec<f64>>>>,
3622        /// Per lift whose corners are rounded (its via points the two corners alone): the corner tolerance.
3623        corners: Vec<Option<f64>>,
3624        /// `profile.path_tolerance_m` and `corner_tolerance_m`.
3625        tolerances: [f64; 2],
3626    }
3627    let build = |setting: &Setting| -> Result<Config, ConfigError> {
3628        let mut changed = cfg.clone();
3629        let [path, corner] = setting.tolerances;
3630        changed.set_text(&format!("profile.path_tolerance_m = {path:?}"))?;
3631        changed.set_text(&format!("profile.corner_tolerance_m = {corner:?}"))?;
3632        for axis in &axis_infos {
3633            for (limit, factor) in limits.iter().zip(setting.factors) {
3634                let path = format!("axis.{}.{}", axis.id, limit.replace("{unit}", axis.unit));
3635                changed.set_text(&format!("{path} = {:?}", cfg.positive(&path)? * factor))?;
3636            }
3637        }
3638        changed.set_text(&format!("effects.corner_blending = {}", setting.blending))?;
3639        changed.set_text(&format!("effects.input_shaping = {}", setting.shaping))?;
3640        changed.set_text(&format!("effects.shaper_follows_pose = {}", setting.follows))?;
3641        changed.set_text(&format!(
3642            "profile.shaper2_frequency_hz = {:?}",
3643            if setting.second { second_frequency.unwrap_or(0.0) } else { 0.0 }
3644        ))?;
3645        if setting.heights.iter().zip(&lifts).any(|(h, lift)| *h != lift.height)
3646            || setting.vias.iter().any(Option::is_some)
3647        {
3648            changed
3649                .set("cycle.segment", cycle_with(cfg, &lifts, &setting.heights, &setting.vias, &setting.corners)?)?;
3650        }
3651        Ok(changed)
3652    };
3653    let runs = std::cell::Cell::new(0usize);
3654    // Every setting run that passed every verdict, for the front.
3655    let passed = std::cell::RefCell::new(Vec::<FrontPoint>::new());
3656    // The cycle of a setting, the checks it fails, and its point of the front where it fails none; if it runs. Touches
3657    // nothing shared, so that settings can run side by side.
3658    let evaluate = |setting: &Setting| -> Option<(CycleLoad, Vec<&'static str>, Option<FrontPoint>)> {
3659        let changed = build(setting).ok()?;
3660        let mut sim = Sim::new(entry, &changed).ok()?;
3661        let load = analyse_cycle_with(&mut sim, false).ok()?;
3662        let failed: Vec<&'static str> =
3663            verdicts(&changed, &load).ok()?.iter().filter(|v| !v.ok).map(|v| v.check).collect();
3664        let point = failed.is_empty().then(|| {
3665            let utilisation = load.motors.iter().fold(0.0, |a: f64, m| a.max(m.utilisation));
3666            let (factors, blending, shaping) = (setting.factors, setting.blending, setting.shaping);
3667            FrontPoint {
3668                duration: load.duration,
3669                energy: supply_energy(&changed, &load),
3670                utilisation,
3671                factors,
3672                blending,
3673                shaping,
3674            }
3675        });
3676        Some((load, failed, point))
3677    };
3678    // A setting's run counted, and its point put on the front.
3679    let count = |result: Option<(CycleLoad, Vec<&'static str>, Option<FrontPoint>)>| {
3680        runs.set(runs.get() + 1);
3681        let (load, failed, point) = result?;
3682        passed.borrow_mut().extend(point);
3683        Some((load, failed))
3684    };
3685    let judged = |setting: &Setting| -> Option<(CycleLoad, Vec<&'static str>)> { count(evaluate(setting)) };
3686    let start = Setting {
3687        factors: [1.0; 3],
3688        blending: cfg.bool("effects.corner_blending")?,
3689        shaping: cfg.bool("effects.input_shaping")?,
3690        follows: cfg.bool("effects.shaper_follows_pose")?,
3691        second: configured > 0.0,
3692        heights: lifts.iter().map(|lift| lift.height).collect(),
3693        vias: vec![None; lifts.len()],
3694        corners: vec![None; lifts.len()],
3695        tolerances: [tolerance, corner_s],
3696    };
3697    let before = match judged(&start) {
3698        Some((load, failed)) if failed.is_empty() => load,
3699        Some((_, failed)) => {
3700            return Err(ConfigError::Part("error-cycle-fails-already", failed.join(", ")));
3701        }
3702        // Said by what stops it: the config (its own error), or the cycle that does not run (its key).
3703        None => {
3704            let changed = build(&start)?;
3705            let why =
3706                |e: CommandError| ConfigError::Invalid(format!("the cycle as configured does not run: {}", e.key));
3707            verdicts(&changed, &analyse_cycle_with(&mut Sim::new(entry, &changed)?, false).map_err(why)?)?;
3708            return Err(ConfigError::Invalid("the cycle as configured cannot be judged".into()));
3709        }
3710    };
3711    // The setting with the lifts the obstacles raised (where it changed them) higher by `lack`, their via points with them.
3712    let raised_by = |setting: &Setting, lack: f64| {
3713        let mut higher = setting.clone();
3714        for (k, lift) in
3715            lifts.iter().enumerate().filter(|(k, lift)| lift.over.is_some() && setting.heights[*k] != lift.height)
3716        {
3717            higher.heights[k] += lift.up * lack;
3718            for z in higher.vias[k].iter_mut().flatten().filter_map(|point| point.last_mut()) {
3719                *z += lift.up * lack;
3720            }
3721        }
3722        higher
3723    };
3724    let (mut best, mut best_load) = (start.clone(), before.clone());
3725    // The settings the search took, one after the other, each faster than the one before: where the robust result steps
3726    // back to.
3727    let mut accepted = vec![(start.clone(), before.clone())];
3728    let mut improved = true;
3729    while improved {
3730        improved = false;
3731        // The lifts lower, all at once and each alone, to the clearance and halfway there.
3732        let mut candidates = Vec::new();
3733        let lower = |setting: &Setting, k: usize, height: f64| {
3734            let mut lower = setting.clone();
3735            lower.heights[k] = height;
3736            lower
3737        };
3738        if lifts.iter().zip(&best.heights).filter(|(lift, h)| **h != lift.needed).count() > 1 {
3739            candidates.push(Setting { heights: lifts.iter().map(|lift| lift.needed).collect(), ..best.clone() });
3740        }
3741        for (k, lift) in lifts.iter().enumerate().filter(|(k, lift)| best.heights[*k] != lift.needed) {
3742            candidates.push(lower(&best, k, lift.needed));
3743            candidates.push(lower(&best, k, 0.5 * (best.heights[k] + lift.needed)));
3744        }
3745        candidates.push(Setting { blending: !best.blending, ..best.clone() });
3746        // A path's corners rounded and its transition curves laid within the deviation the config allows.
3747        for k in (0..2).filter(|&k| best.tolerances[k] < allowed) {
3748            let mut tolerances = best.tolerances;
3749            tolerances[k] = allowed;
3750            candidates.push(Setting { tolerances, ..best.clone() });
3751        }
3752        if best.shaping {
3753            candidates.push(Setting { shaping: false, ..best.clone() });
3754        }
3755        if best.second {
3756            candidates.push(Setting { second: false, ..best.clone() });
3757        }
3758        for i in 0..3 {
3759            for step in [1.5, 1.2] {
3760                let mut faster = best.clone();
3761                faster.factors[i] *= step;
3762                candidates.push(faster);
3763            }
3764        }
3765        // Rounded lifts: a via point to start with, or one moved, or none again.
3766        for (k, lift) in lifts.iter().enumerate() {
3767            let z = lift.from.len() - 1;
3768            let width = (0..z).map(|i| (lift.to[i] - lift.from[i]).powi(2)).sum::<f64>().sqrt();
3769            let with_via = |via: Option<Vec<Vec<f64>>>| {
3770                let mut out = best.clone();
3771                (out.vias[k], out.corners[k]) = (via, None);
3772                out
3773            };
3774            match &best.vias[k] {
3775                None => {
3776                    // The lift's two corners rounded, so that the curve starts at `lowest` on the way up and ends there
3777                    // on the way down: for a right angle it starts 16 / 3 of the tolerance before the corner
3778                    // (`path::round_corners`), so the tolerance is 3 / 16 of the height above `lowest`.
3779                    let above = lift.up * (best.heights[k] - lift.lowest);
3780                    if above > 0.0 {
3781                        let mut rounded = with_via(Some(Vec::new()));
3782                        rounded.corners[k] = Some(3.0 * above / 16.0);
3783                        candidates.push(rounded);
3784                    }
3785                    for above in [0.5, 0.25, 0.125] {
3786                        let mut via: Vec<f64> = (0..z).map(|i| 0.5 * (lift.from[i] + lift.to[i])).collect();
3787                        via.push(best.heights[k] + lift.up * above * width);
3788                        candidates.push(with_via(Some(vec![via])));
3789                    }
3790                    // Over the obstacle that raised the lift, the ends as low as pick and place allow.
3791                    for above in [0.0, 0.125] {
3792                        if let Some(over) = &lift.over {
3793                            let via =
3794                                over[..z].iter().copied().chain([lift.needed + lift.up * above * width]).collect();
3795                            candidates.push(Setting {
3796                                heights: lower(&best, k, lift.lowest).heights,
3797                                ..with_via(Some(vec![via]))
3798                            });
3799                        }
3800                    }
3801                    // The height profile over the obstacles in the way, the ends as low as pick and place allow.
3802                    if let Some(points) = &lift.profile {
3803                        candidates.push(Setting {
3804                            heights: lower(&best, k, lift.lowest).heights,
3805                            ..with_via(Some(points.clone()))
3806                        });
3807                    }
3808                }
3809                // One via point is moved; a profile is kept or dropped.
3810                Some(points) => {
3811                    for via in points.iter().filter(|_| points.len() == 1) {
3812                        for step in [0.125, 1.0 / 32.0] {
3813                            for axis in 0..=z {
3814                                for sign in [-1.0, 1.0] {
3815                                    let mut moved = via.clone();
3816                                    moved[axis] += sign * step * width;
3817                                    candidates.push(with_via(Some(vec![moved])));
3818                                }
3819                            }
3820                        }
3821                    }
3822                    candidates.push(with_via(None));
3823                }
3824            }
3825        }
3826        // A via point whose path would come too near to pick and place, or to an obstacle, is not run.
3827        let machine = probe.machine.as_mut();
3828        candidates.retain(|c| {
3829            lifts.iter().enumerate().all(|(k, lift)| {
3830                c.vias[k].as_ref().is_none_or(|via| {
3831                    clears(
3832                        &axis_infos,
3833                        cycle_s,
3834                        tolerance,
3835                        lift,
3836                        (c.heights[k], c.corners[k]),
3837                        via,
3838                        (&mut *machine, &obstacles, clearance),
3839                    )
3840                })
3841            })
3842        });
3843        // A candidate's tries, at most `budget`, up to the first that is faster than `best` by more than 0.1 ms: its
3844        // own run, and where that only leaves the tool swinging its tries with the shaper right after it. They depend on
3845        // the candidate's own runs alone, so the candidates' tries can run side by side.
3846        let tries_of = |candidate: Setting, best: f64, budget: usize| {
3847            let mut done = Vec::new();
3848            let mut tries = std::collections::VecDeque::from([candidate]);
3849            let mut raised = 0;
3850            while let Some(setting) = tries.pop_front() {
3851                if done.len() >= budget {
3852                    break;
3853                }
3854                let result = evaluate(&setting);
3855                let Some((load, failed, _)) = &result else {
3856                    done.push((setting, result));
3857                    continue;
3858                };
3859                if failed.is_empty() && load.duration < best - 1e-4 {
3860                    done.push((setting, result));
3861                    break;
3862                }
3863                if !failed.is_empty() && failed.iter().all(|check| *check == "settling" || *check == "settling-angle") {
3864                    if !setting.shaping {
3865                        tries.push_back(Setting { shaping: true, follows: false, ..setting.clone() });
3866                        if resonance.is_some() {
3867                            tries.push_back(Setting { shaping: true, follows: true, ..setting.clone() });
3868                        }
3869                    } else if second_frequency.is_some() && !setting.second {
3870                        tries.push_back(Setting { second: true, ..setting.clone() });
3871                    }
3872                }
3873                // The lifts placed over the obstacles keep the clearance at rest; the run sways by some hundredths of a
3874                // millimetre (0.05 mm on the gantry). A setting that fails on that alone, by less than a millimetre, is
3875                // run again (twice at most) with those lifts higher by what the run lacked and 1 um.
3876                let lack = load.clearance.map_or(f64::INFINITY, |run| clearance - run + 1e-6);
3877                if *failed == ["collision"] && raised < 2 && lack < 1e-3 {
3878                    let higher = raised_by(&setting, lack);
3879                    if higher != setting {
3880                        raised += 1;
3881                        tries.push_back(higher);
3882                    }
3883                }
3884                done.push((setting, result));
3885            }
3886            done
3887        };
3888        // The candidates are taken in order, the first faster one accepted: a batch at a time, their tries then counted
3889        // in order as if they had run one after the other, those after the accepted one (or beyond `max_runs`)
3890        // dropped. The first candidate runs alone (it is often taken, and runs beside it would only slow it down), then
3891        // the batch doubles while candidates fail, up to one per processor. The result is the same with any batch.
3892        let (mut from, mut batch) = (0, 1);
3893        'candidates: while from < candidates.len() {
3894            let chunk = &candidates[from..(from + batch).min(candidates.len())];
3895            (from, batch) = (from + chunk.len(), (2 * batch).min(threads().max(1)));
3896            let budget = max_runs.saturating_sub(runs.get());
3897            let best_duration = best_load.duration;
3898            let tried = on_all_cores(chunk.len(), |i| tries_of(chunk[i].clone(), best_duration, budget));
3899            for (setting, result) in tried.into_iter().flatten() {
3900                if runs.get() >= max_runs {
3901                    break 'candidates;
3902                }
3903                let Some((load, failed)) = count(result) else { continue };
3904                if failed.is_empty() && load.duration < best_load.duration - 1e-4 {
3905                    accepted.push((setting.clone(), load.clone()));
3906                    (best, best_load, improved) = (setting, load, true);
3907                    break 'candidates;
3908                }
3909            }
3910        }
3911    }
3912    let mut robust = None;
3913    if options.robust && options.worst {
3914        let (mut corner_runs, last) = (0, accepted.len() - 1);
3915        // The checks a setting fails at the worst corner, the least clearance to the obstacles there, and its worst
3916        // corners. With `ignore`, the search stops at the first batch of runs that fails a check not in it.
3917        let mut at_worst = |setting: &Setting,
3918                            ignore: Option<&[&'static str]>,
3919                            from: &[Worst]|
3920         -> Result<(Vec<&'static str>, f64, Vec<Worst>), ConfigError> {
3921            let changed = build(setting)?;
3922            let stop = |v: &Verdict| ignore.is_some_and(|ignore| !v.ok && !ignore.contains(&v.check));
3923            let (worst, _, runs) = worst_search(entry, &changed, &bounds(&changed)?, from, &stop)?;
3924            corner_runs += runs;
3925            let least =
3926                worst.iter().find(|w| w.verdict.check == "collision").map_or(f64::INFINITY, |w| w.verdict.value);
3927            let mut out: Vec<&'static str> = worst.iter().filter(|w| !w.verdict.ok).map(|w| w.verdict.check).collect();
3928            out.sort();
3929            out.dedup();
3930            Ok((out, least, worst))
3931        };
3932        let (nominal_fails, _, mut from) = at_worst(&best, Some(&[]), &[])?;
3933        let excused = match (nominal_fails.is_empty(), last) {
3934            (true, _) => Vec::new(),
3935            (false, 0) => nominal_fails.clone(),
3936            (false, _) => at_worst(&accepted[0].0, None, &from)?.0,
3937        };
3938        let judged_on = |checks: &[&'static str]| -> Vec<&'static str> {
3939            checks.iter().copied().filter(|c| !excused.contains(c)).collect()
3940        };
3941        // Whether accepted step k passes what it is judged on at the worst corner, or with its lifts over the obstacles
3942        // higher by what the corner lacked (less than a millimetre); and its worst corners, where the next search starts.
3943        let mut pass = |k: usize, from: &[Worst]| -> Result<(Option<(Setting, CycleLoad)>, Vec<Worst>), ConfigError> {
3944            let (fails, least, worst) = at_worst(&accepted[k].0, Some(&excused), from)?;
3945            let failing = judged_on(&fails);
3946            if failing.is_empty() {
3947                return Ok((Some(accepted[k].clone()), worst));
3948            }
3949            if failing == ["collision"] && clearance - least < 1e-3 {
3950                let higher = raised_by(&accepted[k].0, clearance - least + 1e-6);
3951                if higher != accepted[k].0
3952                    && let Some((load, _)) = judged(&higher).filter(|(_, failed)| failed.is_empty())
3953                    && judged_on(&at_worst(&higher, Some(&excused), &worst)?.0).is_empty()
3954                {
3955                    return Ok((Some((higher, load)), worst));
3956                }
3957            }
3958            Ok((None, worst))
3959        };
3960        // The accepted steps from the fastest down, the first that passes what it is judged on taken (`fastest_passing`);
3961        // step 0 (the cycle as configured) passes by definition. Each search starts from the worst corners of the one
3962        // before. The fastest is not judged again where the nominal search already failed it on a check not excused.
3963        let (lo, result) = if nominal_fails.is_empty() {
3964            (last, (best.clone(), best_load.clone()))
3965        } else {
3966            let top =
3967                if matches!(judged_on(&nominal_fails)[..], [] | ["collision"]) { last } else { last.saturating_sub(1) };
3968            let found = fastest_passing(top, |k| {
3969                let (passed, worst) = pass(k, &from)?;
3970                from = worst;
3971                Ok(passed)
3972            })?;
3973            found.unwrap_or_else(|| (0, accepted[0].clone()))
3974        };
3975        let (nominal_duration, steps_back) = (best_load.duration, last - lo);
3976        (best, best_load) = result;
3977        robust = Some(Robust { nominal_duration, nominal_fails, excused, steps_back, runs: corner_runs, worst: true });
3978    } else if options.robust {
3979        let mut band_runs = 0;
3980        // The checks a setting fails in the bands, each once, and the least clearance to the obstacles there.
3981        let mut fails = |setting: &Setting| -> Result<(Vec<&'static str>, f64), ConfigError> {
3982            let changed = build(setting)?;
3983            let bounded = bounds(&changed)?;
3984            band_runs += 2 * bounded.len() + 1;
3985            let bands = verdict_bands(entry, &changed, &bounded)?;
3986            let least = bands.iter().find(|b| b.verdict.check == "collision").map_or(f64::INFINITY, |b| b.low);
3987            let mut out: Vec<&'static str> = bands.into_iter().filter(|b| !b.ok).map(|b| b.verdict.check).collect();
3988            out.sort();
3989            out.dedup();
3990            Ok((out, least))
3991        };
3992        let last = accepted.len() - 1;
3993        let (nominal_fails, mut least) = fails(&best)?;
3994        let excused = match (nominal_fails.is_empty(), last) {
3995            (true, _) => Vec::new(),
3996            (false, 0) => nominal_fails.clone(),
3997            (false, _) => fails(&accepted[0].0)?.0,
3998        };
3999        let judged_on = |checks: &[&'static str]| -> Vec<&'static str> {
4000            checks.iter().copied().filter(|c| !excused.contains(c)).collect()
4001        };
4002        // Pass or fail in the bands need not follow the cycle time, so the steps are judged from the fastest down, and
4003        // no further than the first that passes; the cycle as configured passes what it is judged on by definition.
4004        let (mut k, mut failing) = (last, judged_on(&nominal_fails));
4005        let result = loop {
4006            if failing.is_empty() {
4007                break accepted[k].clone();
4008            }
4009            // A step whose lifts over the obstacles the bounds sway nearer than the clearance, by less than a millimetre:
4010            // those lifts higher by that and 1 um, judged as written and in the bands.
4011            if failing == ["collision"] && clearance - least < 1e-3 {
4012                let higher = raised_by(&accepted[k].0, clearance - least + 1e-6);
4013                if higher != accepted[k].0
4014                    && let Some((load, _)) = judged(&higher).filter(|(_, failed)| failed.is_empty())
4015                    && judged_on(&fails(&higher)?.0).is_empty()
4016                {
4017                    break (higher, load);
4018                }
4019            }
4020            if k <= 1 {
4021                k = 0;
4022                break accepted[0].clone();
4023            }
4024            k -= 1;
4025            let (checks, at_k) = fails(&accepted[k].0)?;
4026            (failing, least) = (judged_on(&checks), at_k);
4027        };
4028        let (nominal_duration, steps_back) = (best_load.duration, last - k);
4029        (best, best_load) = result;
4030        robust = Some(Robust { nominal_duration, nominal_fails, excused, steps_back, runs: band_runs, worst: false });
4031    }
4032    let mut front = Vec::new();
4033    if options.pareto {
4034        let [v, a, j] = best.factors;
4035        let slower: Vec<Setting> = [0.8, 0.6, 0.4]
4036            .into_iter()
4037            .flat_map(|f| [[v, a * f, j * f], [v * f, a * f, j * f]])
4038            .map(|factors| Setting { factors, ..best.clone() })
4039            .collect();
4040        // Side by side, counted in their order.
4041        for result in on_all_cores(slower.len(), |i| evaluate(&slower[i])) {
4042            count(result);
4043        }
4044        front = non_dominated(&passed.borrow());
4045    }
4046    let (from, to) = (build(&start)?, build(&best)?);
4047    let mut changes: Vec<(String, String, String)> = to
4048        .leaves()
4049        .into_iter()
4050        .zip(from.leaves())
4051        .filter(|((_, after), (_, before))| after != before)
4052        .map(|((path, after), (_, before))| (path, before.to_string(), after.to_string()))
4053        .collect();
4054    let (old_cycle, new_cycle) = (from.get("cycle.segment")?, to.get("cycle.segment")?);
4055    if old_cycle != new_cycle {
4056        changes.push(("cycle.segment".into(), old_cycle.to_string(), new_cycle.to_string()));
4057    }
4058    let lifts = lifts
4059        .iter()
4060        .enumerate()
4061        .filter(|(k, lift)| best.heights[*k] != lift.height || best.vias[*k].is_some())
4062        .map(|(k, lift)| LiftChange {
4063            segments: lift.segments,
4064            before: lift.height,
4065            after: best.heights[k],
4066            via: best.vias[k].clone().filter(|_| best.corners[k].is_none()),
4067            corners: best.corners[k],
4068        })
4069        .collect();
4070    Ok(Optimised { before, after: best_load, changes, lifts, runs: runs.get(), robust, front })
4071}
4072
4073/// Keys of `[ratings]` that are a choice of how to judge, not uncertain data of the machine, with a range of their own
4074/// that 20 % either way leaves: the reliability of the life estimates (90 to 99.95 %, `verdicts` refuses 72 and 108).
4075const NOT_MACHINE_DATA: [&str; 1] = ["ratings.bearing_reliability_percent"];
4076
4077/// What one parameter does to the cycle when it is lower and when it is higher than in the config.
4078#[derive(Debug, Clone)]
4079pub struct Sensitivity {
4080    pub path: String,
4081    pub value: f64,
4082    /// The low and the high value the cycle was run with.
4083    pub bounds: (f64, f64),
4084    pub low: CycleLoad,
4085    pub high: CycleLoad,
4086}
4087
4088impl Sensitivity {
4089    /// Relative change of the peak torque and the RMS torque (each of the motor it changes most) and of the
4090    /// cycle time, at the low and at the high value: [peak low, peak high, RMS low, RMS high, time low, time high].
4091    pub fn changes(&self, nominal: &CycleLoad) -> [f64; 6] {
4092        let change = |a: f64, b: f64| if b.abs() > 1e-12 { a / b - 1.0 } else { 0.0 };
4093        let per_motor = |load: &CycleLoad, pick: fn(&MotorLoad) -> f64| -> f64 {
4094            load.motors
4095                .iter()
4096                .zip(&nominal.motors)
4097                .map(|(m, n)| change(pick(m), pick(n)))
4098                .fold(0.0, |a: f64, b| if b.abs() > a.abs() { b } else { a })
4099        };
4100        [
4101            per_motor(&self.low, |m| m.peak_torque),
4102            per_motor(&self.high, |m| m.peak_torque),
4103            per_motor(&self.low, |m| m.rms_torque),
4104            per_motor(&self.high, |m| m.rms_torque),
4105            change(self.low.duration, nominal.duration),
4106            change(self.high.duration, nominal.duration),
4107        ]
4108    }
4109
4110    /// The largest of these changes: how much the results depend on this parameter. Front ends rank by it.
4111    pub fn strength(&self, nominal: &CycleLoad) -> f64 {
4112        self.changes(nominal).iter().fold(0.0, |a: f64, b| a.max(b.abs()))
4113    }
4114}
4115
4116/// The cycle with the config as it is, and with each of `paths` at a low and at a high value, one at a
4117/// time: the bounds the config gives the parameter (see `bounds`), or the value scaled by 1 - delta and
4118/// by 1 + delta where it gives none. Shows which of the uncertain parameters the results depend on, and
4119/// so which are worth measuring. A parameter of value 0 without bounds (nothing to scale), one that is not a number, whose changed value the machine
4120/// refuses, or that only an effect that is off uses (see `bounds`), is left out, and so are the analysis' own choices
4121/// in `NOT_MACHINE_DATA`.
4122pub fn sensitivity(
4123    entry: &MachineEntry,
4124    cfg: &Config,
4125    paths: &[String],
4126    delta: f64,
4127) -> Result<(CycleLoad, Vec<Sensitivity>), ConfigError> {
4128    let cfg = &crate::catalog::resolve(entry, cfg)?;
4129    let configured = bounds(cfg)?;
4130    let run = |cfg: &Config| -> Option<CycleLoad> { analyse_cycle_with(&mut Sim::new(entry, cfg).ok()?, false).ok() };
4131    // (path, value, low, high) of each parameter that is varied; the runs are independent and share the processors.
4132    let varied: Vec<(&String, f64, (f64, f64))> = paths
4133        .iter()
4134        .filter(|path| !effect_off(cfg, path) && !NOT_MACHINE_DATA.contains(&path.as_str()))
4135        .filter_map(|path| {
4136            let value = cfg.f64(path).ok()?;
4137            let bound = configured.iter().find(|b| b.0 == *path).map(|b| (b.1, b.2));
4138            // A value of 0 scaled by 1 -+ delta stays 0: without a range of its own it is not varied (left out).
4139            if bound.is_none() && value == 0.0 {
4140                return None;
4141            }
4142            Some((path, value, bound.unwrap_or((value * (1.0 - delta), value * (1.0 + delta)))))
4143        })
4144        .collect();
4145    // Run 0 is the config as it is, then each parameter at its low and at its high value.
4146    let mut runs = on_all_cores(2 * varied.len() + 1, |k| {
4147        if k == 0 {
4148            return run(cfg);
4149        }
4150        let (path, _, bounds) = varied[(k - 1) / 2];
4151        let mut changed = cfg.clone();
4152        set_bounded(&mut changed, path, if k % 2 == 1 { bounds.0 } else { bounds.1 }).ok()?;
4153        run(&changed)
4154    })
4155    .into_iter();
4156    let nominal = runs.next().flatten().ok_or_else(|| ConfigError::Invalid("cycle".into()))?;
4157    let mut out = Vec::new();
4158    for (path, value, bounds) in varied {
4159        if let (Some(low), Some(high)) = (runs.next().flatten(), runs.next().flatten()) {
4160            out.push(Sensitivity { path: path.clone(), value, bounds, low, high });
4161        }
4162    }
4163    Ok((nominal, out))
4164}
4165
4166/// One point of the frequency response from a motor's torque to its own speed.
4167#[derive(Debug, Clone, Copy)]
4168pub struct SweepPoint {
4169    pub frequency: f64,
4170    /// Speed amplitude per torque amplitude, rad/s per N m.
4171    pub gain: f64,
4172    pub phase_deg: f64,
4173}
4174
4175/// How many frequencies a sweep has unless told otherwise. The first default machine's lowest dip is about
4176/// 2 Hz wide at 22 Hz; 120 points from 5 to 500 Hz put two points into it, 60 points one.
4177pub const SWEEP_POINTS: usize = 120;
4178
4179/// The torque amplitude of a sweep unless told otherwise: 1.5 N m, or 40 % of the drive's peak torque where
4180/// that is less. At 0.05 N m the stiction of the default machines holds the motors and there is no dip,
4181/// and up to 1 N m friction still pulls the dip of the second default machine low (70 Hz at 0.5 N m, 81 at
4182/// 1, 84 at 1.5); above 1.5 N m that machine shows a second, false dip (62 Hz at 2 N m) from its
4183/// nonlinearities.
4184/// The 40 % leave a small motor (0.56 N m peak) most of its torque to hold the axis with.
4185pub fn default_sweep_amplitude(entry: &MachineEntry, cfg: &Config) -> Result<f64, ConfigError> {
4186    let cfg = crate::catalog::resolve(entry, cfg)?;
4187    Ok((0.4 * cfg.positive("drive.peak_torque_nm")?).min(1.5))
4188}
4189
4190/// Mechanical frequency response without control: a sine torque on one motor on top of the holding
4191/// torques, measured at that motor's speed once the response has settled. Belt resonances show as
4192/// peaks, the load swinging against the held motor as a dip. Each frequency starts from the same rest, on a machine
4193/// of its own, so they share the processors.
4194pub fn frequency_sweep(
4195    entry: &MachineEntry,
4196    cfg: &Config,
4197    motor: usize,
4198    frequencies: &[f64],
4199    amplitude: f64,
4200) -> Result<Vec<SweepPoint>, ConfigError> {
4201    let cfg = &crate::catalog::resolve(entry, cfg)?;
4202    let (dt, substeps) = (cfg.positive("sim.dt_s")?, cfg.positive("sim.substeps")? as u32);
4203    // The machine at rest at its start pose under the holding torques.
4204    let at_rest = || -> Result<_, ConfigError> {
4205        let machine = (entry.build)(cfg)?;
4206        let motors = machine.motors().len();
4207        if motor >= motors {
4208            return Err(ConfigError::Invalid("motor".into()));
4209        }
4210        let (mut start, mut hold) = (Vec::new(), vec![0.0; motors]);
4211        machine.equilibrium(&crate::sim::start_pose(cfg, machine.as_ref())?, &mut start, &mut hold);
4212        Ok((machine, start, hold))
4213    };
4214    at_rest()?;
4215    check_frequencies(frequencies)?;
4216    on_all_cores(frequencies.len(), |i| {
4217        let (frequency, (machine, start, hold)) = (frequencies[i], at_rest()?);
4218        let motors = hold.len();
4219        let mut rk = Rk4::new(start.len());
4220        let (mut pos, mut speed) = (vec![0.0; motors], vec![0.0; motors]);
4221        let omega = std::f64::consts::TAU * frequency;
4222        // Whole periods: at least 0.3 s to settle, then at least 0.2 s to measure.
4223        let period = 1.0 / frequency;
4224        let settle = (0.3 / period).ceil().max(5.0) * period;
4225        let measure = (0.2 / period).ceil().max(5.0) * period;
4226        let (settle_steps, measure_steps) = ((settle / dt).round() as u64, (measure / dt).round() as u64);
4227        let (mut state, mut torque) = (start.clone(), hold.clone());
4228        let (mut in_phase, mut quadrature) = (0.0, 0.0);
4229        for step in 0..settle_steps + measure_steps {
4230            let t = (step as f64 + 0.5) * dt;
4231            torque[motor] = hold[motor] + amplitude * (omega * t).sin();
4232            advance(machine.as_ref(), &mut rk, &mut state, &torque, dt, substeps);
4233            if step >= settle_steps {
4234                machine.motor_state(&state, &mut pos, &mut speed);
4235                let t = (step + 1) as f64 * dt;
4236                in_phase += speed[motor] * (omega * t).sin();
4237                quadrature += speed[motor] * (omega * t).cos();
4238            }
4239        }
4240        let (a, b) = (2.0 * in_phase / measure_steps as f64, 2.0 * quadrature / measure_steps as f64);
4241        Ok(SweepPoint { frequency, gain: a.hypot(b) / amplitude, phase_deg: b.atan2(a).to_degrees() })
4242    })
4243    .into_iter()
4244    .collect()
4245}
4246
4247/// A response is measured over whole periods: at 0 Hz that never ends, and below it means nothing.
4248pub(crate) fn check_frequencies(frequencies: &[f64]) -> Result<(), ConfigError> {
4249    if frequencies.iter().all(|f| f.is_finite() && *f > 0.0) {
4250        Ok(())
4251    } else {
4252        Err(ConfigError::Invalid("frequency".into()))
4253    }
4254}
4255
4256/// The modes the machine reports (`Machine::modes`) at `points` places spread evenly over the range of axis `axis`, both
4257/// ends included, the other axes where `pose` has them: the resonances over a stroke, to choose shaper frequencies by
4258/// (`sim-cli modes`, the app's plot of them). Each place with its modes, which may be fewer at one place than at another.
4259pub fn modes_along(machine: &dyn Machine, pose: &[f64], axis: usize, points: usize) -> Vec<(f64, Vec<Mode>)> {
4260    let info = &machine.axes()[axis];
4261    (0..points)
4262        .map(|i| {
4263            let mut at = pose.to_vec();
4264            at[axis] = info.min + (info.max - info.min) * i as f64 / (points.max(2) - 1) as f64;
4265            (at[axis], machine.modes(&at))
4266        })
4267        .collect()
4268}
4269
4270/// The small-amplitude modes (`Machine::modes_small_amplitude`) at the places of `modes_along`'s `rows`, or `None` where
4271/// they are the large-amplitude ones everywhere (no gearbox hysteresis): the front ends' second column.
4272pub fn small_amplitude_along(
4273    machine: &dyn Machine,
4274    pose: &[f64],
4275    axis: usize,
4276    rows: &[(f64, Vec<Mode>)],
4277) -> Option<Vec<Vec<Mode>>> {
4278    let small: Vec<Vec<Mode>> = rows
4279        .iter()
4280        .map(|(position, _)| {
4281            let mut at = pose.to_vec();
4282            at[axis] = *position;
4283            machine.modes_small_amplitude(&at)
4284        })
4285        .collect();
4286    let same = |a: &[Mode], b: &[Mode]| a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.hz == b.hz);
4287    (!rows.iter().zip(&small).all(|((_, large), small)| same(large, small))).then_some(small)
4288}
4289
4290/// Frequencies spaced evenly on a logarithmic axis, both ends included.
4291pub fn log_spaced(from: f64, to: f64, points: usize) -> Vec<f64> {
4292    (0..points).map(|i| from * (to / from).powf(i as f64 / (points.max(2) - 1) as f64)).collect()
4293}
4294
4295// ---------------------------------------------------------------------------------------------
4296// Tuning: how the closed position loop answers a test signal on its setpoint.
4297
4298/// The answer of one axis to a small step of its position setpoint.
4299#[derive(Debug, Clone)]
4300pub struct StepResponse {
4301    pub size: f64,
4302    /// (time since the step, tool position relative to where it was), four times per millisecond.
4303    pub trace: Vec<(f64, f64)>,
4304    /// Time from 10 % to 90 % of the step.
4305    pub rise_time: f64,
4306    /// Highest excursion beyond the step, as a fraction of it.
4307    pub overshoot: f64,
4308    /// After this time the position stays within 2 % of the step.
4309    pub settling_time: f64,
4310}
4311
4312/// Tool position of one axis, after letting the machine come to rest at its start pose.
4313fn settled(entry: &MachineEntry, cfg: &Config, axis: usize) -> Result<(Sim, f64), ConfigError> {
4314    check_cancelled();
4315    let mut sim = Sim::new(entry, cfg)?;
4316    if axis >= sim.machine.axes().len() {
4317        return Err(ConfigError::Invalid("axis".into()));
4318    }
4319    sim.run(0.05, |_| {});
4320    let position = tool_position(&sim, axis);
4321    Ok((sim, position))
4322}
4323
4324fn tool_position(sim: &Sim, axis: usize) -> f64 {
4325    let n = sim.machine.axes().len();
4326    let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
4327    sim.machine.tool_state(&sim.state, &mut pos, &mut vel);
4328    pos[axis]
4329}
4330
4331/// Steps the position setpoint of one axis by `size` (without feedforward, so only the feedback
4332/// loops answer) and records the tool position. With friction on, a small step shows stiction too.
4333pub fn step_response(
4334    entry: &MachineEntry,
4335    cfg: &Config,
4336    axis: usize,
4337    size: f64,
4338    seconds: f64,
4339) -> Result<StepResponse, ConfigError> {
4340    let (mut sim, start) = settled(entry, cfg, axis)?;
4341    sim.control.setpoint_offset[axis] = size;
4342    let (t0, every) = (sim.time(), (0.25e-3 / sim.dt).round().max(1.0) as u64);
4343    let mut trace = vec![(0.0, 0.0)];
4344    sim.run(seconds, |s| {
4345        if s.step % every == 0 {
4346            trace.push((s.time() - t0, tool_position(s, axis) - start));
4347        }
4348    });
4349    let relative = |fraction: f64| trace.iter().find(|(_, y)| y / size >= fraction).map_or(f64::NAN, |(t, _)| *t);
4350    let overshoot = trace.iter().map(|(_, y)| y / size - 1.0).fold(0.0, f64::max);
4351    let settling_time = trace.iter().rev().find(|(_, y)| (y / size - 1.0).abs() > 0.02).map_or(0.0, |(t, _)| *t);
4352    Ok(StepResponse { size, rise_time: relative(0.9) - relative(0.1), overshoot, settling_time, trace })
4353}
4354
4355/// Closed-loop frequency response of the position loop of one axis: a sine on the position
4356/// setpoint, measured at the tool. Gain is tool amplitude over setpoint amplitude. Each frequency is measured on a
4357/// simulation of its own, so they share the processors.
4358pub fn closed_loop_response(
4359    entry: &MachineEntry,
4360    cfg: &Config,
4361    axis: usize,
4362    frequencies: &[f64],
4363    amplitude: f64,
4364) -> Result<Vec<SweepPoint>, ConfigError> {
4365    check_frequencies(frequencies)?;
4366    on_all_cores(frequencies.len(), |i| {
4367        let frequency = frequencies[i];
4368        let (mut sim, start) = settled(entry, cfg, axis)?;
4369        let (omega, t0, dt) = (std::f64::consts::TAU * frequency, sim.time(), sim.dt);
4370        // Whole periods: at least 0.3 s to settle, then at least 0.3 s to measure.
4371        let period = 1.0 / frequency;
4372        let whole = |seconds: f64| ((seconds / period).ceil().max(4.0) * period / dt).round() as u64;
4373        let (settle_steps, measure_steps) = (whole(0.3), whole(0.3));
4374        let (mut in_phase, mut quadrature) = (0.0, 0.0);
4375        for step in 0..settle_steps + measure_steps {
4376            sim.control.setpoint_offset[axis] = amplitude * (omega * (sim.time() - t0)).sin();
4377            sim.step();
4378            if step >= settle_steps {
4379                let (t, y) = (sim.time() - t0, tool_position(&sim, axis) - start);
4380                in_phase += y * (omega * t).sin();
4381                quadrature += y * (omega * t).cos();
4382            }
4383        }
4384        let (a, b) = (2.0 * in_phase / measure_steps as f64, 2.0 * quadrature / measure_steps as f64);
4385        Ok(SweepPoint { frequency, gain: a.hypot(b) / amplitude, phase_deg: b.atan2(a).to_degrees() })
4386    })
4387    .into_iter()
4388    .collect()
4389}
4390
4391/// The -3 dB bandwidth of a closed-loop response: where the gain first falls below 1 / sqrt(2),
4392/// interpolated between the measured points on the logarithmic frequency axis.
4393pub fn bandwidth(points: &[SweepPoint]) -> Option<f64> {
4394    let limit = std::f64::consts::FRAC_1_SQRT_2;
4395    let below = points.iter().position(|p| p.gain < limit)?;
4396    let (a, b) = (points.get(below.checked_sub(1)?)?, &points[below]);
4397    let share = (a.gain - limit) / (a.gain - b.gain);
4398    Some(a.frequency * (b.frequency / a.frequency).powf(share))
4399}
4400
4401/// One point of the open-loop response of a motor's velocity loop (`velocity_loop_response`): the loop gain L
4402/// as a complex number (real, imaginary part) and the sensitivity |S| = |1 / (1 + L)| as measured. L is NaN where the
4403/// point is not a measurement of the linear loop: the torque limit was hit, or the loop moved on its own.
4404#[derive(Debug, Clone, Copy, PartialEq)]
4405pub struct LoopPoint {
4406    pub frequency: f64,
4407    pub re: f64,
4408    pub im: f64,
4409    pub sensitivity: f64,
4410    /// The mechanics from the motor's air-gap torque to its speed in the same measurement, (real, imaginary part) in
4411    /// rad/s per N m: the plant the loop works on, without the current loop, filters and delays. NaN where L is.
4412    pub plant: [f64; 2],
4413}
4414
4415/// The open-loop response of the velocity loop of one motor, measured on the closed loop as a drive's own
4416/// measurement function does: a sine torque d is added to what the loop asks for (u), before the limit, with the
4417/// machine holding its start pose. The torque that reaches the motor is e = u + d, the loop answers u = -L e, so
4418/// L = -U / E and S = E / D at the frequency. Everything between the two is in L: velocity filter, PI, torque
4419/// filter, delays, current loop, the elastic mechanics, and the position loop around it. Sampled at the velocity
4420/// cycle, over whole periods: at least 0.1 s to settle and 0.1 s to measure.
4421///
4422/// Measured with `effects.gearbox_efficiency` off: at standstill the efficiency's fade with the transmitted power
4423/// (`Gearbox::loss_factor`) would act as a large damper on the small-signal torque and hide the loop (a crane hoist read
4424/// no gain crossover); the small-signal loop is that of the lossless gearbox. And with the motor encoders unrounded and
4425/// without noise (`Controller::unrounded_encoders`), their speed still the difference per cycle: above some 270 Hz the
4426/// test swing of a track of linear-motor movers is less than a count, and the rounding read its gain margin as 16.3 to
4427/// 32.9 dB, mover by mover as each stood in its count, where the loop has 16.96 to 17.29 dB (its force ripple's +-2 %).
4428pub fn velocity_loop_response(
4429    entry: &MachineEntry,
4430    cfg: &Config,
4431    motor: usize,
4432    frequencies: &[f64],
4433    amplitude: f64,
4434) -> Result<Vec<LoopPoint>, ConfigError> {
4435    check_frequencies(frequencies)?;
4436    let cfg = &lossless(cfg)?;
4437    frequencies.iter().map(|&frequency| loop_point(settled(entry, cfg, 0)?.0, motor, frequency, amplitude)).collect()
4438}
4439
4440/// The config a velocity loop is measured with (`velocity_loop_response`): effects.gearbox_efficiency off.
4441fn lossless(cfg: &Config) -> Result<Config, ConfigError> {
4442    let mut lossless = cfg.clone();
4443    if lossless.get("effects.gearbox_efficiency").is_ok() {
4444        lossless.set_text("effects.gearbox_efficiency = false")?;
4445    }
4446    Ok(lossless)
4447}
4448
4449/// One point of `velocity_loop_response`, measured on `sim` settled at its start pose.
4450fn loop_point(mut sim: Sim, motor: usize, frequency: f64, amplitude: f64) -> Result<LoopPoint, ConfigError> {
4451    if motor >= sim.control.drives.len() {
4452        return Err(ConfigError::Invalid("motor".into()));
4453    }
4454    // The settling below starts from the rounded encoder's state and runs out its count's step.
4455    sim.control.unrounded_encoders();
4456    let every = (sim.control.drive_params().velocity_cycle / sim.dt).round() as u64;
4457    let (omega, t0, period) = (std::f64::consts::TAU * frequency, sim.time(), 1.0 / frequency);
4458    let whole = |seconds: f64| ((seconds / period).ceil().max(5.0) * period / sim.dt).round() as u64;
4459    let (settle_steps, total) = (whole(0.1), whole(0.1) + whole(0.1));
4460    let (mut u_ab, mut e_ab, mut samples) = ([0.0; 2], [0.0; 2], 0.0);
4461    let (mut torque_ab, mut speed_ab) = ([0.0; 2], [0.0; 2]);
4462    let (mut seen, mut limited, mut pos, mut speed) =
4463        (Vec::new(), false, vec![0.0; sim.control.drives.len()], vec![0.0; sim.control.drives.len()]);
4464    for step in 0..total {
4465        let due = sim.step.is_multiple_of(every);
4466        let (s, c) = (omega * (sim.time() - t0)).sin_cos();
4467        if due {
4468            sim.control.drives[motor].torque_injection = amplitude * s;
4469        }
4470        sim.step();
4471        if due {
4472            // What reaches the motor clipped by the torque limit is no longer the linear loop being measured.
4473            sim.machine.motor_state(&sim.state, &mut pos, &mut speed);
4474            let (p, drive) = (sim.control.drive_params_of(motor), &sim.control.drives[motor]);
4475            let (low, high) = p.torque_range_at(speed[motor], drive.max_voltage(p));
4476            let e = drive.torque_demand + drive.torque_injection;
4477            limited |= !(low < e && e < high);
4478            if step >= settle_steps {
4479                let u = drive.torque_demand;
4480                (u_ab[0], u_ab[1], e_ab[0], e_ab[1]) =
4481                    (u_ab[0] + u * s, u_ab[1] + u * c, e_ab[0] + e * s, e_ab[1] + e * c);
4482                samples += 1.0;
4483                seen.push((s, c, e));
4484                let (t, v) = (drive.torque, speed[motor]);
4485                (torque_ab[0], torque_ab[1], speed_ab[0], speed_ab[1]) =
4486                    (torque_ab[0] + t * s, torque_ab[1] + t * c, speed_ab[0] + v * s, speed_ab[1] + v * c);
4487            }
4488        }
4489    }
4490    // Phasors (sine part, cosine part) of u and e; L = -U / E.
4491    let (u, e) =
4492        ([2.0 * u_ab[0] / samples, 2.0 * u_ab[1] / samples], [2.0 * e_ab[0] / samples, 2.0 * e_ab[1] / samples]);
4493    // What of e is not the sine of the injection and not a constant: a loop that moves on its own (unstable, or in a
4494    // limit cycle) shows here. More of it than the injection itself, and the point is not a measurement of L.
4495    let mean = seen.iter().map(|(_, _, x)| x).sum::<f64>() / samples;
4496    let rest = (seen.iter().map(|(s, c, x)| (x - mean - e[0] * s - e[1] * c).powi(2)).sum::<f64>() / samples).sqrt();
4497    let e2 = e[0] * e[0] + e[1] * e[1];
4498    let (re, im) = if limited || !(rest < amplitude) {
4499        (f64::NAN, f64::NAN)
4500    } else {
4501        (-(u[0] * e[0] + u[1] * e[1]) / e2, -(u[1] * e[0] - u[0] * e[1]) / e2)
4502    };
4503    // Plant = speed / torque, phasors as (sine, cosine) parts; NaN with L.
4504    let (t, v) = (torque_ab, speed_ab);
4505    let t2 = (t[0] * t[0] + t[1] * t[1]) * if re.is_nan() { f64::NAN } else { 1.0 };
4506    let plant = [(v[0] * t[0] + v[1] * t[1]) / t2, (v[1] * t[0] - v[0] * t[1]) / t2];
4507    Ok(LoopPoint { frequency, re, im, sensitivity: e2.sqrt() / amplitude, plant })
4508}
4509
4510/// What an open-loop response says about the stability of the loop.
4511#[derive(Debug, Clone, Copy, PartialEq)]
4512pub struct LoopMargins {
4513    /// The gain crossover (|L| = 1) with the smallest phase margin; NaN without one.
4514    pub crossover_hz: f64,
4515    /// The angle between L and -1 at that crossover (180 degrees plus the phase of L, the phase unwrapped along the
4516    /// frequency axis and taken between -270 and 90 degrees at the first point, by whole turns to between -180 and 180,
4517    /// either sign), the smallest over the crossovers; NaN without a crossover in the measured band (not measurable,
4518    /// not infinite: nothing is known beyond the band). Negative where L encircles -1 (`gain_margin_db` negative):
4519    /// the loop is unstable.
4520    pub phase_margin_deg: f64,
4521    /// By how much the gain may rise before L reaches -1, in dB, at the worst crossing of the negative real axis
4522    /// where the phase falls through -180 degrees and that a later rising crossing beyond -1 does not undo;
4523    /// infinite without one. Negative where |L| > 1 there: the loop encircles -1 and is unstable. A falling crossing
4524    /// beyond -1 that a rising one undoes (the integrators turn the phase past -180 degrees below the crossover and
4525    /// it comes back) is the conditionally stable kind: a gain that falls would be the danger there.
4526    pub gain_margin_db: f64,
4527    /// False when a point of the measurement was not valid (`LoopPoint` with NaN: the torque limit was hit or the
4528    /// loop moved on its own); the margins are then NaN, and a check fails.
4529    pub valid: bool,
4530    /// The highest sensitivity |S| measured, and where. 1 / |S| is the shortest distance of L from -1: |S| <= 2
4531    /// guarantees a gain margin of at least 6 dB and a phase margin of at least 29 degrees.
4532    pub peak_sensitivity: f64,
4533    pub peak_frequency_hz: f64,
4534    /// The loop hammers across its gearbox's play (`backlash_hammering`), which the response does not show; `None`
4535    /// from `loop_margins` alone, `velocity_loop_margins` runs the check.
4536    pub hammering: Option<Hammering>,
4537    /// With a gearbox's play in the loop: by how much the gain may rise before the loop hammers across it, in dB, the
4538    /// describing function's margin (`play_margin`). NaN without play acting on the loop and from `loop_margins` alone;
4539    /// negative: the loop crosses -1 at some amplitude of the swing across the play.
4540    pub play_margin_db: f64,
4541}
4542
4543impl LoopMargins {
4544    /// A valid measurement, both margins positive (a phase margin that is NaN has no crossover to judge), and no
4545    /// hammering across a play: stable. The margin across the play (`play_margin_db`) is told, not judged: the time run
4546    /// is the verdict.
4547    pub fn stable(&self) -> bool {
4548        self.valid && !(self.phase_margin_deg <= 0.0) && self.gain_margin_db > 0.0 && self.hammering.is_none()
4549    }
4550}
4551
4552/// Margins from an open-loop response, between neighbouring points interpolated linearly in log |L| and in the
4553/// unwrapped phase. Points too far apart (more than 180 degrees of phase between them) can miss a sharp resonance.
4554/// A point without a measurement (NaN) makes the margins not valid (and NaN).
4555pub fn loop_margins(points: &[LoopPoint]) -> LoopMargins {
4556    let measured = |p: &&LoopPoint| p.re.is_finite() && p.im.is_finite();
4557    let mut m = LoopMargins {
4558        crossover_hz: f64::NAN,
4559        phase_margin_deg: f64::NAN,
4560        gain_margin_db: f64::INFINITY,
4561        valid: points.iter().all(|p| measured(&p)),
4562        peak_sensitivity: 0.0,
4563        peak_frequency_hz: f64::NAN,
4564        hammering: None,
4565        play_margin_db: f64::NAN,
4566    };
4567    let points: Vec<&LoopPoint> = points.iter().filter(measured).collect();
4568    for p in &points {
4569        if p.sensitivity > m.peak_sensitivity {
4570            (m.peak_sensitivity, m.peak_frequency_hz) = (p.sensitivity, p.frequency);
4571        }
4572    }
4573    if !m.valid {
4574        (m.phase_margin_deg, m.gain_margin_db) = (f64::NAN, f64::NAN);
4575        return m;
4576    }
4577    // Phase in degrees, unwrapped along the frequency axis, then shifted by whole turns (below).
4578    let mut phase: Vec<f64> = Vec::with_capacity(points.len());
4579    for p in &points {
4580        let raw = p.im.atan2(p.re).to_degrees();
4581        phase.push(phase.last().map_or(raw, |last| raw + 360.0 * ((last - raw) / 360.0).round()));
4582    }
4583    let gain: Vec<f64> = points.iter().map(|p| p.re.hypot(p.im).ln()).collect();
4584    // Gain crossovers: (segment, share of the way along it).
4585    let crossovers: Vec<(usize, f64)> = (1..points.len())
4586        .filter(|&i| gain[i - 1].signum() != gain[i].signum())
4587        .map(|i| (i, gain[i - 1] / (gain[i - 1] - gain[i])))
4588        .collect();
4589    // The turn is fixed by the phase at the first point, taken in (-270, 90] (a loop with up to three integrators, or
4590    // a lead, there). Not at the first crossover: one rising out of an anti-resonance has a phase lead above 0 (the
4591    // arm 2 of a five-bar laid flat, +8 degrees at 18 Hz) and turned every phase after it by -360 degrees.
4592    let shift = phase.first().map_or(0.0, |p| -360.0 * ((p - 90.0) / 360.0).ceil());
4593    phase.iter_mut().for_each(|p| *p += shift);
4594    // At each crossover the angle between L and -1, whichever way round: a resonance that lifts |L| over 1 after the
4595    // phase has passed -180 degrees inside the unit circle crosses it again with L away from -1 on the other side (the
4596    // linear motor axis's coupling at its damping's low bound: |L| 1.53 at 1482 Hz, the crossings at -233.4 and -333.7
4597    // degrees, 53.4 degrees from -1 at the nearer one, read as 180 - 333.7 = -153.7). Whether L encircles -1 is the
4598    // count below; it gives the margin its sign.
4599    for &(i, share) in &crossovers {
4600        let turned = 180.0 + phase[i - 1] + (phase[i] - phase[i - 1]) * share;
4601        let margin = (turned - 360.0 * ((turned - 180.0) / 360.0).ceil()).abs();
4602        if !(margin >= m.phase_margin_deg) {
4603            (m.phase_margin_deg, m.crossover_hz) =
4604                (margin, points[i - 1].frequency * (points[i].frequency / points[i - 1].frequency).powf(share));
4605        }
4606    }
4607    // Crossings of the negative real axis (the phase through an odd multiple of -180 degrees), in frequency order,
4608    // from a phase of 0 at the gain of the first point: below the measured range each integrator has turned the
4609    // phase by -90 degrees from there (the small circle of the Nyquist contour around s = 0). Beyond -1 (|L| > 1) a
4610    // falling crossing is an encirclement of -1 and a later rising one beyond -1 undoes it (Nyquist: the loop is
4611    // stable when none is left). The gain margin is the worst falling crossing not undone: negative where |L| > 1.
4612    // A rising crossing beyond -1 with nothing to undo and the falling one beyond -1 that comes next, within 5 % of
4613    // its frequency (`PAIRED`), undo each other too: Nyquist's count is the net one (the servo loops' open loops are
4614    // stable), and the two are one wiggle of points that turned by half a turn from one to the next where |L| is far
4615    // over 1 (the arm's base turn in its gearbox's play at the upper bound rose at 14.28 Hz and fell at 14.32 Hz, at
4616    // |L| 65 and 35: -30.8 dB for a loop that runs quiet). Further apart, or with another crossing between them, the
4617    // fall counts (a rise left over is no encirclement).
4618    const PAIRED: f64 = 1.05;
4619    let (mut open, mut ahead, mut worst) = (Vec::new(), None::<f64>, f64::INFINITY);
4620    let samples: Vec<(f64, f64, f64)> = points
4621        .first()
4622        .map(|p| (p.frequency, 0.0, gain[0]))
4623        .into_iter()
4624        .chain(
4625            points
4626                .iter()
4627                .map(|p| p.frequency)
4628                .zip(phase.iter().copied().zip(gain.iter().copied()))
4629                .map(|(f, (p, g))| (f, p, g)),
4630        )
4631        .collect();
4632    for w in samples.windows(2) {
4633        let ((_, pa, ga), (fb, pb, gb)) = (w[0], w[1]);
4634        let at = |level: f64| ga + (gb - ga) * (pa - level) / (pa - pb);
4635        let mut level = -180.0 + 360.0 * ((pa + 180.0) / 360.0).floor();
4636        while pb < level && level <= pa {
4637            let g = at(level);
4638            if g <= 0.0 {
4639                worst = worst.min(-g);
4640            } else if !ahead.is_some_and(|rise| fb <= rise * PAIRED) {
4641                open.push(g);
4642            }
4643            ahead = None;
4644            level -= 360.0;
4645        }
4646        level += 360.0;
4647        while pa < level && level <= pb {
4648            ahead = (at(level) > 0.0 && open.pop().is_none()).then_some(fb);
4649            level += 360.0;
4650        }
4651    }
4652    m.gain_margin_db = open.iter().fold(worst, |w, g| w.min(-g)) * 20.0 / std::f64::consts::LN_10;
4653    if m.gain_margin_db < 0.0 {
4654        m.phase_margin_deg = -m.phase_margin_deg;
4655    }
4656    m
4657}
4658
4659/// The lowest frequency `velocity_loop_responses` follows a loop down to when its gain crossover lies below
4660/// `loop_frequencies` (a loop with less band than this is no servo loop to judge).
4661pub const LOOP_FLOOR_HZ: f64 = 1.0;
4662
4663/// Frequencies of the velocity-loop measurement of `velocity_loop_margins`: 10 Hz to
4664/// a quarter of the velocity loop's sampling rate (2 kHz at 125 us; above it a period has fewer than four samples), 60 points.
4665pub fn loop_frequencies(cfg: &Config) -> Result<Vec<f64>, ConfigError> {
4666    Ok(log_spaced(10.0, 0.25 / cfg.positive("drive.velocity_cycle_s")?, 60))
4667}
4668
4669/// The amplitude of the test torque: a tenth of the rated torque of the motor `id` (its own `[drive.<id>]`, not the
4670/// shared one).
4671pub fn loop_amplitude(entry: &MachineEntry, cfg: &Config, id: &str) -> Result<f64, ConfigError> {
4672    let own = crate::catalog::motor_config(&crate::catalog::resolve(entry, cfg)?, id)?;
4673    Ok(0.1 * own.positive("drive.rated_torque_nm")?)
4674}
4675
4676/// Where neighbouring points of a response differ by more than this turn (degrees) or this change of magnitude (dB),
4677/// a sharp resonance may lie between them: `refinement` measures their middle too. A first-order lag turns by at
4678/// most 5 degrees between two of the 60 points of `loop_frequencies` (9.4 % apart), the velocity loop's delays by
4679/// about 17 degrees at 2 kHz; a resonance with 1 % damping turns by 180 degrees within 2 % of its frequency.
4680pub const REFINE_TURN_DEG: f64 = 30.0;
4681pub const REFINE_GAIN_DB: f64 = 3.0;
4682/// Points closer than this ratio of frequencies are not split again (0.1 %, a twentieth of the half-power width of a
4683/// mode with 1 % damping).
4684pub const REFINE_CLOSEST: f64 = 1.001;
4685/// At most this many rounds of splitting: 9.4 % halved eight times is 0.04 %.
4686pub const REFINE_ROUNDS: usize = 8;
4687
4688/// The frequencies to measure next between neighbours of a response, `points` (frequency, complex value) in
4689/// frequency order: the geometric middle of each two that differ by more than `REFINE_TURN_DEG` or `REFINE_GAIN_DB`
4690/// and are further apart than `REFINE_CLOSEST`. Points with a value that is not a number are not split.
4691pub fn refinement(points: &[(f64, [f64; 2])]) -> Vec<f64> {
4692    points
4693        .windows(2)
4694        .filter_map(|w| {
4695            let ((fa, a), (fb, b)) = (w[0], w[1]);
4696            // The turn is the angle of b / a, the change of magnitude that of |b| / |a|.
4697            let turn = (a[0] * b[1] - a[1] * b[0]).atan2(a[0] * b[0] + a[1] * b[1]).to_degrees().abs();
4698            let change = 20.0 * (b[0].hypot(b[1]) / a[0].hypot(a[1])).log10().abs();
4699            ((turn > REFINE_TURN_DEG || change > REFINE_GAIN_DB) && fb / fa > REFINE_CLOSEST).then(|| (fa * fb).sqrt())
4700        })
4701        .collect()
4702}
4703
4704/// A long measurement's progress, read from another thread: measurements done, measurements planned so far (the
4705/// refinement adds to them), and a switch that stops it (`velocity_loop_responses` then answers `cancelled`).
4706#[derive(Debug, Default)]
4707pub struct Progress {
4708    pub done: std::sync::atomic::AtomicUsize,
4709    pub total: std::sync::atomic::AtomicUsize,
4710    pub cancel: std::sync::atomic::AtomicBool,
4711}
4712
4713/// The key of the error a cancelled measurement answers with (`ConfigError::Invalid`).
4714pub const CANCELLED: &str = "cancelled";
4715
4716/// Per config of `configs` (of the same machine) per motor the open-loop response of its velocity loop
4717/// (`velocity_loop_response`), in frequency order: at `loop_frequencies` and the machine's resonances (`Machine::modes`
4718/// of the first config) at the config's own start pose, below the band down to the gain crossover where it lies there (to
4719/// `LOOP_FLOOR_HZ`), and where the loop gain or the plant changes fast between two points at
4720/// their middle (`refinement`), in up to `REFINE_ROUNDS` rounds. Every point is measured on a simulation of its own:
4721/// they share the processors. `progress` counts them and can stop the measurement.
4722pub fn velocity_loop_responses(
4723    entry: &MachineEntry,
4724    configs: &[Config],
4725    progress: &Progress,
4726) -> Result<Vec<Vec<Vec<LoopPoint>>>, ConfigError> {
4727    use std::sync::atomic::Ordering::Relaxed;
4728    let first = &crate::catalog::resolve(entry, configs.first().ok_or_else(|| ConfigError::Invalid("config".into()))?)?;
4729    let frequencies = loop_frequencies(first)?;
4730    let spacing = frequencies[1] / frequencies[0];
4731    let machine = (entry.build)(first)?;
4732    let amplitudes =
4733        machine.motors().iter().map(|m| loop_amplitude(entry, first, m.id)).collect::<Result<Vec<_>, _>>()?;
4734    let range = frequencies[0]..=frequencies[frequencies.len() - 1];
4735    // Each config at its own start pose (`velocity_loop_margins` measures several poses): its modes there.
4736    let mut own: Vec<Vec<f64>> = Vec::with_capacity(configs.len());
4737    for cfg in configs {
4738        // A run without the payload (`margin_payloads`) has the modes of the machine without it.
4739        let modes = if cfg.bool("effects.payload").ok() == first.bool("effects.payload").ok() {
4740            machine.modes(&cfg.f64s("start.pose")?)
4741        } else {
4742            (entry.build)(&crate::catalog::resolve(entry, cfg)?)?.modes(&cfg.f64s("start.pose")?)
4743        };
4744        own.push(frequencies.iter().copied().chain(modes.iter().map(|m| m.hz).filter(|f| range.contains(f))).collect());
4745    }
4746    let motors = machine.motors().len();
4747    // Each run settled once, each point started from a copy of it (`Sim::snapshot`): the same start, bit for bit, as
4748    // settling it anew, without the settling's share of the sweep's time.
4749    let lossless = configs.iter().map(lossless).collect::<Result<Vec<_>, _>>()?;
4750    let starts = on_all_cores(configs.len(), |run| settled(entry, &lossless[run], 0).map(|(sim, _)| sim.snapshot()))
4751        .into_iter()
4752        .collect::<Result<Vec<_>, _>>()?;
4753    // Run inside a job whose progress this is, `on_all_cores` counts the points already: not twice. (Its cancel
4754    // unwind then ends the call as `Cancelled` instead of the `CANCELLED` error.)
4755    let counted = current_job().is_some_and(|job| std::ptr::eq(&*job, progress));
4756    let measure = |jobs: &[(usize, usize, f64)]| -> Result<Vec<LoopPoint>, ConfigError> {
4757        if !counted {
4758            progress.total.fetch_add(jobs.len(), Relaxed);
4759        }
4760        on_all_cores(jobs.len(), |j| {
4761            if progress.cancel.load(Relaxed) {
4762                return Err(ConfigError::Invalid(CANCELLED.into()));
4763            }
4764            let (run, motor, frequency) = jobs[j];
4765            check_frequencies(&[frequency])?;
4766            let mut sim = Sim::new(entry, &lossless[run])?;
4767            sim.restore(&starts[run])?;
4768            let point = loop_point(sim, motor, frequency, amplitudes[motor]);
4769            if !counted {
4770                progress.done.fetch_add(1, Relaxed);
4771            }
4772            point
4773        })
4774        .into_iter()
4775        .collect()
4776    };
4777    let mut curves = vec![vec![Vec::<LoopPoint>::new(); motors]; configs.len()];
4778    let mut jobs = Vec::new();
4779    for run in 0..configs.len() {
4780        for motor in 0..motors {
4781            jobs.extend(own[run].iter().map(|&f| (run, motor, f)));
4782        }
4783    }
4784    for round in 0..=REFINE_ROUNDS {
4785        for (&(run, motor, _), point) in jobs.iter().zip(measure(&jobs)?) {
4786            curves[run][motor].push(point);
4787        }
4788        // Below the band, once: where |L| < 1 at the lowest point the integrators put the gain crossover lower, and
4789        // the loop is followed down by the band's own spacing (its points stay where they were) until |L| > 1 or
4790        // `LOOP_FLOOR_HZ`. A loop with its crossover in the band is measured as before.
4791        if round == 0 {
4792            loop {
4793                jobs.clear();
4794                for (run, per_motor) in curves.iter().enumerate() {
4795                    for (motor, curve) in per_motor.iter().enumerate() {
4796                        let low = curve.iter().min_by(|a, b| a.frequency.total_cmp(&b.frequency)).unwrap();
4797                        if low.re.hypot(low.im) < 1.0 && low.frequency / spacing >= LOOP_FLOOR_HZ {
4798                            jobs.push((run, motor, low.frequency / spacing));
4799                        }
4800                    }
4801                }
4802                if jobs.is_empty() {
4803                    break;
4804                }
4805                for (&(run, motor, _), point) in jobs.iter().zip(measure(&jobs)?) {
4806                    curves[run][motor].push(point);
4807                }
4808            }
4809        }
4810        jobs.clear();
4811        for (run, per_motor) in curves.iter_mut().enumerate() {
4812            for (motor, curve) in per_motor.iter_mut().enumerate() {
4813                curve.sort_by(|a, b| a.frequency.total_cmp(&b.frequency));
4814                if round < REFINE_ROUNDS {
4815                    let of = |value: fn(&LoopPoint) -> [f64; 2]| {
4816                        refinement(&curve.iter().map(|p| (p.frequency, value(p))).collect::<Vec<_>>())
4817                    };
4818                    let mut more = of(|p| [p.re, p.im]);
4819                    more.extend(of(|p| p.plant));
4820                    more.sort_by(f64::total_cmp);
4821                    more.dedup();
4822                    jobs.extend(more.into_iter().map(|f| (run, motor, f)));
4823                }
4824            }
4825        }
4826        if jobs.is_empty() {
4827            break;
4828        }
4829    }
4830    Ok(curves)
4831}
4832
4833/// The poses the loops are judged at (`velocity_loop_margins`, `backlash_hammering`): the start pose first, then each
4834/// other pose the cycle stops at (the targets of `cycle.segment`), once each; a pose the cycle reaches with the payload
4835/// on and with it off is listed once for each (`margin_payloads`). The start pose alone without a cycle.
4836pub fn margin_poses(cfg: &Config) -> Result<Vec<Vec<f64>>, ConfigError> {
4837    Ok(margin_states(cfg)?.into_iter().map(|(pose, _)| pose).collect())
4838}
4839
4840/// Whether the payload is on at each pose of `margin_poses`: on at the start (the controller starts with it attached),
4841/// then as the segment that arrives there has it (`payload` is the gripper's state once the segment has arrived). All on
4842/// where the machine has no payload (`effects.payload` off), which changes nothing in it.
4843pub fn margin_payloads(cfg: &Config) -> Result<Vec<bool>, ConfigError> {
4844    Ok(margin_states(cfg)?.into_iter().map(|(_, payload)| payload).collect())
4845}
4846
4847fn margin_states(cfg: &Config) -> Result<Vec<(Vec<f64>, bool)>, ConfigError> {
4848    let mut states = vec![(cfg.f64s("start.pose")?, true)];
4849    let has_payload = cfg.bool("effects.payload").unwrap_or(false);
4850    let number = |v: &toml::Value| v.as_float().or_else(|| v.as_integer().map(|i| i as f64));
4851    for segment in cfg.array("cycle.segment").into_iter().flatten() {
4852        let target: Vec<f64> =
4853            segment.get("target").and_then(|t| t.as_array()).into_iter().flatten().filter_map(number).collect();
4854        let payload = !has_payload || segment.get("payload").and_then(|p| p.as_bool()).unwrap_or(true);
4855        let state = (target, payload);
4856        if state.0.len() == states[0].0.len() && !states.contains(&state) {
4857            states.push(state);
4858        }
4859    }
4860    Ok(states)
4861}
4862
4863/// `cfg` with the machine starting at `pose`, with the payload gone (`effects.payload` off: its mass is 0) where it is
4864/// not `payload`.
4865fn at_pose(cfg: &Config, pose: &[f64], payload: bool) -> Result<Config, ConfigError> {
4866    let mut at = cfg.clone();
4867    at.set_text(&format!("start.pose = {pose:?}"))?;
4868    if !payload {
4869        at.set_text("effects.payload = false")?;
4870    }
4871    Ok(at)
4872}
4873
4874/// The margins of every motor's velocity loop for the config as it is, at each pose of `margin_poses` (the start pose
4875/// first) in the payload state the cycle has there (`margin_payloads`), and with each value of `bounds` at its low and at
4876/// its high bound, one at a time (as `verdict_bands`), at the start pose: per run its name ("" for the config as it is,
4877/// "start.pose=[x y ...]" at another pose, with " effects.payload=false" where the payload is off there, "path=value"
4878/// otherwise) and the margins per motor, from the refined responses of `velocity_loop_responses`. A hammering's `pose`
4879/// is the run's.
4880pub fn velocity_loop_margins(
4881    entry: &MachineEntry,
4882    cfg: &Config,
4883    bounds: &[(String, f64, f64)],
4884) -> Result<Vec<(String, Vec<LoopMargins>)>, ConfigError> {
4885    let resolved = &crate::catalog::resolve(entry, cfg)?;
4886    let (bounds, cfg) = (&followed(cfg, resolved, bounds), resolved);
4887    let mut runs = vec![(String::new(), cfg.clone())];
4888    let (poses, payloads) = (margin_poses(cfg)?, margin_payloads(cfg)?);
4889    for (pose, &payload) in poses.iter().zip(&payloads).skip(1) {
4890        let text: Vec<String> = pose.iter().map(|x| format!("{x}")).collect();
4891        let off = if payload { "" } else { " effects.payload=false" };
4892        runs.push((format!("start.pose=[{}]{off}", text.join(" ")), at_pose(cfg, pose, payload)?));
4893    }
4894    for (path, low, high) in bounds {
4895        for value in [low, high] {
4896            let mut changed = cfg.clone();
4897            set_bounded(&mut changed, path, *value)?;
4898            runs.push((format!("{path}={value:?}"), changed));
4899        }
4900    }
4901    let mut configs: Vec<Config> = runs.iter().map(|(_, c)| c.clone()).collect();
4902    // With the play: each run once more with the flanks held together, for the margin across the play.
4903    let count = configs.len();
4904    let play = cfg.bool("effects.gearbox_backlash").unwrap_or(false);
4905    if play {
4906        for run in 0..count {
4907            let mut closed = configs[run].clone();
4908            closed.set_text("effects.gearbox_backlash = false")?;
4909            configs.push(closed);
4910        }
4911    }
4912    let responses = velocity_loop_responses(entry, &configs, &Progress::default())?;
4913    let motors = responses.first().map_or(0, Vec::len);
4914    let pose_of = |run: usize| if run < poses.len() { run } else { 0 };
4915    let hammering = on_all_cores(count * motors, |j| {
4916        let found = hammering_at(entry, &configs[j / motors], j % motors)?;
4917        Ok(found.map(|h| Hammering { pose: pose_of(j / motors), ..h }))
4918    })
4919    .into_iter()
4920    .collect::<Result<Vec<_>, ConfigError>>()?;
4921    Ok(runs
4922        .into_iter()
4923        .zip(&responses)
4924        .enumerate()
4925        .map(|(run, ((name, _), curves))| {
4926            let margins = curves.iter().enumerate().map(|(motor, points)| LoopMargins {
4927                hammering: hammering[run * motors + motor],
4928                play_margin_db: if play { play_margin(points, &responses[count + run][motor]) } else { f64::NAN },
4929                ..loop_margins(points)
4930            });
4931            (name, margins.collect())
4932        })
4933        .collect())
4934}
4935
4936/// The describing function's gain margin of a velocity loop across its gearbox's play, dB, from the loop measured with
4937/// the play (`play`: small signals, the rotor swinging inside it) and with the flanks held together (`closed`, the
4938/// config with `effects.gearbox_backlash` off). Two things in the loop depend on the swing's amplitude A. Across the
4939/// play the flanks pass their spring's and their damper's force only while in contact (`Gearbox::torque`): over a swing
4940/// about it the first harmonic of both is kappa(A) = 1 - (2 / pi) (asin(b / A) + (b / A) sqrt(1 - (b / A)^2)) of the
4941/// gear's impedance y (b the half play), 0 inside the play, 1 far beyond it. And the friction on the rotor (its seals,
4942/// the gearbox's drag, the mesh), which damps the small-signal measurement (Re(1/P) some 0.2 N m s/rad on the five-bar's
4943/// tool turn, three times its J w at 650 Hz), is a Coulomb force whose first harmonic, 4 F / (pi A w), fades as the
4944/// swing grows. The margin is taken with it faded: the rotor alone, J_m s (J_m the median of Im(1/P) / w over the upper
4945/// half of the play's band), on kappa y to the load J_L (J_m + J_L from the closed plant at its lowest frequency),
4946/// 1 / P(kappa) = J_m s + kappa y J_L s / (kappa y + J_L s), y at each frequency from the closed plant (which so holds
4947/// the friction's small-signal share, scaled with kappa), and the rest of the loop, C = L / P, from the closed
4948/// measurement. The least gain margin (`loop_margins`) of L(kappa) = C P(kappa) over kappa from 1e-3 to 1 (301 values,
4949/// log spaced), each on 3000 frequencies over the band (C's log gain and unwrapped phase and y interpolated in log f).
4950/// A swing that the friction still damps is quieter: the five-bar's tool turn reads -3.07 dB at 0.08 N m s/rad, so it
4951/// would hammer from 0.0562, where the time run (`backlash_hammering`, bisected) hammers from 0.0782 with its friction
4952/// and from 0.0478 with it off (the impacts' harmonics and the damper that cannot pull, which the first harmonic leaves
4953/// out). NaN where the play does not change the loop (none on that motor: the two measurements within 1e-3 at every
4954/// common frequency), where a measurement is not valid, or the inertias do not come out positive.
4955pub fn play_margin(play: &[LoopPoint], closed: &[LoopPoint]) -> f64 {
4956    type Cx = [f64; 2];
4957    let mul = |a: Cx, b: Cx| [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]];
4958    let div = |a: Cx, b: Cx| {
4959        let n = b[0] * b[0] + b[1] * b[1];
4960        [(a[0] * b[0] + a[1] * b[1]) / n, (a[1] * b[0] - a[0] * b[1]) / n]
4961    };
4962    let add = |a: Cx, b: Cx| [a[0] + b[0], a[1] + b[1]];
4963    let sub = |a: Cx, b: Cx| [a[0] - b[0], a[1] - b[1]];
4964    let valid = |p: &LoopPoint| [p.re, p.im, p.plant[0], p.plant[1]].iter().all(|x| x.is_finite());
4965    if play.len() < 2 || closed.len() < 2 || !play.iter().chain(closed).all(valid) {
4966        return f64::NAN;
4967    }
4968    let same = closed.iter().all(|c| {
4969        play.iter()
4970            .find(|p| p.frequency == c.frequency)
4971            .is_none_or(|p| (p.re - c.re).hypot(p.im - c.im) <= 1e-3 * c.re.hypot(c.im))
4972    });
4973    if same {
4974        return f64::NAN;
4975    }
4976    let tau = std::f64::consts::TAU;
4977    let s = |f: f64| [0.0, tau * f];
4978    // The impedance 1 / P = J s of an inertia: J = Im(1 / P) / w.
4979    let inertia = |p: &LoopPoint| div([1.0, 0.0], p.plant)[1] / (tau * p.frequency);
4980    let mut upper: Vec<f64> = play[play.len() / 2..].iter().map(inertia).collect();
4981    upper.sort_by(f64::total_cmp);
4982    let rotor = upper[upper.len() / 2];
4983    let load = inertia(closed.iter().min_by(|a, b| a.frequency.total_cmp(&b.frequency)).unwrap()) - rotor;
4984    if !(rotor > 0.0 && load > 0.0) {
4985        return f64::NAN;
4986    }
4987    // Per measured frequency: ln f, C's ln gain and unwrapped phase, and y.
4988    let mut rows: Vec<(f64, f64, f64, Cx)> = Vec::with_capacity(closed.len());
4989    for p in closed {
4990        let (sv, plant) = (s(p.frequency), p.plant);
4991        let c = div([p.re, p.im], plant);
4992        let ls = mul([load, 0.0], sv);
4993        let load_side = sub(div([1.0, 0.0], plant), mul([rotor, 0.0], sv));
4994        let y = div(mul(load_side, ls), sub(ls, load_side));
4995        let raw = c[1].atan2(c[0]);
4996        let phase = rows.last().map_or(raw, |r| raw + tau * ((r.2 - raw) / tau).round());
4997        rows.push((p.frequency.ln(), c[0].hypot(c[1]).ln(), phase, y));
4998    }
4999    let (low, high) = (rows[0].0, rows[rows.len() - 1].0);
5000    const FINE: usize = 3000;
5001    let fine: Vec<(f64, Cx, Cx)> = (0..FINE)
5002        .map(|i| {
5003            let x = low + (high - low) * i as f64 / (FINE - 1) as f64;
5004            let k = rows.partition_point(|r| r.0 <= x).clamp(1, rows.len() - 1);
5005            let (a, b) = (&rows[k - 1], &rows[k]);
5006            let t = if b.0 > a.0 { ((x - a.0) / (b.0 - a.0)).clamp(0.0, 1.0) } else { 0.0 };
5007            let (gain, phase) = ((a.1 + (b.1 - a.1) * t).exp(), a.2 + (b.2 - a.2) * t);
5008            (x.exp(), [gain * phase.cos(), gain * phase.sin()], add(a.3, mul([t, 0.0], sub(b.3, a.3))))
5009        })
5010        .collect();
5011    (0..=300)
5012        .map(|j| {
5013            let kappa = 10f64.powf(-3.0 + 3.0 * j as f64 / 300.0);
5014            let points: Vec<LoopPoint> = fine
5015                .iter()
5016                .map(|&(f, c, y)| {
5017                    let (sv, ky) = (s(f), mul([kappa, 0.0], y));
5018                    let ls = mul([load, 0.0], sv);
5019                    let impedance = add(mul([rotor, 0.0], sv), div(mul(ky, ls), add(ky, ls)));
5020                    let plant = div([1.0, 0.0], impedance);
5021                    let l = mul(c, plant);
5022                    LoopPoint { frequency: f, re: l[0], im: l[1], sensitivity: 1.0 / (1.0 + l[0]).hypot(l[1]), plant }
5023                })
5024                .collect();
5025            loop_margins(&points).gain_margin_db
5026        })
5027        .fold(f64::INFINITY, f64::min)
5028}
5029
5030/// A velocity loop that keeps oscillating on its own across a gearbox's play after a kick at rest
5031/// (`backlash_hammering`): the frequency, the peak of the torque the loop asks for about its mean (N m), and the pose
5032/// it hammers at, an index into `margin_poses` (0 the start pose).
5033#[derive(Debug, Clone, Copy, PartialEq)]
5034pub struct Hammering {
5035    pub frequency_hz: f64,
5036    pub torque_nm: f64,
5037    pub pose: usize,
5038}
5039
5040/// How long `backlash_hammering` sweeps, and the windows it watches the loop in afterwards.
5041pub const HAMMER_SWEEP_S: f64 = 0.2;
5042pub const HAMMER_WINDOW_S: f64 = 0.1;
5043
5044/// The torque one motor's loop asks for after a sweep at rest: a sine of `amplitude` (N m) added to it as the margin
5045/// measurement adds its own, its frequency rising logarithmically over `loop_frequencies`' band (10 Hz to a quarter of
5046/// the velocity loop's rate) in `HAMMER_SWEEP_S`, then taken off. Per window of `HAMMER_WINDOW_S` after it (three):
5047/// the RMS about the window's mean, the number of times the torque crosses that mean, and its peak about it.
5048fn after_a_sweep(sim: &mut Sim, motor: usize, amplitude: f64) -> [(f64, usize, f64); 3] {
5049    let every = (sim.control.drive_params().velocity_cycle / sim.dt).round() as u64;
5050    let (f0, f1) = (10.0, 0.25 / sim.control.drive_params().velocity_cycle);
5051    let (t0, k) = (sim.time(), (f1 / f0).ln());
5052    let mut windows: [Vec<f64>; 3] = Default::default();
5053    loop {
5054        let t = sim.time() - t0;
5055        let window = ((t - HAMMER_SWEEP_S) / HAMMER_WINDOW_S).floor();
5056        if window >= 3.0 {
5057            break;
5058        }
5059        let due = sim.step.is_multiple_of(every);
5060        if due {
5061            // A logarithmic sweep: the phase is the integral of f0 e^(k t / T).
5062            let phase = std::f64::consts::TAU * f0 * HAMMER_SWEEP_S / k * ((k * t / HAMMER_SWEEP_S).exp() - 1.0);
5063            sim.control.drives[motor].torque_injection = if t < HAMMER_SWEEP_S { amplitude * phase.sin() } else { 0.0 };
5064        }
5065        sim.step();
5066        if due && window >= 0.0 {
5067            windows[window as usize].push(sim.control.drives[motor].torque_demand);
5068        }
5069    }
5070    windows.map(|seen| {
5071        let mean = seen.iter().sum::<f64>() / seen.len() as f64;
5072        let rms = (seen.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / seen.len() as f64).sqrt();
5073        let crossings = seen.windows(2).filter(|w| (w[0] > mean) != (w[1] > mean)).count();
5074        (rms, crossings, seen.iter().map(|x| (x - mean).abs()).fold(0.0, f64::max))
5075    })
5076}
5077
5078/// Whether the velocity loop of `motor` hammers across its gearbox's play: a time run, as the small-signal measurement
5079/// (`velocity_loop_response`) cannot tell. Inside the play the measurement sees the rotor alone; a loop that is stable
5080/// there can still be unstable with the flanks in contact, and then the rotor swings from flank to flank in a limit
5081/// cycle (the describing function of the play rises from 0 with the rotor inside it to the flanks' stiffness with it far
5082/// beyond, so the loop crosses -1 at some amplitude). The motor's rated torque, swept over the band at rest
5083/// (`after_a_sweep`), takes the rotor across the play at each frequency in turn. The loop hammers where, 0.1 to 0.3 s
5084/// after the sweep, the torque it asks for still swings by more in RMS than the margin measurement's test torque
5085/// (`loop_amplitude`, beyond which `loop_point` says a loop moves on its own) and has not fallen to half from the
5086/// one window to the next, and where the same run with `effects.gearbox_backlash` off is quiet (otherwise the play is
5087/// not the cause). On the measurement's config (`lossless`), at each pose of `margin_poses`: where it hammers at
5088/// several, the one with the largest peak of the torque. `None` without the play.
5089pub fn backlash_hammering(entry: &MachineEntry, cfg: &Config, motor: usize) -> Result<Option<Hammering>, ConfigError> {
5090    let (poses, payloads) = (margin_poses(cfg)?, margin_payloads(cfg)?);
5091    let found = on_all_cores(poses.len(), |k| hammering_at(entry, &at_pose(cfg, &poses[k], payloads[k])?, motor));
5092    let mut worst: Option<Hammering> = None;
5093    for (pose, h) in found.into_iter().enumerate() {
5094        if let Some(h) = h?
5095            && worst.is_none_or(|w| h.torque_nm > w.torque_nm)
5096        {
5097            worst = Some(Hammering { pose, ..h });
5098        }
5099    }
5100    Ok(worst)
5101}
5102
5103/// `backlash_hammering` at the config's start pose alone.
5104fn hammering_at(entry: &MachineEntry, cfg: &Config, motor: usize) -> Result<Option<Hammering>, ConfigError> {
5105    if !cfg.bool("effects.gearbox_backlash").unwrap_or(false) {
5106        return Ok(None);
5107    }
5108    let cfg = lossless(&crate::catalog::resolve(entry, cfg)?)?;
5109    let run = |cfg: &Config| -> Result<_, ConfigError> {
5110        let (mut sim, _) = settled(entry, cfg, 0)?;
5111        let id = sim.machine.motors().get(motor).ok_or_else(|| ConfigError::Invalid("motor".into()))?.id;
5112        let rated = 10.0 * loop_amplitude(entry, cfg, id)?;
5113        let [_, early, late] = after_a_sweep(&mut sim, motor, rated);
5114        Ok((early.0 > 0.1 * rated && late.0 > 0.1 * rated && late.0 > 0.5 * early.0).then_some(late))
5115    };
5116    let Some((_, crossings, peak)) = run(&cfg)? else { return Ok(None) };
5117    let mut without = cfg;
5118    without.set_text("effects.gearbox_backlash = false")?;
5119    if run(&without)?.is_some() {
5120        return Ok(None);
5121    }
5122    Ok(Some(Hammering { frequency_hz: crossings as f64 / (2.0 * HAMMER_WINDOW_S), torque_nm: peak, pose: 0 }))
5123}
5124
5125/// The same cycle run twice, once with an effect on and once with it off (`compare_effect`), for overlaying the two.
5126#[derive(Debug, Clone)]
5127pub struct Comparison {
5128    pub signals: Vec<SignalInfo>,
5129    /// Every signal once per millisecond over the measured pass, the time counted from its start: with the effect on,
5130    /// and with it off.
5131    pub on: Vec<Vec<f64>>,
5132    pub off: Vec<Vec<f64>>,
5133}
5134
5135impl Comparison {
5136    /// Peak and RMS of (on - off) of one signal over the rows both runs have. Where one pass is longer (an effect
5137    /// that changes the timing, such as corner blending), the rest of it is not compared.
5138    pub fn difference(&self, signal: usize) -> (f64, f64) {
5139        let (mut peak, mut sum, mut n) = (0f64, 0.0, 0usize);
5140        for (a, b) in self.on.iter().zip(&self.off) {
5141            let d = a[signal] - b[signal];
5142            (peak, sum, n) = (peak.max(d.abs()), sum + d * d, n + 1);
5143        }
5144        (peak, if n > 0 { (sum / n as f64).sqrt() } else { 0.0 })
5145    }
5146}
5147
5148/// Runs the configured cycle and keeps every signal once per millisecond over its second pass, as `analyse_cycle`
5149/// measures it, with the time counted from the start of that pass.
5150pub fn record_cycle(entry: &MachineEntry, cfg: &Config) -> Result<Vec<Vec<f64>>, ConfigError> {
5151    let mut sim = Sim::new(entry, cfg)?;
5152    let refused = |e: CommandError| ConfigError::Invalid(e.key.into());
5153    sim.command(Command::StartCycle).map_err(refused)?;
5154    let every = ((1e-3 / sim.dt).round() as u64).max(1);
5155    let (mut passes, mut last, mut start, mut rows, mut sample) =
5156        (0, sim.control.cycle_passes(), None, Vec::new(), Vec::new());
5157    loop {
5158        sim.step();
5159        let now = sim.control.cycle_passes();
5160        if now != last {
5161            passes += 1;
5162            if passes == 2 {
5163                start = Some(sim.step);
5164            } else if passes == 3 {
5165                break;
5166            }
5167        }
5168        last = now;
5169        if sim.time() > 600.0 {
5170            return Err(refused(CommandError { key: "error-cycle-timeout" }));
5171        }
5172        if let Some(first) = start.filter(|first| (sim.step - first) % every == 0) {
5173            sim.sample(&mut sample);
5174            sample[0] = (sim.step - first) as f64 * sim.dt;
5175            rows.push(sample.clone());
5176        }
5177        // Tripped drives never finish the cycle.
5178        if !sim.control.enabled() {
5179            break;
5180        }
5181    }
5182    Ok(rows)
5183}
5184
5185/// The cycle of `on` against that of `off`: both run on simulations of their own; they are expected to be of the same
5186/// machine, with the same signals.
5187pub fn compare_configs(entry: &MachineEntry, on: &Config, off: &Config) -> Result<Comparison, ConfigError> {
5188    let signals = Sim::new(entry, on)?.signal_infos();
5189    let (with, without) = if std::thread::available_parallelism().is_err() {
5190        (record_cycle(entry, on), record_cycle(entry, off))
5191    } else {
5192        std::thread::scope(|scope| {
5193            let with = scope.spawn(|| record_cycle(entry, on));
5194            let without = record_cycle(entry, off);
5195            (with.join().expect("a run of the cycle panicked"), without)
5196        })
5197    };
5198    Ok(Comparison { signals, on: with?, off: without? })
5199}
5200
5201/// The cycle of `cfg` with `effects.<effect>` on and with it off, whatever the config has it at.
5202pub fn compare_effect(entry: &MachineEntry, cfg: &Config, effect: &str) -> Result<Comparison, ConfigError> {
5203    let path = format!("effects.{effect}");
5204    cfg.bool(&path)?;
5205    let (mut on, mut off) = (cfg.clone(), cfg.clone());
5206    on.set_text(&format!("{path} = true"))?;
5207    off.set_text(&format!("{path} = false"))?;
5208    compare_configs(entry, &on, &off)
5209}
5210
5211#[cfg(test)]
5212mod tests {
5213    use super::*;
5214    use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
5215
5216    fn job() -> std::sync::Arc<Progress> {
5217        std::sync::Arc::new(Progress::default())
5218    }
5219
5220    /// A job's batch is counted: N planned, N done, the results as without a job.
5221    #[test]
5222    fn a_job_counts_its_runs() {
5223        let progress = job();
5224        let out = with_progress(&progress, || on_all_cores(40, |i| i * 2));
5225        assert_eq!(out, Ok((0..40).map(|i| i * 2).collect::<Vec<_>>()));
5226        assert_eq!((progress.total.load(Relaxed), progress.done.load(Relaxed)), (40, 40));
5227    }
5228
5229    /// Without a job nothing is counted or cancelled, and the job context is gone after `with_progress`.
5230    #[test]
5231    fn without_a_job_runs_are_as_before() {
5232        assert_eq!(on_all_cores(10, |i| i + 1), (1..=10).collect::<Vec<_>>());
5233        check_cancelled();
5234        let progress = job();
5235        with_progress(&progress, || ()).unwrap();
5236        assert!(current_job().is_none());
5237        assert_eq!(on_all_cores(3, |i| i), vec![0, 1, 2]);
5238        assert_eq!(progress.total.load(Relaxed), 0);
5239    }
5240
5241    /// The run number 5 cancels: the job ends with `Cancelled`, and far fewer than all 1000 runs were started (each
5242    /// worker takes at most one more run after the flag is set, so not more than 6 plus the thread count).
5243    #[test]
5244    fn a_cancelled_job_stops_taking_runs() {
5245        let progress = job();
5246        let started = AtomicUsize::new(0);
5247        let out = with_progress(&progress, || {
5248            on_all_cores(1000, |i| {
5249                started.fetch_add(1, Relaxed);
5250                if i == 5 {
5251                    progress.cancel.store(true, Relaxed);
5252                }
5253                std::thread::sleep(std::time::Duration::from_millis(1));
5254            })
5255        });
5256        assert_eq!(out, Err(Cancelled));
5257        let started = started.load(Relaxed);
5258        assert!(started < 6 + threads() + 2, "{started} runs started");
5259        assert!(progress.done.load(Relaxed) <= started && progress.done.load(Relaxed) < 1000);
5260    }
5261
5262    /// A nested batch inside a run belongs to the job: its cancel ends the outer batch with `Cancelled`, too.
5263    #[test]
5264    fn a_nested_batch_is_cancelled_too() {
5265        let progress = job();
5266        let started = AtomicUsize::new(0);
5267        let out = with_progress(&progress, || {
5268            on_all_cores(4, |_| {
5269                on_all_cores(500, |i| {
5270                    started.fetch_add(1, Relaxed);
5271                    if i == 3 {
5272                        progress.cancel.store(true, Relaxed);
5273                    }
5274                    std::thread::sleep(std::time::Duration::from_millis(1));
5275                })
5276            })
5277        });
5278        assert_eq!(out, Err(Cancelled));
5279        assert!(started.load(Relaxed) < 4 * 500);
5280    }
5281
5282    /// A job cancelled before it starts runs nothing.
5283    #[test]
5284    fn a_job_cancelled_before_its_start_runs_nothing() {
5285        let progress = job();
5286        progress.cancel.store(true, Relaxed);
5287        let started = AtomicUsize::new(0);
5288        let out = with_progress(&progress, || {
5289            on_all_cores(50, |_| {
5290                started.fetch_add(1, Relaxed);
5291            })
5292        });
5293        assert_eq!((out, started.load(Relaxed)), (Err(Cancelled), 0));
5294    }
5295
5296    /// A real panic in the job stays a panic (not `Cancelled`), whether it is in a run or in the job itself, and the
5297    /// job context is restored.
5298    #[test]
5299    fn a_real_panic_stays_a_panic() {
5300        let progress = job();
5301        let in_job = std::panic::catch_unwind(|| with_progress(&progress, || -> u8 { panic!("model failed") }));
5302        assert!(in_job.is_err_and(|p| !p.is::<Cancelled>()));
5303        let in_run = std::panic::catch_unwind(|| {
5304            with_progress(&progress, || {
5305                on_all_cores(8, |i| {
5306                    if i == 2 {
5307                        panic!("run failed")
5308                    }
5309                })
5310            })
5311        });
5312        assert!(in_run.is_err_and(|p| !p.is::<Cancelled>()));
5313        assert!(current_job().is_none());
5314    }
5315
5316    /// `check_cancelled` raises inside a cancelled job and is silent in a job that is not, and outside any.
5317    #[test]
5318    fn check_cancelled_raises_only_in_a_cancelled_job() {
5319        check_cancelled();
5320        let progress = job();
5321        assert_eq!(with_progress(&progress, check_cancelled), Ok(()));
5322        progress.cancel.store(true, Relaxed);
5323        assert_eq!(with_progress(&progress, check_cancelled), Err(Cancelled));
5324        check_cancelled();
5325    }
5326
5327    /// Sequential work plans and counts its steps in the job.
5328    #[test]
5329    fn sequential_steps_are_counted_in_the_job() {
5330        let progress = job();
5331        with_progress(&progress, || {
5332            plan_steps(3);
5333            (0..3).for_each(|_| step_done());
5334        })
5335        .unwrap();
5336        assert_eq!((progress.total.load(Relaxed), progress.done.load(Relaxed)), (3, 3));
5337    }
5338
5339    /// A value or limit of NaN or infinity is named, whether the row passes or not; finite ones are not.
5340    #[test]
5341    fn a_verdict_that_is_not_finite_is_found() {
5342        let row = |value: f64, limit: f64| Verdict { check: "motor-thermal", motor: None, value, limit, ok: false };
5343        assert!(!any_not_finite(&[row(435.1, 1.0), row(0.0, 2.0)]));
5344        assert!(any_not_finite(&[row(1.0, 2.0), row(f64::INFINITY, 2.0)]));
5345        assert!(any_not_finite(&[row(f64::NAN, 2.0)]));
5346        assert!(any_not_finite(&[row(1.0, f64::NAN)]));
5347    }
5348
5349    /// By hand: a winding that settles at 102 K on every odd pass and 92 K on every even one (a pick alternating between
5350    /// two places) repeats every 2 passes; one at 100, 90, 80, 100, 90, 80 every 3; one that closes in on 95 K by halves
5351    /// (100, 97.5, 96.25, ...) and one that swings about it by halves (100, 92.5, 96.25, 94.375) have no period.
5352    #[test]
5353    fn the_warm_start_finds_the_period_of_a_cycle() {
5354        let rises = |r: &[f64]| r.iter().map(|&x| vec![x, 50.0]).collect::<Vec<_>>();
5355        assert_eq!(period_of(&rises(&[90.0, 102.3, 92.2, 101.9, 92.4])), Some(2));
5356        assert_eq!(period_of(&rises(&[60.0, 100.0, 90.0, 80.0, 100.0])), Some(3));
5357        assert_eq!(period_of(&rises(&[60.0, 105.0, 100.0, 97.5, 96.25])), None);
5358        assert_eq!(period_of(&rises(&[60.0, 110.0, 100.0, 92.5, 96.25])), None);
5359        // Too few warm passes to tell a period of 3 from the cold one's.
5360        assert_eq!(period_of(&rises(&[100.0, 90.0, 80.0, 100.0])), None);
5361    }
5362
5363    /// Steps 1 to 5 where 5, 4 and 2 fail and 3 and 1 pass: the fastest that passes is 3, after judging 5, 4 and 3 (a
5364    /// bisection from 0 and 5 would judge 2, fail, and end at step 1). None pass: `None`, all five judged.
5365    #[test]
5366    fn the_fastest_passing_step_is_found_where_pass_and_fail_do_not_follow_the_steps() {
5367        let mut judged = Vec::new();
5368        let passes = [true, true, false, true, false, false];
5369        let found = fastest_passing(5, |k| -> Result<_, ()> {
5370            judged.push(k);
5371            Ok(passes[k].then_some(k * 10))
5372        });
5373        assert_eq!((found, judged), (Ok(Some((3, 30))), vec![5, 4, 3]));
5374        let mut count = 0;
5375        assert_eq!(fastest_passing(5, |_| -> Result<Option<()>, ()> { Ok((count += 1, None).1) }), Ok(None));
5376        assert_eq!(count, 5);
5377    }
5378
5379    /// The line module's loss in the supply energy: efficiency eta = 0.9, the drive drew 100 J out of the DC link and fed
5380    /// 40 J into it, the bleeder took 2 J, so the module put 102 J in and took the 40 J out (mains 36 J arrive, through the
5381    /// module 142 J). The line gives 102 / 0.9 = 113.33 J and gets 36 J back, 77.33 J from the supply: the DC side's net
5382    /// 60 J, the bleeder's 2 J and the loss (1 / 0.9 - 1) 102 + (1 - 0.9) 40 = 15.33 J. Without the DC link simulated the
5383    /// net 60 J alone.
5384    #[test]
5385    fn the_supply_energy_has_the_line_modules_loss() {
5386        let cfg = Config::parse(
5387            "format_version = 1
5388[effects]
5389dc_link = true
5390regenerative_supply = true
5391[ratings]
5392line_module_efficiency = 0.9
5393",
5394        )
5395        .unwrap();
5396        let motor = MotorLoad {
5397            energy_in: 100.0,
5398            energy_regenerated: 40.0,
5399            mains_energy: 36.0,
5400            line_module_energy: 142.0,
5401            discharge_energy: 2.0,
5402            ..MotorLoad::default()
5403        };
5404        let load = CycleLoad { motors: vec![motor], ..CycleLoad::default() };
5405        assert!((supply_energy(&cfg, &load) - (102.0 / 0.9 - 36.0)).abs() < 1e-9, "{}", supply_energy(&cfg, &load));
5406        let off = Config::parse("format_version = 1\n[effects]\ndc_link = false\n").unwrap();
5407        assert!((supply_energy(&off, &load) - 60.0).abs() < 1e-12);
5408    }
5409
5410    /// The tool's error while it moves is judged only where the config asks a limit for it, in m and in rad each on
5411    /// its own: no row without the keys, and with them a row each that passes up to its limit.
5412    #[test]
5413    fn tracking_is_judged_where_a_limit_is_set() {
5414        let load = CycleLoad { tracking_error_peak: 2e-4, tracking_angle_error_peak: 3e-3, ..CycleLoad::default() };
5415        let base = "format_version = 1\n[effects]\ndc_link = false\npart_heating = false\nthermal_feedback = false\n";
5416        let checks = |text: &str| -> Vec<(&'static str, bool)> {
5417            let cfg = Config::parse(text).unwrap();
5418            verdicts(&cfg, &load)
5419                .unwrap()
5420                .into_iter()
5421                .filter(|v| v.check.starts_with("tracking"))
5422                .map(|v| (v.check, v.ok))
5423                .collect()
5424        };
5425        assert!(checks(base).is_empty());
5426        let set = format!("{base}[ratings]\ntracking_tolerance_m = 1e-4\ntracking_tolerance_rad = 5e-3\n");
5427        assert_eq!(checks(&set), [("tracking", false), ("tracking-angle", true)]);
5428    }
5429
5430    /// The refinement finds a sharp resonance that the 60 points of the loop measurement miss. Two masses on a spring,
5431    /// the motor's J1 = 1e-4 kg m², the load's J2 = 3e-4 kg m², k = 300 N m/rad, a damper c = 0.003 N m s/rad between
5432    /// them. The motor's speed per torque: P(s) = (J2 s² + c s + k) / (s (J1 J2 s² + c (J1 + J2) s + k (J1 + J2))).
5433    /// Anti-resonance sqrt(k / J2) = 1000 rad/s = 159.155 Hz; resonance sqrt(k (J1 + J2) / (J1 J2)) = sqrt(4e6) =
5434    /// 2000 rad/s = 318.310 Hz, damping ratio c (J1 + J2) / (J1 J2) / (2 * 2000) = 40 / 4000 = 0.01. At s = j2000 the
5435    /// numerator is -1200 + 300 + j6 = -900 + j6, the denominator j2000 (-0.12 + j0.0024 + 0.12) = -4.8: |P| = 900.02 /
5436    /// 4.8 = 187.50 rad/s per N m, 150 times the rigid 1 / ((J1 + J2) 2000) = 1.25. The 60 points from 10 to 2000 Hz
5437    /// lie 9.4 % apart, the nearest to the resonance at 303.5 and 331.9 Hz; the higher, the larger, has |P| = 44.7 by
5438    /// the same formula, a quarter of the peak.
5439    #[test]
5440    fn refinement_finds_a_sharp_resonance_the_coarse_sweep_misses() {
5441        let (j1, j2, k, c) = (1e-4, 3e-4, 300.0, 0.003);
5442        let plant = |f: f64| {
5443            let w = std::f64::consts::TAU * f;
5444            let (nr, ni) = (k - j2 * w * w, c * w);
5445            // j w (a + j b) = -w b + j w a
5446            let (a, b) = (k * (j1 + j2) - j1 * j2 * w * w, c * (j1 + j2) * w);
5447            let (dr, di) = (-w * b, w * a);
5448            let d2 = dr * dr + di * di;
5449            (f, [(nr * dr + ni * di) / d2, (ni * dr - nr * di) / d2])
5450        };
5451        let magnitude = |p: &(f64, [f64; 2])| p.1[0].hypot(p.1[1]);
5452        let peak =
5453            |points: &[(f64, [f64; 2])]| *points.iter().max_by(|a, b| magnitude(a).total_cmp(&magnitude(b))).unwrap();
5454        let close = |value: f64, expected: f64, share: f64, what: &str| {
5455            assert!((value / expected - 1.0).abs() < share, "{what}: {value} against {expected}")
5456        };
5457        close(magnitude(&plant(2000.0 / std::f64::consts::TAU)), 187.50, 1e-3, "|P| at the resonance");
5458        let mut points: Vec<_> = log_spaced(10.0, 2000.0, 60).into_iter().map(plant).collect();
5459        assert!(magnitude(&peak(&points)) < 0.25 * 187.5, "the coarse sweep sees the peak: {:?}", peak(&points));
5460        for _ in 0..REFINE_ROUNDS {
5461            let more = refinement(&points);
5462            points.extend(more.into_iter().map(plant));
5463            points.sort_by(|a, b| a.0.total_cmp(&b.0));
5464        }
5465        let top = peak(&points);
5466        close(top.0, 318.310, 2e-3, "resonance");
5467        close(magnitude(&top), 187.50, 0.03, "peak");
5468        let bottom = *points.iter().min_by(|a, b| magnitude(a).total_cmp(&magnitude(b))).unwrap();
5469        close(bottom.0, 159.155, 2e-3, "anti-resonance");
5470        // Only around the two: the rigid stretches (0.78 dB and no turn per step) are not split.
5471        assert!(points.len() < 60 + 80, "{} points", points.len());
5472        assert!(
5473            points.iter().filter(|p| p.0 < 100.0 || p.0 > 700.0).count()
5474                == log_spaced(10.0, 2000.0, 60).iter().filter(|f| **f < 100.0 || **f > 700.0).count()
5475        );
5476    }
5477
5478    /// A lift whose corners are rounded keeps to `lowest` where the tolerance is 3 / 16 of its height above it: from
5479    /// pick and place at 0 up to 0.3 m and across 0.4 m, `lowest` 0.25 m, the corners rounded within 3 * 0.05 / 16 =
5480    /// 9.375 mm start d = 16 / 3 of that = 0.05 m before each corner (`path::round_corners`, a right angle), at 0.25 m on
5481    /// the way up and down: the path stays at `lowest` or above. Half as much again starts 0.075 m before the corners, at
5482    /// 0.225 m, below `lowest`: refused.
5483    #[test]
5484    fn a_lift_with_rounded_corners_keeps_above_the_lowest_height() {
5485        let axis = |id| sim_core::AxisInfo {
5486            id,
5487            key: "",
5488            unit: "m",
5489            min: -1.0,
5490            max: 1.0,
5491            max_vel: 1.0,
5492            max_acc: 10.0,
5493            max_jerk: 200.0,
5494        };
5495        let axes = [axis("x"), axis("z")];
5496        let lift = Lift {
5497            segments: [0, 1, 2],
5498            from: vec![0.0, 0.0],
5499            to: vec![0.4, 0.0],
5500            height: 0.3,
5501            up: 1.0,
5502            lowest: 0.25,
5503            needed: 0.25,
5504            over: None,
5505            profile: None,
5506            payload: true,
5507        };
5508        let path = |corner: f64| lift_path(&axes, 1e-3, 0.0, &lift, (0.3, Some(corner)), &[]);
5509        let lowest = |points: &[(f64, Vec<f64>)]| {
5510            points.iter().filter(|(_, p)| p[0] > 1e-9 && p[0] < 0.4 - 1e-9).map(|(_, p)| p[1]).fold(1.0, f64::min)
5511        };
5512        let rounded = path(3.0 * 0.05 / 16.0).expect("keeps to lowest");
5513        assert!((lowest(&rounded) - 0.25).abs() < 1e-3, "{}", lowest(&rounded));
5514        assert!(path(1.5 * 3.0 * 0.05 / 16.0).is_none());
5515    }
5516
5517    /// The lives and the tooth load from given loads, by hand. Pulley bearing (ISO 281): C 8469 N, P 600 N, the motor at
5518    /// 500 r/min behind a ratio of 5, so the pulley at 100 r/min: (8469 / 600)^3 * 10^6 / (60 * 100) = 468696 h. Gearbox
5519    /// (Siemens): 20000 h * (175 / 100) * (40 N m / 20 N m)^(10/3) = 352778 h. Guide: (5000 / 1000)^3 * 50 km = 6250 km,
5520    /// at 0.25 m/s 6944.4 h. Belt teeth (Megadyne): 2 N m at a motor speed up to 50 rad/s, the pulley at up to
5521    /// 95.49 r/min, where the table allows 35 - 95.49 / 100 = 34.045 N/cm; 100 N * 1.4 / (34.045 * 2.5 cm * 12 teeth,
5522    /// 14 capped) = 0.13707. Beyond the table's end (1000 r/min) its last value holds: 1.6 N m at up to 1000 rad/s,
5523    /// 80 N * 1.4 / (26 * 30) = 0.14359, the highest of the bands.
5524    #[test]
5525    fn the_lives_and_the_tooth_load_are_the_hand_calculated_ones() {
5526        let cfg = Config::parse(
5527            "format_version = 1\n[gearbox]\nratio = 5.0\n[geometry]\npulley_radius_m = 0.02\n[ratings]\npulley_bearing_load_rating_n = 8469.0\ngearbox_rated_torque_nm = 40.0\n\
5528             gearbox_reference_speed_rpm = 175.0\nguide_dynamic_load_rating_n = 5000.0\nbelt_tooth_load_rpm = [0.0, 100.0, 1000.0]\n\
5529             belt_tooth_load_n_cm = [35.0, 34.0, 26.0]\nbelt_width_mm = 25.0\nbelt_service_factor = 1.4\nbelt_teeth_in_mesh = 14.0\nbearing_reliability_percent = 90.0\n",
5530        )
5531        .unwrap();
5532        let mut bands = vec![0.0; 200];
5533        bands[9] = 2.0;
5534        let m = MotorLoad {
5535            mean_speed: 500.0 * std::f64::consts::PI / 30.0,
5536            radial_load_equivalent: Some(600.0),
5537            gearbox_life_torque: Some(20.0),
5538            gearbox_torque: Some((2.0, 1.0)),
5539            gearbox_torque_by_speed: bands.clone(),
5540            ..MotorLoad::default()
5541        };
5542        let close = |a: f64, b: f64, what: &str| assert!((a / b - 1.0).abs() < 1e-5, "{what}: {a} against {b} by hand");
5543        close(rating_life_h(8469.0, 600.0, 100.0), 468696.16, "rating life");
5544        close(pulley_bearing_life_h(&cfg, &m).unwrap(), 468696.16, "pulley bearing");
5545        close(gearbox_life_h(&cfg, &m).unwrap(), 352777.89, "gearbox");
5546        close(belt_tooth_utilisation(&cfg, &m).unwrap().unwrap(), 0.137073, "tooth load");
5547        bands[199] = 1.6;
5548        close(
5549            belt_tooth_utilisation(&cfg, &MotorLoad { gearbox_torque_by_speed: bands, ..m.clone() }).unwrap().unwrap(),
5550            112.0 / 780.0,
5551            "tooth load beyond the table",
5552        );
5553        let load = CycleLoad {
5554            duration: 1.0,
5555            belt_tension: None,
5556            belt_slack_time: None,
5557            belt_tooth_jumps: None,
5558            belt_span_detuning: None,
5559            radial_load_peak: None,
5560            condition_peak: None,
5561            guide_load: Some((1500.0, 1000.0)),
5562            guide_speed: Some(0.25),
5563            guides: Vec::new(),
5564            path_error_peak: 0.0,
5565            path_error_rms: 0.0,
5566            tracking_error_peak: 0.0,
5567            dwell_error_peak: 0.0,
5568            path_angle_error_peak: 0.0,
5569            path_angle_error_rms: 0.0,
5570            tracking_angle_error_peak: 0.0,
5571            dwell_angle_error_peak: 0.0,
5572            path_error_series: Vec::new(),
5573            tripped: false,
5574            motors: vec![m.clone()],
5575            budget: None,
5576            part_rises: Vec::new(),
5577            checks: Vec::new(),
5578            clearance: None,
5579            contact: None,
5580            own_clearance: None,
5581            braking_power_peak: 0.0,
5582            warm_start: None,
5583            conveyor: None,
5584            held_accelerations: Vec::new(),
5585        };
5586        close(guide_life_km(&cfg, &load).unwrap(), 6250.0, "guide km");
5587        close(guide_life_h(&cfg, &load).unwrap(), 6944.444, "guide h");
5588        // Two guides, C = 5000 N: 2000 N at 0.1 m/s lives (5000/2000)^3 * 50 = 781.25 km = 2170.14 h; 1000 N at 3 m/s
5589        // lives 6250 km = 578.70 h. The km life is the first's, the hours the second's: each the lowest over the guides.
5590        let guide = |equivalent: f64, speed: f64| GuideLoad { peak: equivalent, equivalent, speed: Some(speed) };
5591        let two = CycleLoad { guides: vec![guide(2000.0, 0.1), guide(1000.0, 3.0)], ..load.clone() };
5592        close(guide_life_km(&cfg, &two).unwrap(), 781.25, "lowest guide km");
5593        close(guide_life_h(&cfg, &two).unwrap(), 578.704, "lowest guide h");
5594        // What a config or a machine lacks gives no figure: no output torque, no radial load, no rating.
5595        assert_eq!(belt_tooth_utilisation(&cfg, &MotorLoad { gearbox_torque: None, ..m.clone() }).unwrap(), None);
5596        assert_eq!(pulley_bearing_life_h(&cfg, &MotorLoad { radial_load_equivalent: None, ..m.clone() }), None);
5597        assert_eq!(
5598            gearbox_life_h(
5599                &Config::parse("format_version = 1\n[ratings]\ngearbox_rated_torque_nm = 40.0\n").unwrap(),
5600                &m
5601            ),
5602            None
5603        );
5604        // Life factor a1 (ISO 281), by hand: 0.95 * (ln(100/99) / ln(100/90))^(2/3) + 0.05 = 0.248332 at 99 %
5605        // (the table's 0.25); 0.637912 at 95 % (0.64); 0.076832 at 99.95 % (0.077). Both bearing lives scale with it.
5606        let mut reliable = cfg.clone();
5607        for (percent, a1) in [(95.0, 0.637912), (99.0, 0.248332), (99.95, 0.076832)] {
5608            reliable.set_text(&format!("ratings.bearing_reliability_percent = {percent:?}")).unwrap();
5609            close(reliability_factor(&reliable).unwrap(), a1, "a1");
5610            close(pulley_bearing_life_h(&reliable, &m).unwrap(), a1 * 468696.16, "pulley bearing with a1");
5611            close(gearbox_life_h(&reliable, &m).unwrap(), a1 * 352777.89, "gearbox with a1");
5612            close(guide_life_h(&reliable, &load).unwrap(), a1 * 6944.444, "guide with a1");
5613        }
5614        assert_eq!(reliability_factor(&cfg), Some(1.0));
5615        assert_eq!(reliability_factor(&Config::parse("format_version = 1\n").unwrap()), Some(1.0));
5616        // Outside 90 to 99.95 % the standard has no factor: no life (the verdicts refuse it, `sim-machines/tests/life.rs`).
5617        reliable.set_text("ratings.bearing_reliability_percent = 89.0").unwrap();
5618        assert_eq!(pulley_bearing_life_h(&reliable, &m), None);
5619        // A table out of order is refused.
5620        let mut bad = cfg.clone();
5621        bad.set_text("ratings.belt_tooth_load_rpm = [0.0, 1000.0, 100.0]").unwrap();
5622        assert!(belt_tooth_utilisation(&bad, &m).is_err());
5623        // A life is judged from below: 6944 h against 20000 h is 2.88 times too short, and the search's badness says so.
5624        let v = at_least("guide-life", None, 6944.444, 20000.0);
5625        assert!(!v.ok && (utilisation(&v) - 2.88).abs() < 0.001 && (badness(&v) - 13055.556).abs() < 0.001);
5626    }
5627
5628    /// A check judged from below at or below zero is infinitely far over: a belt section pushed (belt-least-tension with a
5629    /// tension of -12 N against 0.5 N) would otherwise have limit over value -0.0417, and the report a margin of
5630    /// +104.2 % beside "not ok". Above zero it stays limit over value: 0.5 / 2 = 0.25.
5631    #[test]
5632    fn an_at_least_check_at_or_below_zero_is_infinitely_far_over() {
5633        let pushed = Verdict { check: "belt-least-tension", motor: None, value: -12.0, limit: 0.5, ok: false };
5634        assert_eq!(utilisation(&pushed), f64::INFINITY);
5635        assert_eq!(utilisation(&Verdict { value: 0.0, ..pushed.clone() }), f64::INFINITY);
5636        assert_eq!(utilisation(&Verdict { value: 2.0, ok: true, ..pushed }), 0.25);
5637    }
5638
5639    /// a_ISO of ISO 281:2007 by hand from the standard's formulae (worked out separately in Python). Rated viscosity
5640    /// ν1 = 45000 * 100^-0.83 / sqrt(36) = 164.082 mm²/s at 100 r/min and D_pw 36 mm; 4500 / sqrt(1000) / sqrt(36) =
5641    /// 23.717 mm²/s at 1000 r/min. With e_C * C_u / P = 0.5 * 150 N / 600 N = 0.125, whose cube root is 0.5: at κ = 1,
5642    /// x = (2.5671 - 1.9987)^0.83 = 0.62568, a_ISO = 0.1 * (1 - 0.62568 * 0.5)^-9.3 = 3.27647; at κ = 0.2 (first
5643    /// branch) 0.198152, at 0.5 (second) 0.610291, at 2 (third) 6.03577, at 4 and above 11.0606; at κ 0.05, below the
5644    /// standard, as at 0.1: 0.100176; with e_C * C_u / P = 2 the bracket is below 0 and a_ISO is capped at 50. The
5645    /// pulley bearing of the life test with ν 120 mm²/s at 100 r/min: κ = 120 / 164.082 = 0.731341, a_ISO 1.555262,
5646    /// L_nm = 1.555262 * 468696.16 = 728945 h.
5647    #[test]
5648    fn a_iso_is_the_hand_calculated_one_of_iso_281() {
5649        let close = |a: f64, b: f64, what: &str| assert!((a / b - 1.0).abs() < 1e-5, "{what}: {a} against {b} by hand");
5650        close(reference_viscosity(100.0, 36.0), 164.082122, "ν1 below 1000 r/min");
5651        close(reference_viscosity(1000.0, 36.0), 23.717082, "ν1 from 1000 r/min");
5652        for (kappa, a_iso) in [
5653            (1.0, 3.276474),
5654            (0.2, 0.198152),
5655            (0.5, 0.610291),
5656            (2.0, 6.035768),
5657            (4.0, 11.060568),
5658            (8.0, 11.060568),
5659            (0.05, 0.100176),
5660        ] {
5661            close(life_modification_factor(kappa, 0.125), a_iso, &format!("a_ISO at κ {kappa}"));
5662        }
5663        // The three branches meet: the standard's curves are continuous.
5664        assert!(
5665            (life_modification_factor(0.4 - 1e-9, 0.125) / life_modification_factor(0.4, 0.125) - 1.0).abs() < 1e-3
5666        );
5667        assert!(
5668            (life_modification_factor(1.0 - 1e-9, 0.125) / life_modification_factor(1.0, 0.125) - 1.0).abs() < 1e-5
5669        );
5670        assert_eq!(life_modification_factor(4.0, 2.0), 50.0);
5671        let text = "format_version = 1\n[gearbox]\nratio = 5.0\n[ratings]\npulley_bearing_load_rating_n = 8469.0\nbearing_lubricant_viscosity_mm2_s = 120.0\n\
5672                    bearing_contamination_factor = 0.5\npulley_bearing_fatigue_limit_n = 150.0\npulley_bearing_mean_diameter_mm = 36.0\n";
5673        let cfg = Config::parse(text).unwrap();
5674        let m = MotorLoad {
5675            mean_speed: 500.0 * std::f64::consts::PI / 30.0,
5676            radial_load_equivalent: Some(600.0),
5677            ..MotorLoad::default()
5678        };
5679        close(pulley_bearing_life_h(&cfg, &m).unwrap(), 728945.29, "pulley bearing with a_ISO");
5680        // Some of the four values and not all, or e_C above 1, is refused by name; none of them is a_ISO = 1.
5681        let partial = Config::parse(&text.replace("pulley_bearing_mean_diameter_mm = 36.0\n", "")).unwrap();
5682        assert!(
5683            matches!(lubrication(&partial), Err(ConfigError::Missing(key)) if key == "ratings.pulley_bearing_mean_diameter_mm")
5684        );
5685        assert_eq!(pulley_bearing_life_h(&partial, &m), None);
5686        let mut dirty = cfg.clone();
5687        dirty.set_text("ratings.bearing_contamination_factor = 1.5").unwrap();
5688        assert!(
5689            matches!(lubrication(&dirty), Err(ConfigError::Invalid(key)) if key == "ratings.bearing_contamination_factor")
5690        );
5691        let bare = Config::parse(
5692            "format_version = 1\n[gearbox]\nratio = 5.0\n[ratings]\npulley_bearing_load_rating_n = 8469.0\n",
5693        )
5694        .unwrap();
5695        close(pulley_bearing_life_h(&bare, &m).unwrap(), 468696.16, "pulley bearing without a_ISO");
5696    }
5697
5698    /// Palmgren-Miner over a two-level spectrum above the rated torque, by hand: M2N 40 N m, M2max 64 N m for 30000
5699    /// revolutions, Wöhler exponent 6. 1000 rev/h at 48 N m, which allows 30000 * (64 / 48)^6 = 30000 * 5.6186557 =
5700    /// 168560 rev, and 100 rev/h at 60 N m, 30000 * (64 / 60)^6 = 30000 * 1.4728969 = 44187 rev; 5000 rev/h at 30 N m do no
5701    /// damage. Damage 1000 / 168560 + 100 / 44187 = 0.0059326 + 0.0022631 = 0.0081957 per hour, life 122.0147 h. Through
5702    /// a cycle's spectrum (ratio 5, so 1000 rev/h of the output are 1000 * 2 pi * 5 / 3600 = 8.72665 rad/s of the motor):
5703    /// 48 N m lies in band 620 (ln(480) / ln(1.01) = 620.5), judged at its upper torque 0.1 * 1.01^621 = 48.2584 N m,
5704    /// 60 N m in band 642 at 60.0680 N m, 30 N m in band 573 (30.23 N m, below M2N): damage
5705    /// 1000 / (30000 * 5.4405290) + 100 / (30000 * 1.4629173) = 0.0061269 + 0.0022786 per hour, life 118.971 h.
5706    #[test]
5707    fn the_gearing_life_is_the_hand_calculated_damage_sum() {
5708        let close = |a: f64, b: f64, what: &str| assert!((a / b - 1.0).abs() < 1e-6, "{what}: {a} against {b} by hand");
5709        close(
5710            gearing_life_h([(30.0, 5000.0), (48.0, 1000.0), (60.0, 100.0)], 40.0, 64.0, 6.0),
5711            122.014741,
5712            "two levels",
5713        );
5714        assert_eq!(gearing_life_h([(30.0, 5000.0), (40.0, 5000.0)], 40.0, 64.0, 6.0), f64::INFINITY);
5715        // At M2max the line gives Siemens' 30000 revolutions: 30000 rev/h last one hour.
5716        close(gearing_life_h([(64.0, 30000.0)], 40.0, 64.0, 6.0), 1.0, "at M2max");
5717        let text = "format_version = 1\n[gearbox]\nratio = 5.0\n[ratings]\ngearbox_rated_torque_nm = 40.0\ngearbox_max_torque_nm = 64.0\n\
5718                    gearbox_gearing_wohler_exponent = 6.0\n";
5719        let cfg = Config::parse(text).unwrap();
5720        let rad_s = |rev_h: f64| rev_h * std::f64::consts::TAU * 5.0 / 3600.0;
5721        let mut spectrum = vec![0.0; 700];
5722        (spectrum[573], spectrum[620], spectrum[642]) = (rad_s(5000.0), rad_s(1000.0), rad_s(100.0));
5723        let m =
5724            MotorLoad { gearbox_torque: Some((60.0, 40.0)), gearbox_torque_spectrum: spectrum, ..MotorLoad::default() };
5725        close(torque_band_floor(621), 48.258422, "band 620's upper torque");
5726        close(gearbox_gearing_life_h(&cfg, &m).unwrap(), 118.971035, "through the spectrum");
5727        // Never above M2N: no figure, as the life would be infinite.
5728        let below = MotorLoad { gearbox_torque_spectrum: m.gearbox_torque_spectrum[..600].to_vec(), ..m.clone() };
5729        assert_eq!(gearbox_gearing_life_h(&cfg, &below), None);
5730        // No output torque reported, or a key missing: no figure.
5731        assert_eq!(gearbox_gearing_life_h(&cfg, &MotorLoad { gearbox_torque: None, ..m.clone() }), None);
5732        let without = Config::parse(&text.replace("gearbox_gearing_wohler_exponent = 6.0\n", "")).unwrap();
5733        assert_eq!(gearbox_gearing_life_h(&without, &m), None);
5734    }
5735
5736    /// The motor's bearings, by hand from Siemens' figure for the 1FK2205: 1000 N at 1500 r/min for L10h = 25000 h is
5737    /// C = 1000 N * (25000 * 60 * 1500 / 10^6)^(1/3) = 1000 N * 2250^(1/3) = 13103.7 N. With the pulley on the shaft, 600 N
5738    /// at a mean 1000 r/min: 25000 h * (1000 / 600)^3 * (1500 / 1000) = 173611 h. Behind a gearbox there is no figure.
5739    #[test]
5740    fn the_motor_bearing_life_is_the_hand_calculated_one() {
5741        let cfg = Config::parse(
5742            "format_version = 1\n[gearbox]\nratio = 1.0\n[ratings]\nmotor_bearing_load_rating_n = 13103.7\n",
5743        )
5744        .unwrap();
5745        let m = MotorLoad {
5746            mean_speed: 1000.0 * std::f64::consts::PI / 30.0,
5747            radial_load_equivalent: Some(600.0),
5748            ..MotorLoad::default()
5749        };
5750        let life = motor_bearing_life_h(&cfg, &m).unwrap();
5751        assert!((life / 173611.11 - 1.0).abs() < 1e-5, "{life} against 173611 h by hand");
5752        let mut geared = cfg.clone();
5753        geared.set_text("gearbox.ratio = 5.0").unwrap();
5754        assert_eq!(motor_bearing_life_h(&geared, &m), None);
5755        assert_eq!(motor_bearing_life_h(&cfg, &MotorLoad { radial_load_equivalent: None, ..m }), None);
5756    }
5757
5758    /// Two motors of one machine with gearbox ratios 5 and 10 at 500 r/min: the pulleys turn at 100 and 50 r/min, so the
5759    /// pulley bearing (C 8469 N, P 600 N, L10 = (C/P)^3 * 1e6 / (60 n) h) lives 468696.16 h and twice that.
5760    #[test]
5761    fn each_motor_gets_its_own_gearbox_ratio() {
5762        let cfg = Config::parse(
5763            "format_version = 1\n[gearbox]\nratio = 5.0\n[gearbox.b]\nratio = 10.0\n[ratings]\npulley_bearing_load_rating_n = 8469.0\nbearing_reliability_percent = 90.0\n",
5764        )
5765        .unwrap();
5766        let motor = |id: &str| MotorLoad {
5767            id: id.into(),
5768            mean_speed: 500.0 * std::f64::consts::PI / 30.0,
5769            radial_load_equivalent: Some(600.0),
5770            ..MotorLoad::default()
5771        };
5772        assert!((output_rpm(&cfg, &motor("a")) - 100.0).abs() < 1e-9);
5773        assert!((output_rpm(&cfg, &motor("b")) - 50.0).abs() < 1e-9);
5774        let (a, b) =
5775            (pulley_bearing_life_h(&cfg, &motor("a")).unwrap(), pulley_bearing_life_h(&cfg, &motor("b")).unwrap());
5776        assert!((a / 468696.16 - 1.0).abs() < 1e-5 && (b / a - 2.0).abs() < 1e-9, "{a} and {b}");
5777    }
5778
5779    /// A guide at 100 N for 1 s at 1 m/s and at 200 N for 1 s at 3 m/s: the speed-weighted cubic mean is
5780    /// cbrt((100^3 * 1 + 200^3 * 3) / (1 + 3)) = cbrt(6.25e6) = 184.20 N (time-weighted: 165.1 N). A braking resistor, with the
5781    /// capacitors holding 2 J: of 5, 1.5 and 3 J fed back with 10 J drawn between each it takes (5 - 2) + 0 + (3 - 2) = 4 J.
5782    /// With 1 J drawn between, the link enters the 1.5 J and the 3 J 1 J full: the resistor takes 3 + 0.5 + 2 = 5.5 J and
5783    /// the link would have to hold 5 J. A cycle that ends on 1 J fed back and begins on 1.5 J
5784    /// enters its first braking 1 J full: 0.5 J spills (the link would hold 2.5 J).
5785    #[test]
5786    fn a_guide_load_is_weighted_with_distance_and_the_resistor_takes_what_the_link_cannot() {
5787        assert!((equivalent_load(100f64.powi(3) + 200f64.powi(3) * 3.0, 4.0) - 184.2).abs() < 0.01);
5788        assert_eq!(equivalent_load(0.0, 0.0), 0.0);
5789        let close = |(a, b): (f64, f64), (c, d): (f64, f64)| assert!((a - c).abs() < 1e-12 && (b - d).abs() < 1e-12);
5790        close(resistor_excess(&[5.0, -10.0, 1.5, -10.0, 3.0, -10.0], 2.0), (4.0, 5.0));
5791        close(resistor_excess(&[5.0, -1.0, 1.5, -1.0, 3.0, -10.0], 2.0), (5.5, 5.0));
5792        close(resistor_excess(&[1.5, -3.0, 1.0], 2.0), (0.5, 2.5));
5793        assert_eq!(resistor_excess(&[], 2.0), (0.0, 0.0));
5794    }
5795
5796    /// The running account (`LinkAccount`) gives the two passes over the whole list, and keeps only the stretches until
5797    /// the link first emptied or filled: here a braking, then 100000 sign changes of noise at rest that draw a little more
5798    /// than they feed back (as a held axis does), then two more brakings. A 0.5 J and a 2 J link fill on the 2.5 J braking
5799    /// (the third stretch), and keep those three.
5800    #[test]
5801    fn the_dc_link_account_matches_two_passes_over_the_list_and_stays_bounded() {
5802        let two_passes = |events: &[f64], room: f64| {
5803            let (mut fill, mut excess, mut most) = (0.0f64, 0.0, 0.0f64);
5804            for (i, &e) in events.iter().chain(events).enumerate() {
5805                fill = (fill + e).max(0.0);
5806                if i >= events.len() {
5807                    most = most.max(fill);
5808                    excess += (fill - room).max(0.0);
5809                }
5810                fill = fill.min(room);
5811            }
5812            (excess, most)
5813        };
5814        let mut events = vec![0.3, -0.05, 2.5, -0.2];
5815        events.extend((0..100_000).map(|i| if i % 2 == 0 { 1e-4 } else { -1.2e-4 }));
5816        events.extend([1.7, -0.4, 3.1, -5.0]);
5817        for room in [0.5, 2.0, 10.0] {
5818            let mut account = LinkAccount::new(room);
5819            events.iter().for_each(|&e| account.push(e));
5820            let ((a, b), (c, d)) = (account.finish(), two_passes(&events, room));
5821            assert!((a - c).abs() < 1e-9 && (b - d).abs() < 1e-12, "room {room}: {a} {b} against {c} {d}");
5822            // A link of 10 J never fills nor empties here: it keeps them all, as the two passes did.
5823            assert!(room > 2.0 || account.prefix.len() == 3, "room {room}: {} stretches kept", account.prefix.len());
5824        }
5825    }
5826
5827    /// A link of 10 J that neither empties nor fills over 400 000 stretches of noise (±1e-4 J, no net) keeps the passes
5828    /// over its voltage window, not the stretches, and gives the two passes' figures within half the grid's step
5829    /// (10 / 512 J). At both ends of the window: after a 0.3 J braking it sits near empty (by hand: nothing spilled, at
5830    /// most 0.6001 J held, the cycle entered 0.3 J full), after a 9.99 J one near full (entered 9.99 J full, the braking
5831    /// spills 9.98 J and the noise's first 1e-4 J: 9.9801 J, at most 19.98 J held). And once the passes meet after the grid
5832    /// was taken (a 12 J braking and 20 J drawn), the figures are the two passes' to rounding again (2.3 J, 12.3 J).
5833    #[test]
5834    fn a_dc_link_that_never_empties_nor_fills_keeps_a_bounded_account_at_both_ends() {
5835        let two_passes = |events: &[f64], room: f64| {
5836            let mut pass = [0.0, 0.0, 0.0];
5837            events.iter().for_each(|&e| link_step(&mut pass, e, room));
5838            pass[1..].fill(0.0);
5839            events.iter().for_each(|&e| link_step(&mut pass, e, room));
5840            (pass[1], pass[2])
5841        };
5842        let room = 10.0;
5843        let noise = (0..400_000).map(|i| if i % 2 == 0 { 1e-4 } else { -1e-4 });
5844        let cases = [
5845            (0.3, vec![], false, (0.0, 0.6001)),
5846            (9.99, vec![], false, (9.9801, 19.98)),
5847            (0.3, vec![12.0, -20.0], true, (2.3, 12.3)),
5848        ];
5849        for (start, end, meets, by_hand) in cases {
5850            let events: Vec<f64> = std::iter::once(start).chain(noise.clone()).chain(end).collect();
5851            let mut account = LinkAccount::new(room);
5852            events.iter().for_each(|&e| account.push(e));
5853            assert!(account.prefix.is_empty() && account.grid.len() == LINK_GRID && account.met == meets);
5854            let ((a, b), (c, d)) = (account.finish(), two_passes(&events, room));
5855            assert!((c - by_hand.0).abs() < 1e-9 && (d - by_hand.1).abs() < 1e-9, "{start}: {c} {d}");
5856            let tolerance = if meets { 1e-9 } else { room / (2.0 * (LINK_GRID - 1) as f64) };
5857            assert!((a - c).abs() <= tolerance && (b - d).abs() <= tolerance, "{start}: {a} {b} against {c} {d}");
5858        }
5859    }
5860
5861    /// Without a gain crossover in the band the phase margin is NaN (not measurable) and `stable` judges the gain margin
5862    /// alone; a valid measurement with a negative margin, or one not valid, is not stable, nor one that hammers across a
5863    /// gearbox's play whatever its margins.
5864    #[test]
5865    fn a_loop_without_a_gain_crossover_is_judged_on_its_gain_margin() {
5866        let m = |phase: f64, gain: f64, valid: bool| LoopMargins {
5867            crossover_hz: f64::NAN,
5868            phase_margin_deg: phase,
5869            gain_margin_db: gain,
5870            valid,
5871            peak_sensitivity: 1.0,
5872            peak_frequency_hz: 10.0,
5873            hammering: None,
5874            play_margin_db: f64::NAN,
5875        };
5876        assert!(m(f64::NAN, 20.0, true).stable());
5877        let hammering = Some(Hammering { frequency_hz: 645.0, torque_nm: 0.7, pose: 0 });
5878        assert!(!LoopMargins { hammering, ..m(40.0, 6.0, true) }.stable());
5879        assert!(!m(f64::NAN, -1.0, true).stable());
5880        assert!(!m(f64::NAN, f64::NAN, true).stable());
5881        assert!(!m(-5.0, 20.0, true).stable() && m(40.0, 6.0, true).stable() && !m(40.0, 6.0, false).stable());
5882    }
5883
5884    /// L(jw) = (wc / jw) e^(-jw tau), an integrator with a dead time, by hand: |L| = 1 at wc, where the phase is
5885    /// -90 degrees - wc tau, so the phase margin is 90 - 360 fc tau degrees (100 Hz, 1 ms: 54); the phase reaches
5886    /// -180 degrees at w = pi / (2 tau) (250 Hz), where |L| = fc / 250 Hz, a gain margin of 20 log 2.5 = 7.959 dB.
5887    #[test]
5888    fn margins_of_an_integrator_with_dead_time_are_the_hand_calculated_ones() {
5889        let (fc, tau) = (100.0, 1e-3);
5890        let points: Vec<LoopPoint> = log_spaced(10.0, 1000.0, 400)
5891            .into_iter()
5892            .map(|f| {
5893                let w = std::f64::consts::TAU * f;
5894                let (gain, phase) = (fc / f, -std::f64::consts::FRAC_PI_2 - w * tau);
5895                let (re, im) = (gain * phase.cos(), gain * phase.sin());
5896                LoopPoint { frequency: f, re, im, sensitivity: 1.0 / (1.0 + re).hypot(im), plant: [0.0; 2] }
5897            })
5898            .collect();
5899        let m = loop_margins(&points);
5900        assert!((m.crossover_hz - fc).abs() < 0.1, "crossover {} Hz", m.crossover_hz);
5901        assert!((m.phase_margin_deg - 54.0).abs() < 0.1, "phase margin {}", m.phase_margin_deg);
5902        assert!((m.gain_margin_db - 20.0 * 2.5f64.log10()).abs() < 0.01, "gain margin {}", m.gain_margin_db);
5903        // Without a crossover and without a crossing of the negative real axis, the gain margin is infinite and the
5904        // phase margin is not measurable (NaN), though the loop counts as stable.
5905        let m =
5906            loop_margins(&points[..10].iter().map(|p| LoopPoint { re: 2.0 + p.re.abs(), ..*p }).collect::<Vec<_>>());
5907        assert!(m.phase_margin_deg.is_nan() && m.gain_margin_db.is_infinite() && m.crossover_hz.is_nan() && m.stable());
5908    }
5909
5910    /// The same loop, stable and unstable: phase margin 90 - 360 fc tau degrees, gain margin 20 log(1 / (4 fc tau)) dB,
5911    /// both negative once the loop is unstable (|L| > 1 where the phase falls through -180 degrees). By hand:
5912    /// 100 Hz, 0.5 ms: 72 degrees, 13.979 dB; 200 Hz, 0.5 ms: 54 degrees, 7.959 dB; 300 Hz, 1 ms: -18 degrees,
5913    /// -1.584 dB; 400 Hz, 1 ms: -54 degrees, -4.082 dB. Points without a measurement (NaN) make the margins invalid.
5914    #[test]
5915    fn margins_are_signed_and_say_an_unstable_loop_is_unstable() {
5916        let response = |fc: f64, tau: f64| -> Vec<LoopPoint> {
5917            log_spaced(10.0, 2000.0, 1000)
5918                .into_iter()
5919                .map(|f| {
5920                    let (gain, phase) = (fc / f, -std::f64::consts::FRAC_PI_2 - std::f64::consts::TAU * f * tau);
5921                    let (re, im) = (gain * phase.cos(), gain * phase.sin());
5922                    LoopPoint { frequency: f, re, im, sensitivity: 1.0 / (1.0 + re).hypot(im), plant: [0.0; 2] }
5923                })
5924                .collect()
5925        };
5926        for (fc, tau, phase, gain) in [
5927            (100.0, 0.5e-3, 72.0, 13.979),
5928            (200.0, 0.5e-3, 54.0, 7.959),
5929            (300.0, 1e-3, -18.0, -1.584),
5930            (400.0, 1e-3, -54.0, -4.082),
5931        ] {
5932            let m = loop_margins(&response(fc, tau));
5933            assert!(
5934                (m.phase_margin_deg - phase).abs() < 0.1 && (m.gain_margin_db - gain).abs() < 0.01 && m.valid,
5935                "{fc} Hz, {tau} s: {m:?}"
5936            );
5937        }
5938        let mut points = response(100.0, 0.5e-3);
5939        points[500].re = f64::NAN;
5940        let m = loop_margins(&points);
5941        assert!(!m.valid && !m.stable() && m.phase_margin_deg.is_nan() && m.gain_margin_db.is_nan(), "{m:?}");
5942    }
5943
5944    /// Points of L(jw) from its gain and phase (radians) at w.
5945    fn loop_points(frequencies: Vec<f64>, l: impl Fn(f64) -> (f64, f64)) -> Vec<LoopPoint> {
5946        frequencies
5947            .into_iter()
5948            .map(|f| {
5949                let (gain, phase) = l(std::f64::consts::TAU * f);
5950                let (re, im) = (gain * phase.cos(), gain * phase.sin());
5951                LoopPoint { frequency: f, re, im, sensitivity: 1.0 / (1.0 + re).hypot(im), plant: [0.0; 2] }
5952            })
5953            .collect()
5954    }
5955
5956    /// L = K (1 + s/a)^2 / (s (1 + s/b)^2 (1 + s/c)), a = 2 pi 300, b = 2 pi 30, c = 2 pi 3000: the phase falls
5957    /// through -180 degrees between b and a with |L| > 1 and rises back through it before the crossover, so L
5958    /// does not encircle -1. The closed loops are stable (largest real parts of their poles -977, -1355, -1459 1/s,
5959    /// found from the characteristic polynomial); phase margins 30.7, 41.6, 42.4 degrees at 589, 1002, 1710 Hz,
5960    /// and no crossing above the crossover: an infinite gain margin.
5961    #[test]
5962    fn a_conditionally_stable_loop_is_stable() {
5963        let (a, b, c) = (std::f64::consts::TAU * 300.0, std::f64::consts::TAU * 30.0, std::f64::consts::TAU * 3000.0);
5964        for (k, phase, hz) in [(3e5, 30.7, 589.0), (6.1e5, 41.6, 1002.0), (1.2e6, 42.4, 1710.0)] {
5965            let m = loop_margins(&loop_points(log_spaced(10.0, 2000.0, 60), |w| {
5966                let gain = k * (1.0 + (w / a).powi(2)) / (w * (1.0 + (w / b).powi(2)) * (1.0 + (w / c).powi(2)).sqrt());
5967                (gain, 2.0 * (w / a).atan() - std::f64::consts::FRAC_PI_2 - 2.0 * (w / b).atan() - (w / c).atan())
5968            }));
5969            assert!(
5970                m.stable()
5971                    && m.gain_margin_db.is_infinite()
5972                    && (m.phase_margin_deg - phase).abs() < 0.3
5973                    && (m.crossover_hz / hz - 1.0).abs() < 0.01,
5974                "K {k}: {m:?}"
5975            );
5976        }
5977    }
5978
5979    /// A type-0 lead loop, L = 3 (1 + s/w5) / ((1 + s/w50) (1 + s/w200) (1 + s/w400)), wn = 2 pi n: the phase is
5980    /// positive at the first point. By hand at the crossover, 1516 Hz: 89.81 - 88.11 - 82.49 - 75.22 = -156.0
5981    /// degrees, a phase margin of 24.0 degrees; the phase tends to -180 degrees and never crosses it.
5982    #[test]
5983    fn a_lead_with_positive_phase_at_the_first_point_keeps_its_phase_margin() {
5984        let w = |n: f64| std::f64::consts::TAU * n;
5985        let m = loop_margins(&loop_points(log_spaced(1.0, 10000.0, 200), |x| {
5986            let lag = |n: f64| (1.0 + (x / w(n)).powi(2)).sqrt();
5987            (
5988                3.0 * lag(5.0) / (lag(50.0) * lag(200.0) * lag(400.0)),
5989                (x / w(5.0)).atan() - (x / w(50.0)).atan() - (x / w(200.0)).atan() - (x / w(400.0)).atan(),
5990            )
5991        }));
5992        assert!(
5993            m.stable()
5994                && m.gain_margin_db.is_infinite()
5995                && (m.phase_margin_deg - 24.0).abs() < 0.2
5996                && (m.crossover_hz / 1516.0 - 1.0).abs() < 0.01,
5997            "{m:?}"
5998        );
5999    }
6000
6001    /// A flat five-bar's arm 2 as measured: the main crossover just below the first point, then an anti-resonance
6002    /// (zeros at 14 Hz) and a resonance (poles at 40 Hz), both damped 0.05, and 1 ms of dead time: L = (2 pi 9.7 / s)
6003    /// (1 + 0.1 s/wz + s^2/wz^2) / (1 + 0.1 s/wp + s^2/wp^2) e^(-s 1 ms). Its first crossover, rising out of the
6004    /// notch at 22.5 Hz, has a phase of +71.4 degrees (a margin of 251.4); the one that counts, at 94.3 Hz, -121.9
6005    /// (by hand from the formula on a fine grid): 58.1 degrees, not 58.1 - 360 as the phase turned at that first one.
6006    #[test]
6007    fn a_crossover_with_phase_lead_before_the_one_that_counts_does_not_turn_the_phase() {
6008        let m = loop_margins(&loop_points(log_spaced(10.0, 2000.0, 60), |w| {
6009            let pair = |wn: f64| {
6010                let (re, im) = (1.0 - (w / wn).powi(2), 0.1 * w / wn);
6011                (re.hypot(im), im.atan2(re))
6012            };
6013            let ((zg, zp), (pg, pp)) = (pair(std::f64::consts::TAU * 14.0), pair(std::f64::consts::TAU * 40.0));
6014            (std::f64::consts::TAU * 9.7 / w * zg / pg, -std::f64::consts::FRAC_PI_2 + zp - pp - w * 1e-3)
6015        }));
6016        assert!((m.phase_margin_deg - 58.1).abs() < 0.5 && (m.crossover_hz / 94.3 - 1.0).abs() < 0.02, "{m:?}");
6017    }
6018
6019    /// Points of L from (frequency, |L|, phase in degrees).
6020    fn points_of(rows: &[(f64, f64, f64)]) -> Vec<LoopPoint> {
6021        rows.iter()
6022            .map(|&(f, gain, deg)| {
6023                let (re, im) = (gain * deg.to_radians().cos(), gain * deg.to_radians().sin());
6024                LoopPoint { frequency: f, re, im, sensitivity: 1.0 / (1.0 + re).hypot(im), plant: [0.0; 2] }
6025            })
6026            .collect()
6027    }
6028
6029    /// A loop of |L| = 100 Hz / f, phase -135 - 90 log10(f / 100 Hz) degrees (the crossover at 100 Hz with 45 degrees,
6030    /// through -180 degrees at 316 Hz with |L| 0.316, 10.0 dB), and a resonance at 1500 Hz that lifts |L| to 1.67 and
6031    /// turns the phase by -180 degrees over it: |L| over 1 between phases -260 and -400, never through -180 or -540
6032    /// degrees there, so L does not encircle -1 and the loop is stable with 45 degrees, its crossovers on the resonance
6033    /// 80 and 140 degrees from -1. Read as 180 plus the phase it was -220 degrees, unstable (the linear motor axis's
6034    /// coupling at its damping's low bound read -153.7 so).
6035    #[test]
6036    fn a_resonance_beyond_the_phase_crossing_inside_the_unit_circle_keeps_the_loop_stable() {
6037        let rows: Vec<(f64, f64, f64)> = log_spaced(10.0, 2000.0, 400)
6038            .into_iter()
6039            .map(|f| {
6040                let lift = 1.0 + 24.0 * (-((f - 1500.0) / 60.0).powi(2)).exp();
6041                let turn = -90.0 * (((f - 1500.0) / 40.0).tanh() + 1.0);
6042                (f, 100.0 / f * lift, -135.0 - 90.0 * (f / 100.0).log10() + turn)
6043            })
6044            .collect();
6045        let m = loop_margins(&points_of(&rows));
6046        assert!(
6047            m.stable() && (m.phase_margin_deg - 45.0).abs() < 0.1 && (m.crossover_hz / 100.0 - 1.0).abs() < 1e-3,
6048            "{m:?}"
6049        );
6050        assert!((m.gain_margin_db - 10.0).abs() < 0.05, "{m:?}");
6051    }
6052
6053    /// The Nyquist count is the net one: a rising crossing of the negative real axis beyond -1 that comes before the
6054    /// falling one it pairs with undoes it as well (no encirclement), as the base turn of the six-axis arm in its
6055    /// gearbox's play read it, the phase of points at |L| 30 to 65 turning by half a turn from one to the next (a rise
6056    /// at 14.28 Hz, a fall at 14.32 Hz). Here at |L| 30 the phase rises from 80 through 180 degrees and falls back, then
6057    /// comes down to the crossover at 100 Hz with 45 degrees and stays: stable, no crossing left, an infinite gain
6058    /// margin. Counted in their order the fall was an encirclement: -29.5 dB and unstable.
6059    #[test]
6060    fn a_rise_beyond_minus_one_before_its_fall_undoes_it() {
6061        let mut rows = vec![(10.0, 30.0, 80.0), (10.4, 30.0, 200.0), (10.6, 30.0, 150.0), (11.5, 30.0, 80.0)];
6062        rows.extend([(12.0, 30.0, 0.0), (12.5, 30.0, -90.0)]);
6063        rows.extend(log_spaced(13.0, 2000.0, 100).into_iter().map(|f| (f, 100.0 / f, -135.0)));
6064        let m = loop_margins(&points_of(&rows));
6065        assert!(m.stable() && m.gain_margin_db.is_infinite() && (m.phase_margin_deg - 45.0).abs() < 0.1, "{m:?}");
6066    }
6067
6068    /// The pairing is of neighbours only: a rise beyond -1 at 10 Hz (the phase from 80 to 200 degrees at |L| 30, held
6069    /// there) does not undo a fall beyond -1 at 300 Hz (from 200 to 150 degrees at |L| 2, held to the crossover at
6070    /// 1000 Hz): that one encircles -1, the loop is unstable, -6.02 dB, the crossover 30 degrees past -1.
6071    #[test]
6072    fn a_rise_beyond_minus_one_does_not_undo_a_fall_far_above_it() {
6073        let mut rows = vec![(10.0, 30.0, 80.0), (10.4, 30.0, 200.0)];
6074        rows.extend(log_spaced(11.0, 3000.0, 200).into_iter().map(|f| {
6075            // |L| 2 up to 300 Hz, then falling to 1 at 1000 Hz.
6076            let gain = 2.0 * (300.0 / f.max(300.0)).powf(0.5f64.ln() / 0.3f64.ln());
6077            (f, gain, if f < 300.0 { 200.0 } else { 150.0 })
6078        }));
6079        let m = loop_margins(&points_of(&rows));
6080        assert!(
6081            !m.stable() && (m.gain_margin_db + 6.02).abs() < 0.1 && (m.phase_margin_deg + 30.0).abs() < 0.1,
6082            "{m:?}"
6083        );
6084    }
6085
6086    /// With the belt's wrap known (effects.belt_wrap) the teeth in mesh are wrap r / p in place of
6087    /// `ratings.belt_teeth_in_mesh`: 2 rad on a pulley of r = 0.02 m with p = 5 mm, 8 teeth. The load of the lives' test,
6088    /// 2 N m at up to 95.49 r/min of the pulley: 100 N * 1.4 / (34.045 N/cm * 2.5 cm * 8) = 0.205610; half a turn,
6089    /// pi r / p = 12.57 teeth, is capped at 12 like the configured 14: 0.137073.
6090    #[test]
6091    fn the_tooth_load_counts_the_teeth_in_mesh_from_the_wrap() {
6092        let cfg = Config::parse(
6093            "format_version = 1
6094[gearbox]
6095ratio = 5.0
6096[geometry]
6097pulley_radius_m = 0.02
6098[belt]
6099tooth_pitch_m = 0.005
6100[ratings]
6101             belt_tooth_load_rpm = [0.0, 100.0, 1000.0]
6102belt_tooth_load_n_cm = [35.0, 34.0, 26.0]
6103belt_width_mm = 25.0
6104belt_service_factor = 1.4
6105             belt_teeth_in_mesh = 14.0
6106",
6107        )
6108        .unwrap();
6109        let mut bands = vec![0.0; 200];
6110        bands[9] = 2.0;
6111        let m = MotorLoad {
6112            gearbox_torque: Some((2.0, 1.0)),
6113            gearbox_torque_by_speed: bands,
6114            belt_wrap: Some(2.0),
6115            ..MotorLoad::default()
6116        };
6117        let close = |a: f64, b: f64| assert!((a / b - 1.0).abs() < 1e-5, "{a} against {b} by hand");
6118        close(belt_tooth_utilisation(&cfg, &m).unwrap().unwrap(), 0.205610);
6119        close(
6120            belt_tooth_utilisation(&cfg, &MotorLoad { belt_wrap: Some(std::f64::consts::PI), ..m.clone() })
6121                .unwrap()
6122                .unwrap(),
6123            0.137073,
6124        );
6125    }
6126
6127    /// The front keeps what no other point beats in all three figures at once. By hand, as (cycle time, energy,
6128    /// utilisation): A (1, 3, 0.5) and B (2, 2, 0.5) beat each other in one figure each, so both stay; C (2, 3, 0.5) is
6129    /// beaten by both; D (3, 1, 0.9) is the slowest but takes the least energy, so it stays; E is A again and is kept
6130    /// once; F (1, 3, 0.6) is A with a higher utilisation, beaten by A alone.
6131    #[test]
6132    fn the_front_keeps_the_points_no_other_beats_in_every_figure() {
6133        let point = |duration: f64, energy: f64, utilisation: f64| FrontPoint {
6134            duration,
6135            energy,
6136            utilisation,
6137            factors: [1.0; 3],
6138            blending: false,
6139            shaping: false,
6140        };
6141        let (a, b, c, d, f) = (
6142            point(1.0, 3.0, 0.5),
6143            point(2.0, 2.0, 0.5),
6144            point(2.0, 3.0, 0.5),
6145            point(3.0, 1.0, 0.9),
6146            point(1.0, 3.0, 0.6),
6147        );
6148        let front = non_dominated(&[d.clone(), c, b.clone(), a.clone(), a.clone(), f]);
6149        assert_eq!(front, [a, b, d]);
6150    }
6151}