Skip to main content

machine_wafer_handler/
lib.rs

1//! Wafer handler: the R-theta-Z arm of semiconductor and flat-panel handling. A column lifts (Z, motor 3, on a ball
2//! screw) and turns (theta, motor 1) an arm of two links of equal length L in the horizontal plane. The upper arm turns
3//! on the column (motor 2, riding on the column); inside it a band from a pulley fixed to the column to one on the
4//! forearm turns the forearm against the upper arm at 2:1, and inside the forearm a band from a pulley fixed to the upper
5//! arm to one on the end effector turns the effector against the forearm at 1:2. So the one motor 2 runs the wrist along
6//! the radial line and the effector keeps pointing outwards along it. The tool pose is (r, theta, z): r the wafer
7//! centre's distance from the column axis along the effector's direction, theta that direction, z the lift.
8//!
9//! Angle convention: phi is the upper arm's angle from the radial line (the column's direction theta), positive
10//! anticlockwise; the links' absolute angles are
11//!
12//! ```text
13//! upper arm  a1 = theta + phi
14//! forearm    a2 = theta - phi + beta      (2:1 against the upper arm: a2 - a1 = -2 phi)
15//! effector   a3 = theta + gamma           (1:2 against the forearm: a3 - a2 = phi)
16//! wrist      W = L u(a1) + L u(a2) = 2 L cos(phi) u(theta)          (beta = gamma = 0)
17//! wafer      C = W + e u(a3),  r = 2 L cos(phi) + e
18//! ```
19//!
20//! with u(a) = (cos a, sin a) and e the effector's length from the wrist to the wafer centre. beta and gamma are the
21//! bands' stretch (effects.band_elasticity), zero where they are rigid. dr/dphi = -2 L sin(phi): zero at full extension
22//! (phi = 0, r = 2 L + e), the singular pose; largest at phi = 90 degrees (the wrist over the column). The working range
23//! keeps phi above the angle where 1 / sin(phi) (`condition`) passes `workspace.max_condition_number`.
24//!
25//! Dynamics: four bodies in the plane (upper arm, forearm, effector, wafer) and the column's turn, each body's kinetic
26//! energy 1/2 m |v|^2 + 1/2 I w^2 with v = J_v q' and w = a_k . q' over q = [theta, phi, beta, gamma] (Kane's method):
27//!
28//! ```text
29//! M(q) q'' + h(q, q') = Q,   M = J_c + sum m J_v^T J_v + I a_k a_k^T,   h = sum m J_v^T (dJ_v/dt q')
30//! ```
31//!
32//! h carries the centrifugal and Coriolis coupling of theta and phi: turning at theta' pushes the arm outwards (the
33//! classic handler error, the wafer pushed out in a fast turn, held by motor 2), and extending at phi' during a turn
34//! drags on motor 1. Gravity acts along -z, on the joints' bearings: it loads the Z motor alone. Each band is a loop of
35//! two spans of stiffness k and pretension T0 over a distal pulley of radius r_b (the proximal one 2 r_b at the elbow
36//! band, r_b / 2 at the wrist band); its stretch s1 = -r_b1 beta, s2 = r_b2 (beta / 2 - gamma), the spans' tensions
37//! T0 +- k s (none once a span runs slack), and its torques on beta and gamma r_b1 dT1 - r_b2 dT2 / 2 and r_b2 dT2.
38//! Motors 1 and 2 drive theta and phi through `RotaryJoint`s, elastic or rigid (effects.joint_elasticity); the Z stroke
39//! is a `RotaryJoint` on a `BallScrew` (motor 3's own config) that lifts the column, the links and the wafer, elastic or
40//! rigid by the same switch: elastic, the coupling's and the screw's stiffness in series is a spring between the rotor
41//! and the column (`Lift`), whose mode with the rotor held is sqrt(K / m) / 2 pi.
42
43use sim_components::catalog::motor_config;
44use sim_components::joint::RotaryJoint;
45use sim_components::mech::{GearTorque, ThermalFeedback};
46use sim_components::transmission::BallScrew;
47use sim_core::{
48    AxisInfo, Config, ConfigError, ENERGY_PARTS, LOSS_PREFIX, Label, Machine, MachineEntry, Mode, MotorInfo, Part,
49    RatingCheck, Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
50};
51
52const I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
53
54pub static ENTRY: MachineEntry = MachineEntry {
55    id: "wafer-handler",
56    key: "machine-wafer-handler",
57    default_config: include_str!("../default.toml"),
58    i18n: I18N,
59    build,
60    suite_configs,
61};
62
63/// Effects that take energy out or put it in; the standard suite runs with them off.
64pub const LOSSY_EFFECTS: [&str; 7] = [
65    "joint_friction",
66    "motor_friction",
67    "gearbox_drag",
68    "gearbox_lost_motion",
69    "gearbox_efficiency",
70    "torque_ripple",
71    "holding_brake",
72];
73
74fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
75    sim_components::base::mount(cfg, Box::new(WaferHandler::new(cfg)?))
76}
77
78/// The default config with every loss switched off: the effects above, the dampers of the gearboxes, the stops and
79/// the bands.
80pub fn lossless_config() -> Config {
81    let mut cfg = ENTRY.config();
82    for effect in LOSSY_EFFECTS {
83        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
84    }
85    for key in [
86        "gearbox.damping_nm_s_rad",
87        "joint.stop_damping_nm_s_rad",
88        "slide.stop_damping_n_s_m",
89        "elbow_band.span_damping_n_s_m",
90        "wrist_band.span_damping_n_s_m",
91    ] {
92        cfg.set_text(&format!("{key} = 0.0")).unwrap();
93    }
94    cfg
95}
96
97/// Loss-free models: rigid, elastic gearboxes, elastic bands and both, with and without the wafer; the elastic one
98/// with part heating and the temperature feedback (no loss, so the gearboxes stay at ambient).
99fn suite_configs() -> Vec<Config> {
100    let mut out = Vec::new();
101    for (gears, bands, payload) in
102        [(false, false, true), (false, false, false), (true, true, true), (true, true, false), (false, true, true)]
103    {
104        let mut cfg = lossless_config();
105        cfg.set_text(&format!("effects.joint_elasticity = {gears}")).unwrap();
106        cfg.set_text(&format!("effects.band_elasticity = {bands}")).unwrap();
107        cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
108        cfg.set_text(&format!("effects.part_heating = {}", gears && payload)).unwrap();
109        cfg.set_text(&format!("effects.thermal_feedback = {}", gears && payload)).unwrap();
110        out.push(cfg);
111    }
112    out
113}
114
115/// A vector in the plane, (x, y).
116pub type V2 = [f64; 2];
117/// The arm's coordinates [theta, phi, beta, gamma], or rates of them.
118pub type Q = [f64; 4];
119/// A 4 x 4 matrix over them.
120pub type Mat = [[f64; 4]; 4];
121
122fn unit(a: f64) -> V2 {
123    [a.cos(), a.sin()]
124}
125
126fn normal(a: f64) -> V2 {
127    [-a.sin(), a.cos()]
128}
129
130fn dot(a: &[f64], b: &[f64]) -> f64 {
131    a.iter().zip(b).map(|(x, y)| x * y).sum()
132}
133
134/// Solves the leading `n` x `n` system m x = b by Gaussian elimination with partial pivoting; `None` where it is
135/// singular. The entries beyond `n` come out zero.
136pub fn solve(m: &Mat, b: &Q, n: usize) -> Option<Q> {
137    let (mut a, mut x) = (*m, *b);
138    for c in 0..n {
139        let p = (c..n).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?;
140        if !(a[p][c].abs() > 1e-300) {
141            return None;
142        }
143        a.swap(c, p);
144        x.swap(c, p);
145        for r in c + 1..n {
146            let f = a[r][c] / a[c][c];
147            for k in c..n {
148                a[r][k] -= f * a[c][k];
149            }
150            x[r] -= f * x[c];
151        }
152    }
153    let mut out = [0.0; 4];
154    for c in (0..n).rev() {
155        let rest: f64 = (c + 1..n).map(|k| a[c][k] * out[k]).sum();
156        out[c] = (x[c] - rest) / a[c][c];
157    }
158    out.iter().all(|v| v.is_finite()).then_some(out)
159}
160
161/// The eigenvalues of the symmetric generalised problem K v = lambda M v over the leading `n` coordinates, lowest
162/// first: M = L L^T (Cholesky), then the symmetric L^-1 K L^-T by Jacobi rotations.
163pub fn generalised_eigenvalues(m: &Mat, k: &Mat, n: usize) -> Option<Vec<f64>> {
164    let mut l = [[0.0; 4]; 4];
165    for i in 0..n {
166        for j in 0..=i {
167            let s: f64 = (0..j).map(|p| l[i][p] * l[j][p]).sum();
168            if i == j {
169                let d = m[i][i] - s;
170                if !(d > 0.0) {
171                    return None;
172                }
173                l[i][i] = d.sqrt();
174            } else {
175                l[i][j] = (m[i][j] - s) / l[j][j];
176            }
177        }
178    }
179    // X = L^-1 K, then A = X L^-T, row by row with forward substitution.
180    let lower_solve = |b: [f64; 4]| {
181        let mut y = [0.0; 4];
182        for i in 0..n {
183            y[i] = (b[i] - (0..i).map(|p| l[i][p] * y[p]).sum::<f64>()) / l[i][i];
184        }
185        y
186    };
187    let columns: Vec<[f64; 4]> = (0..n).map(|c| lower_solve(std::array::from_fn(|r| k[r][c]))).collect();
188    let mut x = [[0.0; 4]; 4];
189    for c in 0..n {
190        for r in 0..n {
191            x[r][c] = columns[c][r];
192        }
193    }
194    let mut a = [[0.0; 4]; 4];
195    for r in 0..n {
196        let row = lower_solve(x[r]);
197        a[r][..n].copy_from_slice(&row[..n]);
198    }
199    for _ in 0..100 {
200        let off: f64 = (0..n)
201            .flat_map(|i| (0..n).filter(move |&j| j != i).map(move |j| (i, j)))
202            .map(|(i, j)| a[i][j] * a[i][j])
203            .sum();
204        if off < 1e-24 * (0..n).map(|i| a[i][i] * a[i][i]).sum::<f64>().max(1e-300) {
205            break;
206        }
207        for p in 0..n {
208            for q in p + 1..n {
209                if a[p][q].abs() < 1e-300 {
210                    continue;
211                }
212                let theta = 0.5 * (2.0 * a[p][q]).atan2(a[q][q] - a[p][p]);
213                let (s, c) = theta.sin_cos();
214                for k in 0..n {
215                    let (kp, kq) = (a[k][p], a[k][q]);
216                    a[k][p] = c * kp - s * kq;
217                    a[k][q] = s * kp + c * kq;
218                }
219                for k in 0..n {
220                    let (pk, qk) = (a[p][k], a[q][k]);
221                    a[p][k] = c * pk - s * qk;
222                    a[q][k] = s * pk + c * qk;
223                }
224            }
225        }
226    }
227    let mut out: Vec<f64> = (0..n).map(|i| a[i][i]).collect();
228    out.sort_by(f64::total_cmp);
229    Some(out)
230}
231
232/// The damping ratio of the mode of K v = lambda M v at `lambda` under the damping matrix C, over the leading `n`
233/// coordinates: v'Cv / (2 w v'Mv), w = sqrt(lambda), the shape v by inverse iteration on K - lambda (1 + 1e-9) M.
234pub fn modal_damping(m: &Mat, k: &Mat, c: &Mat, n: usize, lambda: f64) -> f64 {
235    let shift = lambda * (1.0 + 1e-9);
236    let a: Mat = std::array::from_fn(|i| std::array::from_fn(|j| k[i][j] - shift * m[i][j]));
237    let mut v: Q = [1.0, 0.7, 0.4, 0.2];
238    for _ in 0..3 {
239        let Some(next) = solve(&a, &v, n) else { break };
240        let size = dot(&next, &next).sqrt();
241        v = next.map(|x| x / size);
242    }
243    let quad = |p: &Mat| (0..n).map(|i| v[i] * (0..n).map(|j| p[i][j] * v[j]).sum::<f64>()).sum::<f64>();
244    quad(c) / (2.0 * lambda.sqrt() * quad(m))
245}
246
247/// The links' absolute angles over q = [theta, phi, beta, gamma]: upper arm, forearm, effector.
248pub const LINK_ANGLES: [Q; 3] = [[1.0, 1.0, 0.0, 0.0], [1.0, -1.0, 1.0, 0.0], [1.0, 0.0, 0.0, 1.0]];
249
250/// A rigid body of the arm: its mass, its inertia about its own centre (about z), and its centre's distance from the
251/// joint it turns about, along its link.
252#[derive(Debug, Clone, Copy, PartialEq)]
253pub struct Body {
254    pub mass: f64,
255    pub inertia: f64,
256    pub centre: f64,
257}
258
259/// The arm's geometry and masses, apart from drives and bands.
260#[derive(Debug, Clone)]
261pub struct Arm {
262    /// Both links' length L, and the effector's from the wrist to the wafer centre.
263    pub link: f64,
264    pub effector: f64,
265    /// What turns with the column about its axis (the column's top, motor 2, the shoulder pulley), kg m^2.
266    pub column_inertia: f64,
267    /// Upper arm, forearm, effector.
268    pub bodies: [Body; 3],
269    /// The wafer, its centre at the effector's length.
270    pub wafer: Body,
271}
272
273impl Arm {
274    /// The links' absolute angles at q.
275    pub fn angles(q: &Q) -> [f64; 3] {
276        LINK_ANGLES.map(|a| dot(&a, q))
277    }
278
279    /// r(phi) = 2 L cos(phi) + e, and its first and second derivative by phi.
280    pub fn reach(&self, phi: f64) -> [f64; 3] {
281        let (s, c) = phi.sin_cos();
282        let two_l = 2.0 * self.link;
283        [two_l * c + self.effector, -two_l * s, -two_l * c]
284    }
285
286    /// The upper arm's angle phi from the radial line for a reach r; NaN beyond 2 L + e or behind -2 L + e.
287    pub fn phi(&self, r: f64) -> f64 {
288        let c = (r - self.effector) / (2.0 * self.link);
289        if (-1.0..=1.0).contains(&c) { c.acos() } else { f64::NAN }
290    }
291
292    /// The segments from the column axis to a point on link `k` at `d` from its joint: (length, link).
293    fn segments(&self, k: usize, d: f64) -> impl Iterator<Item = (f64, usize)> {
294        (0..k).map(|j| (self.link, j)).chain(std::iter::once((d, k)))
295    }
296
297    /// The point on link `k` at `d` from its joint.
298    pub fn point(&self, q: &Q, k: usize, d: f64) -> V2 {
299        let a = Self::angles(q);
300        self.segments(k, d).fold([0.0; 2], |p, (l, j)| {
301            let u = unit(a[j]);
302            [p[0] + l * u[0], p[1] + l * u[1]]
303        })
304    }
305
306    /// That point's Jacobian dp/dq (rows x and y) and its acceleration at q'' = 0 (the centripetal terms).
307    pub fn point_motion(&self, q: &Q, qd: &Q, k: usize, d: f64) -> ([Q; 2], V2) {
308        let a = Self::angles(q);
309        let w = LINK_ANGLES.map(|row| dot(&row, qd));
310        let (mut jac, mut bias) = ([[0.0; 4]; 2], [0.0; 2]);
311        for (l, j) in self.segments(k, d) {
312            let (n, u) = (normal(a[j]), unit(a[j]));
313            for r in 0..2 {
314                for c in 0..4 {
315                    jac[r][c] += l * n[r] * LINK_ANGLES[j][c];
316                }
317                bias[r] -= l * w[j] * w[j] * u[r];
318            }
319        }
320        (jac, bias)
321    }
322
323    /// The wafer centre at q.
324    pub fn wafer_centre(&self, q: &Q) -> V2 {
325        self.point(q, 2, self.effector)
326    }
327
328    /// The bodies with their link and centre: upper arm, forearm, effector, and the wafer while it is held.
329    fn moving(&self, wafer: bool) -> impl Iterator<Item = (usize, Body)> + '_ {
330        let mut list = vec![(0, self.bodies[0]), (1, self.bodies[1]), (2, self.bodies[2])];
331        if wafer {
332            list.push((2, Body { centre: self.effector, ..self.wafer }));
333        }
334        list.into_iter()
335    }
336
337    /// The mass matrix M (column, links, effector, and the wafer while held) and the velocity term h = sum m J_v^T
338    /// (dJ_v/dt q') at q and q', over all four coordinates.
339    pub fn dynamics(&self, q: &Q, qd: &Q, wafer: bool) -> (Mat, Q) {
340        let (mut m, mut h) = ([[0.0; 4]; 4], [0.0; 4]);
341        m[0][0] = self.column_inertia;
342        for (k, body) in self.moving(wafer) {
343            let (jac, bias) = self.point_motion(q, qd, k, body.centre);
344            for r in 0..4 {
345                for c in 0..4 {
346                    m[r][c] += body.mass * (jac[0][r] * jac[0][c] + jac[1][r] * jac[1][c])
347                        + body.inertia * LINK_ANGLES[k][r] * LINK_ANGLES[k][c];
348                }
349                h[r] += body.mass * (jac[0][r] * bias[0] + jac[1][r] * bias[1]);
350            }
351        }
352        (m, h)
353    }
354
355    /// The mass the arm moves in the plane (links, effector, wafer while held), kg.
356    pub fn mass(&self, wafer: bool) -> f64 {
357        self.moving(wafer).map(|(_, b)| b.mass).sum()
358    }
359}
360
361/// A band in a link: a loop of two spans over a distal pulley of radius `radius` (the proximal pulley's radius is the
362/// coupling's ratio times it), each span of `stiffness` and `damping`, tensioned to `pretension`.
363#[derive(Debug, Clone, Copy, PartialEq)]
364pub struct Band {
365    pub radius: f64,
366    pub stiffness: f64,
367    pub damping: f64,
368    pub pretension: f64,
369}
370
371impl Band {
372    fn from_config(cfg: &Config, table: &str) -> Result<Self, ConfigError> {
373        Ok(Self {
374            radius: cfg.positive(&format!("{table}.pulley_radius_m"))?,
375            stiffness: cfg.positive(&format!("{table}.span_stiffness_n_m"))?,
376            damping: cfg.non_negative(&format!("{table}.span_damping_n_s_m"))?,
377            pretension: cfg.positive(&format!("{table}.pretension_n"))?,
378        })
379    }
380
381    /// A span's tension at an elongation `e` beyond its pretensioned length and its rate: T0 + k e + c e' while its
382    /// spring holds tension, none once it runs slack.
383    pub fn span_tension(&self, e: f64, rate: f64) -> f64 {
384        if self.pretension + self.stiffness * e > 0.0 {
385            self.pretension + self.stiffness * e + self.damping * rate
386        } else {
387            0.0
388        }
389    }
390
391    /// The tension of the span stretched by `s` less that of the other, shortened by it.
392    pub fn difference(&self, s: f64, rate: f64) -> f64 {
393        self.span_tension(s, rate) - self.span_tension(-s, -rate)
394    }
395
396    /// The work stored in both spans from their pretensioned length: the integral of T0 + k x from 0 to +-s, constant
397    /// once a span is slack: k s^2 while both hold tension.
398    pub fn energy(&self, s: f64) -> f64 {
399        let span = |e: f64| {
400            let (t, k) = (self.pretension, self.stiffness);
401            if t + k * e > 0.0 { t * e + 0.5 * k * e * e } else { -0.5 * t * t / k }
402        };
403        span(s) + span(-s)
404    }
405
406    /// The power its spans' dampers take: c s'^2 per span that holds tension.
407    pub fn loss(&self, s: f64, rate: f64) -> f64 {
408        let taut = |e: f64| self.pretension + self.stiffness * e > 0.0;
409        (taut(s) as u8 + taut(-s) as u8) as f64 * self.damping * rate * rate
410    }
411
412    /// Its torsional stiffness at the distal pulley while both spans hold tension: 2 k r^2.
413    pub fn torsional_stiffness(&self) -> f64 {
414        2.0 * self.stiffness * self.radius * self.radius
415    }
416}
417
418/// How the effector holds the wafer (`[wafer]`), for the verdict "wafer-slip".
419#[derive(Debug, Clone, Copy, PartialEq)]
420pub enum Hold {
421    /// On friction pads, by its weight: it slips when |a_xy| > mu (g + a_z).
422    Pads { mu: f64 },
423    /// On vacuum pads: by its weight and the vacuum's force F over its mass m, |a_xy| > mu (g + a_z + F / m).
424    Vacuum { mu: f64, lift: f64 },
425    /// Clamped at its edge: up to an acceleration the grip takes, whatever its weight.
426    Edge { acceleration: f64 },
427}
428
429impl Hold {
430    fn from_config(cfg: &Config, wafer_kg: f64) -> Result<Self, ConfigError> {
431        Ok(match cfg.get("wafer.hold")?.as_str() {
432            Some("pads") => Self::Pads { mu: cfg.positive("wafer.friction_coefficient")? },
433            Some("vacuum") => Self::Vacuum {
434                mu: cfg.positive("wafer.friction_coefficient")?,
435                lift: cfg.positive("wafer.vacuum_area_m2")? * cfg.positive("wafer.vacuum_pa")? / wafer_kg.max(1e-9),
436            },
437            Some("edge") => Self::Edge { acceleration: cfg.positive("wafer.edge_grip_acceleration_m_s2")? },
438            _ => return Err(ConfigError::Invalid("wafer.hold".into())),
439        })
440    }
441
442    /// The highest in-plane acceleration it holds at rest under gravity `g`, m/s^2: mu g, mu (g + F / m), or the grip's.
443    pub fn at_rest(&self, g: f64) -> f64 {
444        match *self {
445            Self::Pads { mu } => mu * g,
446            Self::Vacuum { mu, lift } => mu * (g + lift),
447            Self::Edge { acceleration } => acceleration,
448        }
449    }
450
451    /// The wafer's in-plane acceleration `a_xy` at the vertical acceleration `a_z` as the in-plane acceleration that asks
452    /// the same share of the hold at rest: |a_xy| (g + F / m) / (g + a_z + F / m) on pads, |a_xy| clamped at the edge. A
453    /// wafer lifted off its pads (g + a_z + F / m <= 0) asks without bound: 1e9 m/s^2.
454    pub fn equivalent(&self, a_xy: f64, a_z: f64, g: f64) -> f64 {
455        let lift = match *self {
456            Self::Pads { .. } => 0.0,
457            Self::Vacuum { lift, .. } => lift,
458            Self::Edge { .. } => return a_xy.abs(),
459        };
460        let (rest, now) = (g + lift, g + a_z + lift);
461        if a_xy == 0.0 || rest <= 0.0 {
462            a_xy.abs()
463        } else if now <= 0.0 {
464            1e9
465        } else {
466            a_xy.abs() * rest / now
467        }
468    }
469}
470
471/// The Z stroke: the column on a ball screw (in N and m) behind its coupling. Its state is [position, speed, brake]; with
472/// effects.joint_elasticity also [rotor angle, rotor speed]: the screw's and the coupling's stiffness (the joint's
473/// gearbox, `Converter::apply` having put the screw's in series, K = 1 / (1 / K_coupling + 1 / K_screw) in N/m) is a
474/// spring between the rotor (a body of its own, J_rotor) and the column (m): m z'' = F_gear + stops and friction + weight,
475/// J_rotor w' = motor torque - gear torque, as the arm's joints have it. With the rotor held the column rings at
476/// sqrt(K / m) / 2 pi (`modes`). The coupling's damper bridges its own spring, not the screw's: with it the state ends in
477/// the gear's Maxwell arm's (`Gearbox::arm`).
478struct Lift {
479    elastic: bool,
480    joint: RotaryJoint,
481    /// What it lifts besides the wafer (column, motors 1 and 2, links, effector), kg; the wafer while it is held.
482    load: f64,
483    payload: f64,
484    g: f64,
485    screw: BallScrew,
486    /// An obstacle's push on the tool along the stroke (`Machine::set_tool_force`), N, held until changed.
487    push: f64,
488}
489
490impl Lift {
491    fn mass(&self, attached: bool) -> f64 {
492        self.load + if attached { self.payload } else { 0.0 }
493    }
494
495    /// The weight along the stroke (negative: down).
496    fn weight(&self, attached: bool) -> f64 {
497        -self.g * self.mass(attached)
498    }
499
500    fn ratio(&self) -> f64 {
501        self.joint.ratio()
502    }
503
504    /// The gear has a Maxwell arm (a damped coupling before the screw), its state x[5].
505    fn relaxes(&self) -> bool {
506        self.elastic && self.joint.gearbox.relax_stiffness > 0.0
507    }
508
509    fn arm(&self, x: &[f64]) -> f64 {
510        if self.relaxes() { x[5] } else { 0.0 }
511    }
512
513    /// The elastic gear's torques, its arm with them.
514    fn gear(&self, x: &[f64]) -> GearTorque {
515        self.joint.gearbox.torque_with(x[3], x[4], x[0], x[1], self.arm(x))
516    }
517
518    /// The acceleration, and the force into the screw after the rotor's own acceleration and out of it:
519    /// (m + eta i^2 J_rotor) q'' = eta drive + weight + stops and friction.
520    fn solve(&self, x: &[f64], torque: f64, engaged: bool, attached: bool) -> (f64, f64, f64) {
521        let (j, i) = (&self.joint, self.ratio());
522        if self.elastic {
523            // The gearbox's spring between the rotor and the column: (acceleration, torque into it, force out of it).
524            let gear = self.gear(x);
525            let acc =
526                (gear.output + j.output_torque(x[0], x[1]) + self.weight(attached) + self.push) / self.mass(attached);
527            return (acc, gear.rotor * i, gear.output);
528        }
529        let drive = j.rigid_drive(torque, x[0] * i, x[1] * i, x[2], engaged).0;
530        let rest = self.weight(attached) + j.output_torque(x[0], x[1]) + self.push;
531        let (m, r) = (self.mass(attached), j.reflected_inertia());
532        // The loss factor of the torque going in, at its fixed point (`mech::settled_loss`).
533        let solve = |loss: f64| (loss * drive + rest) / (m + loss * r);
534        let [loss] =
535            sim_components::mech::settled_loss([1.0], |&[loss]| [j.gearbox.loss_factor(drive - r * solve(loss), x[1])]);
536        let acc = (loss * drive + rest) / (m + loss * r);
537        let into = drive - r * acc;
538        (acc, into, loss * into)
539    }
540
541    /// Kinetic, potential and elastic (stops) energy.
542    fn energy(&self, x: &[f64], attached: bool) -> [f64; 3] {
543        if self.elastic {
544            let kinetic = 0.5 * self.mass(attached) * x[1] * x[1] + 0.5 * self.joint.rotor_inertia * x[4] * x[4];
545            let spring = self.joint.stop_energy(x[0]) + self.joint.gearbox.energy_with(x[3], x[0], self.arm(x));
546            return [kinetic, -self.weight(attached) * x[0], spring];
547        }
548        let kinetic = 0.5 * (self.mass(attached) + self.joint.reflected_inertia()) * x[1] * x[1];
549        [kinetic, -self.weight(attached) * x[0], self.joint.stop_energy(x[0])]
550    }
551
552    /// The rotor's angle and speed.
553    fn rotor(&self, x: &[f64]) -> (f64, f64) {
554        if self.elastic { (x[3], x[4]) } else { (x[0] * self.ratio(), x[1] * self.ratio()) }
555    }
556
557    /// Powers lost in its guides, its motor's friction with the brake, its coupling and screw, its stops and what the
558    /// ripple gives off; and the coupling's loss as a torque at the rotor.
559    fn losses(&self, x: &[f64], torque: f64, engaged: bool, attached: bool) -> ([f64; 5], f64) {
560        let i = self.ratio();
561        let (rotor, speed) = self.rotor(x);
562        let [friction, stop, shaft, drag] = self.joint.losses(x[0], x[1], speed, x[2], engaged);
563        let other = (torque - self.joint.ripple.apply(torque, rotor)) * speed;
564        if self.elastic {
565            let g = self.gear(x);
566            let loss = self.joint.gearbox.loss_power_with(rotor, speed, x[0], x[1], self.arm(x));
567            return ([friction, shaft, loss + drag, stop, other], g.rotor - g.output / i);
568        }
569        let (_, into, out) = self.solve(x, torque, engaged, attached);
570        ([friction, shaft, (into - out) * x[1] + drag, stop, other], (into - out) / i)
571    }
572
573    /// The motor torque's parts (`TORQUE_PARTS`).
574    fn torque_parts(&self, x: &[f64], torque: f64, engaged: bool, attached: bool) -> [f64; 4] {
575        let (j, i) = (&self.joint, self.ratio());
576        let (acc, ..) = self.solve(x, torque, engaged, attached);
577        let (_, gear_at_rotor) = self.losses(x, torque, engaged, attached);
578        let held = j.brake.torque(engaged, self.rotor(x).1, x[2]).0;
579        let parts = [
580            (self.mass(attached) + j.reflected_inertia()) * acc / i,
581            -self.weight(attached) / i,
582            j.shaft.torque(self.rotor(x).1) + held + gear_at_rotor + j.friction.torque(x[1]) / i,
583        ];
584        [parts[0], parts[1], parts[2], torque - parts.iter().sum::<f64>()]
585    }
586
587    /// Rigid, loss-free: (m q'' - weight) / i + J_rotor i q''.
588    fn feedforward(&self, acc: f64, attached: bool) -> f64 {
589        (self.mass(attached) * acc - self.weight(attached)) / self.ratio()
590            + self.joint.rotor_inertia * self.ratio() * acc
591    }
592}
593
594/// The column's height in the scene below the arm's plane, m (view only).
595const COLUMN_DROP: f64 = 0.35;
596
597pub struct WaferHandler {
598    arm: Arm,
599    /// Motor 1 turns the column (theta), motor 2 the upper arm on it (phi).
600    joints: [RotaryJoint; 2],
601    thermal: [Option<ThermalFeedback>; 2],
602    /// The elbow's band and the wrist's.
603    bands: [Band; 2],
604    /// effects.joint_elasticity and effects.band_elasticity.
605    elastic: bool,
606    bands_elastic: bool,
607    lift: Lift,
608    /// What the Z stroke lifts besides the arm (column, motors 1 and 2), for the frame's momentum.
609    carriage: f64,
610    required_life: Option<f64>,
611    g: f64,
612    hold: Hold,
613    slip_limit: f64,
614    direction_limit: f64,
615    band_limit: f64,
616    payload_attached: bool,
617    brake_engaged: bool,
618    /// An obstacle's push on the tool in the plane, along its reach and its turn (`Machine::set_tool_force`), held
619    /// until changed; the lift's is the lift's.
620    push: V2,
621    dwelling: bool,
622    max_condition: f64,
623    axes: Vec<AxisInfo>,
624    motors: Vec<MotorInfo>,
625    rest_slack: f64,
626}
627
628/// The losses of one moment: per joint its friction, its motor's friction with the brake, its gearbox; the stops, what
629/// the ripple gives off, the elbow's and the wrist's band; and per joint the gearbox loss as a torque at the rotor.
630struct Losses {
631    powers: [f64; 10],
632    gear_at_rotor: V2,
633}
634
635impl WaferHandler {
636    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
637        let link = cfg.positive("geometry.link_m")?;
638        let effector = cfg.positive("geometry.effector_m")?;
639        let body = |name: &str| -> Result<Body, ConfigError> {
640            Ok(Body {
641                mass: cfg.positive(&format!("mass.{name}_kg"))?,
642                inertia: cfg.non_negative(&format!("mass.{name}_inertia_kgm2"))?,
643                centre: cfg.non_negative(&format!("mass.{name}_centre_m"))?,
644            })
645        };
646        let payload = cfg.bool("effects.payload")?;
647        let wafer_kg = cfg.positive("mass.payload_kg")?;
648        let wafer = if payload {
649            Body { mass: wafer_kg, inertia: cfg.non_negative("mass.payload_inertia_kgm2")?, centre: effector }
650        } else {
651            Body { mass: 0.0, inertia: 0.0, centre: effector }
652        };
653        let arm = Arm {
654            link,
655            effector,
656            column_inertia: cfg.positive("mass.column_inertia_kgm2")?,
657            bodies: [body("upper_arm")?, body("forearm")?, body("effector")?],
658            wafer,
659        };
660        let g = sim_components::gripper::gravity(cfg)?;
661        let theta = RotaryJoint::from_config(cfg)?;
662        let own = motor_config(cfg, "2")?;
663        let phi = RotaryJoint::from_config(&own)?;
664        if !(phi.range.0 > 0.0 && phi.range.1 < std::f64::consts::PI) {
665            return Err(ConfigError::Invalid("joint.2.min_angle_deg".into()));
666        }
667        let (r_min, r_max) = (cfg.f64("workspace.min_reach_m")?, cfg.positive("workspace.max_reach_m")?);
668        if !(r_min > 0.0 && r_min < r_max) {
669            return Err(ConfigError::Invalid("workspace.min_reach_m".into()));
670        }
671        let span = |id: &str| -> Result<(f64, f64), ConfigError> {
672            let (min, max) =
673                (cfg.f64(&format!("axis.{id}.min_angle_deg"))?, cfg.f64(&format!("axis.{id}.max_angle_deg"))?);
674            if min >= max {
675                return Err(ConfigError::Invalid(format!("axis.{id}.max_angle_deg")));
676            }
677            Ok((min.to_radians(), max.to_radians()))
678        };
679        let mut axes = vec![
680            Self::axis_info(cfg, "r", "axis-reach", "m", (r_min, r_max))?,
681            Self::axis_info(cfg, "theta", "axis-turn", "rad", span("theta")?)?,
682        ];
683        let carriage = cfg.non_negative("z_axis.carriage_kg")?;
684        let z = motor_config(cfg, "3")?;
685        let mut joint = RotaryJoint::linear_from_config(&z)?;
686        let screw = BallScrew::from_config(&z)?;
687        if screw.length < joint.range.1 {
688            return Err(ConfigError::Invalid("screw.length_m".into()));
689        }
690        // The column on the nut's spring, without the wafer (`Converter::apply_back`'s damper of the screw).
691        screw.converter(screw.softest_position()).apply_to(&z, &mut joint, carriage + arm.mass(false))?;
692        // The nut's preload drags like friction in the guides, as a force at the nut.
693        if z.bool("effects.joint_friction")? {
694            joint.friction.coulomb += screw.preload_torque() * screw.ratio();
695        }
696        axes.push(Self::axis_info(cfg, "z", "axis-lift", "m", joint.range)?);
697        let lift = Lift {
698            elastic: cfg.bool("effects.joint_elasticity")?,
699            joint,
700            load: carriage + arm.mass(false),
701            payload: arm.wafer.mass,
702            g,
703            screw,
704            push: 0.0,
705        };
706        let hold = Hold::from_config(cfg, wafer_kg)?;
707        let factor = cfg.positive("ratings.wafer_slip_safety_factor")?;
708        let mut handler = Self {
709            arm,
710            joints: [theta, phi],
711            thermal: [ThermalFeedback::from_config(cfg)?, ThermalFeedback::from_config(&own)?],
712            bands: [Band::from_config(cfg, "elbow_band")?, Band::from_config(cfg, "wrist_band")?],
713            elastic: cfg.bool("effects.joint_elasticity")?,
714            bands_elastic: cfg.bool("effects.band_elasticity")?,
715            lift,
716            carriage,
717            required_life: cfg.f64("ratings.required_life_h").ok(),
718            g,
719            hold,
720            slip_limit: hold.at_rest(g) / factor,
721            direction_limit: cfg.positive("ratings.direction_tolerance_rad")?,
722            band_limit: cfg.positive("ratings.band_max_pretension_share")?,
723            payload_attached: true,
724            brake_engaged: false,
725            push: [0.0; 2],
726            dwelling: false,
727            max_condition: cfg.positive("workspace.max_condition_number")?,
728            axes,
729            motors: vec![
730                MotorInfo { id: "1", key: "motor-turn" },
731                MotorInfo { id: "2", key: "motor-reach" },
732                MotorInfo { id: "3", key: "motor-lift" },
733            ],
734            rest_slack: 0.0,
735        };
736        // The reach's range within the upper arm's stops and the condition number.
737        for r in [r_min, r_max] {
738            if handler.unreachable(&[r, 0.0, handler.axes[2].min], 0.0).is_some() {
739                return Err(ConfigError::Invalid("workspace.max_reach_m".into()));
740            }
741        }
742        handler.rest_slack = handler.rest_sag();
743        Ok(handler)
744    }
745
746    /// An axis from `[axis.<id>]`, its limits in m or rad.
747    fn axis_info(
748        cfg: &Config,
749        id: &'static str,
750        key: &'static str,
751        unit: &'static str,
752        (min, max): (f64, f64),
753    ) -> Result<AxisInfo, ConfigError> {
754        Ok(AxisInfo {
755            id,
756            key,
757            unit,
758            min,
759            max,
760            max_vel: cfg.positive(&format!("axis.{id}.max_velocity_{unit}_s"))?,
761            max_acc: cfg.positive(&format!("axis.{id}.max_acceleration_{unit}_s2"))?,
762            max_jerk: cfg.positive(&format!("axis.{id}.max_jerk_{unit}_s3"))?,
763        })
764    }
765
766    /// How far the motors' pose can be from the wafer's at rest: each gearbox at either side of its backlash (nothing
767    /// loads them at rest, gravity being out of the plane): the column's half play in rad on theta, the upper arm's
768    /// times the most dr/dphi, 2 L, on r; plus a tenth. At least the default 0.1 mm; that alone in the rigid model. The
769    /// allowance holds anywhere on the stroke: the screw's stiffness where it is softest there (`Gearbox::softest`).
770    fn rest_sag(&self) -> f64 {
771        if !self.elastic {
772            return 1e-4;
773        }
774        let [theta, phi] = [&self.joints[0], &self.joints[1]].map(|j| j.gearbox.half_backlash);
775        // The stroke's: half its play and what its weight compresses the screw by, m g / K, in m.
776        let k = self.lift.joint.gearbox.softest(self.lift.joint.range).stiffness;
777        let lift = self.lift.joint.gearbox.half_backlash + if k > 0.0 { -self.lift.weight(true) / k } else { 0.0 };
778        (1.1 * theta.max(2.0 * self.arm.link * phi).max(lift)).max(1e-4)
779    }
780
781    pub fn arm(&self) -> &Arm {
782        &self.arm
783    }
784
785    pub fn bands(&self) -> &[Band; 2] {
786        &self.bands
787    }
788
789    /// The highest in-plane acceleration "wafer-slip" allows, m/s^2.
790    pub fn slip_limit(&self) -> f64 {
791        self.slip_limit
792    }
793
794    /// The number of the arm's coordinates in the state: theta and phi, and beta and gamma with elastic bands.
795    fn nq(&self) -> usize {
796        if self.bands_elastic { 4 } else { 2 }
797    }
798
799    fn planar_len(&self) -> usize {
800        2 * self.nq() + if self.elastic { 6 } else { 2 }
801    }
802
803    /// The arm's coordinates and rates of a state, beta and gamma zero where the bands are rigid.
804    fn coordinates(&self, s: &[f64]) -> (Q, Q) {
805        let n = self.nq();
806        let (mut q, mut qd) = ([0.0; 4], [0.0; 4]);
807        q[..n].copy_from_slice(&s[..n]);
808        qd[..n].copy_from_slice(&s[n..2 * n]);
809        (q, qd)
810    }
811
812    /// Rotor angles and speeds of a state.
813    fn rotors(&self, s: &[f64]) -> (V2, V2) {
814        let n = self.nq();
815        if self.elastic {
816            ([s[2 * n], s[2 * n + 1]], [s[2 * n + 2], s[2 * n + 3]])
817        } else {
818            let i = [self.joints[0].ratio(), self.joints[1].ratio()];
819            ([s[0] * i[0], s[1] * i[1]], [s[n] * i[0], s[n + 1] * i[1]])
820        }
821    }
822
823    fn brakes(&self, s: &[f64]) -> V2 {
824        let at = self.planar_len() - 2;
825        [s[at], s[at + 1]]
826    }
827
828    /// `Machine::twist` and `twist_at`: the motors' angles for the lift's nut place, or none for the far end's.
829    fn twist_for(&self, angle: Option<&[f64]>, torque: &[f64], acc: &[f64], out: &mut [f64]) {
830        let joints = [&self.joints[0], &self.joints[1], &self.lift.joint];
831        for (k, j) in joints.into_iter().enumerate() {
832            out[k] = if self.elastic {
833                let gear = match angle {
834                    Some(a) if k == 2 => j.gearbox.at(a[k] / j.ratio()),
835                    _ => std::borrow::Cow::Borrowed(&j.gearbox),
836                };
837                j.ratio() * gear.static_twist((torque[k] - j.rotor_inertia * acc[k]) * j.ratio())
838            } else {
839                0.0
840            };
841        }
842    }
843
844    /// The Z stroke's state: [position, speed, brake], and with elastic gearboxes [rotor angle, rotor speed] after them,
845    /// and the gear's arm's where it has one (`Lift::relaxes`).
846    fn lift_state<'a>(&self, s: &'a [f64]) -> &'a [f64] {
847        let at = self.planar_len();
848        &s[at..at + self.lift_len()]
849    }
850
851    fn lift_len(&self) -> usize {
852        if self.lift.relaxes() {
853            6
854        } else if self.elastic {
855            5
856        } else {
857            3
858        }
859    }
860
861    /// The bands' stretches and their rates: s1 = -r1 beta, s2 = r2 (beta / 2 - gamma).
862    fn stretches(&self, q: &Q, qd: &Q) -> [V2; 2] {
863        let [r1, r2] = [self.bands[0].radius, self.bands[1].radius];
864        [[-r1 * q[2], -r1 * qd[2]], [r2 * (0.5 * q[2] - q[3]), r2 * (0.5 * qd[2] - qd[3])]]
865    }
866
867    /// The bands' generalised forces on beta and gamma (zero on theta and phi).
868    fn band_forces(&self, q: &Q, qd: &Q) -> Q {
869        if !self.bands_elastic {
870            return [0.0; 4];
871        }
872        let [[s1, v1], [s2, v2]] = self.stretches(q, qd);
873        let (d1, d2) = (self.bands[0].difference(s1, v1), self.bands[1].difference(s2, v2));
874        [0.0, 0.0, self.bands[0].radius * d1 - 0.5 * self.bands[1].radius * d2, self.bands[1].radius * d2]
875    }
876
877    /// The bands' tension swings over their pretension (k s / T0, signed): `from_stretch`, from their stretch (elastic
878    /// bands), else from the forces the rigid model asks of them at the arm's acceleration `qdd`: dT2 = G_gamma / r2,
879    /// dT1 = (G_beta + G_gamma / 2) / r1 of G = M q'' + h over all four coordinates, half of each per span.
880    fn band_shares(&self, q: &Q, qd: &Q, qdd: &Q, from_stretch: bool) -> V2 {
881        if from_stretch {
882            let [[s1, _], [s2, _]] = self.stretches(q, qd);
883            return [0, 1].map(|k| self.bands[k].stiffness * [s1, s2][k] / self.bands[k].pretension);
884        }
885        let (m, h) = self.arm.dynamics(q, qd, self.payload_attached);
886        let g: Q = std::array::from_fn(|r| dot(&m[r], qdd) + h[r]);
887        let [b1, b2] = self.bands;
888        let (d2, d1) = (g[3] / b2.radius, (g[2] + 0.5 * g[3]) / b1.radius);
889        [0.5 * d1 / b1.pretension, 0.5 * d2 / b2.pretension]
890    }
891
892    /// The tool's (r, theta) and their rates at q and q': in the rigid-band model r(phi) and the column's angle; with
893    /// elastic bands from the wafer centre C, r signed along the column's direction and theta its polar angle, so that C
894    /// = r u(theta), and r' = u . C', theta' = n . C' / r.
895    fn plane_tool(&self, q: &Q, qd: &Q) -> (V2, V2) {
896        if !self.bands_elastic {
897            let [r, dr, _] = self.arm.reach(q[1]);
898            return ([r, q[0]], [dr * qd[1], qd[0]]);
899        }
900        let c = self.arm.wafer_centre(q);
901        let (jac, _) = self.arm.point_motion(q, qd, 2, self.arm.effector);
902        let v = [dot(&jac[0], qd), dot(&jac[1], qd)];
903        let (s, k) = q[0].sin_cos();
904        let local = [k * c[0] + s * c[1], -s * c[0] + k * c[1]];
905        let sign = if local[0] >= 0.0 { 1.0 } else { -1.0 };
906        let r = sign * local[0].hypot(local[1]);
907        let theta = q[0] + (sign * local[1]).atan2(sign * local[0]);
908        let (u, n) = (unit(theta), normal(theta));
909        ([r, theta], [dot(&u, &v), dot(&n, &v) / r])
910    }
911
912    /// The effector's direction less the wafer centre's polar angle: the turn of the effector out of the radial line
913    /// through its wafer, which the bands' stretch gives; zero with rigid bands.
914    fn direction_error(&self, q: &Q, qd: &Q) -> f64 {
915        if !self.bands_elastic {
916            return 0.0;
917        }
918        Arm::angles(q)[2] - self.plane_tool(q, qd).0[1]
919    }
920
921    /// The arm's coordinates, rates and accelerations for a tool pose, speed and acceleration in the rigid model: theta
922    /// = theta, phi = acos((r - e) / 2 L), phi' = r' / r_phi, phi'' = (r'' - r_phiphi phi'^2) / r_phi.
923    fn joint_motion(&self, pos: &[f64], vel: &[f64], acc: &[f64]) -> (Q, Q, Q) {
924        let phi = self.arm.phi(pos[0]);
925        let [_, d1, d2] = self.arm.reach(phi);
926        let w = vel[0] / d1;
927        ([pos[1], phi, 0.0, 0.0], [vel[1], w, 0.0, 0.0], [acc[1], (acc[0] - d2 * w * w) / d1, 0.0, 0.0])
928    }
929
930    /// Rigid gearboxes: the arm's acceleration, and per joint the torque into its gearbox (after the rotor's own
931    /// acceleration) and out of it.
932    /// The push at the tool in the plane on the arm's coordinates: its virtual power per unit of each one's rate
933    /// (`sim_core::tool_force_on_rates`, through `plane_tool`); zero without a push and beyond `nq`.
934    fn pushed(&self, s: &[f64]) -> Q {
935        let n = self.nq();
936        let force = [self.push[0], self.push[1], 0.0];
937        let q = sim_core::tool_force_on_rates(self, s, &force, n..2 * n);
938        q.map_or([0.0; 4], |q| std::array::from_fn(|k| q.get(k).copied().unwrap_or(0.0)))
939    }
940
941    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> (Q, V2, V2) {
942        let n = self.nq();
943        let (q, qd) = self.coordinates(s);
944        let (rotor, rotor_speed) = self.rotors(s);
945        let brakes = self.brakes(s);
946        let (mass, h) = self.arm.dynamics(&q, &qd, self.payload_attached);
947        let bands = self.band_forces(&q, &qd);
948        let drive: V2 = std::array::from_fn(|k| {
949            self.joints[k].rigid_drive(torque[k], rotor[k], rotor_speed[k], brakes[k], self.brake_engaged).0
950        });
951        let push = self.pushed(s);
952        let rest: Q = std::array::from_fn(|k| {
953            bands[k] - h[k] + push[k] + if k < 2 { self.joints[k].output_torque(q[k], qd[k]) } else { 0.0 }
954        });
955        let at = |loss: V2| -> Q {
956            let mut m = mass;
957            let mut rhs = rest;
958            for k in 0..2 {
959                m[k][k] += loss[k] * self.joints[k].reflected_inertia();
960                rhs[k] += loss[k] * drive[k];
961            }
962            solve(&m, &rhs, n).unwrap_or([f64::NAN; 4])
963        };
964        // The loss factors of the torques going in, at their fixed point (`mech::settled_loss`).
965        let loss = sim_components::mech::settled_loss([1.0; 2], |loss| {
966            let acc = at(*loss);
967            std::array::from_fn(|k| {
968                self.joints[k].gearbox.loss_factor(drive[k] - self.joints[k].reflected_inertia() * acc[k], qd[k])
969            })
970        });
971        let acc = at(loss);
972        let into: V2 = std::array::from_fn(|k| drive[k] - self.joints[k].reflected_inertia() * acc[k]);
973        (acc, into, std::array::from_fn(|k| loss[k] * into[k]))
974    }
975
976    /// The arm's accelerations in either model.
977    fn arm_acceleration(&self, s: &[f64], torque: &[f64]) -> Q {
978        if self.elastic {
979            let mut d = vec![0.0; self.state_len()];
980            self.derivatives(s, torque, &mut d);
981            let n = self.nq();
982            std::array::from_fn(|k| if k < n { d[n + k] } else { 0.0 })
983        } else {
984            self.rigid_solve(s, torque).0
985        }
986    }
987
988    /// The torque each gearbox passes to its link.
989    fn gear_output(&self, s: &[f64], torque: &[f64]) -> V2 {
990        if self.elastic {
991            let n = self.nq();
992            std::array::from_fn(|k| {
993                self.joints[k].gearbox.torque(s[2 * n + k], s[2 * n + 2 + k], s[k], s[n + k]).output
994            })
995        } else {
996            self.rigid_solve(s, torque).2
997        }
998    }
999
1000    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
1001        let n = self.nq();
1002        let (q, qd) = self.coordinates(s);
1003        let (mass, _) = self.arm.dynamics(&q, &qd, self.payload_attached);
1004        let mut kinetic = 0.5 * (0..n).map(|r| qd[r] * dot(&mass[r][..n], &qd[..n])).sum::<f64>();
1005        let mut elastic: f64 = (0..2).map(|k| self.joints[k].stop_energy(q[k])).sum();
1006        if self.bands_elastic {
1007            let [[s1, _], [s2, _]] = self.stretches(&q, &qd);
1008            elastic += self.bands[0].energy(s1) + self.bands[1].energy(s2);
1009        }
1010        if self.elastic {
1011            for k in 0..2 {
1012                kinetic += 0.5 * self.joints[k].rotor_inertia * s[2 * n + 2 + k].powi(2);
1013                elastic += self.joints[k].gearbox.energy(s[2 * n + k], q[k]);
1014            }
1015        } else {
1016            kinetic += 0.5 * (0..2).map(|k| self.joints[k].reflected_inertia() * qd[k] * qd[k]).sum::<f64>();
1017        }
1018        // Nothing in the plane rises or falls: the potential energy is the Z stroke's alone.
1019        let own = self.lift.energy(self.lift_state(s), self.payload_attached);
1020        [kinetic + own[0], own[1], elastic + own[2]]
1021    }
1022
1023    fn losses(&self, s: &[f64], torque: &[f64]) -> Losses {
1024        let n = self.nq();
1025        let (q, qd) = self.coordinates(s);
1026        let (rotor, rotor_speed) = self.rotors(s);
1027        let brakes = self.brakes(s);
1028        let mut powers = [0.0; 10];
1029        let mut gear_at_rotor = [0.0; 2];
1030        let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque));
1031        let (mut stops, mut other) = (0.0, 0.0);
1032        for k in 0..2 {
1033            let joint = &self.joints[k];
1034            let [friction, stop, shaft, drag] =
1035                joint.losses(q[k], qd[k], rotor_speed[k], brakes[k], self.brake_engaged);
1036            let gear = match &rigid {
1037                Some((_, into, out)) => {
1038                    gear_at_rotor[k] = (into[k] - out[k]) / joint.ratio();
1039                    (into[k] - out[k]) * qd[k]
1040                }
1041                None => {
1042                    let (r, w) = (s[2 * n + k], s[2 * n + 2 + k]);
1043                    let g = joint.gearbox.torque(r, w, q[k], qd[k]);
1044                    gear_at_rotor[k] = g.rotor - g.output / joint.ratio();
1045                    joint.gearbox.loss_power(r, w, q[k], qd[k])
1046                }
1047            };
1048            powers[3 * k..3 * k + 3].copy_from_slice(&[friction, shaft, gear + drag]);
1049            stops += stop;
1050            other += (torque[k] - joint.ripple.apply(torque[k], rotor[k])) * rotor_speed[k];
1051        }
1052        let ([.., stop, ripple], _) =
1053            self.lift.losses(self.lift_state(s), torque[2], self.brake_engaged, self.payload_attached);
1054        powers[6] = stops + stop;
1055        powers[7] = other + ripple;
1056        if self.bands_elastic {
1057            let [[s1, v1], [s2, v2]] = self.stretches(&q, &qd);
1058            powers[8] = self.bands[0].loss(s1, v1);
1059            powers[9] = self.bands[1].loss(s2, v2);
1060        }
1061        Losses { powers, gear_at_rotor }
1062    }
1063
1064    /// The wafer centre's acceleration in the plane at a state's arm accelerations `qdd`.
1065    fn wafer_acceleration(&self, q: &Q, qd: &Q, qdd: &Q) -> V2 {
1066        let (jac, bias) = self.arm.point_motion(q, qd, 2, self.arm.effector);
1067        [dot(&jac[0], qdd) + bias[0], dot(&jac[1], qdd) + bias[1]]
1068    }
1069
1070    /// The torque breakdown, loss powers, energies of the effect views.
1071    fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1072        let (q, qd) = self.coordinates(s);
1073        let (_, rotor_speed) = self.rotors(s);
1074        let brakes = self.brakes(s);
1075        let (mass, h) = self.arm.dynamics(&q, &qd, self.payload_attached);
1076        let acc = self.arm_acceleration(s, torque);
1077        let losses = self.losses(s, torque);
1078        for k in 0..2 {
1079            let joint = &self.joints[k];
1080            let i = joint.ratio();
1081            let held = joint.brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).0;
1082            let parts = [
1083                (dot(&mass[k], &acc) + h[k] + joint.reflected_inertia() * acc[k]) / i,
1084                // Gravity acts out of the plane, on the joints' bearings.
1085                0.0,
1086                joint.shaft.torque(rotor_speed[k]) + held + losses.gear_at_rotor[k] + joint.friction.torque(qd[k]) / i,
1087            ];
1088            out.extend(parts);
1089            out.push(torque[k] - parts.iter().sum::<f64>());
1090        }
1091        out.extend(losses.powers);
1092        out.extend(self.energy_parts(s));
1093        let (state, at) = (self.lift_state(s), (torque[2], self.brake_engaged, self.payload_attached));
1094        out.extend(self.lift.torque_parts(state, at.0, at.1, at.2));
1095        out.extend(&self.lift.losses(state, at.0, at.1, at.2).0[..3]);
1096    }
1097
1098    /// The torque parts and loss powers of motor `motor`.
1099    fn motor_infos(motor: &MotorInfo, joint: &str, coupled: bool) -> (Vec<SignalInfo>, Vec<SignalInfo>) {
1100        let parts = TORQUE_PARTS.map(|part| {
1101            SignalInfo::new(
1102                format!("motor.{}.torque_{part}", motor.id),
1103                motor.key,
1104                &format!("quantity-torque-{part}"),
1105                "N m",
1106            )
1107        });
1108        let gear = if coupled { "quantity-coupling-loss-power" } else { "quantity-gearbox-loss-power" };
1109        let losses = vec![
1110            SignalInfo::new(format!("{LOSS_PREFIX}joint_{}", motor.id), joint, "quantity-friction-power", "W"),
1111            SignalInfo::new(
1112                format!("{LOSS_PREFIX}shaft_{}", motor.id),
1113                motor.key,
1114                "quantity-shaft-friction-power",
1115                "W",
1116            ),
1117            SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"),
1118        ];
1119        (parts.to_vec(), losses)
1120    }
1121
1122    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
1123        let arms: Vec<_> = (0..2)
1124            .map(|k| {
1125                Self::motor_infos(&self.motors[k], ["column", "upper-arm"][k], self.joints[k].gearbox.is_coupling())
1126            })
1127            .collect();
1128        out.extend(arms.iter().flat_map(|(parts, _)| parts.clone()));
1129        out.extend(arms.into_iter().flat_map(|(_, losses)| losses));
1130        out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-joint", "quantity-damping-power", "W"));
1131        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
1132        out.push(SignalInfo::new(format!("{LOSS_PREFIX}band_elbow"), "elbow-band", "quantity-band-damping-power", "W"));
1133        out.push(SignalInfo::new(format!("{LOSS_PREFIX}band_wrist"), "wrist-band", "quantity-band-damping-power", "W"));
1134        out.extend(ENERGY_PARTS.map(|part| {
1135            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
1136        }));
1137        let (parts, losses) = Self::motor_infos(&self.motors[2], self.axes[2].key, self.lift.joint.coupled);
1138        out.extend(parts);
1139        out.extend(losses);
1140    }
1141
1142    /// The scene's parts that move with the wafer: the effector and the wafer at the arm's coordinates.
1143    fn on_effector(&self, q: &Q, z: f64) -> Vec<Part> {
1144        let wrist = self.arm.point(q, 1, self.arm.link);
1145        let centre = self.arm.wafer_centre(q);
1146        let mut parts = vec![Part::new(
1147            "effector",
1148            Shape::Segment { to: [centre[0], centre[1], z], width: 0.06 },
1149            [wrist[0], wrist[1], z],
1150            [0.85, 0.85, 0.8],
1151        )];
1152        if self.payload_attached && self.arm.wafer.mass > 0.0 {
1153            parts.push(Part::new(
1154                "wafer",
1155                Shape::Box { size: [0.3, 0.3, 0.002] },
1156                [centre[0], centre[1], z + 0.005],
1157                [0.35, 0.4, 0.6],
1158            ));
1159        }
1160        parts
1161    }
1162}
1163
1164impl Machine for WaferHandler {
1165    /// In the machine's frame (x, y in the plane, z up, the column's axis at the origin): each link, the effector and
1166    /// the wafer at their centres moving in the plane and up with the stroke, turning at their links' rates; the column
1167    /// and the rotors spinning about z; the rest of what the stroke lifts at the axis.
1168    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
1169        use sim_components::base::{add_point, add_spin};
1170        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
1171        let (q, qd) = self.coordinates(s);
1172        let (z, vz) = (self.lift_state(s)[0], self.lift_state(s)[1]);
1173        for (k, body) in self.arm.moving(self.payload_attached) {
1174            let p = self.arm.point(&q, k, body.centre);
1175            let (jac, _) = self.arm.point_motion(&q, &qd, k, body.centre);
1176            let v = [dot(&jac[0], &qd), dot(&jac[1], &qd)];
1177            add_point(&mut f, body.mass, [p[0], p[1], z], [v[0], v[1], vz]);
1178            add_spin(&mut f, [0.0, 0.0, 1.0], body.inertia, dot(&LINK_ANGLES[k], &qd));
1179        }
1180        add_point(&mut f, self.carriage, [0.0, 0.0, z], [0.0, 0.0, vz]);
1181        add_spin(&mut f, [0.0, 0.0, 1.0], self.arm.column_inertia, qd[0]);
1182        let rotor_speed = self.rotors(s).1;
1183        for k in 0..2 {
1184            add_spin(&mut f, [0.0, 0.0, 1.0], self.joints[k].rotor_inertia, rotor_speed[k]);
1185        }
1186        add_spin(&mut f, [0.0, 0.0, 1.0], self.lift.joint.rotor_inertia, self.lift.rotor(self.lift_state(s)).1);
1187        Some(f)
1188    }
1189
1190    /// The wafer centre at (r cos theta, r sin theta, z) moves with the base by its translation and tilt (as the
1191    /// default moves a point), told along and across the radial line: r by the move along u(theta), theta by the move
1192    /// across it over r, z by the move up.
1193    fn base_shift(&self, tool_pose: &[f64], pivot: [f64; 3], shift: &[f64; 6], out: &mut [f64]) {
1194        let (r, theta) = (tool_pose[0], tool_pose[1]);
1195        let (u, n) = (unit(theta), normal(theta));
1196        let p = [r * u[0] - pivot[0], r * u[1] - pivot[1], tool_pose[2] - pivot[2]];
1197        let t = [shift[3], shift[4], shift[5]];
1198        let moved = [t[1] * p[2] - t[2] * p[1], t[2] * p[0] - t[0] * p[2], t[0] * p[1] - t[1] * p[0]];
1199        let d: [f64; 3] = std::array::from_fn(|k| shift[k] + moved[k]);
1200        let across = d[0] * n[0] + d[1] * n[1];
1201        out[0] = d[0] * u[0] + d[1] * u[1];
1202        out[1] = if r.abs() > 1e-9 { across / r } else { t[2] };
1203        out[2] = d[2];
1204    }
1205
1206    fn axes(&self) -> &[AxisInfo] {
1207        &self.axes
1208    }
1209    fn motors(&self) -> &[MotorInfo] {
1210        &self.motors
1211    }
1212
1213    /// NaN where the reach is beyond the arm's: the controller never asks for one (see `unreachable`).
1214    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1215        motors[0] = self.joints[0].ratio() * tool[1];
1216        motors[1] = self.joints[1].ratio() * self.arm.phi(tool[0]);
1217        motors[2] = self.lift.ratio() * tool[2];
1218    }
1219    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1220        tool[0] = self.arm.reach(motors[1] / self.joints[1].ratio())[0];
1221        tool[1] = motors[0] / self.joints[0].ratio();
1222        tool[2] = motors[2] / self.lift.ratio();
1223    }
1224
1225    fn state_len(&self) -> usize {
1226        self.planar_len() + self.lift_len()
1227    }
1228
1229    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1230        let n = self.nq();
1231        let q = [tool[1], self.arm.phi(tool[0])];
1232        state.clear();
1233        state.extend(q);
1234        state.resize(2 * n, 0.0);
1235        let mut rotors = Vec::new();
1236        for k in 0..2 {
1237            let joint = &self.joints[k];
1238            // At rest the gearbox holds the link against its stops; gravity gives it nothing to hold, nor the bands.
1239            let out = -joint.output_torque(q[k], 0.0);
1240            let rotor = joint.ratio() * (q[k] + if self.elastic { joint.gearbox.static_twist(out) } else { 0.0 });
1241            rotors.push(rotor);
1242            torque[k] = joint.ripple.invert(out / joint.ratio(), rotor);
1243        }
1244        if self.elastic {
1245            state.extend(rotors);
1246            state.extend([0.0; 2]);
1247        }
1248        state.extend([0.0; 2]);
1249        // The stroke holds what it lifts.
1250        let (z, i) = (tool[2], self.lift.ratio());
1251        let out = -self.lift.weight(self.payload_attached) - self.lift.joint.output_torque(z, 0.0);
1252        let rotor = i * (z + if self.elastic { self.lift.joint.gearbox.static_twist_at(z, out) } else { 0.0 });
1253        let held = if self.elastic { self.lift.joint.gearbox.held_at(z, out) } else { out };
1254        torque[2] = self.lift.joint.ripple.invert(held / i, rotor);
1255        state.extend([z, 0.0, 0.0]);
1256        if self.elastic {
1257            state.extend([rotor, 0.0]);
1258        }
1259        if self.lift.relaxes() {
1260            state.push(self.lift.joint.gearbox.arm_rest(rotor, z));
1261        }
1262    }
1263
1264    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1265        let n = self.nq();
1266        let at = self.planar_len();
1267        let state = self.lift_state(s);
1268        out[at] = state[1];
1269        out[at + 1] = self.lift.solve(state, torque[2], self.brake_engaged, self.payload_attached).0;
1270        out[at + 2] = self.lift.joint.brake.torque(self.brake_engaged, self.lift.rotor(state).1, state[2]).1;
1271        if self.elastic {
1272            let j = &self.lift.joint;
1273            let gear = self.lift.gear(state);
1274            let (rotor_acc, _) = j.rotor_under(torque[2], state[3], state[4], gear, state[2], self.brake_engaged);
1275            (out[at + 3], out[at + 4]) = (state[4], rotor_acc);
1276            if self.lift.relaxes() {
1277                out[at + 5] = j.gearbox.arm(state[3], state[0], state[5]).1;
1278            }
1279        }
1280        out[..n].copy_from_slice(&s[n..2 * n]);
1281        if !self.elastic {
1282            let (acc, ..) = self.rigid_solve(s, torque);
1283            let (_, rotor_speed) = self.rotors(s);
1284            let brakes = self.brakes(s);
1285            out[n..2 * n].copy_from_slice(&acc[..n]);
1286            for k in 0..2 {
1287                out[2 * n + k] = self.joints[k].brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).1;
1288            }
1289            return;
1290        }
1291        let (q, qd) = self.coordinates(s);
1292        let (mass, h) = self.arm.dynamics(&q, &qd, self.payload_attached);
1293        let (mut rhs, push) = (self.band_forces(&q, &qd), self.pushed(s));
1294        for r in 0..4 {
1295            rhs[r] += push[r] - h[r];
1296        }
1297        for k in 0..2 {
1298            let joint = &self.joints[k];
1299            let (gear, rotor_acc, brake_rate) = joint.rotor(
1300                torque[k],
1301                s[2 * n + k],
1302                s[2 * n + 2 + k],
1303                q[k],
1304                qd[k],
1305                s[2 * n + 4 + k],
1306                self.brake_engaged,
1307            );
1308            rhs[k] += gear.output + joint.output_torque(q[k], qd[k]);
1309            out[2 * n + k] = s[2 * n + 2 + k];
1310            out[2 * n + 2 + k] = rotor_acc;
1311            out[2 * n + 4 + k] = brake_rate;
1312        }
1313        let acc = solve(&mass, &rhs, n).unwrap_or([f64::NAN; 4]);
1314        out[n..2 * n].copy_from_slice(&acc[..n]);
1315    }
1316
1317    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1318        let (q, qd) = self.coordinates(s);
1319        let (p, v) = self.plane_tool(&q, &qd);
1320        pos[..2].copy_from_slice(&p);
1321        vel[..2].copy_from_slice(&v);
1322        (pos[2], vel[2]) = (self.lift_state(s)[0], self.lift_state(s)[1]);
1323    }
1324    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1325        let n = self.nq();
1326        let d1 = self.arm.reach(s[1])[1];
1327        let w = [vel[1], vel[0] / d1];
1328        s[n..n + 2].copy_from_slice(&w);
1329        if self.elastic {
1330            for k in 0..2 {
1331                s[2 * n + 2 + k] = self.joints[k].ratio() * w[k];
1332            }
1333        }
1334        let at = self.planar_len();
1335        s[at + 1] = vel[2];
1336        if self.elastic {
1337            s[at + 4] = self.lift.ratio() * vel[2];
1338        }
1339    }
1340    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1341        let (rotor, speed) = self.rotors(s);
1342        pos[..2].copy_from_slice(&rotor);
1343        vel[..2].copy_from_slice(&speed);
1344        (pos[2], vel[2]) = self.lift.rotor(self.lift_state(s));
1345    }
1346
1347    /// Rigid, loss-free, at rest: M q'' at the joints over the ratio, plus the rotor's own J_rotor i q''; the stroke's
1348    /// (m q'' - weight) / i + J_rotor i q''.
1349    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
1350        self.feedforward_torque_moving(pos, &[0.0; 3], acc, out);
1351    }
1352
1353    /// With the speed: the joints' motion (`joint_motion`), M q'' + h at the joints over the ratio, plus the rotor's own
1354    /// J_rotor i q''.
1355    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
1356        let (q, qd, qdd) = self.joint_motion(pos, vel, acc);
1357        let (mass, h) = self.arm.dynamics(&q, &qd, self.payload_attached);
1358        for k in 0..2 {
1359            let joint = &self.joints[k];
1360            let at_joint = mass[k][0] * qdd[0] + mass[k][1] * qdd[1] + h[k];
1361            out[k] = at_joint / joint.ratio() + joint.rotor_inertia * joint.ratio() * qdd[k];
1362        }
1363        out[2] = self.lift.feedforward(acc[2], self.payload_attached);
1364    }
1365
1366    /// The rigid model at q'' = 0: per joint the motor shaft's friction (with the gearbox's drag) at i q' and the joint's
1367    /// own friction (bearings, the Z guides and the nut's preload) through the gearbox: f(q') / (i loss).
1368    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
1369        let (_, qd, _) = self.joint_motion(pos, vel, &[0.0; 3]);
1370        let joints = [(&self.joints[0], qd[0]), (&self.joints[1], qd[1]), (&self.lift.joint, vel[2])];
1371        for (k, (joint, v)) in joints.into_iter().enumerate() {
1372            let (i, friction) = (joint.ratio(), joint.friction.torque(v));
1373            out[k] = joint.shaft.torque(i * v) + friction / (i * joint.gearbox.loss_factor(friction, v));
1374        }
1375    }
1376
1377    /// The rating checks' values in the rigid model at a tool pose, speed and acceleration (`rating_checks`' order):
1378    /// the screw's speed, force and d n (its life NaN); "wafer-slip" NaN: the plan's rows are linear in the acceleration
1379    /// and the speed squared along the path, and the size of the wafer's acceleration, a vector's length, is not (it
1380    /// is judged, and `sim-cli optimise` keeps it, the cycle's axis limits are sized for it); "effector-direction" NaN
1381    /// (the rigid model has none); the bands' tension swings (`band_shares`), linear in the acceleration.
1382    fn rigid_checks(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut Vec<f64>) {
1383        let force = self.lift.mass(self.payload_attached) * (acc[2] + self.g);
1384        let mut screw = Vec::new();
1385        self.lift.screw.signals(vel[2], force, &mut screw);
1386        for check in self.lift.screw.rating_checks("z", 2, self.required_life) {
1387            out.push(match check.check {
1388                "screw-speed" => screw[0],
1389                "screw-dn" => screw[1],
1390                "screw-buckling" | "screw-static" => force,
1391                _ => f64::NAN,
1392            });
1393        }
1394        let (q, qd, qdd) = self.joint_motion(pos, vel, acc);
1395        let shares = self.band_shares(&q, &qd, &qdd, false);
1396        out.extend([f64::NAN, f64::NAN, shares[0], shares[1]]);
1397    }
1398
1399    fn energy(&self, s: &[f64]) -> f64 {
1400        self.energy_parts(s).iter().sum()
1401    }
1402
1403    fn set_payload_attached(&mut self, attached: bool) {
1404        self.payload_attached = attached;
1405    }
1406    fn set_brake_engaged(&mut self, engaged: bool) {
1407        self.brake_engaged = engaged;
1408    }
1409    /// A stop met within the step (`HardStop::substeps`, `RotaryJoint::stop_substeps`).
1410    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
1411        let ((q, qd), lift) = (self.coordinates(s), self.lift_state(s));
1412        (0..2)
1413            .map(|k| self.joints[k].stop_substeps(q[k], qd[k], dt))
1414            .fold(self.lift.joint.stop_substeps(lift[0], lift[1], dt), u32::max)
1415    }
1416    /// The push acts on the arm's coordinates beyond the gearboxes (`pushed`, on the bands' too where they are elastic)
1417    /// and on the lift's load, in either model; its power is the budget's crash row.
1418    fn set_tool_force(&mut self, force: &[f64]) -> bool {
1419        self.push = [force[0], force[1]];
1420        self.lift.push = force[2];
1421        true
1422    }
1423    fn set_dwelling(&mut self, dwelling: bool) {
1424        self.dwelling = dwelling;
1425    }
1426
1427    /// The joints' gearboxes' hysteresis states move on to where the step ended (`Gearbox::commit`).
1428    fn after_step(&mut self, s: &mut [f64], _dt: f64) {
1429        if self.elastic {
1430            let n = self.nq();
1431            for k in 0..2 {
1432                self.joints[k].gearbox.commit(s[2 * n + k], s[k]);
1433            }
1434            let x = self.planar_len();
1435            self.lift.joint.gearbox.commit(s[x + 3], s[x]);
1436        }
1437    }
1438
1439    /// As `Machine::adopt_state`, but where the model keeps its states (a changed ratio, not rigid against elastic) the
1440    /// links, the bands' stretch and the stroke stay as they were, and each elastic gearbox keeps its twist and its
1441    /// rotor's speed at the link (scaled by the new over the old dr/dmotor): rebuilt at rest, the bands' lag during a
1442    /// move (0.14 mm at the wafer) was dropped and rang anew, 0.134 mm off a run left alone after a 1 % change of the
1443    /// ratio.
1444    fn adopt_state(&self, old: &dyn Machine, old_state: &[f64]) -> Vec<f64> {
1445        let (m, n) = (self.axes.len(), self.motors.len());
1446        let (mut pos, mut vel) = (vec![0.0; m], vec![0.0; m]);
1447        old.tool_state(old_state, &mut pos, &mut vel);
1448        if old_state.len() != self.state_len() {
1449            let mut state = Vec::new();
1450            self.equilibrium(&pos, &mut state, &mut vec![0.0; n]);
1451            self.set_tool_velocity(&mut state, &vel);
1452            return state;
1453        }
1454        let mut state = old_state.to_vec();
1455        if self.elastic {
1456            let (mut rotor, mut speed) = (vec![0.0; n], vec![0.0; n]);
1457            old.motor_state(old_state, &mut rotor, &mut speed);
1458            // Motor k against the tool axis it drives (motor 1 theta, axis 1; motor 2 r, axis 0), new and old.
1459            let at = |machine: &dyn Machine, shift: f64, axis: usize| {
1460                let mut p = pos.clone();
1461                p[axis] += shift;
1462                let mut out = vec![0.0; n];
1463                machine.inverse(&p, &mut out);
1464                out
1465            };
1466            let (h, nq) = (1e-6, self.nq());
1467            for (k, axis) in [(0, 1), (1, 0)] {
1468                let (before, after) = (at(old, 0.0, axis)[k], at(self, 0.0, axis)[k]);
1469                let scale =
1470                    (at(self, h, axis)[k] - at(self, -h, axis)[k]) / (at(old, h, axis)[k] - at(old, -h, axis)[k]);
1471                state[2 * nq + k] = after + scale * (rotor[k] - before);
1472                state[2 * nq + 2 + k] = scale * speed[k];
1473            }
1474            // The stroke's rotor the same way (motor 3, axis 2), after its position and speed.
1475            let x = self.planar_len();
1476            let (before, after) = (at(old, 0.0, 2)[2], at(self, 0.0, 2)[2]);
1477            let scale = (at(self, h, 2)[2] - at(self, -h, 2)[2]) / (at(old, h, 2)[2] - at(old, -h, 2)[2]);
1478            state[x + 3] = after + scale * (rotor[2] - before);
1479            state[x + 4] = scale * speed[2];
1480            // The gear's arm keeps its stretch over the twist it had.
1481            if self.lift.relaxes() {
1482                let g = &self.lift.joint.gearbox;
1483                state[x + 5] += g.arm_rest(state[x + 3], state[x]) - g.arm_rest(old_state[x + 3], old_state[x]);
1484            }
1485        }
1486        state
1487    }
1488
1489    /// The gearboxes, in the order of `thermal_parts`.
1490    fn set_part_temperatures(&mut self, rises: &[f64]) {
1491        let mut rises = rises.iter();
1492        for k in 0..2 {
1493            if self.joints[k].gearbox.is_coupling() {
1494                continue;
1495            }
1496            if let (Some(law), Some(rise)) = (&self.thermal[k], rises.next()) {
1497                self.joints[k].gearbox.efficiency = law.gearbox_efficiency(*rise);
1498            }
1499        }
1500    }
1501
1502    /// The lowest modes at a tool pose, with the motors held where they are: the bands' (beta, gamma) and, with elastic
1503    /// gearboxes, the column's and the upper arm's on their gearboxes' stiffness; the rigid model's joints held fast.
1504    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
1505        let phi = self.arm.phi(tool_pose[0]);
1506        let q = [tool_pose[1], phi, 0.0, 0.0];
1507        let (mass, _) = self.arm.dynamics(&q, &[0.0; 4], self.payload_attached);
1508        // K and the damping matrix C alike: the bands' 2 k r^2 and 2 c r^2, the gearboxes' stiffness and damping.
1509        let (mut k, mut damper) = ([[0.0; 4]; 4], [[0.0; 4]; 4]);
1510        if self.bands_elastic {
1511            let spans: [(&mut Mat, fn(&Band) -> f64); 2] = [(&mut k, |b| b.stiffness), (&mut damper, |b| b.damping)];
1512            for (p, per_span) in spans {
1513                let [t1, t2] = self.bands.map(|b| 2.0 * per_span(&b) * b.radius * b.radius);
1514                p[2][2] = t1 + 0.25 * t2;
1515                p[2][3] = -0.5 * t2;
1516                p[3][2] = -0.5 * t2;
1517                p[3][3] = t2;
1518            }
1519        }
1520        // The coordinates that move: theta and phi only on elastic gearboxes.
1521        let free: Vec<usize> = (0..4).filter(|&c| if c < 2 { self.elastic } else { self.bands_elastic }).collect();
1522        // The column on its screw and coupling, the rotor held: it moves along z alone, apart from the arm's modes.
1523        // Damping ratio c / (2 sqrt(K m)), c the gear's at the ring (`Gearbox::damping_at`).
1524        let gear = self.lift.joint.gearbox.at(tool_pose[2]);
1525        let lift = (self.elastic && gear.stiffness.is_finite()).then(|| {
1526            let mass = self.lift.mass(self.payload_attached);
1527            let w = (gear.stiffness / mass).sqrt();
1528            Mode { hz: w / std::f64::consts::TAU, damping: gear.damping_at(w) / (2.0 * (gear.stiffness * mass).sqrt()) }
1529        });
1530        if free.is_empty() {
1531            return lift.into_iter().collect();
1532        }
1533        for c in 0..2 {
1534            k[c][c] = self.joints[c].gearbox.stiffness;
1535            damper[c][c] = self.joints[c].gearbox.damping;
1536        }
1537        let (mut m, mut kk, mut cc) = ([[0.0; 4]; 4], [[0.0; 4]; 4], [[0.0; 4]; 4]);
1538        for (a, &i) in free.iter().enumerate() {
1539            for (b, &j) in free.iter().enumerate() {
1540                m[a][b] = mass[i][j];
1541                kk[a][b] = k[i][j];
1542                cc[a][b] = damper[i][j];
1543            }
1544        }
1545        let n = free.len();
1546        let mut modes: Vec<Mode> = generalised_eigenvalues(&m, &kk, n).map_or(Vec::new(), |values| {
1547            values
1548                .into_iter()
1549                .filter(|v| *v > 0.0)
1550                .map(|v| Mode { hz: v.sqrt() / std::f64::consts::TAU, damping: modal_damping(&m, &kk, &cc, n, v) })
1551                .collect()
1552        });
1553        modes.extend(lift);
1554        modes.sort_by(|a, b| a.hz.total_cmp(&b.hz));
1555        modes
1556    }
1557
1558    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
1559        self.modes(tool_pose).first().map(|m| m.hz)
1560    }
1561
1562    /// With effects.joint_elasticity: per motor its gearbox's spring between the rotor and the rest of the motor's rigid
1563    /// inertia at the pose, M_kk over the ratio squared with the other joints held and the bands rigid
1564    /// (`RotaryJoint::train`); the lift's with the screw's stiffness at its height (`train_at`), whose frequency is the
1565    /// column's mode on it (`modes`).
1566    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
1567        if !self.elastic {
1568            return Vec::new();
1569        }
1570        let q = [tool_pose[1], self.arm.phi(tool_pose[0]), 0.0, 0.0];
1571        let (mass, _) = self.arm.dynamics(&q, &[0.0; 4], self.payload_attached);
1572        let whole = |j: &RotaryJoint, m: f64| m / (j.ratio() * j.ratio()) + j.rotor_inertia;
1573        let lift = &self.lift.joint;
1574        vec![
1575            self.joints[0].train(whole(&self.joints[0], mass[0][0])),
1576            self.joints[1].train(whole(&self.joints[1], mass[1][1])),
1577            lift.train_at(tool_pose[2], whole(lift, self.lift.mass(self.payload_attached))),
1578        ]
1579    }
1580
1581    /// The gearboxes' static twist under what reaches them, the rotor's own acceleration taken off (`Gearbox::
1582    /// static_twist`), per motor in motor radians; zeros with rigid gearboxes. The lift's takes the screw's far end.
1583    fn twist(&self, torque: &[f64], acc: &[f64], out: &mut [f64]) {
1584        self.twist_for(None, torque, acc, out)
1585    }
1586
1587    /// `twist` with the lift's spring where its nut is, the rotor's angle over the ratio (`Gearbox::at`): what
1588    /// `identify::fit_joints` takes for a trace of this machine.
1589    fn twist_at(&self, angle: &[f64], torque: &[f64], acc: &[f64], out: &mut [f64]) {
1590        self.twist_for(Some(angle), torque, acc, out)
1591    }
1592
1593    /// How far the reach's motor is from the singular full extension: 1 / sin(phi), the most dr/dphi over this one (1
1594    /// with the wrist over the column, without bound at full extension); infinite out of reach.
1595    fn condition(&self, tool_pose: &[f64]) -> Option<f64> {
1596        let phi = self.arm.phi(tool_pose[0]);
1597        Some(if phi.is_finite() { 1.0 / phi.sin().abs() } else { f64::INFINITY })
1598    }
1599
1600    /// What the gearboxes can sag at rest (`rest_sag`).
1601    fn setpoint_slack(&self) -> f64 {
1602        self.rest_slack
1603    }
1604
1605    fn unreachable(&self, tool: &[f64], _slack: f64) -> Option<&'static str> {
1606        if tool.len() != self.axes.len() {
1607            return Some("error-target-out-of-range");
1608        }
1609        let phi = self.arm.phi(tool[0]);
1610        if !phi.is_finite() {
1611            return Some("error-handler-out-of-reach");
1612        }
1613        let (min, max) = self.joints[1].range;
1614        let (tmin, tmax) = self.joints[0].range;
1615        if phi < min || phi > max || tool[1] < tmin || tool[1] > tmax {
1616            return Some("error-handler-joint-stop");
1617        }
1618        match self.condition(tool) {
1619            Some(c) if c <= self.max_condition => None,
1620            _ => Some("error-handler-singularity"),
1621        }
1622    }
1623
1624    fn signal_infos(&self) -> Vec<SignalInfo> {
1625        let mut out = Vec::new();
1626        for (k, (owner, quantity)) in
1627            [("column", "quantity-column-angle"), ("upper-arm", "quantity-shoulder-angle")].into_iter().enumerate()
1628        {
1629            let motor = &self.motors[k];
1630            out.push(SignalInfo::new(format!("arm.{}.angle", motor.id), owner, quantity, "rad"));
1631            out.push(SignalInfo::new(
1632                format!("gearbox.{}.output_torque", motor.id),
1633                motor.key,
1634                "quantity-gearbox-torque",
1635                "N m",
1636            ));
1637        }
1638        out.push(SignalInfo::new("kinematics.condition", "group-kinematics", "quantity-condition-number", ""));
1639        out.push(SignalInfo::new("effector.direction_error", "effector", "quantity-direction-error", "rad"));
1640        out.push(SignalInfo::new(
1641            "effector.direction_error_at_station",
1642            "effector",
1643            "quantity-direction-error-at-station",
1644            "rad",
1645        ));
1646        out.push(SignalInfo::new("wafer.acceleration", "wafer", "quantity-wafer-acceleration", "m/s^2"));
1647        out.push(SignalInfo::new("band.elbow.pretension_share", "elbow-band", "quantity-band-share", ""));
1648        out.push(SignalInfo::new("band.wrist.pretension_share", "wrist-band", "quantity-band-share", ""));
1649        let axis = &self.axes[2];
1650        out.push(SignalInfo::new(format!("joint.{}.force", axis.id), axis.key, "quantity-joint-force", "N"));
1651        out.extend(self.lift.screw.signal_infos(axis.id, axis.key));
1652        self.effect_infos(&mut out);
1653        out
1654    }
1655
1656    /// The stroke's ball screw (speed, d n, buckling, static load, life); the wafer's hold ("wafer-slip", against the
1657    /// hold at rest over `ratings.wafer_slip_safety_factor`); the effector's direction at a station
1658    /// ("effector-direction", against `ratings.direction_tolerance_rad`); each band's tension swing against
1659    /// `ratings.band_max_pretension_share` of its pretension ("elbow-band-slack", "wrist-band-slack").
1660    fn rating_checks(&self) -> Vec<RatingCheck> {
1661        let mut out = self.lift.screw.rating_checks("z", 2, self.required_life);
1662        let own = |check: &'static str, signal: &str, limit: f64| RatingCheck {
1663            check,
1664            signal: signal.into(),
1665            motor: None,
1666            limit,
1667            life: false,
1668        };
1669        out.push(own("wafer-slip", "wafer.acceleration", self.slip_limit));
1670        out.push(own("effector-direction", "effector.direction_error_at_station", self.direction_limit));
1671        out.push(own("elbow-band-slack", "band.elbow.pretension_share", self.band_limit));
1672        out.push(own("wrist-band-slack", "band.wrist.pretension_share", self.band_limit));
1673        out
1674    }
1675
1676    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1677        let (q, qd) = self.coordinates(s);
1678        let gear = self.gear_output(s, torque);
1679        for k in 0..2 {
1680            out.extend([q[k], gear[k]]);
1681        }
1682        out.push(self.condition(&[self.arm.reach(q[1])[0]]).unwrap_or(f64::NAN));
1683        let direction = self.direction_error(&q, &qd);
1684        out.extend([direction, if self.dwelling { direction } else { 0.0 }]);
1685        let qdd = self.arm_acceleration(s, torque);
1686        let state = self.lift_state(s);
1687        let (a_z, _, force) = self.lift.solve(state, torque[2], self.brake_engaged, self.payload_attached);
1688        let a = self.wafer_acceleration(&q, &qd, &qdd);
1689        let held = self.payload_attached && self.arm.wafer.mass > 0.0;
1690        out.push(if held { self.hold.equivalent(a[0].hypot(a[1]), a_z, self.g) } else { 0.0 });
1691        out.extend(self.band_shares(&q, &qd, &qdd, self.bands_elastic));
1692        out.push(force);
1693        self.lift.screw.signals(state[1], force, out);
1694    }
1695    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1696        self.view_signals(s, torque, out);
1697    }
1698    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1699        out.extend(self.losses(s, torque).powers);
1700        out.extend(&self.lift.losses(self.lift_state(s), torque[2], self.brake_engaged, self.payload_attached).0[..3]);
1701    }
1702
1703    /// The two gearboxes, where there are gearboxes (not on a direct drive); the stroke's coupling warms nothing.
1704    fn thermal_parts(&self) -> Vec<ThermalPart> {
1705        let ids = [("gearbox_1", "motor-turn"), ("gearbox_2", "motor-reach")];
1706        (0..2)
1707            .filter(|&k| !self.joints[k].gearbox.is_coupling())
1708            .enumerate()
1709            .map(|(scene_index, k)| ThermalPart {
1710                id: ids[k].0,
1711                kind: "gearbox",
1712                owner_key: ids[k].1,
1713                scene_part: "gearbox",
1714                scene_index,
1715            })
1716            .collect()
1717    }
1718
1719    /// The machine with the arm's plane at the stroke's height z: the column below it with motor 1 and its gearbox at
1720    /// its foot, motor 2 and its gearbox at its top, the Z motor beside it; the upper arm, the forearm, the effector and
1721    /// the wafer; a bar on each motor turned by its rotor angle and its speed above it.
1722    fn scene(&self, s: &[f64], out: &mut Scene) {
1723        let (q, _) = self.coordinates(s);
1724        let (rotor, rotor_speed) = self.rotors(s);
1725        let z = self.lift_state(s)[0];
1726        out.parts.clear();
1727        out.labels.clear();
1728        let grey = [0.62, 0.64, 0.68];
1729        out.parts.push(Part::new("base", Shape::Box { size: [0.4, 0.4, 0.05] }, [0.0, 0.0, -COLUMN_DROP - 0.1], grey));
1730        out.parts.push(Part::new(
1731            "column",
1732            Shape::Box { size: [0.16, 0.16, COLUMN_DROP] },
1733            [0.0, 0.0, z - 0.5 * COLUMN_DROP],
1734            [0.8, 0.8, 0.82],
1735        ));
1736        let elbow = self.arm.point(&q, 0, self.arm.link);
1737        let wrist = self.arm.point(&q, 1, self.arm.link);
1738        out.parts.push(Part::new(
1739            "upper-arm",
1740            Shape::Segment { to: [elbow[0], elbow[1], z], width: 0.07 },
1741            [0.0, 0.0, z],
1742            [0.2, 0.22, 0.26],
1743        ));
1744        out.parts.push(Part::new(
1745            "forearm",
1746            Shape::Segment { to: [wrist[0], wrist[1], z + 0.04], width: 0.06 },
1747            [elbow[0], elbow[1], z + 0.04],
1748            [0.3, 0.32, 0.36],
1749        ));
1750        out.parts.extend(self.on_effector(&q, z + 0.07));
1751        let lift = self.lift_state(s);
1752        let places = [[0.0, 0.0, z - COLUMN_DROP + 0.05], [0.0, 0.0, z - 0.06], [0.25, 0.0, -COLUMN_DROP - 0.02]];
1753        let own = self.lift.rotor(lift);
1754        let turns = [rotor[0], rotor[1], own.0];
1755        let speeds = [rotor_speed[0], rotor_speed[1], own.1];
1756        for k in 0..3 {
1757            let at = places[k];
1758            out.parts.push(Part::new(
1759                sim_core::scene::MOTOR_PART,
1760                Shape::Box { size: [0.07, 0.07, 0.09] },
1761                at,
1762                [0.9, 0.45, 0.1],
1763            ));
1764            if k < 2 && !self.joints[k].gearbox.is_coupling() {
1765                out.parts.push(Part::new(
1766                    "gearbox",
1767                    Shape::Box { size: [0.08, 0.08, 0.04] },
1768                    [at[0], at[1] - 0.08, at[2]],
1769                    [0.25, 0.25, 0.28],
1770                ));
1771            }
1772            out.parts.push(
1773                Part::new(
1774                    "rotor-bar",
1775                    Shape::Box { size: [0.06, 0.004, 0.01] },
1776                    [at[0], at[1] - 0.04, at[2]],
1777                    [0.1, 0.1, 0.1],
1778                )
1779                .turned(turns[k]),
1780            );
1781            out.labels.push(Label {
1782                pos: [at[0] + 0.1, at[1], at[2]],
1783                owner_key: self.motors[k].key,
1784                value: speeds[k] * 60.0 / std::f64::consts::TAU,
1785                unit_key: "unit-rpm",
1786                decimals: 0,
1787            });
1788        }
1789    }
1790
1791    /// The wafer centre at the effector's height.
1792    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
1793        let c = unit(tool_pose[1]);
1794        Some([tool_pose[0] * c[0], tool_pose[0] * c[1], tool_pose[2] + 0.075])
1795    }
1796
1797    /// The wafer, where `scene` draws it, and the effector as the box around its strip.
1798    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
1799        let (q, _) = self.coordinates(s);
1800        let z = self.lift_state(s)[0] + 0.07;
1801        let mut out = sim_core::scene::scene_boxes(&self.on_effector(&q, z), &["wafer"]);
1802        let (wrist, centre) = (self.arm.point(&q, 1, self.arm.link), self.arm.wafer_centre(&q));
1803        out.push(sim_core::Aabb {
1804            centre: [0.5 * (wrist[0] + centre[0]), 0.5 * (wrist[1] + centre[1]), z],
1805            size: [(wrist[0] - centre[0]).abs() + 0.06, (wrist[1] - centre[1]).abs() + 0.06, 0.01],
1806        });
1807        out
1808    }
1809}
1810
1811#[cfg(test)]
1812mod tests;