Skip to main content

sim_components/
transmission.rs

1//! Transmissions that turn a motor's rotation into the motion of a load, beside belts and planetary gearboxes: ball
2//! screw, rack and pinion, linear motor, worm gear and strain wave gear. Each gives what the simulation needs (ratio
3//! from motor radians to the load's coordinate, efficiency, stiffness, inertia, drag) and the ratings its maker checks
4//! a cycle against, with the maker's published formulas. They know no machine; `chain::JointMachine` puts them on a
5//! joint.
6//!
7//! Units: lengths in m, forces in N, torques in N m, speeds of rotation in r/min where a catalogue gives them so.
8
9use crate::joint::RotaryJoint;
10use crate::mech::{BRISTLE_RATE_MAX, HoldingBrake, TravelCompliance, series_dampers};
11use sim_core::{Config, ConfigError, RatingCheck, SignalInfo};
12use std::f64::consts::PI;
13
14type Result<T> = std::result::Result<T, ConfigError>;
15
16/// Young's modulus and density of screw steel, Pa and kg/m^3.
17pub const STEEL_E: f64 = 2.06e11;
18pub const STEEL_DENSITY: f64 = 7850.0;
19
20/// How a screw shaft is held at its two ends, for its critical speed and buckling load.
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub enum Mounting {
23    FixedFree,
24    SupportedSupported,
25    FixedSupported,
26    FixedFixed,
27}
28
29impl Mounting {
30    pub fn parse(name: &str) -> Option<Self> {
31        Some(match name {
32            "fixed-free" => Self::FixedFree,
33            "supported-supported" => Self::SupportedSupported,
34            "fixed-supported" => Self::FixedSupported,
35            "fixed-fixed" => Self::FixedFixed,
36            _ => return None,
37        })
38    }
39
40    /// lambda L of the first bending mode of a uniform beam with these ends (Euler-Bernoulli): 1.875, pi, 3.927, 4.730.
41    pub fn mode_factor(self) -> f64 {
42        match self {
43            Self::FixedFree => 1.875_104,
44            Self::SupportedSupported => PI,
45            Self::FixedSupported => 3.926_602,
46            Self::FixedFixed => 4.730_041,
47        }
48    }
49
50    /// The factor on the pin-ended Euler load pi^2 E I / L^2: 1/4, 1, 2.046, 4.
51    pub fn buckling_factor(self) -> f64 {
52        match self {
53            Self::FixedFree => 0.25,
54            Self::SupportedSupported => 1.0,
55            Self::FixedSupported => 2.046,
56            Self::FixedFixed => 4.0,
57        }
58    }
59}
60
61/// What turns a gearbox's output rotation into a joint's travel (ball screw, rack and pinion): the travel per radian of
62/// its input (`lever`, m/rad), its own stiffness along the travel (N/m), its backlash (m), efficiency, the inertia
63/// that turns with its input (screw shaft, pinion; kg m^2), and the damping ratio of its spring's own mode (nut,
64/// bearings and guides; `apply_back`).
65#[derive(Debug, Clone, PartialEq)]
66pub struct Converter {
67    pub lever: f64,
68    pub stiffness: f64,
69    pub backlash: f64,
70    pub efficiency: f64,
71    pub inertia: f64,
72    pub damping_ratio: f64,
73}
74
75impl Converter {
76    /// Puts the converter behind `joint`'s gearbox (read in N m and rad at the converter's input): the joint's gearbox
77    /// becomes gearbox and converter together, in N and m. Ratio i / lever; stiffness of the gearbox seen at the joint
78    /// (over lever^2) in series with the converter's, the gearbox's damping across its own spring alone (a Zener solid,
79    /// `Gearbox::arm`); backlash and efficiency added and multiplied as
80    /// effects.gearbox_backlash and effects.gearbox_efficiency say; the converter's inertia joins the rotor over i^2.
81    ///
82    /// With effects.thermal_feedback the gearbox's temperature changes the gearbox's share of the efficiency, not the
83    /// converter's (`RotaryJoint::extra_efficiency`).
84    ///
85    /// The output's own inertia is not known here: the mesh friction's bristle is capped by the rotor's (`apply_to`).
86    pub fn apply(&self, cfg: &Config, joint: &mut RotaryJoint) -> Result<()> {
87        self.apply_to(cfg, joint, f64::INFINITY)
88    }
89
90    /// `apply` for an output of the given inertia at the joint's travel (kg behind a screw, rack or drum): the mesh
91    /// friction's bristle, between the gear's output and the housing, is capped by the smaller of it and the rotor's
92    /// inertia seen at the load, so that a light output (a winch drum) does not stick to the housing at a frequency the
93    /// step cannot follow.
94    pub fn apply_to(&self, cfg: &Config, joint: &mut RotaryJoint, output: f64) -> Result<()> {
95        self.apply_back(cfg, joint, output, self.efficiency)
96    }
97
98    /// `apply_to` for a converter that loses `back_efficiency` where the load drives it back (`self.efficiency` driving):
99    /// the gearbox's back-driving efficiency becomes its own times back_efficiency / efficiency (`Gearbox::back_ratio`).
100    ///
101    /// The converter's spring is in series with the whole gear. The lost-motion band is the gearbox's angle times the
102    /// lever, and over it the converter's spring stretches with the force as it does beyond (`Gearbox::band_compliance`);
103    /// the line beyond the band keeps its offset, b lever / 2. The hysteresis, a friction T_h in parallel with the
104    /// flanks' spring K1 (lever^2 / K1 in m/N at the joint): sliding, the force is K1' (x -+ lever T_h / K1) with K1' the
105    /// series stiffness, so its friction at the joint is T_h / lever times K1' lever^2 / K1, and its loop as wide as the
106    /// gear's, 2 lever T_h / K1; at a reversal the gear is K1 + sigma, in series K1' + sigma' with
107    /// sigma' = series(K1 + sigma) - series(K1).
108    pub fn apply_back(&self, cfg: &Config, joint: &mut RotaryJoint, output: f64, back_efficiency: f64) -> Result<()> {
109        let (g, l) = (&mut joint.gearbox, self.lever);
110        let i = g.ratio;
111        g.ratio = i / l;
112        let converter = self.stiffness;
113        let mesh_factor = g.mesh_stiffness / g.stiffness;
114        let series = move |k: f64| 1.0 / (l * l / k + 1.0 / converter);
115        let (k1, sigma) = (g.stiffness, g.dahl_stiffness);
116        // The three segments are given in torque, so each is in series with the converter as K1 is; the knees are
117        // torques at the gearbox output, forces over the lever at the joint.
118        [g.stiffness, g.upper[0], g.upper[1]] = [g.stiffness, g.upper[0], g.upper[1]].map(series);
119        g.dahl_stiffness = series(k1 + sigma) - g.stiffness;
120        g.knees = g.knees.map(|t| t / l);
121        g.hysteresis *= g.stiffness * l / k1;
122        g.band *= l;
123        g.band_compliance = g.band_compliance * l * l + 1.0 / converter;
124        // Two damped springs in series, the node between them massless: the gear's K_g = K1 / l^2 with its damper c_g
125        // across it alone, and the converter's K_c with c_c = 2 zeta sqrt(K_c m) across it alone, zeta its
126        // `damping_ratio` and m the mass behind it (`output`; none where it is not known). Their K_s + b s + K_m tau s /
127        // (1 + tau s) holds it exactly (`Gearbox::arm`): b = c_g c_c / C, tau = C / S, K_m = (K_g c_c - K_c c_g)^2 /
128        // (S C^2), with S = K_g + K_c, C = c_g + c_c. An arm that would settle faster than the integrator follows
129        // (`BRISTLE_RATE_MAX`, tau under 10 us) is its slow limit, u following x: a damper K_m tau beside b, off by
130        // (omega tau)^2 at a ring of omega (0.4 % at 1 kHz). A rigid converter leaves the gear's damper across it.
131        let damping = g.damping / (l * l);
132        let own = self.own_damping(output);
133        let (across, arm, tau) = series_dampers(k1 / (l * l), damping, converter, own);
134        if !converter.is_finite() {
135            g.damping = damping;
136        } else if arm > 0.0 && tau * BRISTLE_RATE_MAX >= 1.0 {
137            (g.relax_stiffness, g.relax_time, g.damping) = (arm, tau, across);
138        } else {
139            g.damping = across + arm * tau;
140        }
141        g.half_backlash =
142            g.half_backlash * l + if cfg.bool("effects.gearbox_backlash")? { 0.5 * self.backlash } else { 0.0 };
143        if cfg.bool("effects.gearbox_efficiency")? {
144            g.efficiency *= self.efficiency;
145            joint.extra_efficiency *= self.efficiency;
146            g.back_ratio *= back_efficiency / self.efficiency;
147        }
148        joint.rotor_inertia += self.inertia / (i * i);
149        // The mesh friction's bristle is `gearbox.mesh_stiffness_factor` (MESH_STIFFNESS) times the converted series stiffness (N/m now, not N m/rad). No
150        // shipped machine reaches the cap below: rack, screw and both machines hung in cables run the full 2.6e7 to 5.6e7 N/m, and
151        // their gearbox loss per cycle is the same at a tenth and at ten times it to 4e-4 J (rack 16.741 J, screw
152        // 16.762 J, cable-planar 38.167 J, cable-spatial 53.544 to 53.548 J), with their energy budgets closed to 2e-5 J.
153        // A gear far stiffer than any shipped (1e12 N m/rad behind a rigid lever) is capped where the bristle on the
154        // lighter of the rotor's inertia seen at the load and the output's own stays at a quarter of BRISTLE_RATE_MAX
155        // (omega h = 0.39 at the 15.6 us step against RK4's 2.8). A winch drum of 0.32 kg at its radius puts the cap at
156        // 2e8 N/m, above what the winches' gears give.
157        if g.mesh_stiffness > 0.0 {
158            let lighter = (joint.rotor_inertia * g.ratio * g.ratio).min(output);
159            let omega = BRISTLE_RATE_MAX / 4.0;
160            g.mesh_stiffness = (mesh_factor * g.stiffness).min(lighter * omega * omega);
161        }
162        joint.brake = HoldingBrake::from_config(cfg, joint.rotor_inertia)?;
163        Ok(())
164    }
165
166    /// The damper across the converter's spring alone, c_c = 2 zeta sqrt(K_c m) for the mass m behind it (`output`): 0
167    /// where that is not known or the converter is rigid.
168    fn own_damping(&self, output: f64) -> f64 {
169        if output.is_finite() && self.stiffness.is_finite() {
170            2.0 * self.damping_ratio * (self.stiffness * output).sqrt()
171        } else {
172            0.0
173        }
174    }
175}
176
177/// A converter with its own back-driving efficiency (`BallScrew::converter`): derefs to the `Converter`, and applies like
178/// it (`Converter::apply`, `apply_to`) with the back efficiency in the gearbox, and the screw's compliance along the
179/// travel where it follows the nut (`Gearbox::travel`).
180#[derive(Debug, Clone, PartialEq)]
181pub struct BackDriven {
182    pub converter: Converter,
183    pub back_efficiency: f64,
184    pub travel: Option<TravelCompliance>,
185}
186
187impl std::ops::Deref for BackDriven {
188    type Target = Converter;
189    fn deref(&self) -> &Converter {
190        &self.converter
191    }
192}
193
194impl BackDriven {
195    pub fn apply(&self, cfg: &Config, joint: &mut RotaryJoint) -> Result<()> {
196        self.apply_to(cfg, joint, f64::INFINITY)
197    }
198
199    pub fn apply_to(&self, cfg: &Config, joint: &mut RotaryJoint, output: f64) -> Result<()> {
200        // The gear's spring and damper at the joint, before they go in series with the screw: its dampers are laid out
201        // anew where the nut is (`Gearbox::at`).
202        let l2 = self.lever * self.lever;
203        let gear = [joint.gearbox.stiffness / l2, joint.gearbox.damping / l2];
204        self.converter.apply_back(cfg, joint, output, self.back_efficiency)?;
205        joint.gearbox.travel =
206            self.travel.map(|t| TravelCompliance { gear, converter: [self.stiffness, self.own_damping(output)], ..t });
207        Ok(())
208    }
209}
210
211/// A ball screw: shaft, nut and the bearings that hold the shaft. The nut moves the load by `lead` per turn.
212///
213/// Config `[screw]`: `lead_m`, `nominal_diameter_m`, `root_diameter_m`, `length_m` (between the bearings, or from the
214/// fixed bearing to the free end), `mounting` (as `Mounting::parse`), `efficiency`, `friction_coefficient` (with
215/// effects.screw_lead_efficiency, `lead_efficiency`), `nut_stiffness_n_m`,
216/// `bearing_stiffness_n_m`, `preload_n`, `dynamic_load_rating_n` (Ca), `static_load_rating_n` (C0a), `load_factor`
217/// (fw), `static_safety_factor`, `critical_speed_factor`, `buckling_safety_factor`, `max_dn` (d n with d in mm and n in
218/// r/min; 0 for none), and optionally `axial_damping_ratio` (the damping ratio of the mass behind the nut on the screw's
219/// axial spring, from the nut, the bearings and the guides: `Converter::apply_back`; 0 where it is absent). With
220/// effects.screw_stiffness_with_position (off where absent), `fixed_bearing_at_m`: the joint's travel at which the fixed
221/// bearing stands (`TravelCompliance`).
222#[derive(Debug, Clone, PartialEq)]
223pub struct BallScrew {
224    pub lead: f64,
225    pub nominal_diameter: f64,
226    pub root_diameter: f64,
227    pub length: f64,
228    pub mounting: Mounting,
229    pub efficiency: f64,
230    /// Driven back by the load, with effects.screw_lead_efficiency (`lead_back_efficiency`); the forward one otherwise.
231    pub back_efficiency: f64,
232    pub nut_stiffness: f64,
233    pub bearing_stiffness: f64,
234    pub preload: f64,
235    pub dynamic_rating: f64,
236    pub static_rating: f64,
237    pub load_factor: f64,
238    pub static_safety: f64,
239    pub speed_factor: f64,
240    pub buckling_safety: f64,
241    pub max_dn: f64,
242    pub axial_damping_ratio: f64,
243    /// With effects.screw_stiffness_with_position: the joint's travel at the fixed bearing, m. None: the stiffness is
244    /// the one at the position `converter` is given for the whole stroke.
245    pub fixed_bearing_at: Option<f64>,
246}
247
248/// An optional damping ratio, 0 where the key is absent (a config written before 20 November 2026), below 1.
249fn damping_ratio(cfg: &Config, key: &str) -> Result<f64> {
250    if cfg.get(key).is_err() {
251        return Ok(0.0);
252    }
253    let zeta = cfg.non_negative(key)?;
254    if zeta >= 1.0 {
255        return Err(ConfigError::Invalid(key.into()));
256    }
257    Ok(zeta)
258}
259
260impl BallScrew {
261    pub fn from_config(cfg: &Config) -> Result<Self> {
262        let p = |name: &str| cfg.positive(&format!("screw.{name}"));
263        let mounting = cfg
264            .get("screw.mounting")?
265            .as_str()
266            .and_then(Mounting::parse)
267            .ok_or_else(|| ConfigError::Invalid("screw.mounting".into()))?;
268        let (nominal, root) = (p("nominal_diameter_m")?, p("root_diameter_m")?);
269        if root > nominal {
270            return Err(ConfigError::Invalid("screw.root_diameter_m".into()));
271        }
272        let efficiency = p("efficiency")?;
273        if efficiency > 1.0 {
274            return Err(ConfigError::Invalid("screw.efficiency".into()));
275        }
276        let lead = p("lead_m")?;
277        // A config without the switch (one written before 16 November 2026) has it off.
278        let (efficiency, back_efficiency) =
279            if cfg.get("effects.screw_lead_efficiency").is_ok() && cfg.bool("effects.screw_lead_efficiency")? {
280                let mu = cfg.positive("screw.friction_coefficient")?;
281                let back = Self::lead_back_efficiency(lead, nominal, mu);
282                if back <= 0.0 {
283                    return Err(ConfigError::Invalid(
284                        "screw.friction_coefficient (the screw locks itself driven back: its efficiency there is \
285                         not positive, and this gearbox does not model a self-locking screw)"
286                            .into(),
287                    ));
288                }
289                (Self::lead_efficiency(lead, nominal, mu), back)
290            } else {
291                (efficiency, efficiency)
292            };
293        Ok(Self {
294            lead,
295            nominal_diameter: nominal,
296            root_diameter: root,
297            length: p("length_m")?,
298            mounting,
299            efficiency,
300            back_efficiency,
301            nut_stiffness: p("nut_stiffness_n_m")?,
302            bearing_stiffness: p("bearing_stiffness_n_m")?,
303            preload: cfg.non_negative("screw.preload_n")?,
304            dynamic_rating: p("dynamic_load_rating_n")?,
305            static_rating: p("static_load_rating_n")?,
306            load_factor: p("load_factor")?,
307            static_safety: p("static_safety_factor")?,
308            speed_factor: p("critical_speed_factor")?,
309            buckling_safety: p("buckling_safety_factor")?,
310            max_dn: cfg.non_negative("screw.max_dn")?,
311            axial_damping_ratio: damping_ratio(cfg, "screw.axial_damping_ratio")?,
312            // A config without the switch (one written before 21 November 2026) has it off.
313            fixed_bearing_at: if cfg.get("effects.screw_stiffness_with_position").is_ok()
314                && cfg.bool("effects.screw_stiffness_with_position")?
315            {
316                Some(cfg.f64("screw.fixed_bearing_at_m")?)
317            } else {
318                None
319            },
320        })
321    }
322
323    /// The rolling efficiency of a ball screw driving its nut, from its lead angle beta = atan(lead / (pi d)) and the
324    /// balls' friction coefficient mu (THK's formula): (1 - mu tan beta) / (1 + mu / tan beta), tan beta / tan(beta + rho)
325    /// with mu = tan rho. effects.screw_lead_efficiency puts it in place of `screw.efficiency`, which is a catalogue's
326    /// lumped figure that holds the nut's preload drag too; the preload drags apart (`preload_torque`).
327    pub fn lead_efficiency(lead: f64, nominal_diameter: f64, mu: f64) -> f64 {
328        let tan_beta = lead / (PI * nominal_diameter);
329        (1.0 - mu * tan_beta) / (1.0 + mu / tan_beta)
330    }
331
332    /// The efficiency of the load driving the screw back (THK): (1 - mu / tan beta) / (1 + mu tan beta). Zero or less
333    /// where tan beta <= mu: the screw locks itself (`from_config` refuses that). It is the driving one with force and
334    /// motion swapped, tan(beta - rho) / tan(beta) with mu = tan rho.
335    pub fn lead_back_efficiency(lead: f64, nominal_diameter: f64, mu: f64) -> f64 {
336        let tan_beta = lead / (PI * nominal_diameter);
337        (1.0 - mu / tan_beta) / (1.0 + mu * tan_beta)
338    }
339
340    /// Screw radians per metre of travel: 2 pi / lead.
341    pub fn ratio(&self) -> f64 {
342        2.0 * PI / self.lead
343    }
344
345    /// The shaft's moment of inertia about its axis, a solid steel cylinder of the nominal diameter: pi rho L d^4 / 32.
346    pub fn inertia(&self) -> f64 {
347        PI * STEEL_DENSITY * self.length * self.nominal_diameter.powi(4) / 32.0
348    }
349
350    /// Second moment of area and area of the root section.
351    fn section(&self) -> (f64, f64) {
352        let d = self.root_diameter;
353        (PI * d.powi(4) / 64.0, PI * d * d / 4.0)
354    }
355
356    /// The first bending mode of the shaft as a speed, r/min: n = 60 / (2 pi) (lambda L)^2 / L^2 sqrt(E I / (rho A)),
357    /// a uniform beam of the root diameter over `length`.
358    pub fn critical_speed_rpm(&self) -> f64 {
359        let (i, a) = self.section();
360        let omega = (self.mounting.mode_factor() / self.length).powi(2) * (STEEL_E * i / (STEEL_DENSITY * a)).sqrt();
361        omega * 60.0 / (2.0 * PI)
362    }
363
364    /// The highest screw speed the cycle may reach, r/min: the critical speed times `critical_speed_factor` (makers
365    /// ask for 0.8).
366    pub fn allowed_speed_rpm(&self) -> f64 {
367        self.speed_factor * self.critical_speed_rpm()
368    }
369
370    /// Euler's buckling load of the shaft, N: factor pi^2 E I / L^2 with the mounting's factor.
371    pub fn buckling_load(&self) -> f64 {
372        self.mounting.buckling_factor() * PI * PI * STEEL_E * self.section().0 / (self.length * self.length)
373    }
374
375    /// The highest axial force allowed against buckling: the buckling load over `buckling_safety_factor`.
376    pub fn allowed_buckling_force(&self) -> f64 {
377        self.buckling_load() / self.buckling_safety
378    }
379
380    /// The highest axial force allowed by the static rating: C0a over the static safety factor.
381    pub fn allowed_static_force(&self) -> f64 {
382        self.static_rating / self.static_safety
383    }
384
385    /// Axial stiffness between the motor's shaft angle and the nut, N/m, with the nut `x` from the fixed bearing (the
386    /// fixed-fixed shaft held at both ends: A E L / (x (L - x))): shaft, nut and bearings in series. The shaft's
387    /// share at least that of its whole length.
388    pub fn stiffness(&self, x: f64) -> f64 {
389        let ae = STEEL_E * self.section().1;
390        let x = x.clamp(1e-3 * self.length, self.length);
391        let shaft = match self.mounting {
392            Mounting::FixedFixed => ae * self.length / (x * (self.length - x).max(1e-3 * self.length)),
393            _ => ae / x,
394        };
395        1.0 / (1.0 / shaft + 1.0 / self.nut_stiffness + 1.0 / self.bearing_stiffness)
396    }
397
398    /// The drag torque of the nut's preload, N m (THK's formula): K Fpr l / (2 pi), K = 0.05 / sqrt(tan beta), beta the
399    /// lead angle atan(l / (pi d)).
400    pub fn preload_torque(&self) -> f64 {
401        let tan_beta = self.lead / (PI * self.nominal_diameter);
402        0.05 / tan_beta.sqrt() * self.preload * self.lead / (2.0 * PI)
403    }
404
405    /// The load each ball track of a preloaded double nut carries under an axial force: Fpr (1 + Fa / (2.83 Fpr))^(3/2)
406    /// until the force lifts the preload off the other nut (at 2.83 Fpr), the force itself beyond (Hiwin's catalogue).
407    pub fn equivalent_load(&self, force: f64) -> f64 {
408        let f = force.abs();
409        let lift = 2.83 * self.preload;
410        if self.preload <= 0.0 || f >= lift { f } else { self.preload * (1.0 + f / lift).powf(1.5) }
411    }
412
413    /// The share of the nominal life (L10 = (Ca / (fw Fm))^3 10^6 turns, ISO 3408-5) used per hour at an axial force
414    /// and a screw speed (r/min): 60 |n| (fw F_eq / Ca)^3 / 10^6. Its mean over a cycle is one over the life in hours.
415    pub fn damage_rate(&self, force: f64, rpm: f64) -> f64 {
416        60.0 * rpm.abs() * (self.load_factor * self.equivalent_load(force) / self.dynamic_rating).powi(3) / 1e6
417    }
418
419    /// d n, the nominal diameter in mm times the speed in r/min, against `max_dn`.
420    pub fn dn(&self, rpm: f64) -> f64 {
421        self.nominal_diameter * 1e3 * rpm.abs()
422    }
423
424    /// The screw as a converter, stiff as it is with the nut at `x` from the fixed bearing. Every builder passes
425    /// `softest_position()`. Without `fixed_bearing_at` that is the joint gearbox's stiffness for the whole stroke, which
426    /// judges resonance and settling on the safe side; with it the gearbox follows the nut from there (`travel`).
427    pub fn converter(&self, x: f64) -> BackDriven {
428        BackDriven {
429            converter: Converter {
430                lever: 1.0 / self.ratio(),
431                stiffness: self.stiffness(x),
432                backlash: 0.0,
433                efficiency: self.efficiency,
434                inertia: self.inertia(),
435                damping_ratio: self.axial_damping_ratio,
436            },
437            back_efficiency: self.back_efficiency,
438            travel: self.travel(x),
439        }
440    }
441
442    /// The shaft's compliance along the travel with `x` as the reference (`TravelCompliance`), where it follows the nut.
443    pub fn travel(&self, x: f64) -> Option<TravelCompliance> {
444        let fixed_bearing_at = self.fixed_bearing_at?;
445        let mut t = TravelCompliance {
446            ae: STEEL_E * self.section().1,
447            length: self.length,
448            both_ends: self.mounting == Mounting::FixedFixed,
449            fixed_bearing_at,
450            reference: 0.0,
451            gear: [0.0; 2],
452            converter: [0.0; 2],
453        };
454        t.reference = t.shaft(x).0;
455        Some(t)
456    }
457
458    /// Where the shaft is softest: its far end, or its middle where both ends are fixed.
459    pub fn softest_position(&self) -> f64 {
460        if self.mounting == Mounting::FixedFixed { 0.5 * self.length } else { self.length }
461    }
462}
463
464/// The standard pressure angle of a rack and pinion's teeth (DIN 867), in the normal section: the default of
465/// `rack.pressure_angle_deg`.
466const RACK_PRESSURE_ANGLE_DEG: f64 = 20.0;
467
468/// A pinion on a rack. Config `[rack]`: `module_m`, `teeth`, `helix_angle_deg`, `efficiency`, `stiffness_n_m` (mesh and
469/// rack mounting), `backlash_m`, `pinion_inertia_kgm2`, `rated_feed_force_n` (the maker's permissible feed force of the
470/// pair), `service_factor` (K_A), and optionally `pressure_angle_deg` (normal section, 20 where absent) and
471/// `damping_ratio` (the damping ratio of the mass behind the pinion on the mesh's spring: `Converter::apply_back`; 0
472/// where absent).
473#[derive(Debug, Clone, PartialEq)]
474pub struct RackPinion {
475    pub module: f64,
476    pub teeth: f64,
477    pub helix_angle: f64,
478    pub efficiency: f64,
479    pub stiffness: f64,
480    pub backlash: f64,
481    pub pinion_inertia: f64,
482    pub rated_force: f64,
483    pub service_factor: f64,
484    /// Normal pressure angle, rad.
485    pub pressure_angle: f64,
486    pub damping_ratio: f64,
487}
488
489impl RackPinion {
490    pub fn from_config(cfg: &Config) -> Result<Self> {
491        let p = |name: &str| cfg.positive(&format!("rack.{name}"));
492        let helix = cfg.non_negative("rack.helix_angle_deg")?;
493        let efficiency = p("efficiency")?;
494        if helix >= 45.0 || efficiency > 1.0 {
495            return Err(ConfigError::Invalid(
496                if helix >= 45.0 { "rack.helix_angle_deg" } else { "rack.efficiency" }.into(),
497            ));
498        }
499        let alpha =
500            if cfg.get("rack.pressure_angle_deg").is_ok() { p("pressure_angle_deg")? } else { RACK_PRESSURE_ANGLE_DEG };
501        if alpha >= 45.0 {
502            return Err(ConfigError::Invalid("rack.pressure_angle_deg".into()));
503        }
504        Ok(Self {
505            pressure_angle: alpha.to_radians(),
506            module: p("module_m")?,
507            teeth: p("teeth")?,
508            helix_angle: helix.to_radians(),
509            efficiency,
510            stiffness: p("stiffness_n_m")?,
511            backlash: cfg.non_negative("rack.backlash_m")?,
512            pinion_inertia: p("pinion_inertia_kgm2")?,
513            rated_force: p("rated_feed_force_n")?,
514            service_factor: p("service_factor")?,
515            damping_ratio: damping_ratio(cfg, "rack.damping_ratio")?,
516        })
517    }
518
519    /// The pinion's pitch radius: m z / (2 cos beta), the normal module m.
520    pub fn radius(&self) -> f64 {
521        self.module * self.teeth / (2.0 * self.helix_angle.cos())
522    }
523
524    /// The highest feed force the cycle may reach: the rated feed force over the service factor.
525    pub fn allowed_force(&self) -> f64 {
526        self.rated_force / self.service_factor
527    }
528
529    pub fn converter(&self) -> Converter {
530        Converter {
531            lever: self.radius(),
532            stiffness: self.stiffness,
533            backlash: self.backlash,
534            efficiency: self.efficiency,
535            inertia: self.pinion_inertia,
536            damping_ratio: self.damping_ratio,
537        }
538    }
539}
540
541/// An ironcore linear motor: the forcer on the carriage, the magnet track along the axis. Config `[linear_motor]`:
542/// `attraction_force_n` (between forcer and magnets, on the guide), `pole_pitch_m` (north to north, the period of the
543/// cogging). The force constant, resistance and the rest are the drive's `[motor]` values, read with N for N m and m for
544/// rad.
545#[derive(Debug, Clone, PartialEq)]
546pub struct LinearMotor {
547    pub attraction: f64,
548    pub pole_pitch: f64,
549}
550
551impl LinearMotor {
552    pub fn from_config(cfg: &Config) -> Result<Self> {
553        Ok(Self {
554            attraction: cfg.non_negative("linear_motor.attraction_force_n")?,
555            pole_pitch: cfg.positive("linear_motor.pole_pitch_m")?,
556        })
557    }
558
559    /// The cogging's order for `mech::Ripple`, whose angle is here the forcer's position: one period per pole pitch.
560    pub fn cogging_order(&self) -> f64 {
561        2.0 * PI / self.pole_pitch
562    }
563}
564
565/// A worm gear. Config `[worm]`: `lead_angle_deg` (gamma), `friction_coefficient` (mu), `pressure_angle_deg` (alpha_n).
566/// The ratio is the gearbox's.
567#[derive(Debug, Clone, PartialEq)]
568pub struct WormGear {
569    pub lead_angle: f64,
570    pub friction: f64,
571    pub pressure_angle: f64,
572}
573
574impl WormGear {
575    pub fn from_config(cfg: &Config) -> Result<Self> {
576        let gamma = cfg.positive("worm.lead_angle_deg")?;
577        let alpha = cfg.non_negative("worm.pressure_angle_deg")?;
578        if gamma >= 45.0 || alpha >= 45.0 {
579            return Err(ConfigError::Invalid(
580                if gamma >= 45.0 { "worm.lead_angle_deg" } else { "worm.pressure_angle_deg" }.into(),
581            ));
582        }
583        Ok(Self {
584            lead_angle: gamma.to_radians(),
585            friction: cfg.non_negative("worm.friction_coefficient")?,
586            pressure_angle: alpha.to_radians(),
587        })
588    }
589
590    /// The friction angle on the flank: rho' = atan(mu / cos alpha_n).
591    fn friction_angle(&self) -> f64 {
592        (self.friction / self.pressure_angle.cos()).atan()
593    }
594
595    /// Driven by the worm: tan gamma / tan(gamma + rho').
596    pub fn efficiency(&self) -> f64 {
597        self.lead_angle.tan() / (self.lead_angle + self.friction_angle()).tan()
598    }
599
600    /// Driven by the wheel: tan(gamma - rho') / tan gamma; zero or less where the gear locks itself.
601    pub fn back_efficiency(&self) -> f64 {
602        (self.lead_angle - self.friction_angle()).tan() / self.lead_angle.tan()
603    }
604}
605
606/// A strain wave gear (Harmonic Drive's catalogue method). Config `[strain_wave]`: `rated_torque_nm` (Tr, at the rated
607/// input speed), `rated_input_speed_rpm` (nr, 2000 in the catalogues), `rated_life_h` (Ln: 7000 h for CSF, 10000 h for
608/// CSG). The life is L10 = Ln (Tr / Tav)^3 (nr / nav), Tav the cubic mean of the output torque weighted with the input
609/// speed and nav the mean input speed.
610#[derive(Debug, Clone, PartialEq)]
611pub struct StrainWave {
612    pub rated_torque: f64,
613    pub rated_speed: f64,
614    pub rated_life: f64,
615}
616
617impl StrainWave {
618    pub fn from_config(cfg: &Config) -> Result<Self> {
619        let p = |name: &str| cfg.positive(&format!("strain_wave.{name}"));
620        Ok(Self {
621            rated_torque: p("rated_torque_nm")?,
622            rated_speed: p("rated_input_speed_rpm")?,
623            rated_life: p("rated_life_h")?,
624        })
625    }
626
627    /// The share of the rated life used per hour at an output torque and input speed (r/min): |n| / nr (|T| / Tr)^3 / Ln.
628    pub fn damage_rate(&self, torque: f64, input_rpm: f64) -> f64 {
629        input_rpm.abs() / self.rated_speed * (torque.abs() / self.rated_torque).powi(3) / self.rated_life
630    }
631}
632
633/// The signals and rating checks of a ball screw on joint `id` (one of `chain::MOTOR_IDS`, its motor `motor`): screw
634/// speed (r/min), d n, and the share of its life used per hour, from the joint's speed and force (signal
635/// `joint.<id>.force`). Checks: "screw-speed" (against `allowed_speed_rpm`), "screw-dn" (where `max_dn` is set),
636/// "screw-buckling" (|force| against `allowed_buckling_force`; pulling too, on the safe side), "screw-static" (against
637/// `allowed_static_force`) and "screw-life" (against `required_life_h`, where set).
638impl BallScrew {
639    pub fn signal_infos(&self, id: &str, key: &'static str) -> Vec<SignalInfo> {
640        vec![
641            SignalInfo::new(format!("screw.{id}.speed"), key, "quantity-screw-speed", "rpm"),
642            SignalInfo::new(format!("screw.{id}.dn"), key, "quantity-screw-dn", "mm rpm"),
643            SignalInfo::new(format!("screw.{id}.damage_rate"), key, "quantity-damage-rate", "1/h"),
644        ]
645    }
646
647    /// Joint speed (m/s) and force (N) to the values of `signal_infos`.
648    pub fn signals(&self, speed: f64, force: f64, out: &mut Vec<f64>) {
649        let rpm = speed * self.ratio() * 60.0 / (2.0 * PI);
650        out.extend([rpm, self.dn(rpm), self.damage_rate(force, rpm)]);
651    }
652
653    pub fn rating_checks(&self, id: &str, motor: usize, required_life_h: Option<f64>) -> Vec<RatingCheck> {
654        let check = |check: &'static str, signal: &str, limit: f64, life: bool| RatingCheck {
655            check,
656            signal: signal.into(),
657            motor: Some(motor),
658            limit,
659            life,
660        };
661        let force = format!("joint.{id}.force");
662        let mut out = vec![
663            check("screw-speed", &format!("screw.{id}.speed"), self.allowed_speed_rpm(), false),
664            check("screw-buckling", &force, self.allowed_buckling_force(), false),
665            check("screw-static", &force, self.allowed_static_force(), false),
666        ];
667        if self.max_dn > 0.0 {
668            out.push(check("screw-dn", &format!("screw.{id}.dn"), self.max_dn, false));
669        }
670        if let Some(life) = required_life_h {
671            out.push(check("screw-life", &format!("screw.{id}.damage_rate"), life, true));
672        }
673        out
674    }
675}
676
677impl RackPinion {
678    pub fn signal_info(&self, id: &str, key: &'static str) -> SignalInfo {
679        SignalInfo::new(format!("rack.{id}.feed_force"), key, "quantity-rack-feed-force", "N")
680    }
681
682    /// The force on the teeth for the force `force` the rack passes to the load at `speed` and the efficiency
683    /// `efficiency` in effect (1 with effects.gearbox_efficiency off): more than it while the pinion drives, less while
684    /// the load drives it back.
685    pub fn feed_force(force: f64, speed: f64, efficiency: f64) -> f64 {
686        if force * speed >= 0.0 { force / efficiency } else { force * efficiency }
687    }
688
689    /// The radial load the pinion puts on the gearbox's output shaft for the force `tooth_force` on its teeth: the tooth
690    /// force itself, tangential to the pinion and so across the shaft, and the force that pushes pinion and rack apart,
691    /// F tan(alpha_n) / cos(beta), at right angles to it: |F| sqrt(1 + (tan(alpha_n) / cos(beta))^2). The axial force of
692    /// a helical pinion, F tan(beta), and the tilt it puts on the shaft are left out.
693    pub fn radial_load(&self, tooth_force: f64) -> f64 {
694        let apart = self.pressure_angle.tan() / self.helix_angle.cos();
695        tooth_force.abs() * (1.0 + apart * apart).sqrt()
696    }
697
698    /// "rack-feed-force": the force on the teeth of joint `id` (signal `rack.<id>.feed_force`) against `allowed_force`.
699    pub fn rating_checks(&self, id: &str, motor: usize) -> Vec<RatingCheck> {
700        vec![RatingCheck {
701            check: "rack-feed-force",
702            signal: format!("rack.{id}.feed_force"),
703            motor: Some(motor),
704            limit: self.allowed_force(),
705            life: false,
706        }]
707    }
708}
709
710/// The share of a strain wave gear's life used per hour on joint `id`, from its output torque and input speed (rad/s),
711/// and the check "strain-wave-life" against `required_life_h`.
712impl StrainWave {
713    pub fn signal_info(&self, id: &str, key: &'static str) -> SignalInfo {
714        SignalInfo::new(format!("strain_wave.{id}.damage_rate"), key, "quantity-damage-rate", "1/h")
715    }
716
717    pub fn signal(&self, torque: f64, input_speed: f64) -> f64 {
718        self.damage_rate(torque, input_speed * 60.0 / (2.0 * PI))
719    }
720
721    pub fn rating_check(&self, id: &str, motor: usize, required_life_h: f64) -> RatingCheck {
722        RatingCheck {
723            check: "strain-wave-life",
724            signal: format!("strain_wave.{id}.damage_rate"),
725            motor: Some(motor),
726            limit: required_life_h,
727            life: true,
728        }
729    }
730}
731
732#[cfg(test)]
733mod tests {
734    use super::*;
735
736    /// A winch: a gear of ratio 20 and 2e5 N m/rad (5 N m s/rad, efficiency 0.9, mesh friction on; rotor and input
737    /// 2e-4 kg m^2) behind a drum of 25 mm radius that weighs 0.32 kg at its radius. At the cable the gear is
738    /// 2e5 / 0.025^2 = 3.2e8 N/m and the rotor 2e-4 * 800^2 = 128 kg: capped by the rotor alone (`apply`) the bristle is
739    /// the full 3.2e8 N/m, by the drum (`apply_to`) 0.32 kg * (BRISTLE_RATE_MAX / 4)^2 = 2e8 N/m. Driven by a torque of
740    /// sin(2 pi 2 t) N m for a second at the base step's quarter (15.625 us, RK4), reversing four times, it stays
741    /// bounded, and its energy closes: the motor's work is the change of the rotor's, the drum's and the gear's energy and
742    /// the gear's loss (0.0636 J against 252 J that pass back and forth), to 1e-6 of the loss (seen: 4e-11 J).
743    #[test]
744    fn a_gear_at_the_bristle_cap_of_a_light_drum_stays_stable_and_closes_its_energy() {
745        let text = "format_version = 1\n[effects]\njoint_friction = false\nhard_stops = false\nmotor_friction = false\n\
746            torque_ripple = false\ngearbox_backlash = false\ngearbox_efficiency = true\ngearbox_drag = false\n\
747            motor_stiction = false\ngearbox_lost_motion = false\ngearbox_stiffness_curve = false\nthermal_feedback = false\n\
748            holding_brake = false\ngearbox_mesh_friction = true\n\
749            [motor]\nrotor_inertia_kgm2 = 1e-4\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\n\
750            friction_smoothing_rad_s = 1e-3\nfriction_breakaway_nm = 0.0\nfriction_stribeck_rad_s = 2.0\nripple_fraction = 0.0\n\
751            ripple_order = 6.0\ncogging_nm = 0.0\ncogging_order = 6.0\nbrake_torque_nm = 5.0\n\
752            [gearbox]\nratio = 20.0\nefficiency = 0.9\nbacklash_rad = 0.0\nstiffness_nm_rad = 2e5\ndamping_nm_s_rad = 5.0\n\
753            inertia_at_input_kgm2 = 1e-4\nefficiency_torque_nm = 100.0\nno_load_torque_nm = 0.0\nno_load_speed_rpm = 3000.0\n\
754            lost_motion_band_rad = 0.0\nhysteresis_rad = 0.0\nstiffness_t1_nm = 100.0\nstiffness_t2_nm = 100.0\n\
755            stiffness_k2_nm_rad = 2e5\nstiffness_k3_nm_rad = 2e5\n\
756            [joint]\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 1e-3\n\
757            min_angle_deg = -45.0\nmax_angle_deg = 90.0\nstop_stiffness_nm_rad = 1e5\nstop_damping_nm_s_rad = 0.0\n";
758        let cfg = Config::parse(text).unwrap();
759        let drum = Converter {
760            lever: 0.025,
761            stiffness: f64::INFINITY,
762            backlash: 0.0,
763            efficiency: 1.0,
764            inertia: 0.0,
765            damping_ratio: 0.0,
766        };
767        let mass = 0.32;
768        let joint = |output: f64| {
769            let mut j = RotaryJoint::from_config(&cfg).unwrap();
770            drum.apply_to(&cfg, &mut j, output).unwrap();
771            j
772        };
773        assert!((joint(f64::INFINITY).gearbox.mesh_stiffness / 3.2e8 - 1.0).abs() < 1e-12);
774        let mut j = joint(mass);
775        let cap = mass * (BRISTLE_RATE_MAX / 4.0).powi(2);
776        assert!((j.gearbox.mesh_stiffness / cap - 1.0).abs() < 1e-12 && (cap / 2e8 - 1.0).abs() < 1e-12);
777        let command = |t: f64| (std::f64::consts::TAU * 2.0 * t).sin();
778        let rates = |j: &RotaryJoint, s: [f64; 4], t: f64| {
779            let (gear, acc, _) = j.rotor(command(t), s[0], s[1], s[2], s[3], 0.0, false);
780            [s[1], acc, s[3], (gear.output + j.output_torque(s[2], s[3])) / mass]
781        };
782        let energy = |j: &RotaryJoint, s: [f64; 4]| {
783            0.5 * j.rotor_inertia * s[1] * s[1] + 0.5 * mass * s[3] * s[3] + j.gearbox.energy(s[0], s[2])
784        };
785        let power =
786            |j: &RotaryJoint, s: [f64; 4], t: f64| (command(t) * s[1], j.gearbox.loss_power(s[0], s[1], s[2], s[3]));
787        let (dt, mut s, mut t) = (15.625e-6, [0.0; 4], 0.0);
788        let (start, mut work, mut through, mut lost, mut peak) = (energy(&j, s), 0.0, 0.0, 0.0, 0.0f64);
789        for _ in 0..64000 {
790            let add = |s: [f64; 4], k: [f64; 4], h: f64| std::array::from_fn(|i| s[i] + h * k[i]);
791            let k1 = rates(&j, s, t);
792            let k2 = rates(&j, add(s, k1, 0.5 * dt), t + 0.5 * dt);
793            let k3 = rates(&j, add(s, k2, 0.5 * dt), t + 0.5 * dt);
794            let k4 = rates(&j, add(s, k3, dt), t + dt);
795            let (p0, l0) = power(&j, s, t);
796            s = std::array::from_fn(|i| s[i] + dt / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]));
797            t += dt;
798            let (p1, l1) = power(&j, s, t);
799            (work, through, lost) =
800                (work + 0.5 * dt * (p0 + p1), through + 0.5 * dt * (p0.abs() + p1.abs()), lost + 0.5 * dt * (l0 + l1));
801            j.gearbox.commit(s[0], s[2]);
802            peak = peak.max(s[3].abs());
803        }
804        let off = work - (energy(&j, s) - start) - lost;
805        println!(
806            "peak speed {peak:.4} m/s, work {work:.6} J, lost {lost:.6} J, off {off:.3e} J of {through:.6} J through"
807        );
808        assert!(s.iter().all(|x| x.is_finite()) && peak > 0.1 && peak < 2.0, "{s:?}, peak {peak} m/s");
809        assert!(lost > 0.0 && off.abs() < 1e-6 * lost, "off by {off} J, lost {lost} J of {through} J through");
810    }
811
812    fn screw() -> BallScrew {
813        BallScrew {
814            lead: 0.01,
815            nominal_diameter: 0.025,
816            root_diameter: 0.021,
817            length: 1.0,
818            mounting: Mounting::FixedSupported,
819            efficiency: 0.9,
820            back_efficiency: 0.9,
821            nut_stiffness: 5e8,
822            bearing_stiffness: 1e9,
823            preload: 500.0,
824            dynamic_rating: 15000.0,
825            static_rating: 30000.0,
826            load_factor: 1.2,
827            static_safety: 2.0,
828            speed_factor: 0.8,
829            buckling_safety: 2.0,
830            max_dn: 70000.0,
831            axial_damping_ratio: 0.0,
832            fixed_bearing_at: None,
833        }
834    }
835
836    fn close(a: f64, b: f64, what: &str) {
837        assert!((a / b - 1.0).abs() < 1e-4, "{what}: {a} against {b} by hand");
838    }
839
840    /// By hand, d = 21 mm, L = 1 m, steel E = 206 GPa, rho = 7850 kg/m^3:
841    /// I = pi 0.021^4 / 64 = 9.5466e-9 m^4, A = pi 0.021^2 / 4 = 3.4636e-4 m^2, sqrt(E I / (rho A)) = sqrt(206e9 9.5466e-9
842    /// / (7850 3.4636e-4)) = 26.894 m^2/s; fixed-supported (3.9266)^2 = 15.418: omega = 414.66 rad/s, 3959.7 r/min.
843    /// Buckling: 2.046 pi^2 206e9 9.5466e-9 / 1 = 39 711 N. Shaft inertia pi 7850 1 0.025^4 / 32 = 3.0104e-4 kg m^2.
844    /// Stiffness at 0.5 m: shaft A E / x = 1.4270e8 N/m; with 5e8 and 1e9 in series: 1 / (7.0077e-9 + 2e-9 + 1e-9) = 9.9923e7.
845    /// Preload drag: tan beta = 0.01 / (pi 0.025) = 0.12732, K = 0.05 / 0.35682 = 0.14013, 0.14013 500 0.01 / 2 pi = 0.11151 N m.
846    #[test]
847    fn a_ball_screw_has_the_hand_calculated_limits() {
848        let s = screw();
849        close(s.ratio(), 628.3185, "ratio");
850        close(s.critical_speed_rpm(), 3959.7, "critical speed");
851        close(s.allowed_speed_rpm(), 0.8 * 3959.7, "allowed speed");
852        close(s.buckling_load(), 39711.0, "buckling");
853        close(s.allowed_buckling_force(), 19855.5, "buckling allowed");
854        close(s.allowed_static_force(), 15000.0, "static");
855        close(s.inertia(), 3.0104e-4, "inertia");
856        close(s.stiffness(0.5), 9.9923e7, "stiffness");
857        close(s.preload_torque(), 0.11151, "preload drag");
858        close(s.dn(2000.0), 50000.0, "dn");
859    }
860
861    /// THK's rolling efficiency at mu = 0.003. The test screw: tan beta = 0.01 / (pi 0.025) = 0.127324,
862    /// (1 - 0.003 0.127324) / (1 + 0.003 / 0.127324) = 0.999618 / 1.023562 = 0.976607. The ISW bench's 40 x 40:
863    /// tan beta = 0.318310, 0.999045 / 1.009425 = 0.989717. From a config: the switch off keeps screw.efficiency to the
864    /// bit, on takes the lead's.
865    #[test]
866    fn the_screw_efficiency_follows_the_lead_angle_with_its_switch() {
867        close(BallScrew::lead_efficiency(0.01, 0.025, 0.003), 0.976607, "test screw");
868        close(BallScrew::lead_efficiency(0.04, 0.04, 0.003), 0.989717, "ISW screw");
869        let text = |on: bool| {
870            format!(
871                "format_version = 1\n[effects]\nscrew_lead_efficiency = {on}\n[screw]\nlead_m = 0.04\nnominal_diameter_m = 0.04\n\
872                 root_diameter_m = 0.0337\nlength_m = 1.8\nmounting = \"fixed-supported\"\nefficiency = 0.9\n\
873                 friction_coefficient = 0.003\nnut_stiffness_n_m = 5e8\nbearing_stiffness_n_m = 1e9\npreload_n = 500.0\n\
874                 dynamic_load_rating_n = 15000.0\nstatic_load_rating_n = 30000.0\nload_factor = 1.2\n\
875                 static_safety_factor = 2.0\ncritical_speed_factor = 0.8\nbuckling_safety_factor = 2.0\nmax_dn = 0.0\n"
876            )
877        };
878        let screw = |on| BallScrew::from_config(&Config::parse(&text(on)).unwrap()).unwrap();
879        assert_eq!(screw(false).efficiency, 0.9);
880        close(screw(true).efficiency, 0.989717, "from the config");
881    }
882
883    /// Preload 500 N lifts off at 1415 N. At 1000 N: 500 (1 + 1000 / 1415)^1.5 = 500 1.70671^1.5 = 1114.8 N; beyond, the
884    /// force itself. At 1000 r/min and 2000 N: 60 1000 (1.2 2000 / 15000)^3 / 1e6 = 2.4576e-4 per hour, 4069 h.
885    #[test]
886    fn the_screw_life_takes_preload_and_load_factor() {
887        let s = screw();
888        close(s.equivalent_load(1000.0), 1114.8, "preloaded");
889        close(s.equivalent_load(-2000.0), 2000.0, "lifted");
890        close(s.damage_rate(2000.0, -1000.0), 2.4576e-4, "damage");
891        assert_eq!(BallScrew { preload: 0.0, ..s }.equivalent_load(300.0), 300.0);
892    }
893
894    /// Module 2 mm, 30 teeth, 19.5283 degrees helix: r = 0.002 30 / (2 cos 19.5283) = 31.831 mm (100 mm travel per turn).
895    #[test]
896    fn a_helical_pinion_has_its_pitch_radius() {
897        let r = RackPinion {
898            module: 0.002,
899            teeth: 30.0,
900            helix_angle: 19.5283f64.to_radians(),
901            efficiency: 0.97,
902            stiffness: 1e8,
903            backlash: 0.0,
904            pinion_inertia: 1e-4,
905            rated_force: 3000.0,
906            service_factor: 1.5,
907            pressure_angle: 20f64.to_radians(),
908            damping_ratio: 0.0,
909        };
910        close(r.radius() * 2.0 * PI, 0.2, "travel per turn");
911        close(r.allowed_force(), 2000.0, "allowed force");
912    }
913
914    /// gamma 5 degrees, mu 0.05, alpha 20 degrees: rho' = atan(0.05 / 0.93969) = 3.0459 degrees; tan 5 / tan 8.0459 =
915    /// 0.087489 / 0.14136 = 0.61891; back tan 1.9541 / tan 5 = 0.034118 / 0.087489 = 0.38997. At 2 degrees the gear locks.
916    #[test]
917    fn a_worm_gear_has_the_hand_calculated_efficiencies() {
918        let w = WormGear { lead_angle: 5f64.to_radians(), friction: 0.05, pressure_angle: 20f64.to_radians() };
919        close(w.efficiency(), 0.61891, "forward");
920        close(w.back_efficiency(), 0.38997, "back");
921        assert!(WormGear { lead_angle: 2f64.to_radians(), ..w }.back_efficiency() < 0.0);
922    }
923
924    /// Tr 50 N m at 2000 r/min, Ln 7000 h: at 100 N m and 1000 r/min 0.5 8 / 7000 = 5.7143e-4 per hour (1750 h).
925    #[test]
926    fn a_strain_wave_gear_wears_by_the_cube_of_its_torque() {
927        let g = StrainWave { rated_torque: 50.0, rated_speed: 2000.0, rated_life: 7000.0 };
928        close(g.damage_rate(-100.0, 1000.0), 5.7143e-4, "damage");
929    }
930
931    #[test]
932    fn a_linear_motor_cogs_once_per_pole_pitch() {
933        close(LinearMotor { attraction: 0.0, pole_pitch: 0.024 }.cogging_order(), 261.799, "order");
934    }
935    /// At 0.5 m/s and 2000 N on the 10 mm lead: 3000 r/min, d n 25 * 3000 = 75000, 60 * 3000 * (1.2 * 2000 / 15000)^3 /
936    /// 1e6 = 7.3728e-4 per hour. The checks' limits are those of the hand-calculated test above; life only where
937    /// required, d n only where limited.
938    #[test]
939    fn the_screw_reports_and_checks_by_hand() {
940        let s = screw();
941        let mut out = Vec::new();
942        s.signals(0.5, 2000.0, &mut out);
943        close(out[0], 3000.0, "rpm");
944        close(out[1], 75000.0, "dn");
945        close(out[2], 7.3728e-4, "damage");
946        assert_eq!(
947            s.signal_infos("3", "joint-3").iter().map(|i| i.id.as_str()).collect::<Vec<_>>(),
948            ["screw.3.speed", "screw.3.dn", "screw.3.damage_rate"]
949        );
950        let checks = s.rating_checks("3", 2, Some(20000.0));
951        let limit =
952            |id: &str| checks.iter().find(|c| c.check == id).map(|c| (c.limit, c.signal.clone(), c.life, c.motor));
953        assert_eq!(limit("screw-life"), Some((20000.0, "screw.3.damage_rate".into(), true, Some(2))));
954        close(limit("screw-speed").unwrap().0, 0.8 * 3959.7, "speed limit");
955        close(limit("screw-buckling").unwrap().0, 19855.5, "buckling limit");
956        assert_eq!(limit("screw-static").unwrap().1, "joint.3.force");
957        assert_eq!(limit("screw-dn").unwrap().0, 70000.0);
958        let plain = BallScrew { max_dn: 0.0, ..s }.rating_checks("3", 2, None);
959        assert!(plain.iter().all(|c| c.check != "screw-dn" && c.check != "screw-life"));
960        for c in &checks {
961            assert_eq!(c.life, crate::analysis::AT_LEAST.contains(&c.check), "{}", c.check);
962        }
963    }
964
965    /// 100 N m at 1000 r/min in (104.72 rad/s): 5.7143e-4 per hour, as by the catalogue's formula above.
966    #[test]
967    fn the_strain_wave_gear_reports_its_wear_from_the_input_speed() {
968        let g = StrainWave { rated_torque: 50.0, rated_speed: 2000.0, rated_life: 7000.0 };
969        close(g.signal(100.0, 1000.0 * 2.0 * PI / 60.0), 5.7143e-4, "damage");
970        let c = g.rating_check("2", 1, 15000.0);
971        assert!(
972            c.life && c.check == "strain-wave-life" && c.signal == "strain_wave.2.damage_rate" && c.limit == 15000.0
973        );
974    }
975
976    #[test]
977    fn a_rack_is_checked_against_its_feed_force_over_the_service_factor() {
978        let r = RackPinion {
979            module: 0.002,
980            teeth: 30.0,
981            helix_angle: 0.0,
982            efficiency: 0.97,
983            stiffness: 1e8,
984            backlash: 0.0,
985            pinion_inertia: 1e-4,
986            rated_force: 3000.0,
987            service_factor: 1.25,
988            pressure_angle: 20f64.to_radians(),
989            damping_ratio: 0.0,
990        };
991        let c = &r.rating_checks("1", 0)[0];
992        assert!(c.check == "rack-feed-force" && c.signal == "rack.1.feed_force" && c.limit == 2400.0 && !c.life);
993        // 970 N to the load at 97 %: 1000 N on the teeth driving, 940.9 N braking.
994        close(RackPinion::feed_force(970.0, 1.0, 0.97), 1000.0, "driving");
995        close(RackPinion::feed_force(970.0, -1.0, 0.97), 940.9, "braking");
996        // Straight teeth: r = m z / 2 = 30 mm.
997        close(r.converter().lever, 0.03, "lever");
998    }
999
1000    /// THK's back-driving efficiency (1 - mu / tan beta) / (1 + mu tan beta) at mu = 0.003. The ISW bench (tan beta =
1001    /// 0.318310): 0.9905752 / 1.0009549 = 0.9896302 against 0.9897172 driving (8.7e-5 apart); at a lead angle of 7 degrees
1002    /// (tan beta = 0.122785): 0.975567 / 1.000368 = 0.975208 against 0.975790 (6e-4). tan beta = mu locks: 0.
1003    #[test]
1004    fn the_screw_driven_back_loses_by_thks_back_efficiency_and_a_locking_one_is_refused() {
1005        assert!((BallScrew::lead_back_efficiency(0.04, 0.04, 0.003) - 0.989_630_2).abs() < 1e-7);
1006        let lead7 = 7f64.to_radians().tan() * PI * 0.04;
1007        assert!((BallScrew::lead_efficiency(lead7, 0.04, 0.003) - 0.975_790_1).abs() < 1e-7);
1008        assert!((BallScrew::lead_back_efficiency(lead7, 0.04, 0.003) - 0.975_207_7).abs() < 1e-7);
1009        assert!(BallScrew::lead_back_efficiency(0.003 * PI * 0.04, 0.04, 0.003).abs() < 1e-12);
1010        let text = |mu: f64| {
1011            format!(
1012                "format_version = 1\n[effects]\nscrew_lead_efficiency = true\n[screw]\nlead_m = 0.04\nnominal_diameter_m = 0.04\n\
1013                 root_diameter_m = 0.0337\nlength_m = 1.8\nmounting = \"fixed-supported\"\nefficiency = 0.9\n\
1014                 friction_coefficient = {mu}\nnut_stiffness_n_m = 5e8\nbearing_stiffness_n_m = 1e9\npreload_n = 500.0\n\
1015                 dynamic_load_rating_n = 15000.0\nstatic_load_rating_n = 30000.0\nload_factor = 1.2\n\
1016                 static_safety_factor = 2.0\ncritical_speed_factor = 0.8\nbuckling_safety_factor = 2.0\nmax_dn = 0.0\n"
1017            )
1018        };
1019        let screw = BallScrew::from_config(&Config::parse(&text(0.003)).unwrap()).unwrap();
1020        assert!((screw.back_efficiency - 0.989_630_2).abs() < 1e-7);
1021        // mu 0.4 over tan beta 0.318: the screw holds its load.
1022        let err = BallScrew::from_config(&Config::parse(&text(0.4)).unwrap()).unwrap_err();
1023        assert!(format!("{err:?}").contains("locks itself"), "{err:?}");
1024    }
1025
1026    /// The test gearbox of the winch (efficiency 0.9, mesh friction off), behind a converter of efficiency 0.95 that loses
1027    /// 0.9 driven back: driving it loses 0.9 x 0.95 = 0.855, driven back the gear's own 1 / 0.9 and the converter's
1028    /// 1 / 0.9: 1 / 0.81 = 1.234568 (a gear that loses alike both ways would give 1 / 0.855 = 1.169591), and the loss power
1029    /// of a steady twist of 100 N m at 2 m/s backwards is 200 (1 / 0.81 - 1) = 46.9136 W against 200 (1 / 0.855 - 1) =
1030    /// 33.9181 W alike, whatever the rotor's side of the budget (`Gearbox::loss_power`).
1031    #[test]
1032    fn a_converter_with_its_own_back_efficiency_loses_so_driven_back_and_the_budget_has_it() {
1033        let text = "format_version = 1\n[effects]\njoint_friction = false\nhard_stops = false\nmotor_friction = false\n\
1034            torque_ripple = false\ngearbox_backlash = false\ngearbox_efficiency = true\ngearbox_drag = false\n\
1035            motor_stiction = false\ngearbox_lost_motion = false\ngearbox_stiffness_curve = false\nthermal_feedback = false\n\
1036            holding_brake = false\ngearbox_mesh_friction = false\n\
1037            [motor]\nrotor_inertia_kgm2 = 1e-4\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\n\
1038            friction_smoothing_rad_s = 1e-3\nfriction_breakaway_nm = 0.0\nfriction_stribeck_rad_s = 2.0\nripple_fraction = 0.0\n\
1039            ripple_order = 6.0\ncogging_nm = 0.0\ncogging_order = 6.0\nbrake_torque_nm = 5.0\n\
1040            [gearbox]\nratio = 20.0\nefficiency = 0.9\nbacklash_rad = 0.0\nstiffness_nm_rad = 2e5\ndamping_nm_s_rad = 5.0\n\
1041            inertia_at_input_kgm2 = 1e-4\nefficiency_torque_nm = 100.0\nno_load_torque_nm = 0.0\nno_load_speed_rpm = 3000.0\n\
1042            lost_motion_band_rad = 0.0\nhysteresis_rad = 0.0\nstiffness_t1_nm = 100.0\nstiffness_t2_nm = 100.0\n\
1043            stiffness_k2_nm_rad = 2e5\nstiffness_k3_nm_rad = 2e5\n\
1044            [joint]\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 1e-3\n\
1045            min_angle_deg = -45.0\nmax_angle_deg = 90.0\nstop_stiffness_nm_rad = 1e5\nstop_damping_nm_s_rad = 0.0\n";
1046        let cfg = Config::parse(text).unwrap();
1047        let converter = Converter {
1048            lever: 1.0,
1049            stiffness: f64::INFINITY,
1050            backlash: 0.0,
1051            efficiency: 0.95,
1052            inertia: 0.0,
1053            damping_ratio: 0.0,
1054        };
1055        let make = |back: f64| {
1056            let mut j = RotaryJoint::from_config(&cfg).unwrap();
1057            converter.apply_back(&cfg, &mut j, f64::INFINITY, back).unwrap();
1058            j.gearbox
1059        };
1060        let (own, alike) = (make(0.9), make(0.95));
1061        assert!(
1062            (own.loss_factor(1.0, 1e3) - 0.855).abs() < 1e-12 && (alike.loss_factor(1.0, 1e3) - 0.855).abs() < 1e-12
1063        );
1064        assert!((own.loss_factor(1.0, -1e3) - 1.0 / 0.81).abs() < 1e-12, "{}", own.loss_factor(1.0, -1e3));
1065        assert!((alike.loss_factor(1.0, -1e3) - 1.0 / 0.855).abs() < 1e-12);
1066        // A twist of 0.0005 rad at 2e5 N m/rad holds 100 N m at the output; the output runs back at 2 rad/s, the rotor with
1067        // it (twist constant).
1068        let (ratio, out) = (own.ratio, -0.3);
1069        let loss = |g: &crate::mech::Gearbox| g.loss_power(ratio * (out + 5e-4), -2.0 * ratio, out, -2.0);
1070        assert!((loss(&own) - 200.0 * (1.0 / 0.81 - 1.0)).abs() < 1e-6, "{}", loss(&own));
1071        assert!((loss(&alike) - 200.0 * (1.0 / 0.855 - 1.0)).abs() < 1e-6, "{}", loss(&alike));
1072    }
1073
1074    /// The hysteresis loop's and the mesh friction's presliding stiffness are factors on K1, 1 where the key is absent
1075    /// (the mesh one with the converted stiffness, as the K1 itself: 2e5 / 0.025^2 = 3.2e8 N/m behind the drum).
1076    /// `hysteresis_stiffness_factor = 3`: 3 x 3.2e8 = 9.6e8 N/m; `mesh_stiffness_factor = 0.5`: 1.6e8 N/m.
1077    #[test]
1078    fn the_presliding_stiffnesses_are_factors_on_k1_that_default_to_one() {
1079        let base = "format_version = 1\n[effects]\njoint_friction = false\nhard_stops = false\nmotor_friction = false\n\
1080            torque_ripple = false\ngearbox_backlash = false\ngearbox_efficiency = true\ngearbox_drag = false\n\
1081            motor_stiction = false\ngearbox_lost_motion = false\ngearbox_stiffness_curve = false\nthermal_feedback = false\n\
1082            holding_brake = false\ngearbox_mesh_friction = true\n\
1083            [motor]\nrotor_inertia_kgm2 = 1e-4\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\n\
1084            friction_smoothing_rad_s = 1e-3\nfriction_breakaway_nm = 0.0\nfriction_stribeck_rad_s = 2.0\nripple_fraction = 0.0\n\
1085            ripple_order = 6.0\ncogging_nm = 0.0\ncogging_order = 6.0\nbrake_torque_nm = 5.0\n\
1086            [gearbox]\nratio = 20.0\nefficiency = 0.9\nbacklash_rad = 0.0\nstiffness_nm_rad = 2e5\ndamping_nm_s_rad = 5.0\n\
1087            inertia_at_input_kgm2 = 1e-4\nefficiency_torque_nm = 100.0\nno_load_torque_nm = 0.0\nno_load_speed_rpm = 3000.0\n\
1088            lost_motion_band_rad = 0.0\nhysteresis_rad = 0.0\nstiffness_t1_nm = 100.0\nstiffness_t2_nm = 100.0\n\
1089            stiffness_k2_nm_rad = 2e5\nstiffness_k3_nm_rad = 2e5\n{extra}\
1090            [joint]\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 1e-3\n\
1091            min_angle_deg = -45.0\nmax_angle_deg = 90.0\nstop_stiffness_nm_rad = 1e5\nstop_damping_nm_s_rad = 0.0\n";
1092        let drum = Converter {
1093            lever: 0.025,
1094            stiffness: f64::INFINITY,
1095            backlash: 0.0,
1096            efficiency: 1.0,
1097            inertia: 0.0,
1098            damping_ratio: 0.0,
1099        };
1100        let make = |extra: &str| {
1101            let cfg = Config::parse(&base.replace("{extra}", extra)).unwrap();
1102            let mut j = RotaryJoint::from_config(&cfg).unwrap();
1103            drum.apply(&cfg, &mut j).unwrap();
1104            j.gearbox
1105        };
1106        let plain = make("");
1107        assert!(
1108            (plain.dahl_stiffness / 3.2e8 - 1.0).abs() < 1e-12 && (plain.mesh_stiffness / 3.2e8 - 1.0).abs() < 1e-12
1109        );
1110        let set = make("hysteresis_stiffness_factor = 3.0\nmesh_stiffness_factor = 0.5\n");
1111        assert!((set.dahl_stiffness / 9.6e8 - 1.0).abs() < 1e-12, "{}", set.dahl_stiffness);
1112        assert!((set.mesh_stiffness / 1.6e8 - 1.0).abs() < 1e-12, "{}", set.mesh_stiffness);
1113    }
1114
1115    /// The gear behind a converter is the gear and the converter's spring in series, band and hysteresis too. K1 = 2e5
1116    /// N m/rad behind a lever of 0.025 m/rad (3.2e8 N/m) and a spring of 5e7 N/m: K1' = 1 / (3.125e-9 + 2e-8) =
1117    /// 4.324324e7 N/m. A band of 1e-4 rad: the flanks leave it at T_b = 10 N m (400 N); at 100 N (2.5 N m) they twist
1118    /// sqrt(2 x 1e-4 x 2.5 / 2e5) = 5e-5 rad = 1.25e-6 m and the spring 2e-6 m: 3.25e-6 m; at 800 N (20 N m) 1e-4 +
1119    /// 5e-5 rad = 3.75e-6 m and 1.6e-5 m: 1.975e-5 m, an offset of the line of 1.25e-6 m, the gear's 5e-5 rad x lever.
1120    /// hysteresis_rad 2e-4: T_h = 20 N m; sliding, the force at the joint is K1' (x -+ lever T_h / K1), so the friction
1121    /// is 4.324324e7 x 0.025 x 20 / 2e5 = 108.108 N (not 20 / 0.025 = 800 N), and the loop at zero force 2 x 108.108 /
1122    /// K1' = 5e-6 m wide, the gear's 2 T_h / K1 x lever; sigma' = series(4e5) - K1' = 1 / (1.5625e-9 + 2e-8) - K1' =
1123    /// 3.133595e6 N/m. No band, none.
1124    #[test]
1125    fn the_gear_behind_a_converter_is_in_series_with_its_spring_over_the_band_and_the_hysteresis() {
1126        let text = "format_version = 1\n[effects]\njoint_friction = false\nhard_stops = false\nmotor_friction = false\n\
1127            torque_ripple = false\ngearbox_backlash = false\ngearbox_efficiency = false\ngearbox_drag = false\n\
1128            motor_stiction = false\ngearbox_lost_motion = true\ngearbox_stiffness_curve = false\nthermal_feedback = false\n\
1129            holding_brake = false\ngearbox_mesh_friction = false\n\
1130            [motor]\nrotor_inertia_kgm2 = 1e-4\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\n\
1131            friction_smoothing_rad_s = 1e-3\nfriction_breakaway_nm = 0.0\nfriction_stribeck_rad_s = 2.0\nripple_fraction = 0.0\n\
1132            ripple_order = 6.0\ncogging_nm = 0.0\ncogging_order = 6.0\nbrake_torque_nm = 5.0\n\
1133            [gearbox]\nratio = 20.0\nefficiency = 0.9\nbacklash_rad = 0.0\nstiffness_nm_rad = 2e5\ndamping_nm_s_rad = 5.0\n\
1134            inertia_at_input_kgm2 = 1e-4\nefficiency_torque_nm = 100.0\nno_load_torque_nm = 0.0\nno_load_speed_rpm = 3000.0\n\
1135            lost_motion_band_rad = BAND\nhysteresis_rad = 2e-4\nstiffness_t1_nm = 100.0\nstiffness_t2_nm = 100.0\n\
1136            stiffness_k2_nm_rad = 2e5\nstiffness_k3_nm_rad = 2e5\n\
1137            [joint]\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 1e-3\n\
1138            min_angle_deg = -45.0\nmax_angle_deg = 90.0\nstop_stiffness_nm_rad = 1e5\nstop_damping_nm_s_rad = 0.0\n";
1139        let screw = Converter {
1140            lever: 0.025,
1141            stiffness: 5e7,
1142            backlash: 0.0,
1143            efficiency: 1.0,
1144            inertia: 0.0,
1145            damping_ratio: 0.0,
1146        };
1147        let gear = |b: &str| {
1148            let cfg = Config::parse(&text.replace("BAND", b)).unwrap();
1149            let mut j = RotaryJoint::from_config(&cfg).unwrap();
1150            screw.apply(&cfg, &mut j).unwrap();
1151            j.gearbox
1152        };
1153        let g = gear("1e-4");
1154        let rel = |a: f64, b: f64| (a / b - 1.0).abs() < 1e-12;
1155        assert!(rel(g.stiffness, 1.0 / 2.3125e-8) && rel(g.band, 2.5e-6), "{} {}", g.stiffness, g.band);
1156        for (force, twist) in [(100.0, 3.25e-6), (400.0, 2.5e-6 + 8e-6), (800.0, 1.975e-5)] {
1157            assert!(rel(g.static_twist(force), twist), "{force}: {}", g.static_twist(force));
1158            assert!(rel(g.spring(twist).0, force), "{twist}: {}", g.spring(twist).0);
1159        }
1160        assert!(rel(g.hysteresis, 108.108_108_108_108_1) && rel(2.0 * g.hysteresis / g.stiffness, 5e-6));
1161        assert!(rel(g.dahl_stiffness, 1.0 / 2.15625e-8 - 1.0 / 2.3125e-8), "{}", g.dahl_stiffness);
1162        assert_eq!(gear("0.0").band, 0.0);
1163    }
1164
1165    /// The gear's damper bridges its own spring, not the converter's (a Zener solid, `Gearbox::arm`). A gear of
1166    /// K1 = 100 N m/rad and 0.2828 N m s/rad behind a lever of 0.01 m/rad is K_g = 1e6 N/m and c = 2828 N s/m at the
1167    /// joint, a converter of K_c = 1e6 N/m in series: K_s = 5e5 N/m at rest (the arm then carries nothing). A mass of
1168    /// 1 kg on it, the rotor held, rings as the roots of m c s^3 + m (K_c + K_g) s^2 + K_c c s + K_c K_g = 0 say:
1169    /// s = -152.099260 +- 924.266861i and -403.015059 (numpy.roots), so successive peaks fall by
1170    /// exp(-2 pi 152.099260 / 924.266861) = 0.355591 (log decrement 1.033974), the real root's share gone after a few
1171    /// periods. With the damper across the whole series spring (as the converter had it) zeta would be
1172    /// 2828 / (2 sqrt(5e5)) = 2.0: no ring at all. The energy closes: the mass's and the springs' (the arm's with them)
1173    /// and the arm's damper's loss stay the start's. Without damping, or behind a rigid converter, there is no arm and
1174    /// the damping stays as it was, c / lever^2 across the spring; an arm faster than the integrator is its slow limit.
1175    ///
1176    /// With the screw's own damper too, zeta = 0.04 on the 1 kg: c_c = 2 x 0.04 sqrt(1e6 x 1) = 80 N s/m across K_c
1177    /// alone. The pair's m C s^3 + (m S + c_g c_c) s^2 + (K_g c_c + K_c c_g) s + K_g K_c = 0 (S = K_g + K_c, C = c_g +
1178    /// c_c) has s = -181.415607 +- 906.072216i: peaks fall by 0.284213; b = c_g c_c / C = 77.799175 N s/m beside the
1179    /// arm's K_m = (K_g c_c - K_c c_g)^2 / (S C^2) = 446493.00 N/m and tau = C / S = 1.454 ms. Behind a near-rigid gear
1180    /// (K1 = 1e8 N m/rad, no damper) the screw's own mode keeps its 0.04.
1181    #[test]
1182    fn the_gear_damper_behind_a_converter_bridges_the_gear_alone() {
1183        let text = "format_version = 1\n[effects]\njoint_friction = false\nhard_stops = false\nmotor_friction = false\n\
1184            torque_ripple = false\ngearbox_backlash = false\ngearbox_efficiency = false\ngearbox_drag = false\n\
1185            motor_stiction = false\ngearbox_lost_motion = false\ngearbox_stiffness_curve = false\nthermal_feedback = false\n\
1186            holding_brake = false\ngearbox_mesh_friction = false\n\
1187            [motor]\nrotor_inertia_kgm2 = 1e-4\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\n\
1188            friction_smoothing_rad_s = 1e-3\nfriction_breakaway_nm = 0.0\nfriction_stribeck_rad_s = 2.0\nripple_fraction = 0.0\n\
1189            ripple_order = 6.0\ncogging_nm = 0.0\ncogging_order = 6.0\nbrake_torque_nm = 5.0\n\
1190            [gearbox]\nratio = 1.0\nefficiency = 0.9\nbacklash_rad = 0.0\nstiffness_nm_rad = K1\ndamping_nm_s_rad = DAMPING\n\
1191            inertia_at_input_kgm2 = 1e-4\nefficiency_torque_nm = 100.0\nno_load_torque_nm = 0.0\nno_load_speed_rpm = 3000.0\n\
1192            lost_motion_band_rad = 0.0\nhysteresis_rad = 0.0\nstiffness_t1_nm = 100.0\nstiffness_t2_nm = 100.0\n\
1193            stiffness_k2_nm_rad = 100.0\nstiffness_k3_nm_rad = 100.0\n\
1194            [joint]\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 1e-3\n\
1195            min_angle_deg = -45.0\nmax_angle_deg = 90.0\nstop_stiffness_nm_rad = 1e5\nstop_damping_nm_s_rad = 0.0\n";
1196        let geared = |k1: &str, damping: &str, stiffness: f64, damping_ratio: f64| {
1197            let cfg = Config::parse(&text.replace("K1", k1).replace("DAMPING", damping)).unwrap();
1198            let mut j = RotaryJoint::from_config(&cfg).unwrap();
1199            let converter =
1200                Converter { lever: 0.01, stiffness, backlash: 0.0, efficiency: 1.0, inertia: 0.0, damping_ratio };
1201            converter.apply_to(&cfg, &mut j, 1.0).unwrap();
1202            j.gearbox
1203        };
1204        let gear = |damping: &str, stiffness: f64| geared("100.0", damping, stiffness, 0.0);
1205        let rel = |a: f64, b: f64, tol: f64| (a / b - 1.0).abs() < tol;
1206        // The limits: no damping, no arm (the series spring alone); a rigid converter, the damper across the gear.
1207        let plain = gear("0.0", 1e6);
1208        assert!(plain.relax_stiffness == 0.0 && plain.damping == 0.0 && rel(plain.stiffness, 5e5, 1e-12));
1209        let rigid = gear("0.2828", f64::INFINITY);
1210        assert!(rigid.relax_stiffness == 0.0 && rel(rigid.damping, 2828.0, 1e-12) && rel(rigid.stiffness, 1e6, 1e-12));
1211        // 0.001 N m s/rad, c = 10 N s/m: tau = 10 / 2e6 = 5 us, faster than the integrator follows; its slow limit is
1212        // a damper of c (K_c / (K_c + K_g))^2 = 2.5 N s/m across the series spring.
1213        let fast = gear("0.001", 1e6);
1214        assert!(fast.relax_stiffness == 0.0 && rel(fast.damping, 2.5, 1e-12), "{}", fast.damping);
1215        let g = gear("0.2828", 1e6);
1216        assert_eq!(g.damping, 0.0);
1217        assert!(rel(g.relax_stiffness, 5e5, 1e-12) && rel(g.relax_time, 1.414e-3, 1e-12));
1218        // At rest, the series stiffness: the arm relaxed carries nothing.
1219        let x = 1e-3;
1220        assert!(rel(g.static_twist(500.0), 1e-3, 1e-12));
1221        assert!(rel(g.torque_with(0.0, 0.0, -x, 0.0, g.arm_rest(0.0, -x)).output, 500.0, 1e-12));
1222        // Free decay from there, the rotor held: state [out, speed, arm]. The fall of the peaks after the real root's
1223        // share is gone, and what the energy misses.
1224        let decay = |g: &crate::mech::Gearbox| {
1225            let (mass, dt) = (1.0, 1e-6);
1226            let rates = |s: [f64; 3]| {
1227                let force = g.torque_with(0.0, 0.0, s[0], s[1], s[2]).output;
1228                [s[1], force / mass, g.arm(0.0, s[0], s[2]).1]
1229            };
1230            let energy = |s: [f64; 3]| 0.5 * mass * s[1] * s[1] + g.energy_with(0.0, s[0], s[2]);
1231            let u0 = g.arm_rest(0.0, -x);
1232            let (mut s, mut lost, start) = ([-x, 0.0, u0], 0.0, energy([-x, 0.0, u0]));
1233            let mut peaks = Vec::new();
1234            for _ in 0..80000 {
1235                let add = |s: [f64; 3], k: [f64; 3], h: f64| std::array::from_fn(|i| s[i] + h * k[i]);
1236                let k1 = rates(s);
1237                let k2 = rates(add(s, k1, 0.5 * dt));
1238                let k3 = rates(add(s, k2, 0.5 * dt));
1239                let k4 = rates(add(s, k3, dt));
1240                let l0 = g.loss_power_with(0.0, 0.0, s[0], s[1], s[2]);
1241                let next: [f64; 3] =
1242                    std::array::from_fn(|i| s[i] + dt / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]));
1243                lost += 0.5 * dt * (l0 + g.loss_power_with(0.0, 0.0, next[0], next[1], next[2]));
1244                if s[1] > 0.0 && next[1] <= 0.0 {
1245                    peaks.push(next[0]);
1246                }
1247                s = next;
1248            }
1249            assert!(peaks.len() >= 10, "{}", peaks.len());
1250            println!("peaks {peaks:?}");
1251            (peaks[8] / peaks[7], (start - energy(s) - lost) / start)
1252        };
1253        let (fall, off) = decay(&g);
1254        assert!(rel(fall, 0.355591, 2e-5) && off.abs() < 1e-9, "{fall} {off}");
1255        let both = geared("100.0", "0.2828", 1e6, 0.04);
1256        assert!(rel(both.damping, 77.799175, 1e-7) && rel(both.relax_stiffness, 446493.00, 1e-7), "{both:?}");
1257        assert!(rel(both.relax_time, 1.454e-3, 1e-12));
1258        let (fall, off) = decay(&both);
1259        assert!(rel(fall, 0.284213, 2e-5) && off.abs() < 1e-9, "{fall} {off}");
1260        let screw = geared("1e8", "0.0", 1e6, 0.04);
1261        let zeta = screw.damping_at(0.0) / (2.0 * screw.stiffness.sqrt());
1262        assert!(screw.relax_stiffness == 0.0 && rel(zeta, 0.04, 1e-5), "{zeta}");
1263        // The modes' damping at the ring: K_m tau / (1 + (w tau)^2) at w = sqrt(K_s / m).
1264        let w = 5e5f64.sqrt();
1265        assert!(rel(g.damping_at(w), 5e5 * 1.414e-3 / (1.0 + (w * 1.414e-3).powi(2)), 1e-12));
1266        // Along the stroke (effects.screw_stiffness_with_position) the screw's damper keeps its ratio: a shaft of
1267        // E A = 1e6 N (fixed-free over 1 m, the bearing at 0) built at its far end, K_c = 1e6 N/m, is 4e6, 2e6 and
1268        // 1.333e6 N/m with the nut at 0.25, 0.5 and 0.75; the 1 kg behind it, the rotor held, rings with zeta = 0.04
1269        // at each, where the far end's damper held gave 0.04 sqrt(K_c / K): 0.02, 0.0283, 0.0346.
1270        let along = |k1: &str, damping: &str| {
1271            let cfg = Config::parse(&text.replace("K1", k1).replace("DAMPING", damping)).unwrap();
1272            let mut j = RotaryJoint::from_config(&cfg).unwrap();
1273            let travel = TravelCompliance {
1274                ae: 1e6,
1275                length: 1.0,
1276                both_ends: false,
1277                fixed_bearing_at: 0.0,
1278                reference: 1e-6,
1279                gear: [0.0; 2],
1280                converter: [0.0; 2],
1281            };
1282            let converter = Converter {
1283                lever: 0.01,
1284                stiffness: 1e6,
1285                backlash: 0.0,
1286                efficiency: 1.0,
1287                inertia: 0.0,
1288                damping_ratio: 0.04,
1289            };
1290            BackDriven { converter, back_efficiency: 1.0, travel: Some(travel) }.apply_to(&cfg, &mut j, 1.0).unwrap();
1291            j.gearbox
1292        };
1293        let screw = along("1e8", "0.0");
1294        for (q, k) in [(0.25, 4e6), (0.5, 2e6), (0.75, 1e6 / 0.75), (1.0, 1e6)] {
1295            let g = screw.at(q);
1296            let w = g.stiffness.sqrt();
1297            let zeta = g.damping_at(w) * w / (2.0 * g.stiffness);
1298            assert!(rel(g.stiffness, k, 1e-5) && rel(zeta, 0.04, 1e-5), "{q}: {} {zeta}", g.stiffness);
1299        }
1300        // A gear of 1e6 N/m with its damper too keeps the arm (tau 1.45e-3 s); laid out at the far end it is the build's.
1301        let both = along("100.0", "0.2828");
1302        let [b, arm, tau, _] = both.travel.unwrap().dampers(0.0).unwrap();
1303        assert!(both.relax_stiffness > 0.0 && rel(arm, both.relax_stiffness, 1e-12), "{both:?}");
1304        assert!(rel(b, both.damping, 1e-12) && rel(tau, both.relax_time, 1e-12));
1305    }
1306
1307    /// The screw's stiffness is judged at the softest nut position: the far end of a fixed-supported shaft (1 m):
1308    /// A E / x with A E = 7.1350e7 N, in series with 5e8 and 1e9 N/m: 1 / (1.4015e-8 + 2e-9 + 1e-9) = 5.8770e7 N/m; the
1309    /// middle of a fixed-fixed one: A E L / (x (L - x)) = 2.8540e8 N/m, 1 / (3.5037e-9 + 3e-9) = 1.5376e8 N/m, which is
1310    /// the least of the stroke there (the ends are stiffer).
1311    #[test]
1312    fn the_screw_converter_takes_the_softest_position_of_either_bearing_arrangement() {
1313        let free = screw();
1314        assert_eq!(free.softest_position(), 1.0);
1315        close(free.converter(free.softest_position()).stiffness, 5.8770e7, "fixed-supported far end");
1316        assert!((0..=100).all(|i| free.stiffness(0.01 * i as f64) >= free.stiffness(1.0) * (1.0 - 1e-12)));
1317        let fixed = BallScrew { mounting: Mounting::FixedFixed, ..screw() };
1318        assert_eq!(fixed.softest_position(), 0.5);
1319        close(fixed.converter(fixed.softest_position()).stiffness, 1.5376e8, "fixed-fixed middle");
1320        assert!((1..100).all(|i| fixed.stiffness(0.01 * i as f64) >= fixed.stiffness(0.5) * (1.0 - 1e-12)));
1321    }
1322
1323    /// With the stiffness following the nut (`travel`), the shaft's compliance along the travel is the one `stiffness`
1324    /// puts in series, for either bearing arrangement: with the fixed bearing at travel -0.1, the nut 0.25 from it at
1325    /// 0.15 has 1 / stiffness(0.25) - 1 / stiffness(1) more than the far end (fixed-supported: 0.25 / A E - 1 / A E =
1326    /// -1.0512e-8 m/N), and its slope is 1 / A E = 1.4015e-8 m/N per m. The switch and `fixed_bearing_at_m` from a
1327    /// config; without the switch there is none.
1328    #[test]
1329    fn the_screw_compliance_along_the_travel_is_the_stiffness_at_the_nut() {
1330        for mounting in [Mounting::FixedSupported, Mounting::FixedFixed] {
1331            let s = BallScrew { mounting, fixed_bearing_at: Some(-0.1), ..screw() };
1332            let t = s.travel(s.softest_position()).unwrap();
1333            for x in [0.05, 0.25, 0.5, 0.9] {
1334                let by_stiffness = 1.0 / s.stiffness(x) - 1.0 / s.stiffness(s.softest_position());
1335                assert!((t.delta(x - 0.1).0 - by_stiffness).abs() < 1e-20, "{mounting:?} at {x}");
1336                let h = 1e-6;
1337                let slope = (t.delta(x - 0.1 + h).0 - t.delta(x - 0.1 - h).0) / (2.0 * h);
1338                assert!((t.delta(x - 0.1).1 - slope).abs() < 1e-14, "{mounting:?} slope at {x}");
1339            }
1340        }
1341        let t = BallScrew { fixed_bearing_at: Some(-0.1), ..screw() }.travel(1.0).unwrap();
1342        close(t.delta(0.15).0, -1.0512e-8, "compliance less the far end's");
1343        close(t.delta(0.15).1, 1.4015e-8, "slope");
1344        assert!(screw().converter(1.0).travel.is_none());
1345        let text = |on: bool| {
1346            format!(
1347                "format_version = 1\n[effects]\nscrew_stiffness_with_position = {on}\n[screw]\nlead_m = 0.01\n\
1348                 nominal_diameter_m = 0.025\nroot_diameter_m = 0.021\nlength_m = 1.0\nmounting = \"fixed-supported\"\n\
1349                 efficiency = 0.9\nnut_stiffness_n_m = 5e8\nbearing_stiffness_n_m = 1e9\npreload_n = 0.0\n\
1350                 dynamic_load_rating_n = 1e4\nstatic_load_rating_n = 2e4\nload_factor = 1.2\nstatic_safety_factor = 2.0\n\
1351                 critical_speed_factor = 0.8\nbuckling_safety_factor = 2.0\nmax_dn = 0.0\nfixed_bearing_at_m = -0.1\n"
1352            )
1353        };
1354        let read = |on| BallScrew::from_config(&Config::parse(&text(on)).unwrap()).unwrap().fixed_bearing_at;
1355        assert_eq!((read(true), read(false)), (Some(-0.1), None));
1356    }
1357
1358    /// The pressure angle of the teeth: the force pushing pinion and rack apart is F tan(alpha) (straight teeth), the
1359    /// radial load F / cos(alpha): 1000 N gives 1064.18 N at the default 20 degrees (as before) and 1103.38 N at 25.
1360    #[test]
1361    fn the_racks_pressure_angle_is_a_key_that_defaults_to_twenty_degrees() {
1362        let text = |extra: &str| {
1363            format!(
1364                "format_version = 1\n[rack]\nmodule_m = 0.002\nteeth = 30.0\nhelix_angle_deg = 0.0\nefficiency = 0.97\n\
1365                 stiffness_n_m = 1e8\nbacklash_m = 0.0\npinion_inertia_kgm2 = 1e-4\nrated_feed_force_n = 3000.0\n\
1366                 service_factor = 1.5\n{extra}"
1367            )
1368        };
1369        let rack = |extra: &str| RackPinion::from_config(&Config::parse(&text(extra)).unwrap()).unwrap();
1370        close(rack("").radial_load(1000.0), 1064.18, "default 20 degrees");
1371        close(rack("pressure_angle_deg = 25.0\n").radial_load(-1000.0), 1103.38, "25 degrees");
1372        assert!(RackPinion::from_config(&Config::parse(&text("pressure_angle_deg = 60.0\n")).unwrap()).is_err());
1373    }
1374}