Skip to main content

sim_components/
chain.rs

1//! A machine of joints, each driven by a motor through a transmission (`joint::RotaryJoint`): the machine for every
2//! mechanism that can say its dynamics in joint coordinates, M(q) q'' + h(q, q') = tau. A joint's coordinate is an angle
3//! (rad) or a travel (m); its gearbox's ratio is motor radians per unit of it, so a ball screw is a gearbox of ratio
4//! 2 pi / lead (times any reduction before it), a rack 1 / pinion radius, a linear motor 1 (its "rotor" the forcer, its
5//! torques forces). Stiffness, backlash, friction and stops are those at the joint, in its unit.
6//!
7//! Rigid: the rotors turn with their joints times the ratio, their inertia counts at the joint times the ratio squared,
8//! and each gearbox loses its efficiency on what passes through it (two passes, as on the delta). Elastic
9//! (`effects.joint_elasticity`): the rotors are states of their own behind the gearboxes' springs.
10//!
11//! A mechanism (`Mechanism`) gives the load's dynamics, its kinematics from joints to the tool, its own signals and
12//! rating checks and its scene. Everything else (states, losses, energy, torque breakdown, friction view, heating
13//! gearboxes) is here, the same for all.
14
15use crate::joint::RotaryJoint;
16use crate::mech::ThermalFeedback;
17use sim_core::{
18    AxisInfo, ENERGY_PARTS, FRICTION_SIGNALS, FrameMomentum, FrictionContact, LOSS_PREFIX, Machine, MotorInfo,
19    RatingCheck, Scene, SignalInfo, TORQUE_PARTS, ThermalPart,
20};
21
22/// Solves the n x n system `m` (row by row) x = b by Gaussian elimination with partial pivoting; `None` where `m` is
23/// singular.
24pub fn solve(m: &[f64], b: &[f64]) -> Option<Vec<f64>> {
25    let (mut a, mut x) = (m.to_vec(), b.to_vec());
26    solve_in_place(&mut a, &mut x).then_some(x)
27}
28
29/// `solve` without its copies: eliminates `a` in place and leaves the solution in `x`; `false` where `a` is singular or
30/// the solution not finite (`a` and `x` are then of no use).
31pub fn solve_in_place(a: &mut [f64], x: &mut [f64]) -> bool {
32    let n = x.len();
33    for c in 0..n {
34        let Some(p) = (c..n).max_by(|&i, &j| a[i * n + c].abs().total_cmp(&a[j * n + c].abs())) else { return false };
35        if !(a[p * n + c].abs() > 1e-300) {
36            return false;
37        }
38        if p != c {
39            for k in 0..n {
40                a.swap(p * n + k, c * n + k);
41            }
42            x.swap(p, c);
43        }
44        for r in c + 1..n {
45            let f = a[r * n + c] / a[c * n + c];
46            for k in c..n {
47                a[r * n + k] -= f * a[c * n + k];
48            }
49            x[r] -= f * x[c];
50        }
51    }
52    for c in (0..n).rev() {
53        let s: f64 = (c + 1..n).map(|k| a[c * n + k] * x[k]).sum();
54        x[c] = (x[c] - s) / a[c * n + c];
55    }
56    x.iter().all(|v| v.is_finite())
57}
58
59/// The inverse of an n x n matrix (row by row), column by column with `solve`; `None` where it is singular.
60pub fn invert(m: &[f64], n: usize) -> Option<Vec<f64>> {
61    let mut inv = vec![0.0; n * n];
62    for c in 0..n {
63        let e: Vec<f64> = (0..n).map(|r| if r == c { 1.0 } else { 0.0 }).collect();
64        let x = solve(m, &e)?;
65        for r in 0..n {
66            inv[r * n + c] = x[r];
67        }
68    }
69    Some(inv)
70}
71
72/// The eigenvalues of the symmetric n x n matrix `a` (row by row), by Jacobi rotations.
73pub fn eigenvalues(mut a: Vec<f64>, n: usize) -> Vec<f64> {
74    for _ in 0..100 {
75        let off: f64 = (0..n * n).filter(|k| k / n != k % n).map(|k| a[k].powi(2)).sum();
76        let diag: f64 = (0..n).map(|k| a[k * n + k].powi(2)).sum();
77        if !(off > 1e-30 * diag) {
78            break;
79        }
80        for p in 0..n {
81            for q in p + 1..n {
82                if a[p * n + q] == 0.0 {
83                    continue;
84                }
85                let theta = 0.5 * (a[q * n + q] - a[p * n + p]) / a[p * n + q];
86                let t = if theta == 0.0 { 1.0 } else { theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt()) };
87                let (c, s) = (1.0 / (t * t + 1.0).sqrt(), t / (t * t + 1.0).sqrt());
88                for k in 0..n {
89                    let (akp, akq) = (a[k * n + p], a[k * n + q]);
90                    a[k * n + p] = c * akp - s * akq;
91                    a[k * n + q] = s * akp + c * akq;
92                }
93                for k in 0..n {
94                    let (apk, aqk) = (a[p * n + k], a[q * n + k]);
95                    a[p * n + k] = c * apk - s * aqk;
96                    a[q * n + k] = s * apk + c * aqk;
97                }
98            }
99        }
100    }
101    (0..n).map(|k| a[k * n + k]).collect()
102}
103
104/// The 2-norm condition number of a rows x cols matrix (row by row): sqrt of the largest over the smallest eigenvalue
105/// of J^T J; infinite where it is singular.
106pub fn condition_number(j: &[f64], rows: usize, cols: usize) -> f64 {
107    let jtj: Vec<f64> =
108        (0..cols * cols).map(|rc| (0..rows).map(|k| j[k * cols + rc / cols] * j[k * cols + rc % cols]).sum()).collect();
109    let eig = eigenvalues(jtj, cols);
110    let (most, least) = (eig.iter().copied().fold(0.0, f64::max), eig.iter().copied().fold(f64::INFINITY, f64::min));
111    if !(least > 1e-24 * most) { f64::INFINITY } else { (most / least).sqrt() }
112}
113
114/// `matrix_modes_at` with K and C diagonal: K's diagonal given, C's entry of coordinate r at the mode's w (a gear's
115/// damper bridged by a Maxwell arm damps by frequency, `damping_at`).
116fn generalized_modes(m: &[f64], k: &[f64], c: impl Fn(usize, f64) -> f64, n: usize) -> Vec<sim_core::Mode> {
117    let diagonal = (0..n * n).map(|rc| if rc / n == rc % n { k[rc / n] } else { 0.0 }).collect::<Vec<_>>();
118    matrix_modes_at(m, &diagonal, |r, col, w| if r == col { c(r, w) } else { 0.0 }, n)
119}
120
121/// `matrix_modes_at` with a constant C (symmetric, row by row).
122pub fn matrix_modes(m: &[f64], k: &[f64], c: &[f64], n: usize) -> Vec<sim_core::Mode> {
123    matrix_modes_at(m, k, |r, col, _| c[r * n + col], n)
124}
125
126/// The modes of M x'' + C x' + K x = 0 (`n` coordinates, M, K and C symmetric, row by row): w^2 of K x = w^2 M x, the
127/// eigenvalues of L^-1 K L^-T (M = L L^T) by Jacobi rotations, C's entry (r, col) at a frequency given by `c`. `hz` is
128/// that undamped w (what a shaper following the mode takes). The damping ratio is the damped problem's (`damped_ratio`):
129/// -Re lambda / |lambda| of the eigenvalue of M lambda^2 + C lambda + K that belongs to the mode, C at |lambda|; where
130/// that is not found (an overdamped mode, or two modes' eigenvalues not told apart) the estimate on the undamped shape,
131/// x^T C(w) x / (2 w) with x^T M x = 1, which differs where C couples modes that lie close (C not proportional to M
132/// and K). Empty where M is not positive definite.
133fn matrix_modes_at(m: &[f64], k: &[f64], c: impl Fn(usize, usize, f64) -> f64, n: usize) -> Vec<sim_core::Mode> {
134    let mut l = vec![0.0; n * n];
135    for i in 0..n {
136        for j in 0..=i {
137            let s = m[i * n + j] - (0..j).map(|p| l[i * n + p] * l[j * n + p]).sum::<f64>();
138            if i == j && !(s > 0.0) {
139                return Vec::new();
140            }
141            l[i * n + j] = if i == j { s.sqrt() } else { s / l[j * n + j] };
142        }
143    }
144    // w = L^-1, by forward substitution column by column.
145    let mut w = vec![0.0; n * n];
146    for j in 0..n {
147        for i in 0..n {
148            let s = f64::from(u8::from(i == j)) - (0..i).map(|p| l[i * n + p] * w[p * n + j]).sum::<f64>();
149            w[i * n + j] = s / l[i * n + i];
150        }
151    }
152    // W K, then (W K) W^T.
153    let wk: Vec<f64> = (0..n * n).map(|rc| (0..n).map(|p| w[rc / n * n + p] * k[p * n + rc % n]).sum()).collect();
154    let mut a: Vec<f64> = (0..n * n).map(|rc| (0..n).map(|p| wk[rc / n * n + p] * w[rc % n * n + p]).sum()).collect();
155    let mut v: Vec<f64> = (0..n * n).map(|rc| f64::from(u8::from(rc / n == rc % n))).collect();
156    for _ in 0..100 {
157        let off: f64 = (0..n * n).filter(|rc| rc / n != rc % n).map(|rc| a[rc] * a[rc]).sum();
158        let diag: f64 = (0..n).map(|i| a[i * n + i] * a[i * n + i]).sum();
159        if !(off > 1e-30 * diag) {
160            break;
161        }
162        for p in 0..n {
163            for q in p + 1..n {
164                if a[p * n + q] == 0.0 {
165                    continue;
166                }
167                let theta = (a[q * n + q] - a[p * n + p]) / (2.0 * a[p * n + q]);
168                let t = theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt());
169                let (cs, sn) = (1.0 / (t * t + 1.0).sqrt(), t / (t * t + 1.0).sqrt());
170                for r in 0..n {
171                    let (rp, rq) = (a[r * n + p], a[r * n + q]);
172                    (a[r * n + p], a[r * n + q]) = (cs * rp - sn * rq, sn * rp + cs * rq);
173                }
174                for r in 0..n {
175                    let (pr, qr) = (a[p * n + r], a[q * n + r]);
176                    (a[p * n + r], a[q * n + r]) = (cs * pr - sn * qr, sn * pr + cs * qr);
177                }
178                for r in 0..n {
179                    let (rp, rq) = (v[r * n + p], v[r * n + q]);
180                    (v[r * n + p], v[r * n + q]) = (cs * rp - sn * rq, sn * rp + cs * rq);
181                }
182            }
183        }
184    }
185    let undamped: Vec<(f64, f64)> = (0..n)
186        .filter_map(|i| {
187            let omega = a[i * n + i].sqrt();
188            // x = L^-T y, y the eigenvector.
189            let x: Vec<f64> = (0..n).map(|r| (0..n).map(|p| w[p * n + r] * v[p * n + i]).sum::<f64>()).collect();
190            let damping =
191                (0..n * n).map(|rc| x[rc / n] * c(rc / n, rc % n, omega) * x[rc % n]).sum::<f64>() / (2.0 * omega);
192            (omega > 0.0 && omega.is_finite()).then_some((omega, damping))
193        })
194        .collect();
195    let seeds: Vec<[f64; 2]> = undamped.iter().map(|&(w, z)| seed(w, z)).collect();
196    // M^-1 = W^T W.
197    let m_inv: Vec<f64> = (0..n * n).map(|rc| (0..n).map(|p| w[p * n + rc / n] * w[p * n + rc % n]).sum()).collect();
198    undamped
199        .iter()
200        .map(|&(omega, estimate)| {
201            let damping = damped_ratio(&m_inv, k, &c, n, omega, estimate, &seeds).unwrap_or(estimate);
202            sim_core::Mode { hz: omega / std::f64::consts::TAU, damping }
203        })
204        .collect()
205}
206
207/// Where a mode of undamped frequency `w` and damping ratio `z` has its eigenvalue: -z w + i w sqrt(1 - z^2).
208fn seed(w: f64, z: f64) -> [f64; 2] {
209    [-z * w, w * (1.0 - z * z).max(0.0).sqrt()]
210}
211
212/// The damping ratio -Re lambda / |lambda| of the eigenvalue lambda of M lambda^2 + C(|lambda|) lambda + K (M^-1 given as
213/// `m_inv`) that belongs to the mode of undamped frequency `w0` and estimated ratio `z0`: the eigenvalue of the companion
214/// matrix [[0, I], [-M^-1 K, -M^-1 C]] nearest the mode's `seed` (`shapes::eigen_near`), C taken anew at |lambda| until
215/// it holds. `None` for an estimate of 0 (nothing to find: lambda = i w0) or of 1 and more (overdamped), where the one
216/// found is nearer another mode's seed of `seeds` than its own (two modes' eigenvalues not told apart), or where the
217/// iteration does not settle.
218fn damped_ratio(
219    m_inv: &[f64],
220    k: &[f64],
221    c: &impl Fn(usize, usize, f64) -> f64,
222    n: usize,
223    w0: f64,
224    z0: f64,
225    seeds: &[[f64; 2]],
226) -> Option<f64> {
227    if !(z0 > 0.0 && z0 < 1.0) {
228        return None;
229    }
230    let product = |b: &[f64]| -> Vec<f64> {
231        (0..n * n).map(|rc| (0..n).map(|p| m_inv[rc / n * n + p] * b[p * n + rc % n]).sum()).collect()
232    };
233    let stiffness = product(k);
234    let size = 2 * n;
235    let own = seed(w0, z0);
236    let (mut lambda, mut w) = (own, w0);
237    for _ in 0..50 {
238        let damper = product(&(0..n * n).map(|rc| c(rc / n, rc % n, w)).collect::<Vec<_>>());
239        let mut a = vec![0.0; size * size];
240        for r in 0..n {
241            a[r * size + n + r] = 1.0;
242            for col in 0..n {
243                a[(n + r) * size + col] = -stiffness[r * n + col];
244                a[(n + r) * size + n + col] = -damper[r * n + col];
245            }
246        }
247        (lambda, _) = crate::shapes::eigen_near(&a, size, lambda)?;
248        let next = lambda[0].hypot(lambda[1]);
249        if (next - w).abs() <= 1e-12 * w {
250            let distance = |s: &[f64; 2]| (lambda[0] - s[0]).hypot(lambda[1] - s[1]);
251            let nearest = seeds.iter().map(distance).fold(f64::INFINITY, f64::min);
252            return (lambda[1] > 0.0 && distance(&own) <= nearest).then(|| -lambda[0] / next);
253        }
254        w = next;
255    }
256    None
257}
258
259/// `solve`'s elimination of a fixed-size matrix, kept for several right-hand sides: each solve does the very operations
260/// `solve` does, so the results are the same to the bit, without a heap allocation and with the matrix eliminated once.
261pub struct Lu<const N: usize> {
262    a: [[f64; N]; N],
263    factor: [[f64; N]; N],
264    pivot: [usize; N],
265}
266
267impl<const N: usize> Lu<N> {
268    /// `None` where `m` is singular (as `solve`).
269    pub fn new(m: &[[f64; N]; N]) -> Option<Self> {
270        let (mut a, mut factor, mut pivot) = (*m, [[0.0; N]; N], [0; N]);
271        for c in 0..N {
272            let p = (c..N).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?;
273            if !(a[p][c].abs() > 1e-300) {
274                return None;
275            }
276            a.swap(p, c);
277            pivot[c] = p;
278            for r in c + 1..N {
279                let f = a[r][c] / a[c][c];
280                for k in c..N {
281                    a[r][k] -= f * a[c][k];
282                }
283                factor[r][c] = f;
284            }
285        }
286        Some(Self { a, factor, pivot })
287    }
288
289    /// x with m x = b; `None` where it is not finite (as `solve`).
290    pub fn solve(&self, mut x: [f64; N]) -> Option<[f64; N]> {
291        for c in 0..N {
292            x.swap(self.pivot[c], c);
293            for r in c + 1..N {
294                x[r] -= self.factor[r][c] * x[c];
295            }
296        }
297        for c in (0..N).rev() {
298            let s: f64 = (c + 1..N).map(|k| self.a[c][k] * x[k]).sum();
299            x[c] = (x[c] - s) / self.a[c][c];
300        }
301        x.iter().all(|v| v.is_finite()).then_some(x)
302    }
303
304    /// m^-1 (rows), column by column as `solve` would find each; `None` where a column is not finite.
305    pub fn inverse(&self) -> Option<[[f64; N]; N]> {
306        let mut inv = [[0.0; N]; N];
307        for c in 0..N {
308            let x = self.solve(std::array::from_fn(|r| if r == c { 1.0 } else { 0.0 }))?;
309            for r in 0..N {
310                inv[r][c] = x[r];
311            }
312        }
313        Some(inv)
314    }
315}
316
317/// Joints (driven and passive) whose load the elastic model's derivatives keep on the stack; more take the heap.
318const ON_STACK: usize = 9;
319
320/// What a mechanism tells the joint machine.
321pub trait Mechanism: Send {
322    /// The load's mass matrix M (n x n, row by row, without the rotors) and h with M q'' + h = the torques (forces) at
323    /// the joints: velocity terms plus gravity. With the payload as it is attached. Where the mechanism has passive
324    /// joints (`passive_joints`), q and q' hold them after the driven ones, and M and h are of them all.
325    fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]);
326    /// The load's potential energy (passive joints included, their springs not); its gravity torques are those of h at
327    /// rest.
328    fn potential(&self, q: &[f64]) -> f64;
329    /// Joints that no motor drives, after the driven ones (a payload swinging on the flange): each with its spring
330    /// (N m/rad) and damper (N m s/rad) towards zero. None by default.
331    fn passive_joints(&self) -> Vec<(f64, f64)> {
332        Vec::new()
333    }
334    /// The passive joints' position signals, one per joint in their order (their values are the joints' positions):
335    /// by default those of a payload swinging on the flange, `swing.<k>.angle`.
336    fn passive_signals(&self) -> Vec<SignalInfo> {
337        (1..=self.passive_joints().len())
338            .map(|k| SignalInfo::new(format!("swing.{k}.angle"), "group-payload-swing", "quantity-swing-angle", "rad"))
339            .collect()
340    }
341    /// The id (`power.<id>`) and the owner's key of the loss row of the passive joints' dampers: by default the swinging
342    /// payload's. `None` (no row) only where every passive joint's damper is zero.
343    fn passive_loss_row(&self) -> Option<(&'static str, &'static str)> {
344        Some(("payload_swing", "group-payload-swing"))
345    }
346    /// The passive joints' positions at rest with the driven ones at `q` (a contact pressed in by its load): all zero by
347    /// default.
348    fn passive_rest(&self, _q: &[f64]) -> Vec<f64> {
349        vec![0.0; self.passive_joints().len()]
350    }
351    /// How far the tool pose moves at joints q (the driven ones) when the passive joints stand at `passive` rather than
352    /// at zero, into `out` (zeroed first): a forearm rocking on its rod. Zero by default (a swinging payload's joints
353    /// do not move the flange's frame).
354    fn passive_shift(&self, _q: &[f64], _passive: &[f64], out: &mut [f64]) {
355        out.iter_mut().for_each(|o| *o = 0.0);
356    }
357    /// The damping (N m s/rad) of each passive joint's own damper that `dynamics` applies (not in `passive_joints`'
358    /// pair), in their order, for the modes' damping figures; missing entries 0.
359    fn passive_extra_damping(&self) -> Vec<f64> {
360        Vec::new()
361    }
362    /// How many of the first passive joints the arm's trains and held modes take free (a rocking forearm: stiff, but a
363    /// mode of its own), rather than hold. 0 by default.
364    fn passive_in_modes(&self) -> usize {
365        0
366    }
367    /// A loss row of the mechanism's own (a contact's damper, a guide's friction), booked beside the joints' and the
368    /// two-way modes': its id (`power.<id>`) and the owner's key; `None` (no row) by default.
369    fn loss_row(&self) -> Option<(&'static str, &'static str)> {
370        None
371    }
372    /// The power the row of `loss_row` takes out, W, at all joints' q and qd (passive ones included): 0 by default.
373    fn loss_power(&self, _q: &[f64], _qd: &[f64]) -> f64 {
374        0.0
375    }
376    fn set_payload_attached(&mut self, attached: bool);
377    /// Whether the motors are linear motors (their signals in m, m/s, N): `Machine::motor_linear`. False by default.
378    fn linear_motor(&self) -> bool {
379        false
380    }
381    /// As `Machine::links` and `Machine::set_link_change`: the bodies whose inertial parameters a trace can be fitted for.
382    fn links(&self) -> Vec<String> {
383        Vec::new()
384    }
385    fn set_link_change(&mut self, _link: usize, _factor: f64, _moment: [f64; 3]) {}
386
387    /// Joints to tool pose. The joints themselves by default.
388    fn forward(&self, q: &[f64], tool: &mut [f64]) {
389        tool.copy_from_slice(q);
390    }
391    /// Tool pose to joints; `false` where it cannot be reached.
392    fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
393        q.copy_from_slice(tool);
394        true
395    }
396    /// What `inverse` carries from one call to the next (a numerical inverse's last solution, which the next starts
397    /// from), as a fixed count of numbers, for `Machine::memory`. None by default.
398    fn memory(&self) -> Vec<f64> {
399        Vec::new()
400    }
401    /// Sets back what `memory` gave (empty: none, as before the first `inverse`), as `inverse` keeps it: behind a lock.
402    fn set_memory(&self, _memory: &[f64]) {}
403    fn unreachable(&self, _tool: &[f64], _slack: f64) -> Option<&'static str> {
404        None
405    }
406    /// `Machine::condition` at a tool pose; `None` where the tool is the joints.
407    fn condition(&self, _tool: &[f64]) -> Option<f64> {
408        None
409    }
410    /// Whether the tool pose is the joints themselves (`forward` and `inverse` as by default): then the joint speeds and
411    /// accelerations are the tool's, without going through the Jacobian.
412    fn tool_is_joints(&self) -> bool {
413        true
414    }
415
416    /// Whether the mechanism works on a process (a press force, a cut), which `process_torque` gives: then the machine
417    /// reports the power given to it as `power.process`. None by default.
418    fn has_process(&self) -> bool {
419        false
420    }
421    /// Adds the torques (forces) the process puts on the joints at positions `q` and speeds `qd` to `out`, positive
422    /// turning a joint up. Not conservative and not in `dynamics`: the torque breakdown counts it among the rest, and
423    /// the feedforward leaves it out, as a drive does not know it.
424    fn process_torque(&self, _q: &[f64], _qd: &[f64], _out: &mut [f64]) {}
425
426    /// As `Machine::cam` and `Machine::cam_at`: an electronic cam the mechanism runs as its cycle, its slaves the tool
427    /// axes. None by default.
428    fn cam(&self) -> Option<sim_core::CamMaster> {
429        None
430    }
431    fn cam_at(&self, _master: f64, _out: &mut [[f64; 4]]) {}
432    fn cam_curve(&self) -> Option<sim_core::CamCurve> {
433        None
434    }
435
436    /// The mechanism's own signals, after the machine's: their infos, and their values from joint positions, speeds,
437    /// accelerations and the force (torque) each transmission passes to its joint.
438    fn signal_infos(&self) -> Vec<SignalInfo> {
439        Vec::new()
440    }
441    fn signals(&self, _q: &[f64], _qd: &[f64], _qdd: &[f64], _force: &[f64], _out: &mut Vec<f64>) {}
442    /// Whether a signal needs the joints' jerk q''' (`signals_with_jerk`): the chain works it out only then, as it costs
443    /// three more evaluations of the machine's derivatives.
444    fn reads_jerk(&self) -> bool {
445        false
446    }
447    /// `signals` with the joints' jerk as well, for a mechanism that `reads_jerk`; zeros where it does not.
448    fn signals_with_jerk(&self, q: &[f64], qd: &[f64], qdd: &[f64], _qddd: &[f64], force: &[f64], out: &mut Vec<f64>) {
449        self.signals(q, qd, qdd, force, out);
450    }
451    fn rating_checks(&self) -> Vec<RatingCheck> {
452        Vec::new()
453    }
454    /// As `Machine::rigid_guide_loads`: the loads of the guides among `signals`, at a tool pose and acceleration.
455    fn rigid_guide_loads(&self, _tool: &[f64], _acc: &[f64], _out: &mut Vec<[f64; 2]>) {}
456
457    /// The ids of the boxes `scene` draws that move with the load and can hit an obstacle (`Machine::collision_bodies`).
458    fn collision_parts(&self) -> &'static [&'static str] {
459        &[]
460    }
461    /// The ids of the segments `scene` draws, in order from the base to the tool, as the links that the check of the
462    /// machine's own parts looks at (`Machine::self_collision_capsules`): each a capsule of half its width, not an
463    /// obstacle's part. Empty by default: the machine's own parts are then those of `collision_parts`.
464    fn collision_links(&self) -> &'static [&'static str] {
465        &[]
466    }
467
468    /// For effects.base_compliance (`Machine::frame_momentum`): the load's momentum at joints q and speeds qd (passive
469    /// ones included), in the frame of the tool pose's x, y, z, each driven joint's rotor adding `rotor_spin` (its
470    /// inertia times its speed: N m s, or N s for a linear motor's forcer) along its own axis. `None` by default.
471    fn frame_momentum(&self, _q: &[f64], _qd: &[f64], _rotor_spin: &[f64]) -> Option<FrameMomentum> {
472        None
473    }
474    /// Bending modes of the load's links (effects.link_bending): its motion drives them and they move the tool; the
475    /// joints feel them only where `flex_coupling` gives them two-way, else not (one-way, as `base::Based`). Their count
476    /// must not change. Empty by default.
477    fn flex_modes(&self) -> Vec<FlexMode> {
478        Vec::new()
479    }
480    /// The force on each of `flex_modes` at the driven joints' positions q, speeds qd and accelerations qdd, in its
481    /// coordinate (N).
482    fn flex_loads(&self, _q: &[f64], _qd: &[f64], _qdd: &[f64], _out: &mut [f64]) {}
483    /// How far the tool pose moves at joints q when the modes deflect by `deflection`, into `out` (zeroed first).
484    fn flex_shift(&self, _q: &[f64], _deflection: &[f64], _out: &mut [f64]) {}
485    /// How far the tool pose moves at joints q by the bending's static part that has no coordinate of its own (the
486    /// weights' load on a shape without inertia, state-free), into `out` (zeroed first): zero by default.
487    fn static_shift(&self, _q: &[f64], out: &mut [f64]) {
488        out.iter_mut().for_each(|o| *o = 0.0);
489    }
490    /// effects.link_bending_reaction: the modes two-way, coordinates of their own beside the joints, at all joints' q and
491    /// qd (passive ones included) and the modes' deflections d and rates dd (`FlexCoupling`). `None` where they are
492    /// one-way (`flex_loads`), the default.
493    fn flex_coupling(&self, _q: &[f64], _qd: &[f64], _d: &[f64], _dd: &[f64]) -> Option<FlexCoupling> {
494        None
495    }
496
497    /// Draws the machine at joint positions `q` (passive ones included) with the motor shafts at `rotors` (rad) turning
498    /// at `rotor_speeds`.
499    fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene);
500    fn scene_point(&self, _tool: &[f64]) -> Option<[f64; 3]> {
501        None
502    }
503}
504
505/// A bending mode of a mechanism's load (`Mechanism::flex_modes`): its modal mass (kg), stiffness (N/m) and damping
506/// (N s/m), in the coordinate of its deflection (a link's tip, m; a twist's angle, rad, and kg m^2, N m/rad), the link
507/// (0 the first) it bends and how.
508#[derive(Debug, Clone, Copy, PartialEq)]
509pub struct FlexMode {
510    pub link: usize,
511    pub mass: f64,
512    pub stiffness: f64,
513    pub damping: f64,
514    pub kind: FlexKind,
515}
516
517/// How a link deflects in a `FlexMode`: in the plane its joint turns it in, across that plane, or twisted about its
518/// length; a bend's second shape where a link bends in two (`BendSecond`, `BendAcrossSecond`).
519#[derive(Debug, Clone, Copy, PartialEq, Eq)]
520pub enum FlexKind {
521    Bend,
522    BendAcross,
523    Twist,
524    BendSecond,
525    BendAcrossSecond,
526}
527
528impl FlexKind {
529    /// Its signal's id after `link.<n>.`, the quantity's translation key and its unit.
530    fn signal(self) -> (&'static str, &'static str, &'static str) {
531        match self {
532            FlexKind::Bend => ("bend", "quantity-link-bend", "m"),
533            FlexKind::BendAcross => ("bend_across", "quantity-link-bend-across", "m"),
534            FlexKind::Twist => ("twist", "quantity-link-twist", "rad"),
535            FlexKind::BendSecond => ("bend_2", "quantity-link-bend-2", "m"),
536            FlexKind::BendAcrossSecond => ("bend_across_2", "quantity-link-bend-across-2", "m"),
537        }
538    }
539}
540
541/// The two-way bending modes (`Mechanism::flex_coupling`) at one moment, with T = 1/2 q'^T M q' + d'^T p +
542/// 1/2 d'^T M_d d' their share of the kinetic energy and V = -d^T Q_g of the potential:
543///
544/// ```text
545/// M q'' + B^T d'' = tau - h + G         G = d (d^T Q_g) / dq, the joints' load as the bending moves the weights
546/// B q'' + M_d d'' = F - K d - C d'      F = Q_g - B' q' - 1/2 M_d' d'
547/// ```
548///
549/// B' q' and M_d' along the motion, so that T + V + 1/2 d^T K d changes by the joints' work less C d'^2 alone.
550#[derive(Debug, Clone, PartialEq)]
551pub struct FlexCoupling {
552    /// M_d, modes x modes, row by row.
553    pub mass: Vec<f64>,
554    /// B, modes x joints (all, passive ones included), row by row.
555    pub coupling: Vec<f64>,
556    /// p = B q', per mode.
557    pub momentum: Vec<f64>,
558    /// F, per mode.
559    pub force: Vec<f64>,
560    /// G, per joint.
561    pub joint: Vec<f64>,
562    /// V = -d^T Q_g.
563    pub potential: f64,
564}
565
566/// One joint as the machine sees it: its drive, the joint's id and translation key (for friction contacts and signals),
567/// and where it has a gearbox ahead of a converter (screw, rack): the joint's travel per radian of the gearbox output,
568/// so that the torque at the gearbox output is the joint force times it (signal `gearbox.<motor>.output_torque`).
569#[derive(Debug, Clone)]
570pub struct JointSpec {
571    pub drive: RotaryJoint,
572    pub id: &'static str,
573    pub key: &'static str,
574    pub gear_lever: Option<f64>,
575    /// The joint's unit: "m" for a travel, "rad" for an angle (the axes may be the tool's, in other units).
576    pub unit: &'static str,
577}
578
579pub struct JointMachine<M: Mechanism> {
580    pub mechanism: M,
581    pub joints: Vec<JointSpec>,
582    pub elastic: bool,
583    pub thermal: Option<ThermalFeedback>,
584    /// Per joint, the efficiency its own gearbox has at the reference temperature, which `thermal`'s law warms from:
585    /// empty where every joint has the shared `[gearbox]`'s (`ThermalFeedback::efficiency`). A machine whose joints have
586    /// gearboxes of their own (`[gearbox.<k>]`) sets it.
587    pub gear_efficiencies: Vec<f64>,
588    pub axes: Vec<AxisInfo>,
589    pub motors: Vec<MotorInfo>,
590    brake_engaged: bool,
591    /// `Machine::setpoint_slack`, worked out when first asked for (`rest_sag`, 1.4 s on the seven-joint arm).
592    rest_slack: std::sync::OnceLock<f64>,
593    /// Whether the payload is attached, as `set_payload_attached` last had it (attached as built).
594    payload_attached: bool,
595    /// `Mechanism::passive_joints`: their angles and speeds follow the joint machine's own states.
596    passive: Vec<(f64, f64)>,
597    /// `Mechanism::passive_loss_row`, where there are passive joints.
598    passive_row: Option<(&'static str, &'static str)>,
599    /// How many bending modes the mechanism has (`Mechanism::flex_modes`); their deflections and rates end the state,
600    /// after the passive joints'.
601    flex: usize,
602    /// Whether the modes are two-way (`Mechanism::flex_coupling`).
603    two_way: bool,
604    /// An obstacle's push on the tool, per axis (`Machine::set_tool_force`), held until changed; empty for none.
605    push: Vec<f64>,
606    /// The joints and the Jacobian the push was last taken through (`push_on_joints`).
607    push_jacobian: std::sync::Mutex<(Vec<f64>, Vec<f64>)>,
608}
609
610/// How far (m or rad) the joints may move before the push's Jacobian is worked out again (`push_on_joints`).
611const PUSH_JACOBIAN_REUSE: f64 = 1e-5;
612
613/// The losses of one moment: per joint its friction, its motor's friction with the brake, its gearbox; then the stops
614/// and what the ripple gives off. And per joint the gearbox loss as a torque at the rotor.
615struct Losses {
616    powers: Vec<f64>,
617    gear_at_rotor: Vec<f64>,
618}
619
620impl<M: Mechanism> JointMachine<M> {
621    /// `axes` as many as joints, or fewer where the joints are redundant to the tool (a seven-joint arm whose tool has
622    /// six axes: the mechanism's `inverse` resolves the redundancy); one motor per joint, in their order.
623    pub fn new(
624        mechanism: M,
625        joints: Vec<JointSpec>,
626        elastic: bool,
627        thermal: Option<ThermalFeedback>,
628        axes: Vec<AxisInfo>,
629        motors: Vec<MotorInfo>,
630    ) -> Self {
631        assert!(axes.len() <= joints.len() && joints.len() == motors.len());
632        let (passive, flex) = (mechanism.passive_joints(), mechanism.flex_modes().len());
633        // Without a row the dampers' heat would be lost from the budget.
634        let passive_row = if passive.is_empty() { None } else { mechanism.passive_loss_row() };
635        assert!(passive_row.is_some() || passive.iter().all(|(_, c)| *c == 0.0));
636        let rest = vec![0.0; joints.len() + passive.len()];
637        let two_way = flex > 0 && mechanism.flex_coupling(&rest, &rest, &vec![0.0; flex], &vec![0.0; flex]).is_some();
638        Self {
639            mechanism,
640            joints,
641            elastic,
642            thermal,
643            gear_efficiencies: Vec::new(),
644            axes,
645            motors,
646            brake_engaged: false,
647            rest_slack: std::sync::OnceLock::new(),
648            payload_attached: true,
649            passive,
650            passive_row,
651            flex,
652            two_way,
653            push: Vec::new(),
654            push_jacobian: std::sync::Mutex::new((Vec::new(), Vec::new())),
655        }
656    }
657
658    /// The push at the tool (`push`) on the driven joints at q: its virtual work per unit of each, through the Jacobian
659    /// `tool_state` takes the tool's speed with, sum_i F_i d tool_i / d q_k. `None` without a push. The Jacobian is
660    /// worked out again only where the joints have moved `PUSH_JACOBIAN_REUSE` from where it last was (a numerical one
661    /// is 2 n forward solutions, each a Newton's iteration on a parallel platform): what the push's power then misses of
662    /// the tool's speed is the Jacobian's change over that (a six-leg platform's move into a slab: 63 s against 39 s, its
663    /// budget 1.94e-5 of the supply against 1.91e-5; `sim-machines`' collision tests).
664    fn push_on_joints(&self, q: &[f64]) -> Option<Vec<f64>> {
665        if self.push.iter().all(|f| *f == 0.0) {
666            return None;
667        }
668        let n = self.n();
669        let mut memo = self.push_jacobian.lock().unwrap_or_else(|e| e.into_inner());
670        if memo.0.len() != n || memo.0.iter().zip(q).any(|(a, b)| (a - b).abs() > PUSH_JACOBIAN_REUSE) {
671            *memo = (q.to_vec(), self.jacobian(q));
672        }
673        let jac = &memo.1;
674        Some((0..n).map(|k| self.push.iter().enumerate().map(|(i, f)| f * jac[i * n + k]).sum()).collect())
675    }
676
677    /// The push at the tool on the bending modes at joints q: per mode the tool's move by a unit deflection
678    /// (`flex_shift`, linear in it) times the push. `None` without a push or modes.
679    fn push_on_modes(&self, q: &[f64]) -> Option<Vec<f64>> {
680        if self.flex == 0 || self.push.iter().all(|f| *f == 0.0) {
681            return None;
682        }
683        let unit = |m: usize| (0..self.flex).map(|i| if i == m { 1.0 } else { 0.0 }).collect::<Vec<f64>>();
684        let on = |m: usize| self.flex_shift(q, &unit(m)).iter().zip(&self.push).map(|(x, f)| x * f).sum();
685        Some((0..self.flex).map(on).collect())
686    }
687
688    /// `rest_sag` as it is at the build: worked out on first use, before anything it reads changes (the payload, a
689    /// link's mass), from the mechanism's inverse as built (no last solution), whose own memory it leaves as it was.
690    fn rest_slack(&self) -> f64 {
691        *self.rest_slack.get_or_init(|| {
692            let kept = self.mechanism.memory();
693            self.mechanism.set_memory(&[]);
694            let slack = self.rest_sag();
695            self.mechanism.set_memory(&kept);
696            slack
697        })
698    }
699
700    /// How far the motors' pose can be from the tool's at rest, as the delta works it out: each gearbox twisted by the
701    /// torque it holds against gravity over its stiffness, plus half its backlash, through the forward kinematics; at
702    /// the corners and the centre of the axes' box, with the payload as it is (attached at the start); plus a tenth,
703    /// at least the default 0.1 mm. That alone in the rigid model, whose gearboxes do not twist. An arm's gears under
704    /// its weight: some mrad.
705    fn rest_sag(&self) -> f64 {
706        let n = self.n();
707        if !self.elastic {
708            return 1e-4;
709        }
710        // Five places along each axis, every combination: the sag is largest where a joint's weight arm is (where the
711        // links lie level), which a corner of the box need not be (the arm's second joint at its lower end with the
712        // first one between its ends sags 3.71 mrad, the corners and centre gave 2.77).
713        const LEVELS: usize = 5;
714        let m = self.axes.len();
715        let poses: Vec<Vec<f64>> = (0..LEVELS.pow(m as u32))
716            .map(|c| {
717                (self.axes.iter().enumerate())
718                    .map(|(i, a)| {
719                        a.min + (a.max - a.min) * (c / LEVELS.pow(i as u32) % LEVELS) as f64 / (LEVELS - 1) as f64
720                    })
721                    .collect()
722            })
723            .collect();
724        let (mut q, mut tool, mut sagged) = (vec![0.0; n], vec![0.0; m], vec![0.0; m]);
725        let mut most = 0f64;
726        for pose in poses {
727            if !self.mechanism.inverse(&pose, &mut q) {
728                continue;
729            }
730            let (_, gravity) = self.load(&q, &vec![0.0; n]);
731            // A process force that holds at rest (a press's force through a dwell) twists the gearbox too; the
732            // mechanisms whose process acts only in motion put none here.
733            let process = self.process(&q, &vec![0.0; n]);
734            let twisted: Vec<f64> = (0..n)
735                .map(|k| q[k] + self.joints[k].drive.gearbox.static_twist_at(q[k], gravity[k] - process[k]))
736                .collect();
737            self.mechanism.forward(&q, &mut tool);
738            self.mechanism.forward(&twisted, &mut sagged);
739            most = most.max(tool.iter().zip(&sagged).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max));
740        }
741        f64::max(1e-4, 1.1 * most)
742    }
743
744    fn n(&self) -> usize {
745        self.joints.len()
746    }
747
748    /// Where the bending modes' deflections start in the state, after the passive joints'; their rates follow them.
749    fn flex_at(&self) -> usize {
750        self.passive_at() + 2 * self.passive.len()
751    }
752
753    /// The bending modes' deflections and rates.
754    fn flex_state<'a>(&self, s: &'a [f64]) -> (&'a [f64], &'a [f64]) {
755        let (at, m) = (self.flex_at(), self.flex);
756        (&s[at..at + m], &s[at + m..at + 2 * m])
757    }
758
759    /// The bending modes' rates into `out`, from the joints' accelerations `acc` (the driven ones first): m d'' + c d' +
760    /// k d = load.
761    /// Two-way, `acc` carries the modes' accelerations after the joints' (`flex_solve`).
762    fn flex_rates(&self, s: &[f64], acc: &[f64], out: &mut [f64]) {
763        if self.flex == 0 {
764            return;
765        }
766        let joints = self.n() + self.passive.len();
767        if acc.len() > joints {
768            let ((_, rate), at, m) = (self.flex_state(s), self.flex_at(), self.flex);
769            out[at..at + m].copy_from_slice(rate);
770            out[at + m..at + 2 * m].copy_from_slice(&acc[joints..]);
771            return;
772        }
773        let (q, qd) = self.arms(s);
774        let mut load = vec![0.0; self.flex];
775        self.mechanism.flex_loads(q, qd, &acc[..q.len()], &mut load);
776        if let Some(push) = self.push_on_modes(q) {
777            load.iter_mut().zip(push).for_each(|(l, p)| *l += p);
778        }
779        let ((d, rate), at, m) = (self.flex_state(s), self.flex_at(), self.flex);
780        for (k, mode) in self.mechanism.flex_modes().iter().enumerate() {
781            out[at + k] = rate[k];
782            out[at + m + k] = (load[k] - mode.stiffness * d[k] - mode.damping * rate[k]) / mode.mass;
783        }
784    }
785
786    /// The two-way modes' coupling at state `s` (`Mechanism::flex_coupling`); `None` where they are one-way.
787    fn flex_coupling(&self, s: &[f64]) -> Option<FlexCoupling> {
788        if !self.two_way {
789            return None;
790        }
791        let (q, qd) = self.all_joints(s);
792        let (d, rate) = self.flex_state(s);
793        self.mechanism.flex_coupling(&q, &qd, d, rate)
794    }
795
796    /// The joints' accelerations from their `mass` and `rhs` (all joints, M q'' = rhs); two-way (`coupling`, see
797    /// `FlexCoupling`) solved together with the modes', which follow the joints'. NaN where singular.
798    fn flex_solve(&self, coupling: Option<&FlexCoupling>, s: &[f64], mass: &[f64], rhs: &[f64]) -> Vec<f64> {
799        let Some(c) = coupling else {
800            return solve(mass, rhs).unwrap_or_else(|| vec![f64::NAN; rhs.len()]);
801        };
802        let (all, f) = (rhs.len(), self.flex);
803        let size = all + f;
804        let ((d, rate), modes) = (self.flex_state(s), self.mechanism.flex_modes());
805        let push = self.push_on_modes(&s[..self.n()]).unwrap_or_else(|| vec![0.0; f]);
806        let (mut m, mut b) = (vec![0.0; size * size], vec![0.0; size]);
807        for r in 0..all {
808            m[r * size..r * size + all].copy_from_slice(&mass[r * all..(r + 1) * all]);
809            b[r] = rhs[r] + c.joint[r];
810        }
811        for i in 0..f {
812            for j in 0..all {
813                m[(all + i) * size + j] = c.coupling[i * all + j];
814                m[j * size + all + i] = c.coupling[i * all + j];
815            }
816            m[(all + i) * size + all..(all + i + 1) * size].copy_from_slice(&c.mass[i * f..(i + 1) * f]);
817            b[all + i] = c.force[i] - modes[i].stiffness * d[i] - modes[i].damping * rate[i] + push[i];
818        }
819        solve(&m, &b).unwrap_or_else(|| vec![f64::NAN; size])
820    }
821
822    /// The two-way modes with the motors held (`Machine::modes`): the joints on their gearboxes' springs where they are
823    /// elastic (held where rigid; passive joints held), the modes on theirs, coupled through the mass, K x = w^2 M x.
824    /// Without `damped` the frequencies alone (damping 0), as `resonance_hz` wants them.
825    fn coupled_modes(&self, q: &[f64], damped: bool) -> Vec<sim_core::Mode> {
826        let (n, f) = (self.n(), self.flex);
827        let all = n + self.passive.len();
828        let rest = |len: usize| vec![0.0; len];
829        let mut qa = q.to_vec();
830        qa.resize(all, 0.0);
831        let Some(c) = self.mechanism.flex_coupling(&qa, &rest(all), &rest(f), &rest(f)) else { return Vec::new() };
832        let modes = self.mechanism.flex_modes();
833        let free = if self.elastic { n } else { 0 };
834        let size = free + f;
835        let (load, _) = self.load(q, &rest(n));
836        let (mut m, mut k, mut damping) = (rest(size * size), rest(size), rest(size));
837        for r in 0..free {
838            m[r * size..r * size + free].copy_from_slice(&load[r * n..r * n + free]);
839            k[r] = self.joints[r].drive.gearbox.at(q[r]).stiffness;
840        }
841        for i in 0..f {
842            for j in 0..free {
843                m[(free + i) * size + j] = c.coupling[i * all + j];
844                m[j * size + free + i] = c.coupling[i * all + j];
845            }
846            m[(free + i) * size + free..(free + i + 1) * size].copy_from_slice(&c.mass[i * f..(i + 1) * f]);
847            (k[free + i], damping[free + i]) = (modes[i].stiffness, modes[i].damping);
848        }
849        let c = |r: usize, w: f64| match r {
850            _ if !damped => 0.0,
851            r if r < free => self.joints[r].drive.gearbox.at(q[r]).damping_at(w),
852            r => damping[r],
853        };
854        generalized_modes(&m, &k, c, size)
855    }
856
857    /// An arm's joints on their gearboxes' springs with the motors held, at joints q (`Machine::modes`): K x = w^2 M x
858    /// with M the load's mass matrix there (passive joints held, the rotors left out: a velocity loop far stiffer than
859    /// the mode holds them) and K, C the gearboxes' stiffnesses and dampings. Empty for one joint (`two_mass_frequency`
860    /// tells its mode) and in the rigid model. With the links' bending two-way these are among `coupled_modes`. Without
861    /// `damped` the frequencies alone (damping 0).
862    fn held_modes(&self, q: &[f64], damped: bool) -> Vec<sim_core::Mode> {
863        let n = self.n();
864        if n < 2 || !self.elastic {
865            return Vec::new();
866        }
867        let gear = |k: usize| &self.joints[k].drive.gearbox;
868        let free = self.mechanism.passive_in_modes();
869        // The passive joints taken free (a rocking forearm) are coordinates of their own on their springs and dampers.
870        let (load, size) = match self.load_with_free(q) {
871            Some(whole) => {
872                let (all, size) = (n + self.passive.len(), n + free);
873                ((0..size * size).map(|rc| whole[rc / size * all + rc % size]).collect::<Vec<_>>(), size)
874            }
875            None => (self.load(q, &vec![0.0; n]).0, n),
876        };
877        let extra = self.mechanism.passive_extra_damping();
878        let k: Vec<f64> =
879            (0..size).map(|j| if j < n { gear(j).at(q[j]).stiffness } else { self.passive[j - n].0 }).collect();
880        let c = |j: usize, w: f64| match j {
881            _ if !damped => 0.0,
882            j if j < n => gear(j).at(q[j]).damping_at(w),
883            j => self.passive[j - n].1 + extra.get(j - n).copied().unwrap_or(0.0),
884        };
885        generalized_modes(&load, &k, c, size)
886    }
887
888    /// The tool's move by the bending modes at joints q, deflections d: `Mechanism::flex_shift`.
889    fn flex_shift(&self, q: &[f64], d: &[f64]) -> Vec<f64> {
890        let mut out = vec![0.0; self.axes.len()];
891        if self.flex > 0 {
892            self.mechanism.flex_shift(q, d, &mut out);
893        }
894        out
895    }
896
897    /// The tool's move by the passive joints at `passive` (`Mechanism::passive_shift`), at the driven joints q.
898    fn passive_shift(&self, q: &[f64], passive: &[f64]) -> Vec<f64> {
899        let mut out = vec![0.0; self.axes.len()];
900        self.mechanism.passive_shift(q, passive, &mut out);
901        out
902    }
903
904    /// Where the gears' Maxwell arms' states start (`Gearbox::arm`), after the bending modes' rates: one each for the
905    /// elastic joints whose gear has an arm (a screw or rack with a damped gear before it).
906    fn arm_at(&self) -> usize {
907        self.flex_at() + 2 * self.flex
908    }
909
910    /// Joint k's arm's place in the state, if its gear has one.
911    fn arm_slot(&self, k: usize) -> Option<usize> {
912        let has = |i: usize| self.elastic && self.joints[i].drive.gearbox.relax_stiffness > 0.0;
913        has(k).then(|| self.arm_at() + (0..k).filter(|&i| has(i)).count())
914    }
915
916    /// Joint k's arm's state, 0 where its gear has none (`Gearbox::torque_with` then leaves it out).
917    fn arm(&self, s: &[f64], k: usize) -> f64 {
918        self.arm_slot(k).map_or(0.0, |i| s[i])
919    }
920
921    /// Joint positions and speeds of a state.
922    fn arms<'a>(&self, s: &'a [f64]) -> (&'a [f64], &'a [f64]) {
923        let n = self.n();
924        (&s[..n], &s[n..2 * n])
925    }
926
927    /// Rotor angles and speeds.
928    fn rotors(&self, s: &[f64]) -> (Vec<f64>, Vec<f64>) {
929        let n = self.n();
930        if self.elastic {
931            (s[2 * n..3 * n].to_vec(), s[3 * n..4 * n].to_vec())
932        } else {
933            (0..n).map(|k| (s[k] * self.joints[k].drive.ratio(), s[n + k] * self.joints[k].drive.ratio())).unzip()
934        }
935    }
936
937    fn brakes<'a>(&self, s: &'a [f64]) -> &'a [f64] {
938        let n = self.n();
939        let at = if self.elastic { 4 * n } else { 2 * n };
940        &s[at..at + n]
941    }
942
943    /// The process's torques at the joints (`Mechanism::process_torque`).
944    fn process(&self, q: &[f64], qd: &[f64]) -> Vec<f64> {
945        let mut out = vec![0.0; self.n()];
946        self.mechanism.process_torque(q, qd, &mut out);
947        out
948    }
949
950    /// The driven joints' part of the load with the passive joints held at rest at zero: what the rigid feedforward
951    /// and the poses at rest see (the payload as if fixed to the flange).
952    fn load(&self, q: &[f64], qd: &[f64]) -> (Vec<f64>, Vec<f64>) {
953        let (n, p) = (self.n(), self.passive.len());
954        if p == 0 {
955            let (mut mass, mut bias) = (vec![0.0; n * n], vec![0.0; n]);
956            self.mechanism.dynamics(q, qd, &mut mass, &mut bias);
957            return (mass, bias);
958        }
959        let rest = |x: &[f64]| -> Vec<f64> { x.iter().copied().chain(std::iter::repeat_n(0.0, p)).collect() };
960        let (mass, bias) = self.load_all(&rest(q), &rest(qd));
961        let all = n + p;
962        ((0..n * n).map(|rc| mass[rc / n * all + rc % n]).collect(), bias[..n].to_vec())
963    }
964
965    /// The load of all joints, passive ones included.
966    fn load_all(&self, q: &[f64], qd: &[f64]) -> (Vec<f64>, Vec<f64>) {
967        let all = q.len();
968        let (mut mass, mut bias) = (vec![0.0; all * all], vec![0.0; all]);
969        self.mechanism.dynamics(q, qd, &mut mass, &mut bias);
970        (mass, bias)
971    }
972
973    /// The mass matrix of all joints at driven joints q with the passive ones at rest (`Mechanism::passive_rest`), where
974    /// the mechanism has passive joints its trains and held modes take free (`passive_in_modes`); else `None`.
975    fn load_with_free(&self, q: &[f64]) -> Option<Vec<f64>> {
976        if self.mechanism.passive_in_modes() == 0 {
977            return None;
978        }
979        let qa: Vec<f64> = q.iter().copied().chain(self.mechanism.passive_rest(q)).collect();
980        Some(self.load_all(&qa, &vec![0.0; qa.len()]).0)
981    }
982
983    /// Where the passive joints' angles start in the state; their speeds follow them.
984    fn passive_at(&self) -> usize {
985        self.n() * if self.elastic { 5 } else { 3 }
986    }
987
988    /// All joints' positions and speeds, passive ones after the driven ones.
989    fn all_joints(&self, s: &[f64]) -> (Vec<f64>, Vec<f64>) {
990        let (p, at) = (self.passive.len(), self.passive_at());
991        let (q, qd) = self.arms(s);
992        (q.iter().chain(&s[at..at + p]).copied().collect(), qd.iter().chain(&s[at + p..at + 2 * p]).copied().collect())
993    }
994
995    /// The passive joints' spring and damper torques.
996    fn passive_torque(&self, qp: &[f64], qdp: &[f64]) -> Vec<f64> {
997        self.passive.iter().zip(qp.iter().zip(qdp)).map(|((k, c), (q, qd))| -k * q - c * qd).collect()
998    }
999
1000    /// Rigid model: the joints' accelerations (passive ones after the driven ones), and per driven joint the torque
1001    /// into its gearbox (after the rotor's own acceleration) and out of it, at the joint.
1002    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
1003        let (n, p) = (self.n(), self.passive.len());
1004        let all = n + p;
1005        let (q, qd) = self.arms(s);
1006        let (rotor, rotor_speed) = self.rotors(s);
1007        let brakes = self.brakes(s);
1008        let joints;
1009        let (qa, qda) = if p == 0 {
1010            (q, qd)
1011        } else {
1012            joints = self.all_joints(s);
1013            (&joints.0[..], &joints.1[..])
1014        };
1015        let (mass, bias) = self.load_all(qa, qda);
1016        let springs = self.passive_torque(&qa[n..], &qda[n..]);
1017        let drive: Vec<f64> = (0..n)
1018            .map(|k| {
1019                self.joints[k].drive.rigid_drive(torque[k], rotor[k], rotor_speed[k], brakes[k], self.brake_engaged).0
1020            })
1021            .collect();
1022        let mut process = self.process(q, qd);
1023        if let Some(push) = self.push_on_joints(q) {
1024            process.iter_mut().zip(push).for_each(|(p, f)| *p += f);
1025        }
1026        let rest: Vec<f64> = (0..n)
1027            .map(|k| self.joints[k].drive.output_torque(q[k], qd[k]) - bias[k] + process[k])
1028            .chain((0..p).map(|i| springs[i] - bias[n + i]))
1029            .collect();
1030        let coupling = self.flex_coupling(s);
1031        let solve_with = |loss: &[f64]| -> Vec<f64> {
1032            let mut m = mass.clone();
1033            for k in 0..n {
1034                m[k * all + k] += loss[k] * self.joints[k].drive.reflected_inertia();
1035            }
1036            let mut x: Vec<f64> = (0..all).map(|k| if k < n { loss[k] * drive[k] } else { 0.0 } + rest[k]).collect();
1037            // Without two-way bending the plain solve, in place; with it the links' modes beside the joints.
1038            match coupling.as_ref() {
1039                None => {
1040                    if !solve_in_place(&mut m, &mut x) {
1041                        x.fill(f64::NAN);
1042                    }
1043                    x
1044                }
1045                Some(c) => self.flex_solve(Some(c), s, &m, &x),
1046            }
1047        };
1048        // The loss factors of the torques going in, at their fixed point (`mech::settled_loss`).
1049        let loss = crate::mech::settled_loss(vec![1.0; n], |loss| {
1050            let acc = solve_with(loss);
1051            (0..n)
1052                .map(|k| {
1053                    self.joints[k]
1054                        .drive
1055                        .gearbox
1056                        .loss_factor(drive[k] - self.joints[k].drive.reflected_inertia() * acc[k], qd[k])
1057                })
1058                .collect()
1059        });
1060        let acc = solve_with(&loss);
1061        let into: Vec<f64> = (0..n).map(|k| drive[k] - self.joints[k].drive.reflected_inertia() * acc[k]).collect();
1062        let out = (0..n).map(|k| loss[k] * into[k]).collect();
1063        (acc, into, out)
1064    }
1065
1066    /// Joint accelerations (passive ones after the driven ones) and the force (torque) each transmission passes to its
1067    /// joint, in either model.
1068    fn motion(&self, s: &[f64], torque: &[f64]) -> (Vec<f64>, Vec<f64>) {
1069        let n = self.n();
1070        if self.elastic {
1071            let mut d = vec![0.0; self.state_len()];
1072            self.derivatives(s, torque, &mut d);
1073            let gear = (0..n)
1074                .map(|k| {
1075                    self.joints[k]
1076                        .drive
1077                        .gearbox
1078                        .torque_with(s[2 * n + k], s[3 * n + k], s[k], s[n + k], self.arm(s, k))
1079                        .output
1080                })
1081                .collect();
1082            let at = self.passive_at() + self.passive.len();
1083            (d[n..2 * n].iter().chain(&d[at..at + self.passive.len()]).copied().collect(), gear)
1084        } else {
1085            let (acc, _, out) = self.rigid_solve(s, torque);
1086            (acc, out)
1087        }
1088    }
1089
1090    /// The joints' jerk (passive ones after the driven ones) at the motor torque held: the rate of `motion`'s
1091    /// accelerations along the state's rate, a central difference over 1 us. Exact with elastic joints, whose
1092    /// accelerations follow from the state alone; with rigid ones it leaves out the drive's torque rate, which the
1093    /// machine does not know.
1094    fn joint_jerk(&self, s: &[f64], torque: &[f64]) -> Vec<f64> {
1095        let (mut rate, h) = (vec![0.0; s.len()], 1e-6);
1096        self.derivatives(s, torque, &mut rate);
1097        let at = |sign: f64| {
1098            let moved: Vec<f64> = s.iter().zip(&rate).map(|(x, r)| x + sign * h * r).collect();
1099            self.motion(&moved, torque).0
1100        };
1101        at(1.0).iter().zip(at(-1.0)).map(|(up, down)| (up - down) / (2.0 * h)).collect()
1102    }
1103
1104    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
1105        let (q, _) = self.all_joints(s);
1106        self.energy_parts_with(s, &self.load_all(&q, &vec![0.0; q.len()]).0)
1107    }
1108
1109    /// `energy_parts` with the load's mass matrix at rest (all joints, `load_all` at no speed) known.
1110    fn energy_parts_with(&self, s: &[f64], mass: &[f64]) -> [f64; 3] {
1111        let n = self.n();
1112        let (q, qd) = self.all_joints(s);
1113        let all = q.len();
1114        let mut kinetic =
1115            0.5 * (0..all).map(|i| (0..all).map(|j| qd[i] * mass[i * all + j] * qd[j]).sum::<f64>()).sum::<f64>();
1116        let mut potential = self.mechanism.potential(&q);
1117        let mut elastic: f64 = (0..n).map(|k| self.joints[k].drive.stop_energy(q[k])).sum::<f64>()
1118            + self.passive.iter().zip(&q[n..]).map(|((k, _), q)| 0.5 * k * q * q).sum::<f64>();
1119        // Two-way modes (`FlexCoupling`): d'^T p + 1/2 d'^T M_d d', -d^T Q_g and their springs.
1120        if let Some(c) = self.flex_coupling(s) {
1121            let ((d, rate), f) = (self.flex_state(s), self.flex);
1122            for (i, mode) in self.mechanism.flex_modes().iter().enumerate() {
1123                let own: f64 = (0..f).map(|k| c.mass[i * f + k] * rate[k]).sum();
1124                kinetic += rate[i] * (c.momentum[i] + 0.5 * own);
1125                elastic += 0.5 * mode.stiffness * d[i] * d[i];
1126            }
1127            potential += c.potential;
1128        }
1129        for k in 0..n {
1130            let j = &self.joints[k].drive;
1131            if self.elastic {
1132                kinetic += 0.5 * j.rotor_inertia * s[3 * n + k] * s[3 * n + k];
1133                elastic += j.gearbox.energy_with(s[2 * n + k], s[k], self.arm(s, k));
1134            } else {
1135                kinetic += 0.5 * j.reflected_inertia() * qd[k] * qd[k];
1136            }
1137        }
1138        [kinetic, potential, elastic]
1139    }
1140
1141    fn losses(&self, s: &[f64], torque: &[f64]) -> Losses {
1142        let n = self.n();
1143        let (q, qd) = self.arms(s);
1144        let (rotor, rotor_speed) = self.rotors(s);
1145        let brakes = self.brakes(s);
1146        let row = usize::from(self.passive_row.is_some());
1147        let (mut powers, mut gear_at_rotor) = (vec![0.0; 3 * n + 2 + row], vec![0.0; n]);
1148        if row > 0 {
1149            // The passive joints' dampers.
1150            let (_, qd) = self.all_joints(s);
1151            powers[3 * n + 2] = self.passive.iter().zip(&qd[n..]).map(|((_, c), w)| c * w * w).sum();
1152        }
1153        let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque));
1154        for k in 0..n {
1155            let j = &self.joints[k].drive;
1156            let [friction, stop, shaft, drag] = j.losses(q[k], qd[k], rotor_speed[k], brakes[k], self.brake_engaged);
1157            let gear = match &rigid {
1158                Some((_, into, out)) => {
1159                    gear_at_rotor[k] = (into[k] - out[k]) / j.ratio();
1160                    (into[k] - out[k]) * qd[k]
1161                }
1162                None => {
1163                    let u = self.arm(s, k);
1164                    let g = j.gearbox.torque_with(s[2 * n + k], s[3 * n + k], s[k], s[n + k], u);
1165                    gear_at_rotor[k] = g.rotor - g.output / j.ratio();
1166                    j.gearbox.loss_power_with(s[2 * n + k], s[3 * n + k], s[k], s[n + k], u)
1167                }
1168            };
1169            powers[3 * k..3 * k + 3].copy_from_slice(&[friction, shaft, gear + drag]);
1170            powers[3 * n] += stop;
1171            powers[3 * n + 1] += (torque[k] - j.ripple.apply(torque[k], rotor[k])) * rotor_speed[k];
1172        }
1173        if self.mechanism.has_process() {
1174            powers.push(-self.process(q, qd).iter().zip(qd).map(|(t, v)| t * v).sum::<f64>());
1175        }
1176        if self.two_way {
1177            let rate = self.flex_state(s).1;
1178            powers.push(self.mechanism.flex_modes().iter().zip(rate).map(|(m, v)| m.damping * v * v).sum());
1179        }
1180        if self.mechanism.loss_row().is_some() {
1181            let (q, qd) = self.all_joints(s);
1182            powers.push(self.mechanism.loss_power(&q, &qd));
1183        }
1184        Losses { powers, gear_at_rotor }
1185    }
1186
1187    /// The torque breakdown, loss powers, energies and friction signals of the effect views.
1188    fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1189        let n = self.n();
1190        let (q, qd) = self.arms(s);
1191        let (_, rotor_speed) = self.rotors(s);
1192        let brakes = self.brakes(s);
1193        let (qa, qda) = self.all_joints(s);
1194        let all = qa.len();
1195        let (mass, bias) = self.load_all(&qa, &qda);
1196        let (at_rest, gravity) = self.load_all(&qa, &vec![0.0; all]);
1197        let (acc, _) = self.motion(s, torque);
1198        let losses = self.losses(s, torque);
1199        for k in 0..n {
1200            let j = &self.joints[k].drive;
1201            let i = j.ratio();
1202            let moving: f64 = (0..all).map(|c| mass[k * all + c] * acc[c]).sum();
1203            let held = j.brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).0;
1204            let parts = [
1205                (moving + bias[k] - gravity[k] + j.reflected_inertia() * acc[k]) / i,
1206                gravity[k] / i,
1207                j.shaft.torque(rotor_speed[k]) + held + losses.gear_at_rotor[k] + j.friction.torque_at(q[k], qd[k]) / i,
1208            ];
1209            out.extend(parts);
1210            out.push(torque[k] - parts.iter().sum::<f64>());
1211        }
1212        out.extend(&losses.powers);
1213        out.extend(self.energy_parts_with(s, &at_rest));
1214        for k in 0..n {
1215            out.extend(self.joints[k].drive.friction_signals(qd[k]));
1216        }
1217    }
1218
1219    /// The joint's unit and the unit of what drives it: rad and N m, or m and N.
1220    fn units(&self, k: usize) -> (&'static str, &'static str) {
1221        if self.joints[k].unit == "m" { ("m/s", "N") } else { ("rad/s", "N m") }
1222    }
1223
1224    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
1225        for (k, motor) in self.motors.iter().enumerate() {
1226            let unit = if self.motor_linear(k) { "N" } else { "N m" };
1227            out.extend(TORQUE_PARTS.map(|part| {
1228                SignalInfo::new(
1229                    format!("motor.{}.torque_{part}", motor.id),
1230                    motor.key,
1231                    &format!("quantity-torque-{part}"),
1232                    unit,
1233                )
1234            }));
1235        }
1236        for (k, motor) in self.motors.iter().enumerate() {
1237            let gear = if self.joints[k].drive.coupled {
1238                "quantity-coupling-loss-power"
1239            } else {
1240                "quantity-gearbox-loss-power"
1241            };
1242            out.push(SignalInfo::new(
1243                format!("{LOSS_PREFIX}joint_{}", motor.id),
1244                self.joints[k].key,
1245                "quantity-friction-power",
1246                "W",
1247            ));
1248            out.push(SignalInfo::new(
1249                format!("{LOSS_PREFIX}shaft_{}", motor.id),
1250                motor.key,
1251                "quantity-shaft-friction-power",
1252                "W",
1253            ));
1254            out.push(SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"));
1255        }
1256        out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-joint", "quantity-damping-power", "W"));
1257        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
1258        // In the order of `losses`: the passive joints' dampers, then the process.
1259        if let Some((id, owner)) = self.passive_row {
1260            out.push(SignalInfo::new(format!("{LOSS_PREFIX}{id}"), owner, "quantity-damping-power", "W"));
1261        }
1262        if self.mechanism.has_process() {
1263            out.push(SignalInfo::new(
1264                format!("{LOSS_PREFIX}process"),
1265                "group-process",
1266                "quantity-power-given-off",
1267                "W",
1268            ));
1269        }
1270        if self.two_way {
1271            out.push(SignalInfo::new(
1272                format!("{LOSS_PREFIX}link_bending"),
1273                "group-link_bending",
1274                "quantity-damping-power",
1275                "W",
1276            ));
1277        }
1278        if let Some((id, owner)) = self.mechanism.loss_row() {
1279            out.push(SignalInfo::new(format!("{LOSS_PREFIX}{id}"), owner, "quantity-damping-power", "W"));
1280        }
1281        out.extend(ENERGY_PARTS.map(|part| {
1282            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
1283        }));
1284        for (k, contact) in self.friction_contacts().iter().enumerate() {
1285            let (speed, force) = self.units(k);
1286            for part in FRICTION_SIGNALS {
1287                let unit = match part {
1288                    "speed" => speed,
1289                    "load_scale" => "",
1290                    _ => force,
1291                };
1292                out.push(SignalInfo::new(
1293                    format!("{}.friction_{part}", contact.id),
1294                    contact.owner_key,
1295                    &format!("quantity-friction-{}", part.replace('_', "-")),
1296                    unit,
1297                ));
1298            }
1299        }
1300    }
1301
1302    /// The lowest mode of a one-joint machine with an elastic transmission: the load (M) and the rotor seen at the joint
1303    /// (J i^2) on the transmission's spring k, f = sqrt(k (1/M + 1/(J i^2))) / (2 pi). `None` for more joints.
1304    pub fn two_mass_frequency(&self, q: &[f64]) -> Option<f64> {
1305        if self.n() != 1 {
1306            return None;
1307        }
1308        let (mass, _) = self.load(q, &[0.0]);
1309        let j = &self.joints[0].drive;
1310        Some(
1311            (j.gearbox.at(q[0]).stiffness * (1.0 / mass[0] + 1.0 / j.reflected_inertia())).sqrt()
1312                / (2.0 * std::f64::consts::PI),
1313        )
1314    }
1315
1316    /// One joint's modes at q: the gearbox's twist x = q - r between the rotor (r, J i^2 at the joint) and the joint,
1317    /// and each passive joint on its own spring, coupled through the mass, with the joint's rigid motion (no spring)
1318    /// taken out: M over (x, q, p) has q's row, and q'' = -(M_qx x'' + M_qp p'') / M_qq leaves the Schur complement
1319    /// M_ss - M_sq M_qs / M_qq over s = (x, p); K, C the gearbox's and the passive joints' (`generalized_modes`).
1320    /// Without passive joints this is `two_mass_frequency`, damping c / (2 sqrt(k mu)), mu = M J i^2 / (M + J i^2).
1321    /// A passive joint with no spring of its own (a contact the mechanism's forces hold) is held, as `load` holds it.
1322    /// Without `damped` the frequencies alone (damping 0).
1323    fn single_joint_modes(&self, q: &[f64], damped: bool) -> Vec<sim_core::Mode> {
1324        let qa: Vec<f64> = q.iter().copied().chain(self.mechanism.passive_rest(q)).collect();
1325        let all = qa.len();
1326        let (mass, _) = self.load_all(&qa, &vec![0.0; all]);
1327        let drive = &self.joints[0].drive;
1328        let jr = drive.reflected_inertia();
1329        // The gear's spring at the joint's travel (a screw's stiffness follows its nut, `Gearbox::at`).
1330        let gear = drive.gearbox.at(q[0]);
1331        let sprung: Vec<usize> = (0..self.passive.len()).filter(|&p| self.passive[p].0 > 0.0).map(|p| p + 1).collect();
1332        if sprung.is_empty() {
1333            // The closed form, so that the frequency is the one `resonance_hz` always gave, to the bit; zeta = c w / 2k.
1334            let damping = |hz: f64| {
1335                let w = std::f64::consts::TAU * hz;
1336                gear.damping_at(w) * w / (2.0 * gear.stiffness)
1337            };
1338            return self
1339                .two_mass_frequency(q)
1340                .map(|hz| sim_core::Mode { hz, damping: damping(hz) })
1341                .into_iter()
1342                .collect();
1343        }
1344        let size = 1 + sprung.len();
1345        // The coordinates' rows of M over (x, q, p): x couples to q by -J i^2, a passive joint by M's own entries.
1346        let to_q: Vec<f64> = std::iter::once(-jr).chain(sprung.iter().map(|&p| mass[p * all])).collect();
1347        let m_qq = jr + mass[0];
1348        let mut m = vec![0.0; size * size];
1349        m[0] = jr;
1350        for (a, &pa) in sprung.iter().enumerate() {
1351            for (b, &pb) in sprung.iter().enumerate() {
1352                m[(a + 1) * size + b + 1] = mass[pa * all + pb];
1353            }
1354        }
1355        (0..size * size).for_each(|rc| m[rc] -= to_q[rc / size] * to_q[rc % size] / m_qq);
1356        let extra = self.mechanism.passive_extra_damping();
1357        let (k, c): (Vec<f64>, Vec<f64>) =
1358            std::iter::once((gear.stiffness, gear.damping))
1359                .chain(sprung.iter().map(|&p| {
1360                    (self.passive[p - 1].0, self.passive[p - 1].1 + extra.get(p - 1).copied().unwrap_or(0.0))
1361                }))
1362                .unzip();
1363        let c = |r: usize, w: f64| match r {
1364            _ if !damped => 0.0,
1365            0 => gear.damping_at(w),
1366            r => c[r],
1367        };
1368        generalized_modes(&m, &k, c, size)
1369    }
1370}
1371
1372impl<M: Mechanism> Machine for JointMachine<M> {
1373    /// The mechanism's (`Mechanism::frame_momentum`, passive joints included), each rotor's spin from the state.
1374    fn frame_momentum(&self, s: &[f64]) -> Option<FrameMomentum> {
1375        let (q, qd) = self.all_joints(s);
1376        let spin: Vec<f64> =
1377            self.rotors(s).1.iter().zip(&self.joints).map(|(w, j)| j.drive.rotor_inertia * w).collect();
1378        self.mechanism.frame_momentum(&q, &qd, &spin)
1379    }
1380    fn axes(&self) -> &[AxisInfo] {
1381        &self.axes
1382    }
1383    fn motors(&self) -> &[MotorInfo] {
1384        &self.motors
1385    }
1386    fn motor_linear(&self, _motor: usize) -> bool {
1387        self.mechanism.linear_motor()
1388    }
1389
1390    fn rating_checks(&self) -> Vec<RatingCheck> {
1391        self.mechanism.rating_checks()
1392    }
1393    fn cam(&self) -> Option<sim_core::CamMaster> {
1394        self.mechanism.cam()
1395    }
1396    fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
1397        self.mechanism.cam_at(master, out);
1398    }
1399    fn cam_curve(&self) -> Option<sim_core::CamCurve> {
1400        self.mechanism.cam_curve()
1401    }
1402
1403    /// NaN where the pose cannot be reached: the controller never asks for one (see `unreachable`).
1404    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1405        let mut q = vec![0.0; self.n()];
1406        let ok = self.mechanism.inverse(tool, &mut q);
1407        for k in 0..self.n() {
1408            motors[k] = if ok { self.joints[k].drive.ratio() * q[k] } else { f64::NAN };
1409        }
1410    }
1411    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1412        let q: Vec<f64> = (0..self.n()).map(|k| motors[k] / self.joints[k].drive.ratio()).collect();
1413        self.mechanism.forward(&q, tool);
1414    }
1415
1416    fn state_len(&self) -> usize {
1417        self.arm_at() + (0..self.n()).filter(|&k| self.arm_slot(k).is_some()).count()
1418    }
1419
1420    /// With bending links, the tool (not the joints' pose) at `tool`: the links bent by their load at rest.
1421    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1422        let n = self.n();
1423        let (mut q, mut bent, mut pose) = (vec![0.0; n], vec![0.0; self.flex], tool.to_vec());
1424        let rocks = self.mechanism.passive_in_modes() > 0;
1425        for _ in 0..if self.flex > 0 || rocks { 3 } else { 1 } {
1426            if !self.mechanism.inverse(&pose, &mut q) {
1427                q.fill(f64::NAN);
1428            }
1429            let mut shift = vec![0.0; self.axes.len()];
1430            if self.flex > 0 {
1431                let mut load = vec![0.0; self.flex];
1432                self.mechanism.flex_loads(&q, &vec![0.0; n], &vec![0.0; n], &mut load);
1433                let modes = self.mechanism.flex_modes();
1434                bent = load.iter().zip(&modes).map(|(l, m)| l / m.stiffness).collect();
1435                shift = self.flex_shift(&q, &bent);
1436            }
1437            // The rocking forearm rests sagged on its rod: the flange stands where the pose says.
1438            if rocks {
1439                let sagged = self.passive_shift(&q, &self.mechanism.passive_rest(&q));
1440                shift.iter_mut().zip(&sagged).for_each(|(s, d)| *s += d);
1441            }
1442            if self.two_way {
1443                let mut statics = vec![0.0; self.axes.len()];
1444                self.mechanism.static_shift(&q, &mut statics);
1445                shift.iter_mut().zip(&statics).for_each(|(s, d)| *s += d);
1446            }
1447            if self.flex > 0 || rocks {
1448                pose = tool.iter().zip(&shift).map(|(t, s)| t - s).collect();
1449            }
1450        }
1451        // The passive joints where they rest (a contact pressed in by its load), the driven ones' weights with them.
1452        let rest = self.mechanism.passive_rest(&q);
1453        let gravity = if rest.iter().all(|x| *x == 0.0) {
1454            self.load(&q, &vec![0.0; n]).1
1455        } else {
1456            let all: Vec<f64> = q.iter().chain(&rest).copied().collect();
1457            self.load_all(&all, &vec![0.0; all.len()]).1[..n].to_vec()
1458        };
1459        // Two-way, the bent links shift the weights: G of `FlexCoupling` at rest.
1460        let mut shift = vec![0.0; n];
1461        if self.two_way {
1462            let all = n + self.passive.len();
1463            let mut qa = q.clone();
1464            qa.resize(all, 0.0);
1465            if let Some(c) = self.mechanism.flex_coupling(&qa, &vec![0.0; all], &bent, &vec![0.0; self.flex]) {
1466                shift.copy_from_slice(&c.joint[..n]);
1467            }
1468        }
1469        state.clear();
1470        state.extend(&q);
1471        state.extend(vec![0.0; n]);
1472        for k in 0..n {
1473            let j = &self.joints[k].drive;
1474            // At rest the transmission holds the load against gravity and the stops.
1475            let out = gravity[k] - shift[k] - j.output_torque(q[k], 0.0);
1476            let rotor = j.ratio() * (q[k] + if self.elastic { j.gearbox.static_twist_at(q[k], out) } else { 0.0 });
1477            if self.elastic {
1478                state.push(rotor);
1479            }
1480            let held = if self.elastic { j.gearbox.held_at(q[k], out) } else { out };
1481            torque[k] = j.ripple.invert(held / j.ratio(), rotor);
1482        }
1483        state.resize(self.passive_at(), 0.0);
1484        state.extend(rest);
1485        state.resize(self.flex_at(), 0.0);
1486        state.extend(bent);
1487        state.resize(self.state_len(), 0.0);
1488        // The arms at rest carry nothing.
1489        for k in 0..n {
1490            if let Some(i) = self.arm_slot(k) {
1491                state[i] = self.joints[k].drive.gearbox.arm_rest(state[2 * n + k], q[k]);
1492            }
1493        }
1494    }
1495
1496    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1497        let n = self.n();
1498        let (q, qd) = self.arms(s);
1499        out[..n].copy_from_slice(qd);
1500        let (p, at) = (self.passive.len(), self.passive_at());
1501        out[at..at + p].copy_from_slice(&s[at + p..at + 2 * p]);
1502        if !self.elastic {
1503            let (acc, ..) = self.rigid_solve(s, torque);
1504            let (_, rotor_speed) = self.rotors(s);
1505            let brakes = self.brakes(s);
1506            out[n..2 * n].copy_from_slice(&acc[..n]);
1507            out[at + p..at + 2 * p].copy_from_slice(&acc[n..n + p]);
1508            for k in 0..n {
1509                out[2 * n + k] = self.joints[k].drive.brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).1;
1510            }
1511            return self.flex_rates(s, &acc, out);
1512        }
1513        // Without passive joints the driven ones are all, as they stand in the state.
1514        let joints;
1515        let (qa, qda) = if p == 0 {
1516            (q, qd)
1517        } else {
1518            joints = self.all_joints(s);
1519            (&joints.0[..], &joints.1[..])
1520        };
1521        // The load, the process and the accelerations on the stack for up to `ON_STACK` joints: this runs four times a
1522        // sub-step, and the heap's allocations were a tenth of a six-joint arm's step.
1523        let all = n + p;
1524        let (mut stack, mut heap) =
1525            (([0.0; ON_STACK * ON_STACK], [0.0; ON_STACK], [0.0; ON_STACK], [0.0; ON_STACK]), None);
1526        let (mass, bias, process, rhs): (&mut [f64], &mut [f64], &mut [f64], &mut [f64]) = if all <= ON_STACK {
1527            (&mut stack.0[..all * all], &mut stack.1[..all], &mut stack.2[..n], &mut stack.3[..all])
1528        } else {
1529            let (m, b, pr, r) = heap.insert((vec![0.0; all * all], vec![0.0; all], vec![0.0; n], vec![0.0; all]));
1530            (m, b, pr, r)
1531        };
1532        self.mechanism.dynamics(qa, qda, mass, bias);
1533        let springs = self.passive_torque(&qa[n..], &qda[n..]);
1534        self.mechanism.process_torque(q, qd, process);
1535        // An obstacle's push at the tool acts on the joints beyond the gearboxes, as the process does.
1536        if let Some(push) = self.push_on_joints(q) {
1537            process.iter_mut().zip(push).for_each(|(p, f)| *p += f);
1538        }
1539        for i in 0..p {
1540            rhs[n + i] = springs[i] - bias[n + i];
1541        }
1542        for k in 0..n {
1543            let j = &self.joints[k].drive;
1544            let u = self.arm(s, k);
1545            let gear = j.gearbox.torque_with(s[2 * n + k], s[3 * n + k], q[k], qd[k], u);
1546            let (rotor_acc, brake_rate) =
1547                j.rotor_under(torque[k], s[2 * n + k], s[3 * n + k], gear, s[4 * n + k], self.brake_engaged);
1548            if let Some(i) = self.arm_slot(k) {
1549                out[i] = j.gearbox.arm(s[2 * n + k], q[k], u).1;
1550            }
1551            rhs[k] = gear.output - bias[k] + j.output_torque(q[k], qd[k]) + process[k];
1552            out[2 * n + k] = s[3 * n + k];
1553            out[3 * n + k] = rotor_acc;
1554            out[4 * n + k] = brake_rate;
1555        }
1556        // Without two-way bending the plain solve, in place; with it the links' modes beside the joints.
1557        let coupling = self.flex_coupling(s);
1558        let coupled;
1559        let acc: &[f64] = match coupling.as_ref() {
1560            None => {
1561                if !solve_in_place(mass, rhs) {
1562                    rhs.fill(f64::NAN);
1563                }
1564                rhs
1565            }
1566            Some(c) => {
1567                coupled = self.flex_solve(Some(c), s, mass, rhs);
1568                &coupled
1569            }
1570        };
1571        out[n..2 * n].copy_from_slice(&acc[..n]);
1572        out[at + p..at + 2 * p].copy_from_slice(&acc[n..n + p]);
1573        self.flex_rates(s, acc, out);
1574    }
1575
1576    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1577        let (q, qd) = self.arms(s);
1578        self.mechanism.forward(q, pos);
1579        let jac = self.jacobian(q);
1580        let n = self.n();
1581        for (i, v) in vel.iter_mut().enumerate().take(self.axes.len()) {
1582            *v = (0..n).map(|k| jac[i * n + k] * qd[k]).sum();
1583        }
1584        if self.flex > 0 {
1585            let (d, rate) = self.flex_state(s);
1586            pos.iter_mut().zip(self.flex_shift(q, d)).for_each(|(p, d)| *p += d);
1587            vel.iter_mut().zip(self.flex_shift(q, rate)).for_each(|(v, d)| *v += d);
1588        }
1589        if self.two_way {
1590            let mut shift = vec![0.0; self.axes.len()];
1591            self.mechanism.static_shift(q, &mut shift);
1592            pos.iter_mut().zip(&shift).for_each(|(x, d)| *x += d);
1593            // The rate of the static part and of the modes' shift along the joints' motion (their places change with q), by
1594            // central differences over 1e-6 rad along q'.
1595            let fastest = qd.iter().fold(0.0f64, |a, v| a.max(v.abs()));
1596            if fastest > 0.0 {
1597                let h = 1e-6 / fastest;
1598                let (d, _) = self.flex_state(s);
1599                let at = |sign: f64| -> Vec<f64> {
1600                    let moved: Vec<f64> = q.iter().zip(qd).map(|(q, v)| q + sign * h * v).collect();
1601                    let mut stat = vec![0.0; self.axes.len()];
1602                    self.mechanism.static_shift(&moved, &mut stat);
1603                    stat.iter().zip(self.flex_shift(&moved, d)).map(|(a, b)| a + b).collect()
1604                };
1605                let (ahead, behind) = (at(1.0), at(-1.0));
1606                vel.iter_mut().zip(ahead.iter().zip(&behind)).for_each(|(v, (a, b))| *v += (a - b) / (2.0 * h));
1607            }
1608        }
1609        if self.mechanism.passive_in_modes() > 0 {
1610            let (p, at) = (self.passive.len(), self.passive_at());
1611            pos.iter_mut().zip(self.passive_shift(q, &s[at..at + p])).for_each(|(x, d)| *x += d);
1612            // The rate of that move: the shift is nearly linear in the passive joints, so by a step of 1e-6 rad along them.
1613            let rate = &s[at + p..at + 2 * p];
1614            let fastest = rate.iter().fold(0.0f64, |a, r| a.max(r.abs()));
1615            if fastest > 0.0 {
1616                let h = 1e-6 / fastest;
1617                let (a, b) =
1618                    (rate.iter().map(|r| r * h).collect::<Vec<_>>(), rate.iter().map(|r| -r * h).collect::<Vec<_>>());
1619                let (ahead, behind) = (self.passive_shift(q, &a), self.passive_shift(q, &b));
1620                vel.iter_mut().zip(ahead.iter().zip(&behind)).for_each(|(v, (a, b))| *v += (a - b) / (2.0 * h));
1621            }
1622        }
1623    }
1624    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1625        let n = self.n();
1626        let mut pos = vec![0.0; self.axes.len()];
1627        self.mechanism.forward(&s[..n], &mut pos);
1628        let zero = vec![0.0; pos.len()];
1629        let (_, qd, _) = self.joint_motion(&pos, vel, &zero);
1630        s[n..2 * n].copy_from_slice(&qd);
1631        if self.elastic {
1632            for k in 0..n {
1633                s[3 * n + k] = self.joints[k].drive.ratio() * qd[k];
1634            }
1635        }
1636    }
1637    /// `rotors`, written in place (called at every stage of the integration).
1638    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1639        let n = self.n();
1640        if self.elastic {
1641            pos[..n].copy_from_slice(&s[2 * n..3 * n]);
1642            vel[..n].copy_from_slice(&s[3 * n..4 * n]);
1643        } else {
1644            for k in 0..n {
1645                (pos[k], vel[k]) = (s[k] * self.joints[k].drive.ratio(), s[n + k] * self.joints[k].drive.ratio());
1646            }
1647        }
1648    }
1649
1650    /// Rigid, loss-free, at rest: (M q'' + g) at the joint over the ratio, plus the rotor's own J i q'', with q'' what
1651    /// the tool's acceleration asks at rest.
1652    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
1653        let zero = vec![0.0; pos.len()];
1654        let (q, qd, qdd) = self.joint_motion(pos, &zero, acc);
1655        let motor = |x: &[f64]| -> Vec<f64> { (0..self.n()).map(|k| x[k] * self.joints[k].drive.ratio()).collect() };
1656        self.rigid_motor_torque(&motor(&q), &motor(&qd), &motor(&qdd), out);
1657    }
1658
1659    /// The rigid model at q'' = 0: per joint, at its speed q' (`joint_motion`), the motor shaft's friction (with the
1660    /// gearbox's drag) at i q' and the joint's own friction (guides, bearings, a screw nut's preload) through the gearbox
1661    /// as `rigid_solve` takes it: f(q') / (i loss), the loss factor that of what the gearbox passes at rest, f plus the
1662    /// weight it holds (driven back where the weight pulls the joint along). The brake is released and the stops are
1663    /// not touched in a move.
1664    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
1665        let (_, qd, _) = self.joint_motion(pos, vel, &vec![0.0; pos.len()]);
1666        let mut hold = vec![0.0; out.len()];
1667        self.feedforward_torque(pos, &vec![0.0; pos.len()], &mut hold);
1668        for (k, joint) in self.joints.iter().enumerate() {
1669            let (j, v) = (&joint.drive, qd[k]);
1670            let friction = j.friction.torque(v);
1671            let loss = j.gearbox.loss_factor(friction + j.ratio() * hold[k], v);
1672            out[k] = j.shaft.torque(j.ratio() * v) + friction / (j.ratio() * loss);
1673        }
1674    }
1675
1676    fn rigid_guide_loads(&self, pos: &[f64], acc: &[f64], out: &mut Vec<[f64; 2]>) {
1677        self.mechanism.rigid_guide_loads(pos, acc, out);
1678    }
1679
1680    /// The friction in each joint (`RotaryJoint::friction`, its Coulomb level and viscous part, at the joint) as torque
1681    /// at its motor while the tool moves along `dir`: through the ratio and what a screw or rack passes on
1682    /// (`extra_efficiency`), the joint's speed per speed along the path from the kinematics.
1683    fn rigid_friction(&self, pos: &[f64], dir: &[f64], out: &mut Vec<[f64; 2]>) {
1684        let (_, qd, _) = self.joint_motion(pos, dir, &vec![0.0; pos.len()]);
1685        for (joint, rate) in self.joints.iter().zip(qd) {
1686            let (f, lever) = (&joint.drive.friction, 1.0 / (joint.drive.ratio() * joint.drive.extra_efficiency));
1687            let sign = if rate == 0.0 { 0.0 } else { rate.signum() };
1688            out.push([f.coulomb * sign * lever, f.viscous * rate * lever]);
1689        }
1690    }
1691
1692    /// The mechanism's signals (`Mechanism::signals`) and each joint's force (`joint.<id>.force`) at the joints' motion,
1693    /// with the force M q'' + h that the rigid model passes to each joint (the process force left out, as the
1694    /// feedforward leaves it out), read for each check of `rating_checks`; NaN for a life or a signal not among them.
1695    /// A check on `plan.<signal>` reads <signal>: a limit of the plan alone, which the verdicts judge on the setpoint's
1696    /// rigid motion through this (`analysis::Tally`), not on the simulated signal.
1697    fn rigid_checks(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut Vec<f64>) {
1698        let n = self.n();
1699        let (q, qd, qdd) = self.joint_motion(pos, vel, acc);
1700        let (mass, bias) = self.load(&q, &qd);
1701        let force: Vec<f64> = (0..n).map(|k| (0..n).map(|c| mass[k * n + c] * qdd[c]).sum::<f64>() + bias[k]).collect();
1702        let mut values = Vec::new();
1703        self.mechanism.signals(&q, &qd, &qdd, &force, &mut values);
1704        let infos = self.mechanism.signal_infos();
1705        for check in self.mechanism.rating_checks() {
1706            let signal = check.signal.strip_prefix("plan.").unwrap_or(&check.signal);
1707            let joint = (0..n).find(|&k| signal == format!("joint.{}.force", self.joints[k].id));
1708            let value = match (check.life, joint) {
1709                (true, _) => f64::NAN,
1710                (false, Some(k)) => force[k],
1711                (false, None) => infos.iter().position(|s| s.id == signal).map_or(f64::NAN, |i| values[i]),
1712            };
1713            out.push(value);
1714        }
1715    }
1716
1717    /// The joints' motion (`joint_motion`), then `rigid_motor_torque` with the velocity terms: the Coriolis and
1718    /// centripetal torques of M(q) changing with the pose, in joint space too.
1719    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
1720        let (q, qd, qdd) = self.joint_motion(pos, vel, acc);
1721        let motor = |x: &[f64]| -> Vec<f64> { (0..self.n()).map(|k| x[k] * self.joints[k].drive.ratio()).collect() };
1722        self.rigid_motor_torque(&motor(&q), &motor(&qd), &motor(&qdd), out);
1723    }
1724
1725    /// Exact in joint coordinates, velocity terms included (`feedforward_torque` leaves them out): M q'' + h at the
1726    /// joint over the ratio, plus the rotor's own J_rotor i q''.
1727    fn rigid_motor_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], out: &mut [f64]) {
1728        self.rigid_split_torque(angle, speed, acc, acc, out);
1729    }
1730
1731    /// Elastic: the gearbox's static twist under what reaches it, (torque − J_rotor acc) i at the joint (ripple, motor
1732    /// friction and the gearbox's losses and damping left out), times the ratio. Zeros where the joints are rigid.
1733    /// Behind a screw whose stiffness follows the nut, the far end's: `twist_at` has the nut's place.
1734    fn twist(&self, torque: &[f64], acc: &[f64], out: &mut [f64]) {
1735        for (k, joint) in self.joints.iter().enumerate() {
1736            let j = &joint.drive;
1737            out[k] = if self.elastic {
1738                j.ratio() * j.gearbox.static_twist((torque[k] - j.rotor_inertia * acc[k]) * j.ratio())
1739            } else {
1740                0.0
1741            };
1742        }
1743    }
1744
1745    /// `twist` with the gear's spring where the nut is, the rotor's angle over the ratio (`Gearbox::at`).
1746    fn twist_at(&self, angle: &[f64], torque: &[f64], acc: &[f64], out: &mut [f64]) {
1747        for (k, joint) in self.joints.iter().enumerate() {
1748            let j = &joint.drive;
1749            let gear = j.gearbox.at(angle[k] / j.ratio());
1750            out[k] = if self.elastic {
1751                j.ratio() * gear.static_twist((torque[k] - j.rotor_inertia * acc[k]) * j.ratio())
1752            } else {
1753                0.0
1754            };
1755        }
1756    }
1757
1758    fn rigid_split_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], rotor_acc: &[f64], out: &mut [f64]) {
1759        let n = self.n();
1760        let joint = |x: &[f64]| -> Vec<f64> { (0..n).map(|k| x[k] / self.joints[k].drive.ratio()).collect() };
1761        let (q, qd, qdd) = (joint(angle), joint(speed), joint(acc));
1762        let (mass, bias) = self.load(&q, &qd);
1763        for k in 0..n {
1764            let j = &self.joints[k].drive;
1765            let at_joint: f64 = (0..n).map(|c| mass[k * n + c] * qdd[c]).sum::<f64>() + bias[k];
1766            out[k] = at_joint / j.ratio() + j.rotor_inertia * rotor_acc[k];
1767        }
1768    }
1769
1770    fn energy(&self, s: &[f64]) -> f64 {
1771        self.energy_parts(s).iter().sum()
1772    }
1773
1774    fn set_payload_attached(&mut self, attached: bool) {
1775        if attached != self.payload_attached {
1776            self.rest_slack();
1777        }
1778        self.payload_attached = attached;
1779        self.mechanism.set_payload_attached(attached);
1780    }
1781    fn links(&self) -> Vec<String> {
1782        self.mechanism.links()
1783    }
1784    fn set_link_change(&mut self, link: usize, factor: f64, moment: [f64; 3]) {
1785        self.rest_slack();
1786        self.mechanism.set_link_change(link, factor, moment);
1787    }
1788    fn set_brake_engaged(&mut self, engaged: bool) {
1789        self.brake_engaged = engaged;
1790    }
1791    /// A joint meeting its stop within the step (`RotaryJoint::stop_substeps`). Each gear's
1792    /// efficiency switch near zero power at the step's start (`mech::Gearbox::fade_damping`) on the inertia it drives
1793    /// there, 1 / (M^-1)_kk of the load's mass matrix (the other joints free): the cuts `mech::fade_substeps` asks for.
1794    /// The most of them. The mass matrix only where a gear is near zero power.
1795    fn substeps_wanted(&self, s: &[f64], torque: &[f64], dt: f64, substeps: u32) -> u32 {
1796        let (n, h) = (self.n(), dt / f64::from(substeps));
1797        let (q, qd) = self.arms(s);
1798        let stop_cuts = (0..n).map(|k| self.joints[k].drive.stop_substeps(q[k], qd[k], dt)).max().unwrap_or(1);
1799        let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque).2);
1800        let damping: Vec<f64> = (0..n)
1801            .map(|k| {
1802                let gear = &self.joints[k].drive.gearbox;
1803                let output = match &rigid {
1804                    Some(out) => out[k],
1805                    None => {
1806                        gear.torque_with(s[2 * n + k], s[3 * n + k], s[k], s[n + k], self.arm(s, k)).rotor * gear.ratio
1807                    }
1808                };
1809                gear.fade_damping(output, qd[k])
1810            })
1811            .collect();
1812        if damping.iter().all(|c| *c == 0.0) {
1813            return stop_cuts;
1814        }
1815        let (q, rates) = self.all_joints(s);
1816        let (mass, _) = self.load_all(&q, &rates);
1817        let all = q.len();
1818        (0..n)
1819            .filter(|&k| damping[k] > 0.0)
1820            .map(|k| {
1821                let unit: Vec<f64> = (0..all).map(|i| if i == k { 1.0 } else { 0.0 }).collect();
1822                let inertia = solve(&mass, &unit).map_or(f64::NAN, |x| 1.0 / x[k]);
1823                crate::mech::fade_substeps(damping[k], h, inertia)
1824            })
1825            .fold(stop_cuts, u32::max)
1826    }
1827    /// The push acts on the joints beyond the gearboxes and on the links' bending modes, as the tool moves with each
1828    /// (`push_on_joints`, `push_on_modes`), in either model; its power is the budget's crash row.
1829    fn set_tool_force(&mut self, force: &[f64]) -> bool {
1830        self.push.clear();
1831        self.push.extend_from_slice(force);
1832        true
1833    }
1834
1835    /// The gearboxes, in the order of `thermal_parts`.
1836    /// The gearboxes' hysteresis states move on to where the step ended (`Gearbox::commit`), and so do the joints'
1837    /// presliding friction states (`ShaftFriction::commit`).
1838    fn after_step(&mut self, s: &mut [f64], _dt: f64) {
1839        let n = self.n();
1840        if self.elastic {
1841            for k in 0..n {
1842                self.joints[k].drive.gearbox.commit(s[2 * n + k], s[k]);
1843            }
1844        }
1845        // The joints' positions and speeds lead the state in both models (`arms`).
1846        for k in 0..n {
1847            self.joints[k].drive.friction.commit(s[k], s[n + k]);
1848        }
1849    }
1850    /// The mechanism's, then the gearboxes' hysteresis anchors, then those of the joints whose friction has a presliding
1851    /// state.
1852    fn memory(&self) -> Vec<f64> {
1853        let gears = crate::mech::Gearbox::anchors(self.joints.iter().map(|j| &j.drive.gearbox));
1854        let frictions =
1855            self.joints.iter().filter(|j| j.drive.friction.presliding > 0.0).flat_map(|j| j.drive.friction.anchor);
1856        [self.mechanism.memory(), gears, frictions.collect()].concat()
1857    }
1858    fn set_memory(&mut self, memory: &[f64]) {
1859        let (own, rest) = memory.split_at(self.mechanism.memory().len().min(memory.len()));
1860        self.mechanism.set_memory(own);
1861        // Two numbers per gear, three with its mesh friction's anchor (`Gearbox::anchors`).
1862        let geared = crate::mech::Gearbox::anchors(self.joints.iter().map(|j| &j.drive.gearbox)).len();
1863        let (gears, frictions) = rest.split_at(geared.min(rest.len()));
1864        crate::mech::Gearbox::set_anchors(self.joints.iter_mut().map(|j| &mut j.drive.gearbox), gears);
1865        let sliding = self.joints.iter_mut().filter(|j| j.drive.friction.presliding > 0.0);
1866        for (joint, anchor) in sliding.zip(frictions.as_chunks::<2>().0) {
1867            joint.drive.friction.anchor = *anchor;
1868        }
1869    }
1870
1871    fn set_part_temperatures(&mut self, rises: &[f64]) {
1872        let Some(law) = &self.thermal else { return };
1873        let geared = self.joints.iter_mut().enumerate().filter(|(_, j)| !j.drive.coupled);
1874        for ((k, joint), rise) in geared.zip(rises) {
1875            // From the joint's own gearbox's efficiency where it has one (a track's planetary gearbox beside an arm's
1876            // strain wave gears), else the shared one's.
1877            let warmed = match self.gear_efficiencies.get(k) {
1878                Some(&efficiency) => ThermalFeedback { efficiency, ..law.clone() }.gearbox_efficiency(*rise),
1879                None => law.gearbox_efficiency(*rise),
1880            };
1881            joint.drive.gearbox.efficiency = warmed * joint.drive.extra_efficiency;
1882            joint.drive.shaft.set_oil(law.viscosity_factor(*rise));
1883        }
1884    }
1885
1886    /// Elastic: per joint its gearbox's spring (K1, in series with a converter's own compliance behind it) between the
1887    /// rotor and the joint's rigid inertia M_kk with the other joints held, referred to the motor over the ratio.
1888    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
1889        let mut q = vec![0.0; self.n()];
1890        if !self.elastic || !self.mechanism.inverse(tool_pose, &mut q) {
1891            return Vec::new();
1892        }
1893        let (mass, _) = self.load(&q, &vec![0.0; self.n()]);
1894        let free = self.mechanism.passive_in_modes();
1895        let (all, whole) = (self.n() + self.passive.len(), self.load_with_free(&q));
1896        (0..self.n())
1897            .map(|k| {
1898                let j = &self.joints[k].drive;
1899                let load = match &whole {
1900                    // A rocking forearm on its spring moves with the joint's own mode: the load inertia the joint
1901                    // rings against is its held one less what the free joints take back at that frequency.
1902                    Some(m) if free > 0 => {
1903                        let (own, stiffness) = (m[k * all + k], j.gearbox.at(q[k]).stiffness);
1904                        let mut eff = own;
1905                        for _ in 0..3 {
1906                            let w2 = stiffness / eff;
1907                            let a: Vec<f64> = (0..free * free)
1908                                .map(|rc| {
1909                                    let (r, c) = (rc / free, rc % free);
1910                                    m[(self.n() + r) * all + self.n() + c]
1911                                        - if r == c { self.passive[r].0 / w2 } else { 0.0 }
1912                                })
1913                                .collect();
1914                            let b: Vec<f64> = (0..free).map(|r| m[(self.n() + r) * all + k]).collect();
1915                            let Some(x) = solve(&a, &b) else { break };
1916                            eff = own - b.iter().zip(&x).map(|(b, x)| b * x).sum::<f64>();
1917                        }
1918                        eff
1919                    }
1920                    _ => mass[k * self.n() + k],
1921                };
1922                j.train_at(q[k], load / (j.ratio() * j.ratio()) + j.rotor_inertia)
1923            })
1924            .collect()
1925    }
1926
1927    /// One joint: the lowest of its two-mass mode and its passive joints' (`single_joint_modes`). An arm: the lowest of
1928    /// its joints' modes with the motors held (`held_modes`, or with the links' bending two-way `coupled_modes`): each
1929    /// turns the joints and so moves the tool.
1930    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
1931        let mut q = vec![0.0; self.n()];
1932        if !self.mechanism.inverse(tool_pose, &mut q) {
1933            return None;
1934        }
1935        let modes = if self.n() == 1 {
1936            self.single_joint_modes(&q, false)
1937        } else if self.two_way {
1938            self.coupled_modes(&q, false)
1939        } else {
1940            self.held_modes(&q, false)
1941        };
1942        modes.iter().map(|m| m.hz).reduce(f64::min)
1943    }
1944
1945    /// One joint's two-mass mode and its passive joints' (`single_joint_modes`), or an arm's joints with the motors held
1946    /// (`held_modes`), and the links' bending modes (`Mechanism::flex_modes`), lowest first; two-way, the modes of joints
1947    /// and links together with the motors held (`coupled_modes`).
1948    fn modes(&self, tool_pose: &[f64]) -> Vec<sim_core::Mode> {
1949        let mut q = vec![0.0; self.n()];
1950        let mut out: Vec<sim_core::Mode> = if self.n() == 1 {
1951            if self.mechanism.inverse(tool_pose, &mut q) { self.single_joint_modes(&q, true) } else { Vec::new() }
1952        } else if !self.two_way && self.mechanism.inverse(tool_pose, &mut q) {
1953            self.held_modes(&q, true)
1954        } else {
1955            Vec::new()
1956        };
1957        if self.two_way {
1958            let mut q = vec![0.0; self.n()];
1959            if self.mechanism.inverse(tool_pose, &mut q) {
1960                out.extend(self.coupled_modes(&q, true));
1961            }
1962        } else {
1963            out.extend(self.mechanism.flex_modes().iter().map(|m| {
1964                let w = (m.stiffness / m.mass).sqrt();
1965                sim_core::Mode { hz: w / std::f64::consts::TAU, damping: m.damping / (2.0 * m.mass * w) }
1966            }));
1967        }
1968        out.sort_by(|a, b| a.hz.total_cmp(&b.hz));
1969        out
1970    }
1971
1972    fn setpoint_slack(&self) -> f64 {
1973        self.rest_slack()
1974    }
1975
1976    fn condition(&self, tool: &[f64]) -> Option<f64> {
1977        self.mechanism.condition(tool)
1978    }
1979
1980    fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
1981        if let Some(why) = self.mechanism.unreachable(tool, slack) {
1982            return Some(why);
1983        }
1984        let mut q = vec![0.0; self.n()];
1985        if !self.mechanism.inverse(tool, &mut q) {
1986            return Some("error-target-out-of-range");
1987        }
1988        // A joint beyond its stops, by more than `slack` (taken in the joint's unit: where the tool is the joints, as on
1989        // the arms and slides, that is the controller's slack; an arm's gears twist under its weight beyond a stop).
1990        let beyond = self
1991            .joints
1992            .iter()
1993            .zip(&q)
1994            .any(|(j, q)| *q < j.drive.range.0 - slack - 1e-9 || *q > j.drive.range.1 + slack + 1e-9);
1995        beyond.then_some("error-joint-beyond-stop")
1996    }
1997
1998    fn signal_infos(&self) -> Vec<SignalInfo> {
1999        let mut out = Vec::new();
2000        for (k, motor) in self.motors.iter().enumerate() {
2001            let unit = self.joints[k].unit;
2002            out.push(SignalInfo::new(
2003                format!("joint.{}.position", self.joints[k].id),
2004                self.joints[k].key,
2005                "quantity-joint-position",
2006                unit,
2007            ));
2008            out.push(SignalInfo::new(
2009                format!("joint.{}.force", self.joints[k].id),
2010                self.joints[k].key,
2011                "quantity-joint-force",
2012                self.units(k).1,
2013            ));
2014            if self.joints[k].gear_lever.is_some() || self.joints[k].unit != "m" {
2015                out.push(SignalInfo::new(
2016                    format!("gearbox.{}.output_torque", motor.id),
2017                    motor.key,
2018                    "quantity-gearbox-torque",
2019                    "N m",
2020                ));
2021            }
2022        }
2023        out.extend(self.mechanism.passive_signals());
2024        out.extend(self.mechanism.signal_infos());
2025        out.extend(self.mechanism.flex_modes().iter().map(|m| {
2026            let (id, quantity, unit) = m.kind.signal();
2027            SignalInfo::new(format!("link.{}.{id}", m.link + 1), JOINT_KEYS[m.link], quantity, unit)
2028        }));
2029        self.effect_infos(&mut out);
2030        out
2031    }
2032
2033    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2034        let (q, qd) = self.arms(s);
2035        let (acc, force) = self.motion(s, torque);
2036        for k in 0..self.n() {
2037            out.extend([q[k], force[k]]);
2038            match self.joints[k].gear_lever {
2039                // Ahead of the converter: more than the joint's force times the lever while it drives, less while the
2040                // load drives it back.
2041                Some(lever) => {
2042                    let e = self.joints[k].drive.extra_efficiency;
2043                    out.push(force[k] * lever * if force[k] * qd[k] >= 0.0 { 1.0 / e } else { e });
2044                }
2045                None if self.joints[k].unit != "m" => out.push(force[k]),
2046                None => {}
2047            }
2048        }
2049        let at = self.passive_at();
2050        out.extend(&s[at..at + self.passive.len()]);
2051        let jerk = if self.mechanism.reads_jerk() { self.joint_jerk(s, torque) } else { vec![0.0; acc.len()] };
2052        self.mechanism.signals_with_jerk(q, qd, &acc, &jerk, &force, out);
2053        out.extend_from_slice(self.flex_state(s).0);
2054    }
2055    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2056        self.view_signals(s, torque, out);
2057    }
2058    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2059        out.extend(self.losses(s, torque).powers);
2060    }
2061
2062    /// Each joint's friction (`RotaryJoint::friction_split`: with a slide's presliding also the rise to its breakaway
2063    /// level), owned by the joint's axis: the friction view spans that
2064    /// axis's speed limit (with the joint's own key it found no axis and spanned 1 m/s or rad/s).
2065    fn friction_contacts(&self) -> Vec<FrictionContact> {
2066        self.joints
2067            .iter()
2068            .zip(&self.axes)
2069            .map(|(j, axis)| FrictionContact { id: j.id_signal(), owner_key: axis.key })
2070            .collect()
2071    }
2072    fn friction_rotary(&self, i: usize) -> bool {
2073        i < self.joints.len() && self.units(i).0 == "rad/s"
2074    }
2075    fn friction_curve(&self, i: usize, speed: f64, _load_scale: f64) -> [f64; 3] {
2076        self.joints.get(i).map_or([0.0; 3], |joint| joint.drive.friction_split(speed))
2077    }
2078
2079    /// The gearboxes, where there are gearboxes (not on a direct drive).
2080    fn thermal_parts(&self) -> Vec<ThermalPart> {
2081        self.joints
2082            .iter()
2083            .zip(&self.motors)
2084            .filter(|(j, _)| !j.drive.coupled)
2085            .enumerate()
2086            .map(|(k, (_, m))| ThermalPart {
2087                id: GEARBOX_IDS[MOTOR_IDS.iter().position(|id| *id == m.id).unwrap_or(0)],
2088                kind: "gearbox",
2089                owner_key: m.key,
2090                scene_part: "gearbox",
2091                scene_index: k,
2092            })
2093            .collect()
2094    }
2095
2096    fn scene(&self, s: &[f64], out: &mut Scene) {
2097        let (q, _) = self.all_joints(s);
2098        let (rotor, speed) = self.rotors(s);
2099        out.parts.clear();
2100        out.labels.clear();
2101        self.mechanism.scene(&q, &rotor, &speed, out);
2102    }
2103    fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
2104        self.mechanism.scene_point(tool)
2105    }
2106
2107    /// The boxes of the scene that the mechanism names (`Mechanism::collision_parts`).
2108    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
2109        let mut scene = Scene::default();
2110        self.scene(s, &mut scene);
2111        sim_core::scene::scene_boxes(&scene.parts, self.mechanism.collision_parts())
2112    }
2113
2114    /// The links of the mechanism (`Mechanism::collision_links`) as capsules, for the check of the machine's own parts.
2115    fn self_collision_capsules(&self, s: &[f64]) -> Vec<sim_core::Capsule> {
2116        let links = self.mechanism.collision_links();
2117        let mut capsules = self.collision_capsules(s);
2118        if links.is_empty() {
2119            return capsules;
2120        }
2121        let mut scene = Scene::default();
2122        self.scene(s, &mut scene);
2123        capsules.extend(scene.parts.iter().filter(|part| links.contains(&part.id)).filter_map(
2124            |part| match part.shape {
2125                sim_core::Shape::Segment { to, width } => {
2126                    Some(sim_core::Capsule { from: part.pos, to, radius: width / 2.0 })
2127                }
2128                _ => None,
2129            },
2130        ));
2131        capsules
2132    }
2133
2134    /// The exact adjacency of the links: link i with link i + 1, across a link of no length (the frames of a spherical
2135    /// wrist coincide) to the next one, and with the links of no length at the end of the next one; the tool's boxes
2136    /// with the last two links that have a length and those after them (the flange box reaches back over the link
2137    /// before the last). The obstacles' capsules come first among the capsules and are not joined to anything here.
2138    fn connected_bodies(&self, s: &[f64], boxes: usize, capsules: usize) -> Option<Vec<(usize, usize)>> {
2139        if self.mechanism.collision_links().is_empty() {
2140            return None;
2141        }
2142        let all = self.self_collision_capsules(s);
2143        if all.len() != capsules {
2144            return None;
2145        }
2146        let own = self.collision_capsules(s).len();
2147        let long: Vec<bool> =
2148            all.iter().map(|c| (0..3).map(|i| (c.to[i] - c.from[i]).powi(2)).sum::<f64>() > 1e-12).collect();
2149        let mut pairs = Vec::new();
2150        for i in own..capsules {
2151            // Up to and including the next link that has a length, and the links of no length at its end (a point at the
2152            // flange sits on the quill, at its length from the arm before).
2153            let mut reached = false;
2154            for j in i + 1..capsules {
2155                if reached && long[j] {
2156                    break;
2157                }
2158                pairs.push((boxes + i, boxes + j));
2159                reached |= long[j];
2160            }
2161        }
2162        // The last two links with a length, and what comes after them.
2163        let from = (own..capsules).rev().filter(|k| long[*k]).nth(1).unwrap_or(own);
2164        for b in 0..boxes {
2165            pairs.extend((from..capsules).map(|k| (b, boxes + k)));
2166            pairs.extend((0..b).map(|a| (a, b)));
2167        }
2168        Some(pairs)
2169    }
2170}
2171
2172impl<M: Mechanism> JointMachine<M> {
2173    /// The joints' positions, speeds and accelerations for the tool's pose, speed and acceleration. Where the tool is
2174    /// the joints, those themselves. With as many axes as joints: q' = J^-1 v and q'' = J^-1 (a - J' q'), J' q' the
2175    /// second difference of the forward kinematics along q'. With fewer (a redundant arm): by central differences of
2176    /// the mechanism's `inverse`, which resolves the redundancy, along v and along a, so that speeds and accelerations
2177    /// are those of the very joints it gives: q' = (q(x + h v) - q(x - h v)) / 2h, q'' = (q(x + h v) - 2 q(x) +
2178    /// q(x - h v)) / h^2 + (q(x + k a) - q(x - k a)) / 2k, steps of 1e-3 of the tool's units (the inverse's solution is good
2179    /// to about 1e-11, which a second difference over 1e-4 would multiply by 1e8).
2180    pub fn joint_motion(&self, pos: &[f64], vel: &[f64], acc: &[f64]) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
2181        let (n, m) = (self.n(), self.axes.len());
2182        if self.mechanism.tool_is_joints() {
2183            return (pos[..n].to_vec(), vel[..n].to_vec(), acc[..n].to_vec());
2184        }
2185        let solved = |x: &[f64]| -> Vec<f64> {
2186            let mut q = vec![0.0; n];
2187            if !self.mechanism.inverse(x, &mut q) {
2188                q.fill(f64::NAN);
2189            }
2190            q
2191        };
2192        let q = solved(pos);
2193        if m < n {
2194            let along = |d: &[f64]| -> Option<(f64, Vec<f64>, Vec<f64>)> {
2195                let size = d.iter().map(|v| v * v).sum::<f64>().sqrt();
2196                (size > 0.0).then(|| {
2197                    let h = 1e-3 / size;
2198                    let at = |s: f64| solved(&(0..m).map(|i| pos[i] + s * d[i]).collect::<Vec<_>>());
2199                    (h, at(h), at(-h))
2200                })
2201            };
2202            let (mut qd, mut qdd) = (vec![0.0; n], vec![0.0; n]);
2203            if let Some((h, ahead, behind)) = along(&vel[..m]) {
2204                for k in 0..n {
2205                    qd[k] = (ahead[k] - behind[k]) / (2.0 * h);
2206                    qdd[k] = (ahead[k] - 2.0 * q[k] + behind[k]) / (h * h);
2207                }
2208            }
2209            if let Some((h, ahead, behind)) = along(&acc[..m]) {
2210                for k in 0..n {
2211                    qdd[k] += (ahead[k] - behind[k]) / (2.0 * h);
2212                }
2213            }
2214            return (q, qd, qdd);
2215        }
2216        let jac = self.jacobian(&q);
2217        let qd = solve(&jac, &vel[..n]).unwrap_or_else(|| vec![f64::NAN; n]);
2218        let speed = qd.iter().map(|v| v * v).sum::<f64>().sqrt();
2219        let mut curve = vec![0.0; n];
2220        if speed > 0.0 {
2221            // A step of 1e-4 rad (m) along q': truncation ~1e-8, rounding ~1e-16 / 1e-8 of the tool's size.
2222            let h = 1e-4 / speed;
2223            let (mut a, mut b, mut c) = (vec![0.0; n], vec![0.0; n], vec![0.0; n]);
2224            let at = |s: f64| -> Vec<f64> { (0..n).map(|k| q[k] + s * qd[k]).collect() };
2225            self.mechanism.forward(&at(h), &mut a);
2226            self.mechanism.forward(&q, &mut b);
2227            self.mechanism.forward(&at(-h), &mut c);
2228            curve = (0..n).map(|k| (a[k] - 2.0 * b[k] + c[k]) / (h * h)).collect();
2229        }
2230        let rhs: Vec<f64> = (0..n).map(|k| acc[k] - curve[k]).collect();
2231        let qdd = solve(&jac, &rhs).unwrap_or_else(|| vec![f64::NAN; n]);
2232        (q, qd, qdd)
2233    }
2234
2235    /// d tool / d q (axes x joints, row by row), by central differences of `Mechanism::forward`; exact (to rounding)
2236    /// where the tool is the joints.
2237    pub fn jacobian(&self, q: &[f64]) -> Vec<f64> {
2238        let (n, rows) = (self.n(), self.axes.len());
2239        // Where the tool is the joints, the identity to the bit: the difference quotient of the copy is off by up to
2240        // 1e-10, and a model switch that rebuilt the joints changed the tool's speed by that.
2241        if self.mechanism.tool_is_joints() {
2242            return (0..rows * n).map(|i| if i / n == i % n { 1.0 } else { 0.0 }).collect();
2243        }
2244        let (mut jac, mut a, mut b) = (vec![0.0; rows * n], vec![0.0; rows], vec![0.0; rows]);
2245        let mut p = q.to_vec();
2246        for c in 0..n {
2247            let h = 1e-6 * q[c].abs().max(1.0);
2248            p[c] = q[c] + h;
2249            self.mechanism.forward(&p, &mut a);
2250            p[c] = q[c] - h;
2251            self.mechanism.forward(&p, &mut b);
2252            p[c] = q[c];
2253            for r in 0..rows {
2254                jac[r * n + c] = (a[r] - b[r]) / (2.0 * h);
2255            }
2256        }
2257        jac
2258    }
2259}
2260
2261/// Motor ids "1" to "7" and the ids of their gearboxes' loss powers, so that `ThermalPart` gets `&'static str`s.
2262pub const MOTOR_IDS: [&str; 7] = ["1", "2", "3", "4", "5", "6", "7"];
2263const GEARBOX_IDS: [&str; 7] =
2264    ["gearbox_1", "gearbox_2", "gearbox_3", "gearbox_4", "gearbox_5", "gearbox_6", "gearbox_7"];
2265/// Translation keys of motors 1 to 7 and of joints 1 to 7.
2266pub const MOTOR_KEYS: [&str; 7] = [
2267    "motor-joint-1",
2268    "motor-joint-2",
2269    "motor-joint-3",
2270    "motor-joint-4",
2271    "motor-joint-5",
2272    "motor-joint-6",
2273    "motor-joint-7",
2274];
2275pub const JOINT_KEYS: [&str; 7] = ["joint-1", "joint-2", "joint-3", "joint-4", "joint-5", "joint-6", "joint-7"];
2276const JOINT_SIGNALS: [&str; 7] = ["joint.1", "joint.2", "joint.3", "joint.4", "joint.5", "joint.6", "joint.7"];
2277
2278impl JointSpec {
2279    /// "joint.<id>" for the friction contact, where the id is one of `MOTOR_IDS`.
2280    fn id_signal(&self) -> &'static str {
2281        JOINT_SIGNALS[MOTOR_IDS.iter().position(|id| *id == self.id).unwrap_or(0)]
2282    }
2283}
2284
2285#[cfg(test)]
2286mod tests {
2287    use super::*;
2288
2289    /// Two joints on springs of 100 and 50 N m/rad with the mass matrix [[2, 0.5], [0.5, 1]] kg m^2: det(K - l M) =
2290    /// (100 - 2 l)(50 - l) - (0.5 l)^2 = 1.75 l^2 - 200 l + 5000 = 0, l = (200 -+ sqrt(5000)) / 3.5 = 36.939805 and
2291    /// 77.345910 (rad/s)^2, 0.967314 and 1.399712 Hz. Uncoupled (no 0.5), each joint alone: sqrt(k / J) / 2 pi, 1.125395
2292    /// Hz for both. A damper of 2 N m s/rad on the first joint alone damps the uncoupled first mode by c / (2 sqrt(k J))
2293    /// = 2 / (2 sqrt(200)) = 0.070711.
2294    #[test]
2295    fn held_joint_modes_are_the_hand_solved_eigenvalues() {
2296        let tau = std::f64::consts::TAU;
2297        let coupled = generalized_modes(&[2.0, 0.5, 0.5, 1.0], &[100.0, 50.0], |_, _| 0.0, 2);
2298        let mut hz: Vec<f64> = coupled.iter().map(|m| m.hz).collect();
2299        hz.sort_by(f64::total_cmp);
2300        let by_hand = [(200.0 - 5000f64.sqrt()) / 3.5, (200.0 + 5000f64.sqrt()) / 3.5].map(|l: f64| l.sqrt() / tau);
2301        assert!((hz[0] - 0.967314).abs() < 1e-6 && (hz[1] - 1.399712).abs() < 1e-6, "{hz:?}");
2302        assert!((hz[0] - by_hand[0]).abs() < 1e-12 && (hz[1] - by_hand[1]).abs() < 1e-12);
2303        let alone = generalized_modes(&[2.0, 0.0, 0.0, 1.0], &[100.0, 50.0], |r, _| [2.0, 0.0][r], 2);
2304        for m in &alone {
2305            assert!((m.hz - 1.125395).abs() < 1e-6, "{alone:?}");
2306        }
2307        assert!(alone.iter().any(|m| (m.damping - 0.070711).abs() < 1e-6), "{alone:?}");
2308    }
2309
2310    /// The two joints above with a damper of 6 N m s/rad on the first and 0.5 on the second, C not proportional to M and
2311    /// K: each mode's damping ratio is that of its root of det(M l^2 + C l + K) = (2 l^2 + 6 l + 100)(l^2 + 0.5 l + 50) -
2312    /// (0.5 l^2)^2, found here by Newton's method from the undamped frequency (not through the companion matrix the code
2313    /// takes), -Re l / |l|; the frequencies stay the undamped ones to the bit. The two roots' -Re l add up to half the
2314    /// trace of M^-1 C, (1 x 6 + 2 x 0.5) / 1.75 / 2 = 2.0 (M^-1 = [[1, -0.5], [-0.5, 2]] / 1.75).
2315    #[test]
2316    fn coupled_modes_are_damped_as_the_damped_problems_roots() {
2317        type Cx = (f64, f64);
2318        let mul = |a: Cx, b: Cx| (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0);
2319        let add = |a: Cx, b: Cx| (a.0 + b.0, a.1 + b.1);
2320        let poly = |l: Cx, d: [f64; 3]| add(add(mul((d[0], 0.0), mul(l, l)), mul((d[1], 0.0), l)), (d[2], 0.0));
2321        let det = |l: Cx| {
2322            let off = mul((0.5, 0.0), mul(l, l));
2323            let a = mul(poly(l, [2.0, 6.0, 100.0]), poly(l, [1.0, 0.5, 50.0]));
2324            add(a, mul((-1.0, 0.0), mul(off, off)))
2325        };
2326        let root = |mut l: Cx| {
2327            for _ in 0..100 {
2328                let h = 1e-7 * l.0.hypot(l.1);
2329                let (f, g) = (det(l), add(det((l.0 + h, l.1)), mul((-1.0, 0.0), det(l))));
2330                let slope = (g.0 / h, g.1 / h);
2331                let n = slope.0 * slope.0 + slope.1 * slope.1;
2332                let step = ((f.0 * slope.0 + f.1 * slope.1) / n, (f.1 * slope.0 - f.0 * slope.1) / n);
2333                l = (l.0 - step.0, l.1 - step.1);
2334            }
2335            l
2336        };
2337        let (m, k, c) = ([2.0, 0.5, 0.5, 1.0], [100.0, 50.0], [6.0, 0.5]);
2338        let modes = generalized_modes(&m, &k, |r, _| c[r], 2);
2339        let undamped = generalized_modes(&m, &k, |_, _| 0.0, 2);
2340        let mut real_sum = 0.0;
2341        for (mode, plain) in modes.iter().zip(&undamped) {
2342            assert_eq!(mode.hz, plain.hz);
2343            let w = std::f64::consts::TAU * mode.hz;
2344            let l = root((-0.1 * w, w));
2345            assert!(det(l).0.hypot(det(l).1) < 1e-9, "{l:?}");
2346            let by_hand = -l.0 / l.0.hypot(l.1);
2347            assert!((mode.damping - by_hand).abs() < 1e-9, "{mode:?} against {by_hand}");
2348            real_sum -= l.0;
2349        }
2350        assert!((real_sum - 2.0).abs() < 1e-9, "{real_sum}");
2351    }
2352
2353    #[test]
2354    fn gaussian_elimination_solves_and_refuses_singular() {
2355        let x = solve(&[0.0, 2.0, 1.0, 1.0], &[4.0, 3.0]).unwrap();
2356        assert!((x[0] - 1.0).abs() < 1e-12 && (x[1] - 2.0).abs() < 1e-12);
2357        assert!(solve(&[1.0, 2.0, 2.0, 4.0], &[1.0, 2.0]).is_none());
2358    }
2359}