Skip to main content

sim_components/
motor_fit.rs

1//! Identification that needs no machine model: one motor's drive train from its own trace, in the motor's
2//! units (rad, rad/s, N m at the shaft). So it works on any imported drive trace, also of a machine the
3//! simulator has no config for.
4//!
5//! - Inertia and friction: torque = J α + b ω + (Tc + (Ts - Tc) e^-(ω/ωs)²) sign ω + T0, with the Stribeck
6//!   part kept only where the trace shows it, and the LuGre bristle stiffness σ0 from the reversals.
7//! - Drive delays and filters (the fit's stage 3): a gain, a first-order lag and a dead time between a
8//!   setpoint and what follows it (torque setpoint to torque, position setpoint to position).
9//! - Stiffness and damping between motor and load, as a two-mass model: from a frequency response (measured
10//!   by the drive, or computed here from a trace with an excitation), or from the ringing after a torque step.
11//!
12//! Every value comes with a standard error from the least-squares covariance, widened for residuals that
13//! are correlated from row to row; `Estimate::interval` is the 95 % interval from it. Every model says how
14//! well it reproduces the trace (`Quality`).
15
16use crate::analysis::SweepPoint;
17use crate::identify::{Resonance, resonance};
18use std::f64::consts::TAU;
19
20/// A fitted value and its standard error.
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Estimate {
23    pub value: f64,
24    pub error: f64,
25}
26
27impl Estimate {
28    /// The 95 % confidence interval, value ± 1.96 standard errors.
29    pub fn interval(&self) -> (f64, f64) {
30        (self.value - 1.96 * self.error, self.value + 1.96 * self.error)
31    }
32}
33
34/// How well a model reproduces a measured signal: RMS of the difference, and the normalised fit
35/// 100 % × (1 - |measured - model| / |measured - mean|): 100 % is exact, 0 % no better than the mean.
36#[derive(Debug, Clone, Copy, PartialEq)]
37pub struct Quality {
38    pub rms: f64,
39    pub fit_percent: f64,
40}
41
42pub fn quality(measured: &[f64], model: &[f64]) -> Quality {
43    let n = measured.len().max(1) as f64;
44    let mean = measured.iter().sum::<f64>() / n;
45    let off: f64 = measured.iter().zip(model).map(|(m, s)| (m - s).powi(2)).sum();
46    let spread: f64 = measured.iter().map(|m| (m - mean).powi(2)).sum();
47    Quality { rms: (off / n).sqrt(), fit_percent: 100.0 * (1.0 - (off / spread.max(f64::MIN_POSITIVE)).sqrt()) }
48}
49
50/// Solves a x = b by elimination with partial pivoting; `None` where `a` is (nearly) singular.
51fn solve(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
52    let n = b.len();
53    let size = a.iter().flatten().fold(0.0, |m: f64, v| m.max(v.abs()));
54    for col in 0..n {
55        let pivot = (col..n).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs()))?;
56        if !(a[pivot][col].abs() > 1e-12 * size) {
57            return None;
58        }
59        a.swap(col, pivot);
60        b.swap(col, pivot);
61        for row in col + 1..n {
62            let f = a[row][col] / a[col][col];
63            for j in col..n {
64                a[row][j] -= f * a[col][j];
65            }
66            b[row] -= f * b[col];
67        }
68    }
69    let mut x = vec![0.0; n];
70    for row in (0..n).rev() {
71        x[row] = (b[row] - (row + 1..n).map(|j| a[row][j] * x[j]).sum::<f64>()) / a[row][row];
72    }
73    Some(x)
74}
75
76/// Solves a x = b for a symmetric positive (semi)definite `a` whose diagonal spans many decades, by
77/// solving the system scaled to a unit diagonal.
78fn solve_scaled(a: &[Vec<f64>], b: &[f64]) -> Option<Vec<f64>> {
79    let d: Vec<f64> = (0..b.len()).map(|i| a[i][i].max(f64::MIN_POSITIVE).sqrt()).collect();
80    let scaled = (0..b.len()).map(|i| (0..b.len()).map(|j| a[i][j] / (d[i] * d[j])).collect()).collect();
81    let x = solve(scaled, b.iter().zip(&d).map(|(b, d)| b / d).collect())?;
82    Some(x.iter().zip(&d).map(|(x, d)| x / d).collect())
83}
84
85/// A least-squares fit: the values, their standard errors and the residuals at the values.
86struct Fitted {
87    values: Vec<f64>,
88    errors: Vec<f64>,
89    residuals: Vec<f64>,
90}
91
92/// Levenberg-Marquardt on `residuals` from `start`, with a numeric Jacobian whose steps are 1e-6 of
93/// `scale` (the size each value is expected to have). The covariance is σ² (JᵀJ)⁻¹, with σ² widened by
94/// (1 + ρ) / (1 - ρ) for a lag-one correlation ρ of the residuals: rows of a filtered trace are not
95/// independent measurements. `None` where the values cannot be told apart (singular normal equations).
96fn least_squares(start: &[f64], scale: &[f64], residuals: &dyn Fn(&[f64]) -> Vec<f64>) -> Option<Fitted> {
97    let n = start.len();
98    let cost = |r: &[f64]| r.iter().map(|v| v * v).sum::<f64>();
99    let mut p = start.to_vec();
100    let mut r = residuals(&p);
101    let mut c = cost(&r);
102    if !c.is_finite() || r.len() <= n {
103        return None;
104    }
105    let jacobian = |p: &[f64], r: &[f64]| -> Vec<Vec<f64>> {
106        (0..n)
107            .map(|j| {
108                let h = 1e-6 * scale[j];
109                let mut q = p.to_vec();
110                q[j] += h;
111                residuals(&q).iter().zip(r).map(|(a, b)| (a - b) / h).collect()
112            })
113            .collect()
114    };
115    let normal = |jac: &[Vec<f64>]| -> Vec<Vec<f64>> {
116        (0..n).map(|a| (0..n).map(|b| jac[a].iter().zip(&jac[b]).map(|(x, y)| x * y).sum()).collect()).collect()
117    };
118    let mut lambda = 1e-3;
119    for _ in 0..200 {
120        let jac = jacobian(&p, &r);
121        let a = normal(&jac);
122        let g: Vec<f64> = jac.iter().map(|col| -col.iter().zip(&r).map(|(x, y)| x * y).sum::<f64>()).collect();
123        let mut improved = false;
124        while lambda < 1e12 {
125            let mut damped = a.clone();
126            (0..n).for_each(|i| damped[i][i] += lambda * a[i][i].max(1e-300));
127            let Some(step) = solve_scaled(&damped, &g) else {
128                lambda *= 10.0;
129                continue;
130            };
131            let q: Vec<f64> = p.iter().zip(&step).map(|(a, b)| a + b).collect();
132            let rq = residuals(&q);
133            let cq = cost(&rq);
134            if cq.is_finite() && cq < c {
135                let done = c - cq < 1e-12 * c;
136                (p, r, c) = (q, rq, cq);
137                lambda = (lambda / 3.0).max(1e-12);
138                improved = !done;
139                break;
140            }
141            lambda *= 4.0;
142        }
143        if !improved {
144            break;
145        }
146    }
147    let a = normal(&jacobian(&p, &r));
148    let m = r.len();
149    let rho = (r.windows(2).map(|w| w[0] * w[1]).sum::<f64>() / c.max(f64::MIN_POSITIVE)).clamp(0.0, 0.98);
150    let variance = c / (m - n) as f64 * (1.0 + rho) / (1.0 - rho);
151    let errors = (0..n)
152        .map(|j| {
153            let unit: Vec<f64> = (0..n).map(|i| if i == j { 1.0 } else { 0.0 }).collect();
154            solve_scaled(&a, &unit).map(|column| (variance * column[j]).max(0.0).sqrt())
155        })
156        .collect::<Option<Vec<f64>>>()?;
157    Some(Fitted { values: p, errors, residuals: r })
158}
159
160/// The standard error of `f(values)` by first-order propagation of independent errors.
161fn propagate(f: &dyn Fn(&[f64]) -> f64, inputs: &[Estimate]) -> Estimate {
162    let values: Vec<f64> = inputs.iter().map(|e| e.value).collect();
163    let value = f(&values);
164    let error = (0..inputs.len())
165        .map(|i| {
166            let mut shifted = values.clone();
167            shifted[i] += inputs[i].error;
168            (f(&shifted) - value).powi(2)
169        })
170        .sum::<f64>()
171        .sqrt();
172    Estimate { value, error }
173}
174
175/// Rows on either side that a smoothing window spans: 5 ms, at least one row and at most the trace. `None` where
176/// the times do not rise (a zero step made the window `usize::MAX` rows and `2 w + 1` overflowed).
177fn half_window(time: &[f64]) -> Option<usize> {
178    if time.windows(2).any(|p| !(p[1] > p[0])) {
179        return None;
180    }
181    let step = (time[time.len() - 1] - time[0]) / (time.len() - 1) as f64;
182    Some(((0.005 / step).round() as usize).clamp(1, time.len()))
183}
184
185/// Inertia and friction of one motor's drive train, at the motor shaft.
186#[derive(Debug, Clone, PartialEq)]
187pub struct Friction {
188    /// Total inertia: rotor, couplings, gearbox and the load reflected to the motor. kg m².
189    pub inertia: Estimate,
190    /// N m s/rad.
191    pub viscous: Estimate,
192    /// Sliding (Coulomb) friction, N m.
193    pub coulomb: Estimate,
194    /// Breakaway torque and the Stribeck speed (rad/s) of the drop to Coulomb friction; `None` where the
195    /// trace does not show a drop that is clearly above its noise.
196    pub stiction: Option<Estimate>,
197    pub stribeck_speed: Option<Estimate>,
198    /// A torque that does not depend on the motion: weight on a vertical axis, a cable pull. N m.
199    pub constant: Estimate,
200    /// LuGre bristle stiffness σ0 from the reversals (N m/rad); `None` with fewer than three reversals whose
201    /// presliding the trace resolves (a fast reversal crosses it within a row: see the measurement procedure).
202    pub presliding_stiffness: Option<Estimate>,
203    /// The model against the smoothed measured torque on the rows used.
204    pub quality: Quality,
205    /// The model's torque per row of the trace (from the smoothed speed and acceleration).
206    pub model: Vec<f64>,
207}
208
209/// Inertia and friction from a trace's speed and torque at one motor (`angle` for the presliding).
210/// Speed and torque are averaged over 5 ms on either side, the acceleration is the slope of the speed across
211/// that window. Rows slower than 1 % of the top speed are left out, and so are rows whose window has a reversal. `None` if the motor does not turn both
212/// ways (Coulomb friction and a constant torque cannot be told apart then) or the trace is too short.
213pub fn friction(time: &[f64], angle: &[f64], speed: &[f64], torque: &[f64]) -> Option<Friction> {
214    let rows = time.len();
215    if rows < 20 {
216        return None;
217    }
218    let w = half_window(time)?;
219    let top = speed.iter().fold(0.0, |a: f64, b| a.max(b.abs()));
220    let mean = |x: &[f64], i: usize| x[i - w..=i + w].iter().sum::<f64>() / (2 * w + 1) as f64;
221    let mut smooth = vec![(0.0, 0.0, 0.0); rows];
222    for i in w..rows.saturating_sub(w) {
223        smooth[i] = (mean(speed, i), (speed[i + w] - speed[i - w]) / (time[i + w] - time[i - w]), mean(torque, i));
224    }
225    // A row whose window spans a reversal would average the two Coulomb levels: only windows of one sign.
226    let used: Vec<usize> = (w..rows.saturating_sub(w))
227        .filter(|&i| {
228            smooth[i].0.abs() > 0.01 * top && speed[i - w..=i + w].iter().all(|v| v.signum() == smooth[i].0.signum())
229        })
230        .collect();
231    let one_way = |sign: f64| used.iter().filter(|&&i| smooth[i].0.signum() == sign).count();
232    if one_way(1.0).min(one_way(-1.0)) < 10 * (2 * w + 1) {
233        return None;
234    }
235    let stribeck = |p: &[f64], v: f64, a: f64| {
236        p[0] * a + p[1] * v + (p[2] + p.get(4).map_or(0.0, |ds| ds * (-(v / p[5]).powi(2)).exp())) * v.signum() + p[3]
237    };
238    let residuals =
239        |p: &[f64]| -> Vec<f64> { used.iter().map(|&i| stribeck(p, smooth[i].0, smooth[i].1) - smooth[i].2).collect() };
240    let level = torque.iter().fold(0.0, |a: f64, b| a.max(b.abs())).max(1e-9);
241    let accel = used.iter().fold(0.0, |a: f64, &i| a.max(smooth[i].1.abs())).max(1e-9);
242    let scale = [level / accel, level / top, level, level, level, top];
243    let plain = least_squares(&[0.0; 4], &scale[..4], &residuals)?;
244    // Stribeck: started from the plain fit with a drop of a fifth of the Coulomb friction at 5 % of top speed.
245    let p = &plain.values;
246    let start = [p[0], p[1], p[2], p[3], 0.2 * p[2].abs(), 0.05 * top];
247    let curved = least_squares(&start, &scale, &residuals);
248    let curved = curved.filter(|f| {
249        let (drop, speed) = ((f.values[4], f.errors[4]), (f.values[5].abs(), f.errors[5]));
250        // Kept only where the drop is real and the speed it happens at is known to better than half and lies
251        // inside what the trace covers.
252        let rss = |r: &[f64]| r.iter().map(|v| v * v).sum::<f64>();
253        drop.0 > 3.0 * drop.1 && speed.1 < 0.5 * speed.0 && speed.0 < top && rss(&f.residuals) < rss(&plain.residuals)
254    });
255    let fit = curved.as_ref().unwrap_or(&plain);
256    let at = |q: usize| Estimate { value: fit.values[q], error: fit.errors[q] };
257    let model: Vec<f64> = smooth.iter().map(|&(v, a, _)| stribeck(&fit.values, v, a)).collect();
258    let measured: Vec<f64> = used.iter().map(|&i| smooth[i].2).collect();
259    let modelled: Vec<f64> = used.iter().map(|&i| model[i]).collect();
260    let coulomb = at(2);
261    let presliding = presliding(time, angle, speed, torque, &smooth, w, &fit.values, coulomb.value, 0.01 * top);
262    Some(Friction {
263        inertia: at(0),
264        viscous: at(1),
265        coulomb,
266        stiction: curved
267            .as_ref()
268            .map(|f| propagate(&|v| v[0] + v[1], &[at(2), Estimate { value: f.values[4], error: f.errors[4] }])),
269        stribeck_speed: curved.as_ref().map(|f| Estimate { value: f.values[5].abs(), error: f.errors[5] }),
270        constant: at(3),
271        presliding_stiffness: presliding,
272        quality: quality(&measured, &modelled),
273        model,
274    })
275}
276
277/// σ0 from the reversals: after the smoothed speed changes sign, friction (torque less inertia and constant
278/// torque) swings from one sliding level to the other over a small angle. In the LuGre model the slope of
279/// friction over angle is σ0 (1 - F / g): twice σ0 at the turning point and σ0 where friction passes zero.
280/// So the slope is taken over the middle half of the swing, |F| < Tc / 2, per reversal whose swing ends
281/// within 0.5 s while the speed stays below `slow` (else it is a fast reversal, where the swing is the
282/// loops' doing) and covers at least four rows; the median of them, with their spread as its error.
283#[allow(clippy::too_many_arguments)]
284fn presliding(
285    time: &[f64],
286    angle: &[f64],
287    speed: &[f64],
288    torque: &[f64],
289    smooth: &[(f64, f64, f64)],
290    w: usize,
291    p: &[f64],
292    coulomb: f64,
293    slow: f64,
294) -> Option<Estimate> {
295    let rows = time.len();
296    let half = 0.5 * coulomb.abs();
297    let mut slopes = Vec::new();
298    for i in w + 1..rows.saturating_sub(w) {
299        let (before, after) = (smooth[i - 1].0, smooth[i].0);
300        if before == 0.0 || after == 0.0 || before.signum() == after.signum() {
301            continue;
302        }
303        let sign = after.signum();
304        // The turning point: the raw row nearest the sign change of the smoothed speed.
305        let start = (i - w..i + w).min_by(|&a, &b| speed[a].abs().total_cmp(&speed[b].abs()))?;
306        let friction = |k: usize| sign * (torque[k] - p[0] * smooth[k].1 - p[3]);
307        let mut points = Vec::new();
308        let mut ended = false;
309        for k in start..rows - w {
310            if time[k] - time[start] > 0.5 || speed[k].abs() > slow {
311                break;
312            }
313            let f = friction(k);
314            if f > half {
315                ended = true;
316                break;
317            }
318            if f >= -half {
319                points.push((sign * angle[k], f));
320            }
321        }
322        if !ended || points.len() < 4 {
323            continue;
324        }
325        let n = points.len() as f64;
326        let (mx, my) = (points.iter().map(|p| p.0).sum::<f64>() / n, points.iter().map(|p| p.1).sum::<f64>() / n);
327        let sxx: f64 = points.iter().map(|p| (p.0 - mx).powi(2)).sum();
328        let sxy: f64 = points.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum();
329        if sxx > 0.0 && sxy > 0.0 {
330            slopes.push(sxy / sxx);
331        }
332    }
333    if slopes.len() < 3 {
334        return None;
335    }
336    slopes.sort_by(f64::total_cmp);
337    let median = slopes[slopes.len() / 2];
338    let spread = (slopes.iter().map(|s| (s - median).powi(2)).sum::<f64>() / (slopes.len() - 1) as f64).sqrt();
339    Some(Estimate { value: median, error: 1.25 * spread / (slopes.len() as f64).sqrt() })
340}
341
342/// A setpoint and what follows it, as gain × first-order lag × dead time: the drive's loops, filters and
343/// bus delays lumped together (stage 3 of the fit).
344#[derive(Debug, Clone, PartialEq)]
345pub struct Lag {
346    pub gain: Estimate,
347    /// s.
348    pub time_constant: Estimate,
349    /// s. Below zero where the output leads the setpoint: the two signals' times are misaligned.
350    pub dead_time: Estimate,
351    /// The model against the measured output, and against the measured difference setpoint - output
352    /// (the following error, which says more where the output follows closely).
353    pub quality: Quality,
354    pub error_quality: Quality,
355    pub model: Vec<f64>,
356}
357
358/// The output of the lag model for an input, starting where the measured output starts and at rest. The
359/// input is held from one row to the next, as a drive holds a setpoint for its cycle; delayed by a dead time
360/// that is not a whole number of rows it changes once within a step, and both parts are solved exactly.
361/// Rows have to be evenly spaced.
362fn lag_response(time: &[f64], input: &[f64], output0: f64, gain: f64, tau: f64, dead: f64) -> Vec<f64> {
363    let (rows, start) = (time.len(), time[0]);
364    let step = (time[rows - 1] - start) / (rows - 1) as f64;
365    // The held input at a time, and the time it changes next.
366    let held = |t: f64| -> (f64, f64) {
367        let k = ((t - start) / step).floor();
368        let value = if k < 0.0 { input[0] } else { input[(k as usize).min(rows - 1)] };
369        (value, start + (k + 1.0) * step)
370    };
371    let mut out = vec![output0; rows];
372    for k in 1..rows {
373        let (from, to) = (time[k - 1] - dead, time[k] - dead);
374        let (first, change) = held(from + 1e-9 * step);
375        let mut y = out[k - 1];
376        let mut go = |value: f64, span: f64| {
377            let a = (-span.max(0.0) / tau).exp();
378            y = a * y + (1.0 - a) * (output0 + gain * (value - input[0]));
379        };
380        if change < to {
381            go(first, change - from);
382            go(held(change + 1e-9 * step).0, to - change);
383        } else {
384            go(first, to - from);
385        }
386        out[k] = y;
387    }
388    out
389}
390
391/// The input, linear between rows, delayed by `dead`, times `gain`, from where the output starts.
392fn delayed(time: &[f64], input: &[f64], output0: f64, gain: f64, dead: f64) -> Vec<f64> {
393    time.iter()
394        .map(|&t| {
395            let k = time.partition_point(|&x| x <= t - dead).clamp(1, time.len() - 1);
396            let share = ((t - dead - time[k - 1]) / (time[k] - time[k - 1])).clamp(0.0, 1.0);
397            output0 + gain * (input[k - 1] + share * (input[k] - input[k - 1]) - input[0])
398        })
399        .collect()
400}
401
402/// Fits gain, lag and dead time from `input` (a setpoint) to `output`. The trace has to start at rest.
403/// The start is the best point of a grid (dead time 0 to 20 rows, time constant 0 and 1 to 100 rows). A
404/// time constant the trace cannot resolve (shorter than a fraction of a row, or a following error too small
405/// to show it) is reported as 0 ± one row, and gain and dead time are fitted without it.
406pub fn lag(time: &[f64], input: &[f64], output: &[f64]) -> Option<Lag> {
407    let rows = time.len();
408    if rows < 20 {
409        return None;
410    }
411    let step = (time[rows - 1] - time[0]) / (rows - 1) as f64;
412    // The output at rest is fitted too ([gain, ln τ, dead time, rest]): one noisy first sample would bias all.
413    let span =
414        output.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b)) - output.iter().fold(f64::INFINITY, |a, &b| a.min(b));
415    let rest = output[..rows.min(5)].iter().sum::<f64>() / rows.min(5) as f64;
416    let residuals = |p: &[f64]| -> Vec<f64> {
417        lag_response(time, input, p[3], p[0], p[1].exp(), p[2]).iter().zip(output).map(|(m, y)| m - y).collect()
418    };
419    let cost = |p: &[f64]| residuals(p).iter().map(|v| v * v).sum::<f64>();
420    let none = (1e-6 * step).ln();
421    let mut best = (f64::INFINITY, [1.0, step.ln(), 0.0, rest]);
422    for d in 0..=20 {
423        for t in 0..=21 {
424            let tau = if t == 21 { none } else { (step * 100f64.powf(t as f64 / 20.0)).ln() };
425            let p = [1.0, tau, d as f64 * step, rest];
426            let c = cost(&p);
427            if c < best.0 {
428                best = (c, p);
429            }
430        }
431    }
432    // Resolved: the log of the time constant known to better than a factor e.
433    let scale = [1.0, 1.0, step, span.max(1e-12)];
434    let resolved = least_squares(&best.1, &scale, &residuals).filter(|f| f.errors[1] < 1.0 && f.values[1] > none + 1.0);
435    let (gain, tau, dead, rest) = match resolved {
436        Some(f) => {
437            let tau = f.values[1].exp();
438            (
439                Estimate { value: f.values[0], error: f.errors[0] },
440                Estimate { value: tau, error: tau * f.errors[1] },
441                Estimate { value: f.values[2], error: f.errors[2] },
442                f.values[3],
443            )
444        }
445        // A held input delayed without a lag is a staircase that moves in whole rows, with no slope to fit the
446        // delay on; between rows the input is taken as linear instead.
447        None => {
448            let f = least_squares(&[best.1[0], best.1[2], rest], &[1.0, step, scale[3]], &|p: &[f64]| {
449                delayed(time, input, p[2], p[0], p[1]).iter().zip(output).map(|(m, y)| m - y).collect()
450            })?;
451            (
452                Estimate { value: f.values[0], error: f.errors[0] },
453                Estimate { value: 0.0, error: step },
454                Estimate { value: f.values[1], error: f.errors[1] },
455                f.values[2],
456            )
457        }
458    };
459    let model = match tau.value {
460        0.0 => delayed(time, input, rest, gain.value, dead.value),
461        tau => lag_response(time, input, rest, gain.value, tau, dead.value),
462    };
463    let following = |y: &[f64]| -> Vec<f64> { input.iter().zip(y).map(|(u, y)| u - y).collect() };
464    Some(Lag {
465        gain,
466        time_constant: tau,
467        dead_time: dead,
468        quality: quality(output, &model),
469        error_quality: quality(&following(output), &following(&model)),
470        model,
471    })
472}
473
474/// The frequency response from `input` to `output` of a trace with an excitation in it (noise, a chirp, a
475/// PRBS), at the given frequencies: Welch's H1 estimate over Hann windows with half overlap, each window
476/// long enough for four periods of the lowest frequency. With it the coherence, 0 to 1: below about 0.8
477/// the point is mostly noise or the response is not linear there. `None` for a trace too short for eight
478/// windows: with few windows the coherence of pure noise comes out near 1.
479pub fn frequency_response(
480    time: &[f64],
481    input: &[f64],
482    output: &[f64],
483    frequencies: &[f64],
484) -> Option<Vec<(SweepPoint, f64)>> {
485    let rows = time.len();
486    if rows < 32 || frequencies.is_empty() {
487        return None;
488    }
489    let step = (time[rows - 1] - time[0]) / (rows - 1) as f64;
490    let lowest = frequencies.iter().fold(f64::INFINITY, |a, &b| a.min(b));
491    let length = ((4.0 / (lowest * step)).ceil() as usize).clamp(8, rows);
492    let window: Vec<f64> = (0..length).map(|k| 0.5 - 0.5 * (TAU * k as f64 / length as f64).cos()).collect();
493    let starts: Vec<usize> = (0..).map(|s| s * length / 2).take_while(|s| s + length <= rows).collect();
494    if starts.len() < 8 {
495        return None;
496    }
497    let response = frequencies
498        .iter()
499        .map(|&f| {
500            let (mut pxy, mut pxx, mut pyy) = ((0.0, 0.0), 0.0, 0.0);
501            for &s in &starts {
502                let spectrum = |x: &[f64]| -> (f64, f64) {
503                    let m = x[s..s + length].iter().sum::<f64>() / length as f64;
504                    (0..length).fold((0.0, 0.0), |(re, im), k| {
505                        let (phase, v) = (TAU * f * k as f64 * step, window[k] * (x[s + k] - m));
506                        (re + v * phase.cos(), im - v * phase.sin())
507                    })
508                };
509                let (x, y) = (spectrum(input), spectrum(output));
510                // conj(X) Y
511                pxy = (pxy.0 + x.0 * y.0 + x.1 * y.1, pxy.1 + x.0 * y.1 - x.1 * y.0);
512                pxx += x.0 * x.0 + x.1 * x.1;
513                pyy += y.0 * y.0 + y.1 * y.1;
514            }
515            let gain = pxy.0.hypot(pxy.1) / pxx;
516            let coherence = (pxy.0 * pxy.0 + pxy.1 * pxy.1) / (pxx * pyy);
517            (SweepPoint { frequency: f, gain, phase_deg: pxy.1.atan2(pxy.0).to_degrees() }, coherence)
518        })
519        .collect();
520    Some(response)
521}
522
523/// Motor and load coupled by a spring with damping: the belt or the coupling, at the motor shaft.
524#[derive(Debug, Clone, Copy, PartialEq)]
525pub struct TwoMass {
526    /// kg m².
527    pub total_inertia: Estimate,
528    pub motor_inertia: Estimate,
529    pub load_inertia: Estimate,
530    /// N m/rad and N m s/rad.
531    pub stiffness: Estimate,
532    pub damping: Estimate,
533    /// Hz: where the load swings against the motor (a peak in torque to speed), and where the motor stands
534    /// while the load swings (the dip).
535    pub resonance: Estimate,
536    pub anti_resonance: Estimate,
537}
538
539/// The two-mass model from a frequency response of motor torque to motor speed: the dip (the lowest in
540/// frequency, as `resonance` finds it), the highest peak above it up to five times its frequency, and the
541/// total inertia from the part below a third of the dip (gain = 1 / (J ω) there, corrected for the two
542/// frequencies). Then
543/// J_motor = J (f_dip / f_peak)², J_load = J - J_motor, stiffness = J_load (2π f_dip)², and the damping from
544/// the width of the dip. That is the start for a least-squares fit of the whole model (with a viscous
545/// friction at the motor) through all points, whose values and errors are returned; where that fails, the
546/// values read off the dip and peak.
547/// `None` without a dip, a peak inside the response, or three points below the dip.
548pub fn two_mass(sweep: &[SweepPoint]) -> Option<TwoMass> {
549    let mut sweep = sweep.to_vec();
550    sweep.sort_by(|a, b| a.frequency.total_cmp(&b.frequency));
551    let Resonance { frequency: fa, damping: zeta, frequency_error: fa_error } = resonance(&sweep)?;
552    let level: Vec<f64> = sweep.iter().map(|p| p.gain * p.frequency).collect();
553    let above: Vec<usize> =
554        (0..sweep.len()).filter(|&i| sweep[i].frequency > fa && sweep[i].frequency <= 5.0 * fa).collect();
555    let peak = *above.iter().max_by(|&&a, &&b| level[a].total_cmp(&level[b]))?;
556    if peak == 0 || peak + 1 >= sweep.len() || level[peak] < level[peak - 1] || level[peak] < level[peak + 1] {
557        return None;
558    }
559    // A parabola through the three points in log frequency and log level.
560    let (x, y) = (
561        [peak - 1, peak, peak + 1].map(|i| sweep[i].frequency.ln()),
562        [peak - 1, peak, peak + 1].map(|i| level[i].ln()),
563    );
564    let (d1, d2) = ((y[1] - y[0]) / (x[1] - x[0]), (y[2] - y[1]) / (x[2] - x[1]));
565    let curve = (d2 - d1) / (0.5 * (x[2] - x[0]));
566    let top = if curve < 0.0 { 0.5 * (x[0] + x[1]) - d1 / curve } else { x[1] };
567    let fr = Estimate { value: top.exp(), error: 0.5 * (sweep[peak + 1].frequency - sweep[peak - 1].frequency) / 2.0 };
568    // Below the dip the response is that of the total inertia times (1 - (f/fa)²) / (1 - (f/fr)²) (without
569    // damping), which is taken out.
570    let correction = |f: f64| (1.0 - (f / fa).powi(2)) / (1.0 - (f / fr.value).powi(2));
571    let low: Vec<f64> = sweep
572        .iter()
573        .filter(|p| p.frequency < fa / 3.0)
574        .map(|p| correction(p.frequency) / (TAU * p.gain * p.frequency))
575        .collect();
576    if low.len() < 3 {
577        return None;
578    }
579    let n = low.len() as f64;
580    let mean = low.iter().sum::<f64>() / n;
581    let total =
582        Estimate { value: mean, error: (low.iter().map(|j| (j - mean).powi(2)).sum::<f64>() / (n - 1.0) / n).sqrt() };
583    let fa = Estimate { value: fa, error: fa_error };
584    let inputs = [total, fa, fr, Estimate { value: zeta, error: 0.0 }];
585    let motor = |v: &[f64]| v[0] * (v[1] / v[2]).powi(2);
586    let load = |v: &[f64]| v[0] - motor(v);
587    let stiffness = |v: &[f64]| load(v) * (TAU * v[1]).powi(2);
588    // The dip is the load alone on the spring: its damping ratio is c / (2 sqrt(k J_load)).
589    let damping = |v: &[f64]| 2.0 * v[3] * (stiffness(v) * load(v)).sqrt();
590    let rough = TwoMass {
591        total_inertia: total,
592        motor_inertia: propagate(&motor, &inputs),
593        load_inertia: propagate(&load, &inputs),
594        stiffness: propagate(&stiffness, &inputs),
595        damping: propagate(&damping, &inputs),
596        resonance: fr,
597        anti_resonance: fa,
598    };
599    // Then the whole model through every point, in log gain: total inertia, the motor's share of it,
600    // stiffness, damping, and a viscous friction at the motor that bends the response at low frequencies.
601    // Read off the dip alone, its width also has the slope towards the peak in it.
602    let share = rough.motor_inertia.value / total.value;
603    if !(share > 0.0 && share < 1.0 && rough.damping.value > 0.0) {
604        return Some(rough);
605    }
606    let start = [total.value.ln(), share, rough.stiffness.value.ln(), rough.damping.value.ln(), 0.0];
607    let b_scale = total.value * TAU * sweep[0].frequency;
608    let residuals =
609        |p: &[f64]| -> Vec<f64> { sweep.iter().map(|q| (two_mass_gain(p, q.frequency) / q.gain).ln()).collect() };
610    let Some(fit) = least_squares(&start, &[1.0, 1.0, 1.0, 1.0, b_scale], &residuals) else { return Some(rough) };
611    let at = |q: usize| Estimate { value: fit.values[q], error: fit.errors[q] };
612    let exp = |q: usize| propagate(&|v| v[0].exp(), &[at(q)]);
613    let (j, s, k) = (exp(0), at(1), exp(2));
614    Some(TwoMass {
615        total_inertia: j,
616        motor_inertia: propagate(&|v| v[0] * v[1], &[j, s]),
617        load_inertia: propagate(&|v| v[0] * (1.0 - v[1]), &[j, s]),
618        stiffness: k,
619        damping: exp(3),
620        resonance: propagate(&|v| (v[2] / (v[0] * v[1] * (1.0 - v[1]))).sqrt() / TAU, &[j, s, k]),
621        anti_resonance: propagate(&|v| (v[2] / (v[0] * (1.0 - v[1]))).sqrt() / TAU, &[j, s, k]),
622    })
623}
624
625/// |motor speed / motor torque| of the two-mass model at `f` for [ln J, motor share, ln k, ln c, b]:
626/// 1 / |J_m s + b + D J_l s / (J_l s + D)| with D = c + k / s, s = j 2π f.
627fn two_mass_gain(p: &[f64], f: f64) -> f64 {
628    let (j, w) = (p[0].exp(), TAU * f);
629    let (jm, jl, k, c, b) = (j * p[1], j * (1.0 - p[1]), p[2].exp(), p[3].exp(), p[4]);
630    let mul = |a: (f64, f64), b: (f64, f64)| (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0);
631    let div = |a: (f64, f64), b: (f64, f64)| {
632        let n = b.0 * b.0 + b.1 * b.1;
633        ((a.0 * b.0 + a.1 * b.1) / n, (a.1 * b.0 - a.0 * b.1) / n)
634    };
635    let d = (c, -k / w);
636    let load_s = (0.0, jl * w);
637    let coupled = div(mul(d, load_s), (d.0 + load_s.0, d.1 + load_s.1));
638    let total = (b + coupled.0, jm * w + coupled.1);
639    1.0 / total.0.hypot(total.1)
640}
641
642/// A damped oscillation riding on a slow trend: what the motor speed does after a torque step.
643#[derive(Debug, Clone, PartialEq)]
644pub struct Ringing {
645    /// Undamped natural frequency, Hz.
646    pub frequency: Estimate,
647    pub damping_ratio: Estimate,
648    pub quality: Quality,
649}
650
651/// Fits A e^(-σt) sin(ω_d t + φ) + c0 + c1 t + c2 t² to `signal` between `from` and `until` (s), with t
652/// from `from`. The quadratic takes the rigid motion under the step. The start for ω_d is the strongest
653/// frequency of what is left after the trend; the start for φ the best of eight. `None` with fewer than
654/// 20 rows in the span or no fit.
655pub fn ringing(time: &[f64], signal: &[f64], from: f64, until: f64) -> Option<Ringing> {
656    let rows: Vec<usize> = (0..time.len()).filter(|&i| time[i] >= from && time[i] <= until).collect();
657    if rows.len() < 20 {
658        return None;
659    }
660    let t: Vec<f64> = rows.iter().map(|&i| time[i] - from).collect();
661    let y: Vec<f64> = rows.iter().map(|&i| signal[i]).collect();
662    let span = t[t.len() - 1];
663    let level = y.iter().fold(0.0, |a: f64, b| a.max(b.abs())).max(1e-12);
664    let trend = least_squares(&[0.0; 3], &[level, level / span, level / span / span], &|p: &[f64]| {
665        t.iter().zip(&y).map(|(t, y)| p[0] + p[1] * t + p[2] * t * t - y).collect()
666    })?;
667    let rest = &trend.residuals;
668    let step = span / (t.len() - 1) as f64;
669    let candidates = crate::analysis::log_spaced(2.0 / span, 0.25 / step, 200);
670    let power = |f: f64| {
671        let (re, im) = t
672            .iter()
673            .zip(rest)
674            .fold((0.0, 0.0), |(re, im), (t, r)| (re + r * (TAU * f * t).cos(), im + r * (TAU * f * t).sin()));
675        re * re + im * im
676    };
677    let fd = candidates.into_iter().max_by(|a, b| power(*a).total_cmp(&power(*b)))?;
678    let amplitude = rest.iter().fold(0.0, |a: f64, b| a.max(b.abs()));
679    let model =
680        |p: &[f64], t: f64| p[0] * (-p[3] * t).exp() * (TAU * p[2] * t + p[1]).sin() + p[4] + p[5] * t + p[6] * t * t;
681    let residuals = |p: &[f64]| -> Vec<f64> { t.iter().zip(&y).map(|(&t, y)| model(p, t) - y).collect() };
682    let tp = &trend.values;
683    let cost = |p: &[f64]| residuals(p).iter().map(|v| v * v).sum::<f64>();
684    let start = (0..8)
685        .map(|k| [amplitude, k as f64 * TAU / 8.0, fd, 0.1 * TAU * fd, tp[0], tp[1], tp[2]])
686        .min_by(|a, b| cost(a).total_cmp(&cost(b)))?;
687    let fit = least_squares(&start, &[level, 1.0, fd, TAU * fd, level, level / span, level / span / span], &residuals)?;
688    let (wd, sigma) = (
689        Estimate { value: TAU * fit.values[2], error: TAU * fit.errors[2] },
690        Estimate { value: fit.values[3], error: fit.errors[3] },
691    );
692    let fitted: Vec<f64> = t.iter().map(|&t| model(&fit.values, t)).collect();
693    Some(Ringing {
694        frequency: propagate(&|v| v[0].hypot(v[1]) / TAU, &[wd, sigma]),
695        damping_ratio: propagate(&|v| v[1] / v[0].hypot(v[1]), &[wd, sigma]),
696        quality: quality(&y, &fitted),
697    })
698}
699
700/// The two-mass model from the ringing after a torque step, which shows the resonance (motor and load
701/// against each other), given the total inertia (from `friction`) and the motor's own (the rotor, from its
702/// data sheet, plus what sits on the motor side of the spring). Its reduced inertia
703/// μ = J_motor J_load / J gives stiffness = μ (2π f)² and damping = 2 ζ sqrt(stiffness μ).
704pub fn two_mass_from_ringing(ringing: &Ringing, total: Estimate, motor: Estimate) -> TwoMass {
705    let inputs = [total, motor, ringing.frequency, ringing.damping_ratio];
706    let reduced = |v: &[f64]| v[1] * (v[0] - v[1]) / v[0];
707    let stiffness = |v: &[f64]| reduced(v) * (TAU * v[2]).powi(2);
708    TwoMass {
709        total_inertia: total,
710        motor_inertia: motor,
711        load_inertia: propagate(&|v| v[0] - v[1], &inputs),
712        stiffness: propagate(&stiffness, &inputs),
713        damping: propagate(&|v| 2.0 * v[3] * (stiffness(v) * reduced(v)).sqrt(), &inputs),
714        resonance: ringing.frequency,
715        anti_resonance: propagate(&|v| v[2] * (v[1] / v[0]).sqrt(), &inputs),
716    }
717}
718
719/// The names `Identified` gives its values and qualities, every one it can give.
720pub const QUANTITIES: [&str; 19] = [
721    "inertia_kg_m2",
722    "viscous_nm_s_rad",
723    "coulomb_nm",
724    "constant_torque_nm",
725    "stiction_nm",
726    "stribeck_speed_rad_s",
727    "presliding_stiffness_nm_rad",
728    "current_loop_gain",
729    "current_loop_time_constant_s",
730    "current_loop_dead_time_s",
731    "position_loop_gain",
732    "position_loop_time_constant_s",
733    "position_loop_dead_time_s",
734    "friction_model_fit_percent",
735    "friction_model_rms_nm",
736    "current_loop_fit_percent",
737    "current_loop_following_error_fit_percent",
738    "position_loop_fit_percent",
739    "position_loop_following_error_fit_percent",
740];
741
742/// Everything a trace of one motor gives without extra tests: inertia and friction, and the lags from torque
743/// setpoint to torque (where the trace has the setpoint) and from position setpoint to position. What
744/// `sim-cli identify` and the app show.
745#[derive(Debug, Clone, PartialEq)]
746pub struct Identified {
747    pub friction: Option<Friction>,
748    pub current_loop: Option<Lag>,
749    pub position_loop: Option<Lag>,
750}
751
752impl Identified {
753    pub fn of(time: &[f64], motor: &crate::trace::MotorTrace, torque_setpoint: Option<&[f64]>) -> Self {
754        Self {
755            friction: friction(time, &motor.angle, &motor.speed, &motor.torque),
756            current_loop: torque_setpoint.and_then(|input| lag(time, input, &motor.torque)),
757            position_loop: lag(time, &motor.setpoint, &motor.angle),
758        }
759    }
760
761    /// The fitted values by name (quantity and unit, as `sim-cli identify` writes them), in a fixed order;
762    /// what the trace did not show is left out.
763    pub fn estimates(&self) -> Vec<(&'static str, Estimate)> {
764        let mut out = Vec::new();
765        if let Some(f) = &self.friction {
766            out.extend([
767                ("inertia_kg_m2", f.inertia),
768                ("viscous_nm_s_rad", f.viscous),
769                ("coulomb_nm", f.coulomb),
770                ("constant_torque_nm", f.constant),
771            ]);
772            let optional = [
773                ("stiction_nm", f.stiction),
774                ("stribeck_speed_rad_s", f.stribeck_speed),
775                ("presliding_stiffness_nm_rad", f.presliding_stiffness),
776            ];
777            out.extend(optional.into_iter().filter_map(|(name, e)| e.map(|e| (name, e))));
778        }
779        for (names, lag) in [
780            (["current_loop_gain", "current_loop_time_constant_s", "current_loop_dead_time_s"], &self.current_loop),
781            (["position_loop_gain", "position_loop_time_constant_s", "position_loop_dead_time_s"], &self.position_loop),
782        ] {
783            if let Some(l) = lag {
784                out.extend(names.into_iter().zip([l.gain, l.time_constant, l.dead_time]));
785            }
786        }
787        out
788    }
789
790    /// How well each model reproduces the trace, by name: fit in percent, and the friction model's RMS in N m.
791    pub fn qualities(&self) -> Vec<(&'static str, f64)> {
792        let mut out = Vec::new();
793        if let Some(f) = &self.friction {
794            out.extend([
795                ("friction_model_fit_percent", f.quality.fit_percent),
796                ("friction_model_rms_nm", f.quality.rms),
797            ]);
798        }
799        for (names, lag) in [
800            (["current_loop_fit_percent", "current_loop_following_error_fit_percent"], &self.current_loop),
801            (["position_loop_fit_percent", "position_loop_following_error_fit_percent"], &self.position_loop),
802        ] {
803            if let Some(l) = lag {
804                out.extend(names.into_iter().zip([l.quality.fit_percent, l.error_quality.fit_percent]));
805            }
806        }
807        out
808    }
809}