Skip to main content

sim_components/
identify.rs

1//! Fitting a config to a measured machine, in stages: first the rigid values of each axis from a drive
2//! trace (or, where the motors do not turn in proportion to the axes, of each motor: `fit_joints`), then the
3//! load's resonance on the belt from a frequency sweep, or its stiffness from a move's trace
4//! (`fit_move_stiffness`). Nothing here edits a config; the results say what the config would have to be. `sim-cli fit
5//! --write` writes the one result that is a single key of the config (the factor on a stiffness) back, with its error
6//! band as `[bounds]`; the others are lumped values of several keys.
7//!
8//! Every stage runs the same estimate on the measurement and on the config's own simulation of the same
9//! run, and reports the two side by side. What the simple estimate gets wrong (gearbox losses that grow
10//! with the torque, friction that depends on the load, a resonance that moves with the sweep's amplitude)
11//! it gets wrong on both sides, so the difference between them is what the config is off by.
12
13use crate::analysis::SweepPoint;
14use crate::trace::{Trace, TraceError, replay};
15use sim_core::{Config, ConfigError, Machine, MachineEntry};
16
17/// Rows on either side of a row that are averaged with it: 11 rows in all, 11 ms in a trace from a run.
18/// Long enough to average the belt's ringing and the noise, short against a ramp of the profile.
19const WINDOW: usize = 5;
20
21/// The least share of the trace's residual that the residual of (trace − replay) is taken to have (`difference_share`).
22const REPEATABILITY: f64 = 1e-3;
23
24/// The rigid values of one axis, in this order: moved mass (with rotors and pulleys counted as mass at the
25/// axis), viscous friction, Coulomb friction and constant force. In N, kg, s and the axis's unit.
26#[derive(Debug, Clone, PartialEq)]
27pub struct AxisFit {
28    /// What the estimate gives on the config's simulation of the trace's setpoints.
29    pub config: [f64; 4],
30    /// What it gives on the trace, and the standard error of that.
31    pub fitted: [f64; 4],
32    pub error: [f64; 4],
33    /// How much the moved mass varies over the poses of the trace's rows that the fit takes (the config's inertia there,
34    /// as `mass_spread` takes it), in the mass's unit: in `error[0]` (in quadrature), and named in the advice where it is
35    /// the larger part of it.
36    pub mass_spread: f64,
37    /// Where the payload was picked or dropped during the trace (`fit_rigid`), rising: the time and its standard error
38    /// in s, then the change of the payload's factor there (+1 for the config's payload picked, −1 for it dropped) and
39    /// its standard error. With steps, `fitted` holds the values before the first.
40    pub payload_steps: Vec<(f64, f64, f64, f64)>,
41    /// What the friction does beyond its sliding level (`friction_details`), those the trace shows; the config's NaN
42    /// where its replay does not show it.
43    pub details: Vec<FrictionDetail>,
44    /// The units of the four values (`fit_units`), for the axis's own unit: kg, N s/m, N, N on a linear axis.
45    pub units: [&'static str; 4],
46}
47
48/// The units of an axis's four rigid values (moved mass, viscous friction, Coulomb friction, constant force) by the
49/// axis's unit (`AxisInfo::unit`): those of a rotary axis ("rad") are kg m², N m s/rad, N m and N m, every other one's kg,
50/// N s/m, N and N.
51pub fn fit_units(axis_unit: &str) -> [&'static str; 4] {
52    if axis_unit == "rad" { ["kg m²", "N m s/rad", "N m", "N m"] } else { ["kg", "N s/m", "N", "N"] }
53}
54
55impl AxisFit {
56    /// What the fit says to change in the config, as translation keys with their argument: the axis named
57    /// `axis` with the change of mass and constant force, and the factors on the two kinds of friction; then each
58    /// payload step.
59    pub fn advice(&self, axis: &str) -> Vec<(&'static str, String)> {
60        let change = |q: usize| {
61            format!("{axis}: {:+.3} {} ± {:.3}", self.fitted[q] - self.config[q], self.units[q], self.error[q])
62        };
63        let factor = |q: usize| {
64            format!("{axis}: × {:.3} ± {:.3}", self.fitted[q] / self.config[q], (self.error[q] / self.config[q]).abs())
65        };
66        let spread = (self.mass_spread > (self.error[0].powi(2) - self.mass_spread.powi(2)).max(0.0).sqrt())
67            .then(|| ("fit-mass-spread", format!("{axis}: ± {:.2e} {}", self.mass_spread, self.units[0])));
68        [("fit-mass", change(0)), ("fit-viscous", factor(1)), ("fit-coulomb", factor(2)), ("fit-constant", change(3))]
69            .into_iter()
70            .chain(spread)
71            // Viscous friction the trace does not tell from Coulomb friction (`rigid_values`) has no advice.
72            .filter(|(key, _)| *key != "fit-viscous" || (self.fitted[1].is_finite() && self.config[1].is_finite()))
73            .chain(self.payload_steps.iter().map(|(time, time_error, change, error)| {
74                ("fit-axis-payload-step", format!("{axis}: {time:.3} s ± {time_error:.3}, {change:+.3} ± {error:.3}"))
75            }))
76            .collect()
77    }
78}
79
80/// Per axis: the force the motors put on it and its speed, both from the trace's motor values through
81/// the machine's transformation. Motor angle per axis travel turns motor torques into axis forces
82/// (the same power on both sides), so the fit works per axis even where every motor moves every axis.
83fn axis_view(machine: &dyn Machine, trace: &Trace) -> Vec<(Vec<f64>, Vec<f64>)> {
84    let (axes, motors, h) = (machine.axes().len(), trace.motors.len(), 1e-3);
85    let mut out = vec![(Vec::new(), Vec::new()); axes];
86    let (mut pose, mut ahead) = (vec![0.0; axes], vec![0.0; axes]);
87    let (mut base, mut shifted) = (vec![0.0; motors], vec![0.0; motors]);
88    for row in 0..trace.time.len() {
89        let angle: Vec<f64> = trace.motors.iter().map(|m| m.angle[row]).collect();
90        let moved: Vec<f64> = trace.motors.iter().map(|m| m.angle[row] + h * m.speed[row]).collect();
91        machine.forward(&angle, &mut pose);
92        machine.forward(&moved, &mut ahead);
93        machine.inverse(&pose, &mut base);
94        for (i, (force, speed)) in out.iter_mut().enumerate() {
95            speed.push((ahead[i] - pose[i]) / h);
96            pose[i] += h;
97            machine.inverse(&pose, &mut shifted);
98            pose[i] -= h;
99            force.push((0..motors).map(|k| trace.motors[k].torque[row] * (shifted[k] - base[k]) / h).sum());
100        }
101    }
102    out
103}
104
105/// The force on `axis` per unit of each axis's acceleration at a pose: the motor torques per unit of that acceleration
106/// (`Machine::feedforward_torque`, as `trace::per_axis_fit` probes them) through the transformation as `axis_view` takes
107/// a force. On the axis's own acceleration its moved mass, on the others' what their motion pushes on it.
108fn inertia_row(machine: &dyn Machine, pose: &[f64], axis: usize) -> Vec<f64> {
109    let (n, motors, h) = (pose.len(), machine.motors().len(), 1e-3);
110    let (mut rest, mut moved, mut base, mut shifted) =
111        (vec![0.0; motors], vec![0.0; motors], vec![0.0; motors], vec![0.0; motors]);
112    let unit = |i: usize| (0..n).map(|j| if j == i { 1.0 } else { 0.0 }).collect::<Vec<f64>>();
113    let ahead: Vec<f64> = pose.iter().zip(unit(axis)).map(|(p, a)| p + h * a).collect();
114    machine.inverse(pose, &mut base);
115    machine.inverse(&ahead, &mut shifted);
116    machine.feedforward_torque(pose, &vec![0.0; n], &mut rest);
117    (0..n)
118        .map(|i| {
119            machine.feedforward_torque(pose, &unit(i), &mut moved);
120            (0..motors).map(|k| (moved[k] - rest[k]) * (shifted[k] - base[k]) / h).sum()
121        })
122        .collect()
123}
124
125/// How far the inertial force on `axis` strays from one constant mass over the trace's rows that the fit takes
126/// (`samples`, every tenth): per row the force the config's inertia puts on the axis at that row's pose and with every
127/// axis's acceleration there (`inertia_row`, the accelerations from `travel` smoothed as `rigid_samples` smooths them),
128/// less the mass that fits those forces best times the axis's acceleration, as a mass: sqrt(Σ r² / Σ a²). 0 on a machine
129/// whose inertia does not change with the pose and does not couple its axes; on one the fit per axis takes although it
130/// does (up to `PER_AXIS_SPREAD`: the T-shaped belt gantry's belt, the disc cam without its payload) the fitted mass is a mean over
131/// the trace, and what the config's mass is to change by is known no better than this.
132fn mass_spread(
133    machine: &dyn Machine,
134    trace: &Trace,
135    travel: &[Vec<f64>],
136    samples: &[Sample],
137    axis: usize,
138    h: usize,
139) -> f64 {
140    let time = &trace.time;
141    let mut pose = vec![0.0; travel.len()];
142    let forces: Vec<(f64, f64)> = samples
143        .iter()
144        .step_by(10)
145        .map(|(row, x, _)| {
146            machine.forward(&trace.motors.iter().map(|m| m.angle[*row]).collect::<Vec<f64>>(), &mut pose);
147            let acc = |i: usize| {
148                let slope = |a: usize| (travel[i][a + 1] - travel[i][a]) / (time[a + 1] - time[a]);
149                triangle(&|a| 2.0 * (slope(a) - slope(a - 1)) / (time[a + 1] - time[a - 1]), h, *row)
150            };
151            let force = inertia_row(machine, &pose, axis)
152                .iter()
153                .enumerate()
154                .map(|(i, m)| m * if i == axis { x[0] } else { acc(i) })
155                .sum::<f64>();
156            (force, x[0])
157        })
158        .collect();
159    let squares: f64 = forces.iter().map(|(_, a)| a * a).sum();
160    if squares <= 0.0 {
161        return 0.0;
162    }
163    let mass = forces.iter().map(|(f, a)| f * a).sum::<f64>() / squares;
164    (forces.iter().map(|(f, a)| (f - mass * a).powi(2)).sum::<f64>() / squares).sqrt()
165}
166
167/// Least squares of force = mass * acceleration + viscous * speed + coulomb * sign(speed) + constant + Σ the `extra`
168/// columns (one value per row each, by a value of their own) on the rows where the axis moves: values and standard
169/// errors, the four first. Rows slower than 5 % of the top speed are left out, because there friction is neither
170/// of the two terms. Viscous friction is NaN where the speeds used hardly vary (`inflation` above `WEAK`), its share then
171/// in the Coulomb value. `None` if the axis does not move both ways, since one direction alone cannot tell Coulomb friction
172/// from a constant force. The columns are scaled to unit length before the normal matrix is solved, as `solve` does:
173/// accelerations and ones differ by orders of magnitude.
174///
175/// The acceleration is the second difference of the axis's `travel` (an encoder's position is far less noisy than the speed
176/// differentiated, and noise on a regressor biases its value towards zero: the mass came out 15 % low on a noisy trace),
177/// and the force and every column are smoothed alike by the triangle of half-width `h` (`smoothing`, `per` rows to a
178/// measurement), as `regressor` does for `fit_joints`. `basis` fixes the columns used (the trace's, for the config's
179/// replay). The rows (`rigid_samples`) are best the same in trace and replay (`common`).
180fn rigid_values(samples: &[Sample], per: f64, basis: Option<&[usize]>) -> Option<Solved> {
181    let p = samples.first()?.1.len();
182    let one_way = |sign: f64| samples.iter().filter(|(_, x, _)| x[2] == sign).count();
183    if one_way(1.0).min(one_way(-1.0)) < 10 * (2 * WINDOW + 1) {
184        return None;
185    }
186    let basis: Vec<usize> = match basis {
187        // The replay has no payload steps: the trace's columns of them are left out.
188        Some(b) => b.iter().copied().filter(|&j| j < p).collect(),
189        None => {
190            // A column that is zero on every row used (the payload's force on an axis it does not load) has no value.
191            let mut basis: Vec<usize> = (0..p).filter(|&j| samples.iter().any(|(_, x, _)| x[j] != 0.0)).collect();
192            // At one speed each way (a constant-speed run, measured: inflation 223) the speed is its sign times a constant,
193            // and viscous against Coulomb friction is noise: viscous is left out (NaN) and the Coulomb value holds both.
194            if inflation(samples, &basis, 1).is_none_or(|f| f > WEAK) {
195                basis.retain(|&j| j != 1);
196            }
197            basis
198        }
199    };
200    solve(samples, Some(&basis), per)
201}
202
203/// The rows of `rigid_values`, one per row where the axis moves (`steady`): the acceleration, the speed and its sign,
204/// 1, then the `extra` columns, and the force, all smoothed by the triangle of half-width `h`.
205fn rigid_samples(
206    time: &[f64],
207    force: &[f64],
208    speed: &[f64],
209    travel: &[f64],
210    extra: &[Vec<f64>],
211    h: usize,
212) -> Vec<Sample> {
213    let (rows, top) = (time.len(), top_speed(speed));
214    let smooth = |x: &[f64], i: usize| triangle(&|r| x[r], h, i);
215    let slope = |a: usize| (travel[a + 1] - travel[a]) / (time[a + 1] - time[a]);
216    let second = |a: usize| 2.0 * (slope(a) - slope(a - 1)) / (time[a + 1] - time[a - 1]);
217    (h + 1..rows.saturating_sub(h + 1))
218        .filter_map(|i| {
219            let v = steady(speed, top, h, i)?;
220            let mut x = vec![triangle(&second, h, i), v, v.signum(), 1.0];
221            x.extend(extra.iter().map(|column| smooth(column, i)));
222            Some((i, x, smooth(force, i)))
223        })
224        .collect()
225}
226
227/// The samples of the trace and of the replay on the rows (keyed by `key`: the row, and in the motors' coordinates the
228/// motor) that both take, in their order. A row that one takes and the other not lies at a stop or a reversal, where the
229/// rigid model misses most (the smoothed friction is no longer ± its level): taken by one alone, that misfit does not
230/// cancel in fitted − config. The axis's own config to 0.9 m and back with noise of 0.1 rad/s on the speed (0.04 % of
231/// the top speed) came out 2 % low on viscous and 2 % high on Coulomb friction (3.7 standard errors) that way: the
232/// replay's speed is exactly 0 at rest, sign +1, so it took the rows on the way out whose window reaches into the rest,
233/// the trace with its noise did not.
234fn common(
235    trace: Vec<Sample>,
236    replay: Vec<Sample>,
237    key: impl Fn(&Sample) -> (usize, usize),
238) -> (Vec<Sample>, Vec<Sample>) {
239    let keys = |s: &[Sample]| s.iter().map(&key).collect::<std::collections::HashSet<_>>();
240    let (in_trace, in_replay) = (keys(&trace), keys(&replay));
241    let only = |s: Vec<Sample>, other: &std::collections::HashSet<(usize, usize)>| {
242        s.into_iter().filter(|x| other.contains(&key(x))).collect::<Vec<Sample>>()
243    };
244    (only(trace, &in_replay), only(replay, &in_trace))
245}
246
247/// The factor that turns the standard errors of the trace's fit into those of fitted − config, the residuals of trace
248/// and replay on the same rows (`common`) and the same basis. What the rigid model misses of the machine is in both alike,
249/// so fitted − config does not hold it, only the noise and what else the trace has that the replay has not: their
250/// variance is that of the residual of (trace − replay), Σ (r_trace − r_replay)² / (N − m · per) times `per` as in
251/// `solve`, and so the factor sqrt(Σ (r_trace − r_replay)² / Σ r_trace²), as N, m and `per` are the trace's. Measured on
252/// the one-axis belt drive's own config with the test noise (`the_fit_s_errors_cover_its_noise`, 80 seeds): (fitted − config) /
253/// error has a standard deviation of 0.88 to 1.15 for mass, viscous and Coulomb friction (the audit found 0.40 to 0.43
254/// with the trace's residual alone). Not below `REPEATABILITY` of the trace's residual, so that a replay identical to
255/// its trace does not give an error of zero.
256fn difference_share(trace: &[f64], replay: &[f64]) -> f64 {
257    let own: f64 = trace.iter().map(|r| r * r).sum();
258    let apart: f64 = trace.iter().zip(replay).map(|(t, r)| (t - r).powi(2)).sum();
259    if own > 0.0 { (apart / own).sqrt().max(REPEATABILITY) } else { 1.0 }
260}
261
262/// What the friction of an axis does beyond the rigid values' sliding level (`friction_details`): its name as the CLI
263/// writes it, and as in `AxisFit` the estimate on the config's replay, on the trace, and its standard error.
264#[derive(Debug, Clone, PartialEq)]
265pub struct FrictionDetail {
266    pub quantity: &'static str,
267    pub config: f64,
268    pub fitted: f64,
269    pub error: f64,
270}
271
272/// The quantities of `friction_details`, in its order.
273pub const FRICTION_DETAILS: [&str; 3] = ["held_force_n", "breakaway_force_n", "presliding_stiffness_n_m"];
274
275/// The mean of `x` and its standard error, the variance of a mean of n rows widened by (1 + ρ) / (1 − ρ) for the lag-one
276/// correlation ρ of the rows about it (neighbouring rows of a trace are not independent), as `fit_move_stiffness` does.
277fn mean_and_error(x: &[f64]) -> (f64, f64) {
278    let n = x.len() as f64;
279    let mean = x.iter().sum::<f64>() / n;
280    let squares: f64 = x.iter().map(|v| (v - mean).powi(2)).sum();
281    let rho = (x.windows(2).map(|w| (w[0] - mean) * (w[1] - mean)).sum::<f64>() / squares.max(f64::MIN_POSITIVE))
282        .clamp(0.0, 0.98);
283    (mean, (squares / (n - 1.0) / n * (1.0 + rho) / (1.0 - rho)).sqrt())
284}
285
286/// Friction beyond the sliding level, from one axis's force, speed and travel along the trace's rows and its rigid values
287/// (`rigid_values`: mass, viscous, Coulomb, constant; NaN viscous counts 0): each `None` where the trace does not show it.
288///
289/// - `held_force_n`: what the axis holds at rest after its last motion, the force less the constant one on the rows of
290///   the last stretch at rest (the speed within 1 % of the top speed, averaged over the window) after its first 0.1 s,
291///   at least 0.1 s of them. A friction smoothed through zero holds nothing; one that sticks holds what the loops
292///   wound up when the axis stopped.
293/// - `breakaway_force_n`: the friction at the lowest speeds, sign(v) (F − m a − b v − constant) on the rows whose speed
294///   is between 1 % and 5 % of the top speed and falls in size towards a stop or a reversal, keeping its sign across the
295///   window; at least ten windows of them. Above the Coulomb value where the friction rises towards rest (stiction and
296///   a Stribeck curve), at it where it does not.
297/// - `presliding_stiffness_n_m`: at each reversal of the averaged speed, the travel from the turning point (the row of
298///   least speed) at which the friction, the force less inertia and constant, has turned from one sliding level through
299///   zero; in Dahl's law (`ShaftFriction::presliding_force`) z = g (1 − 2 exp(−σ x / g)) passes zero at x = g ln 2 / σ, so
300///   σ = Coulomb ln 2 / x. The median over the reversals, its error 1.25 their spread over the root of their count,
301///   as `motor_fit` does for its LuGre bristles; only with two reversals or more and an error below the value. A
302///   reversal whose friction does not pass zero within 0.5 s or that crosses in its first row (faster than the trace
303///   resolves) is left out. On a machine whose friction has no presliding state it reads, as a Dahl σ, how far the
304///   axis travels while its friction turns: the smoothing of its Coulomb step over speed, LuGre bristles, the drive
305///   train's give and the loops' lag together. Compared with the replay's by the same estimate, not a value to set.
306///
307/// Each mean's standard error from `mean_and_error`. A row is reported only where the trace tells it (`None` else):
308/// the CLI, Python and the app list the three after an axis's rigid values where they are there.
309pub fn friction_details(
310    time: &[f64],
311    force: &[f64],
312    speed: &[f64],
313    travel: &[f64],
314    rigid: &[f64],
315) -> [Option<(f64, f64)>; 3] {
316    let (w, rows) = (WINDOW, time.len());
317    if rows < 2 * w + 3 {
318        return [None; 3];
319    }
320    let [mass, viscous, coulomb, constant] =
321        [rigid[0], rigid[1], rigid[2], rigid[3]].map(|v| if v.is_nan() { 0.0 } else { v });
322    let top = speed.iter().fold(0.0, |a: f64, b| a.max(b.abs()));
323    let mean = |x: &[f64], i: usize| x[i - w..=i + w].iter().sum::<f64>() / (2 * w + 1) as f64;
324    let inner = w..rows - w;
325    let v: Vec<f64> = inner.clone().map(|i| mean(speed, i)).collect();
326    let at = |i: usize| v[i - w];
327    let acc = |i: usize| (speed[i + w] - speed[i - w]) / (time[i + w] - time[i - w]);
328    let step = (time[rows - 1] - time[0]) / (rows - 1) as f64;
329    let tenth = (0.1 / step).round() as usize;
330    // The last stretch at rest after a motion.
331    let held = {
332        let still = |i: usize| at(i).abs() <= 0.01 * top;
333        let end = inner.clone().rev().find(|&i| still(i));
334        end.and_then(|end| {
335            let start = (inner.start..=end).rev().take_while(|&i| still(i)).last()?;
336            let moved = (inner.start..start).any(|i| !still(i));
337            let rest: Vec<f64> = (start + tenth..=end).map(|i| force[i] - constant).collect();
338            (moved && rest.len() >= tenth).then(|| mean_and_error(&rest))
339        })
340    };
341    let breakaway = {
342        let slow: Vec<f64> = inner
343            .clone()
344            .filter(|&i| {
345                let s = at(i);
346                (0.01 * top..0.05 * top).contains(&s.abs())
347                    && acc(i) * s < 0.0
348                    && speed[i - w..=i + w].iter().all(|x| x.signum() == s.signum())
349            })
350            .map(|i| at(i).signum() * (mean(force, i) - mass * acc(i) - viscous * at(i) - constant))
351            .collect();
352        (slow.len() >= 10 * (2 * w + 1)).then(|| mean_and_error(&slow))
353    };
354    let presliding = {
355        let mut stiffness = Vec::new();
356        for i in inner.start + w + 1..inner.end.saturating_sub(w) {
357            let (before, after) = (at(i - 1), at(i));
358            if before == 0.0 || after == 0.0 || before.signum() == after.signum() {
359                continue;
360            }
361            let sign = after.signum();
362            let turn = (i - w..i + w).min_by(|&a, &b| speed[a].abs().total_cmp(&speed[b].abs())).unwrap_or(i);
363            let friction = |k: usize| sign * (force[k] - mass * acc(k) - constant);
364            if friction(turn) >= 0.0 {
365                continue;
366            }
367            let crossing = (turn..(turn + 5 * tenth).min(inner.end)).find(|&k| friction(k) >= 0.0);
368            if let Some(k) = crossing.filter(|&k| k > turn + 1) {
369                // Linear between the rows on either side of the crossing.
370                let (f0, f1) = (friction(k - 1), friction(k));
371                let x = |r: usize| (travel[r] - travel[turn]).abs();
372                let distance = x(k - 1) + (x(k) - x(k - 1)) * (-f0) / (f1 - f0);
373                if distance > 0.0 {
374                    stiffness.push(coulomb * std::f64::consts::LN_2 / distance);
375                }
376            }
377        }
378        stiffness.sort_by(f64::total_cmp);
379        let n = stiffness.len();
380        // Reported where the trace tells it: two reversals at least, for an error, and that error below the value.
381        (n > 1)
382            .then(|| {
383                let median = stiffness[n / 2];
384                let spread = (stiffness.iter().map(|s| (s - median).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
385                    * 1.25
386                    / (n as f64).sqrt();
387                (median, spread)
388            })
389            .filter(|(median, spread)| spread < median)
390    };
391    [held, breakaway, presliding]
392}
393
394/// 1 / (1 − R²) of column `j` on the other columns of `basis`, uncentred and at unit length as `solve` takes them.
395fn inflation(samples: &[Sample], basis: &[usize], j: usize) -> Option<f64> {
396    let dot = |a: usize, b: usize| samples.iter().map(|(_, x, _)| x[a] * x[b]).sum::<f64>();
397    let gram: Vec<Vec<f64>> =
398        basis.iter().map(|&a| basis.iter().map(|&b| dot(a, b) / (dot(a, a) * dot(b, b)).sqrt()).collect()).collect();
399    let k = basis.iter().position(|&c| c == j)?;
400    inverse_of(&gram, &(0..basis.len()).collect::<Vec<_>>()).map(|inverse| inverse[k][k])
401}
402
403/// Stage 1: the rigid values of every axis from a trace, next to the config's. `None` for an axis the
404/// trace does not move in both directions.
405/// The machine has to pass `trace::per_axis_fit` (a linear transformation and an inertia that does not change with the
406/// pose); others are refused with `error-trace-not-linear` and go to `fit_joints`.
407///
408/// A payload picked or dropped during the trace is looked for as `fit_joints` does (`payload_steps`, in the motors'
409/// coordinates, against the config's replay); at each step found an axis gets a column of its own, the payload's force
410/// on it (the rigid model's with less without the payload, through the transformation) from the step on, whose value
411/// is the change of the payload's factor there (`AxisFit::payload_steps`). The axis's values are then those before the
412/// first step, the config's those of its replay, which holds the payload all along. Links (`Machine::links`): no
413/// machine the fit per axis takes reports any, the per-axis values hold them.
414pub fn fit_rigid(entry: &MachineEntry, cfg: &Config, trace: &Trace) -> Result<Vec<Option<AxisFit>>, TraceError> {
415    let mut machine = (entry.build)(&crate::catalog::resolve(entry, cfg)?)?;
416    if !crate::trace::per_axis_fit(machine.as_ref()) {
417        return Err(TraceError { key: "error-trace-not-linear", detail: String::new() });
418    }
419    let simulated = replay(entry, cfg, trace)?;
420    let (h, per) = smoothing(&trace.time, smoothing_span(machine.as_ref(), trace));
421    let steps = match (regressor(machine.as_mut(), trace, h), regressor(machine.as_mut(), &simulated, h)) {
422        (Some(measured), Some(config)) => {
423            let (measured, config) = common(measured, config, |s| (s.0, motor_of(&s.1, trace.motors.len())));
424            payload_steps(&measured, &config, &trace.time, h, per)
425        }
426        _ => Vec::new(),
427    };
428    // The payload's torque at each motor, row by row, as a trace whose axis view is the payload's force on each axis.
429    let mut payload = trace.clone();
430    payload.motors.iter_mut().for_each(|m| m.torque.fill(0.0));
431    if !steps.is_empty() {
432        let n = trace.motors.len();
433        let (mut with, mut without) = (vec![0.0; n], vec![0.0; n]);
434        for i in 1..trace.time.len() - 1 {
435            let t = &trace.time;
436            let at = |k: usize, a: usize| trace.motors[k].angle[a];
437            let angle: Vec<f64> = (0..n).map(|k| at(k, i)).collect();
438            let speed: Vec<f64> = trace.motors.iter().map(|m| m.speed[i]).collect();
439            let acc: Vec<f64> = (0..n)
440                .map(|k| {
441                    let slope = |a: usize| (at(k, a + 1) - at(k, a)) / (t[a + 1] - t[a]);
442                    2.0 * (slope(i) - slope(i - 1)) / (t[i + 1] - t[i - 1])
443                })
444                .collect();
445            machine.set_payload_attached(false);
446            machine.rigid_motor_torque(&angle, &speed, &acc, &mut without);
447            machine.set_payload_attached(true);
448            machine.rigid_motor_torque(&angle, &speed, &acc, &mut with);
449            for k in 0..n {
450                payload.motors[k].torque[i] = with[k] - without[k];
451            }
452        }
453    }
454    let carried = axis_view(machine.as_ref(), &payload);
455    // Each axis's travel along the rows, for the presliding (`friction_details`).
456    let travels = |t: &Trace| -> Vec<Vec<f64>> {
457        let mut pose = vec![0.0; machine.axes().len()];
458        let mut out = vec![Vec::new(); pose.len()];
459        for row in 0..t.time.len() {
460            machine.forward(&t.motors.iter().map(|m| m.angle[row]).collect::<Vec<f64>>(), &mut pose);
461            out.iter_mut().zip(&pose).for_each(|(o, p)| o.push(*p));
462        }
463        out
464    };
465    let (measured_travel, config_travel) = (travels(trace), travels(&simulated));
466    let views = axis_view(machine.as_ref(), trace).into_iter().zip(axis_view(machine.as_ref(), &simulated));
467    Ok(views
468        .zip(&carried)
469        .enumerate()
470        .map(|(axis, ((measured, config), (force, _)))| {
471            // From each step on, the payload's force on the axis.
472            let columns: Vec<Vec<f64>> = steps
473                .iter()
474                .map(|&(step, _)| (0..trace.time.len()).map(|i| if i >= step { force[i] } else { 0.0 }).collect())
475                .collect();
476            let (samples, replayed) = common(
477                rigid_samples(&trace.time, &measured.0, &measured.1, &measured_travel[axis], &columns, h),
478                rigid_samples(&trace.time, &config.0, &config.1, &config_travel[axis], &[], h),
479                |s| (s.0, 0),
480            );
481            let fit = rigid_values(&samples, per, None)?;
482            // The replay's values on the trace's rows and basis, so that the two differ by the config alone.
483            let replay_fit = rigid_values(&replayed, per, Some(&fit.basis))?;
484            let share = difference_share(&fit.residuals, &replay_fit.residuals);
485            let values = fit.values;
486            let mut errors: Vec<f64> = fit.errors.iter().map(|e| e * share).collect();
487            // The mass is the mean over the trace's poses of an inertia that may vary with them (`PER_AXIS_SPREAD`): its
488            // spread there, in the mass's error.
489            let mass_spread = mass_spread(machine.as_ref(), trace, &measured_travel, &samples, axis, h);
490            errors[0] = errors[0].hypot(mass_spread);
491            let four = |v: &[f64]| -> [f64; 4] { std::array::from_fn(|q| v[q]) };
492            let own = four(&replay_fit.values);
493            let fitted = friction_details(&trace.time, &measured.0, &measured.1, &measured_travel[axis], &values);
494            let replayed = friction_details(&trace.time, &config.0, &config.1, &config_travel[axis], &own);
495            let details = FRICTION_DETAILS
496                .iter()
497                .zip(fitted.iter().zip(&replayed))
498                .filter_map(|(quantity, (fitted, replayed))| {
499                    let (value, error) = (*fitted)?;
500                    Some(FrictionDetail { quantity, config: replayed.map_or(f64::NAN, |r| r.0), fitted: value, error })
501                })
502                .collect();
503            Some(AxisFit {
504                config: own,
505                fitted: four(&values),
506                error: four(&errors),
507                mass_spread,
508                details,
509                units: fit_units(machine.axes()[axis].unit),
510                payload_steps: steps
511                    .iter()
512                    .enumerate()
513                    .map(|(j, &(row, time_error))| (trace.time[row], time_error, values[4 + j], errors[4 + j]))
514                    .collect(),
515            })
516        })
517        .collect())
518}
519
520/// One value of the fit in the motors' coordinates (`fit_joints`): its name as the CLI writes it, of what (a motor's
521/// id, a link's name, or `payload`), and as in `AxisFit` the config's estimate, the measured one and its standard error.
522/// Per motor in N m, kg m², s and rad at the motor shaft. A base parameter: where the trace cannot tell other values
523/// from this one, `combines` names them (as `quantity of`) with the factor their change enters this one's change by, so
524/// that fitted less config is the change of this value plus each factor times the change of that one.
525#[derive(Debug, Clone, PartialEq)]
526pub struct JointValue {
527    pub quantity: &'static str,
528    pub of: String,
529    pub config: f64,
530    pub fitted: f64,
531    pub error: f64,
532    pub combines: Vec<(String, f64)>,
533}
534
535impl JointValue {
536    /// `quantity of`, as `combines` and the advice name a value.
537    pub fn name(&self) -> String {
538        format!("{} {}", self.quantity, self.of)
539    }
540}
541
542/// Stage 1 in the motors' coordinates (`fit_joints`).
543#[derive(Debug, Clone, PartialEq)]
544pub struct JointFit {
545    /// The base parameters: every value the trace tells apart from the others, with what it `combines`.
546    pub values: Vec<JointValue>,
547    /// Pairs of `values` (their indices) whose measured estimates correlate by more than `ALIKE`: the trace cannot
548    /// tell them apart, only a sum (or difference) of them is known, and each one's error band is wide for that.
549    pub alike: Vec<(usize, usize)>,
550    /// Values (`quantity of`) that are not reported on their own: those a base parameter combines, and those the
551    /// rigid torques do not depend on at all (a link's first moment along its own joint's axis).
552    pub folded: Vec<String>,
553    /// Where the payload was picked or dropped during the trace, rising: each time and its standard error, in s. The
554    /// payload's factor is then fitted per stretch between them: before the first (`payload_factor_before`) and from each
555    /// on (`payload_factor_after`, of `payload` for one step, `payload 1`, `payload 2`, ... for several).
556    pub payload_steps: Vec<(f64, f64)>,
557}
558
559/// Above this correlation of two estimates the trace does not tell them apart.
560pub const ALIKE: f64 = 0.95;
561
562/// No value's variance may be inflated by more than this by the others' (1 / (1 − R²) of its column on all the others):
563/// less than a tenth of its column outside what the others explain (and no less than 1, which rounding gives where the
564/// columns are exactly dependent). A column that would make one so is not fitted on
565/// its own but folded into those before it (`solve`): exactly where the rigid model only knows their sum (a link
566/// turning about a fixed axis adds to its motor's inertia and nothing else), nearly where the trace does not move the
567/// joints that would tell them apart (an elbow held still, a link never tilted against gravity).
568pub const WEAK: f64 = 100.0;
569
570/// The payload's factor has to differ before and after a step by this many of its standard errors for the step to
571/// count (`JointFit::payload_steps`), more than the trace's after less before differs from the config's replay's. Well
572/// above 3, as the search tries some hundred splits and keeps the best; on the swings with the payload held (delta,
573/// SCARA, arm) none was found, on the delta's pick the difference was some 70 standard errors.
574pub const PAYLOAD_STEP_SIGMAS: f64 = 6.0;
575
576/// The quantities of `fit_joints` per motor, after the factor on the payload (`payload_factor`).
577pub const JOINT_QUANTITIES: [&str; 4] =
578    ["added_inertia_kg_m2", "viscous_friction_nm_s_rad", "coulomb_friction_nm", "constant_torque_nm"];
579
580/// The quantities of `fit_joints` per link of a chain (`Machine::links`), after the motors': the factor on its mass,
581/// first moment and inertia together, and the change of its first moment along x, y and z of its frame, its mass and
582/// its inertia about its frame kept.
583pub const LINK_QUANTITIES: [&str; 4] =
584    ["link_mass_factor", "link_first_moment_x_kg_m", "link_first_moment_y_kg_m", "link_first_moment_z_kg_m"];
585
586/// The payload's factor before the first step and from each step on (`JointFit::payload_steps`), in place of
587/// `payload_factor`.
588pub const PAYLOAD_STEP_QUANTITIES: [&str; 2] = ["payload_factor_before", "payload_factor_after"];
589
590impl JointFit {
591    /// What the fit says to change in the config, as translation keys with their argument: the factor on the payload
592    /// (or its step), per motor the changes of inertia, friction and constant torque at its shaft, per link its mass
593    /// factor and first moment; then what each base parameter combines, what has no effect and the pairs that cannot
594    /// be told apart.
595    pub fn advice(&self) -> Vec<(&'static str, String)> {
596        let factor = |v: &JointValue| format!("× {:.3} ± {:.3}", v.fitted / v.config, (v.error / v.config).abs());
597        let mut out: Vec<(&'static str, String)> = Vec::new();
598        // The stretches' factors lead the values, in order of time.
599        let stretches: Vec<&JointValue> =
600            self.values.iter().filter(|v| PAYLOAD_STEP_QUANTITIES.contains(&v.quantity)).collect();
601        for (j, (time, error)) in self.payload_steps.iter().enumerate() {
602            let at = |s: usize| stretches.get(s).map(|v| factor(v)).unwrap_or_default();
603            out.push(("fit-payload-step", format!("{time:.3} s ± {error:.3}: {} → {}", at(j), at(j + 1))));
604        }
605        out.extend(self.values.iter().filter_map(|v| {
606            let change = |unit: &str| format!("{}: {:+.4} {unit} ± {:.4}", v.of, v.fitted - v.config, v.error);
607            Some(match v.quantity {
608                "payload_factor" => ("fit-payload", factor(v)),
609                "payload_factor_before" | "payload_factor_after" => return None,
610                "added_inertia_kg_m2" => {
611                    ("fit-joint-inertia", format!("{}: {:+.3e} kg m² ± {:.1e}", v.of, v.fitted - v.config, v.error))
612                }
613                "viscous_friction_nm_s_rad" => {
614                    ("fit-joint-viscous", format!("{}: {:+.2e} N m s/rad ± {:.1e}", v.of, v.fitted - v.config, v.error))
615                }
616                "coulomb_friction_nm" => ("fit-joint-coulomb", change("N m")),
617                "constant_torque_nm" => ("fit-joint-constant", change("N m")),
618                "link_mass_factor" => ("fit-link-mass", format!("{}: {}", v.of, factor(v))),
619                axis => ("fit-link-moment", format!("{} {}", &axis[18..19], change("kg m"))),
620            })
621        }));
622        for v in self.values.iter().filter(|v| !v.combines.is_empty()) {
623            let parts: Vec<String> = v.combines.iter().map(|(name, c)| format!("{c:+.3e} × {name}")).collect();
624            out.push(("fit-combined", format!("{}: {}", v.name(), parts.join(", "))));
625        }
626        let combined: Vec<&String> = self.values.iter().flat_map(|v| v.combines.iter().map(|(n, _)| n)).collect();
627        let no_effect: Vec<&str> = self.folded.iter().filter(|f| !combined.contains(f)).map(String::as_str).collect();
628        if !no_effect.is_empty() {
629            out.push(("fit-no-effect", no_effect.join(", ")));
630        }
631        out.extend(
632            self.alike
633                .iter()
634                .map(|&(a, b)| ("fit-alike", format!("{} / {}", self.values[a].name(), self.values[b].name()))),
635        );
636        out
637    }
638}
639
640/// The first moment's change the links' columns are taken over (kg m): the torques are linear in it, so the size only
641/// sets the rounding.
642const MOMENT_STEP: f64 = 0.01;
643
644/// One row of the stacked regressor: the trace's row, the regressor Y and the torque the rigid model leaves over.
645type Sample = (usize, Vec<f64>, f64);
646
647/// The span over which the regressor's rows are smoothed, s: a triangle of this half-width (`smoothing`). A gear's ringing
648/// above 1 / 0.04 s = 25 Hz is all but gone from it (the triangle's response is sinc², below 0.05 beyond its first zero),
649/// the slow swings of an exciting trajectory pass (0.995 at 1 Hz), and as the torque and every column are smoothed alike
650/// the fit holds whatever passes. Set by the six-axis arm's gears (their ringing at some 30 Hz); shorter only where a
651/// trace leaves too few rows at it (`smoothing_span`).
652pub const SMOOTHING_S: f64 = 0.04;
653
654/// The shortest span (`smoothing_span`) on a machine without modes: the rigid fit's own window of 11 rows at 1 ms
655/// (`WINDOW`), which averages the noise but has no ringing to take out.
656pub const RIGID_SPAN_S: f64 = 0.011;
657
658/// The span a machine's trace is smoothed over, s: `SMOOTHING_S` where every motor turns each way long enough at it
659/// (`turns_both_ways`); else the longest span at which they do, in whole rows of the trace's step, but not shorter than
660/// one period of the machine's lowest mode (`Machine::modes`, at the forward kinematics of the motor angles at ten rows
661/// spread over the trace), where the triangle's first zero takes its ringing out. `SMOOTHING_S` where none does (or
662/// where the lowest mode is below 25 Hz): the trace is then not fitted. The four-arm delta's lifts last some 60 ms and its
663/// arms 2 and 4 reverse in each traverse: at 40 ms its motor 2 kept its sign forward for 198 of the 810 rows a direction
664/// needs; its lowest mode, 44 Hz without the payload, allows down to 23 ms.
665///
666/// A machine that reports no mode at all may go down to `RIGID_SPAN_S`: the cycle of a planar two-arm picker with friction
667/// feedforward from its model (15 November 2026) keeps motor 1 turning backwards for 808 of the 810 rows 40 ms needs,
668/// and its fit was skipped.
669pub fn smoothing_span(machine: &dyn Machine, trace: &Trace) -> f64 {
670    let (n, rows, longest) = (machine.axes().len(), trace.time.len(), smoothing(&trace.time, SMOOTHING_S).0);
671    if turns_both_ways_within(trace, longest) {
672        return SMOOTHING_S;
673    }
674    let lowest = (0..10)
675        .map(|k| k * rows.saturating_sub(1) / 9)
676        .filter(|&r| r < rows)
677        .filter_map(|r| {
678            let angles: Vec<f64> = trace.motors.iter().map(|m| m.angle[r]).collect();
679            let mut pose = vec![0.0; n];
680            machine.forward(&angles, &mut pose);
681            machine.modes(&pose).first().map(|m| m.hz).filter(|hz| hz.is_finite() && *hz > 0.0)
682        })
683        .fold(f64::INFINITY, f64::min);
684    // A machine that reports no mode (the planar delta, rigid) has no ringing to smooth away: down to `RIGID_SPAN_S`.
685    let shortest_span = if lowest.is_finite() { 1.0 / lowest } else { RIGID_SPAN_S };
686    let (shortest, step) = (smoothing(&trace.time, shortest_span).0, median_step(&trace.time).unwrap_or(1.0));
687    (shortest..longest).rev().find(|&h| turns_both_ways_within(trace, h)).map_or(SMOOTHING_S, |h| h as f64 * step)
688}
689
690/// A trace's step, the median of its rows' spacing; `None` for fewer than two rows.
691fn median_step(time: &[f64]) -> Option<f64> {
692    let mut steps: Vec<f64> = time.windows(2).map(|p| p[1] - p[0]).collect();
693    steps.sort_by(f64::total_cmp);
694    steps.get(steps.len() / 2).copied()
695}
696
697/// The triangle's half-width `h` in rows of a trace's step (the median) for a span in s, and how many rows of a series
698/// smoothed by it count as one measurement: (Σ w)² / Σ w² for the weights w = h − |j|, |j| < h (h⁴ / (h² + 2 Σ (h −
699/// j)²), about 1.5 h; for a moving average of 2w + 1 rows the same formula gives 2w + 1).
700fn smoothing(time: &[f64], span: f64) -> (usize, f64) {
701    let h = median_step(time).map_or(1, |step| ((span / step).round() as usize).max(1));
702    let squares = (h * h) as f64 + 2.0 * (1..h).map(|j| ((h - j) * (h - j)) as f64).sum::<f64>();
703    (h, (h * h) as f64 * (h * h) as f64 / squares)
704}
705
706/// The triangle (h − |j|) / h² about row i of a series, |j| < h: its weights sum to 1.
707fn triangle(at: &dyn Fn(usize) -> f64, h: usize, i: usize) -> f64 {
708    (1..h).map(|j| (h - j) as f64 * (at(i - j) + at(i + j))).sum::<f64>() / (h * h) as f64 + at(i) / h as f64
709}
710
711fn top_speed(speed: &[f64]) -> f64 {
712    speed.iter().fold(0.0, |a: f64, b| a.max(b.abs()))
713}
714
715/// A motor's speed at row i smoothed by the triangle of half-width `h`, where that is above 5 % of its `top` speed and
716/// the speed keeps its sign across the window (sign q̇ smoothed over a reversal is no longer ±1); `None` elsewhere.
717fn steady(speed: &[f64], top: f64, h: usize, i: usize) -> Option<f64> {
718    let v = triangle(&|r| speed[r], h, i);
719    (v.abs() > 0.05 * top && speed[i + 1 - h..i + h].iter().all(|s| s.signum() == v.signum())).then_some(v)
720}
721
722/// Whether `fit_joints` can fit the machine's trace: every motor turns each way for at least ten windows' worth of rows
723/// that it takes (`steady`, over the machine's `smoothing_span`), else its Coulomb friction cannot be told from a
724/// constant torque.
725pub fn turns_both_ways(machine: &dyn Machine, trace: &Trace) -> bool {
726    turns_both_ways_within(trace, smoothing(&trace.time, smoothing_span(machine, trace)).0)
727}
728
729/// `turns_both_ways` with the triangle's half-width `h` in rows.
730fn turns_both_ways_within(trace: &Trace, h: usize) -> bool {
731    let rows = trace.time.len();
732    trace.motors.iter().all(|m| {
733        let (mut ways, top) = ([0usize; 2], top_speed(&m.speed));
734        for v in (h + 1..rows.saturating_sub(h + 1)).filter_map(|i| steady(&m.speed, top, h, i)) {
735            ways[usize::from(v > 0.0)] += 1;
736        }
737        ways[0].min(ways[1]) >= 10 * (2 * h + 1)
738    })
739}
740
741/// The stacked regressor of the motor torques on the machine's rigid model, τ − τ_rigid = Y θ, in the motors' own
742/// coordinates: per motor k a row
743///
744/// [τ_k,rigid − τ_k,rigid without payload, then per motor q̈_k, q̇_k, sign q̇_k, 1 at motor k's own place, then per
745/// link (`Machine::links`) the change of τ_k,rigid with the link's inertial parameters doubled and with 0.01 kg m more
746/// first moment along x, y and z, per unit],
747///
748/// the rigid torques from `Machine::rigid_split_torque` at each row's load motion with the rotors at their own
749/// acceleration, linear in each of these. The load: each motor's angle less the twist of its train that its torque
750/// holds (`Machine::twist`, zeros where the trains are rigid), a two-mass model per joint; its speed the measured one
751/// less the twist's slope, its acceleration the second difference of the load's angle (an encoder's angle is far less
752/// noisy than the speed differentiated, and noise on a regressor biases its value towards zero). Then the torque and
753/// every column are smoothed alike along the rows by a triangle of half-width `h` (`smoothing`): the equation holds as
754/// well smoothed, and what the rigid model does not have, the gears' ringing and the noise, is smoothed away. Before 14
755/// November the rigid model was taken at the motors' angles, the acceleration was the second difference across ±5 rows
756/// and the torque their mean: on the six-axis arm with its gears elastic a link's mass factor came out −11.8 for
757/// +0.57 (smoothing alone: −9.4; with the twist: + 0.558). A motor's row only where its smoothed speed is above 5 % of its top speed and its speed keeps its sign across
758/// the window (sign q̇ smoothed over a reversal is no longer ±1). A link's column that changes the stacked rigid torque
759/// by less than 1e-9 of it is set to zeros: rounding, of a parameter that has no effect. `None` where a motor does not
760/// turn both ways.
761fn regressor(machine: &mut dyn Machine, trace: &Trace, h: usize) -> Option<Vec<Sample>> {
762    let (rows, n, links) = (trace.time.len(), trace.motors.len(), machine.links().len());
763    let p = 1 + 4 * n + 4 * links;
764    if rows < 2 * h + 5 || !turns_both_ways_within(trace, h) {
765        return None;
766    }
767    let t = &trace.time;
768    let top: Vec<f64> = trace.motors.iter().map(|m| top_speed(&m.speed)).collect();
769    // Per motor, row by row as measured: the columns, the torque the rigid model leaves over and the rigid torque.
770    let mut raw = vec![vec![0.0; rows * p]; n];
771    let (mut left, mut stacked) = (vec![vec![0.0; rows]; n], vec![vec![0.0; rows]; n]);
772    let (mut with, mut without, mut changed) = (vec![0.0; n], vec![0.0; n], vec![0.0; n]);
773    let steps = [
774        (2.0, [0.0; 3]),
775        (1.0, [MOMENT_STEP, 0.0, 0.0]),
776        (1.0, [0.0, MOMENT_STEP, 0.0]),
777        (1.0, [0.0, 0.0, MOMENT_STEP]),
778    ];
779    // The second difference of a series per motor at row a (rows 1 to rows − 2).
780    let second = |x: &dyn Fn(usize) -> f64, a: usize| {
781        2.0 * ((x(a + 1) - x(a)) / (t[a + 1] - t[a]) - (x(a) - x(a - 1)) / (t[a] - t[a - 1])) / (t[a + 1] - t[a - 1])
782    };
783    // Each motor's acceleration and the twist of its train (`Machine::twist_at`), row by row: the load is where the motor's
784    // angle less the twist puts it, a two-mass model per joint whose spring's force the motor's torque tells.
785    let rotor_acc: Vec<Vec<f64>> = (0..rows)
786        .map(|i| {
787            (0..n)
788                .map(|k| if i == 0 || i == rows - 1 { 0.0 } else { second(&|a| trace.motors[k].angle[a], i) })
789                .collect()
790        })
791        .collect();
792    let twist: Vec<Vec<f64>> = (0..rows)
793        .map(|i| {
794            let mut out = vec![0.0; n];
795            let angle: Vec<f64> = trace.motors.iter().map(|m| m.angle[i]).collect();
796            let torque: Vec<f64> = trace.motors.iter().map(|m| m.torque[i]).collect();
797            machine.twist_at(&angle, &torque, &rotor_acc[i], &mut out);
798            out
799        })
800        .collect();
801    let load = |k: usize, a: usize| trace.motors[k].angle[a] - twist[a][k];
802    for i in 2..rows - 2 {
803        let angle: Vec<f64> = (0..n).map(|k| load(k, i)).collect();
804        let speed: Vec<f64> = (0..n)
805            .map(|k| trace.motors[k].speed[i] - (twist[i + 1][k] - twist[i - 1][k]) / (t[i + 1] - t[i - 1]))
806            .collect();
807        let acc: Vec<f64> = (0..n).map(|k| second(&|a| load(k, a), i)).collect();
808        machine.set_payload_attached(false);
809        machine.rigid_split_torque(&angle, &speed, &acc, &rotor_acc[i], &mut without);
810        machine.set_payload_attached(true);
811        machine.rigid_split_torque(&angle, &speed, &acc, &rotor_acc[i], &mut with);
812        for k in 0..n {
813            let x = &mut raw[k][i * p..(i + 1) * p];
814            x[0] = with[k] - without[k];
815            x[1 + 4 * k..5 + 4 * k].copy_from_slice(&[acc[k], speed[k], speed[k].signum(), 1.0]);
816            (left[k][i], stacked[k][i]) = (trace.motors[k].torque[i] - with[k], with[k]);
817        }
818        for l in 0..links {
819            for (c, (factor, moment)) in steps.iter().enumerate() {
820                machine.set_link_change(l, *factor, *moment);
821                machine.rigid_split_torque(&angle, &speed, &acc, &rotor_acc[i], &mut changed);
822                let size = if c == 0 { 1.0 } else { MOMENT_STEP };
823                for k in 0..n {
824                    raw[k][i * p + 1 + 4 * n + 4 * l + c] = (changed[k] - with[k]) / size;
825                }
826            }
827            machine.set_link_change(l, 1.0, [0.0; 3]);
828        }
829    }
830    let smooth = |at: &dyn Fn(usize) -> f64, i: usize| triangle(at, h, i);
831    let mut samples: Vec<Sample> = Vec::new();
832    // The stacked rigid torque's and each link column's change's sum of squares, for the columns of no effect.
833    let (mut rigid, mut link_change) = (0.0, vec![0.0; 4 * links]);
834    for i in h + 1..rows - h - 1 {
835        for k in 0..n {
836            if steady(&trace.motors[k].speed, top[k], h, i).is_none() {
837                continue;
838            }
839            let x: Vec<f64> = (0..p).map(|c| smooth(&|r| raw[k][r * p + c], i)).collect();
840            for (c, change) in link_change.iter_mut().enumerate() {
841                let size = if c % 4 == 0 { 1.0 } else { MOMENT_STEP };
842                *change += (x[1 + 4 * n + c] * size).powi(2);
843            }
844            rigid += smooth(&|r| stacked[k][r], i).powi(2);
845            samples.push((i, x, smooth(&|r| left[k][r], i)));
846        }
847    }
848    for (c, change) in link_change.iter().enumerate() {
849        if change.sqrt() <= 1e-9 * rigid.sqrt() {
850            samples.iter_mut().for_each(|(_, x, _)| x[1 + 4 * n + c] = 0.0);
851        }
852    }
853    Some(samples)
854}
855
856/// Which of the `motors` a row of `regressor` belongs to: the one whose constant column holds its 1.
857fn motor_of(x: &[f64], motors: usize) -> usize {
858    (0..motors).find(|&k| x[4 + 4 * k] > 0.5).unwrap_or(0)
859}
860
861/// The regressor with the payload's column split at the trace's rows `steps`: one column for each stretch between them.
862fn split(samples: &[Sample], steps: &[usize]) -> Vec<Sample> {
863    samples
864        .iter()
865        .map(|(row, x, y)| {
866            // One column per stretch between the steps (rising rows); a row in stretch s has the payload's in column s.
867            let mut out = vec![0.0; steps.len() + 1];
868            out[steps.partition_point(|s| s <= row)] = x[0];
869            out.extend_from_slice(&x[1..]);
870            (*row, out, *y)
871        })
872        .collect()
873}
874
875/// A least-squares fit of the stacked regressor on its base parameters.
876struct Solved {
877    /// Per column: the value (NaN outside the basis), its standard error, and for a column of the basis the columns it
878    /// combines with their factors.
879    values: Vec<f64>,
880    errors: Vec<f64>,
881    combines: Vec<Vec<(usize, f64)>>,
882    covariance: Vec<Vec<f64>>,
883    basis: Vec<usize>,
884    /// What the fit leaves over, per sample in the order given.
885    residuals: Vec<f64>,
886}
887
888/// Least squares on the base parameters: the columns, in their order, that the trace tells apart from those already
889/// taken (each column taken where with it no value's variance inflation, the diagonal of the inverse normal matrix of
890/// the columns scaled to unit length, is above `WEAK`), or the `basis` given (the trace's, for the config's replay). The payload's and the motors' columns come first, so a link's
891/// parameter that the motors' own values already hold is folded into those, and the links' parameters are reported
892/// only for what the motors' cannot hold. Each dropped column j is X_j = Σ X_i B_ij + r_j over the basis, B the least
893/// squares projection, r_j orthogonal to every column of the basis (zero where the model only knows the sum); so its
894/// value enters each base value i with the factor B_ij (`combines`) and its r_j only the residual, not the base values.
895/// Standard errors as `rigid_values`, the variance widened by `per` rows to a measurement (`smoothing`). `None` where
896/// the normal matrix cannot be solved.
897fn solve(samples: &[Sample], basis: Option<&[usize]>, per: f64) -> Option<Solved> {
898    let p = samples.first()?.1.len();
899    let norm: Vec<f64> = (0..p).map(|j| samples.iter().map(|(_, x, _)| x[j] * x[j]).sum::<f64>().sqrt()).collect();
900    let live: Vec<usize> = (0..p).filter(|&j| norm[j] > 0.0).collect();
901    let (mut gram, mut right) = (vec![vec![0.0; p]; p], vec![0.0; p]);
902    for (_, x, y) in samples {
903        for &a in &live {
904            let za = x[a] / norm[a];
905            right[a] += za * y;
906            for &b in &live {
907                gram[a][b] += za * x[b] / norm[b];
908            }
909        }
910    }
911    let basis: Vec<usize> = match basis {
912        Some(b) => b.to_vec(),
913        None => live.iter().fold(Vec::new(), |chosen: Vec<usize>, &j| {
914            let mut trial = chosen.clone();
915            trial.push(j);
916            let told_apart = inverse_of(&gram, &trial)
917                .is_some_and(|inv| (0..trial.len()).all(|a| (1.0 - 1e-6..=WEAK).contains(&inv[a][a])));
918            if told_apart { trial } else { chosen }
919        }),
920    };
921    let m = basis.len();
922    let inverse = inverse_of(&gram, &basis)?;
923    let mut values = vec![f64::NAN; p];
924    for (a, &j) in basis.iter().enumerate() {
925        values[j] = (0..m).map(|b| inverse[a][b] * right[basis[b]]).sum::<f64>() / norm[j];
926    }
927    let mut combines = vec![Vec::new(); p];
928    for &j in live.iter().filter(|j| !basis.contains(j)) {
929        for (a, &i) in basis.iter().enumerate() {
930            let scaled: f64 = (0..m).map(|b| inverse[a][b] * gram[basis[b]][j]).sum();
931            // Shares below 1 % of the folded column are left out of what is reported: rounding, or next to nothing.
932            if scaled.abs() > 0.01 {
933                combines[i].push((j, scaled * norm[j] / norm[i]));
934            }
935        }
936    }
937    let residuals: Vec<f64> =
938        samples.iter().map(|(_, x, y)| y - basis.iter().map(|&j| values[j] * x[j]).sum::<f64>()).collect();
939    let residual: f64 = residuals.iter().map(|r| r * r).sum();
940    // Neighbouring rows share most of their smoothing, so only every `per`th row counts as a measurement; and each value
941    // fitted takes `per` rows' worth of the residual's freedom, not one (the columns vary slowly against the smoothing):
942    // with N − m the axis's own config with the test noise gave (fitted − config) / error a standard deviation of 1.22.
943    let variance = residual / (samples.len() as f64 - m as f64 * per).max(1.0) * per;
944    let mut covariance = vec![vec![f64::NAN; p]; p];
945    for (a, &i) in basis.iter().enumerate() {
946        for (b, &j) in basis.iter().enumerate() {
947            covariance[i][j] = variance * inverse[a][b] / (norm[i] * norm[j]);
948        }
949    }
950    let errors = (0..p).map(|j| covariance[j][j].sqrt()).collect();
951    Some(Solved { values, errors, combines, covariance, basis, residuals })
952}
953
954/// The standard errors of the values a fit on `samples` (`solve`) gives on the columns `basis`, from the residual `e`
955/// per sample taken row by row (White 1980: Σ (A'A)⁻¹ a_i e_i² a_i' (A'A)⁻¹, widened by `per` and the freedom as
956/// `solve` widens its variance), indexed by column as `Solved::errors`; NaN outside the basis. Where the residual sits
957/// in a few rows of high leverage, it is larger than the residual's mean square over all rows gives.
958fn row_errors(samples: &[Sample], basis: &[usize], e: &[f64], per: f64) -> Vec<f64> {
959    let p = samples.first().map_or(0, |s| s.1.len());
960    let m = basis.len();
961    let norm: Vec<f64> = (0..p).map(|j| samples.iter().map(|(_, x, _)| x[j] * x[j]).sum::<f64>().sqrt()).collect();
962    let mut gram = vec![vec![0.0; p]; p];
963    for (_, x, _) in samples {
964        for &a in basis {
965            for &b in basis {
966                gram[a][b] += x[a] / norm[a] * x[b] / norm[b];
967            }
968        }
969    }
970    let mut errors = vec![f64::NAN; p];
971    let Some(inverse) = inverse_of(&gram, basis) else { return errors };
972    let mut sum = vec![0.0; m];
973    for ((_, x, _), e) in samples.iter().zip(e) {
974        let z: Vec<f64> = basis.iter().map(|&j| x[j] / norm[j]).collect();
975        for (a, s) in sum.iter_mut().enumerate() {
976            *s += (e * (0..m).map(|b| inverse[a][b] * z[b]).sum::<f64>()).powi(2);
977        }
978    }
979    let freedom = samples.len() as f64 / (samples.len() as f64 - m as f64 * per).max(1.0);
980    for (a, &j) in basis.iter().enumerate() {
981        errors[j] = (sum[a] * per * freedom).sqrt() / norm[j];
982    }
983    errors
984}
985
986/// The inverse of the normal matrix `gram` on the columns `of`; `None` where it has none.
987fn inverse_of(gram: &[Vec<f64>], of: &[usize]) -> Option<Vec<Vec<f64>>> {
988    let m = of.len();
989    let normal: Vec<f64> = of.iter().flat_map(|&a| of.iter().map(move |&b| gram[a][b])).collect();
990    let unit = |a: usize| (0..m).map(|b| if a == b { 1.0 } else { 0.0 }).collect::<Vec<f64>>();
991    (0..m).map(|a| crate::chain::solve(&normal, &unit(a))).collect()
992}
993
994/// Where in the stretch `within` (rows, the ends kept out) the payload's column `column` of the regressor is best split
995/// in two: the column split at every row in turn, on the base parameters `basis` of the fit with the steps found so far
996/// (the column one of them), and the row whose split leaves the least sum of squares; every `coarse`th row, then every
997/// row about the best (`coarse` = 2h + 1 of `smoothing`). Its standard error is how far from it the sum of squares stays
998/// within one variance (as `solve` takes it, `per` rows to a measurement) of its least. In: the regressor split at the
999/// steps so far, its basis, the column, the stretch, the trace's times; out: the row and the time's error.
1000///
1001/// A sum of squares per split from running sums along the rows: only the split column changes with the split, and it
1002/// is zero outside its stretch.
1003#[allow(clippy::too_many_arguments)]
1004fn best_split(
1005    samples: &[Sample],
1006    basis: &[usize],
1007    column: usize,
1008    within: std::ops::Range<usize>,
1009    time: &[f64],
1010    coarse: usize,
1011    per: f64,
1012) -> Option<(usize, f64)> {
1013    let at = basis.iter().position(|&j| j == column)?;
1014    let (m, rows) = (basis.len(), time.len());
1015    let norm: Vec<f64> =
1016        basis.iter().map(|&j| samples.iter().map(|(_, x, _)| x[j] * x[j]).sum::<f64>().sqrt()).collect();
1017    let (mut gram, mut right, mut yy) = (vec![0.0; m * m], vec![0.0; m], 0.0);
1018    // Per row of the trace: the split column's products with every column and with the torque, summed up to it.
1019    let mut running = vec![vec![0.0; m + 1]; rows + 1];
1020    let mut by_row = vec![vec![0.0; m + 1]; rows];
1021    for (row, x, y) in samples {
1022        let z: Vec<f64> = basis.iter().zip(&norm).map(|(&j, n)| x[j] / n).collect();
1023        for a in 0..m {
1024            right[a] += z[a] * y;
1025            for b in 0..m {
1026                gram[a * m + b] += z[a] * z[b];
1027            }
1028            by_row[*row][a] += z[at] * z[a];
1029        }
1030        by_row[*row][m] += z[at] * y;
1031        yy += y * y;
1032    }
1033    for row in 0..rows {
1034        running[row + 1] = (0..=m).map(|c| running[row][c] + by_row[row][c]).collect();
1035    }
1036    let others: Vec<usize> = (0..m).filter(|&a| a != at).collect();
1037    // The sum of squares left with the split before `row`: the column before, after, then the basis's others.
1038    let left = |row: usize| -> Option<f64> {
1039        let s = &running[row];
1040        let k = m + 1;
1041        let (mut normal, mut rhs) = (vec![0.0; k * k], vec![0.0; k]);
1042        normal[0] = s[at];
1043        normal[k + 1] = gram[at * m + at] - s[at];
1044        rhs[0] = s[m];
1045        rhs[1] = right[at] - s[m];
1046        for (o, &a) in others.iter().enumerate() {
1047            let r = o + 2;
1048            normal[r] = s[a];
1049            normal[r * k] = s[a];
1050            normal[k + r] = gram[at * m + a] - s[a];
1051            normal[r * k + 1] = gram[at * m + a] - s[a];
1052            rhs[r] = right[a];
1053            for (o2, &b) in others.iter().enumerate() {
1054                normal[r * k + o2 + 2] = gram[a * m + b];
1055            }
1056        }
1057        let theta = crate::chain::solve(&normal, &rhs)?;
1058        Some(yy - theta.iter().zip(&rhs).map(|(t, r)| t * r).sum::<f64>())
1059    };
1060    let (from, to) = (within.start, within.end);
1061    let best_of = |rows: &mut dyn Iterator<Item = usize>| {
1062        rows.filter_map(|r| left(r).map(|s| (r, s))).min_by(|a, b| a.1.total_cmp(&b.1))
1063    };
1064    let (rough, _) = best_of(&mut (from..to).step_by(coarse))?;
1065    let near = rough.saturating_sub(coarse).max(from)..(rough + coarse).min(to);
1066    let (row, least) = best_of(&mut near.clone())?;
1067    let variance = least / (samples.len() - m - 1) as f64 * per;
1068    let spread = near
1069        .filter(|&r| left(r).is_some_and(|s| s - least <= variance))
1070        .map(|r| (time[r] - time[row]).abs())
1071        .fold(0.0, f64::max);
1072    Some((row, spread.max(time[row] - time[row - 1])))
1073}
1074
1075/// At most this many payload steps are looked for in one trace.
1076pub const MAX_PAYLOAD_STEPS: usize = 8;
1077
1078/// Where the payload was picked or dropped during the trace, as rows with the time's standard error, rising. One step
1079/// at a time: in each stretch between the steps found so far (a tenth of the trace kept from its ends and from every
1080/// step) the best split (`best_split`); the regressor split there is fitted on the trace and, on that basis, on the
1081/// config's replay (which holds the payload all along), and the split counts where the factor's change across it on the
1082/// trace less that on the replay is more than `PAYLOAD_STEP_SIGMAS` of its standard error. Of the stretches' splits that
1083/// count, the one with the most standard errors is taken, then the search goes on, up to `MAX_PAYLOAD_STEPS`.
1084fn payload_steps(measured: &[Sample], config: &[Sample], time: &[f64], h: usize, per: f64) -> Vec<(usize, f64)> {
1085    let (rows, margin) = (time.len(), time.len() / 10);
1086    let mut steps: Vec<(usize, f64)> = Vec::new();
1087    // The stretches' columns all fitted on their own, ahead of every other.
1088    let leading = |fit: &Solved, stretches: usize| {
1089        fit.basis.len() >= stretches && (0..stretches).eq(fit.basis[..stretches].iter().copied())
1090    };
1091    while steps.len() < MAX_PAYLOAD_STEPS {
1092        let at: Vec<usize> = steps.iter().map(|s| s.0).collect();
1093        let current = split(measured, &at);
1094        let Some(fit) = solve(&current, None, per).filter(|f| leading(f, at.len() + 1)) else { break };
1095        let ends: Vec<usize> = std::iter::once(0).chain(at.iter().copied()).chain(std::iter::once(rows)).collect();
1096        let mut best: Option<(f64, usize, f64)> = None;
1097        for (stretch, pair) in ends.windows(2).enumerate() {
1098            let within = pair[0] + margin..pair[1].saturating_sub(margin);
1099            if within.is_empty() {
1100                continue;
1101            }
1102            let Some((row, error)) = best_split(&current, &fit.basis, stretch, within, time, 2 * h + 1, per) else {
1103                continue;
1104            };
1105            let mut trial = at.clone();
1106            trial.insert(stretch, row);
1107            let Some(split_fit) = solve(&split(measured, &trial), None, per).filter(|f| leading(f, trial.len() + 1))
1108            else {
1109                continue;
1110            };
1111            let Some(own) = solve(&split(config, &trial), Some(&split_fit.basis), per) else { continue };
1112            let (a, b, c) = (stretch, stretch + 1, &split_fit.covariance);
1113            let sigma = (c[a][a] + c[b][b] - 2.0 * c[a][b]).sqrt();
1114            let change = (split_fit.values[b] - split_fit.values[a]) - (own.values[b] - own.values[a]);
1115            let sigmas = change.abs() / sigma;
1116            if sigmas > PAYLOAD_STEP_SIGMAS && best.is_none_or(|(most, ..)| sigmas > most) {
1117                best = Some((sigmas, row, error));
1118            }
1119        }
1120        let Some((_, row, error)) = best else { break };
1121        steps.push((row, error));
1122        steps.sort_by_key(|s| s.0);
1123    }
1124    steps
1125}
1126
1127/// Stage 1 in the motors' own coordinates, for every machine, and the only one for a machine whose motors do not turn
1128/// in proportion to its axes (the delta's arms, a SCARA, an arm): the motor torques regressed on the machine's own
1129/// rigid model (`regressor`), on the trace and on the config's replay of it, on the trace's base parameters (`solve`).
1130/// For the config the payload's factor and each link's come out near 1 and the added inertias and first moments near
1131/// 0, friction and constant torque as the config has them at the motor shaft, gearbox losses and all, so that the
1132/// difference is what the config is off by. `None` where a motor does not turn both ways in the trace.
1133///
1134/// Each motor's added inertia stands for what its rotor and its link add about the joint alone; a link's mass factor
1135/// and first moments are reported where they act otherwise (on other joints, against gravity, with the pose), else
1136/// folded into the motors' values (`JointValue::combines`). What else it cannot tell apart depends on the moves and is
1137/// folded or listed in `alike`; a trace that swings every axis over much of its range at several frequencies
1138/// (docs/measurement-procedure.md) leaves none of the motors'. Elastic gears (`effects.joint_elasticity`): their
1139/// ringing is smoothed out of the torque and of the rigid model alike (`regressor`, `SMOOTHING_S`); the slow twist
1140/// under the load is left out (on the six-axis arm 1.5 mrad of a joint's angle under 100 N m), a shortcut that holds
1141/// while the swings stay well below the gears' resonance.
1142///
1143/// Payloads picked or dropped during the trace (no gripper column in a trace, so from its torques: `payload_steps`)
1144/// are fitted per stretch between the steps: `payload_factor_before` up to the first step, `payload_factor_after` from
1145/// each step on (of `payload` for one step, `payload 1`, `payload 2`, ... for several). The config's replay keeps its
1146/// payload and is fitted with the same split; a step counts where the trace's change of the factor across it differs
1147/// from the replay's by more than `PAYLOAD_STEP_SIGMAS` standard errors, so that what the rigid model misses of the
1148/// machine over the trace, the same in both, is not taken for one.
1149///
1150/// A factor on the rest of the rigid model (arms, platform, rotors) is not fitted: on the delta it correlated by more
1151/// than 0.95 with the motors' added inertias and constant torques together (gravity is nearly constant over a trace,
1152/// and each arm's inertia sits on its own motor), so it made all of them unknown.
1153pub fn fit_joints(entry: &MachineEntry, cfg: &Config, trace: &Trace) -> Result<Option<JointFit>, TraceError> {
1154    let simulated = replay(entry, cfg, trace)?;
1155    let mut machine = (entry.build)(&crate::catalog::resolve(entry, cfg)?)?;
1156    let ids: Vec<String> = machine.motors().iter().map(|m| m.id.to_string()).collect();
1157    let links = machine.links();
1158    let (h, per) = smoothing(&trace.time, smoothing_span(machine.as_ref(), trace));
1159    let (Some(measured), Some(config)) =
1160        (regressor(machine.as_mut(), trace, h), regressor(machine.as_mut(), &simulated, h))
1161    else {
1162        return Ok(None);
1163    };
1164    // Trace and replay on the same rows of each motor (`common`).
1165    let (measured, config) = common(measured, config, |s| (s.0, motor_of(&s.1, ids.len())));
1166    let steps = payload_steps(&measured, &config, &trace.time, h, per);
1167    let at: Vec<usize> = steps.iter().map(|s| s.0).collect();
1168    let Some(fitted) = solve(&split(&measured, &at), None, per) else { return Ok(None) };
1169    let Some(replayed) = solve(&split(&config, &at), Some(&fitted.basis), per) else { return Ok(None) };
1170    // The standard errors are those of fitted less config (`difference_share`), not the trace's alone, whose residual
1171    // holds what the rigid model misses of the machine in both; and at least those of the same difference taken row by
1172    // row (`row_errors`): on the cable-driven platforms, whose gearbox mesh friction sticks at rest, a replay breaks away a row
1173    // before or after its trace at a move's start (0.03 N m for a row), which the mean square over all rows spread thin:
1174    // their own traces missed the config by 4.0 (planar) and 5.8 (spatial) standard errors, 0.89 and 0.85 with it.
1175    let share = difference_share(&fitted.residuals, &replayed.residuals);
1176    let apart: Vec<f64> = fitted.residuals.iter().zip(&replayed.residuals).map(|(t, r)| t - r).collect();
1177    let by_row = row_errors(&split(&measured, &at), &fitted.basis, &apart, per);
1178    let payload: Vec<(&'static str, String)> = match steps.len() {
1179        0 => vec![("payload_factor", "payload".to_string())],
1180        1 => PAYLOAD_STEP_QUANTITIES.iter().map(|q| (*q, "payload".to_string())).collect(),
1181        many => std::iter::once((PAYLOAD_STEP_QUANTITIES[0], "payload".to_string()))
1182            .chain((1..=many).map(|j| (PAYLOAD_STEP_QUANTITIES[1], format!("payload {j}"))))
1183            .collect(),
1184    };
1185    let factors = payload.len();
1186    let names: Vec<(&'static str, String)> = payload
1187        .into_iter()
1188        .chain(ids.iter().flat_map(|id| JOINT_QUANTITIES.map(|q| (q, id.clone()))))
1189        .chain(links.iter().flat_map(|l| LINK_QUANTITIES.map(|q| (q, l.clone()))))
1190        .collect();
1191    // Factors are fitted as a change, as the rest; the config's own counts 1.
1192    let shift = |j: usize| if j < factors || names[j].0 == "link_mass_factor" { 1.0 } else { 0.0 };
1193    let label = |j: usize| format!("{} {}", names[j].0, names[j].1);
1194    let values: Vec<JointValue> = fitted
1195        .basis
1196        .iter()
1197        .map(|&j| JointValue {
1198            quantity: names[j].0,
1199            of: names[j].1.clone(),
1200            config: replayed.values[j] + shift(j),
1201            fitted: fitted.values[j] + shift(j),
1202            error: (fitted.errors[j] * share).max(by_row[j]),
1203            combines: fitted.combines[j].iter().map(|&(i, c)| (label(i), c)).collect(),
1204        })
1205        .collect();
1206    let mut alike = Vec::new();
1207    let c = &fitted.covariance;
1208    for (a, &i) in fitted.basis.iter().enumerate() {
1209        for (b, &j) in fitted.basis.iter().enumerate().skip(a + 1) {
1210            if (c[i][j] / (c[i][i] * c[j][j]).sqrt()).abs() > ALIKE {
1211                alike.push((a, b));
1212            }
1213        }
1214    }
1215    let folded = (0..names.len()).filter(|j| !fitted.basis.contains(j)).map(label).collect();
1216    let payload_steps = steps.iter().map(|&(row, error)| (trace.time[row], error)).collect();
1217    Ok(Some(JointFit { values, alike, folded, payload_steps }))
1218}
1219
1220// The load swinging on the belt against the motor, read from a frequency sweep.
1221#[derive(Debug, Clone, Copy, PartialEq)]
1222pub struct Resonance {
1223    pub frequency: f64,
1224    /// Damping ratio from the width of the dip. Friction and the gearbox widen it too, so this is not
1225    /// the belt's damping alone.
1226    pub damping: f64,
1227    /// Half the distance between the sweep's points at the dip: the frequency is not known better.
1228    pub frequency_error: f64,
1229}
1230
1231/// Stage 2: the resonance of the load on the belt, from a frequency sweep of motor torque to motor speed
1232/// (`frequency_sweep`, or a drive's measurement of the mechanical system). Where the load resonates the
1233/// motor hardly moves, which shows as a dip. Its frequency squared is stiffness over load mass, so with
1234/// the masses right, measured over config frequency, squared, is the factor the stiffness is off by.
1235///
1236/// The dip is not read off a move's trace: the closed loops and friction damp the ringing, and the belt's stiffness
1237/// changes along the way; `fit_move_stiffness` replays such a trace instead. A sweep that does not have the dip and
1238/// both its flanks gives `None`.
1239///
1240/// A machine with more than one spring shows more than one dip (the first default machine has three,
1241/// near 22, 62 and 107 Hz); this is the lowest in frequency, the load swinging on the whole drive train, so that the config's
1242/// sweep and the measured one are compared at the same dip. The points may come in any order.
1243pub fn resonance(sweep: &[SweepPoint]) -> Option<Resonance> {
1244    dips(sweep).into_iter().next()
1245}
1246
1247/// Every dip of a sweep with both its flanks (as `resonance` reads one), rising in frequency.
1248fn dips(sweep: &[SweepPoint]) -> Vec<Resonance> {
1249    let mut sweep = sweep.to_vec();
1250    sweep.sort_by(|a, b| a.frequency.total_cmp(&b.frequency));
1251    // Gain times frequency is level for a pure inertia, so the dip is not hidden in the 1 / f slope.
1252    let level: Vec<f64> = sweep.iter().map(|p| p.gain * p.frequency).collect();
1253    // The flanks, where the response has twice the power of the lowest point, are steep: noise moves
1254    // them little, where it can move the lowest point by a whole step.
1255    let flanks = |lowest: usize| {
1256        let limit = level[lowest] * std::f64::consts::SQRT_2;
1257        let below = (0..lowest).rev().find(|&i| level[i] > limit)?;
1258        let above = (lowest + 1..level.len()).find(|&i| level[i] > limit)?;
1259        // Not a dip of its own where a deeper point lies between its flanks.
1260        level[below..=above].iter().all(|&l| l >= level[lowest]).then_some((limit, below, above))
1261    };
1262    let mut out: Vec<Resonance> = Vec::new();
1263    let mut last = None;
1264    for (limit, below, above) in (0..level.len()).filter_map(flanks) {
1265        // Two equal lowest points of one dip give it once.
1266        if last == Some((below, above)) {
1267            continue;
1268        }
1269        last = Some((below, above));
1270        let crossing = |outside: usize, inside: usize| {
1271            let share = (limit - level[inside]) / (level[outside] - level[inside]);
1272            sweep[inside].frequency + share * (sweep[outside].frequency - sweep[inside].frequency)
1273        };
1274        let (low, high) = (crossing(below, below + 1), crossing(above, above - 1));
1275        let frequency = (low * high).sqrt();
1276        let step = (sweep[below + 1].frequency - sweep[below].frequency)
1277            .max(sweep[above].frequency - sweep[above - 1].frequency);
1278        out.push(Resonance { frequency, damping: (high - low) / (2.0 * frequency), frequency_error: 0.5 * step });
1279    }
1280    out
1281}
1282
1283/// A frequency response as `sim-cli sweep` writes it: the columns `frequency_hz` and `gain_rad_s_per_nm`. A
1284/// phase is not read; the fit does not use it. A frequency that is not finite and above zero is refused, as `sweep` refuses
1285/// it: before, a file with 0 Hz in it got past to the fit, and was refused only when it had a dip.
1286pub fn parse_sweep(text: &str) -> Result<Vec<SweepPoint>, TraceError> {
1287    let table = crate::trace::columns(text, &["frequency_hz".to_string(), "gain_rad_s_per_nm".to_string()])?;
1288    crate::analysis::check_frequencies(&table[0])?;
1289    Ok(table[0]
1290        .iter()
1291        .zip(&table[1])
1292        .map(|(&frequency, &gain)| SweepPoint { frequency, gain, phase_deg: 0.0 })
1293        .collect())
1294}
1295
1296/// Stage 2 done: the resonance of the config's own sweep and that of the measured one.
1297#[derive(Debug, Clone, Copy, PartialEq)]
1298pub struct SweepFit {
1299    pub config: Resonance,
1300    pub fitted: Resonance,
1301    /// The factor on the belt's stiffness at which the config's dip lies at the measured frequency (`fit_sweep`).
1302    pub factor: f64,
1303    /// d ln f / d ln k of the dip there: 1/2 for a mode the belt carries alone, less for one it shares.
1304    pub exponent: f64,
1305}
1306
1307impl SweepFit {
1308    /// The factor the belt stiffness is off by, and its standard error: the measured frequency's, carried through
1309    /// f ~ k^exponent, factor x (error / f) / exponent (with the pure belt's 1/2: twice the frequency's relative error).
1310    pub fn stiffness(&self) -> (f64, f64) {
1311        (self.factor, self.factor * self.fitted.frequency_error / self.fitted.frequency / self.exponent)
1312    }
1313
1314    /// What to change in the config, as a translation key with its argument.
1315    pub fn advice(&self) -> (&'static str, String) {
1316        let (factor, error) = self.stiffness();
1317        ("fit-stiffness", format!("× {factor:.3} ± {error:.3}"))
1318    }
1319}
1320
1321/// Stage 2 on a measured sweep, taken on `motor` with a torque `amplitude`: a dip of the measured sweep, and of the
1322/// config's own sweep the dip of the same mode. The config's sweep has the measured frequencies and,
1323/// at the step of each end, more beyond them up to a factor of √2: its dip of the same mode may lie near an end, where
1324/// the range misses one of its flanks. Before, the config's lowest dip with both flanks was taken: on the T-shaped belt gantry with
1325/// its belt at 0.8 of the stiffness, swept from 50 to 130 Hz, its dip at 55 Hz missed its lower flank by 0.1 of 726,
1326/// and the next one, at 94 Hz, was set against the measured 61.5 Hz (factor 0.42 for 1.25). `None` where the measured
1327/// sweep shows no dip with both flanks, or the config's none at all.
1328///
1329/// Which dip is the measured mode is told by how the config's dips move with the stiffness, not by being the nearest (that
1330/// holds only while the stiffness is off by less than the ratio of neighbouring dips' frequencies, 61.5 and 103 Hz on the
1331/// T-shaped belt gantry: a factor of 1.3 either way). The config is swept a second time with `BELT_STIFFNESS_KEY` raised
1332/// by `STIFFNESS_PROBE`, and each dip matched to the nearest dip of that sweep gives its exponent s in f ~ k^s: 1/2 for a
1333/// mode the belt carries alone, less for one it shares, 0 for one it does not carry. Each dip with s of at least 1/4 is
1334/// tried as each of the measured sweep's dips: the stiffness that puts it there moves every dip by its own exponent, and the
1335/// pair is taken whose moved dips meet the measured sweep's dips best (the sum of the log distances, each measured dip to
1336/// the nearest moved one and each moved one inside the measured range to the nearest measured one; of equal sums the
1337/// nearer). Before, the measured sweep's lowest dip was the one: on the T-shaped belt gantry swept from 5 to 500 Hz that is
1338/// a 22 Hz mode the belt hardly moves, and it was set against the config's 60 Hz belt mode (× 0.103 for 1). With no
1339/// such dip, or no key `BELT_STIFFNESS_KEY` in the config, the nearest dip of all. The cost is a second sweep of the
1340/// config. On the T-shaped belt gantry swept from 30 to 200 Hz this takes the 60 Hz dip for a belt from half to 2.5
1341/// times as stiff (`sweep.rs`); the nearest dip took the 102 Hz one beyond 1.8 times. The factor (`SweepFit::factor`) is
1342/// then the one at which the config's dip lies at the measured frequency, found by sweeping the config at it (a secant,
1343/// `SECANT_STEPS` sweeps at most); without the key, the pure belt law (f_measured / f_config)^2.
1344pub fn fit_sweep(
1345    entry: &MachineEntry,
1346    cfg: &Config,
1347    motor: usize,
1348    measured: &[SweepPoint],
1349    amplitude: f64,
1350) -> Result<Option<SweepFit>, ConfigError> {
1351    let measured_dips = dips(measured);
1352    let Some(&lowest) = measured_dips.first() else { return Ok(None) };
1353    let mut frequencies: Vec<f64> = measured.iter().map(|p| p.frequency).collect();
1354    frequencies.sort_by(f64::total_cmp);
1355    let n = frequencies.len();
1356    let mut wider = frequencies.clone();
1357    if n >= 2 {
1358        let (low, high) = (frequencies[0], frequencies[n - 1]);
1359        let (down, up) = (frequencies[1] / low, high / frequencies[n - 2]);
1360        let mut f = low / down;
1361        while down > 1.001 && f >= low / std::f64::consts::SQRT_2 {
1362            wider.push(f);
1363            f /= down;
1364        }
1365        let mut f = high * up;
1366        while up > 1.001 && f <= high * std::f64::consts::SQRT_2 {
1367            wider.push(f);
1368            f *= up;
1369        }
1370    }
1371    let config = crate::analysis::frequency_sweep(entry, cfg, motor, &wider, amplitude)?;
1372    let apart = |r: &Resonance, m: &Resonance| (r.frequency / m.frequency).ln().abs();
1373    let all = dips(&config);
1374    let nearest = || all.iter().copied().min_by(|a, b| apart(a, &lowest).total_cmp(&apart(b, &lowest)));
1375    let belt_law = |config: Resonance| SweepFit {
1376        config,
1377        fitted: lowest,
1378        factor: (lowest.frequency / config.frequency).powi(2),
1379        exponent: 0.5,
1380    };
1381    let Ok(base) = cfg.f64(BELT_STIFFNESS_KEY) else {
1382        return Ok(nearest().map(belt_law));
1383    };
1384    let mut stiffer = cfg.clone();
1385    stiffer.set_text(&format!("{BELT_STIFFNESS_KEY} = {:?}", base * STIFFNESS_PROBE))?;
1386    let probe = dips(&crate::analysis::frequency_sweep(entry, &stiffer, motor, &wider, amplitude)?);
1387    // Each dip's exponent s of f ~ k^s: by how far the probe's dip of the same mode (the nearest, taken only within a
1388    // factor 1.2) lies from it; 0 where the probe has none there.
1389    let exponent = |r: &Resonance| {
1390        probe
1391            .iter()
1392            .map(|q| (q.frequency / r.frequency).ln())
1393            .filter(|m| m.abs() < 1.2f64.ln())
1394            .min_by(|a, b| a.abs().total_cmp(&b.abs()))
1395            .map_or(0.0, |moved| moved / STIFFNESS_PROBE.ln())
1396    };
1397    let modes: Vec<(Resonance, f64)> = all.iter().map(|r| (*r, exponent(r))).collect();
1398    let (low, high) = (frequencies[0], frequencies[n - 1]);
1399    let log_gap =
1400        |f: f64, set: &mut dyn Iterator<Item = f64>| set.map(|g| (f / g).ln().abs()).fold(f64::INFINITY, f64::min);
1401    // The config's dips moved to the stiffness at which dip `i` is the measured dip `j`, against the measured dips both
1402    // ways (each measured dip to the nearest moved one, each moved one inside the measured range to the nearest measured).
1403    let mismatch = |(i, j): (usize, usize)| {
1404        let (r, s) = modes[i];
1405        let k_log = (measured_dips[j].frequency / r.frequency).ln() / s;
1406        let moved: Vec<f64> = modes.iter().map(|(q, t)| q.frequency * (t * k_log).exp()).collect();
1407        let to_moved: f64 = measured_dips.iter().map(|m| log_gap(m.frequency, &mut moved.iter().copied())).sum();
1408        let to_measured: f64 = moved
1409            .iter()
1410            .filter(|f| (low..=high).contains(*f))
1411            .map(|f| log_gap(*f, &mut measured_dips.iter().map(|m| m.frequency)))
1412            .sum();
1413        to_moved + to_measured
1414    };
1415    // Each mode the belt carries against each measured dip: the measured sweep's lowest dip may be a mode the belt does
1416    // not carry (a frame's), which no stiffness moves the config's belt mode to.
1417    let candidates: Vec<(usize, usize)> = (0..modes.len())
1418        .filter(|&i| modes[i].1 >= 0.25)
1419        .flat_map(|i| (0..measured_dips.len()).map(move |j| (i, j)))
1420        .collect();
1421    let gap = |(i, j): (usize, usize)| apart(&modes[i].0, &measured_dips[j]);
1422    let best =
1423        candidates.into_iter().min_by(|&a, &b| mismatch(a).total_cmp(&mismatch(b)).then(gap(a).total_cmp(&gap(b))));
1424    let Some((i, j)) = best else { return Ok(nearest().map(belt_law)) };
1425    let fitted = measured_dips[j];
1426    // The factor at which the config's dip is the measured one, by sweeping the config at it: a secant on ln f over
1427    // ln k from the config's own and the probe's dip, each step a sweep at the factor the last two give, its dip the
1428    // one nearest where the secant puts it (within a factor 1.2). A mode the belt shares does not move as sqrt(k)
1429    // (k^0.37 to k^0.45 on the T-shaped belt gantry), so the exponent the probe measures at 1.1 does not hold at 2.5.
1430    let (config, s) = modes[i];
1431    let target = fitted.frequency.ln();
1432    let mut points =
1433        vec![(0.0, config.frequency.ln()), (STIFFNESS_PROBE.ln(), config.frequency.ln() + s * STIFFNESS_PROBE.ln())];
1434    for _ in 0..SECANT_STEPS {
1435        let ((ka, fa), (kb, fb)) = (points[points.len() - 2], points[points.len() - 1]);
1436        let slope = (fb - fa) / (kb - ka);
1437        if (target - fb).abs() < 1e-5 || (target - fa).abs() < 1e-5 || slope < 0.05 {
1438            break;
1439        }
1440        let k = kb + (target - fb) / slope;
1441        let mut at = cfg.clone();
1442        at.set_text(&format!("{BELT_STIFFNESS_KEY} = {:?}", base * k.exp()))?;
1443        let expected = fb + slope * (k - kb);
1444        let Some(f) = dips(&crate::analysis::frequency_sweep(entry, &at, motor, &wider, amplitude)?)
1445            .iter()
1446            .map(|q| q.frequency.ln())
1447            .filter(|f| (f - expected).abs() < 1.2f64.ln())
1448            .min_by(|a, b| (a - expected).abs().total_cmp(&(b - expected).abs()))
1449        else {
1450            break;
1451        };
1452        points.push((k, f));
1453    }
1454    // The last two points' secant read at the measured frequency (the nearer of them to it, when it is that).
1455    let ((ka, fa), (kb, fb)) = (points[points.len() - 2], points[points.len() - 1]);
1456    let slope = (fb - fa) / (kb - ka);
1457    let k = if (target - fa).abs() < 1e-5 { ka } else { kb + (target - fb) / slope };
1458    // The exponent there, for the error: the chord from the solution to the nearest swept point at least the probe's
1459    // step away (two points closer than that, as the secant's last ones are, give the dip's resolution, not its slope:
1460    // 0.04 for 0.41 at 2.5 times on the gantry; at half the step, 1.8 % in frequency against the sweep's 3.9 % between
1461    // points, still 0.23 there where the modes move as k^0.37).
1462    let exponent = points
1463        .iter()
1464        .filter(|(kp, _)| (kp - k).abs() >= STIFFNESS_PROBE.ln())
1465        .min_by(|a, b| (a.0 - k).abs().total_cmp(&(b.0 - k).abs()))
1466        .map_or(slope, |(kp, fp)| (target - fp) / (k - kp));
1467    Ok(Some(SweepFit { config, fitted, factor: k.exp(), exponent }))
1468}
1469
1470/// The most sweeps `fit_sweep` takes to put the config's dip on the measured one after the probe.
1471const SECANT_STEPS: usize = 4;
1472
1473/// The factor `fit_sweep` raises the stiffness by for its second sweep: small enough that a mode stays near where it was,
1474/// large enough to tell a shift of 5 % from the sweep's resolution.
1475const STIFFNESS_PROBE: f64 = 1.1;
1476
1477/// Above this standard error, over the factor, a trace is taken not to excite the mode enough (`fit_move_stiffness`).
1478pub const MOVE_STIFFNESS_LIMIT: f64 = 0.1;
1479
1480/// Below this ratio of the trace's ringing power to what the fitted replay leaves of it, a trace is taken not to ring
1481/// above its noise (`fit_move_stiffness`): 1.25 is the replay explaining an RMS of at least half what it leaves,
1482/// ringing² − residual² ≥ (residual / 2)².
1483pub const MOVE_RINGING_RATIO: f64 = 1.25;
1484
1485/// The config key `fit_move_stiffness` scales unless told another: the belts' stiffness, of every belt machine.
1486pub const BELT_STIFFNESS_KEY: &str = "belt.stiffness_ea_n";
1487
1488/// Stage 2 from an ordinary move's trace (`fit_move_stiffness`): the factor on the stiffness and its standard error,
1489/// and the ringing the fit compares, RMS over the motors in N m: in the trace, and what the config's replay with the
1490/// factor leaves of it.
1491#[derive(Debug, Clone, Copy, PartialEq)]
1492pub struct MoveStiffness {
1493    pub factor: f64,
1494    pub error: f64,
1495    pub ringing: f64,
1496    pub residual: f64,
1497}
1498
1499impl MoveStiffness {
1500    /// What to change in the config, as a translation key with its argument.
1501    pub fn advice(&self) -> (&'static str, String) {
1502        ("fit-move-stiffness", format!("× {:.3} ± {:.3}", self.factor, self.error))
1503    }
1504}
1505
1506/// What is left of each motor torque after its mean over 10 ms on either side is taken off: the ringing of the load on
1507/// its springs (12 ms a period at 84 Hz), without the rigid motion (ramps of tens of ms and more), which a wrong mass or
1508/// friction would put in. Rows within the window of either end are left out.
1509fn ringing(trace: &Trace) -> Vec<f64> {
1510    let rows = trace.time.len();
1511    let step = (trace.time[rows - 1] - trace.time[0]) / (rows - 1) as f64;
1512    let w = ((0.01 / step).round() as usize).max(1);
1513    let mut out = Vec::new();
1514    for m in &trace.motors {
1515        out.extend(
1516            (w..rows.saturating_sub(w))
1517                .map(|i| m.torque[i] - m.torque[i - w..=i + w].iter().sum::<f64>() / (2 * w + 1) as f64),
1518        );
1519    }
1520    out
1521}
1522
1523/// Stage 2 from an ordinary move's trace, no sweep: an output-error fit of the stiffness. The config is replayed with
1524/// the value at `key` (the belts' stiffness, `BELT_STIFFNESS_KEY`, or another spring between motor and load) times a
1525/// factor, and the factor is the one whose replay's motor torques ring as the trace's do (`ringing`: least squares over
1526/// every motor and row). The replay has the config's loops, filters, delays and friction, which damp the ringing of a
1527/// move in the trace as they do in the machine, so that they need not be fitted as well; a free two-mass fit of the
1528/// torque took the drive's own lag, at 51 Hz on the belt axis, for the belt. The masses have to be right first (stage
1529/// 1), as for a sweep.
1530///
1531/// The factor is searched from 1/4 to 4: nine replays a factor of 1.41 apart, then a parabola through seven replays
1532/// between the neighbours of the best, and another through seven within ±10 % of its vertex (24 replays in all). Its
1533/// standard error from the curvature 2 a of the last parabola: var(ln factor) = 2 σ² / (2 a), σ² = S / (N − 1) widened
1534/// by (1 + ρ) / (1 − ρ) for the lag-one correlation ρ of the residuals (the ringing of neighbouring rows is not
1535/// independent), plus the variance of the vertex from the points' scatter about the parabola (on a trace without noise
1536/// that is all there is: 0.70 on the belt axis came out 0.681 ± 0.001 without it).
1537///
1538/// Refused with `fit-move-not-excited` where that error is above `MOVE_STIFFNESS_LIMIT` of the factor, the best
1539/// factor lies at an end of the range, or the trace's ringing power is below `MOVE_RINGING_RATIO` times what the
1540/// fitted replay leaves (the standard error alone let a move that rings at its noise level through): the trace's moves did not ring the load enough against its noise (a gentle
1541/// move, a low jerk, a heavily damped mode). With `fit-move-no-key` where the config has no number at `key`.
1542pub fn fit_move_stiffness(
1543    entry: &MachineEntry,
1544    cfg: &Config,
1545    trace: &Trace,
1546    key: &str,
1547) -> Result<MoveStiffness, TraceError> {
1548    let base = cfg.f64(key).map_err(|_| TraceError { key: "fit-move-no-key", detail: key.to_string() })?;
1549    let measured = ringing(trace);
1550    // The replays: 9 on the grid, 7 per parabola (two), and the one at the result.
1551    crate::analysis::plan_steps(9 + 2 * 7 + 1);
1552    let cost = |u: f64| -> Result<(f64, Vec<f64>), TraceError> {
1553        crate::analysis::check_cancelled();
1554        let mut scaled = cfg.clone();
1555        scaled.set_text(&format!("{key} = {:?}", base * u.exp()))?;
1556        let residuals: Vec<f64> =
1557            ringing(&replay(entry, &scaled, trace)?).iter().zip(&measured).map(|(s, m)| m - s).collect();
1558        crate::analysis::step_done();
1559        Ok((residuals.iter().map(|r| r * r).sum(), residuals))
1560    };
1561    let not_excited = |detail: String| TraceError { key: "fit-move-not-excited", detail };
1562    let grid: Vec<f64> = (0..9).map(|i| (i as f64 - 4.0) * 0.5 * std::f64::consts::LN_2).collect();
1563    let costs = grid.iter().map(|&u| cost(u).map(|c| c.0)).collect::<Result<Vec<f64>, _>>()?;
1564    let best = (0..grid.len()).min_by(|&a, &b| costs[a].total_cmp(&costs[b])).unwrap_or(0);
1565    if best == 0 || best + 1 == grid.len() {
1566        return Err(not_excited(format!("× {:.2}", grid[best].exp())));
1567    }
1568    // Parabolas through evenly spaced replays, not golden sections: the sum of squares is jagged on a small scale (a belt
1569    // tooth or the gearbox's play meets a little earlier or later), which a parabola through several points averages
1570    // over. First between the grid's neighbours of its best point, then ±0.1 about that vertex.
1571    // Vertex, curvature (twice the square term) and the vertex's standard error from how far the points scatter about
1572    // the parabola: σ_p² (AᵀA)⁻¹ for the linear term over twice the square term, squared.
1573    let parabola = |from: f64, to: f64| -> Result<Option<(f64, f64, f64)>, TraceError> {
1574        let mid = 0.5 * (from + to);
1575        let points = (0..7)
1576            .map(|i| from + (to - from) * i as f64 / 6.0)
1577            .map(|u| cost(u).map(|c| (u - mid, c.0)))
1578            .collect::<Result<Vec<_>, _>>()?;
1579        let (mut a, mut b) = (vec![0.0; 9], vec![0.0; 3]);
1580        for (x, c) in &points {
1581            let row = [1.0, *x, x * x];
1582            for r in 0..3 {
1583                b[r] += row[r] * c;
1584                (0..3).for_each(|k| a[3 * r + k] += row[r] * row[k]);
1585            }
1586        }
1587        let Some(v) = crate::chain::solve(&a, &b).filter(|v| v[2] > 0.0) else { return Ok(None) };
1588        let scatter = points.iter().map(|(x, c)| (c - v[0] - v[1] * x - v[2] * x * x).powi(2)).sum::<f64>()
1589            / (points.len() - 3) as f64;
1590        let linear = crate::chain::solve(&a, &[0.0, 1.0, 0.0]).map_or(f64::INFINITY, |column| column[1]);
1591        Ok(Some(((mid - 0.5 * v[1] / v[2]).clamp(from, to), 2.0 * v[2], (scatter * linear).sqrt() / (2.0 * v[2]))))
1592    };
1593    let curved =
1594        |found: Option<(f64, f64, f64)>| found.ok_or_else(|| not_excited(format!("× {:.2} ± inf", grid[best].exp())));
1595    let (first, ..) = curved(parabola(grid[best - 1], grid[best + 1])?)?;
1596    let (u, curvature, jagged) = curved(parabola(first - 0.1, first + 0.1)?)?;
1597    let (s, residuals) = cost(u)?;
1598    let rho = (residuals.windows(2).map(|w| w[0] * w[1]).sum::<f64>() / s.max(f64::MIN_POSITIVE)).clamp(0.0, 0.98);
1599    let variance = s / (residuals.len() - 1) as f64 * (1.0 + rho) / (1.0 - rho);
1600    let factor = u.exp();
1601    let error = factor * (2.0 * variance / curvature + jagged * jagged).sqrt();
1602    let rms = |x: &[f64]| (x.iter().map(|v| v * v).sum::<f64>() / x.len().max(1) as f64).sqrt();
1603    let (ringing, residual) = (rms(&measured), rms(&residuals));
1604    if !(error <= MOVE_STIFFNESS_LIMIT * factor && ringing * ringing >= MOVE_RINGING_RATIO * residual * residual) {
1605        return Err(not_excited(format!("× {factor:.2} ± {error:.2}")));
1606    }
1607    Ok(MoveStiffness { factor, error, ringing, residual })
1608}
1609
1610#[cfg(test)]
1611mod tests {
1612    use super::*;
1613
1614    /// The dip of a response with a known resonance: gain * f = |fa^2 - f^2 + 2 j d fa f| has its lowest
1615    /// point at fa and twice that power where f^2 = fa^2 (1 -+ 2 d).
1616    #[test]
1617    fn resonance_reads_frequency_and_damping_off_a_known_dip() {
1618        let (fa, d) = (80.0f64, 0.05);
1619        let sweep: Vec<SweepPoint> = crate::analysis::log_spaced(50.0, 130.0, 60)
1620            .into_iter()
1621            .map(|f| SweepPoint { frequency: f, gain: (fa * fa - f * f).hypot(2.0 * d * fa * f) / f, phase_deg: 0.0 })
1622            .collect();
1623        let found = resonance(&sweep).unwrap();
1624        assert!((found.frequency - fa).abs() < found.frequency_error && found.frequency_error < 0.01 * fa, "{found:?}");
1625        assert!((found.damping - d).abs() < 0.05 * d, "{found:?}");
1626        // Half a dip is none.
1627        assert_eq!(resonance(&sweep[..25]), None);
1628        // From high to low frequency, the same dip. The damping came out negative.
1629        let falling: Vec<SweepPoint> = sweep.iter().rev().copied().collect();
1630        assert_eq!(resonance(&falling), Some(found));
1631    }
1632
1633    /// Of two dips the lowest in frequency is reported, also where the one above it is deeper: the first default machine's
1634    /// dips at 22 and 62 Hz are about as deep, and which was the deepest changed with the amplitude and the
1635    /// stiffness, so a fit could compare the config's one dip with the other one measured.
1636    #[test]
1637    fn of_two_dips_the_lowest_in_frequency_is_reported() {
1638        let dip = |f: f64, fa: f64, d: f64| (fa * fa - f * f).hypot(2.0 * d * fa * f) / (fa * fa);
1639        let sweep: Vec<SweepPoint> = crate::analysis::log_spaced(10.0, 200.0, 200)
1640            .into_iter()
1641            .map(|f| SweepPoint {
1642                frequency: f,
1643                gain: 1000.0 * dip(f, 22.0, 0.05).min(1.0) * dip(f, 62.0, 0.01).min(1.0) / f,
1644                phase_deg: 0.0,
1645            })
1646            .collect();
1647        // The dip at 62 Hz goes down to 0.02, the one at 22 Hz to 0.1.
1648        let found = resonance(&sweep).unwrap();
1649        assert!((found.frequency - 22.0).abs() < 0.5 && (found.damping - 0.05).abs() < 0.01, "{found:?}");
1650    }
1651
1652    /// Measured, the ISW ball screw bench (datasets/isw-ball-screw-axis, CC BY 4.0), at the motor (rad through the lead
1653    /// of 0.04 m), against the same estimates worked out by hand from the CSV (numpy, rows as stated):
1654    /// - held: the S-profile's rows 5000 to 6219; its top speed there 33.58 rad/s, at rest (the 11-row mean within 1 %)
1655    ///   from 5.214 s to the end; its torque after the first 0.1 s of that, 901 rows, averages -1.44440 N m.
1656    /// - presliding: the sine's rows 2300 to 7800 with mass 0.0199 kg m², Coulomb 2.0 N m, no constant: the reversals at
1657    ///   2.503 s and 7.504 s, the friction through zero 1.0797e-3 and 1.0625e-3 rad on, so sigma = 2.0 ln 2 / x = 1284.0
1658    ///   and 1304.7 N m/rad (3.2e7 N/m at the table); the median of two the upper, 1304.7, its error
1659    ///   1.25 * 20.7 / sqrt 2 = 18.3. One reversal alone (rows 2300 to 2800) gives no row: no error.
1660    /// - breakaway: the sine's rows 1000 to 19000, the same values: 262 rows between 1 % and 5 % of the top speed
1661    ///   (9.962 rad/s) slowing down average 1.63760 N m, below the Coulomb level: the linear drive's force at the ends of
1662    ///   the sine (-75 N at 350 mm, +67 N at 150 mm; docs/validation.md) is not in the torque's model.
1663    #[test]
1664    fn held_force_breakaway_and_presliding_of_the_measured_ball_screw() {
1665        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../datasets/isw-ball-screw-axis/");
1666        let read = |name: &str| std::fs::read_to_string(format!("{dir}{name}")).unwrap();
1667        let mapping = crate::import::Mapping::parse(&read("map.toml")).unwrap();
1668        let rows_of = |name: &str, rows: std::ops::Range<usize>, rigid: [f64; 4]| {
1669            let trace = crate::import::import(&read(name), &mapping).unwrap().trace;
1670            let m = &trace.motors[0];
1671            let r = rows.clone();
1672            friction_details(&trace.time[r.clone()], &m.torque[r.clone()], &m.speed[r.clone()], &m.angle[r], &rigid)
1673        };
1674        // The map shifts the setpoint by a row (time_offset_s), the import then starts 1 ms in: row i of the file is row
1675        // i - 1 here.
1676        let [held, ..] = rows_of("s-profile-v300.csv", 4999..6219, [0.0; 4]);
1677        let (value, error) = held.unwrap();
1678        // Its standard error, 0.037 N m, is mostly the integrator unwinding slowly (-1.70 to -1.53 N m) against the friction.
1679        assert!((value + 1.44440).abs() < 1e-4 && error > 0.0 && error < 0.05, "{value} {error}");
1680        let [_, _, presliding] = rows_of("sine-a100-v100.csv", 2299..7799, [0.0199, 0.0, 2.0, 0.0]);
1681        let (value, error) = presliding.unwrap();
1682        assert!((value - 1304.7).abs() < 2.5 && (error - 18.3).abs() < 3.0, "{value} {error}");
1683        let [_, _, one] = rows_of("sine-a100-v100.csv", 2299..2799, [0.0199, 0.0, 2.0, 0.0]);
1684        assert_eq!(one, None);
1685        let [_, breakaway, _] = rows_of("sine-a100-v100.csv", 999..18999, [0.0199, 0.0, 2.0, 0.0]);
1686        let (value, error) = breakaway.unwrap();
1687        // The import resamples onto its own grid (from + i step), a little off the file's times: 1e-3 here, 2.5 and 3
1688        // above (1303.2 +- 16.5 against 1304.7 +- 18.3 by hand).
1689        assert!((value - 1.63760).abs() < 1e-3 && error < 0.05, "{value} {error}");
1690    }
1691
1692    /// Measured: the ISW ball screw bench (datasets/isw-ball-screw-axis, CC BY 4.0) at 0.1 m/s out and back, 5 s each
1693    /// side of the reversal. At one speed each way viscous and Coulomb friction are one value: the viscous column's
1694    /// inflation is 279 here (223 on the whole file, 16 on the S-profile), so viscous is left out and Coulomb holds
1695    /// both. Hand calculation from the rows at full speed (|v| > 0.099 m/s): mean torque 2.8292 N m out, -2.6337 N m
1696    /// back, so
1697    /// Coulomb (with the viscous share) (2.8292 + 2.6337) / 2 = 2.7314 N m and constant (2.8292 - 2.6337) / 2 = 0.0977
1698    /// N m. Before, viscous was fitted from the ramps alone, and on the whole file the fit advised a factor of -8.6.
1699    #[test]
1700    fn at_one_speed_each_way_viscous_friction_is_left_in_the_coulomb_value() {
1701        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../datasets/isw-ball-screw-axis/");
1702        let read = |name: &str| std::fs::read_to_string(format!("{dir}{name}")).unwrap();
1703        let mapping = crate::import::Mapping::parse(&read("map.toml")).unwrap();
1704        let trace = crate::import::import(&read("constant-speed-v100.csv"), &mapping).unwrap().trace;
1705        let rows = 2000..12000;
1706        let motor = &trace.motors[0];
1707        let (h, per) = smoothing(&trace.time[rows.clone()], RIGID_SPAN_S);
1708        let samples = rigid_samples(
1709            &trace.time[rows.clone()],
1710            &motor.torque[rows.clone()],
1711            &motor.speed[rows.clone()],
1712            &motor.angle[rows],
1713            &[],
1714            h,
1715        );
1716        let fit = rigid_values(&samples, per, None).unwrap();
1717        let (values, errors) = (fit.values, fit.errors);
1718        assert!(values[1].is_nan() && errors[1].is_nan(), "{values:?}");
1719        assert!((values[2] - 2.7314).abs() < 0.03 * 2.7314, "{values:?} {errors:?}");
1720        assert!((values[3] - 0.0977).abs() < 0.02, "{values:?} {errors:?}");
1721        let fit = AxisFit {
1722            config: values.clone().try_into().unwrap(),
1723            fitted: values.try_into().unwrap(),
1724            error: [0.0; 4],
1725            mass_spread: 0.0,
1726            payload_steps: Vec::new(),
1727            details: Vec::new(),
1728            units: fit_units("m"),
1729        };
1730        assert!(fit.advice("x").iter().all(|(key, _)| *key != "fit-viscous"));
1731    }
1732
1733    /// A sine of 0.1 m at 1 Hz (4 s, 1 ms rows) on a 2 kg axis: F = 2 x'' + 0.5 x' + 1 sign(x') + 0.3 N from the exact
1734    /// travel, while the speed column carries noise of ±0.05 m/s (10 % of the top speed 0.628 m/s). The acceleration comes
1735    /// from the travel's second difference, so the mass is 2.0 whatever the speed column's noise (from the speed's slope
1736    /// it came out some 15 % low on a measured sine). `difference_share`: the same residual twice leaves no more than
1737    /// `REPEATABILITY` of the band, a replay residual of zero the whole band (factor 1).
1738    #[test]
1739    fn the_mass_comes_from_the_travel_and_not_from_a_noisy_speed() {
1740        let rows = 4000;
1741        let time: Vec<f64> = (0..rows).map(|i| i as f64 * 1e-3).collect();
1742        let w = 2.0 * std::f64::consts::PI;
1743        let travel: Vec<f64> = time.iter().map(|t| 0.1 * (w * t).sin()).collect();
1744        let noise = |i: usize| 0.05 * (((i * 7919) % 13) as f64 - 6.0) / 6.0;
1745        let speed: Vec<f64> = time.iter().enumerate().map(|(i, t)| 0.1 * w * (w * t).cos() + noise(i)).collect();
1746        let force: Vec<f64> = time
1747            .iter()
1748            .map(|t| {
1749                let v = 0.1 * w * (w * t).cos();
1750                2.0 * -0.1 * w * w * (w * t).sin() + 0.5 * v + v.signum() + 0.3
1751            })
1752            .collect();
1753        let (h, per) = smoothing(&time, SMOOTHING_S);
1754        let fit = rigid_values(&rigid_samples(&time, &force, &speed, &travel, &[], h), per, None).unwrap();
1755        assert!((fit.values[0] - 2.0).abs() < 0.02, "{:?}", fit.values);
1756        assert_eq!(difference_share(&fit.residuals, &fit.residuals), REPEATABILITY);
1757        assert_eq!(difference_share(&fit.residuals, &vec![0.0; fit.residuals.len()]), 1.0);
1758        assert_eq!(fit_units("rad")[0], "kg m²");
1759    }
1760}