sim_components/mech.rs
1//! Mechanical components: belt, guide friction, shaft friction, gearbox, torque ripple, tooth meshing, hard stops,
2//! cable chain, holding brake.
3//! Each reads its own parameters and its own switch from the config and knows no machine.
4
5use sim_core::{Config, ConfigError};
6
7type Result<T> = std::result::Result<T, ConfigError>;
8
9/// The hand-set factor of effects.temperature. With effects.thermal_feedback it is not used: the temperatures then
10/// come from `ThermalFeedback`.
11fn temperature_scale(cfg: &Config, leaf: &str) -> Result<f64> {
12 Ok(if cfg.bool("effects.temperature")? && !cfg.bool("effects.thermal_feedback")? {
13 cfg.positive(&format!("temperature.{leaf}"))?
14 } else {
15 1.0
16 })
17}
18
19// ---------------------------------------------------------------------------------------------
20// Temperature feedback
21
22const KELVIN: f64 = 273.15;
23
24/// With effects.thermal_feedback: what the temperatures of the parts do to friction, gearbox losses and belt
25/// stiffness. The config's values hold at `reference` (gearbox makers quote their no-load torque at 20 °C); the
26/// machine stands in air at `ambient`, and a part is at ambient plus its rise (effects.part_heating; without it the
27/// rises stay 0).
28///
29/// - Lubricant viscosity (Arrhenius/Andrade): nu(T) / nu_ref = exp(B (1/T - 1/T_ref)), T in K. A mineral oil of
30/// viscosity index about 100 has B = 3470 K (ISO VG 32: 32 and 5.4 mm²/s at 40 and 100 °C) to 4730 K (VG 220:
31/// 220 and 19.4 mm²/s); VG 68 (68 and 8.7) gives 4000 K.
32/// - Guide: its viscous coefficient follows the viscosity; Coulomb and stiction levels (rolling contact, seals)
33/// stay as they are.
34/// - Gearbox: a share s of its loss (1 - eta_ref) is churning and bearing drag, which follows the viscosity; the
35/// rest, tooth friction, does not: 1 - eta = (1 - eta_ref) (1 - s + s nu / nu_ref).
36/// - Gearbox with effects.gearbox_drag: its churning and bearing drag is the no-load running torque (`GearDrag`),
37/// which follows the viscosity by its own law; the efficiency then is the teeth's alone, and s is taken as 0.
38/// - Shaft seals: the motor shaft's Coulomb and breakaway levels (`ShaftFriction`) follow (nu / nu_ref)^m, m
39/// `seal_viscosity_exponent`: a lip seal runs on a lubricant film whose shear grows with the viscosity, less than in
40/// proportion.
41/// - Belt: polyurethane loses modulus as it warms, but the steel cords carry EA: EA (1 - alpha (T - T_ref)), alpha a
42/// few 1e-4 per K (steel's own modulus falls by about 2.5e-4 per K). The belt is taken at ambient: it has no loss
43/// of its own in the model, and a stiffness that changed while running would change its stored energy.
44#[derive(Debug, Clone)]
45pub struct ThermalFeedback {
46 /// K.
47 pub ambient: f64,
48 pub reference: f64,
49 /// B of the viscosity law, K.
50 pub viscosity_slope: f64,
51 pub gearbox_viscous_share: f64,
52 /// alpha, 1/K.
53 pub belt_coefficient: f64,
54 /// The gearbox's efficiency at the reference temperature (1 with effects.gearbox_efficiency off).
55 pub efficiency: f64,
56 /// m of the seals' law.
57 pub seal_exponent: f64,
58}
59
60impl ThermalFeedback {
61 /// `None` with the effect off.
62 pub fn from_config(cfg: &Config) -> Result<Option<Self>> {
63 if !cfg.bool("effects.thermal_feedback")? {
64 return Ok(None);
65 }
66 let celsius = |leaf: &str| -> Result<f64> {
67 let t = cfg.f64(&format!("thermal_feedback.{leaf}"))? + KELVIN;
68 if t > 0.0 { Ok(t) } else { Err(ConfigError::Invalid(format!("thermal_feedback.{leaf}"))) }
69 };
70 let share = cfg.non_negative("thermal_feedback.gearbox_viscous_loss_share")?;
71 if share > 1.0 {
72 return Err(ConfigError::Invalid("thermal_feedback.gearbox_viscous_loss_share".into()));
73 }
74 Ok(Some(Self {
75 ambient: celsius("ambient_c")?,
76 reference: celsius("reference_c")?,
77 viscosity_slope: cfg.non_negative("thermal_feedback.viscosity_slope_k")?,
78 gearbox_viscous_share: if cfg.bool("effects.gearbox_drag")? { 0.0 } else { share },
79 belt_coefficient: cfg.f64("thermal_feedback.belt_stiffness_coefficient_1_k")?,
80 efficiency: Gearbox::configured_efficiency(cfg)?,
81 seal_exponent: cfg.non_negative("thermal_feedback.seal_viscosity_exponent")?,
82 }))
83 }
84
85 /// nu / nu_ref of a lubricant `rise` above ambient.
86 pub fn viscosity_factor(&self, rise: f64) -> f64 {
87 (self.viscosity_slope * (1.0 / (self.ambient + rise) - 1.0 / self.reference)).exp()
88 }
89
90 /// The gearbox's efficiency `rise` above ambient. Not below 0.01: a gearbox far below its reference temperature
91 /// would otherwise lose more than it transmits.
92 pub fn gearbox_efficiency(&self, rise: f64) -> f64 {
93 let s = self.gearbox_viscous_share;
94 (1.0 - (1.0 - self.efficiency) * (1.0 - s + s * self.viscosity_factor(rise))).max(0.01)
95 }
96
97 /// Factor on the belt's EA at ambient.
98 pub fn belt_stiffness_factor(&self) -> f64 {
99 1.0 - self.belt_coefficient * (self.ambient - self.reference)
100 }
101}
102
103// ---------------------------------------------------------------------------------------------
104// Belt tooth jump
105
106/// States per driven pulley with effects.belt_tooth_jump: the slip of the belt over the pulley u (m of belt, a
107/// whole number of pitches while the teeth are in mesh), its rate, the direction of a jump under way (+1, -1;
108/// 0 while in mesh), u where the jump began, the jumps counted, and the ridge force of the jump under way.
109pub const JUMP_STATES: usize = 6;
110
111/// With effects.belt_tooth_jump: the belt's teeth jump over a driven pulley.
112///
113/// The teeth climb out when the effective pull at the pulley, |T_a - T_b|, exceeds `climb` times the slack-side
114/// tension min(T_a, T_b): each tooth in mesh is held in its groove by the tension's radial pull, T p / r over one
115/// pitch, and pushed out by its share of the pull times the tangent of an effective flank angle (flank, friction
116/// and the tooth's give together). Summed over the z_m teeth in mesh: climb = k z_m p / r, k = 1 / tan(effective
117/// angle) an estimate (`belt.tooth_jump_factor`). The pull a pulley can take before the teeth jump is then
118/// proportional to the tension the belt is set up with: the torque at which timing belts jump is reported to rise
119/// with their installation tension. No maker's chart was read for the factor.
120///
121/// Once out, the teeth ride over the pulley's: the belt, with its mass, moves on its own, and the pulley holds it
122/// back with a ridge force F_s sin(2 pi d / p), d how far it has slid, F_s the pull it climbed out at (climb times
123/// the slack side's tension then), held over the jump so that the ridge is a spring with the energy
124/// F_s p / (2 pi) (1 - cos(2 pi d / p)). That force is what the pulley passes on meanwhile. Where the belt crosses the
125/// next groove (d = p) the teeth fall in: a jump, counted; where it slides back over the groove it left (d < 0),
126/// they fall back in, uncounted. Either way belt and pulley run on together, at the speed that keeps their momentum
127/// (a plastic impact): what that takes is what a jump dissipates. Where the pull settles below the ridge the belt
128/// stays half out, held by it.
129///
130/// The belt's mass is the share the machine lumps on that pulley (effects.belt_mass, which the effect needs): while
131/// the teeth are out it moves with the belt and not with the pulley.
132#[derive(Debug, Clone)]
133pub struct ToothJump {
134 pub pitch: f64,
135 pub climb: f64,
136 /// `belt.tooth_jump_factor`, k: with the wrap angle known (`set_wrap`) climb = k z_m p / r = k wrap.
137 pub factor: f64,
138 /// The belt's mass lumped on the pulley, kg.
139 pub mass: f64,
140}
141
142impl ToothJump {
143 /// `None` with the effect off. `radius` is the driven pulley's, `mass` the belt's mass the machine lumps on it;
144 /// none (effects.belt_mass off) is refused.
145 pub fn from_config(cfg: &Config, radius: f64, mass: f64) -> Result<Option<Self>> {
146 if !cfg.bool("effects.belt_tooth_jump")? {
147 return Ok(None);
148 }
149 if mass <= 0.0 {
150 return Err(ConfigError::Invalid("effects.belt_tooth_jump".into()));
151 }
152 let (pitch, factor) = (cfg.positive("belt.tooth_pitch_m")?, cfg.positive("belt.tooth_jump_factor")?);
153 let climb = factor * cfg.positive("ratings.belt_teeth_in_mesh")? * pitch / radius;
154 Ok(Some(Self { pitch, climb, factor, mass }))
155 }
156
157 /// The teeth in mesh from the angle `wrap` (rad) by which the belt wraps the pulley (effects.belt_wrap), in place of
158 /// `ratings.belt_teeth_in_mesh`: a pulley of radius r has 2 pi r / p teeth, wrap / (2 pi) of them in mesh, so
159 /// z_m = wrap r / p and climb = k z_m p / r = k wrap, whatever the pitch and radius.
160 pub fn set_wrap(&mut self, wrap: f64) {
161 self.climb = self.factor * wrap;
162 }
163
164 /// The pulley's inertia: `lumped` (with the belt's share) while the teeth are in mesh, without it while they are out.
165 pub fn pulley_inertia(&self, slip: &[f64], lumped: f64, radius: f64) -> f64 {
166 if slip[2] == 0.0 { lumped } else { lumped - self.mass * radius * radius }
167 }
168
169 /// Whether the teeth climb out at these tensions of the two sections that meet at the pulley.
170 pub fn climbs(&self, a: f64, b: f64) -> bool {
171 (a - b).abs() > self.climb * a.min(b).max(0.0)
172 }
173
174 /// The force between belt and pulley along the belt, towards +u on the pulley: the sections' pull `force` while
175 /// the teeth are in mesh, the ridge force while they are out.
176 pub fn pulley_force(&self, slip: &[f64], force: f64) -> f64 {
177 if slip[2] == 0.0 { force } else { slip[5] * (std::f64::consts::TAU * (slip[0] - slip[3]) / self.pitch).sin() }
178 }
179
180 /// `pulley_force` as a torque on a pulley of `radius`: the belt's torque as it is while in mesh, so that an effect
181 /// that never climbs out changes no bit.
182 pub fn pulley_torque(&self, slip: &[f64], belt_torque: f64, radius: f64) -> f64 {
183 if slip[2] == 0.0 { belt_torque } else { radius * self.pulley_force(slip, 0.0) }
184 }
185
186 /// The rates of a pulley's slip states: none while in mesh. While the teeth are out, the belt moves on its own at
187 /// r da/dt + du/dt (a the pulley's angle) under `force`, the sections' pull towards +u, less the ridge force:
188 /// d2u/dt2 = (force - ridge) / mass - `surface_acc`, the pulley's surface acceleration r d2a/dt2.
189 pub fn rates(&self, slip: &[f64], force: f64, surface_acc: f64, out: &mut [f64]) {
190 out[..JUMP_STATES].fill(0.0);
191 if slip[2] != 0.0 {
192 (out[0], out[1]) = (slip[1], (force - self.pulley_force(slip, force)) / self.mass - surface_acc);
193 }
194 }
195
196 /// What a sliding belt adds to the energy of a machine that counts its mass with the pulley, whose surface moves at
197 /// v: 1/2 m (v + du/dt)^2 - 1/2 m v^2, and the ridge's energy; 0 while the teeth are in mesh.
198 pub fn slip_energy(&self, slip: &[f64], surface_speed: f64) -> f64 {
199 if slip[2] == 0.0 {
200 return 0.0;
201 }
202 let ridge = slip[5] * self.pitch / std::f64::consts::TAU
203 * (1.0 - (std::f64::consts::TAU * (slip[0] - slip[3]) / self.pitch).cos());
204 0.5 * self.mass * slip[1] * (2.0 * surface_speed + slip[1]) + ridge
205 }
206
207 /// After a step: starts a jump where the teeth climb out at the tensions `a`, `b` (the section that +u feeds
208 /// and the other one), or ends one where the belt has crossed the next groove (a jump) or the one it left: belt
209 /// and pulley then share their momentum, `surface_speed` the pulley's and `rest_mass` its inertia without the belt
210 /// over r^2. Returns whether it changed anything: the machine's energy then changes at once.
211 pub fn update(&self, slip: &mut [f64], a: f64, b: f64, rest_mass: f64, surface_speed: &mut f64) -> bool {
212 let dir = slip[2];
213 if dir == 0.0 {
214 if !self.climbs(a, b) {
215 return false;
216 }
217 (slip[1], slip[2], slip[3], slip[5]) = (0.0, (a - b).signum(), slip[0], self.climb * a.min(b).max(0.0));
218 return true;
219 }
220 let travel = (slip[0] - slip[3]) * dir;
221 if (0.0..self.pitch).contains(&travel) {
222 return false;
223 }
224 let jumped = travel >= self.pitch;
225 *surface_speed += self.mass * slip[1] / (rest_mass + self.mass);
226 slip[0] = slip[3] + if jumped { dir * self.pitch } else { 0.0 };
227 (slip[1], slip[2], slip[5]) = (0.0, 0.0, 0.0);
228 if jumped {
229 slip[4] += 1.0;
230 }
231 true
232 }
233}
234
235// ---------------------------------------------------------------------------------------------
236// Sideways vibration of the free belt spans
237
238/// The angle (rad) by which a belt wraps a pulley of radius `r` (effects.belt_wrap), the pulley's centre at the origin and
239/// its two spans leaving towards +x, one over the top, one under the bottom. Each span runs to the next wheel, given as
240/// (d, h, r2): its centre d along +x and h out on the span's own side (up for the upper span, down for the lower), and
241/// its radius r2, positive where pulley and wheel lie on either side of the belt (an inner tangent), negative where on
242/// the same side (an outer tangent), 0 for a clamp. A span leans away from the pulley by atan2(h, d) - asin((r + r2) / D),
243/// D the distance of the centres (0 for a span that leaves level), and takes as much off the half turn:
244/// wrap = pi - lean_upper - lean_lower.
245pub fn wrap_angle(r: f64, upper: [f64; 3], lower: [f64; 3]) -> f64 {
246 let lean = |[d, h, r2]: [f64; 3]| h.atan2(d) - ((r + r2) / d.hypot(h)).asin();
247 std::f64::consts::PI - lean(upper) - lean(lower)
248}
249
250/// First transverse mode of a free belt span as a string: f1 = sqrt(T / mu) / (2 L). The belt's own speed lowers it
251/// by the factor 1 - v² / c² (c = sqrt(T / mu)), below 0.2 % at the speeds and tensions here, left out. 0 for a slack
252/// span.
253pub fn span_frequency(length: f64, tension: f64, mass_per_m: f64) -> f64 {
254 if tension > 0.0 && length > 0.0 { (tension / mass_per_m).sqrt() / (2.0 * length) } else { 0.0 }
255}
256
257/// How far a span's first mode is from the nearest excitation, as a share of the mode: min |f1 - f_e| / f1. 1 for
258/// a slack span or none.
259pub fn span_detuning(f1: f64, excitations: &[f64]) -> f64 {
260 if f1 <= 0.0 {
261 return 1.0;
262 }
263 excitations.iter().filter(|f| **f > 0.0).map(|f| (f1 - f).abs() / f1).fold(1.0, f64::min)
264}
265
266/// The frequencies one drive excites the belt with, Hz: the tooth mesh |v| / p at the pulley (v its belt speed), and
267/// with effects.torque_ripple the motor's ripple and cogging orders times its turns per second.
268pub fn drive_excitations(pitch: f64, belt_speed: f64, ripple: &Ripple, motor_speed: f64, out: &mut Vec<f64>) {
269 let turns = motor_speed.abs() / std::f64::consts::TAU;
270 out.push(belt_speed.abs() / pitch);
271 if ripple.ripple != 0.0 {
272 out.push(ripple.ripple_order.abs() * turns);
273 }
274 if ripple.cogging != 0.0 {
275 out.push(ripple.cogging_order.abs() * turns);
276 }
277}
278
279// ---------------------------------------------------------------------------------------------
280// Belt
281
282/// A toothed belt. A *section* is the belt between two points that hold it (a driven pulley or a
283/// clamp); idlers in between are free, so the tension is the same along the whole section.
284///
285/// A section has a geometric length `geo` (set by the pose) and holds `mat` of unstretched belt
286/// (changed by the pulleys feeding belt in or out). Stretch e = geo - mat, stiffness k = EA / mat,
287/// tension T = max(0, k e + c de/dt).
288#[derive(Debug, Clone)]
289pub struct Belt {
290 pub ea: f64,
291 pub damping: f64,
292 /// Material loss: a section damps with its stiffness times this time, so a short section damps more.
293 pub damping_time: f64,
294 pub pretension: f64,
295 pub slack: bool,
296 pub mass_per_m: f64,
297 /// The teeth in mesh on a driven pulley give way like this much more belt: EA / tooth-mesh stiffness.
298 /// A machine adds it to the geometric length of a section once per driven pulley the section ends at.
299 /// `mat` then holds it too, and k = EA / mat is the belt and the teeth in series.
300 pub tooth_length: f64,
301}
302
303#[derive(Debug, Clone, Copy, Default)]
304pub struct SectionForce {
305 /// Pulls on whatever the section's ends are attached to.
306 pub tension: f64,
307 /// Force on the belt material fed into the section, -dV/d(mat) plus damping. It exceeds the
308 /// tension by the factor (1 + strain/2), because stretched belt carries its strain energy along.
309 /// Using it at the pulleys makes the model conserve energy exactly.
310 pub material: f64,
311}
312
313impl Belt {
314 pub fn from_config(cfg: &Config) -> Result<Self> {
315 let feedback = ThermalFeedback::from_config(cfg)?.map_or(1.0, |t| t.belt_stiffness_factor());
316 let ea = cfg.positive("belt.stiffness_ea_n")? * temperature_scale(cfg, "belt_stiffness_scale")? * feedback;
317 if ea <= 0.0 {
318 return Err(ConfigError::Invalid("thermal_feedback.belt_stiffness_coefficient_1_k".into()));
319 }
320 let damping = cfg.bool("effects.belt_damping")?;
321 let material = cfg.bool("effects.belt_material_damping")? && damping;
322 let teeth = cfg.bool("effects.belt_tooth_stiffness")?;
323 Ok(Self {
324 ea,
325 damping: if damping && !material { cfg.non_negative("belt.damping_n_s_m")? } else { 0.0 },
326 damping_time: if material { cfg.non_negative("belt.damping_time_s")? } else { 0.0 },
327 tooth_length: if teeth { ea / cfg.positive("belt.tooth_mesh_stiffness_n_m")? } else { 0.0 },
328 // Not negative: at minus EA the belt would have no length at rest, and a belt cannot push.
329 pretension: cfg.non_negative("belt.pretension_n")?,
330 slack: cfg.bool("effects.belt_slack")?,
331 mass_per_m: if cfg.bool("effects.belt_mass")? { cfg.non_negative("belt.mass_kg_m")? } else { 0.0 },
332 })
333 }
334
335 /// Unstretched belt in a section of length `geo` at pretension.
336 pub fn rest_length(&self, geo: f64) -> f64 {
337 geo / (1.0 + self.pretension / self.ea)
338 }
339
340 pub fn section(&self, geo: f64, mat: f64, geo_rate: f64, mat_rate: f64) -> SectionForce {
341 let e = geo - mat;
342 let elastic = self.ea * e / mat;
343 let total = elastic + (self.damping + self.damping_time * self.ea / mat) * (geo_rate - mat_rate);
344 if self.slack && e < 0.0 {
345 return SectionForce { tension: total.max(0.0), material: total.max(0.0) };
346 }
347 let tension = if self.slack { total.max(0.0) } else { total };
348 SectionForce { tension, material: tension + elastic * e / (2.0 * mat) }
349 }
350
351 pub fn energy(&self, geo: f64, mat: f64) -> f64 {
352 let e = geo - mat;
353 if self.slack && e < 0.0 { 0.0 } else { 0.5 * self.ea * e * e / mat }
354 }
355
356 /// Power the damping of a section takes, W: what goes into it (the tension on the length, less the material
357 /// force on the belt fed in) less what its stored energy gains. c (rate)^2 while it is taut.
358 pub fn loss_power(&self, geo: f64, mat: f64, geo_rate: f64, mat_rate: f64) -> f64 {
359 let (f, e) = (self.section(geo, mat, geo_rate, mat_rate), geo - mat);
360 let stored = if self.slack && e < 0.0 {
361 0.0
362 } else {
363 self.ea * e / mat * (geo_rate - mat_rate) - 0.5 * self.ea * e * e / (mat * mat) * mat_rate
364 };
365 f.tension * geo_rate - f.material * mat_rate - stored
366 }
367
368 /// Material per section at rest, when section i carries `base + offsets[i]` and the sections
369 /// share `total` of belt. The base tension follows from the total; found by bisection.
370 pub fn static_material(&self, geo: &[f64], offsets: &[f64], total: f64) -> Vec<f64> {
371 let material = |base: f64| -> Vec<f64> {
372 let tension = |o: f64| if self.slack { (base + o).max(0.0) } else { base + o };
373 geo.iter().zip(offsets).map(|(g, o)| g / (1.0 + tension(*o) / self.ea)).collect()
374 };
375 let (mut lo, mut hi) = (-0.5 * self.ea, self.ea);
376 for _ in 0..200 {
377 let mid = 0.5 * (lo + hi);
378 if material(mid).iter().sum::<f64>() > total { lo = mid } else { hi = mid }
379 }
380 material(0.5 * (lo + hi))
381 }
382}
383
384// ---------------------------------------------------------------------------------------------
385// Hard stops
386
387/// How many base steps ahead, at the speed of a step's start, a stop counts as met within the step
388/// (`HardStop::met_within`): the step may speed the axis up on its way.
389const STOP_REACH: f64 = 2.0;
390
391/// The parts a sub-step is cut into where a stop is met within the base step (`HardStop::met_within`). The stop's
392/// damper takes hold at once as the axis touches, a step in the force that a sub-step across it integrates with an
393/// error in steps at each contact, falling with about the third power of the sub-step: an arm's upper link, swinging
394/// into its joint's stop with a bending link and parallelogram bars, kept its energy to 1.3e-5 J of 2.8 mJ over 10 s
395/// at the 15.6 us sub-steps, 3.2e-7 J cut by 4 and 5.3e-9 J by 16 (1.8e-8 J with the stops off); three carriages
396/// pulsed into their stops, on springs alone, 7.7e-9 J, 2.6e-11 J cut by 16. An axis resting in a stop is cut all the
397/// while.
398pub const STOP_SUBSTEPS: u32 = 16;
399
400/// End stops of an axis whose stroke runs from 0 to `stroke`: a spring and a damper at both ends that act
401/// only beyond it.
402#[derive(Debug, Clone)]
403pub struct HardStop {
404 pub stiffness: f64,
405 pub damping: f64,
406}
407
408impl HardStop {
409 pub fn from_config(cfg: &Config) -> Result<Self> {
410 let (stiffness, damping) =
411 (cfg.positive("hard_stop.stiffness_n_m")?, cfg.non_negative("hard_stop.damping_n_s_m")?);
412 Ok(if cfg.bool("effects.hard_stops")? {
413 Self { stiffness, damping }
414 } else {
415 Self { stiffness: 0.0, damping: 0.0 }
416 })
417 }
418
419 /// How far a position is beyond the stroke: negative below 0, positive above the stroke.
420 fn beyond(pos: f64, stroke: f64) -> f64 {
421 pos - pos.clamp(0.0, stroke)
422 }
423
424 /// Force of the stops on the axis. They push back, they never hold on.
425 pub fn force(&self, pos: f64, vel: f64, stroke: f64) -> f64 {
426 let beyond = Self::beyond(pos, stroke);
427 let force = -self.stiffness * beyond - self.damping * vel;
428 if force * beyond < 0.0 { force } else { 0.0 }
429 }
430
431 pub fn energy(&self, pos: f64, stroke: f64) -> f64 {
432 0.5 * self.stiffness * Self::beyond(pos, stroke).powi(2)
433 }
434
435 /// Whether an axis at `pos` moving at `vel` meets a stop within a base step `dt` (s): in one already, or nearer to
436 /// the one it moves towards than `STOP_REACH` steps at its speed (`STOP_SUBSTEPS`). Never without stops.
437 pub fn met_within(&self, pos: f64, vel: f64, stroke: f64, dt: f64) -> bool {
438 let gap = if vel > 0.0 { stroke - pos } else { pos };
439 self.stiffness > 0.0 && (Self::beyond(pos, stroke) != 0.0 || gap < STOP_REACH * vel.abs() * dt)
440 }
441
442 /// The parts a sub-step is cut into for these stops (`met_within`): `STOP_SUBSTEPS`, else 1.
443 pub fn substeps(&self, pos: f64, vel: f64, stroke: f64, dt: f64) -> u32 {
444 if self.met_within(pos, vel, stroke, dt) { STOP_SUBSTEPS } else { 1 }
445 }
446
447 /// Power the stops take, W: what the axis loses to them less what their springs store.
448 pub fn loss_power(&self, pos: f64, vel: f64, stroke: f64) -> f64 {
449 -(self.force(pos, vel, stroke) + self.stiffness * Self::beyond(pos, stroke)) * vel
450 }
451}
452
453// ---------------------------------------------------------------------------------------------
454// Cable chain
455
456/// A cable chain along an axis, fixed at the x = 0 end: half of every metre the carriage travels joins the
457/// run that moves with it. It drags with a constant force. All zero with the effect off.
458#[derive(Debug, Clone)]
459pub struct CableChain {
460 pub mass_per_m: f64,
461 /// Chain that moves with the carriage at x = 0.
462 pub length0: f64,
463 pub drag: f64,
464}
465
466impl CableChain {
467 pub fn from_config(cfg: &Config) -> Result<Self> {
468 let on = cfg.bool("effects.cable_chain")?;
469 let value = |leaf: &str| cfg.non_negative(&format!("cable_chain.{leaf}"));
470 let (mass_per_m, length0, drag) = (value("mass_kg_m")?, value("length_at_zero_m")?, value("drag_n")?);
471 Ok(Self { mass_per_m: if on { mass_per_m } else { 0.0 }, length0, drag: if on { drag } else { 0.0 } })
472 }
473
474 /// (mass that moves with the carriage at x, its growth per metre). A mass m(x) moving at v takes
475 /// m dv/dt + m' v^2 / 2 of force: the second part is what picking up chain costs.
476 pub fn mass(&self, x: f64) -> (f64, f64) {
477 (self.mass_per_m * (self.length0 + 0.5 * x), 0.5 * self.mass_per_m)
478 }
479
480 /// Drag opposing v; it fades out at rest, below `fade_v`.
481 pub fn drag(&self, v: f64, fade_v: f64) -> f64 {
482 self.drag * (v / fade_v).tanh()
483 }
484}
485
486// ---------------------------------------------------------------------------------------------
487// Holding brake
488
489/// A brake at its full torque has given way by this angle.
490const BRAKE_DEFLECTION_RAD: f64 = 1e-3;
491/// A released brake forgets its deflection this fast.
492const BRAKE_RELEASE_S: f64 = 1e-3;
493/// A slipping brake forgets this fast what it is deflected beyond its full torque. Well above the integration
494/// step (a quarter of 62.5 us by default), so that a brake that engages at any speed is stable.
495const BRAKE_SLIP_S: f64 = 5e-5;
496
497/// Holding brake on a motor shaft, engaged while the drives are disabled. A machine keeps one state per
498/// brake, its deflection s.
499#[derive(Debug, Clone)]
500pub struct HoldingBrake {
501 /// (its torque, the damping of the shaft held in it); `None` with the effect off.
502 held: Option<(f64, f64)>,
503}
504
505impl HoldingBrake {
506 /// `j_rotor` is the inertia the brake holds directly: rotor and gearbox input.
507 pub fn from_config(cfg: &Config, j_rotor: f64) -> Result<Self> {
508 if !cfg.bool("effects.holding_brake")? {
509 return Ok(Self { held: None });
510 }
511 let torque = cfg.positive("motor.brake_torque_nm")?;
512 // Critical damping of the rotor on the brake's stiffness, so that it stops without ringing.
513 Ok(Self { held: Some((torque, 2.0 * (torque / BRAKE_DEFLECTION_RAD * j_rotor).sqrt())) })
514 }
515
516 /// (torque opposing the speed, rate of the deflection s).
517 ///
518 /// Held, the shaft sits on a damped spring that reaches the brake torque at `BRAKE_DEFLECTION_RAD`. The
519 /// torque never exceeds the brake torque: beyond it the brake slips, and s stops following the shaft.
520 /// A friction contact with bristle damping (LuGre) gave many times the brake torque when it engaged at
521 /// speed, and its state was too stiff for the step above 178 rad/s.
522 pub fn torque(&self, engaged: bool, speed: f64, s: f64) -> (f64, f64) {
523 match self.held {
524 Some((torque, damping)) if engaged => {
525 let rate = speed - (s - s.clamp(-BRAKE_DEFLECTION_RAD, BRAKE_DEFLECTION_RAD)) / BRAKE_SLIP_S;
526 ((torque / BRAKE_DEFLECTION_RAD * s + damping * rate).clamp(-torque, torque), rate)
527 }
528 _ => (0.0, -s / BRAKE_RELEASE_S),
529 }
530 }
531}
532
533// ---------------------------------------------------------------------------------------------
534// Guide friction
535
536/// LuGre friction contact: Coulomb, viscous, stiction and the Stribeck drop between them,
537/// with one internal state s (the bristle deflection).
538#[derive(Debug, Clone)]
539pub struct Lugre {
540 pub on: bool,
541 pub sigma0: f64,
542 pub sigma1: f64,
543 pub viscous: f64,
544 pub coulomb: f64,
545 pub stiction: f64,
546 pub stribeck_v: f64,
547 /// Guide preload; with `load_dependent` the Coulomb and stiction levels scale with preload + load.
548 pub preload: f64,
549 pub load_dependent: bool,
550}
551
552impl Lugre {
553 pub fn from_config(cfg: &Config, table: &str) -> Result<Self> {
554 let scale = temperature_scale(cfg, "friction_scale")?;
555 let get = |leaf: &str| cfg.non_negative(&format!("{table}.{leaf}"));
556 let coulomb = cfg.positive(&format!("{table}.coulomb_n"))? * scale;
557 Ok(Self {
558 on: cfg.bool("effects.guide_friction")?,
559 sigma0: cfg.positive(&format!("{table}.bristle_stiffness_n_m"))?,
560 sigma1: get("bristle_damping_n_s_m")?,
561 // With the feedback, at ambient; the machine follows the guide's temperature (`ThermalFeedback`).
562 viscous: get("viscous_n_s_m")?
563 * scale
564 * ThermalFeedback::from_config(cfg)?.map_or(1.0, |t| t.viscosity_factor(0.0)),
565 coulomb,
566 // Breaking away takes at least what sliding takes. A value below the Coulomb level counts as that
567 // level: uncertainty bounds of the two that overlap would otherwise give runs that slide harder
568 // than they break away.
569 stiction: (cfg.positive(&format!("{table}.stiction_n"))? * scale).max(coulomb),
570 stribeck_v: cfg.positive(&format!("{table}.stribeck_m_s"))?,
571 preload: cfg.positive(&format!("{table}.preload_n"))?,
572 load_dependent: cfg.bool("effects.load_dependent_friction")?,
573 })
574 }
575
576 /// Factor on the friction levels for a guide load, relative to the load the levels were given for.
577 pub fn load_scale(&self, load: f64, nominal_load: f64) -> f64 {
578 if self.load_dependent { (self.preload + load.abs()) / (self.preload + nominal_load.abs()) } else { 1.0 }
579 }
580
581 /// Sliding level g(v) = Fc + (Fs - Fc) exp(-(v/vs)^2), times the load scale.
582 pub fn level(&self, v: f64, load_scale: f64) -> f64 {
583 load_scale * (self.coulomb + (self.stiction - self.coulomb) * (-(v / self.stribeck_v).powi(2)).exp())
584 }
585
586 /// Returns (friction force opposing positive v, ds/dt).
587 pub fn eval(&self, v: f64, s: f64, load_scale: f64) -> (f64, f64) {
588 if !self.on {
589 return (0.0, 0.0);
590 }
591 let level = self.level(v, load_scale);
592 let rate = self.sigma0 * v.abs() / level;
593 if rate <= BRISTLE_RATE_MAX {
594 let s_dot = v - self.sigma0 * v.abs() * s / level;
595 return (self.sigma0 * s + self.sigma1 * s_dot + self.viscous * v, s_dot);
596 }
597 // shortcut: bristles that would settle faster than `BRISTLE_RATE_MAX` settle at that rate, with their
598 // force scaled so that sliding still takes the level; step the friction state implicitly if what
599 // bristles do within 10 us ever matters.
600 let s_dot = v - BRISTLE_RATE_MAX * s;
601 (self.sigma0 * s * BRISTLE_RATE_MAX / rate + self.sigma1 * s_dot + self.viscous * v, s_dot)
602 }
603
604 /// Steady sliding at v, g(v) sign(v) + b v, split into [Coulomb, viscous, stiction]: the Coulomb level, b v,
605 /// and what the Stribeck curve adds to the Coulomb level, (Fs - Fc) exp(-(v/vs)^2), each times the load scale.
606 /// Zero with the effect off.
607 pub fn steady(&self, v: f64, load_scale: f64) -> [f64; 3] {
608 if !self.on {
609 return [0.0; 3];
610 }
611 let (sign, coulomb) = (if v == 0.0 { 0.0 } else { v.signum() }, load_scale * self.coulomb);
612 [coulomb * sign, self.viscous * v, (self.level(v, load_scale) - coulomb) * sign]
613 }
614
615 /// The steady sliding force for a feedforward at a planned speed v (`Machine::steady_friction`): `steady`'s sum, its
616 /// level g(v) faded in by tanh(v / v_s) over the Stribeck speed, g(v) tanh(v / v_s) + b v. Above a few v_s it is
617 /// `steady` (1 m/s on a 10 mm/s Stribeck speed: to 1e-86); towards rest it falls to 0 smoothly instead of stepping
618 /// from the breakaway level, so that a move's last micrometres and its stop put no torque step on the axis, as the
619 /// bristles that stick there take the force over without one.
620 pub fn feedforward(&self, v: f64, load_scale: f64) -> f64 {
621 if !self.on {
622 return 0.0;
623 }
624 self.level(v, load_scale) * (v / self.stribeck_v).tanh() + self.viscous * v
625 }
626
627 /// The force of `eval` split into [Coulomb, viscous, stiction]: b v, and the bristle force (all the rest) shared
628 /// in the proportion of the Coulomb level to what the Stribeck curve adds to it at this speed. In steady
629 /// sliding these are the parts of `steady`; at rest the bristles hold with the shares of the stiction level.
630 pub fn split(&self, v: f64, s: f64, load_scale: f64) -> [f64; 3] {
631 if !self.on {
632 return [0.0; 3];
633 }
634 let (viscous, level) = (self.viscous * v, self.level(v, load_scale));
635 // No level (a load scale of 0): nothing for the bristles to hold, and no share to split by.
636 if level == 0.0 {
637 return [0.0, viscous, 0.0];
638 }
639 let coulomb = load_scale * self.coulomb / level;
640 let bristles = self.eval(v, s, load_scale).0 - viscous;
641 [bristles * coulomb, viscous, bristles * (1.0 - coulomb)]
642 }
643}
644
645/// The fastest the bristles of a friction contact settle, 1/s. The bristle state settles at the rate
646/// sigma0 |v| / level, which a stiff bristle on a light contact at speed takes beyond what the integrator can
647/// follow (1e6 N/m, 12 N and 2.5 m/s: 2.1e5 1/s, against a limit of 2.8 over the 15.6 us step = 1.8e5 1/s for
648/// RK4): the friction force then grew without bound. No config shipped reaches the cap with its own values.
649pub const BRISTLE_RATE_MAX: f64 = 1.0e5;
650
651// ---------------------------------------------------------------------------------------------
652// Motor shaft
653
654/// The exponent of the no-load running torque on viscosity times speed: Palmgren's law for the drag of rolling bearings
655/// running in oil, M0 ~ (nu n)^(2/3) (SKF's rolling bearing catalogue, the drag term f0 (nu n)^(2/3) dm^3), which the
656/// planet bearings and the churning of a gearbox follow.
657pub const DRAG_EXPONENT: f64 = 2.0 / 3.0;
658
659/// A gearbox's no-load running torque at its input (gearbox makers' T0 or T012): what it takes to turn the gearbox
660/// with nothing on its output, from the churning of its lubricant, its bearings and its seals. Makers quote it at a
661/// reference input speed and 20 °C (Neugart: average idle torque; B&R's 8G planetary gearboxes: "at 20 °C and
662/// 3000 rpm"). It scales with speed and the lubricant's viscosity by Palmgren's law:
663/// T0(n, nu) = T0_ref (nu / nu_ref * |n| / n_ref)^(2/3). Zero with effects.gearbox_drag off and on a coupling.
664#[derive(Debug, Clone, Copy, PartialEq)]
665pub struct GearDrag {
666 /// T0_ref, N m at the input.
667 pub torque: f64,
668 /// n_ref, rad/s at the input.
669 pub speed: f64,
670}
671
672impl GearDrag {
673 pub const NONE: Self = Self { torque: 0.0, speed: 1.0 };
674
675 pub fn from_config(cfg: &Config) -> Result<Self> {
676 let (torque, rpm) =
677 (cfg.non_negative("gearbox.no_load_torque_nm")?, cfg.positive("gearbox.no_load_speed_rpm")?);
678 let on = cfg.bool("effects.gearbox_drag")? && cfg.positive("gearbox.ratio")? != 1.0;
679 Ok(if on { Self { torque, speed: rpm * std::f64::consts::TAU / 60.0 } } else { Self::NONE })
680 }
681
682 /// The drag opposing a positive input `speed` (rad/s) with the lubricant at `oil` = nu / nu_ref.
683 pub fn torque(&self, speed: f64, oil: f64) -> f64 {
684 if self.torque == 0.0 {
685 return 0.0;
686 }
687 (self.torque * (oil * speed.abs() / self.speed).powf(DRAG_EXPONENT)).copysign(speed)
688 }
689
690 /// The efficiency of a gearbox of `ratio` whose teeth pass `tooth` of the power, with this drag at the input: the
691 /// share of the input power that reaches the output, T2 / (i T1) with T1 = T2 / (i tooth) + T0(n, nu). It falls at
692 /// part load, at speed and in the cold, as makers' efficiency charts do. 0 with no output torque.
693 pub fn efficiency(&self, tooth: f64, ratio: f64, output_torque: f64, input_speed: f64, oil: f64) -> f64 {
694 let t2 = output_torque.abs();
695 if t2 == 0.0 {
696 return 0.0;
697 }
698 t2 / (ratio * (t2 / (ratio * tooth) + self.torque(input_speed.abs(), oil)))
699 }
700
701 /// The teeth's efficiency of a gearbox whose catalogue efficiency `full` holds at the output torque `at` with this
702 /// drag at its reference speed: the inverse of `efficiency`, 1 / (1 / full - i T0_ref / at), at most 1 (a drag that
703 /// takes all the loss leaves the teeth without one).
704 pub fn tooth_efficiency(&self, full: f64, ratio: f64, at: f64) -> f64 {
705 // Without a drag the efficiency as given, to the bit (1 / (1 / full) may differ from it in the last place).
706 if self.torque == 0.0 {
707 return full;
708 }
709 let inverse = 1.0 / full - ratio * self.torque / at;
710 if inverse <= 1.0 { 1.0 } else { 1.0 / inverse }
711 }
712}
713
714/// Motor and bearing friction on the shaft, with what the gearbox's input adds to it: a Coulomb level that breaks away
715/// from a higher stiction level along a Stribeck curve (effects.motor_stiction), viscous friction, and the gearbox's
716/// no-load running torque (`GearDrag`). The Coulomb step is smoothed with tanh so a shaft at rest sees no chattering
717/// torque.
718///
719/// The Coulomb and stiction levels are those of the seals and bearings: on a geared motor the shaft's seal is the
720/// gearbox's input seal and runs in its lubricant, so with effects.thermal_feedback both follow the gearbox's
721/// lubricant (`oil`, nu / nu_ref) to the power `seal_exponent`, as the drag follows it by its own law.
722#[derive(Debug, Clone)]
723pub struct ShaftFriction {
724 pub coulomb: f64,
725 pub viscous: f64,
726 pub smoothing: f64,
727 /// The breakaway level at rest; one below `coulomb` counts as `coulomb` (so with effects.motor_stiction off).
728 pub stiction: f64,
729 /// The speed over which the level falls from stiction to Coulomb, rad/s.
730 pub stribeck: f64,
731 pub drag: GearDrag,
732 /// nu / nu_ref of the gearbox's lubricant (1 at the reference temperature; `ThermalFeedback` sets it).
733 pub oil: f64,
734 /// The exponent of the seals' levels on `oil` (0 without effects.thermal_feedback).
735 pub seal_exponent: f64,
736 /// With a stiffness above 0 (a slide's effects.slide_presliding), the level is a presliding state of its own in
737 /// place of the tanh: Dahl's law, the force over the travel since the last step's end (`presliding_force`). 0: none.
738 pub presliding: f64,
739 /// Where the last step ended, travel and friction force (`commit`); NaN before the first: then no force.
740 pub anchor: [f64; 2],
741}
742
743impl ShaftFriction {
744 /// No friction: a bearing friction of a joint or slide (`coulomb`, `viscous`, `smoothing`) has none of the rest.
745 pub const NONE: Self = Self {
746 coulomb: 0.0,
747 viscous: 0.0,
748 smoothing: 1.0,
749 stiction: 0.0,
750 stribeck: 1.0,
751 drag: GearDrag::NONE,
752 oil: 1.0,
753 seal_exponent: 0.0,
754 presliding: 0.0,
755 anchor: [f64::NAN, 0.0],
756 };
757
758 pub fn from_config(cfg: &Config) -> Result<Self> {
759 let on = cfg.bool("effects.motor_friction")?;
760 let coulomb = if on { cfg.non_negative("motor.friction_coulomb_nm")? } else { 0.0 };
761 let breakaway = cfg.non_negative("motor.friction_breakaway_nm")?;
762 let feedback = ThermalFeedback::from_config(cfg)?;
763 Ok(Self {
764 coulomb,
765 viscous: if on { cfg.non_negative("motor.friction_viscous_nm_s_rad")? } else { 0.0 },
766 smoothing: cfg.positive("motor.friction_smoothing_rad_s")?,
767 // A breakaway level below the Coulomb level counts as that level, as for the guides (`Lugre`).
768 stiction: if on && cfg.bool("effects.motor_stiction")? { breakaway.max(coulomb) } else { coulomb },
769 stribeck: cfg.positive("motor.friction_stribeck_rad_s")?,
770 drag: GearDrag::from_config(cfg)?,
771 // With the feedback, at ambient; the machine follows the gearbox's temperature (`set_oil`).
772 oil: feedback.as_ref().map_or(1.0, |t| t.viscosity_factor(0.0)),
773 seal_exponent: feedback.map_or(0.0, |t| t.seal_exponent),
774 ..Self::NONE
775 })
776 }
777
778 /// With effects.thermal_feedback: the gearbox's lubricant at nu / nu_ref = `oil` (`ThermalFeedback::viscosity_factor`
779 /// of the gearbox's rise).
780 pub fn set_oil(&mut self, oil: f64) {
781 self.oil = oil;
782 }
783
784 /// The sliding level at `speed`: Fc + (Fs - Fc) exp(-(w / ws)^2), times the seals' temperature factor.
785 pub fn level(&self, speed: f64) -> f64 {
786 let stribeck = (self.stiction.max(self.coulomb) - self.coulomb) * (-(speed / self.stribeck).powi(2)).exp();
787 self.oil.powf(self.seal_exponent) * (self.coulomb + stribeck)
788 }
789
790 /// Torque opposing a positive speed.
791 /// The gearbox's drag acts on the rotor with the seals' friction (every machine has this one call on its rotor), but
792 /// its loss is the gearbox's: the machines book `drag_power` in the gearbox's loss, which warms the gearbox.
793 pub fn torque(&self, speed: f64) -> f64 {
794 self.level(speed) * (speed / self.smoothing).tanh() + self.viscous * speed + self.drag.torque(speed, self.oil)
795 }
796
797 /// The power the gearbox's drag (effects.gearbox_drag) takes at a rotor speed, W: the gearbox's loss, not the motor's.
798 pub fn drag_power(&self, speed: f64) -> f64 {
799 self.drag.torque(speed, self.oil) * speed
800 }
801
802 /// With `presliding`: the friction force at travel `x` and speed `speed`, Dahl's law solved from the anchor
803 /// [x0, z0] along a travel that ran one way, z = s g - (s g - z0) exp(-sigma |x - x0| / g), g the level at the speed
804 /// (`level`: Coulomb, or stiction falling to it along the Stribeck curve), s the sign of x - x0 (of the speed at the
805 /// anchor itself). It holds any force within ±g at rest without creeping (the travel, not the time, moves it), turns
806 /// over a presliding travel of about g / sigma at a reversal, and slides at ±g. 0 before the first step and
807 /// without a level.
808 pub fn presliding_force(&self, x: f64, speed: f64) -> f64 {
809 let ([x0, z0], g) = (self.anchor, self.level(speed));
810 if x0.is_nan() || g <= 0.0 {
811 return 0.0;
812 }
813 let s = if x > x0 || (x == x0 && speed >= 0.0) { 1.0 } else { -1.0 };
814 s * g - (s * g - z0) * (-self.presliding * (x - x0).abs() / g).exp()
815 }
816
817 /// The torque (force) opposing a positive speed at travel `x`: `torque`, with `presliding` the Dahl force in place of
818 /// the smoothed level.
819 pub fn torque_at(&self, x: f64, speed: f64) -> f64 {
820 if self.presliding == 0.0 {
821 return self.torque(speed);
822 }
823 self.presliding_force(x, speed) + self.viscous * speed + self.drag.torque(speed, self.oil)
824 }
825
826 /// Ends a step: with `presliding`, the anchor moves to where the step ended (`Machine::after_step`).
827 pub fn commit(&mut self, x: f64, speed: f64) {
828 if self.presliding > 0.0 {
829 self.anchor = [x, self.presliding_force(x, speed)];
830 }
831 }
832}
833
834/// Position-dependent motor torque: ripple proportional to the torque, cogging independent of it.
835#[derive(Debug, Clone)]
836pub struct Ripple {
837 pub ripple: f64,
838 pub ripple_order: f64,
839 pub cogging: f64,
840 pub cogging_order: f64,
841}
842
843impl Ripple {
844 pub fn from_config(cfg: &Config) -> Result<Self> {
845 let on = cfg.bool("effects.torque_ripple")?;
846 // Below one: at one the torque would vanish at an angle, and `invert` divide by zero there.
847 let ripple = cfg.non_negative("motor.ripple_fraction")?;
848 if ripple >= 1.0 {
849 return Err(ConfigError::Invalid("motor.ripple_fraction".into()));
850 }
851 Ok(Self {
852 ripple: if on { ripple } else { 0.0 },
853 ripple_order: cfg.f64("motor.ripple_order")?,
854 cogging: if on { cfg.f64("motor.cogging_nm")? } else { 0.0 },
855 cogging_order: cfg.f64("motor.cogging_order")?,
856 })
857 }
858
859 /// Torque at the shaft for a torque produced by the current.
860 pub fn apply(&self, torque: f64, angle: f64) -> f64 {
861 torque * (1.0 + self.ripple * (self.ripple_order * angle).sin())
862 + self.cogging * (self.cogging_order * angle).sin()
863 }
864
865 /// The current torque that gives `shaft` at the shaft: the inverse of `apply`.
866 pub fn invert(&self, shaft: f64, angle: f64) -> f64 {
867 (shaft - self.cogging * (self.cogging_order * angle).sin())
868 / (1.0 + self.ripple * (self.ripple_order * angle).sin())
869 }
870}
871
872/// Tooth meshing: a small periodic force at the tooth-pass frequency.
873#[derive(Debug, Clone)]
874pub struct ToothMesh {
875 pub force: f64,
876 pub pitch: f64,
877}
878
879impl ToothMesh {
880 pub fn from_config(cfg: &Config) -> Result<Self> {
881 Ok(Self {
882 force: if cfg.bool("effects.tooth_meshing")? { cfg.f64("belt.tooth_force_n")? } else { 0.0 },
883 pitch: cfg.positive("belt.tooth_pitch_m")?,
884 })
885 }
886
887 /// Force along the belt for a belt travel at the pulley.
888 pub fn force(&self, travel: f64) -> f64 {
889 self.force * (std::f64::consts::TAU * travel / self.pitch).sin()
890 }
891}
892
893// ---------------------------------------------------------------------------------------------
894// Gearbox
895
896/// Gearbox between motor shaft and pulley: ratio, torsional stiffness, backlash as a dead zone,
897/// efficiency. Stiffness, damping and backlash are given at the output side.
898///
899/// The torsional characteristic, as makers measure it with the input locked (e the twist beyond half the backlash):
900///
901/// - Lost motion (effects.gearbox_lost_motion): the flanks do not take the load at once. Over a band b beyond the
902/// backlash the stiffness rises from 0 to K1, T = K1 e^2 / (2 b); beyond it T = K1 (e - b/2). And a hysteresis: the
903/// twist under load lags the torque by a friction torque T_h in the flanks and bearings, so that loading and unloading
904/// run on two curves apart by 2 T_h / K1 in angle (Harmonic Drive: "hysteresis loss", the loop's width at zero
905/// torque). The friction is a state, Dahl's model on the contact twist x (the twist beyond the backlash, signed):
906/// dz/dx = sigma (1 - sgn(dx) z / T_h), in parallel with the spring. It holds its torque at rest, and at small
907/// amplitudes it is a spring of sigma (the gear is stiffer, K1 + sigma, not locked); over a twist of a few T_h / sigma
908/// it reaches +-T_h. Both 0 with the effect off.
909/// - Three-segment stiffness (effects.gearbox_stiffness_curve): K1 up to T1, K2 from T1 to T2, K3 beyond, as
910/// Harmonic Drive gives it for its strain wave gears; the twist at T is T / K1 below T1, T1 / K1 + (T - T1) / K2
911/// below T2, T1 / K1 + (T2 - T1) / K2 + (T - T2) / K3 above. Off: K1 throughout.
912#[derive(Debug, Clone)]
913pub struct Gearbox {
914 pub ratio: f64,
915 /// K1, N m/rad.
916 pub stiffness: f64,
917 pub damping: f64,
918 pub half_backlash: f64,
919 pub efficiency: f64,
920 /// b, rad.
921 pub band: f64,
922 /// c, rad / (N m): a spring in series with the gear's flanks that K1 (and K2, K3) already hold, 0 for a gear alone.
923 /// Behind a converter it is the converter's own compliance (`Converter::apply_to`): over the band the flanks stiffen
924 /// and the converter's spring does not, so the band's curve is the flanks' plus c T (`spring`).
925 pub band_compliance: f64,
926 /// T_h, N m.
927 pub hysteresis: f64,
928 /// Dahl's sigma, the hysteresis's stiffness at a reversal, N m/rad: `gearbox.hysteresis_stiffness_factor` times K1,
929 /// K1 itself where the key is absent (no maker publishes the loop's shape at a reversal).
930 pub dahl_stiffness: f64,
931 /// The efficiency driven back over the efficiency driving, 1 for a gear that loses alike both ways (`loss_factor`).
932 /// A screw sets it from its lead angle (`Converter::apply_back`).
933 pub back_ratio: f64,
934 /// The hysteresis's state where the last step ended: the contact twist x and its torque z there (`commit`; behind a
935 /// screw whose stiffness follows the nut, on the reference's twist y = r x, `at`). Within a
936 /// step z follows Dahl's law exactly from it for a twist that runs one way (`hysteresis_torque`). A NaN twist: not
937 /// stepped yet, z is 0 at the twist of the first step's end.
938 pub anchor: [f64; 2],
939 /// r of `at`, the gear's own twist y = r x over the contact twist x: 1 on the gear itself, where `anchor` is in x. On
940 /// `at`'s gear the anchor's twist stays the reference's y0, so that the branch at the anchor compares x r with it,
941 /// the same product `commit` stored, not x with y0 / r, which rounding puts an ulp to either side.
942 pub twist_scale: f64,
943 /// [T1, T2], N m; infinite with the curve off.
944 pub knees: [f64; 2],
945 /// [K2, K3], N m/rad.
946 pub upper: [f64; 2],
947 /// With effects.gearbox_mesh_friction: the stiffness of the mesh friction's bristle against the housing (presliding),
948 /// N m/rad at the output (N/m behind a screw, rack or drum: `Converter::apply`), `MESH_STIFFNESS` times K1; 0 with
949 /// the effect off (`mesh_friction`).
950 pub mesh_stiffness: f64,
951 /// The output angle at which the mesh friction's bristle is relaxed, where the last step ended (`commit`); NaN before
952 /// the first step (no friction yet).
953 pub mesh_anchor: f64,
954 /// Behind a converter with a damper (`Converter::apply_back`): the damper bridges the gear's spring and not the
955 /// converter's in series with it, a three-element (Zener) solid. It stands here in its Maxwell form, the series
956 /// spring as above in parallel with an arm of a spring K_m (`relax_stiffness`, N/m) and a damper of time constant
957 /// tau (`relax_time`, s) in series, whose end u is a state of the machine (`arm`). 0 for none: the damping then
958 /// bridges the whole spring (`damping`), as it does in the slow limit of an arm faster than the integrator follows.
959 pub relax_stiffness: f64,
960 pub relax_time: f64,
961 /// Behind a ball screw with effects.screw_stiffness_with_position: the shaft's compliance follows the nut
962 /// (`TravelCompliance`); the fields above hold it at the reference position. None: one stiffness for the stroke.
963 pub travel: Option<TravelCompliance>,
964}
965
966/// A ball screw shaft's axial compliance as the nut travels (effects.screw_stiffness_with_position): the shaft between
967/// the fixed bearing and the nut, a / (E A) with the nut `a` from it, or a (L - a) / (E A L) where both ends hold it
968/// axially (fixed-fixed); a = |q - fixed_bearing_at| for the joint's travel q. The gear's springs were put in series with
969/// the screw at `reference` (m/N, the shaft's compliance there); at q they are in series with the difference too
970/// (`Gearbox::at`). The nut's distance is clamped as `transmission::BallScrew::stiffness` clamps it.
971///
972/// The screw's damper keeps its damping ratio along the stroke: c_c = 2 zeta sqrt(K_c m) at the screw's stiffness K_c
973/// where the nut is (a loss factor eta = 2 zeta gives the same, eta K_c / omega at the screw's own omega =
974/// sqrt(K_c / m)), so c_c(q) = c_c sqrt(K_c(q) / K_c) of the reference's; with the gear's damper the two in series are
975/// laid out anew there (`series_dampers`).
976#[derive(Debug, Clone, Copy, PartialEq)]
977pub struct TravelCompliance {
978 /// E A of the root section, N.
979 pub ae: f64,
980 pub length: f64,
981 pub both_ends: bool,
982 /// The joint's travel at which the fixed bearing stands, m.
983 pub fixed_bearing_at: f64,
984 pub reference: f64,
985 /// The gear's own spring and damper at the joint, K_g (N/m) and c_g (N s/m), as `Converter::apply_back` puts them
986 /// in series with the screw (`BackDriven::apply_to`).
987 pub gear: [f64; 2],
988 /// The screw's K_c (N/m) and its damper c_c (N s/m) at the reference; K_c 0: the dampers keep the reference's.
989 pub converter: [f64; 2],
990}
991
992/// Two damped springs in series with a massless node between them (`transmission::Converter::apply_back`): the gear's
993/// K_g with c_g across it alone, the converter's K_c with c_c across it alone. Beside their series spring they are a
994/// damper b = c_g c_c / C and a Maxwell arm K_m = (K_g c_c - K_c c_g)^2 / (S C^2) of time constant tau = C / S, with
995/// S = K_g + K_c and C = c_g + c_c: (b, K_m, tau). All 0 where neither has a damper.
996pub fn series_dampers(k_g: f64, c_g: f64, k_c: f64, c_c: f64) -> (f64, f64, f64) {
997 let (sum, dampers) = (k_c + k_g, c_g + c_c);
998 if dampers <= 0.0 {
999 return (0.0, 0.0, 0.0);
1000 }
1001 (c_g * c_c / dampers, (k_g * c_c - k_c * c_g).powi(2) / (sum * dampers * dampers), dampers / sum)
1002}
1003
1004impl TravelCompliance {
1005 /// The series dampers (`series_dampers`) with the screw's compliance dc from the reference's: K_c = 1 / (1 / K_c0 +
1006 /// dc), c_c = c_c0 sqrt(K_c / K_c0). [b, K_m, tau, dK_m / d(dc)]; None where `converter` is not set.
1007 pub fn dampers(&self, dc: f64) -> Option<[f64; 4]> {
1008 let ([k_g, c_g], [k0, c0]) = (self.gear, self.converter);
1009 if k0 <= 0.0 {
1010 return None;
1011 }
1012 let k_c = 1.0 / (1.0 / k0 + dc);
1013 let c_c = c0 * (k_c / k0).sqrt();
1014 let (b, arm, tau) = series_dampers(k_g, c_g, k_c, c_c);
1015 let (sum, dampers) = (k_c + k_g, c_g + c_c);
1016 // dK_m / dK_c with c_c' = c_c / (2 K_c): 2 N N' / (S C^2) - K_m / S - 2 K_m c_c' / C, N = K_g c_c - K_c c_g.
1017 let slope = if dampers > 0.0 {
1018 let rate = c_c / (2.0 * k_c);
1019 let n = k_g * c_c - k_c * c_g;
1020 2.0 * n * (k_g * rate - c_g) / (sum * dampers * dampers) - arm / sum - 2.0 * arm * rate / dampers
1021 } else {
1022 0.0
1023 };
1024 // dK_c / d(dc) = -K_c^2.
1025 Some([b, arm, tau, -slope * k_c * k_c])
1026 }
1027
1028 /// The shaft's compliance with the nut `a` from the fixed bearing, and its slope in a.
1029 pub fn shaft(&self, a: f64) -> (f64, f64) {
1030 let (l, lo) = (self.length, 1e-3 * self.length);
1031 let inside = a > lo && a < l;
1032 let x = a.clamp(lo, l);
1033 if self.both_ends {
1034 let rest = (l - x).max(lo);
1035 (x * rest / (self.ae * l), if inside && l - x > lo { (l - 2.0 * x) / (self.ae * l) } else { 0.0 })
1036 } else {
1037 (x / self.ae, if inside { 1.0 / self.ae } else { 0.0 })
1038 }
1039 }
1040
1041 /// The compliance at travel q less the reference's, and its slope in q.
1042 pub fn delta(&self, q: f64) -> (f64, f64) {
1043 let d = q - self.fixed_bearing_at;
1044 let (c, slope) = self.shaft(d.abs());
1045 (c - self.reference, slope * d.signum())
1046 }
1047}
1048
1049/// The mesh friction's bristle stiffness over K1 where `gearbox.mesh_stiffness_factor` is absent: K1 itself, as the
1050/// hysteresis's Dahl stiffness (`gearbox.hysteresis_stiffness_factor`). Presliding then takes mu
1051/// of the gear's twist under the same torque (20 % at an efficiency of 0.8), and the friction a reversal of 2 mu of an
1052/// amplitude to turn round, which lowers the damping of a small ring below the friction law's (see the tests). The
1053/// energy budget does not choose it: with the friction booked as its whole power the belt axes, whose light pulleys
1054/// stick to the housing first, close their passes at K1, 3 K1 and 10 K1 alike (the one-axis belt drive under 1e-6 unaccounted,
1055/// gearbox loss 3.04659 J at all three; the T-shaped belt gantry 4e-6, 8.70004, 8.70027 and 8.70029 J; with the friction off 3.04944
1056/// and 8.82445 J). (The 1.4 and 2.0 % they missed at 10 K1 were the earlier bookkeeping's, of the store's rate.)
1057pub const MESH_STIFFNESS: f64 = 1.0;
1058
1059#[derive(Debug, Clone, Copy)]
1060pub struct GearTorque {
1061 /// Torque driving the output shaft.
1062 pub output: f64,
1063 /// Reaction that the motor shaft has to overcome.
1064 pub rotor: f64,
1065}
1066
1067/// Below this power the efficiency fades out, so a gearbox at rest has no torque step.
1068const EFFICIENCY_FADE_W: f64 = 0.5;
1069
1070/// What a sub-step h may be of the efficiency switch's time J / c on the inertia J it acts on (`fade_substeps`), kappa:
1071/// c h' / J = kappa within the refined sub-step h'. 1 gives the holds of 0.5 to 1e-8 of their force and the budgets to
1072/// three digits at half the cuts; 2, inside RK4's bound of 2.8 for a pure damper, does not (a lift on a compliant base
1073/// held 27 350.0 N instead of 27 346.75 N, its budget 1.5e-5 off).
1074const FADE_KAPPA: f64 = 1.0;
1075
1076/// How far off zero power (in widths of the switch, 0.5 W) a gear's power counts as near it at a step's start, where the
1077/// step is refined for the switch (`Gearbox::fade_damping`): a step can carry a gear that far into it.
1078const FADE_NEAR: f64 = 40.0;
1079
1080/// The sub-steps a sub-step `h` (s) is to be cut into, at least 1, for a switch's damper `damping` (`Gearbox::
1081/// fade_damping`) on the inertia `j` its gear drives (kg m^2, or kg on a travel): c h' / J within `FADE_KAPPA`.
1082pub fn fade_substeps(damping: f64, h: f64, j: f64) -> u32 {
1083 let n = (damping * h / (FADE_KAPPA * j)).ceil();
1084 if n.is_finite() && n > 1.0 { n.min(u32::MAX as f64) as u32 } else { 1 }
1085}
1086
1087/// A rigid solve's loss factors (`Gearbox::loss_factor`) at their fixed point: each is taken of the torque going into its
1088/// gearbox, which depends on the acceleration the factors give, so `next` gives the factors at the acceleration solved
1089/// with `loss`, from `start` (all 1, loss-free) until they settle to rounding. The efficiency's fade over the power is
1090/// weak (each round takes some 0.1 of what is left, on the linkage at 0.01 m/s), so a few rounds do; a loss-free one
1091/// settles in one.
1092pub fn settled_loss<T: AsRef<[f64]>>(start: T, mut next: impl FnMut(&T) -> T) -> T {
1093 let mut loss = start;
1094 for _ in 0..12 {
1095 let new = next(&loss);
1096 let settled = new.as_ref().iter().zip(loss.as_ref()).all(|(a, b)| (a - b).abs() <= 1e-14);
1097 loss = new;
1098 if settled {
1099 break;
1100 }
1101 }
1102 loss
1103}
1104
1105impl Gearbox {
1106 pub fn from_config(cfg: &Config) -> Result<Self> {
1107 // A negative backlash would turn the dead zone inside out (and `clamp` panics on that).
1108 let backlash = cfg.non_negative("gearbox.backlash_rad")?;
1109 let stiffness = cfg.positive("gearbox.stiffness_nm_rad")?;
1110 let lost = cfg.bool("effects.gearbox_lost_motion")?;
1111 let (band, width) =
1112 (cfg.non_negative("gearbox.lost_motion_band_rad")?, cfg.non_negative("gearbox.hysteresis_rad")?);
1113 let knees = [cfg.positive("gearbox.stiffness_t1_nm")?, cfg.positive("gearbox.stiffness_t2_nm")?];
1114 let upper = [cfg.positive("gearbox.stiffness_k2_nm_rad")?, cfg.positive("gearbox.stiffness_k3_nm_rad")?];
1115 if knees[1] < knees[0] {
1116 return Err(ConfigError::Invalid("gearbox.stiffness_t2_nm".into()));
1117 }
1118 Ok(Self {
1119 ratio: cfg.positive("gearbox.ratio")?,
1120 stiffness,
1121 damping: cfg.non_negative("gearbox.damping_nm_s_rad")?,
1122 half_backlash: if cfg.bool("effects.gearbox_backlash")? { 0.5 * backlash } else { 0.0 },
1123 // With the feedback, at ambient; the machine follows the gearbox's temperature (`ThermalFeedback`).
1124 efficiency: match ThermalFeedback::from_config(cfg)? {
1125 Some(t) => t.gearbox_efficiency(0.0),
1126 None => Self::configured_efficiency(cfg)?,
1127 },
1128 band: if lost { band } else { 0.0 },
1129 band_compliance: 0.0,
1130 hysteresis: if lost { 0.5 * stiffness * width } else { 0.0 },
1131 dahl_stiffness: stiffness * Self::optional_factor(cfg, "gearbox.hysteresis_stiffness_factor")?,
1132 back_ratio: 1.0,
1133 anchor: [f64::NAN, 0.0],
1134 twist_scale: 1.0,
1135 knees: if cfg.bool("effects.gearbox_stiffness_curve")? { knees } else { [f64::INFINITY; 2] },
1136 upper,
1137 // A config without the switch (one written before 15 November 2026) has the faded efficiency.
1138 mesh_stiffness: if cfg.get("effects.gearbox_mesh_friction").is_ok()
1139 && cfg.bool("effects.gearbox_mesh_friction")?
1140 {
1141 stiffness * Self::optional_factor(cfg, "gearbox.mesh_stiffness_factor")?
1142 } else {
1143 0.0
1144 },
1145 mesh_anchor: f64::NAN,
1146 relax_stiffness: 0.0,
1147 relax_time: 0.0,
1148 travel: None,
1149 })
1150 }
1151
1152 /// The gear with the nut at `travel` along the screw: behind a screw whose stiffness follows the nut (`travel`), its
1153 /// springs K1, K2, K3 each in series with the shaft's compliance there less the reference's, dc, and the band's
1154 /// series spring c + dc (the flanks' own k_f stays: 1 / k_f = 1 / K1 - c). The screw's damper keeps its damping
1155 /// ratio, and it and the gear's damper in series are laid out at the screw's stiffness there, the damper and the
1156 /// Maxwell arm (`TravelCompliance::dampers`; an arm the build folded into the damper, faster than the integrator
1157 /// follows, stays folded). Itself otherwise. The nut sits on the shaft's point the rotor has turned to it, the rotor's
1158 /// angle over the ratio (`nut`); at a pose the joint's travel, which is that less the twist.
1159 ///
1160 /// The hysteresis is a friction across the gear's own flanks, so it acts on the gear's own twist, which the spring's
1161 /// force tells (F / K_g), not on the twist through the gear and the screw, which grows with the shaft at a force: its
1162 /// state lives on y = r x, x the contact twist and r = K1(here) / K1 (the reference's K1 x and K1(here) x are the
1163 /// same force), with the reference's T_h and sigma. Seen in x that is T_h r, sigma r^2 and the anchor (y0 / r, r z0),
1164 /// its twist kept as y0 with r beside it (`twist_scale`):
1165 /// the friction at the joint, K1 lever T_h / K_g, follows K1 as `Converter::apply_back` has it at the reference, the
1166 /// loop keeps its width 2 T_h / K1 in the twist, and a load carried along the stroke leaves the state where it was.
1167 /// Its store z^2 / (2 sigma) is the reference's in y; what the nut's place adds to y, x r'(s), is work on it the rotor
1168 /// does (`hysteresis_place`). The mesh friction's bristle, a stiffness of the gear's own flanks as the hysteresis's
1169 /// Dahl stiffness is, follows K1 as well: sigma_m r (its bound follows the spring's force there).
1170 pub fn at(&self, travel: f64) -> std::borrow::Cow<'_, Self> {
1171 let Some(t) = self.travel else { return std::borrow::Cow::Borrowed(self) };
1172 let dc = t.delta(travel).0;
1173 let series = |k: f64| 1.0 / (1.0 / k + dc);
1174 let r = series(self.stiffness) / self.stiffness;
1175 let mut here = Self {
1176 stiffness: series(self.stiffness),
1177 upper: self.upper.map(series),
1178 band_compliance: self.band_compliance + dc,
1179 hysteresis: self.hysteresis * r,
1180 dahl_stiffness: self.dahl_stiffness * r * r,
1181 mesh_stiffness: self.mesh_stiffness * r,
1182 anchor: [self.anchor[0], self.anchor[1] * r],
1183 twist_scale: r,
1184 travel: None,
1185 ..self.clone()
1186 };
1187 // At the reference itself the build's dampers, to the bit.
1188 if let Some([b, arm, tau, _]) = t.dampers(dc).filter(|_| dc != 0.0) {
1189 if self.relax_stiffness > 0.0 {
1190 (here.damping, here.relax_stiffness, here.relax_time) = (b, arm, tau);
1191 } else {
1192 here.damping = b + arm * tau;
1193 }
1194 }
1195 std::borrow::Cow::Owned(here)
1196 }
1197
1198 /// The gear where the screw behind it is softest over the joint's travel `lo..=hi` (`at`): the shaft's compliance
1199 /// grows with the nut's distance from the fixed bearing, so an end of the travel, or with both ends held the
1200 /// shaft's middle where the travel reaches it. Itself without a screw that follows the nut.
1201 pub fn softest(&self, (lo, hi): (f64, f64)) -> std::borrow::Cow<'_, Self> {
1202 let Some(t) = self.travel else { return std::borrow::Cow::Borrowed(self) };
1203 let middle = [-0.5, 0.5].map(|s| (t.fixed_bearing_at + s * t.length).clamp(lo, hi));
1204 let at = [lo, hi, middle[0], middle[1]].into_iter().max_by(|a, b| t.delta(*a).0.total_cmp(&t.delta(*b).0));
1205 self.at(at.unwrap_or(lo))
1206 }
1207
1208 /// F^2 K_m'(s) / (2 K_m^2): what the Maxwell arm's store K_m (x - u)^2 / 2 gains per unit of the nut's place s at a
1209 /// fixed x and u, F = K_m (x - u) the arm's force (`at`: K_m follows the screw's stiffness). As with the spring's
1210 /// `travel_force`, the rotor feels it. 0 without an arm or with the dampers not laid out along the stroke.
1211 fn arm_place(&self, s: f64, force: f64) -> f64 {
1212 let Some(t) = self.travel else { return 0.0 };
1213 if self.relax_stiffness == 0.0 || force == 0.0 {
1214 return 0.0;
1215 }
1216 let (dc, slope) = t.delta(s);
1217 let Some([_, arm, _, rate]) = t.dampers(dc) else { return 0.0 };
1218 0.5 * force * force * rate * slope / (arm * arm)
1219 }
1220
1221 /// z x r'(s) / r: the work per unit of the nut's place s on the hysteresis's state, whose twist y = r x (`at`) the place
1222 /// moves at a fixed x by x r'(s) against its torque z / r (z the torque in x at the place). As with the spring's
1223 /// `travel_force`, the rotor feels it. r'(s) / r = -K1(s) c'(s), c the shaft's compliance. 0 without hysteresis or
1224 /// `travel`.
1225 fn hysteresis_place(&self, rotor_angle: f64, out_angle: f64, rate: f64) -> f64 {
1226 let Some(t) = self.travel.filter(|_| self.hysteresis > 0.0) else { return 0.0 };
1227 let (twist, e) = self.beyond(rotor_angle, out_angle);
1228 let x = Self::contact(twist, e);
1229 if x == 0.0 {
1230 return 0.0;
1231 }
1232 let s = self.nut(rotor_angle);
1233 let (dc, slope) = t.delta(s);
1234 let z = self.at(s).hysteresis_torque(x, rate).0;
1235 -z * x * slope / (1.0 / self.stiffness + dc)
1236 }
1237
1238 /// The nut's place along the screw in the dynamics: the shaft's point the rotor has turned to it, s = phi / i.
1239 fn nut(&self, rotor_angle: f64) -> f64 {
1240 rotor_angle / self.ratio
1241 }
1242
1243 /// T^2 c'(s) / 2, what the spring's energy falls by per unit of the nut's place s at a fixed twist, T the spring's
1244 /// force (`spring`): its complementary energy holds c T^2 / 2 of the compliance c(s) in series, so at a fixed twist
1245 /// dV / dc = -T^2 / 2. With s = phi / i the rotor feels it, not the nut: the shaft between the bearing and the nut
1246 /// grows by the material the rotor turns into it, and the nut passes the shaft's force T alone. 0 without `travel`.
1247 fn travel_force(&self, rotor_angle: f64, out_angle: f64) -> f64 {
1248 let Some(t) = self.travel else { return 0.0 };
1249 let (_, e) = self.beyond(rotor_angle, out_angle);
1250 if e == 0.0 {
1251 return 0.0;
1252 }
1253 let s = self.nut(rotor_angle);
1254 let spring = self.at(s).spring(e).0;
1255 0.5 * spring * spring * t.delta(s).1
1256 }
1257
1258 /// An optional positive factor on K1 (1 where the key is absent, as the shipped files have it).
1259 fn optional_factor(cfg: &Config, key: &str) -> Result<f64> {
1260 if cfg.get(key).is_ok() { cfg.positive(key) } else { Ok(MESH_STIFFNESS) }
1261 }
1262
1263 /// The efficiency as configured: 1 with effects.gearbox_efficiency off. With effects.gearbox_drag the teeth's
1264 /// alone (`GearDrag::tooth_efficiency`): `gearbox.efficiency` holds at `gearbox.efficiency_torque_nm` with the drag.
1265 pub fn configured_efficiency(cfg: &Config) -> Result<f64> {
1266 let efficiency = cfg.positive("gearbox.efficiency")?;
1267 if efficiency > 1.0 {
1268 return Err(ConfigError::Invalid("gearbox.efficiency".into()));
1269 }
1270 let at = cfg.positive("gearbox.efficiency_torque_nm")?;
1271 if !cfg.bool("effects.gearbox_efficiency")? {
1272 return Ok(1.0);
1273 }
1274 Ok(GearDrag::from_config(cfg)?.tooth_efficiency(efficiency, cfg.positive("gearbox.ratio")?, at))
1275 }
1276
1277 /// A ratio of 1 is a direct drive: the table describes the coupling between motor and pulley, there is no
1278 /// gearbox, and what `loss_power` gives is the coupling's damping.
1279 pub fn is_coupling(&self) -> bool {
1280 self.ratio == 1.0
1281 }
1282
1283 /// The flanks can separate: a backlash or a lost-motion band.
1284 fn has_play(&self) -> bool {
1285 self.half_backlash > 0.0 || self.band > 0.0
1286 }
1287
1288 /// The flanks' own K1, k_f = K1 / (1 - c K1) (K1 itself without a series spring), and the torque T_b = k_f b / 2 at
1289 /// which they leave the band.
1290 fn flanks(&self) -> (f64, f64) {
1291 let kf = self.stiffness / (1.0 - self.band_compliance * self.stiffness);
1292 (kf, 0.5 * kf * self.band)
1293 }
1294
1295 /// The spring's (torque, energy) at a twist `e` >= 0 beyond the dead zone: the lost-motion band, then the three
1296 /// segments in x = e - b/2.
1297 ///
1298 /// In the band the flanks twist e_f = sqrt(2 b T / k_f) and the series spring c T, so e = e_f + c T, a quadratic in
1299 /// sqrt(T), with the energy T e_f / 3 + c T^2 / 2; the band ends at e = b + c T_b. Beyond it the line K1 x reaches
1300 /// T_b at x = b/2 + c T_b (1 / K1 = 1 / k_f + c), and the energy there is k_f b^2 / 24 + K1 x^2 / 2. Without the
1301 /// series spring T = K1 e^2 / (2 b).
1302 pub fn spring(&self, e: f64) -> (f64, f64) {
1303 let (k1, b, c) = (self.stiffness, self.band, self.band_compliance);
1304 let (kf, tb) = self.flanks();
1305 if e < b && c == 0.0 {
1306 return (k1 * e * e / (2.0 * b), k1 * e * e * e / (6.0 * b));
1307 }
1308 if e < b + c * tb {
1309 let a = (2.0 * b / kf).sqrt();
1310 let s = 2.0 * e / (a + (a * a + 4.0 * c * e).sqrt());
1311 let t = s * s;
1312 return (t, t * (a * s / 3.0 + 0.5 * c * t));
1313 }
1314 let (x, base) = (e - 0.5 * b, kf * b * b / 24.0);
1315 let ([t1, t2], [k2, k3]) = (self.knees, self.upper);
1316 let x1 = t1 / k1;
1317 if x <= x1 {
1318 return (k1 * x, base + 0.5 * k1 * x * x);
1319 }
1320 let (x2, e1) = (x1 + (t2 - t1) / k2, base + 0.5 * t1 * x1);
1321 if x <= x2 {
1322 let t = t1 + k2 * (x - x1);
1323 return (t, e1 + 0.5 * (t1 + t) * (x - x1));
1324 }
1325 let t = t2 + k3 * (x - x2);
1326 (t, e1 + 0.5 * (t1 + t2) * (x2 - x1) + 0.5 * (t2 + t) * (x - x2))
1327 }
1328
1329 /// The twist beyond the dead zone that the spring needs for `torque` >= 0: the inverse of `spring`.
1330 pub fn spring_twist(&self, torque: f64) -> f64 {
1331 let (k1, b) = (self.stiffness, self.band);
1332 let (kf, tb) = self.flanks();
1333 if torque < tb {
1334 return (2.0 * b * torque / kf).sqrt() + self.band_compliance * torque;
1335 }
1336 let ([t1, t2], [k2, k3]) = (self.knees, self.upper);
1337 let x = if torque <= t1 {
1338 torque / k1
1339 } else if torque <= t2 {
1340 t1 / k1 + (torque - t1) / k2
1341 } else {
1342 t1 / k1 + (t2 - t1) / k2 + (torque - t2) / k3
1343 };
1344 x + 0.5 * b
1345 }
1346
1347 /// The twist at the output, rotor over ratio less output, and how far it is beyond the dead zone (>= 0).
1348 fn beyond(&self, rotor_angle: f64, out_angle: f64) -> (f64, f64) {
1349 let twist = rotor_angle / self.ratio - out_angle;
1350 (twist, (twist.abs() - self.half_backlash).max(0.0))
1351 }
1352
1353 /// Factor on a torque at the output: efficiency when driving, 1 / (back efficiency) when driven back, the back
1354 /// efficiency being the efficiency times `back_ratio` (the same, 1 / efficiency, for a gear that loses alike).
1355 pub fn loss_factor(&self, output_torque: f64, output_speed: f64) -> f64 {
1356 let t = (output_torque * output_speed / EFFICIENCY_FADE_W).tanh();
1357 if t >= 0.0 { self.efficiency.powf(t) } else { (self.efficiency * self.back_ratio).min(1.0).powf(t) }
1358 }
1359
1360 /// The damper the efficiency's switch puts on the output's speed while the gear passes `output_torque` near zero
1361 /// power: the two flanks meet over tanh(T w / 0.5 W), so the factor changes with w by up to T^2 |ln eta| / 0.5 W
1362 /// (N m s/rad, or N s/m on a travel). 0 while the power `output_torque` times `output_speed` stands more than
1363 /// `FADE_NEAR` times the 0.5 W off zero, where the factor stands still (`fade_substeps` refines the step by it).
1364 /// 0 too where the mesh friction holds (its anchor committed, `torque_arm`): the friction's bristle then sticks and
1365 /// slides between the drive's and the driven-back bound, and the faded factor is not in the torque at all.
1366 pub fn fade_damping(&self, output_torque: f64, output_speed: f64) -> f64 {
1367 if self.mesh_stiffness > 0.0 && !self.mesh_anchor.is_nan() {
1368 return 0.0;
1369 }
1370 if (output_torque * output_speed).abs() > FADE_NEAR * EFFICIENCY_FADE_W {
1371 return 0.0;
1372 }
1373 let back = (self.efficiency * self.back_ratio).min(1.0);
1374 output_torque * output_torque * self.efficiency.ln().abs().max(back.ln().abs()) / EFFICIENCY_FADE_W
1375 }
1376
1377 /// The contact twist x: the twist beyond the dead zone with its sign, 0 inside it.
1378 fn contact(twist: f64, e: f64) -> f64 {
1379 if e == 0.0 { 0.0 } else { e.copysign(twist) }
1380 }
1381
1382 /// The hysteresis torque z at the contact twist `x` and its slope dz/dx: Dahl's law solved from the anchor for a twist
1383 /// that ran one way to `x`, z = s T_h - (s T_h - z0) exp(-sigma |x - x0| / T_h), s the sign of x - x0, or of the
1384 /// twist's `rate` at the anchor itself (where a step has just ended). Behind a screw whose stiffness follows the nut
1385 /// the anchor's twist is y0 and x - x0 is (x r - y0) / r (`twist_scale`), and at the anchor `rate` is the gear's own
1386 /// twist's, y' / r (`loss_arm`).
1387 pub fn hysteresis_torque(&self, x: f64, rate: f64) -> (f64, f64) {
1388 let (th, [y0, z0], r) = (self.hysteresis, self.anchor, self.twist_scale);
1389 if th == 0.0 || y0.is_nan() {
1390 return (0.0, 0.0);
1391 }
1392 let y = x * r;
1393 let s = if y > y0 || (y == y0 && rate >= 0.0) { 1.0 } else { -1.0 };
1394 let z = s * th - (s * th - z0) * (-self.dahl_stiffness * (y - y0).abs() / r / th).exp();
1395 (z, self.dahl_stiffness * (1.0 - s * z / th))
1396 }
1397
1398 /// The hysteresis anchors of `gears`, two numbers each, and the mesh friction's where it has one: what `commit`
1399 /// carries between steps (`Machine::memory`).
1400 pub fn anchors<'a>(gears: impl IntoIterator<Item = &'a Gearbox>) -> Vec<f64> {
1401 gears
1402 .into_iter()
1403 .flat_map(|g| g.anchor.into_iter().chain((g.mesh_stiffness > 0.0).then_some(g.mesh_anchor)))
1404 .collect()
1405 }
1406
1407 /// Sets back what `anchors` gave (`Machine::set_memory`).
1408 pub fn set_anchors<'a>(gears: impl IntoIterator<Item = &'a mut Gearbox>, memory: &[f64]) {
1409 let mut memory = memory.iter().copied();
1410 for g in gears {
1411 if let (Some(x), Some(z)) = (memory.next(), memory.next()) {
1412 g.anchor = [x, z];
1413 }
1414 if g.mesh_stiffness > 0.0
1415 && let Some(a) = memory.next()
1416 {
1417 g.mesh_anchor = a;
1418 }
1419 }
1420 }
1421
1422 /// Ends a step: the hysteresis's state moves on to the twist the step ended at (`Machine::after_step`).
1423 pub fn commit(&mut self, rotor_angle: f64, out_angle: f64) {
1424 // The mesh friction first, with the hysteresis's torque from its anchor as the step had it, and its bristle
1425 // where the nut is (`at`).
1426 if self.mesh_stiffness > 0.0 {
1427 let here = self.at(self.nut(rotor_angle));
1428 let f = here.mesh_friction(self.held_torque(rotor_angle, out_angle), out_angle);
1429 self.mesh_anchor = out_angle - f / here.mesh_stiffness;
1430 }
1431 if self.hysteresis == 0.0 {
1432 return;
1433 }
1434 let (twist, e) = self.beyond(rotor_angle, out_angle);
1435 let x = Self::contact(twist, e);
1436 // Behind a screw whose stiffness follows the nut, kept on the reference's twist y = r x (`at`).
1437 let here = self.at(self.nut(rotor_angle));
1438 let r = here.twist_scale;
1439 self.anchor = [x * r, here.hysteresis_torque(x, 0.0).0 / r];
1440 }
1441
1442 /// The torques without the Maxwell arm (`arm`): a gear's whole torque where it has none.
1443 pub fn torque(&self, rotor_angle: f64, rotor_speed: f64, out_angle: f64, out_speed: f64) -> GearTorque {
1444 debug_assert!(self.relax_stiffness == 0.0, "a gear with a Maxwell arm takes its state: `torque_with`");
1445 self.torque_arm(rotor_angle, rotor_speed, out_angle, out_speed, 0.0)
1446 }
1447
1448 /// `torque` with the Maxwell arm at its state `u` (`arm`).
1449 pub fn torque_with(
1450 &self,
1451 rotor_angle: f64,
1452 rotor_speed: f64,
1453 out_angle: f64,
1454 out_speed: f64,
1455 u: f64,
1456 ) -> GearTorque {
1457 let arm = self.arm(rotor_angle, out_angle, u).0;
1458 self.torque_arm(rotor_angle, rotor_speed, out_angle, out_speed, arm)
1459 }
1460
1461 /// `torque` with the arm's force `arm` beside the damping: the flanks pass it as they do the damping's, nothing
1462 /// within the dead zone.
1463 fn torque_arm(&self, rotor_angle: f64, rotor_speed: f64, out_angle: f64, out_speed: f64, arm: f64) -> GearTorque {
1464 if self.travel.is_some() {
1465 // The springs at the nut's place, and where the flanks pass a torque the rotor feels the place's own force:
1466 // its reaction is dV / dphi = (T - T^2 c' / 2 + F^2 K_m' / (2 K_m^2)) / i, the arm's store's too, and the
1467 // work the place does on the hysteresis's state (`hysteresis_place`).
1468 let s = self.nut(rotor_angle);
1469 let mut t = self.at(s).torque_arm(rotor_angle, rotor_speed, out_angle, out_speed, arm);
1470 if t.rotor != 0.0 {
1471 let rate = rotor_speed / self.ratio - out_speed;
1472 let place = self.arm_place(s, arm) + self.hysteresis_place(rotor_angle, out_angle, rate);
1473 t.rotor -= (self.travel_force(rotor_angle, out_angle) - place) / self.ratio;
1474 }
1475 return t;
1476 }
1477 let (twist, e) = self.beyond(rotor_angle, out_angle);
1478 // In the backlash the flanks are apart; without play they touch at zero twist too, where the hysteresis holds.
1479 if e == 0.0 && (self.has_play() || self.hysteresis == 0.0) {
1480 return GearTorque { output: 0.0, rotor: 0.0 };
1481 }
1482 let rate = rotor_speed / self.ratio - out_speed;
1483 let held = self.spring(e).0.copysign(twist) + self.hysteresis_torque(Self::contact(twist, e), rate).0;
1484 let torque = held + self.damping * rate + arm;
1485 // Tooth flanks can push but not pull: while they separate fast, the damping must not reverse the torque.
1486 if self.has_play() && torque * twist < 0.0 {
1487 return GearTorque { output: 0.0, rotor: 0.0 };
1488 }
1489 // Before the first step's commit (and in a machine that does not commit its gears) the faded efficiency.
1490 if self.mesh_stiffness > 0.0 && !self.mesh_anchor.is_nan() {
1491 return GearTorque { output: torque - self.mesh_friction(held, out_angle), rotor: torque / self.ratio };
1492 }
1493 GearTorque { output: torque * self.loss_factor(torque, out_speed), rotor: torque / self.ratio }
1494 }
1495
1496 /// With effects.gearbox_mesh_friction: the friction in the mesh at the output, against the housing, when the gear
1497 /// passes `held` (its spring's and hysteresis's torque) at the output angle `out_angle`. It opposes the output's
1498 /// motion, bounded by mu |held| with mu = 1 - eta (eta the teeth's efficiency), so that driving the output gets
1499 /// eta held and driven back it takes (1 + mu) held: the back-driving efficiency is 1 / (1 + mu) = 1 / (2 - eta).
1500 /// A gear with its own back efficiency (`back_ratio` r not 1: a screw's or a worm's lead angle) is driven back at
1501 /// exactly eta r, as `loss_factor` has it: the bound there is 1 / (eta r) - 1 (a worm of 0.763 driving and 0.693
1502 /// back would get 0.734 back from r / (2 - eta)). At
1503 /// rest it sticks: an elastic-plastic bristle of `mesh_stiffness` from the anchor where the last step left it, the
1504 /// friction sigma (out - anchor) up to the bound. 0 before the first step's commit (the gear then has the faded
1505 /// efficiency) and with the effect off.
1506 pub fn mesh_friction(&self, held: f64, out_angle: f64) -> f64 {
1507 if self.mesh_stiffness == 0.0 || self.mesh_anchor.is_nan() {
1508 return 0.0;
1509 }
1510 // The friction's sign against the held torque's: with it the output is driven (eta held), against it driven back.
1511 let driving = (1.0 - self.efficiency) * held.abs();
1512 let back = if self.back_ratio == 1.0 {
1513 driving
1514 } else {
1515 (1.0 / (self.efficiency * self.back_ratio) - 1.0).max(0.0) * held.abs()
1516 };
1517 let (lo, hi) = if held >= 0.0 { (-back, driving) } else { (-driving, back) };
1518 (self.mesh_stiffness * (out_angle - self.mesh_anchor)).clamp(lo, hi)
1519 }
1520
1521 /// The torque the spring and hysteresis pass at the rotor and output angles at rest, the damping left out (the
1522 /// friction's bound is on it).
1523 fn held_torque(&self, rotor_angle: f64, out_angle: f64) -> f64 {
1524 let (twist, e) = self.beyond(rotor_angle, out_angle);
1525 if e == 0.0 && (self.has_play() || self.hysteresis == 0.0) {
1526 return 0.0;
1527 }
1528 let here = self.at(self.nut(rotor_angle));
1529 here.spring(e).0.copysign(twist) + here.hysteresis_torque(Self::contact(twist, e), 0.0).0
1530 }
1531
1532 /// The Maxwell arm's force and the rate of its state `u` (`relax_stiffness`): with x the contact twist (0 in the dead
1533 /// zone), F = K_m (x - u) and du/dt = (x - u) / tau. At rest u = x and the arm carries nothing, so the static
1534 /// stiffness is the series spring's. (0, 0) without an arm.
1535 ///
1536 /// For a gear of K1 at the joint, K_g, damping c across it and a converter of K_c in series (node between them
1537 /// massless), the series pair is K_c (K_g + c s) / (K_c + K_g + c s); the arm's K_m = K_c^2 / (K_c + K_g) and
1538 /// tau = c / (K_c + K_g) give the same beside K_s = K_c K_g / (K_c + K_g): K_s + K_m tau s / (1 + tau s). The arm
1539 /// is the K1 line's: over the lost-motion band and the stiffness curve's upper segments the gear is softer, and
1540 /// there the arm stays the K1 line's. In the dead zone its force does not reach the flanks (`torque_with`) and it
1541 /// relaxes towards x = 0 by the same law.
1542 pub fn arm(&self, rotor_angle: f64, out_angle: f64, u: f64) -> (f64, f64) {
1543 if self.relax_stiffness == 0.0 {
1544 return (0.0, 0.0);
1545 }
1546 let here = self.at(self.nut(rotor_angle));
1547 let (twist, e) = self.beyond(rotor_angle, out_angle);
1548 let d = Self::contact(twist, e) - u;
1549 (here.relax_stiffness * d, d / here.relax_time)
1550 }
1551
1552 /// The arm's state at rest: the contact twist, where it carries nothing.
1553 pub fn arm_rest(&self, rotor_angle: f64, out_angle: f64) -> f64 {
1554 let (twist, e) = self.beyond(rotor_angle, out_angle);
1555 Self::contact(twist, e)
1556 }
1557
1558 /// `energy` with the arm's spring at its state `u`, K_m (x - u)^2 / 2 (K_m at the nut's place, `at`).
1559 pub fn energy_with(&self, rotor_angle: f64, out_angle: f64, u: f64) -> f64 {
1560 let f = self.arm(rotor_angle, out_angle, u).0;
1561 let store = || 0.5 * f * f / self.at(self.nut(rotor_angle)).relax_stiffness;
1562 self.energy(rotor_angle, out_angle) + if f == 0.0 { 0.0 } else { store() }
1563 }
1564
1565 /// The viscous damping the gear puts on a ring of `omega` rad/s for the modes: `damping`, and the arm's
1566 /// K_m tau / (1 + (omega tau)^2) (the imaginary part of its K_m i omega tau / (1 + i omega tau) over omega).
1567 pub fn damping_at(&self, omega: f64) -> f64 {
1568 if self.relax_stiffness == 0.0 {
1569 return self.damping;
1570 }
1571 let wt = omega * self.relax_time;
1572 self.damping + self.relax_stiffness * self.relax_time / (1.0 + wt * wt)
1573 }
1574
1575 /// The twist beyond the backlash that transmits `output_torque` at rest, with its sign: the spring's alone.
1576 pub fn spring_twist_signed(&self, output_torque: f64) -> f64 {
1577 if output_torque == 0.0 { 0.0 } else { self.spring_twist(output_torque.abs()).copysign(output_torque) }
1578 }
1579
1580 /// Twist at rest that transmits `output_torque`, on the matching side of the backlash.
1581 pub fn static_twist(&self, output_torque: f64) -> f64 {
1582 if output_torque == 0.0 {
1583 0.0
1584 } else {
1585 (self.spring_twist(output_torque.abs()) + self.half_backlash).copysign(output_torque)
1586 }
1587 }
1588
1589 /// `static_twist` at the joint's travel `travel`: the nut on the shaft's point `travel` plus the twist (`at`), which
1590 /// one step from the twist at `travel` finds to (c' x)^2 of it.
1591 pub fn static_twist_at(&self, travel: f64, output_torque: f64) -> f64 {
1592 let first = self.at(travel).static_twist(output_torque);
1593 if self.travel.is_none() {
1594 return first;
1595 }
1596 self.at(travel + first).static_twist(output_torque)
1597 }
1598
1599 /// What the rotor holds at rest, times the ratio, against a torque F at the output with the nut at `travel`: the
1600 /// spring passes F, and behind a screw whose stiffness follows the nut the rotor feels F - F^2 c' / 2
1601 /// (`travel_force`). F itself otherwise.
1602 pub fn held_at(&self, travel: f64, output_torque: f64) -> f64 {
1603 let slope = self.travel.map_or(0.0, |t| t.delta(travel).1);
1604 output_torque - 0.5 * output_torque * output_torque * slope
1605 }
1606
1607 /// The energy in the spring and in the hysteresis's state, z^2 / (2 sigma). Not the mesh friction's bristle: see
1608 /// `loss_power`.
1609 pub fn energy(&self, rotor_angle: f64, out_angle: f64) -> f64 {
1610 let (twist, e) = self.beyond(rotor_angle, out_angle);
1611 let here = self.at(self.nut(rotor_angle));
1612 let z = here.hysteresis_torque(Self::contact(twist, e), 0.0).0;
1613 here.spring(e).1 + if z == 0.0 { 0.0 } else { z * z / (2.0 * here.dahl_stiffness) }
1614 }
1615
1616 /// Power the gearbox takes, W: what the rotor puts in less what the output gives the pulley and what spring and
1617 /// hysteresis store. The efficiency loss, the damping and the hysteresis's friction, s x' z^2 / T_h.
1618 ///
1619 /// The mesh friction counts as F w, all of its power: its bristle's store F^2 / (2 sigma) is neither in `energy`
1620 /// nor taken off here. Its rate, F dF/dt / sigma, depends on whether the bristle sticks or slides, which at a
1621 /// step's end (where `commit` leaves it exactly at its bound) says nothing about the step itself: there the anchor
1622 /// stands, the output runs many bristle lengths (0.1 m/s over 62.5 us is 6e-6 m against mu |held| / sigma = 1e-7 m on
1623 /// a carriage hung in four cables) and the friction slides at the bound throughout, also where the bound grew faster than
1624 /// sigma w at the ends. Booked that way it missed 1.80 J of 38.17 J on that carriage's cycle, at any step
1625 /// (dt / 4 the same), and 10.8 J at 3 sigma. Left out, what is not booked is the store itself, at most
1626 /// (mu |held|)^2 / (2 sigma) per gear: 4e-7 J there.
1627 pub fn loss_power(&self, rotor_angle: f64, rotor_speed: f64, out_angle: f64, out_speed: f64) -> f64 {
1628 self.loss_arm(rotor_angle, rotor_speed, out_angle, out_speed, (0.0, 0.0))
1629 }
1630
1631 /// `loss_power` with the arm at its state `u`: the arm's store (`energy_with`) is taken off too, so that its damper's
1632 /// power, K_m (x - u)^2 / tau, is in the loss.
1633 pub fn loss_power_with(&self, rotor_angle: f64, rotor_speed: f64, out_angle: f64, out_speed: f64, u: f64) -> f64 {
1634 self.loss_arm(rotor_angle, rotor_speed, out_angle, out_speed, self.arm(rotor_angle, out_angle, u))
1635 }
1636
1637 fn loss_arm(&self, rotor_angle: f64, rotor_speed: f64, out_angle: f64, out_speed: f64, arm: (f64, f64)) -> f64 {
1638 let (arm, arm_rate) = arm;
1639 let t = self.torque_arm(rotor_angle, rotor_speed, out_angle, out_speed, arm);
1640 let (twist, e) = self.beyond(rotor_angle, out_angle);
1641 // The arm's store's change with the nut's place (`arm_place`) is stored, not lost.
1642 let place = self.arm_place(self.nut(rotor_angle), arm) * rotor_speed / self.ratio;
1643 if e == 0.0 && self.has_play() {
1644 // The contact twist stands at 0: the arm's store changes by -F du/dt and with its place alone.
1645 return t.rotor * rotor_speed - t.output * out_speed + arm * arm_rate - place;
1646 }
1647 let rate = rotor_speed / self.ratio - out_speed;
1648 let here = self.at(self.nut(rotor_angle));
1649 let x = Self::contact(twist, e);
1650 // The hysteresis's twist y = r x moves with the nut's place too (`hysteresis_place`): its store follows y, and at
1651 // the anchor its branch goes by y' / r = x' + moved s', which a nut travelling at a standing twist turns alone.
1652 let z = here.hysteresis_torque(x, rate).0;
1653 let moved = if z == 0.0 { 0.0 } else { self.hysteresis_place(rotor_angle, out_angle, rate) / z };
1654 let (z, slope) = here.hysteresis_torque(x, rate + moved * rotor_speed / self.ratio);
1655 let stored = if z == 0.0 { 0.0 } else { z * slope / here.dahl_stiffness };
1656 // The store's change with the nut's place, -T^2 c' s' / 2 (`travel_force`), is not lost.
1657 t.rotor * rotor_speed
1658 - t.output * out_speed
1659 - (here.spring(e).0.copysign(twist) + stored) * rate
1660 - stored * moved * rotor_speed / self.ratio
1661 - arm * (rate - arm_rate)
1662 - place
1663 + self.travel_force(rotor_angle, out_angle) * rotor_speed / self.ratio
1664 }
1665}
1666
1667#[cfg(test)]
1668mod tests {
1669 use super::*;
1670
1671 fn belt() -> Belt {
1672 Belt {
1673 ea: 5e5,
1674 damping: 0.0,
1675 damping_time: 0.0,
1676 pretension: 300.0,
1677 slack: true,
1678 mass_per_m: 0.0,
1679 tooth_length: 0.0,
1680 }
1681 }
1682
1683 #[test]
1684 fn belt_tension_is_ea_strain_and_pretension_at_rest() {
1685 let b = belt();
1686 let mat = b.rest_length(1.2);
1687 assert!((b.section(1.2, mat, 0.0, 0.0).tension - 300.0).abs() < 1e-9);
1688 // k = EA / L: 1 mm more on about 1.2 m of belt.
1689 let more = b.section(1.201, mat, 0.0, 0.0).tension - 300.0;
1690 assert!((more - 5e5 * 0.001 / mat).abs() < 1e-6);
1691 }
1692
1693 #[test]
1694 fn belt_tension_cannot_go_below_zero_unless_slack_is_off() {
1695 let mut b = belt();
1696 assert_eq!(b.section(0.99, 1.0, 0.0, 0.0).tension, 0.0);
1697 assert_eq!(b.energy(0.99, 1.0), 0.0);
1698 b.slack = false;
1699 assert!(b.section(0.99, 1.0, 0.0, 0.0).tension < 0.0);
1700 }
1701
1702 #[test]
1703 fn belt_damping_acts_on_the_stretch_rate() {
1704 let mut b = belt();
1705 b.damping = 100.0;
1706 let mat = b.rest_length(1.0);
1707 let still = b.section(1.0, mat, 0.0, 0.0).tension;
1708 assert!((b.section(1.0, mat, 0.5, 0.2).tension - still - 100.0 * 0.3).abs() < 1e-9);
1709 }
1710
1711 /// Material damping c = k tau with k = EA / L: 0.5 m of belt is four times as stiff as 2 m and damps
1712 /// four times as hard.
1713 #[test]
1714 fn material_damping_scales_with_the_section_stiffness() {
1715 let mut b = belt();
1716 b.damping_time = 2e-4;
1717 // Stretching at 0.3 m/s. Short: k = 5e5 / 0.5 = 1e6 N/m, c = 200 N s/m, 60 N.
1718 // Long: k = 5e5 / 2 = 2.5e5 N/m, c = 50 N s/m, 15 N.
1719 for (mat, force) in [(0.5, 60.0), (2.0, 15.0)] {
1720 let still = b.section(mat + 0.001, mat, 0.0, 0.0).tension;
1721 let moving = b.section(mat + 0.001, mat, 0.5, 0.2).tension;
1722 assert!((moving - still - force).abs() < 1e-9, "{mat} m: {} N", moving - still);
1723 }
1724 }
1725
1726 /// Tooth stiffness in series: a 1 m section that ends at one driven pulley with 2e6 N/m of tooth
1727 /// stiffness has 1 / (1 / 5e5 + 1 / 2e6) = 4e5 N/m, the same as 1.25 m of belt.
1728 #[test]
1729 fn teeth_in_mesh_are_a_spring_in_series_with_the_section() {
1730 let mut b = belt();
1731 b.tooth_length = b.ea / 2e6;
1732 let geo = 1.0 + b.tooth_length;
1733 let mat = b.rest_length(geo);
1734 assert!((b.section(geo, mat, 0.0, 0.0).tension - 300.0).abs() < 1e-9);
1735 let more = b.section(geo + 1e-4, mat, 0.0, 0.0).tension - 300.0;
1736 // The belt is already stretched by the pretension, hence the 0.1 % tolerance.
1737 assert!((more - 4e5 * 1e-4).abs() < 1e-3 * 40.0, "{more} N");
1738 }
1739
1740 #[test]
1741 fn belt_forces_are_the_gradient_of_its_energy() {
1742 let b = belt();
1743 let (geo, mat, h) = (1.003, 1.0, 1e-7);
1744 let f = b.section(geo, mat, 0.0, 0.0);
1745 let d_geo = (b.energy(geo + h, mat) - b.energy(geo - h, mat)) / (2.0 * h);
1746 let d_mat = (b.energy(geo, mat + h) - b.energy(geo, mat - h)) / (2.0 * h);
1747 assert!((f.tension - d_geo).abs() < 1e-3, "{} vs {d_geo}", f.tension);
1748 assert!((f.material + d_mat).abs() < 1e-3, "{} vs {d_mat}", f.material);
1749 }
1750
1751 #[test]
1752 fn static_material_meets_the_tension_offsets() {
1753 let b = belt();
1754 let geo = [1.0, 2.0, 1.5];
1755 let total: f64 = geo.iter().map(|g| b.rest_length(*g)).sum();
1756 let mat = b.static_material(&geo, &[0.0, 40.0, 0.0], total);
1757 assert!((mat.iter().sum::<f64>() - total).abs() < 1e-12);
1758 let t: Vec<f64> = geo.iter().zip(&mat).map(|(g, m)| b.section(*g, *m, 0.0, 0.0).tension).collect();
1759 assert!((t[1] - t[0] - 40.0).abs() < 1e-6 && (t[2] - t[0]).abs() < 1e-6, "{t:?}");
1760 }
1761
1762 fn lugre() -> Lugre {
1763 Lugre {
1764 on: true,
1765 sigma0: 5e5,
1766 sigma1: 1500.0,
1767 viscous: 20.0,
1768 coulomb: 15.0,
1769 stiction: 20.0,
1770 stribeck_v: 0.01,
1771 preload: 200.0,
1772 load_dependent: true,
1773 }
1774 }
1775
1776 #[test]
1777 fn lugre_steady_sliding_is_coulomb_plus_viscous() {
1778 let f = lugre();
1779 // Steady state: ds/dt = 0, so s = g(v) sign(v) / sigma0.
1780 for v in [0.5, -0.5] {
1781 let s = f.level(v, 1.0) * v.signum() / f.sigma0;
1782 let (force, s_dot) = f.eval(v, s, 1.0);
1783 assert!(s_dot.abs() < 1e-12);
1784 assert!((force - v.signum() * (15.0 + 20.0 * 0.5)).abs() < 1e-9, "{force}");
1785 }
1786 }
1787
1788 /// The feedforward's force by hand: at 0.5 m/s the steady 15 + 20 x 0.5 = 25 N (tanh(50) is 1 to 1e-43); at the
1789 /// Stribeck speed 0.01 m/s, g = 15 + 5 / e = 16.8394 N times tanh(1) = 0.761594, plus 0.2 N: 13.0248 N; at rest 0.
1790 #[test]
1791 fn the_friction_feedforward_fades_the_level_in_over_the_stribeck_speed() {
1792 let f = lugre();
1793 assert!((f.feedforward(-0.5, 1.0) + 25.0).abs() < 1e-12);
1794 let by_hand = (15.0 + 5.0 * (-1f64).exp()) * 1f64.tanh() + 0.2;
1795 assert!((f.feedforward(0.01, 1.0) - by_hand).abs() < 1e-12 && (by_hand - 13.0248).abs() < 1e-4);
1796 assert_eq!(f.feedforward(0.0, 1.0), 0.0);
1797 }
1798
1799 /// Stiff bristles on a light contact at speed. By hand: 1e6 N/m, a level of 12 N and 2.5 m/s make the
1800 /// bristle state settle at 1e6 * 2.5 / 12 = 2.1e5 1/s. RK4 with the simulator's 15.625 us is stable up to
1801 /// 2.785 / 15.625 us = 1.78e5 1/s: beyond it the friction force grew without bound (seen with these two
1802 /// values at their bounds together in a real-machine config). Capped at 1e5 1/s the state settles, and
1803 /// sliding takes the level plus the viscous part as before: 12 N + 20 N s/m * 2.5 m/s = 62 N.
1804 #[test]
1805 fn lugre_with_stiff_bristles_at_speed_stays_stable_and_slides_at_its_level() {
1806 let l = Lugre { sigma0: 1e6, coulomb: 12.0, stiction: 20.0, ..lugre() };
1807 let (v, h, mut s) = (2.5, 15.625e-6, 0.0);
1808 for _ in 0..2000 {
1809 let rate = |s: f64| l.eval(v, s, 1.0).1;
1810 let (k1, k2) = (rate(s), rate(s + 0.5 * h * rate(s)));
1811 let k3 = rate(s + 0.5 * h * k2);
1812 s += h / 6.0 * (k1 + 2.0 * k2 + 2.0 * k3 + rate(s + h * k3));
1813 }
1814 let (force, s_dot) = l.eval(v, s, 1.0);
1815 assert!((force - 62.0).abs() < 1e-6 && s_dot.abs() < 1e-9, "{force} N, bristles moving at {s_dot} m/s");
1816 // Below the cap nothing has changed: the force is sigma0 s + sigma1 ds/dt + viscous v with ds/dt = v - rate s.
1817 let (slow, s) = (0.1, 1e-5);
1818 let s_dot = slow - 1e6 * slow * s / l.level(slow, 1.0);
1819 assert_eq!(l.eval(slow, s, 1.0), (1e6 * s + 1500.0 * s_dot + 20.0 * slow, s_dot));
1820 }
1821
1822 /// The friction view's curve, by hand for the test contact (Fc 15 N, Fs 20 N, b 20 N s/m, vs 0.01 m/s), as
1823 /// [Coulomb, viscous, stiction]: at 0.5 m/s 15, 10 and 5 exp(-2500) = 0 N; at 0.01 m/s 15, 0.2 and 5 / e =
1824 /// 1.83940 N; at -0.005 m/s -15, -0.1 and -5 exp(-0.25) = -3.89400 N. With the load scale 2 both levels double:
1825 /// 30, 0.2 and 3.67879 N at 0.01 m/s. In steady sliding the live split is the curve; held at rest by a bristle
1826 /// deflection of 1e-5 m (5 N) it is 5 * 15 / 20 = 3.75 N Coulomb and 1.25 N stiction.
1827 #[test]
1828 fn lugre_steady_curve_and_live_split_follow_the_formula() {
1829 let f = lugre();
1830 let close = |a: [f64; 3], b: [f64; 3]| a.iter().zip(&b).all(|(a, b)| (a - b).abs() < 1e-5);
1831 for (v, scale, expected) in [
1832 (0.5, 1.0, [15.0, 10.0, 0.0]),
1833 (0.01, 1.0, [15.0, 0.2, 1.83940]),
1834 (-0.005, 1.0, [-15.0, -0.1, -3.89400]),
1835 (0.01, 2.0, [30.0, 0.2, 3.67879]),
1836 ] {
1837 let steady = f.steady(v, scale);
1838 assert!(close(steady, expected), "{v} m/s: {steady:?}");
1839 let s = f.level(v, scale) * v.signum() / f.sigma0;
1840 assert!(close(f.split(v, s, scale), steady), "{v} m/s: {:?}", f.split(v, s, scale));
1841 assert!((f.split(v, s, scale).iter().sum::<f64>() - f.eval(v, s, scale).0).abs() < 1e-9);
1842 }
1843 assert!(close(f.split(0.0, 1e-5, 1.0), [3.75, 0.0, 1.25]), "{:?}", f.split(0.0, 1e-5, 1.0));
1844 assert_eq!(Lugre { on: false, ..lugre() }.steady(0.5, 1.0), [0.0; 3]);
1845 }
1846
1847 /// A load scale of 0 leaves no friction level: the split is the viscous part alone, not NaN from 0 / 0.
1848 #[test]
1849 fn the_split_without_a_friction_level_is_the_viscous_part() {
1850 let f = lugre();
1851 assert_eq!(f.split(0.0, 0.0, 0.0), [0.0; 3]);
1852 assert_eq!(f.split(0.5, 1e-5, 0.0), [0.0, 10.0, 0.0]);
1853 }
1854
1855 /// Loss powers by hand. Belt damping 100 N s/m stretched at 0.3 m/s: 100 * 0.3^2 = 9 W, whatever the stretch.
1856 /// Gearbox 5:1 at 90 % passing 2 N m at 50 rad/s out: 2 * 50 * 0.1 = 10 W; driven back, 2 / 0.9 * 50 - 2 * 50
1857 /// = 11.11 W; loss-free with 5 N m s/rad damping and the rotor 1 rad/s ahead at the output: 5 W. End stop with
1858 /// 200 N s/m, 1 mm beyond and moving on out at 0.1 m/s: 200 * 0.01 = 2 W.
1859 #[test]
1860 fn loss_powers_are_the_hand_calculated_ones() {
1861 let mut b = belt();
1862 b.damping = 100.0;
1863 let mat = b.rest_length(1.0);
1864 assert!(
1865 (b.loss_power(1.0, mat, 0.5, 0.2) - 9.0).abs() < 1e-9
1866 && (b.loss_power(1.003, mat, -0.1, 0.2) - 9.0).abs() < 1e-9
1867 );
1868 let mut g = gearbox();
1869 g.efficiency = 0.9;
1870 let twist = 5.0 * g.static_twist(2.0);
1871 assert!(
1872 (g.loss_power(twist, 250.0, 0.0, 50.0) - 10.0).abs() < 1e-9,
1873 "{}",
1874 g.loss_power(twist, 250.0, 0.0, 50.0)
1875 );
1876 assert!((g.loss_power(twist, -250.0, 0.0, -50.0) - (2.0 / 0.9 - 2.0) * 50.0).abs() < 1e-9);
1877 let g = Gearbox { damping: 5.0, half_backlash: 0.0, ..gearbox() };
1878 assert!((g.loss_power(5.0 * 1e-4, 5.0, 0.0, 0.0) - 5.0).abs() < 1e-9);
1879 let stop = HardStop { stiffness: 1e6, damping: 200.0 };
1880 assert!((stop.loss_power(1.001, 0.1, 1.0) - 2.0).abs() < 1e-9 && stop.loss_power(0.5, 0.1, 1.0) == 0.0);
1881 }
1882
1883 #[test]
1884 fn lugre_level_falls_from_stiction_to_coulomb() {
1885 let f = lugre();
1886 assert!((f.level(0.0, 1.0) - 20.0).abs() < 1e-12);
1887 assert!((f.level(1.0, 1.0) - 15.0).abs() < 1e-9);
1888 assert!(f.level(0.005, 1.0) < 20.0 && f.level(0.005, 1.0) > 15.0);
1889 }
1890
1891 /// A stiction level given below the Coulomb level counts as the Coulomb level: the contact never slides
1892 /// harder than it breaks away. A stiction level above it is taken as given.
1893 #[test]
1894 fn lugre_stiction_is_never_below_coulomb() {
1895 let level = |stiction: f64| {
1896 let text = format!(
1897 "format_version = 1
1898[effects]
1899guide_friction = true
1900temperature = false
1901thermal_feedback = false
1902load_dependent_friction = false
1903[guide]
1904bristle_stiffness_n_m = 1e5
1905bristle_damping_n_s_m = 300.0
1906viscous_n_s_m = 20.0
1907coulomb_n = 26.0
1908stiction_n = {stiction:?}
1909stribeck_m_s = 0.01
1910preload_n = 200.0
1911"
1912 );
1913 let f = Lugre::from_config(&Config::parse(&text).unwrap(), "guide").unwrap();
1914 (f.level(0.0, 1.0), f.level(1.0, 1.0))
1915 };
1916 assert_eq!(level(20.0), (26.0, 26.0));
1917 assert_eq!(level(30.0), (30.0, 26.0));
1918 }
1919
1920 #[test]
1921 fn lugre_levels_scale_with_guide_load_and_switch_off() {
1922 let mut f = lugre();
1923 assert!((f.load_scale(300.0, 100.0) - 500.0 / 300.0).abs() < 1e-12);
1924 assert!((f.level(0.0, 2.0) - 40.0).abs() < 1e-12);
1925 f.load_dependent = false;
1926 assert_eq!(f.load_scale(300.0, 100.0), 1.0);
1927 f.on = false;
1928 assert_eq!(f.eval(0.3, 1e-5, 1.0), (0.0, 0.0));
1929 }
1930
1931 #[test]
1932 fn shaft_friction_is_coulomb_plus_viscous_away_from_rest() {
1933 let f = ShaftFriction { coulomb: 0.02, viscous: 1e-4, smoothing: 0.5, ..ShaftFriction::NONE };
1934 assert!((f.torque(100.0) - (0.02 + 0.01)).abs() < 1e-12);
1935 assert!((f.torque(-100.0) + (0.02 + 0.01)).abs() < 1e-12);
1936 assert_eq!(f.torque(0.0), 0.0);
1937 }
1938
1939 #[test]
1940 fn ripple_and_cogging_are_periodic_and_invertible() {
1941 let r = Ripple { ripple: 0.02, ripple_order: 24.0, cogging: 0.01, cogging_order: 24.0 };
1942 let quarter = std::f64::consts::TAU / 24.0 / 4.0;
1943 assert!((r.apply(1.0, quarter) - (1.02 + 0.01)).abs() < 1e-12);
1944 assert!((r.apply(1.0, 0.3) - r.apply(1.0, 0.3 + std::f64::consts::TAU / 24.0)).abs() < 1e-12);
1945 assert!((r.apply(r.invert(0.7, 0.3), 0.3) - 0.7).abs() < 1e-12);
1946 }
1947
1948 #[test]
1949 fn tooth_mesh_repeats_once_per_tooth() {
1950 let t = ToothMesh { force: 2.0, pitch: 0.005 };
1951 assert!((t.force(0.00125) - 2.0).abs() < 1e-12);
1952 assert!((t.force(0.001) - t.force(0.006)).abs() < 1e-9);
1953 }
1954
1955 fn gearbox() -> Gearbox {
1956 Gearbox {
1957 ratio: 5.0,
1958 stiffness: 1e4,
1959 damping: 0.0,
1960 half_backlash: 4e-4,
1961 efficiency: 1.0,
1962 band: 0.0,
1963 band_compliance: 0.0,
1964 hysteresis: 0.0,
1965 dahl_stiffness: 1e4,
1966 back_ratio: 1.0,
1967 anchor: [f64::NAN, 0.0],
1968 twist_scale: 1.0,
1969 knees: [f64::INFINITY; 2],
1970 upper: [1e4; 2],
1971 mesh_stiffness: 0.0,
1972 mesh_anchor: f64::NAN,
1973 relax_stiffness: 0.0,
1974 relax_time: 0.0,
1975 travel: None,
1976 }
1977 }
1978
1979 #[test]
1980 fn gearbox_transmits_nothing_inside_the_backlash() {
1981 let g = gearbox();
1982 // Output-side twist of +-4e-4 rad is free: that is 8e-4 rad of lost motion in total.
1983 assert_eq!(g.torque(5.0 * 3.9e-4, 0.0, 0.0, 0.0).output, 0.0);
1984 assert_eq!(g.torque(-5.0 * 3.9e-4, 0.0, 0.0, 0.0).output, 0.0);
1985 let t = g.torque(5.0 * 5e-4, 0.0, 0.0, 0.0);
1986 assert!((t.output - 1e4 * 1e-4).abs() < 1e-9 && (t.rotor - t.output / 5.0).abs() < 1e-12);
1987 assert!((g.static_twist(1.0) - (1e-4 + 4e-4)).abs() < 1e-15);
1988 assert!((g.torque(5.0 * g.static_twist(-2.0), 0.0, 0.0, 0.0).output + 2.0).abs() < 1e-9);
1989 }
1990
1991 #[test]
1992 fn gearbox_flanks_in_contact_never_pull() {
1993 let mut g = gearbox();
1994 g.damping = 5.0;
1995 // Engaged on the positive side by 1e-4 rad (1 N m of spring torque), output running away at 1 rad/s.
1996 let t = g.torque(5.0 * 5e-4, 0.0, 0.0, 1.0);
1997 assert_eq!((t.output, t.rotor), (0.0, 0.0));
1998 // Closing instead, the damping adds to the spring.
1999 assert!((g.torque(5.0 * 5e-4, 0.0, 0.0, -1.0).output - 6.0).abs() < 1e-9);
2000 // Without backlash the gearbox is a plain spring and damper, in both directions.
2001 g.half_backlash = 0.0;
2002 assert!((g.torque(5.0 * 1e-4, 0.0, 0.0, 1.0).output + 4.0).abs() < 1e-9);
2003 }
2004
2005 fn feedback() -> ThermalFeedback {
2006 ThermalFeedback {
2007 ambient: 293.15,
2008 reference: 293.15,
2009 viscosity_slope: 4000.0,
2010 gearbox_viscous_share: 0.5,
2011 belt_coefficient: 3e-4,
2012 efficiency: 0.95,
2013 seal_exponent: 0.33,
2014 }
2015 }
2016
2017 /// The temperature laws at fixed temperatures, by hand. B 4000 K, ambient and reference 20 °C. 30 K above:
2018 /// nu / nu_ref = exp(4000 (1 / 323.15 - 1 / 293.15)) = exp(-1.26672) = 0.281749; the gearbox of 95 % with half its
2019 /// loss viscous then has 1 - 0.05 (0.5 + 0.5 * 0.281749) = 0.967956. At -10 °C ambient the oil is 4.73776 times
2020 /// as thick and the gearbox has 1 - 0.05 (0.5 + 2.36888) = 0.856556. At ambient = reference nothing changes; at
2021 /// 40 °C ambient the belt has 1 - 3e-4 * 20 = 0.994 of its EA.
2022 #[test]
2023 fn the_temperature_laws_follow_their_formulas() {
2024 let t = feedback();
2025 let close = |a: f64, b: f64| assert!((a - b).abs() < 1e-6, "{a} against {b}");
2026 close(t.viscosity_factor(0.0), 1.0);
2027 close(t.gearbox_efficiency(0.0), 0.95);
2028 close(t.belt_stiffness_factor(), 1.0);
2029 close(t.viscosity_factor(30.0), 0.281749);
2030 close(t.gearbox_efficiency(30.0), 0.967956);
2031 let cold = ThermalFeedback { ambient: 263.15, ..feedback() };
2032 close(cold.viscosity_factor(0.0), 4.737759);
2033 close(cold.gearbox_efficiency(0.0), 0.856556);
2034 close(ThermalFeedback { ambient: 313.15, ..feedback() }.belt_stiffness_factor(), 0.994);
2035 // A gearbox without losses keeps none, warm or cold.
2036 close(ThermalFeedback { efficiency: 1.0, ..cold }.gearbox_efficiency(0.0), 1.0);
2037 }
2038
2039 /// The teeth climb out above climb times the slack side's tension: with climb 6, 100 N and 700 N climb, 100 N and
2040 /// 600 N do not, and a slack side climbs at any pull. A jump runs towards the tight side against the ridge, 600 N
2041 /// (6 * 100 N) times sin(2 pi d / p): at d = p / 4 the full 600 N, its energy 600 N * 5 mm / pi = 0.954930 J at
2042 /// the top; it ends where the belt crosses the next groove (counted) or the one it left (not counted).
2043 /// Level spans on both sides (to a clamp at the pulley's top, r2 = 0, and under an idler as large as the pulley,
2044 /// r2 = -r) wrap half a turn. A span that leaves straight up to a clamp at (0, 0.5 m) over a pulley of r = 0.02 m
2045 /// touches it on its left at 90 degrees plus asin(r / D) less: lean = pi / 2 - asin(0.04), so with a level lower span
2046 /// wrap = pi / 2 + asin(0.04) = 1.610807 rad. With climb = k wrap the tooth jump threshold follows: k = 2.4 gives
2047 /// 2.4 pi = 7.539822 for the half turn.
2048 #[test]
2049 fn the_wrap_angle_is_half_a_turn_less_the_lean_of_both_spans() {
2050 let close = |a: f64, b: f64| assert!((a - b).abs() < 1e-6, "{a} against {b} by hand");
2051 close(wrap_angle(0.02, [0.4, 0.02, 0.0], [1.2, 0.0, -0.02]), std::f64::consts::PI);
2052 close(wrap_angle(0.02, [0.0, 0.5, 0.0], [1.2, 0.0, -0.02]), 1.610807);
2053 let mut jump = ToothJump { pitch: 0.005, climb: 6.0, factor: 2.4, mass: 0.26 };
2054 jump.set_wrap(std::f64::consts::PI);
2055 close(jump.climb, 7.539822);
2056 }
2057
2058 #[test]
2059 fn a_tooth_jump_starts_at_the_climb_limit_and_ends_one_pitch_on() {
2060 let jump = ToothJump { pitch: 0.005, climb: 6.0, factor: 2.4, mass: 0.26 };
2061 assert!(
2062 jump.climbs(100.0, 700.1)
2063 && jump.climbs(700.1, 100.0)
2064 && !jump.climbs(100.0, 600.0)
2065 && jump.climbs(0.0, 1.0)
2066 );
2067 let mut slip = [0.0; JUMP_STATES];
2068 let mut v = 1.0;
2069 assert!(!jump.update(&mut slip, 100.0, 600.0, 1.0, &mut v) && slip == [0.0; JUMP_STATES]);
2070 assert_eq!(jump.pulley_force(&slip, -500.0), -500.0);
2071 // Section b is the tight one: the belt slides towards it, -u.
2072 assert!(
2073 jump.update(&mut slip, 100.0, 701.0, 1.0, &mut v) && slip == [0.0, 0.0, -1.0, 0.0, 0.0, 600.0] && v == 1.0
2074 );
2075 assert_eq!(
2076 (jump.pulley_inertia(&slip, 1e-3, 0.02), jump.pulley_inertia(&[0.0; JUMP_STATES], 1e-3, 0.02)),
2077 (1e-3 - 0.26 * 4e-4, 1e-3)
2078 );
2079 slip[0] = -0.00125;
2080 assert!((jump.pulley_force(&slip, -601.0) + 600.0).abs() < 1e-9);
2081 let mut rates = [0.0; JUMP_STATES];
2082 jump.rates(&slip, -601.0, 2.0, &mut rates);
2083 assert!((rates[1] - (-1.0 / 0.26 - 2.0)).abs() < 1e-9 && rates[0] == 0.0, "{rates:?}");
2084 slip[0] = -0.0025;
2085 slip[1] = -1.0;
2086 // 1/2 0.26 ((1 - 1)^2 - 1^2) = -0.13 J, and the ridge's top.
2087 assert!((jump.slip_energy(&slip, 1.0) - (-0.13 + 0.954930)).abs() < 1e-6, "{}", jump.slip_energy(&slip, 1.0));
2088 assert_eq!(jump.slip_energy(&[0.0; JUMP_STATES], 1.0), 0.0);
2089 (slip[0], slip[1]) = (-0.0049, -1.0);
2090 assert!(!jump.update(&mut slip, 100.0, 701.0, 1.0, &mut v));
2091 // Landed one pitch on: a pulley of 1 kg at its surface at 1 m/s and the belt of 0.26 kg at 0 m/s run on at
2092 // 1 / 1.26 = 0.793651 m/s.
2093 slip[0] = -0.0051;
2094 assert!(
2095 jump.update(&mut slip, 100.0, 701.0, 1.0, &mut v) && slip == [-0.005, 0.0, 0.0, 0.0, 1.0, 0.0],
2096 "{slip:?}"
2097 );
2098 assert!((v - 0.793651).abs() < 1e-6, "{v}");
2099 // Back over the groove it left: in again where it was, not counted.
2100 let mut back = [0.0101, -0.1, 1.0, 0.01, 2.0, 50.0];
2101 let mut v = 0.0;
2102 assert!(!jump.update(&mut back, 0.0, 0.0, 1.0, &mut v));
2103 back[0] = 0.0099;
2104 assert!(jump.update(&mut back, 0.0, 0.0, 1.0, &mut v) && back == [0.01, 0.0, 0.0, 0.01, 2.0, 0.0], "{back:?}");
2105 }
2106
2107 /// A span of 0.25 m at 300 N with 0.1 kg/m: f1 = sqrt(3000) / 0.5 = 109.545 Hz. Excited at 100 Hz it is 8.71 %
2108 /// off; with nothing exciting, or slack, it counts as 1. The drive at 1 m/s of belt with a 5 mm pitch meshes at
2109 /// 200 Hz, and a motor at 250 rad/s with ripple and cogging of order 24 adds 954.930 Hz.
2110 #[test]
2111 fn a_span_vibrates_as_a_string_and_is_judged_against_the_excitations() {
2112 let f = span_frequency(0.25, 300.0, 0.1);
2113 assert!((f - 109.544512).abs() < 1e-6, "{f}");
2114 assert!((span_detuning(f, &[0.0, 100.0, 300.0]) - 0.087129).abs() < 1e-6);
2115 assert_eq!(
2116 (span_detuning(f, &[0.0]), span_detuning(0.0, &[100.0]), span_frequency(0.25, 0.0, 0.1)),
2117 (1.0, 1.0, 0.0)
2118 );
2119 let ripple = Ripple { ripple: 0.02, ripple_order: 24.0, cogging: 0.01, cogging_order: 24.0 };
2120 let mut out = Vec::new();
2121 drive_excitations(0.005, -1.0, &ripple, -250.0, &mut out);
2122 assert!(
2123 out.len() == 3 && (out[0] - 200.0).abs() < 1e-9 && (out[1] - 954.929659).abs() < 1e-6 && out[1] == out[2],
2124 "{out:?}"
2125 );
2126 out.clear();
2127 drive_excitations(0.005, 1.0, &Ripple { ripple: 0.0, cogging: 0.0, ..ripple }, 250.0, &mut out);
2128 assert_eq!(out.len(), 1);
2129 }
2130
2131 /// The SP+ 100's no-load running torque, 0.93 N m at 3000 r/min and 20 degC, by Palmgren's law
2132 /// T0 = T0_ref (nu / nu_ref * n / n_ref)^(2/3) with the configs' oil (B = 4000 K, reference 20 degC), by hand:
2133 /// 1500 r/min warm: 0.93 * 0.5^(2/3) = 0.585863 N m. 40 degC: nu / nu_ref = exp(4000 (1/313.15 - 1/293.15)) =
2134 /// 0.418340, so 0.93 * 0.418340^(2/3) = 0.520199 N m at 3000 r/min. 0 degC: 2.715774, so 1.810278 N m at 3000 and
2135 /// 0.93 * (2.715774 * 0.5)^(2/3) = 1.140404 N m at 1500 r/min. It opposes the speed, and is 0 at rest.
2136 #[test]
2137 fn the_no_load_torque_follows_speed_and_temperature_by_palmgrens_law() {
2138 let drag = GearDrag { torque: 0.93, speed: 3000.0 * std::f64::consts::TAU / 60.0 };
2139 let oil = ThermalFeedback { efficiency: 0.94, ..feedback() };
2140 let (warm, cold) =
2141 (oil.viscosity_factor(20.0), ThermalFeedback { ambient: 273.15, ..oil }.viscosity_factor(0.0));
2142 let rpm = |n: f64| n * std::f64::consts::TAU / 60.0;
2143 for (speed, oil, expected) in [
2144 (rpm(3000.0), 1.0, 0.93),
2145 (rpm(1500.0), 1.0, 0.585863),
2146 (rpm(3000.0), warm, 0.520199),
2147 (rpm(3000.0), cold, 1.810278),
2148 (rpm(1500.0), cold, 1.140404),
2149 (-rpm(1500.0), 1.0, -0.585863),
2150 ] {
2151 let t = drag.torque(speed, oil);
2152 assert!((t - expected).abs() < 1e-6, "{speed} rad/s, oil {oil}: {t} N m against {expected}");
2153 }
2154 assert_eq!(drag.torque(0.0, 1.0), 0.0);
2155 assert_eq!(GearDrag::NONE.torque(100.0, 1.0), 0.0);
2156 }
2157
2158 /// The efficiency map of a planetary gearbox of ratio 5 (the NRB060: 95 % at its rated 40 N m, 0.125 N m no-load
2159 /// torque at 3000 r/min), by hand. The teeth: 1 / (1 / 0.95 - 5 * 0.125 / 40) = 0.964314. Then
2160 /// eta = T2 / (5 (T2 / (5 * 0.964314) + T0)): 0.95 at 40 N m and 3000 r/min (the catalogue's point); at part load
2161 /// 10 N m 0.909499; slower, 1500 r/min (T0 0.078745), 0.929041; at 40 N m cold (0 degC, T0 0.243317) 0.936837 and
2162 /// warm (40 degC) 0.956255. The SP+ 100's drag takes all its loss: its teeth come out at 1 (1 / 0.94 - 20 * 0.93 /
2163 /// 259 = 0.992 is below 1), and at T2N cold from the start it passes 259 / (259 + 20 * 0.93) = 0.932997.
2164 #[test]
2165 fn the_efficiency_map_falls_at_part_load_slow_speed_and_in_the_cold_as_calculated() {
2166 let rpm = |n: f64| n * std::f64::consts::TAU / 60.0;
2167 let drag = GearDrag { torque: 0.125, speed: rpm(3000.0) };
2168 let tooth = drag.tooth_efficiency(0.95, 5.0, 40.0);
2169 assert!((tooth - 0.964314).abs() < 1e-6, "{tooth}");
2170 let (warm, cold) = (
2171 feedback().viscosity_factor(20.0),
2172 ThermalFeedback { ambient: 273.15, ..feedback() }.viscosity_factor(0.0),
2173 );
2174 for (torque, speed, oil, expected) in [
2175 (40.0, 3000.0, 1.0, 0.95),
2176 (10.0, 3000.0, 1.0, 0.909499),
2177 (10.0, 1500.0, 1.0, 0.929041),
2178 (40.0, 3000.0, cold, 0.936837),
2179 (40.0, 3000.0, warm, 0.956255),
2180 ] {
2181 let eta = drag.efficiency(tooth, 5.0, torque, rpm(speed), oil);
2182 assert!((eta - expected).abs() < 1e-6, "{torque} N m, {speed} r/min, oil {oil}: {eta}");
2183 }
2184 let sp = GearDrag { torque: 0.93, speed: rpm(3000.0) };
2185 assert_eq!(sp.tooth_efficiency(0.94, 20.0, 259.0), 1.0);
2186 assert!((sp.efficiency(1.0, 20.0, 259.0, rpm(3000.0), 1.0) - 0.932997).abs() < 1e-6);
2187 assert_eq!(GearDrag::NONE.tooth_efficiency(0.94, 20.0, 259.0), 0.94);
2188 }
2189
2190 /// The shaft's breakaway, by hand: Coulomb 0.05 N m, breakaway 0.075 N m, Stribeck speed 2 rad/s, smoothing
2191 /// 0.5 rad/s. At rest the level is the breakaway, 0.075 N m; at 0.5 rad/s (0.05 + 0.025 exp(-0.0625)) tanh(1) =
2192 /// 0.055966 N m; at 20 rad/s the Coulomb level, 0.05 N m. The seals at 0 degC with m = 0.33: 2.715774^0.33 =
2193 /// 1.390544 times as much. A breakaway given below the Coulomb level counts as that level, and so does any with
2194 /// effects.motor_stiction off.
2195 #[test]
2196 fn the_shaft_breaks_away_at_its_stiction_level_and_slides_at_its_coulomb_level() {
2197 let f = ShaftFriction { coulomb: 0.05, smoothing: 0.5, stiction: 0.075, stribeck: 2.0, ..ShaftFriction::NONE };
2198 assert!((f.level(0.0) - 0.075).abs() < 1e-12);
2199 assert!((f.torque(0.5) - 0.055966).abs() < 1e-6, "{}", f.torque(0.5));
2200 assert!((f.torque(-20.0) + 0.05).abs() < 1e-12);
2201 let mut cold = f.clone();
2202 cold.seal_exponent = 0.33;
2203 cold.set_oil(2.715774);
2204 assert!((cold.level(0.0) / f.level(0.0) - 1.390544).abs() < 1e-6);
2205 let text = |stiction: bool, breakaway: f64| {
2206 format!(
2207 "format_version = 1\n[effects]\nmotor_friction = true\nmotor_stiction = {stiction}\ngearbox_drag = false\nthermal_feedback = false\n\
2208 [motor]\nfriction_coulomb_nm = 0.05\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 0.5\nfriction_breakaway_nm = {breakaway:?}\nfriction_stribeck_rad_s = 2.0\n\
2209 [gearbox]\nratio = 20.0\nno_load_torque_nm = 0.93\nno_load_speed_rpm = 3000.0\n"
2210 )
2211 };
2212 let level = |stiction, breakaway| {
2213 ShaftFriction::from_config(&Config::parse(&text(stiction, breakaway)).unwrap()).unwrap().level(0.0)
2214 };
2215 for (stiction, breakaway, expected) in [(true, 0.075, 0.075), (true, 0.03, 0.05), (false, 0.075, 0.05)] {
2216 assert!((level(stiction, breakaway) - expected).abs() < 1e-15, "{stiction} {breakaway}");
2217 }
2218 }
2219
2220 /// The presliding state, by hand: Coulomb 100 N, breakaway 150 N, Stribeck speed 1 mm/s, sigma 1e6 N/m, viscous
2221 /// 10 N s/m. From the anchor [0, 0] at rest the level is 150 N; 1.5e-4 m on (sigma x / g = 1) the force is
2222 /// 150 (1 - exp(-1)) = 94.8181 N, and it stays there at rest however long (it moves with the travel, not the time).
2223 /// Turned back by 1.5e-4 m at rest: -150 + (150 + 94.8181) exp(-1) = -59.9364 N. Sliding at 1 mm/s far from the
2224 /// anchor: the level 100 + 50 exp(-1) = 118.394 N, plus 10 * 0.001 viscous. Without a presliding stiffness the
2225 /// smoothed step as before, to the bit.
2226 #[test]
2227 fn a_presliding_friction_holds_at_rest_and_turns_over_its_travel() {
2228 let mut f = ShaftFriction {
2229 coulomb: 100.0,
2230 viscous: 10.0,
2231 stiction: 150.0,
2232 stribeck: 1e-3,
2233 smoothing: 1e-3,
2234 presliding: 1e6,
2235 ..ShaftFriction::NONE
2236 };
2237 assert_eq!(f.presliding_force(1e-4, 0.0), 0.0);
2238 f.commit(0.0, 0.0);
2239 assert_eq!(f.anchor, [0.0, 0.0]);
2240 assert!((f.presliding_force(1.5e-4, 0.0) - 94.8181).abs() < 1e-4);
2241 f.commit(1.5e-4, 0.0);
2242 for _ in 0..1000 {
2243 f.commit(1.5e-4, 0.0);
2244 }
2245 assert!((f.torque_at(1.5e-4, 0.0) - 94.8181).abs() < 1e-4, "{}", f.torque_at(1.5e-4, 0.0));
2246 assert!((f.presliding_force(0.0, 0.0) + 59.9364).abs() < 1e-4);
2247 assert!((f.torque_at(0.1, 1e-3) - 118.3940 - 0.01).abs() < 1e-3, "{}", f.torque_at(0.1, 1e-3));
2248 let smoothed = ShaftFriction { presliding: 0.0, ..f.clone() };
2249 assert_eq!(smoothed.torque_at(1.5e-4, 0.3).to_bits(), smoothed.torque(0.3).to_bits());
2250 }
2251
2252 /// Harmonic Drive's size 32 strain wave gear, ratio 80 and up (Table 43): K1 6.7e4 N m/rad to T1 29 N m, K2 1.1e5 to
2253 /// T2 108 N m, K3 1.2e5 beyond. The twist by hand: 29 / 6.7e4 = 4.328358e-4 rad at T1 (the table's 4.4e-4), that
2254 /// plus 79 / 1.1e5 = 1.151018e-3 rad at T2 (11.6e-4), that plus 29 / 1.2e5 = 1.392684e-3 rad at its rated 137 N m.
2255 /// The spring gives the torque back, and its energy rises by the torque times the twist.
2256 #[test]
2257 fn the_three_segment_stiffness_twists_as_harmonic_drive_calculates() {
2258 let g = Gearbox {
2259 ratio: 120.0,
2260 stiffness: 6.7e4,
2261 half_backlash: 0.0,
2262 knees: [29.0, 108.0],
2263 upper: [1.1e5, 1.2e5],
2264 ..gearbox()
2265 };
2266 for (torque, twist) in [(29.0, 4.328358e-4), (108.0, 1.151018e-3), (137.0, 1.392684e-3)] {
2267 assert!((g.static_twist(torque) - twist).abs() < 1e-9, "{torque} N m: {}", g.static_twist(torque));
2268 assert!((g.static_twist(-torque) + twist).abs() < 1e-9);
2269 assert!((g.spring(twist).0 - torque).abs() < 1e-3, "{}", g.spring(twist).0);
2270 let h = 1e-8;
2271 let slope = (g.spring(twist + h).1 - g.spring(twist - h).1) / (2.0 * h);
2272 assert!((slope - torque).abs() < 1e-3, "{slope}");
2273 }
2274 // Off, the knees are at infinity: K1 throughout.
2275 assert!(
2276 (Gearbox { stiffness: 6.7e4, half_backlash: 0.0, ..gearbox() }.static_twist(137.0) - 137.0 / 6.7e4).abs()
2277 < 1e-15
2278 );
2279 }
2280
2281 /// A gear behind a screw whose compliance follows the nut (`TravelCompliance`): E A = 1e4, fixed-free over 1, the
2282 /// fixed bearing at -0.2 of the travel and the gear built at the far end (reference 1e-4, all of the band's series
2283 /// spring). With the nut 0.3 along the travel it is 0.5 from the bearing: dc = -5e-5, K1 = 1 / (2e-4 - 5e-5) =
2284 /// 6666.67, and so for K2 and K3. The nut sits where the rotor has turned it, s = phi / 5. The output's force is the
2285 /// spring's T, the energy's slope along the output at a fixed rotor angle; the rotor's reaction is the energy's slope
2286 /// along its angle, (T - T^2 c' / 2) / 5 (c' = 1e-4), through the band and the three segments; without the place's
2287 /// own term it misses by up to 1.2e-4. At the far end the gear is the reference's. Loss-free, the loss power is 0 on
2288 /// the move.
2289 #[test]
2290 fn a_gear_behind_a_screw_takes_the_nuts_travel_force_from_its_energy() {
2291 let g = Gearbox {
2292 stiffness: 5e3,
2293 half_backlash: 0.0,
2294 band: 2e-4,
2295 band_compliance: 1e-4,
2296 knees: [1.5, 3.0],
2297 upper: [4e3, 3e3],
2298 travel: Some(TravelCompliance {
2299 ae: 1e4,
2300 length: 1.0,
2301 both_ends: false,
2302 fixed_bearing_at: -0.2,
2303 reference: 1e-4,
2304 gear: [0.0; 2],
2305 converter: [0.0; 2],
2306 }),
2307 ..gearbox()
2308 };
2309 assert!((g.at(0.3).stiffness - 1.0 / 1.5e-4).abs() < 1e-8 && (g.at(0.3).upper[0] - 1.0 / 2.0e-4).abs() < 1e-8);
2310 assert!((g.at(0.8).stiffness - 5e3).abs() < 1e-9 && g.at(0.8).band_compliance == 1e-4);
2311 let (q, h) = (0.3, 1e-8);
2312 for twist in [1e-4, 4e-4, 6e-4, 8e-4, 1.2e-3] {
2313 let rotor = 5.0 * (twist + q);
2314 let t = g.torque(rotor, 0.0, q, 0.0);
2315 let along = -(g.energy(rotor, q + h) - g.energy(rotor, q - h)) / (2.0 * h);
2316 let turning = (g.energy(rotor + 5.0 * h, q) - g.energy(rotor - 5.0 * h, q)) / (10.0 * h);
2317 let spring = g.at(twist + q).spring(twist).0;
2318 assert!((t.output - along).abs() < 1e-7, "{twist}: {} against {along}", t.output);
2319 assert!((t.rotor - turning).abs() < 2e-8, "{twist}: {} against {turning}", t.rotor);
2320 assert!((t.output - spring).abs() < 1e-12, "{twist}");
2321 assert!((5.0 * t.rotor - spring + 0.5 * spring * spring * 1e-4).abs() < 1e-12, "{twist}");
2322 assert!(g.loss_power(rotor, 2.0, q, 0.3).abs() < 1e-12);
2323 }
2324 }
2325
2326 /// The dampers follow the nut with the screw's stiffness (`TravelCompliance::dampers`): a gear of K_g = 2e4 with
2327 /// c_g = 10 in series with a screw that is all shaft, K_c = 1e4 with c_c = 20 at the far end (E A = 1e4, fixed-free
2328 /// over 1, the bearing at -0.2, built at 0.8). There b = 200 / 30 = 6.6667, K_m = (4e5 - 1e5)^2 / (3e4 * 900) =
2329 /// 3333.33, tau = 30 / 3e4 = 1e-3. At q = 0.3 the shaft is 0.5: K_c = 2e4, c_c = 20 sqrt(2) = 28.284 (the damping
2330 /// ratio kept), so b = 282.84 / 38.284 = 7.3880, K_m = (2e4 (28.284 - 10))^2 / (4e4 * 38.284^2) = 2280.9 and
2331 /// tau = 38.284 / 4e4 = 9.5711e-4; dK_m / d(dc) against a difference quotient. With the arm at a state u its store
2332 /// K_m (x - u)^2 / 2 follows the nut as the spring's does: the rotor's reaction is the energy's slope along its angle
2333 /// at fixed u and the output's force the slope along the output, and on a move the loss is the dampers' alone,
2334 /// b x'^2 + K_m (x - u)^2 / tau, at the nut's place.
2335 #[test]
2336 fn the_dampers_behind_a_screw_follow_the_nut() {
2337 let (k_g, c_g, k_c, c_c) = (2e4, 10.0, 1e4, 20.0);
2338 let (b, arm, tau) = series_dampers(k_g, c_g, k_c, c_c);
2339 let g = Gearbox {
2340 stiffness: 1.0 / (1.0 / k_g + 1.0 / k_c),
2341 upper: [1.0 / (1.0 / k_g + 1.0 / k_c); 2],
2342 half_backlash: 0.0,
2343 band_compliance: 1e-4,
2344 damping: b,
2345 relax_stiffness: arm,
2346 relax_time: tau,
2347 travel: Some(TravelCompliance {
2348 ae: 1e4,
2349 length: 1.0,
2350 both_ends: false,
2351 fixed_bearing_at: -0.2,
2352 reference: 1e-4,
2353 gear: [k_g, c_g],
2354 converter: [k_c, c_c],
2355 }),
2356 ..gearbox()
2357 };
2358 let rel = |a: f64, b: f64, tol: f64| (a / b - 1.0).abs() < tol;
2359 assert!(rel(b, 6.666667, 1e-6) && rel(arm, 3333.333, 1e-6) && rel(tau, 1e-3, 1e-12));
2360 let far = g.at(0.8);
2361 assert!(far.damping == b && far.relax_stiffness == arm && far.relax_time == tau);
2362 let here = g.at(0.3);
2363 assert!(rel(here.damping, 7.387961, 1e-6) && rel(here.relax_time, 9.571068e-4, 1e-6), "{here:?}");
2364 assert!(rel(here.relax_stiffness, 2280.944, 1e-6), "{}", here.relax_stiffness);
2365 let t = g.travel.unwrap();
2366 let h = 1e-9;
2367 let quotient = (t.dampers(-5e-5 + h).unwrap()[1] - t.dampers(-5e-5 - h).unwrap()[1]) / (2.0 * h);
2368 assert!(rel(t.dampers(-5e-5).unwrap()[3], quotient, 1e-6), "{quotient}");
2369 let (q, h) = (0.3, 1e-8);
2370 for (twist, u) in [(1e-4, 0.0), (4e-4, 1e-4), (8e-4, 9e-4)] {
2371 let rotor = 5.0 * (twist + q);
2372 let t = g.torque_with(rotor, 0.0, q, 0.0, u);
2373 let along = -(g.energy_with(rotor, q + h, u) - g.energy_with(rotor, q - h, u)) / (2.0 * h);
2374 let turning = (g.energy_with(rotor + 5.0 * h, q, u) - g.energy_with(rotor - 5.0 * h, q, u)) / (10.0 * h);
2375 assert!((t.output - along).abs() < 1e-6, "{twist}: {} against {along}", t.output);
2376 assert!((t.rotor - turning).abs() < 2e-7, "{twist}: {} against {turning}", t.rotor);
2377 let (rate, s) = (2.0 / 5.0 - 0.3, g.nut(rotor));
2378 let at = g.at(s);
2379 let (force, arm_rate) = g.arm(rotor, q, u);
2380 let dissipated = at.damping * rate * rate + force * arm_rate;
2381 assert!((g.loss_power_with(rotor, 2.0, q, 0.3, u) - dissipated).abs() < 1e-12, "{twist}");
2382 }
2383 }
2384
2385 /// The mesh friction's bristle behind a screw whose compliance follows the nut follows K1 as the gear's own stiffness
2386 /// (`at`): the screw below (K1 5e3 at the far end, 6666.67 with the nut at 0.3, r = 4/3), sigma_m 1e5 at the far end,
2387 /// 1.3333e5 there; teeth of 0.8 (mu 0.2). The nut at 0.3 at a twist of 3e-4 (2 N), the output pushed on by 1e-5 m:
2388 /// the twist 2.9e-4 holds 1.93333 N, the bristle slides at its bound mu |held| = 0.386667 N, and `commit` leaves the
2389 /// anchor 0.386667 / 1.3333e5 = 2.9e-6 m behind the output; pulled back by 1.5e-6 m the bristle holds
2390 /// 1.3333e5 x 1.4e-6 = 0.186667 N (its bound there 0.388667). With the anchor left at the far end's bristle
2391 /// (0.386667 / 1e5 = 3.86667e-6 m behind) it read 0.315556 N.
2392 #[test]
2393 fn the_mesh_bristle_behind_a_screw_follows_the_nut() {
2394 let mut g = Gearbox {
2395 stiffness: 5e3,
2396 upper: [5e3; 2],
2397 half_backlash: 0.0,
2398 efficiency: 0.8,
2399 mesh_stiffness: 1e5,
2400 travel: Some(TravelCompliance {
2401 ae: 1e4,
2402 length: 1.0,
2403 both_ends: false,
2404 fixed_bearing_at: -0.2,
2405 reference: 1e-4,
2406 gear: [0.0; 2],
2407 converter: [0.0; 2],
2408 }),
2409 ..gearbox()
2410 };
2411 let rel = |a: f64, b: f64| (a / b - 1.0).abs() < 1e-9;
2412 assert!(rel(g.at(0.3).mesh_stiffness, 1e5 * 4.0 / 3.0));
2413 // The nut at 0.3: the rotor at 5 x 0.3, the output at 0.3 less the twist (and less how far it is pushed).
2414 let (rotor, twist) = (1.5, 3e-4);
2415 assert!(rel(g.at(0.3).spring(twist).0, 2.0));
2416 let friction = |g: &Gearbox, push: f64| {
2417 let out = 0.3 - twist + push;
2418 g.at(0.3).mesh_friction(g.held_torque(rotor, out), out)
2419 };
2420 g.commit(rotor, 0.3 - twist);
2421 g.commit(rotor, 0.3 - twist + 1e-5);
2422 assert!(rel(friction(&g, 1e-5), 0.2 * 6666.666666666667 * 2.9e-4), "{}", friction(&g, 1e-5));
2423 let back = friction(&g, 1e-5 - 1.5e-6);
2424 assert!(rel(back, 4.0 / 3.0 * 1e5 * 1.4e-6), "{back}");
2425 }
2426
2427 /// The hysteresis behind a screw whose compliance follows the nut acts on the gear's own twist (`at`): the screw of
2428 /// `a_gear_behind_a_screw_takes_the_nuts_travel_force_from_its_energy` (K1 5e3 at the far end, 6666.67 with the nut
2429 /// at 0.3: r = 4/3), T_h = 1 and sigma = 5e3 there. At 0.3 the friction is 4/3, sigma 5e3 (4/3)^2 = 8888.89, and the
2430 /// loop as wide as at the far end, 2 T_h / K1 = 4e-4. Loaded at the far end from rest to the spring's 2 N m (x =
2431 /// 4e-4) the state is 1 - exp(-2) = 0.864665; carried at that force to 0.3 (x = 3e-4, the same y = r x) it stays
2432 /// there, 4/3 of it = 1.152887 in x. Before, on the twist through gear and screw, it slid back to
2433 /// -1 + 1.864665 exp(-0.5) = 0.130985. On a move the loss is the power in less the store's rate along the move
2434 /// (a difference quotient of `energy` at the anchor) and not below 0: the place's work on the state is stored.
2435 #[test]
2436 fn the_hysteresis_behind_a_screw_acts_on_the_gears_own_twist() {
2437 let mut g = Gearbox {
2438 stiffness: 5e3,
2439 upper: [5e3; 2],
2440 half_backlash: 0.0,
2441 hysteresis: 1.0,
2442 dahl_stiffness: 5e3,
2443 travel: Some(TravelCompliance {
2444 ae: 1e4,
2445 length: 1.0,
2446 both_ends: false,
2447 fixed_bearing_at: -0.2,
2448 reference: 1e-4,
2449 gear: [0.0; 2],
2450 converter: [0.0; 2],
2451 }),
2452 ..gearbox()
2453 };
2454 let rel = |a: f64, b: f64| (a / b - 1.0).abs() < 1e-9;
2455 let here = g.at(0.3);
2456 assert!(rel(here.hysteresis, 4.0 / 3.0) && rel(here.dahl_stiffness, 5e3 * 16.0 / 9.0), "{here:?}");
2457 assert!(rel(2.0 * here.hysteresis / here.stiffness, 4e-4));
2458 // The nut at q: the rotor at 5 q, the output at q less the twist.
2459 let at = |q: f64, x: f64| (5.0 * q, q - x);
2460 let (rotor, out) = at(0.8, 0.0);
2461 g.commit(rotor, out);
2462 let (rotor, out) = at(0.8, 4e-4);
2463 g.commit(rotor, out);
2464 let (rotor, out) = at(0.3, 3e-4);
2465 let spring = g.at(0.3).spring(3e-4).0;
2466 assert!(rel(spring, 2.0));
2467 let z = g.torque(rotor, 0.0, out, 0.0).output - spring;
2468 assert!(rel(z, 4.0 / 3.0 * (1.0 - (-2.0f64).exp())), "{z}");
2469 assert!((z - 1.152887).abs() < 1e-6);
2470 // Moving on: the rotor at 2 rad/s (the nut at 0.4 m/s), the output at 0.3 m/s.
2471 // Forward differences: the state turns at the anchor, so its slope there is the move's side's. By hand the
2472 // loss is z (z / T_h) y' / r: 1.152887 x 0.864665 x (0.4 - 0.3 - 6666.67 x 1e-4 x 3e-4 x 0.4) = 0.0996063.
2473 let (w, v, h) = (2.0, 0.3, 1e-9);
2474 let t = g.torque(rotor, w, out, v);
2475 let rate = (g.energy(rotor + w * h, out + v * h) - g.energy(rotor, out)) / h;
2476 let loss = g.loss_power(rotor, w, out, v);
2477 let balance = t.rotor * w - t.output * v - rate;
2478 assert!((loss - balance).abs() < 1e-6, "{loss} against {balance}");
2479 assert!((loss - 0.0996063).abs() < 1e-6, "{loss}");
2480 }
2481
2482 /// The screw of `the_hysteresis_behind_a_screw_acts_on_the_gears_own_twist`, its hysteresis along the stroke or not.
2483 fn hysteresis_screw(along: bool) -> Gearbox {
2484 let travel = TravelCompliance {
2485 ae: 1e4,
2486 length: 1.0,
2487 both_ends: false,
2488 fixed_bearing_at: -0.2,
2489 reference: 1e-4,
2490 gear: [0.0; 2],
2491 converter: [0.0; 2],
2492 };
2493 Gearbox {
2494 stiffness: 5e3,
2495 upper: [5e3; 2],
2496 half_backlash: 0.0,
2497 hysteresis: 1.0,
2498 dahl_stiffness: 5e3,
2499 travel: along.then_some(travel),
2500 ..gearbox()
2501 }
2502 }
2503
2504 /// Right after a step's end (where `Sim::step` takes the loss powers) the hysteresis's branch is the move's, not
2505 /// rounding's: committed at a twist x with z > 0, the loss is z^2 |y'| / (r T_h) by hand, y' / r = x' - K c' x s'
2506 /// the gear's own twist's rate (`hysteresis_place`, K and T_h at the nut, c' the shaft's compliance's slope, s' the
2507 /// nut's speed), for the twist running on, turning back, and standing while the nut travels either way. 200 anchors
2508 /// along the stroke. With the anchor's x rebuilt as (x r) / r, 87 of 400 were off by more than 0.1 % (worst 200 %,
2509 /// the sign flipped) behind the screw, none without it.
2510 #[test]
2511 fn the_hysteresis_loss_at_the_anchor_goes_by_the_move() {
2512 for along in [false, true] {
2513 for k in 0..200 {
2514 let mut g = hysteresis_screw(along);
2515 let q = 0.3 + 1e-3 * k as f64;
2516 let x = 2e-4 + 1e-7 * k as f64;
2517 g.commit(5.0 * (q + 1e-4), q);
2518 let (rotor, out) = (5.0 * (q + x), q);
2519 g.commit(rotor, out);
2520 let s = g.nut(rotor);
2521 let here = g.at(s);
2522 let z = here.hysteresis_torque(x, 0.0).0;
2523 assert!(z > 0.0);
2524 let shift = g.travel.map_or(0.0, |t| -here.stiffness * t.delta(s).1 * x);
2525 // (rotor, output) speeds: the twist on and back with the output still, and the nut travelling at a
2526 // standing twist.
2527 for (w, v) in [(5e-3, 0.0), (-5e-3, 0.0), (5.0, 1.0), (-5.0, -1.0)] {
2528 let own = w / 5.0 - v + shift * w / 5.0;
2529 let hand = z * z * own.abs() / here.hysteresis;
2530 let loss = g.loss_power(rotor, w, out, v);
2531 if hand == 0.0 {
2532 assert!(loss.abs() < 1e-12, "{along} {k} {w}: {loss} W");
2533 } else {
2534 assert!((loss / hand - 1.0).abs() < 1e-6, "{along} {k} {w}: {loss} against {hand} W by hand");
2535 }
2536 }
2537 }
2538 }
2539 }
2540
2541 /// The load 2 + 0.8 sin(2 pi 7 t) N m for a second, the nut held at 0.3 m or running from 0.8 to 0 m, the anchor
2542 /// committed after each step at the state the next step starts from: the work put in less the store's change less
2543 /// the loss integrated (trapezoids) closes to rounding, with the screw's compliance along the stroke and without.
2544 /// With the branch at the anchor from rounding 9.1e-5 J of 7.4e-4 J lost stayed open with the nut held, at any step.
2545 #[test]
2546 fn the_hysteresis_behind_a_screw_closes_its_budget_over_load_cycles() {
2547 for along in [false, true] {
2548 for (q0, q1) in [(0.3, 0.3), (0.8, 0.0)] {
2549 let mut g = hysteresis_screw(along);
2550 let n = 100_000;
2551 let dt = 1.0 / n as f64;
2552 let state = |g: &Gearbox, t: f64| {
2553 let (q, f) = (q0 + (q1 - q0) * t, 2.0 + 0.8 * (std::f64::consts::TAU * 7.0 * t).sin());
2554 (5.0 * (q + f / g.at(q).stiffness), q)
2555 };
2556 let power = |g: &Gearbox, t: f64| {
2557 let h = 1e-7;
2558 let ((r, o), (a, b)) = (state(g, t), (state(g, t + h), state(g, t - h)));
2559 let (w, v) = ((a.0 - b.0) / (2.0 * h), (a.1 - b.1) / (2.0 * h));
2560 let tq = g.torque(r, w, o, v);
2561 (tq.rotor * w - tq.output * v, g.loss_power(r, w, o, v))
2562 };
2563 let (r, o) = state(&g, 0.0);
2564 g.commit(r, o);
2565 let e0 = g.energy(r, o);
2566 let (mut work, mut lost) = (0.0, 0.0);
2567 for i in 0..n {
2568 let (t0, t1) = (i as f64 * dt, (i + 1) as f64 * dt);
2569 let ((p0, l0), (p1, l1)) = (power(&g, t0), power(&g, t1));
2570 work += 0.5 * (p0 + p1) * dt;
2571 lost += 0.5 * (l0 + l1) * dt;
2572 let (r, o) = state(&g, t1);
2573 g.commit(r, o);
2574 }
2575 let (r, o) = state(&g, 1.0);
2576 let open = work - (g.energy(r, o) - e0) - lost;
2577 assert!(lost > 7e-4 && open.abs() < 1e-9, "{along} {q0}: {open} J open of {lost} J lost");
2578 }
2579 }
2580 }
2581
2582 /// The lost-motion band, by hand. K1 1e4 N m/rad, half backlash 4e-4 rad, a band of 2e-4 rad: 1e-4 rad into the band
2583 /// 1e4 * 1e-8 / 4e-4 = 0.25 N m, at its end 1 N m (= K1 b / 2), 1e-4 rad beyond 2 N m; the twist for 2 N m is
2584 /// 4e-4 + 2e-4 / 2 + 2e-4 = 7e-4 rad.
2585 #[test]
2586 fn the_lost_motion_band_is_the_calculated_one() {
2587 let g = Gearbox { band: 2e-4, ..gearbox() };
2588 let out = |twist: f64| g.torque(5.0 * twist, 0.0, 0.0, 0.0).output;
2589 assert!((out(5e-4) - 0.25).abs() < 1e-9 && (out(6e-4) - 1.0).abs() < 1e-9 && (out(7e-4) - 2.0).abs() < 1e-9);
2590 assert!((g.static_twist(2.0) - 7e-4).abs() < 1e-15 && (g.static_twist(0.25) - 5e-4).abs() < 1e-15);
2591 let h = 1e-9;
2592 for twist in [5e-4, 6e-4, 7e-4] {
2593 let slope = (g.energy(5.0 * (twist + h), 0.0) - g.energy(5.0 * (twist - h), 0.0)) / (2.0 * h);
2594 assert!((slope - out(twist)).abs() < 1e-5, "{twist}: {slope}");
2595 }
2596 }
2597
2598 /// The band with a spring of 1e4 N m/rad in series with the flanks of the test above (c = 1e-4 rad/N m, K1 = 5e3 in
2599 /// series): the flanks twist sqrt(2 b T / 1e4) in the band, the spring c T. 0.25 N m: 1e-4 + 2.5e-5 = 1.25e-4 rad
2600 /// beyond the backlash; the band ends at T_b = 1 N m at 2e-4 + 1e-4 = 3e-4 rad; 2 N m: 2 / 5e3 + 1e-4 = 5e-4 rad
2601 /// (the flanks' 3e-4 and the spring's 2e-4). The energy's slope is the torque, also across the band's end.
2602 #[test]
2603 fn a_spring_in_series_with_the_band_adds_its_own_twist_to_the_flanks() {
2604 let g = Gearbox { stiffness: 5e3, band: 2e-4, band_compliance: 1e-4, ..gearbox() };
2605 let out = |twist: f64| g.torque(5.0 * twist, 0.0, 0.0, 0.0).output;
2606 for (beyond, torque) in [(1.25e-4, 0.25), (3e-4, 1.0), (5e-4, 2.0)] {
2607 assert!((out(4e-4 + beyond) - torque).abs() < 1e-9, "{beyond}: {}", out(4e-4 + beyond));
2608 assert!((g.static_twist(torque) - 4e-4 - beyond).abs() < 1e-15, "{torque}: {}", g.static_twist(torque));
2609 }
2610 let h = 1e-9;
2611 for twist in [5.25e-4, 7e-4 - 2.0 * h, 7e-4 + 2.0 * h, 9e-4] {
2612 let slope = (g.energy(5.0 * (twist + h), 0.0) - g.energy(5.0 * (twist - h), 0.0)) / (2.0 * h);
2613 assert!((slope - out(twist)).abs() < 1e-5, "{twist}: {slope}");
2614 }
2615 }
2616
2617 /// A strain wave gear's hysteresis of 2.909e-4 rad (1 arcmin) on K1 1e4 N m/rad: a flanks' friction T_h of
2618 /// 1.4545 N m, sigma = K1. Loaded to 0.01 rad (sigma x / T_h = 68.75: z is T_h to the bit) and unloaded, the torque
2619 /// is K1 x - T_h + 2 T_h exp(-sigma (0.01 - x) / T_h), zero at x = +1.4545e-4 rad; loaded back from -0.01 rad, zero at
2620 /// -1.4545e-4 rad: the loop is 2.909e-4 rad wide. Back at x = 0 the gear holds -1.4545 N m. From z = 0 at x = 0 (the
2621 /// first step's end), at x = T_h / sigma = 1.4545e-4 rad z = T_h (1 - 1/e) = 0.919419 N m, and twisting on at
2622 /// 0.5 rad/s the hysteresis takes s x' z^2 / T_h = 0.290592 W, the rate of energy lost as the twist runs on, and as
2623 /// much when a step ends there and the twist turns back.
2624 #[test]
2625 fn the_hysteresis_loop_is_as_wide_as_given_and_holds_its_torque_at_rest() {
2626 let th = 0.5 * 1e4 * 2.909e-4;
2627 let mut g = Gearbox { half_backlash: 0.0, hysteresis: th, ..gearbox() };
2628 let torque = |g: &Gearbox, x: f64| g.torque(5.0 * x, 0.0, 0.0, 0.0).output;
2629 g.commit(0.0, 0.0);
2630 assert_eq!(g.anchor, [0.0, 0.0]);
2631 let x = th / 1e4;
2632 assert!((torque(&g, x) - (1e4 * x + 0.919419)).abs() < 1e-6, "{}", torque(&g, x));
2633 assert!((g.loss_power(5.0 * x, 5.0 * 0.5, 0.0, 0.0) - 0.290592).abs() < 1e-6);
2634 // The loss is what the work put in leaves after spring and state: over 1e-9 rad of twist at 0.5 rad/s.
2635 let (h, rate) = (1e-9, 0.5);
2636 let work = torque(&g, x) * h;
2637 let stored = g.energy(5.0 * (x + h), 0.0) - g.energy(5.0 * x, 0.0);
2638 assert!((work - stored - g.loss_power(5.0 * x, 5.0 * rate, 0.0, 0.0) * h / rate).abs() < 1e-12);
2639 // A step ends there and the twist turns back: the friction still takes s x' z^2 / T_h = (-1)(-0.5) z^2 / T_h, the
2640 // same 0.290592 W (the direction comes from the rate at the anchor, not from x - x0 = 0).
2641 g.commit(5.0 * x, 0.0);
2642 assert!((g.loss_power(5.0 * x, -5.0 * 0.5, 0.0, 0.0) - 0.290592).abs() < 1e-6);
2643
2644 g.commit(5.0 * 0.01, 0.0);
2645 assert!((g.anchor[1] - th).abs() < 1e-12);
2646 assert!(torque(&g, 1.4545e-4).abs() < 1e-9, "unloading: {} N m", torque(&g, 1.4545e-4));
2647 g.commit(0.0, 0.0);
2648 assert!((torque(&g, 0.0) + 1.4545).abs() < 1e-9, "at rest: {} N m", torque(&g, 0.0));
2649 g.commit(-5.0 * 0.01, 0.0);
2650 assert!(torque(&g, -1.4545e-4).abs() < 1e-9, "loading: {} N m", torque(&g, -1.4545e-4));
2651 }
2652
2653 /// At small amplitudes the hysteresis is a spring of sigma beside K1, not a lock: a twist of 1e-7 rad at 100 Hz,
2654 /// stepped at 10 us as `Sim` steps (`commit` at each step's end), gives a first harmonic of torque in phase of
2655 /// (K1 + sigma) 1e-7 = 2e-3 N m and almost none in quadrature (sigma x / T_h = 7e-4: the loop is a sliver). The old
2656 /// friction on the twist's rate, T_h tanh(x' / 1e-3 rad/s), gave 0.09 N m in quadrature, 45 times the spring's.
2657 #[test]
2658 fn a_gear_with_hysteresis_answers_small_signals_as_its_stiffness() {
2659 let th = 0.5 * 1e4 * 2.909e-4;
2660 let mut g = Gearbox { half_backlash: 0.0, hysteresis: th, ..gearbox() };
2661 let (amp, w, dt) = (1e-7, std::f64::consts::TAU * 100.0, 1e-5);
2662 let (mut inphase, mut quad) = (0.0, 0.0);
2663 for k in 0..20_000 {
2664 let t = k as f64 * dt;
2665 let (x, rate) = (amp * (w * t).sin(), amp * w * (w * t).cos());
2666 let torque = g.torque(5.0 * x, 5.0 * rate, 0.0, 0.0).output;
2667 g.commit(5.0 * x, 0.0);
2668 // The last ten periods.
2669 if k >= 10_000 {
2670 inphase += torque * (w * t).sin() * 2.0 / 10_000.0;
2671 quad += torque * (w * t).cos() * 2.0 / 10_000.0;
2672 }
2673 }
2674 assert!((inphase / amp - 2e4).abs() < 0.01 * 2e4 && (quad / amp).abs() < 0.01 * 2e4, "{inphase} {quad}");
2675 }
2676
2677 #[test]
2678 fn gearbox_efficiency_loses_torque_in_the_direction_of_power_flow() {
2679 let mut g = gearbox();
2680 g.efficiency = 0.9;
2681 let twist = 5.0 * g.static_twist(2.0);
2682 let driving = g.torque(twist, 0.0, 0.0, 50.0);
2683 let driven = g.torque(twist, 0.0, 0.0, -50.0);
2684 assert!((driving.output - 2.0 * 0.9).abs() < 1e-9, "{}", driving.output);
2685 assert!((driven.output - 2.0 / 0.9).abs() < 1e-9, "{}", driven.output);
2686 assert!((g.torque(twist, 0.0, 0.0, 0.0).output - 2.0).abs() < 1e-12);
2687 }
2688
2689 /// A gear of ratio 10, K1 1e4 N m/rad, teeth of efficiency 0.8 (mu = 0.2), with its mesh friction; its bristle 100 K1
2690 /// (1e6 N m/rad), stiff enough that the friction law shows alone (the shipped K1:
2691 /// `the_shipped_bristle_rings_down_by_its_hand_calculated_ratio`).
2692 fn meshing() -> Gearbox {
2693 Gearbox { ratio: 10.0, half_backlash: 0.0, efficiency: 0.8, mesh_stiffness: 1e6, mesh_anchor: 0.0, ..gearbox() }
2694 }
2695
2696 /// Passing 100 N m (a twist of 0.01 rad at the output), sliding forward the output gets (1 - 0.2) 100 = 80 N m and the
2697 /// rotor puts in 100 / 10 = 10 N m at 10 times the speed: 80 / 100 = 0.8. Driven back the output takes (1 + 0.2) 100 =
2698 /// 120 N m for the rotor's 10 N m: 100 / 120 = 0.833333 = 1 / (2 - 0.8), where the faded efficiency had 0.8 either
2699 /// way. Sticking, the friction is the bristle's 1e6 N m/rad times how far the output is from its anchor: 5 N m at
2700 /// 5e-6 rad, within the bound of 20 N m.
2701 #[test]
2702 fn the_mesh_friction_passes_the_teeth_efficiency_each_way() {
2703 let g = meshing();
2704 let rotor = |out: f64| 10.0 * (out + 0.01);
2705 let driving = g.torque(rotor(1.0), 0.0, 1.0, 0.0);
2706 assert!((driving.output - 80.0).abs() < 1e-9 && (driving.rotor - 10.0).abs() < 1e-12, "{driving:?}");
2707 let driven = g.torque(rotor(-1.0), 0.0, -1.0, 0.0);
2708 assert!((driven.output - 120.0).abs() < 1e-9, "{driven:?}");
2709 assert!((driven.rotor * 10.0 / driven.output - 1.0 / 1.2).abs() < 1e-12);
2710 let stuck = g.torque(rotor(5e-6), 0.0, 5e-6, 0.0);
2711 assert!((stuck.output - 95.0).abs() < 1e-9, "{stuck:?}");
2712 // Off, as before: the faded efficiency.
2713 let faded = Gearbox { mesh_stiffness: 0.0, ..g.clone() };
2714 assert!((faded.torque(rotor(1.0), 0.0, 1.0, 1.0).output - 100.0 * faded.loss_factor(100.0, 1.0)).abs() < 1e-9);
2715 }
2716
2717 /// Where the mesh friction holds, the step is not cut for the efficiency's switch: the friction's bristle sticks and
2718 /// slides between the drive's bound and the driven-back one, and the faded factor whose damper the cuts resolve is not
2719 /// in the torque. Passing 100 N m at rest the faded gear's switch is a damper of 100^2 |ln 0.8| / 0.5 W =
2720 /// 4462.87 N m s/rad, 70 cuts of a 15.625 us sub-step on 1e-3 kg m^2; with the friction's anchor committed none.
2721 /// Measured on the moves into a slab (`collision.rs`, `assert_stops_at_the_face`), cut against uncut, 26 November
2722 /// 2026: steps of the push cut 37114 of 40000 (SCARA), 41600 of 48000 (URDF arm), 43282 of 64000 (arm on a track),
2723 /// 35276 of 48000 (palletiser), 36524 of 40000 (Stewart platform with effects.gearbox_mesh_friction), now 0 on
2724 /// each, the track of movers none either way; every hold force, depth, crash row and budget the same to 1e-6
2725 /// relative or better (palletiser 5853.6933 N against 5853.6968 N, unaccounted 2.547e-3 against 2.579e-3 J of
2726 /// 2293 J; Stewart platform 52 710.6168 N both, 4.8907e-4 J of 1707 J both), its run 974 s against 2131 s beside
2727 /// other jobs. Without the mesh friction (the shipped Stewart platform: 36629 of 40000 steps cut, 52 047.6 N,
2728 /// 5.06e-4 J of 1728 J) the faded switch keeps its cuts.
2729 #[test]
2730 fn the_mesh_friction_asks_no_cuts_for_the_efficiency_switch() {
2731 let stuck = meshing();
2732 assert_eq!(stuck.fade_damping(100.0, 0.0), 0.0);
2733 assert_eq!(fade_substeps(stuck.fade_damping(100.0, 0.0), 15.625e-6, 1e-3), 1);
2734 // Before the first step's commit the gear has the faded efficiency, and its switch is cut for.
2735 let faded = Gearbox { mesh_anchor: f64::NAN, ..meshing() };
2736 let damping = faded.fade_damping(100.0, 0.0);
2737 assert!((damping - 1e4 * 0.8f64.ln().abs() / 0.5).abs() < 1e-9, "{damping}");
2738 assert_eq!(fade_substeps(damping, 15.625e-6, 1e-3), 70);
2739 }
2740
2741 /// With the no-load running torque (`GearDrag`) at the input: a catalogue efficiency of 0.9 at 50 N m out with
2742 /// T0 = 0.1 N m at the reference speed leaves the teeth 1 / (1 / 0.9 - 10 0.1 / 50) = 0.916497. At that point, driving
2743 /// at the reference speed: T1 = 50 / (10 0.916497) + 0.1 = 5.555556 N m, 50 / (10 T1) = 0.9; at a tenth of the torque
2744 /// T1 = 5 / 9.16497 + 0.1 = 0.645556 N m, 5 / 6.45556 = 0.774527: the efficiency falls at part load.
2745 #[test]
2746 fn mesh_friction_and_drag_give_the_catalogue_efficiency_and_less_at_part_load() {
2747 let drag = GearDrag { torque: 0.1, speed: 300.0 };
2748 let tooth = drag.tooth_efficiency(0.9, 10.0, 50.0);
2749 assert!((tooth - 0.916497).abs() < 1e-6, "{tooth}");
2750 let g = Gearbox { efficiency: tooth, ..meshing() };
2751 for (out, want) in [(50.0, 0.9), (5.0, 0.774527)] {
2752 // The twist that passes out / tooth, the output sliding forward at 30 rad/s (the input at 300).
2753 let held = out / tooth;
2754 let t = g.torque(10.0 * (1.0 + held / 1e4), 300.0, 1.0, 30.0);
2755 let input = t.rotor + drag.torque(300.0, 1.0);
2756 let efficiency = t.output * 30.0 / (input * 300.0);
2757 assert!((t.output - out).abs() < 1e-9 && (efficiency - want).abs() < 1e-6, "{efficiency} at {out} N m");
2758 }
2759 }
2760
2761 /// The output (1 kg m^2) on the gear, its rotor set by `rotor(t)`, against a constant load torque `load` (a weight
2762 /// that the gear holds up), from at rest at `start`: RK4 at 1e-5 s with the anchor committed after each step. The
2763 /// output angle and speed at each step, and the energy the gear's loss power took.
2764 fn run_output(
2765 g: &mut Gearbox,
2766 rotor: impl Fn(f64) -> f64,
2767 load: f64,
2768 start: f64,
2769 seconds: f64,
2770 ) -> (Vec<(f64, f64, f64)>, f64) {
2771 let (dt, mut state, mut lost) = (1e-5, [start, 0.0], 0.0);
2772 let mut trace = Vec::new();
2773 let steps = (seconds / dt).round() as usize;
2774 let rotor_speed = |t: f64| (rotor(t + 1e-7) - rotor(t - 1e-7)) / 2e-7;
2775 for k in 0..steps {
2776 let t = k as f64 * dt;
2777 let f = |s: [f64; 2], t: f64| [s[1], g.torque(rotor(t), rotor_speed(t), s[0], s[1]).output - load];
2778 let k1 = f(state, t);
2779 let k2 = f([state[0] + 0.5 * dt * k1[0], state[1] + 0.5 * dt * k1[1]], t + 0.5 * dt);
2780 let k3 = f([state[0] + 0.5 * dt * k2[0], state[1] + 0.5 * dt * k2[1]], t + 0.5 * dt);
2781 let k4 = f([state[0] + dt * k3[0], state[1] + dt * k3[1]], t + dt);
2782 let power = |s: [f64; 2], t: f64| g.loss_power(rotor(t), rotor_speed(t), s[0], s[1]);
2783 let p0 = power(state, t);
2784 state = [
2785 state[0] + dt / 6.0 * (k1[0] + 2.0 * k2[0] + 2.0 * k3[0] + k4[0]),
2786 state[1] + dt / 6.0 * (k1[1] + 2.0 * k2[1] + 2.0 * k3[1] + k4[1]),
2787 ];
2788 lost += 0.5 * dt * (p0 + power(state, t + dt));
2789 g.commit(rotor(t + dt), state[0]);
2790 trace.push((t + dt, state[0], state[1]));
2791 }
2792 (trace, lost)
2793 }
2794
2795 /// A weight of 100 N m held by the gear (a twist of 0.01 rad, anchored there). The motor winds the gear on slowly
2796 /// (1 N m of spring torque per second at a blocked output): the output stands, but for the bristle's give of at most
2797 /// 25 / 1e6 = 2.5e-5 rad, until the gear passes 100 / 0.8 = 125 N m, the torque that lifts the weight; then it lifts.
2798 /// Wound back the other way it stands until 100 / 1.2 = 83.33 N m and then lowers: it holds anything in between.
2799 #[test]
2800 fn a_held_gear_stands_inside_its_friction_band_and_breaks_away_at_its_ends() {
2801 for (direction, edge) in [(1.0, 125.0), (-1.0, 100.0 / 1.2)] {
2802 let mut g = Gearbox { damping: 20.0, ..meshing() };
2803 // At rest the twist 0.01 rad holds the weight with no friction.
2804 let rotor = move |t: f64| 10.0 * (0.01 + direction * t / 1e4);
2805 let (trace, _) = run_output(&mut g, rotor, 100.0, 0.0, 50.0);
2806 let away = trace.iter().find(|(_, angle, _)| angle.abs() > 3e-5).expect("it never broke away");
2807 // The spring's torque then, at the output standing within the bristle's give: 1e4 (rotor / 10 - angle).
2808 let held = 1e4 * (rotor(away.0) / 10.0 - away.1);
2809 assert!((held - edge).abs() < 3.0, "direction {direction}: broke away at {held} N m, by hand {edge}");
2810 let before = trace.iter().take_while(|(t, ..)| 1e4 * (rotor(*t) / 10.0) < edge - 3.0);
2811 assert!(before.clone().all(|(_, angle, _)| angle.abs() <= 2.5e-5 + 1e-9));
2812 }
2813 }
2814
2815 /// Around zero load, the motor held: the output (1 kg m^2 on 1e4 N m/rad, 15.9 Hz) let go 0.01 rad off. The friction
2816 /// mu 1e4 |x| against the motion takes, from one turning point A1 to the next A2, mu 1e4 (A1^2 + A2^2) / 2 of the
2817 /// spring's 1e4 (A1^2 - A2^2) / 2: A2 / A1 = sqrt((1 - mu) / (1 + mu)), a cycle (1 - mu) / (1 + mu) = 0.666667, a
2818 /// damping of ln(1.5) / (2 pi) = 0.0645 (the faded efficiency gives the same ring some 1 %). The bristle's give at
2819 /// each reversal, 2 mu / 100 of the amplitude, leaves a little less: within 5 %. And the loss power integrates to the
2820 /// energy the ring lost (spring, bristle and output) within 1 %: the power jumps where the friction sticks or slides
2821 /// on inside a step, which the trapezoid takes at the step's ends, by up to F w dt = 9 W 1e-5 s each time, four times
2822 /// a cycle (seen: 0.4 %).
2823 #[test]
2824 fn a_ring_around_zero_load_decays_by_the_hand_calculated_damping() {
2825 let mut g = meshing();
2826 g.mesh_anchor = f64::NAN;
2827 let (trace, lost) = run_output(&mut g, |_| 0.0, 0.0, 0.01, 0.4);
2828 let peaks: Vec<f64> =
2829 trace.windows(3).filter(|w| w[1].1 > w[0].1 && w[1].1 >= w[2].1 && w[1].1 > 0.0).map(|w| w[1].1).collect();
2830 let ratio = peaks[1] / peaks[0];
2831 assert!((ratio / (0.8 / 1.2) - 1.0).abs() < 0.05, "a cycle {ratio}, by hand 0.666667, peaks {peaks:?}");
2832 let &(_, angle, speed) = trace.last().unwrap();
2833 let energy = |angle: f64, speed: f64| g.energy(0.0, angle) + 0.5 * speed * speed;
2834 let gone = energy(0.01, 0.0) - energy(angle, speed);
2835 assert!((lost - gone).abs() < 1e-2 * gone, "lost {lost} J, gone {gone} J");
2836 }
2837
2838 /// The same ring with the shipped bristle, sigma = K1 (`MESH_STIFFNESS`). At a turning point A the friction stands at
2839 /// its bound mu K A, its anchor at A - mu K A / sigma = A (1 - mu). Turning back the output sticks on the spring and the
2840 /// bristle (2 K) until the friction reaches the other bound, K (x - A (1 - mu)) = -mu K x at x1 = A (1 - mu) / (1 + mu),
2841 /// with v1^2 = K (1 + mu^2) (A^2 - x1^2) (1 kg m^2); then it slides, on K (1 - mu) down to x = 0 and on K (1 + mu)
2842 /// beyond, to the next turning point A2: A2^2 / A^2 = ((1 + mu^2)(1 - r^2) + (1 - mu) r^2) / (1 + mu), r = 2 / 3, = 7 / 9
2843 /// per half cycle. A cycle keeps 7 / 9 = 0.777778 of its amplitude, a damping of ln(9 / 7) / (2 pi) = 0.0400 against the
2844 /// friction law's 0.0645: the bristle's give at each reversal.
2845 #[test]
2846 fn the_shipped_bristle_rings_down_by_its_hand_calculated_ratio() {
2847 let mut g = Gearbox { mesh_stiffness: MESH_STIFFNESS * 1e4, mesh_anchor: f64::NAN, ..meshing() };
2848 let (trace, _) = run_output(&mut g, |_| 0.0, 0.0, 0.01, 0.4);
2849 let peaks: Vec<f64> =
2850 trace.windows(3).filter(|w| w[1].1 > w[0].1 && w[1].1 >= w[2].1 && w[1].1 > 0.0).map(|w| w[1].1).collect();
2851 for w in peaks.windows(2).take(4) {
2852 assert!((w[1] / w[0] - 7.0 / 9.0).abs() < 1e-4, "a cycle {}, by hand 0.777778 ({peaks:?})", w[1] / w[0]);
2853 }
2854 }
2855
2856 /// The mesh friction's bound by the direction: with the gear at an efficiency of 0.8 it takes 0.2 of the held torque
2857 /// from the output it drives; driven back 0.2 of it too at a back ratio of 1 (as before), and at r = 0.5 the back
2858 /// efficiency 0.8 x 0.5 = 0.4 exactly: the output must bring 100 / 0.4 = 250 N m, a friction of 150 N m. Held 100 N m,
2859 /// the bristle far from its anchor either way.
2860 #[test]
2861 fn the_mesh_friction_is_bounded_by_the_back_efficiency_when_driven_back() {
2862 for (ratio, back) in [(1.0, 20.0), (0.5, 150.0)] {
2863 let g = Gearbox { back_ratio: ratio, ..meshing() };
2864 assert!((g.mesh_friction(100.0, 1.0) - 20.0).abs() < 1e-12);
2865 assert!((g.mesh_friction(100.0, -1.0) + back).abs() < 1e-9, "{ratio}: {}", g.mesh_friction(100.0, -1.0));
2866 assert!((g.mesh_friction(-100.0, -1.0) + 20.0).abs() < 1e-12);
2867 assert!((g.mesh_friction(-100.0, 1.0) - back).abs() < 1e-9);
2868 }
2869 }
2870
2871 /// The step is cut where a stop is met within it and while an axis rests in it (the stiff contact's frequency is
2872 /// what the base step cannot hold: stroke 1 m, dt = 1 ms, the reach 2 steps at the speed, 2 mm at 1 m/s): 1 mm
2873 /// short of the face going in, and 1 mm or 5 cm inside it at rest, is cut by `STOP_SUBSTEPS`; mid-stroke, or with no
2874 /// stops, it is not.
2875 #[test]
2876 fn the_step_is_cut_at_a_stop_and_while_resting_in_it() {
2877 let stop = HardStop { stiffness: 1e6, damping: 200.0 };
2878 let (stroke, dt) = (1.0, 1e-3);
2879 let cut = |pos: f64, vel: f64| stop.substeps(pos, vel, stroke, dt);
2880 assert_eq!(cut(0.999, 1.0), STOP_SUBSTEPS);
2881 assert_eq!(cut(0.5, 1.0), 1);
2882 assert_eq!(cut(1.001, 0.0), STOP_SUBSTEPS);
2883 assert_eq!(cut(1.05, 0.0), STOP_SUBSTEPS);
2884 assert_eq!(HardStop { stiffness: 0.0, damping: 0.0 }.substeps(0.999, 1.0, stroke, dt), 1);
2885 }
2886}