Skip to main content

sim_netlist/
scissor.rs

1//! `ScissorMachine`: a scissor lift from a machine file's `[[machine.scissor]]` node. n stages of crossed arm pairs,
2//! each arm L from pin to pin, stand on the base; a screw, turned by the motor through its gearbox, pulls the sliding
3//! foot of the lowest stage towards the fixed one and so raises the platform. The tool is the platform's height z.
4//!
5//! With u the span between the feet, a stage stands s = sqrt(L^2 - u^2) high and the platform h = n s. The gearbox's
6//! output turns the screw by theta, which moves the foot by c theta, c = lead / (2 pi): u = u_0 - c theta, u_0 the span
7//! at the lowest height. So
8//!
9//! ```text
10//! h = n s,   dh/dtheta = n c u / s,   d2h/dtheta2 = -n c^2 L^2 / s^3
11//! ```
12//!
13//! and by virtual work the screw pulls the foot with F = W dh/du = W n u / s = W n cot(alpha) for a weight W on the
14//! platform, alpha the arms' angle to the base: the force ratio grows without bound as the lift folds flat.
15//!
16//! Dynamics in theta, as the linkage's: M(theta) theta'' + m h' h'' theta'^2 = tau_gear + Q_g, M = J_screw + m h'^2,
17//! Q_g = -g m_g h'. m counts the platform, the payload and the arms' vertical motion, arms (4 n^2 - 1) / (12 n^2) (the
18//! centres of stage k's arms at (k - 1/2) h / n); m_g the platform, the payload and half the arms.
19//! The arms are uniform rods of mass m_a = arms / 2n, all 2n centres at the horizontal u / 2 (the stages stack on the
20//! same two feet columns) and at the heights (k - 1/2) s, the feet's rollers without mass of their own. Beside their
21//! vertical motion (m above) the centres move sideways at u' / 2 = -c theta' / 2, and each arm turns at
22//! alpha' = s' / u (tan alpha = s / u) about its centre, I = m_a L^2 / 12, with s' = c u theta' / s. Their kinetic
23//! energy 2n (m_a/2)(u'/2)^2 + 2n (I/2) alpha'^2 adds
24//!
25//! ```text
26//! M_a = arms c^2 (1/4 + L^2 / (12 s^2)),   1/2 dM_a/dtheta theta'^2 = -arms c^3 L^2 u theta'^2 / (12 s^4)
27//! ```
28//!
29//! to M and to the speed term (about 16 % of the vertical motion's share at mid height).
30//!
31//! The joint is a `RotaryJoint` on the motor's own config (motor, gearbox, brake), without joint friction or stops: the
32//! screw's efficiency counts with the gearbox's (effects.gearbox_efficiency); elastic or rigid with
33//! effects.joint_elasticity, as the linkage.
34
35use crate::machine::intern;
36use crate::netlist::{AxisNode, Kind, MotorNode, NODES, Netlist, Node, Transmission, number};
37use sim_components::catalog::motor_config;
38use sim_components::joint::RotaryJoint;
39use sim_components::mech::{HardStop, ShaftFriction, ThermalFeedback};
40use sim_core::{
41    AxisInfo, Config, ConfigError, ENERGY_PARTS, LOSS_PREFIX, Label, Machine, MotorInfo, Part, Scene, Shape,
42    SignalInfo, TORQUE_PARTS, ThermalPart,
43};
44use toml::Value;
45
46const G: f64 = 9.80665;
47
48/// The scissor node, read and checked: its numbers by name (an optional one left out is 0, the screw's efficiency 1)
49/// and its gearbox's id.
50pub struct ScissorNode {
51    pub id: String,
52    pub gearbox: String,
53    values: Vec<(&'static str, f64)>,
54}
55
56impl ScissorNode {
57    pub fn value(&self, name: &str) -> f64 {
58        self.values.iter().find(|(n, _)| *n == name).map_or(0.0, |(_, v)| *v)
59    }
60}
61
62/// The netlist of a file with a scissor lift: one axis (its height), one motor, the gearbox and the scissor node; no
63/// other node and no belt effect.
64pub(crate) fn read(
65    cfg: &Config,
66    axes: &[Node],
67    motors: &[Node],
68    gearboxes: &[Node],
69    scissors: &[Node],
70    others: &[&[Node]],
71) -> Result<Netlist, ConfigError> {
72    let node = match scissors {
73        [node] => node,
74        _ => return Err(ConfigError::Invalid(format!("{} (one scissor per file)", scissors[1].path))),
75    };
76    if let Some(other) = others.iter().find_map(|nodes| nodes.first()) {
77        return Err(ConfigError::Invalid(format!(
78            "{} (a file with a scissor lift has an axis, a motor, a gearbox and the scissor only)",
79            other.path
80        )));
81    }
82    let effects = cfg.get("effects").ok().and_then(Value::as_table);
83    for (effect, on) in effects.into_iter().flatten() {
84        if effect.starts_with("belt_") && on.as_bool() == Some(true) {
85            return Err(ConfigError::Invalid(format!("effects.{effect} (a scissor lift has no belt: switch it off)")));
86        }
87    }
88    let id_of = |n: &Node| n.table["id"].as_str().unwrap_or_default().to_string();
89    let one = |nodes: &[Node], field: &str, list: &str| -> Result<usize, ConfigError> {
90        let id = node.text(field)?.unwrap_or_default();
91        match nodes.iter().position(|n| n.table["id"].as_str() == Some(id)) {
92            Some(i) if nodes.len() == 1 => Ok(i),
93            Some(_) => Err(ConfigError::Invalid(format!("{} (one machine.{list} node)", node.at(field)))),
94            None => Err(ConfigError::Invalid(format!("{} = \"{id}\"", node.at(field)))),
95        }
96    };
97
98    let fields = NODES.iter().find(|(list, ..)| *list == "scissor").map_or(&[][..], |(_, _, f)| *f);
99    let (mut refs, mut values) = (Vec::new(), Vec::new());
100    for f in fields.iter().filter(|f| f.kind == Kind::Number) {
101        let v = node.get(f.name).map(|v| number(cfg, v, &node.at(f.name), &mut refs)).transpose()?;
102        let v = v.unwrap_or(if f.name == "screw_efficiency" { 1.0 } else { 0.0 });
103        let positive = !["payload_kg", "screw_inertia_kgm2", "arms_kg"].contains(&f.name);
104        if if positive { !(v > 0.0) } else { !(v >= 0.0) } {
105            return Err(ConfigError::Invalid(node.at(f.name)));
106        }
107        values.push((f.name, v));
108    }
109    let value = |name: &str| values.iter().find(|(n, _)| *n == name).map_or(0.0, |(_, v)| *v);
110    let stages = value("stages");
111    for (field, bad, why) in [
112        ("stages", stages.fract() != 0.0, "a whole number"),
113        ("screw_efficiency", value("screw_efficiency") > 1.0, "at most 1"),
114        ("max_height_m", value("max_height_m") <= value("min_height_m"), "above min_height_m"),
115        ("max_height_m", value("max_height_m") >= stages * value("arm_m"), "below stages times arm_m"),
116    ] {
117        if bad {
118            return Err(ConfigError::Invalid(format!("{} ({why})", node.at(field))));
119        }
120    }
121
122    let axis = &axes[one(axes, "axis", "axis")?];
123    for field in ["stroke_m", "stroke_rad", "incline_deg", "cable_chain"] {
124        if axis.get(field).is_some() {
125            return Err(ConfigError::Invalid(format!(
126                "{} (a scissor lift's axis takes its range from min_height_m and max_height_m)",
127                axis.at(field)
128            )));
129        }
130    }
131    let axis_id = id_of(axis);
132    let axis_key = axis.text("key")?.map_or_else(|| format!("axis-{axis_id}"), str::to_string);
133    let gearbox = &gearboxes[one(gearboxes, "gearbox", "gearbox")?];
134    let motor_id = gearbox.text("motor")?.unwrap_or_default();
135    let motor = match motors.iter().position(|n| n.table["id"].as_str() == Some(motor_id)) {
136        Some(m) if motors.len() == 1 => &motors[m],
137        _ => return Err(ConfigError::Invalid(format!("{} = \"{motor_id}\" (the one motor)", gearbox.at("motor")))),
138    };
139    let key = motor.text("key")?.map_or_else(|| format!("motor-{motor_id}"), str::to_string);
140    Ok(Netlist {
141        axes: vec![AxisNode {
142            id: axis_id,
143            key: axis_key,
144            stroke: value("max_height_m") - value("min_height_m"),
145            incline_deg: 90.0,
146            cable_chain: false,
147            rotary: false,
148        }],
149        // What drives the platform is the scissor, which the netlist's transmissions do not describe.
150        motors: vec![MotorNode {
151            id: motor_id.to_string(),
152            key,
153            radius: 1.0,
154            inertia: 0.0,
155            pulley: String::new(),
156            at: None,
157            body: None,
158            clockwise: false,
159            transmission: Transmission::Belt,
160            axis: None,
161            worm: None,
162        }],
163        sections: Vec::new(),
164        bodies: Vec::new(),
165        guides: Vec::new(),
166        idlers: Vec::new(),
167        frame: None,
168        spans: Vec::new(),
169        lean: None,
170        refs,
171        values: Vec::new(),
172        linkage: None,
173        scissor: Some(ScissorNode { id: id_of(node), gearbox: id_of(gearbox), values }),
174        gantry: None,
175        tcp: None,
176    })
177}
178
179/// Effects that take energy out or put it in: the standard suite runs with them off.
180pub const LOSSY_EFFECTS: [&str; 4] = ["motor_friction", "gearbox_efficiency", "torque_ripple", "holding_brake"];
181
182// Elastic state: [theta, omega, rotor angle, rotor speed, brake]; rigid: [theta, omega, brake].
183const N_ELASTIC: usize = 5;
184const N_RIGID: usize = 3;
185
186/// The stages' geometry: their number n, the arms' length L, the screw's lever c = lead / (2 pi) (m of the foot per
187/// rad of the screw) and the feet's span u_0 at the angle 0, the lowest height.
188#[derive(Debug, Clone, Copy)]
189pub struct Stages {
190    pub stages: f64,
191    pub arm: f64,
192    pub lever: f64,
193    pub span_low: f64,
194}
195
196impl Stages {
197    /// The platform's height and its first and second derivative by the screw's angle theta.
198    pub fn height(&self, theta: f64) -> [f64; 3] {
199        let (n, c, l) = (self.stages, self.lever, self.arm);
200        let u = self.span_low - c * theta;
201        let s = (l * l - u * u).max(0.0).sqrt();
202        [n * s, n * c * u / s, -n * c * c * l * l / s.powi(3)]
203    }
204
205    /// What the arms' turning and sideways motion add at the screw angle theta, for arms of total mass `arms`: to the
206    /// mass M (arms c^2 (1/4 + L^2 / (12 s^2))) and to the speed term (1/2 dM/dtheta, per theta'^2).
207    pub fn arm_motion(&self, theta: f64, arms: f64) -> (f64, f64) {
208        let (c, l) = (self.lever, self.arm);
209        let u = self.span_low - c * theta;
210        let s = (self.height(theta)[0] / self.stages).max(1e-9);
211        (arms * c * c * (0.25 + l * l / (12.0 * s * s)), -arms * c.powi(3) * l * l * u / (12.0 * s.powi(4)))
212    }
213
214    /// The screw's angle for a height; NaN out of reach.
215    pub fn angle(&self, h: f64) -> f64 {
216        let s = h / self.stages;
217        let u = (self.arm * self.arm - s * s).sqrt();
218        if h > 0.0 && u.is_finite() { (self.span_low - u) / self.lever } else { f64::NAN }
219    }
220
221    /// The force the screw pulls the foot with to hold the weight `w` (N) at the height h: W n u / s = W n cot(alpha).
222    pub fn actuator_force(&self, w: f64, h: f64) -> f64 {
223        let s = h / self.stages;
224        w * self.stages * (self.arm * self.arm - s * s).sqrt() / s
225    }
226}
227
228pub struct ScissorMachine {
229    geometry: Stages,
230    min_height: f64,
231    max_height: f64,
232    /// The screw's inertia at the gearbox output; the moving mass m (without the payload) and the weight's mass m_g.
233    screw_inertia: f64,
234    m_moving: f64,
235    /// The arms' total mass, for their turning and sideways motion.
236    arms: f64,
237    m_weight: f64,
238    m_payload: f64,
239    payload_attached: bool,
240    brake_engaged: bool,
241    /// An obstacle's push on the platform along z (`Machine::set_tool_force`), N; held until changed.
242    tool_push: f64,
243    /// The screw's efficiency (1 with effects.gearbox_efficiency off), which the gearbox's carries.
244    screw_efficiency: f64,
245    joint: RotaryJoint,
246    thermal: Option<ThermalFeedback>,
247    elastic: bool,
248    g: f64,
249    axes: [AxisInfo; 1],
250    motors: [MotorInfo; 1],
251    gearbox_id: &'static str,
252    id: &'static str,
253    rest_slack: f64,
254}
255
256impl ScissorMachine {
257    pub fn from_node(cfg: &Config, net: &Netlist, node: &ScissorNode) -> Result<Self, ConfigError> {
258        let v = |name: &str| node.value(name);
259        let (stages, arm, lever) = (v("stages"), v("arm_m"), v("lead_m") / std::f64::consts::TAU);
260        let (min_height, max_height) = (v("min_height_m"), v("max_height_m"));
261        let span_low = (arm * arm - (min_height / stages).powi(2)).sqrt();
262        let own = motor_config(cfg, &net.motors[0].id)?;
263        let theta_max = (span_low - (arm * arm - (max_height / stages).powi(2)).sqrt()) / lever;
264        let free = ShaftFriction::NONE;
265        let mut joint = RotaryJoint::with(&own, free, HardStop { stiffness: 0.0, damping: 0.0 }, (0.0, theta_max))?;
266        let counts = cfg.bool("effects.gearbox_efficiency")?;
267        let screw_efficiency = if counts { v("screw_efficiency") } else { 1.0 };
268        joint.gearbox.efficiency *= screw_efficiency;
269        let axis = &net.axes[0];
270        let arms = v("arms_kg");
271        let mut machine = Self {
272            geometry: Stages { stages, arm, lever, span_low },
273            min_height,
274            max_height,
275            screw_inertia: v("screw_inertia_kgm2"),
276            m_moving: v("platform_kg") + arms * (4.0 * stages * stages - 1.0) / (12.0 * stages * stages),
277            arms,
278            m_weight: v("platform_kg") + 0.5 * arms,
279            m_payload: if cfg.bool("effects.payload")? { v("payload_kg") } else { 0.0 },
280            payload_attached: true,
281            brake_engaged: false,
282            tool_push: 0.0,
283            screw_efficiency,
284            joint,
285            thermal: ThermalFeedback::from_config(cfg)?,
286            elastic: cfg.bool("effects.joint_elasticity")?,
287            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
288            axes: [AxisInfo {
289                id: intern(&axis.id),
290                key: intern(&axis.key),
291                unit: "m",
292                min: min_height,
293                max: max_height,
294                max_vel: cfg.positive(&format!("axis.{}.max_velocity_m_s", axis.id))?,
295                max_acc: cfg.positive(&format!("axis.{}.max_acceleration_m_s2", axis.id))?,
296                max_jerk: cfg.positive(&format!("axis.{}.max_jerk_m_s3", axis.id))?,
297            }],
298            motors: [MotorInfo { id: intern(&net.motors[0].id), key: intern(&net.motors[0].key) }],
299            // The warmth's id is that of the gearbox's loss.
300            gearbox_id: intern(&format!("gearbox_{}", net.motors[0].id)),
301            id: intern(&node.id),
302            rest_slack: 0.0,
303        };
304        machine.rest_slack = machine.rest_sag();
305        Ok(machine)
306    }
307
308    fn height(&self, theta: f64) -> [f64; 3] {
309        self.geometry.height(theta)
310    }
311    fn angle(&self, h: f64) -> f64 {
312        self.geometry.angle(h)
313    }
314
315    fn m_nt(&self) -> f64 {
316        self.m_moving + if self.payload_attached { self.m_payload } else { 0.0 }
317    }
318    fn m_g(&self) -> f64 {
319        self.m_weight + if self.payload_attached { self.m_payload } else { 0.0 }
320    }
321
322    /// M, the velocity term m h' h'' w^2 and Q_g at theta and its speed w.
323    fn load(&self, theta: f64, w: f64) -> (f64, f64, f64) {
324        let [_, d1, d2] = self.height(theta);
325        let (turn, turn_rate) = self.geometry.arm_motion(theta, self.arms);
326        (
327            self.screw_inertia + self.m_nt() * d1 * d1 + turn,
328            (self.m_nt() * d1 * d2 + turn_rate) * w * w,
329            -self.g * self.m_g() * d1,
330        )
331    }
332
333    /// An obstacle's push F on the platform (`set_tool_force`) on the arms' angle, h' F: in the equations of motion
334    /// only, not in the feedforward or the state at rest.
335    fn push(&self, theta: f64) -> f64 {
336        self.tool_push * self.height(theta)[1]
337    }
338
339    fn rotor(&self, s: &[f64]) -> (f64, f64) {
340        if self.elastic { (s[2], s[3]) } else { (self.joint.ratio() * s[0], self.joint.ratio() * s[1]) }
341    }
342    fn brake(&self, s: &[f64]) -> f64 {
343        s[if self.elastic { 4 } else { 2 }]
344    }
345
346    /// Rigid model: theta'', the torque into the gearbox (after the rotor's own acceleration) and out of it.
347    fn rigid_solve(&self, s: &[f64], torque: f64) -> (f64, f64, f64) {
348        let (theta, w) = (s[0], s[1]);
349        let (rotor, rotor_speed) = self.rotor(s);
350        let (mass, velocity, gravity) = self.load(theta, w);
351        let j = &self.joint;
352        let drive = j.rigid_drive(torque, rotor, rotor_speed, self.brake(s), self.brake_engaged).0;
353        let rest = gravity + self.push(theta) - velocity + j.output_torque(theta, w);
354        let first = (drive + rest) / (mass + j.reflected_inertia());
355        let loss = j.gearbox.loss_factor(drive - j.reflected_inertia() * first, w);
356        let acc = (loss * drive + rest) / (mass + loss * j.reflected_inertia());
357        let into = drive - j.reflected_inertia() * acc;
358        (acc, into, loss * into)
359    }
360
361    fn acceleration(&self, s: &[f64], torque: f64) -> f64 {
362        let mut d = [0.0; N_ELASTIC];
363        self.derivatives(s, &[torque], &mut d);
364        d[1]
365    }
366
367    fn gear(&self, s: &[f64], torque: f64) -> f64 {
368        if self.elastic {
369            self.joint.gearbox.torque(s[2], s[3], s[0], s[1]).output
370        } else {
371            self.rigid_solve(s, torque).2
372        }
373    }
374
375    /// The shaft's friction with the brake, the gearbox's loss, and what the ripple gives off (W); and the gearbox's
376    /// loss as a torque at the rotor.
377    fn losses(&self, s: &[f64], torque: f64) -> ([f64; 3], f64) {
378        let (theta, w) = (s[0], s[1]);
379        let (rotor, rotor_speed) = self.rotor(s);
380        let j = &self.joint;
381        let [_, _, shaft, drag] = j.losses(theta, w, rotor_speed, self.brake(s), self.brake_engaged);
382        let (gear, at_rotor) = if self.elastic {
383            let g = j.gearbox.torque(s[2], s[3], theta, w);
384            (j.gearbox.loss_power(s[2], s[3], theta, w), g.rotor - g.output / j.ratio())
385        } else {
386            let (_, into, out) = self.rigid_solve(s, torque);
387            ((into - out) * w, (into - out) / j.ratio())
388        };
389        ([shaft, gear + drag, (torque - j.ripple.apply(torque, rotor)) * rotor_speed], at_rotor)
390    }
391
392    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
393        let (theta, w) = (s[0], s[1]);
394        let (mass, ..) = self.load(theta, w);
395        let mut kinetic = 0.5 * mass * w * w;
396        let potential = self.g * self.m_g() * self.height(theta)[0];
397        let mut elastic = 0.0;
398        if self.elastic {
399            kinetic += 0.5 * self.joint.rotor_inertia * s[3] * s[3];
400            elastic += self.joint.gearbox.energy(s[2], s[0]);
401        } else {
402            kinetic += 0.5 * self.joint.reflected_inertia() * w * w;
403        }
404        [kinetic, potential, elastic]
405    }
406
407    /// How far the motor's pose can be from the platform's at rest: the gearbox twisted by what it holds over its
408    /// stiffness and half its backlash, through dh/dtheta, over 21 heights, payload on; plus a tenth. At least 0.1 mm;
409    /// that alone in the rigid model.
410    fn rest_sag(&self) -> f64 {
411        if !self.elastic {
412            return 1e-4;
413        }
414        let gear = &self.joint.gearbox;
415        let most = (0..=20)
416            .map(|k| self.min_height + (self.max_height - self.min_height) * k as f64 / 20.0)
417            .map(|h| {
418                let [_, d1, _] = self.height(self.angle(h));
419                let held = self.g * (self.m_weight + self.m_payload) * d1;
420                d1 * (held / gear.stiffness + gear.half_backlash)
421            })
422            .fold(0.0, f64::max);
423        (1.1 * most).max(1e-4)
424    }
425}
426
427impl Machine for ScissorMachine {
428    fn axes(&self) -> &[AxisInfo] {
429        &self.axes
430    }
431    fn motors(&self) -> &[MotorInfo] {
432        &self.motors
433    }
434    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
435        motors[0] = self.joint.ratio() * self.angle(tool[0]);
436    }
437    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
438        tool[0] = self.height(motors[0] / self.joint.ratio())[0];
439    }
440    fn state_len(&self) -> usize {
441        if self.elastic { N_ELASTIC } else { N_RIGID }
442    }
443
444    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
445        let theta = self.angle(tool[0]);
446        let (_, _, gravity) = self.load(theta, 0.0);
447        let j = &self.joint;
448        let out = -gravity - j.output_torque(theta, 0.0);
449        let rotor = j.ratio() * (theta + if self.elastic { j.gearbox.static_twist(out) } else { 0.0 });
450        state.clear();
451        state.extend([theta, 0.0]);
452        if self.elastic {
453            state.extend([rotor, 0.0]);
454        }
455        state.push(0.0);
456        torque[0] = j.ripple.invert(out / j.ratio(), rotor);
457    }
458
459    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
460        let j = &self.joint;
461        if !self.elastic {
462            let (acc, ..) = self.rigid_solve(s, torque[0]);
463            let rotor_speed = self.rotor(s).1;
464            out[..3].copy_from_slice(&[s[1], acc, j.brake.torque(self.brake_engaged, rotor_speed, s[2]).1]);
465            return;
466        }
467        let (theta, w) = (s[0], s[1]);
468        let (mass, velocity, gravity) = self.load(theta, w);
469        let (gear, rotor_acc, brake_rate) = j.rotor(torque[0], s[2], s[3], theta, w, s[4], self.brake_engaged);
470        let acc = (gear.output + gravity + self.push(theta) - velocity + j.output_torque(theta, w)) / mass;
471        out[..5].copy_from_slice(&[w, acc, s[3], rotor_acc, brake_rate]);
472    }
473
474    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
475        let [h, d1, _] = self.height(s[0]);
476        (pos[0], vel[0]) = (h, d1 * s[1]);
477    }
478    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
479        s[1] = vel[0] / self.height(s[0])[1];
480        if self.elastic {
481            s[3] = self.joint.ratio() * s[1];
482        }
483    }
484    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
485        (pos[0], vel[0]) = self.rotor(s);
486    }
487
488    /// Rigid, loss-free, at rest: theta'' = z'' / h', M theta'' - Q_g over the ratio, plus the rotor's J i theta''.
489    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
490        let theta = self.angle(pos[0]);
491        let (mass, _, gravity) = self.load(theta, 0.0);
492        let acc = acc[0] / self.height(theta)[1];
493        let j = &self.joint;
494        out[0] = (mass * acc - gravity) / j.ratio() + j.rotor_inertia * j.ratio() * acc;
495    }
496
497    /// With the speed: theta' = z' / h', theta'' = (z'' - h'' theta'^2) / h', and J_screw theta'' + m h' z'' - Q_g at
498    /// the screw, plus the arms' turning and sideways motion, M_a theta'' + 1/2 dM_a/dtheta theta'^2.
499    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
500        let theta = self.angle(pos[0]);
501        let [_, d1, d2] = self.height(theta);
502        let (_, _, gravity) = self.load(theta, 0.0);
503        let w = vel[0] / d1;
504        let theta_acc = (acc[0] - d2 * w * w) / d1;
505        let (turn, turn_rate) = self.geometry.arm_motion(theta, self.arms);
506        let j = &self.joint;
507        out[0] = (self.screw_inertia * theta_acc + self.m_nt() * d1 * acc[0] + turn * theta_acc + turn_rate * w * w
508            - gravity)
509            / j.ratio()
510            + j.rotor_inertia * j.ratio() * theta_acc;
511    }
512
513    fn energy(&self, s: &[f64]) -> f64 {
514        self.energy_parts(s).iter().sum()
515    }
516    /// What moves on the frame, as the dynamics have it (the module): the platform with the payload at its height h,
517    /// rising at h'; per stage k its two arms' centres (2 m_a, m_a = arms / 2n), crossing at the horizontal x_f + u / 2
518    /// from the fixed foot x_f (where the drawing has it at the lowest height, -u_0 / 2) and at (k - 1/2) s, moving at
519    /// u' / 2 = -c theta' / 2 and (k - 1/2) s'; the two arms of a stage turn opposite ways, so their spins cancel; the
520    /// screw (along x, at theta') and the rotor spin about x. An obstacle's push is not in its outside force: a
521    /// compliant base takes it through the tool's shift (`base::Based`).
522    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
523        use sim_components::base::{add_point, add_spin};
524        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
525        let Stages { stages, lever, span_low, .. } = self.geometry;
526        let (theta, w) = (s[0], s[1]);
527        let [h, d1, _] = self.height(theta);
528        let (u, du) = (span_low - lever * theta, -lever * w);
529        let (stage, rise) = (h / stages, d1 * w / stages);
530        let platform = self.m_weight - 0.5 * self.arms + if self.payload_attached { self.m_payload } else { 0.0 };
531        add_point(&mut f, platform, [0.0, 0.0, h], [0.0, 0.0, d1 * w]);
532        let pair = self.arms / stages;
533        for k in 0..stages as usize {
534            let up = k as f64 + 0.5;
535            add_point(&mut f, pair, [-0.5 * span_low + 0.5 * u, 0.0, up * stage], [0.5 * du, 0.0, up * rise]);
536        }
537        add_spin(&mut f, [1.0, 0.0, 0.0], self.screw_inertia, w);
538        add_spin(&mut f, [1.0, 0.0, 0.0], self.joint.rotor_inertia, self.rotor(s).1);
539        Some(f)
540    }
541    fn set_payload_attached(&mut self, attached: bool) {
542        self.payload_attached = attached;
543    }
544    /// The push acts on the platform, the tool (`push`): h' F on the arms' angle, whose power is F times the platform's
545    /// speed.
546    fn set_tool_force(&mut self, force: &[f64]) -> bool {
547        self.tool_push = force[0];
548        true
549    }
550    fn set_brake_engaged(&mut self, engaged: bool) {
551        self.brake_engaged = engaged;
552    }
553    /// The gear's efficiency switch near zero power at the step's start (`mech::Gearbox::fade_damping`) on the screw's
554    /// inertia M(theta) there.
555    fn substeps_wanted(&self, s: &[f64], torque: &[f64], dt: f64, substeps: u32) -> u32 {
556        let h = dt / f64::from(substeps);
557        let gear = &self.joint.gearbox;
558        let output = if self.elastic {
559            gear.torque(s[2], s[3], s[0], s[1]).rotor * gear.ratio
560        } else {
561            self.rigid_solve(s, torque[0]).2
562        };
563        let damping = gear.fade_damping(output, s[1]);
564        if damping == 0.0 {
565            return 1;
566        }
567        sim_components::mech::fade_substeps(damping, h, self.load(s[0], s[1]).0)
568    }
569    /// The gearboxes' hysteresis states move on to where the step ended (`Gearbox::commit`).
570    fn after_step(&mut self, s: &mut [f64], _dt: f64) {
571        if self.elastic {
572            self.joint.gearbox.commit(s[2], s[0]);
573        }
574    }
575    fn memory(&self) -> Vec<f64> {
576        self.joint.gearbox.anchor.to_vec()
577    }
578    fn set_memory(&mut self, memory: &[f64]) {
579        sim_components::mech::Gearbox::set_anchors([&mut self.joint.gearbox], memory)
580    }
581
582    fn set_part_temperatures(&mut self, rises: &[f64]) {
583        if let (Some(law), Some(rise), false) = (&self.thermal, rises.first(), self.joint.gearbox.is_coupling()) {
584            self.joint.gearbox.efficiency = law.gearbox_efficiency(*rise) * self.screw_efficiency;
585        }
586    }
587    fn setpoint_slack(&self) -> f64 {
588        self.rest_slack
589    }
590    fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
591        let inside = tool.len() == 1 && tool[0] >= self.min_height - slack && tool[0] <= self.max_height + slack;
592        (!inside).then_some("error-target-out-of-range")
593    }
594
595    fn signal_infos(&self) -> Vec<SignalInfo> {
596        let (motor, axis) = (&self.motors[0], &self.axes[0]);
597        let mut out = vec![
598            SignalInfo::new(format!("gearbox.{}.output_torque", motor.id), motor.key, "quantity-gearbox-torque", "N m"),
599            SignalInfo::new(format!("scissor.{}.actuator_force", self.id), axis.key, "quantity-joint-force", "N"),
600        ];
601        out.extend(TORQUE_PARTS.map(|part| {
602            SignalInfo::new(
603                format!("motor.{}.torque_{part}", motor.id),
604                motor.key,
605                &format!("quantity-torque-{part}"),
606                "N m",
607            )
608        }));
609        let gear = if self.joint.gearbox.is_coupling() {
610            "quantity-coupling-loss-power"
611        } else {
612            "quantity-gearbox-loss-power"
613        };
614        out.extend([
615            SignalInfo::new(
616                format!("{LOSS_PREFIX}shaft_{}", motor.id),
617                motor.key,
618                "quantity-shaft-friction-power",
619                "W",
620            ),
621            SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"),
622            SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"),
623        ]);
624        out.extend(ENERGY_PARTS.map(|part| {
625            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
626        }));
627        out
628    }
629
630    /// The gearbox's output torque, and the force on the sliding foot, the screw's torque over its lever c. The joint's
631    /// gearbox carries the screw's loss too, so `gear` is the torque after the screw: the gearbox's own shaft carries
632    /// more of it while it drives (gear / eta_s) and less while the load drives it back (gear eta_s), as the registered
633    /// screw axes report.
634    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
635        let gear = self.gear(s, torque[0]);
636        let shaft = shaft_torque(gear, s[1], self.screw_efficiency);
637        out.extend([shaft, gear / self.geometry.lever]);
638    }
639    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
640        let (theta, w) = (s[0], s[1]);
641        let j = &self.joint;
642        let (mass, velocity, gravity) = self.load(theta, w);
643        let acc = self.acceleration(s, torque[0]);
644        let (powers, gear_at_rotor) = self.losses(s, torque[0]);
645        let rotor_speed = self.rotor(s).1;
646        let held = j.brake.torque(self.brake_engaged, rotor_speed, self.brake(s)).0;
647        let parts = [
648            (mass * acc + velocity + j.reflected_inertia() * acc) / j.ratio(),
649            -gravity / j.ratio(),
650            j.shaft.torque(rotor_speed) + held + gear_at_rotor,
651        ];
652        out.extend(parts);
653        out.push(torque[0] - parts.iter().sum::<f64>());
654        out.extend(powers);
655        out.extend(self.energy_parts(s));
656    }
657    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
658        out.extend(self.losses(s, torque[0]).0);
659    }
660
661    fn thermal_parts(&self) -> Vec<ThermalPart> {
662        if self.joint.gearbox.is_coupling() {
663            return Vec::new();
664        }
665        vec![ThermalPart {
666            id: self.gearbox_id,
667            kind: "gearbox",
668            owner_key: self.motors[0].key,
669            scene_part: "gearbox",
670            scene_index: 0,
671        }]
672    }
673
674    /// The lift in the plane y = 0: the base, the motor and gearbox at the fixed foot, the screw to the sliding foot,
675    /// the crossed arms of every stage, the platform and the payload on it.
676    fn scene(&self, s: &[f64], out: &mut Scene) {
677        let h = self.height(s[0])[0];
678        let (rotor, rotor_speed) = self.rotor(s);
679        let Stages { stages, arm, .. } = self.geometry;
680        let (n, u) = (stages as usize, (arm * arm - (h / stages).powi(2)).max(0.0).sqrt());
681        let grey = [0.62, 0.64, 0.68];
682        out.parts.clear();
683        out.labels.clear();
684        let width = arm.max(0.2);
685        out.parts.push(Part::new("base", Shape::Box { size: [width + 0.2, 0.4, 0.04] }, [0.0, 0.0, -0.02], grey));
686        let foot = [-0.5 * u, 0.0, 0.0];
687        out.parts.push(Part::new(
688            sim_core::scene::MOTOR_PART,
689            Shape::Box { size: [0.12, 0.09, 0.09] },
690            [-0.5 * width - 0.2, 0.0, 0.06],
691            [0.9, 0.45, 0.1],
692        ));
693        out.parts.push(Part::new(
694            "gearbox",
695            Shape::Box { size: [0.06, 0.09, 0.09] },
696            [-0.5 * width - 0.11, 0.0, 0.06],
697            [0.25, 0.25, 0.28],
698        ));
699        out.parts.push(
700            Part::new(
701                "rotor-bar",
702                Shape::Box { size: [0.004, 0.07, 0.012] },
703                [-0.5 * width - 0.27, 0.0, 0.06],
704                [0.1, 0.1, 0.1],
705            )
706            .turned(rotor),
707        );
708        out.parts.push(Part::new(
709            "screw",
710            Shape::Segment { to: [0.5 * u, 0.0, 0.06], width: 0.016 },
711            [-0.5 * width - 0.08, 0.0, 0.06],
712            [0.5, 0.5, 0.55],
713        ));
714        let stage = h / stages;
715        for k in 0..n {
716            let (low, high) = (k as f64 * stage, (k + 1) as f64 * stage);
717            for (from, to) in [(foot[0], 0.5 * u), (0.5 * u, foot[0])] {
718                out.parts.push(Part::new(
719                    "arm",
720                    Shape::Segment { to: [to, 0.0, high], width: 0.03 },
721                    [from, 0.0, low],
722                    [0.2, 0.22, 0.26],
723                ));
724            }
725        }
726        out.parts.push(Part::new(
727            "platform",
728            Shape::Box { size: [width, 0.4, 0.03] },
729            [0.0, 0.0, h + 0.015],
730            [0.55, 0.55, 0.6],
731        ));
732        if self.payload_attached && self.m_payload > 0.0 {
733            out.parts.push(Part::new(
734                "payload",
735                Shape::Box { size: [0.2, 0.2, 0.15] },
736                [0.0, 0.0, h + 0.105],
737                [0.2, 0.7, 0.3],
738            ));
739        }
740        out.labels.push(Label {
741            pos: [-0.5 * width - 0.2, 0.0, 0.16],
742            owner_key: self.motors[0].key,
743            value: rotor_speed * 60.0 / std::f64::consts::TAU,
744            unit_key: "unit-rpm",
745            decimals: 0,
746        });
747        out.labels.push(Label {
748            pos: [0.5 * width + 0.1, 0.0, h],
749            owner_key: self.axes[0].key,
750            value: h,
751            unit_key: "unit-m",
752            decimals: 3,
753        });
754    }
755
756    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
757        Some([0.0, 0.0, tool_pose[0] + 0.03])
758    }
759}
760
761/// The gearbox's own output torque from the torque after the screw: more while it drives, less while driven back.
762fn shaft_torque(after_screw: f64, speed: f64, screw_efficiency: f64) -> f64 {
763    after_screw * if after_screw * speed >= 0.0 { 1.0 / screw_efficiency } else { screw_efficiency }
764}
765
766#[cfg(test)]
767mod tests {
768    use super::*;
769
770    /// Two stages of 1 m arms, lead 10 mm: at h = 0.6 m a stage stands 0.3 m, the feet u = sqrt(1 - 0.09) = 0.953939 m
771    /// apart; a weight W = 1000 N on the platform takes F = W n u / s = 1000 * 2 * 0.953939 / 0.3 = 6359.59 N at the
772    /// foot (cot alpha = 3.17980). At h = 1.6 m (s = 0.8, u = 0.6): F = 1000 * 2 * 0.6 / 0.8 = 1500 N, cot alpha = 0.75.
773    /// The ratio of the two, 4.23973, is the price of lifting from low down. By virtual work, F = W dh/du: the
774    /// derivative of `height` by theta over the lever c gives the same.
775    #[test]
776    fn the_scissor_force_ratio_is_n_cot_alpha_at_two_heights() {
777        let lift = Stages { stages: 2.0, arm: 1.0, lever: 0.01 / std::f64::consts::TAU, span_low: 0.99f64.sqrt() };
778        for (h, by_hand, cot) in [(0.6, 6359.59, 3.179_797), (1.6, 1500.0, 0.75)] {
779            let force = lift.actuator_force(1000.0, h);
780            assert!((force - by_hand).abs() < 0.01, "h = {h}: {force} N against {by_hand}");
781            assert!((force - 1000.0 * 2.0 * cot).abs() < 0.001, "h = {h}: n cot alpha");
782            let theta = lift.angle(h);
783            let [height, d1, _] = lift.height(theta);
784            assert!((height - h).abs() < 1e-12, "{height}");
785            assert!((1000.0 * d1 / lift.lever - force).abs() < 1e-6, "virtual work at h = {h}");
786        }
787        let ratio = lift.actuator_force(1000.0, 0.6) / lift.actuator_force(1000.0, 1.6);
788        assert!((ratio - 4.239_73).abs() < 1e-5, "{ratio}");
789        // d2h/dtheta2 against central differences of dh/dtheta.
790        let theta = lift.angle(1.0);
791        let step = 1e-3;
792        let numeric = (lift.height(theta + step)[1] - lift.height(theta - step)[1]) / (2.0 * step);
793        assert!((lift.height(theta)[2] - numeric).abs() < 1e-9 * numeric.abs().max(1e-9), "{numeric}");
794    }
795    /// The arms' turning and sideways motion, by hand: two stages of 1 m arms, 40 kg of arms, lever c = 0.01 m/rad, at
796    /// h = 1 m (s = 0.5, u = 0.866025). Sideways: 2n (m_a / 2) (c / 2)^2 per theta'^2 = arms c^2 / 8 = 5e-4, so M = 1e-3;
797    /// turning: 2n (m_a L^2 / 24) (s' / u)^2 with s' = c u / s gives arms L^2 c^2 / (24 s^2) = 40 * 1e-4 / 6 =
798    /// 6.6667e-4, M = 1.33333e-3: M_a = 2.33333e-3 kg m^2. The speed term is half the slope of M_a, which a central
799    /// difference of the mass confirms.
800    #[test]
801    fn the_arms_turning_and_sideways_motion_add_their_inertia() {
802        let lift = Stages { stages: 2.0, arm: 1.0, lever: 0.01, span_low: 0.99f64.sqrt() };
803        let theta = lift.angle(1.0);
804        let (m, rate) = lift.arm_motion(theta, 40.0);
805        assert!((m - 2.333_333e-3).abs() < 1e-8, "{m}");
806        let step = 1e-4;
807        let slope = (lift.arm_motion(theta + step, 40.0).0 - lift.arm_motion(theta - step, 40.0).0) / (2.0 * step);
808        assert!((rate - 0.5 * slope).abs() < 1e-6 * rate.abs(), "{rate} against {}", 0.5 * slope);
809    }
810    /// Screw 0.9, gearbox 0.96, ratio 20, the weight needing F c = 27.780 N m after both (motor 1.60763 N m lifting:
811    /// 1.60763 * 20 * 0.96 * 0.9). Lifting the gearbox's own shaft carries 27.780 / 0.9 = 30.867 N m; lowering
812    /// (same holding torque, speed reversed) 27.780 * 0.9 = 25.002 N m.
813    #[test]
814    fn the_gearbox_shaft_carries_the_screws_loss() {
815        assert!((shaft_torque(27.780, 0.05, 0.9) - 30.867).abs() < 1e-3);
816        assert!((shaft_torque(27.780, -0.05, 0.9) - 25.002).abs() < 1e-3);
817    }
818}