1use crate::joint::RotaryJoint;
10use crate::mech::{BRISTLE_RATE_MAX, HoldingBrake, TravelCompliance, series_dampers};
11use sim_core::{Config, ConfigError, RatingCheck, SignalInfo};
12use std::f64::consts::PI;
13
14type Result<T> = std::result::Result<T, ConfigError>;
15
16pub const STEEL_E: f64 = 2.06e11;
18pub const STEEL_DENSITY: f64 = 7850.0;
19
20#[derive(Debug, Clone, Copy, PartialEq)]
22pub enum Mounting {
23 FixedFree,
24 SupportedSupported,
25 FixedSupported,
26 FixedFixed,
27}
28
29impl Mounting {
30 pub fn parse(name: &str) -> Option<Self> {
31 Some(match name {
32 "fixed-free" => Self::FixedFree,
33 "supported-supported" => Self::SupportedSupported,
34 "fixed-supported" => Self::FixedSupported,
35 "fixed-fixed" => Self::FixedFixed,
36 _ => return None,
37 })
38 }
39
40 pub fn mode_factor(self) -> f64 {
42 match self {
43 Self::FixedFree => 1.875_104,
44 Self::SupportedSupported => PI,
45 Self::FixedSupported => 3.926_602,
46 Self::FixedFixed => 4.730_041,
47 }
48 }
49
50 pub fn buckling_factor(self) -> f64 {
52 match self {
53 Self::FixedFree => 0.25,
54 Self::SupportedSupported => 1.0,
55 Self::FixedSupported => 2.046,
56 Self::FixedFixed => 4.0,
57 }
58 }
59}
60
61#[derive(Debug, Clone, PartialEq)]
66pub struct Converter {
67 pub lever: f64,
68 pub stiffness: f64,
69 pub backlash: f64,
70 pub efficiency: f64,
71 pub inertia: f64,
72 pub damping_ratio: f64,
73}
74
75impl Converter {
76 pub fn apply(&self, cfg: &Config, joint: &mut RotaryJoint) -> Result<()> {
87 self.apply_to(cfg, joint, f64::INFINITY)
88 }
89
90 pub fn apply_to(&self, cfg: &Config, joint: &mut RotaryJoint, output: f64) -> Result<()> {
95 self.apply_back(cfg, joint, output, self.efficiency)
96 }
97
98 pub fn apply_back(&self, cfg: &Config, joint: &mut RotaryJoint, output: f64, back_efficiency: f64) -> Result<()> {
109 let (g, l) = (&mut joint.gearbox, self.lever);
110 let i = g.ratio;
111 g.ratio = i / l;
112 let converter = self.stiffness;
113 let mesh_factor = g.mesh_stiffness / g.stiffness;
114 let series = move |k: f64| 1.0 / (l * l / k + 1.0 / converter);
115 let (k1, sigma) = (g.stiffness, g.dahl_stiffness);
116 [g.stiffness, g.upper[0], g.upper[1]] = [g.stiffness, g.upper[0], g.upper[1]].map(series);
119 g.dahl_stiffness = series(k1 + sigma) - g.stiffness;
120 g.knees = g.knees.map(|t| t / l);
121 g.hysteresis *= g.stiffness * l / k1;
122 g.band *= l;
123 g.band_compliance = g.band_compliance * l * l + 1.0 / converter;
124 let damping = g.damping / (l * l);
132 let own = self.own_damping(output);
133 let (across, arm, tau) = series_dampers(k1 / (l * l), damping, converter, own);
134 if !converter.is_finite() {
135 g.damping = damping;
136 } else if arm > 0.0 && tau * BRISTLE_RATE_MAX >= 1.0 {
137 (g.relax_stiffness, g.relax_time, g.damping) = (arm, tau, across);
138 } else {
139 g.damping = across + arm * tau;
140 }
141 g.half_backlash =
142 g.half_backlash * l + if cfg.bool("effects.gearbox_backlash")? { 0.5 * self.backlash } else { 0.0 };
143 if cfg.bool("effects.gearbox_efficiency")? {
144 g.efficiency *= self.efficiency;
145 joint.extra_efficiency *= self.efficiency;
146 g.back_ratio *= back_efficiency / self.efficiency;
147 }
148 joint.rotor_inertia += self.inertia / (i * i);
149 if g.mesh_stiffness > 0.0 {
158 let lighter = (joint.rotor_inertia * g.ratio * g.ratio).min(output);
159 let omega = BRISTLE_RATE_MAX / 4.0;
160 g.mesh_stiffness = (mesh_factor * g.stiffness).min(lighter * omega * omega);
161 }
162 joint.brake = HoldingBrake::from_config(cfg, joint.rotor_inertia)?;
163 Ok(())
164 }
165
166 fn own_damping(&self, output: f64) -> f64 {
169 if output.is_finite() && self.stiffness.is_finite() {
170 2.0 * self.damping_ratio * (self.stiffness * output).sqrt()
171 } else {
172 0.0
173 }
174 }
175}
176
177#[derive(Debug, Clone, PartialEq)]
181pub struct BackDriven {
182 pub converter: Converter,
183 pub back_efficiency: f64,
184 pub travel: Option<TravelCompliance>,
185}
186
187impl std::ops::Deref for BackDriven {
188 type Target = Converter;
189 fn deref(&self) -> &Converter {
190 &self.converter
191 }
192}
193
194impl BackDriven {
195 pub fn apply(&self, cfg: &Config, joint: &mut RotaryJoint) -> Result<()> {
196 self.apply_to(cfg, joint, f64::INFINITY)
197 }
198
199 pub fn apply_to(&self, cfg: &Config, joint: &mut RotaryJoint, output: f64) -> Result<()> {
200 let l2 = self.lever * self.lever;
203 let gear = [joint.gearbox.stiffness / l2, joint.gearbox.damping / l2];
204 self.converter.apply_back(cfg, joint, output, self.back_efficiency)?;
205 joint.gearbox.travel =
206 self.travel.map(|t| TravelCompliance { gear, converter: [self.stiffness, self.own_damping(output)], ..t });
207 Ok(())
208 }
209}
210
211#[derive(Debug, Clone, PartialEq)]
223pub struct BallScrew {
224 pub lead: f64,
225 pub nominal_diameter: f64,
226 pub root_diameter: f64,
227 pub length: f64,
228 pub mounting: Mounting,
229 pub efficiency: f64,
230 pub back_efficiency: f64,
232 pub nut_stiffness: f64,
233 pub bearing_stiffness: f64,
234 pub preload: f64,
235 pub dynamic_rating: f64,
236 pub static_rating: f64,
237 pub load_factor: f64,
238 pub static_safety: f64,
239 pub speed_factor: f64,
240 pub buckling_safety: f64,
241 pub max_dn: f64,
242 pub axial_damping_ratio: f64,
243 pub fixed_bearing_at: Option<f64>,
246}
247
248fn damping_ratio(cfg: &Config, key: &str) -> Result<f64> {
250 if cfg.get(key).is_err() {
251 return Ok(0.0);
252 }
253 let zeta = cfg.non_negative(key)?;
254 if zeta >= 1.0 {
255 return Err(ConfigError::Invalid(key.into()));
256 }
257 Ok(zeta)
258}
259
260impl BallScrew {
261 pub fn from_config(cfg: &Config) -> Result<Self> {
262 let p = |name: &str| cfg.positive(&format!("screw.{name}"));
263 let mounting = cfg
264 .get("screw.mounting")?
265 .as_str()
266 .and_then(Mounting::parse)
267 .ok_or_else(|| ConfigError::Invalid("screw.mounting".into()))?;
268 let (nominal, root) = (p("nominal_diameter_m")?, p("root_diameter_m")?);
269 if root > nominal {
270 return Err(ConfigError::Invalid("screw.root_diameter_m".into()));
271 }
272 let efficiency = p("efficiency")?;
273 if efficiency > 1.0 {
274 return Err(ConfigError::Invalid("screw.efficiency".into()));
275 }
276 let lead = p("lead_m")?;
277 let (efficiency, back_efficiency) =
279 if cfg.get("effects.screw_lead_efficiency").is_ok() && cfg.bool("effects.screw_lead_efficiency")? {
280 let mu = cfg.positive("screw.friction_coefficient")?;
281 let back = Self::lead_back_efficiency(lead, nominal, mu);
282 if back <= 0.0 {
283 return Err(ConfigError::Invalid(
284 "screw.friction_coefficient (the screw locks itself driven back: its efficiency there is \
285 not positive, and this gearbox does not model a self-locking screw)"
286 .into(),
287 ));
288 }
289 (Self::lead_efficiency(lead, nominal, mu), back)
290 } else {
291 (efficiency, efficiency)
292 };
293 Ok(Self {
294 lead,
295 nominal_diameter: nominal,
296 root_diameter: root,
297 length: p("length_m")?,
298 mounting,
299 efficiency,
300 back_efficiency,
301 nut_stiffness: p("nut_stiffness_n_m")?,
302 bearing_stiffness: p("bearing_stiffness_n_m")?,
303 preload: cfg.non_negative("screw.preload_n")?,
304 dynamic_rating: p("dynamic_load_rating_n")?,
305 static_rating: p("static_load_rating_n")?,
306 load_factor: p("load_factor")?,
307 static_safety: p("static_safety_factor")?,
308 speed_factor: p("critical_speed_factor")?,
309 buckling_safety: p("buckling_safety_factor")?,
310 max_dn: cfg.non_negative("screw.max_dn")?,
311 axial_damping_ratio: damping_ratio(cfg, "screw.axial_damping_ratio")?,
312 fixed_bearing_at: if cfg.get("effects.screw_stiffness_with_position").is_ok()
314 && cfg.bool("effects.screw_stiffness_with_position")?
315 {
316 Some(cfg.f64("screw.fixed_bearing_at_m")?)
317 } else {
318 None
319 },
320 })
321 }
322
323 pub fn lead_efficiency(lead: f64, nominal_diameter: f64, mu: f64) -> f64 {
328 let tan_beta = lead / (PI * nominal_diameter);
329 (1.0 - mu * tan_beta) / (1.0 + mu / tan_beta)
330 }
331
332 pub fn lead_back_efficiency(lead: f64, nominal_diameter: f64, mu: f64) -> f64 {
336 let tan_beta = lead / (PI * nominal_diameter);
337 (1.0 - mu / tan_beta) / (1.0 + mu * tan_beta)
338 }
339
340 pub fn ratio(&self) -> f64 {
342 2.0 * PI / self.lead
343 }
344
345 pub fn inertia(&self) -> f64 {
347 PI * STEEL_DENSITY * self.length * self.nominal_diameter.powi(4) / 32.0
348 }
349
350 fn section(&self) -> (f64, f64) {
352 let d = self.root_diameter;
353 (PI * d.powi(4) / 64.0, PI * d * d / 4.0)
354 }
355
356 pub fn critical_speed_rpm(&self) -> f64 {
359 let (i, a) = self.section();
360 let omega = (self.mounting.mode_factor() / self.length).powi(2) * (STEEL_E * i / (STEEL_DENSITY * a)).sqrt();
361 omega * 60.0 / (2.0 * PI)
362 }
363
364 pub fn allowed_speed_rpm(&self) -> f64 {
367 self.speed_factor * self.critical_speed_rpm()
368 }
369
370 pub fn buckling_load(&self) -> f64 {
372 self.mounting.buckling_factor() * PI * PI * STEEL_E * self.section().0 / (self.length * self.length)
373 }
374
375 pub fn allowed_buckling_force(&self) -> f64 {
377 self.buckling_load() / self.buckling_safety
378 }
379
380 pub fn allowed_static_force(&self) -> f64 {
382 self.static_rating / self.static_safety
383 }
384
385 pub fn stiffness(&self, x: f64) -> f64 {
389 let ae = STEEL_E * self.section().1;
390 let x = x.clamp(1e-3 * self.length, self.length);
391 let shaft = match self.mounting {
392 Mounting::FixedFixed => ae * self.length / (x * (self.length - x).max(1e-3 * self.length)),
393 _ => ae / x,
394 };
395 1.0 / (1.0 / shaft + 1.0 / self.nut_stiffness + 1.0 / self.bearing_stiffness)
396 }
397
398 pub fn preload_torque(&self) -> f64 {
401 let tan_beta = self.lead / (PI * self.nominal_diameter);
402 0.05 / tan_beta.sqrt() * self.preload * self.lead / (2.0 * PI)
403 }
404
405 pub fn equivalent_load(&self, force: f64) -> f64 {
408 let f = force.abs();
409 let lift = 2.83 * self.preload;
410 if self.preload <= 0.0 || f >= lift { f } else { self.preload * (1.0 + f / lift).powf(1.5) }
411 }
412
413 pub fn damage_rate(&self, force: f64, rpm: f64) -> f64 {
416 60.0 * rpm.abs() * (self.load_factor * self.equivalent_load(force) / self.dynamic_rating).powi(3) / 1e6
417 }
418
419 pub fn dn(&self, rpm: f64) -> f64 {
421 self.nominal_diameter * 1e3 * rpm.abs()
422 }
423
424 pub fn converter(&self, x: f64) -> BackDriven {
428 BackDriven {
429 converter: Converter {
430 lever: 1.0 / self.ratio(),
431 stiffness: self.stiffness(x),
432 backlash: 0.0,
433 efficiency: self.efficiency,
434 inertia: self.inertia(),
435 damping_ratio: self.axial_damping_ratio,
436 },
437 back_efficiency: self.back_efficiency,
438 travel: self.travel(x),
439 }
440 }
441
442 pub fn travel(&self, x: f64) -> Option<TravelCompliance> {
444 let fixed_bearing_at = self.fixed_bearing_at?;
445 let mut t = TravelCompliance {
446 ae: STEEL_E * self.section().1,
447 length: self.length,
448 both_ends: self.mounting == Mounting::FixedFixed,
449 fixed_bearing_at,
450 reference: 0.0,
451 gear: [0.0; 2],
452 converter: [0.0; 2],
453 };
454 t.reference = t.shaft(x).0;
455 Some(t)
456 }
457
458 pub fn softest_position(&self) -> f64 {
460 if self.mounting == Mounting::FixedFixed { 0.5 * self.length } else { self.length }
461 }
462}
463
464const RACK_PRESSURE_ANGLE_DEG: f64 = 20.0;
467
468#[derive(Debug, Clone, PartialEq)]
474pub struct RackPinion {
475 pub module: f64,
476 pub teeth: f64,
477 pub helix_angle: f64,
478 pub efficiency: f64,
479 pub stiffness: f64,
480 pub backlash: f64,
481 pub pinion_inertia: f64,
482 pub rated_force: f64,
483 pub service_factor: f64,
484 pub pressure_angle: f64,
486 pub damping_ratio: f64,
487}
488
489impl RackPinion {
490 pub fn from_config(cfg: &Config) -> Result<Self> {
491 let p = |name: &str| cfg.positive(&format!("rack.{name}"));
492 let helix = cfg.non_negative("rack.helix_angle_deg")?;
493 let efficiency = p("efficiency")?;
494 if helix >= 45.0 || efficiency > 1.0 {
495 return Err(ConfigError::Invalid(
496 if helix >= 45.0 { "rack.helix_angle_deg" } else { "rack.efficiency" }.into(),
497 ));
498 }
499 let alpha =
500 if cfg.get("rack.pressure_angle_deg").is_ok() { p("pressure_angle_deg")? } else { RACK_PRESSURE_ANGLE_DEG };
501 if alpha >= 45.0 {
502 return Err(ConfigError::Invalid("rack.pressure_angle_deg".into()));
503 }
504 Ok(Self {
505 pressure_angle: alpha.to_radians(),
506 module: p("module_m")?,
507 teeth: p("teeth")?,
508 helix_angle: helix.to_radians(),
509 efficiency,
510 stiffness: p("stiffness_n_m")?,
511 backlash: cfg.non_negative("rack.backlash_m")?,
512 pinion_inertia: p("pinion_inertia_kgm2")?,
513 rated_force: p("rated_feed_force_n")?,
514 service_factor: p("service_factor")?,
515 damping_ratio: damping_ratio(cfg, "rack.damping_ratio")?,
516 })
517 }
518
519 pub fn radius(&self) -> f64 {
521 self.module * self.teeth / (2.0 * self.helix_angle.cos())
522 }
523
524 pub fn allowed_force(&self) -> f64 {
526 self.rated_force / self.service_factor
527 }
528
529 pub fn converter(&self) -> Converter {
530 Converter {
531 lever: self.radius(),
532 stiffness: self.stiffness,
533 backlash: self.backlash,
534 efficiency: self.efficiency,
535 inertia: self.pinion_inertia,
536 damping_ratio: self.damping_ratio,
537 }
538 }
539}
540
541#[derive(Debug, Clone, PartialEq)]
546pub struct LinearMotor {
547 pub attraction: f64,
548 pub pole_pitch: f64,
549}
550
551impl LinearMotor {
552 pub fn from_config(cfg: &Config) -> Result<Self> {
553 Ok(Self {
554 attraction: cfg.non_negative("linear_motor.attraction_force_n")?,
555 pole_pitch: cfg.positive("linear_motor.pole_pitch_m")?,
556 })
557 }
558
559 pub fn cogging_order(&self) -> f64 {
561 2.0 * PI / self.pole_pitch
562 }
563}
564
565#[derive(Debug, Clone, PartialEq)]
568pub struct WormGear {
569 pub lead_angle: f64,
570 pub friction: f64,
571 pub pressure_angle: f64,
572}
573
574impl WormGear {
575 pub fn from_config(cfg: &Config) -> Result<Self> {
576 let gamma = cfg.positive("worm.lead_angle_deg")?;
577 let alpha = cfg.non_negative("worm.pressure_angle_deg")?;
578 if gamma >= 45.0 || alpha >= 45.0 {
579 return Err(ConfigError::Invalid(
580 if gamma >= 45.0 { "worm.lead_angle_deg" } else { "worm.pressure_angle_deg" }.into(),
581 ));
582 }
583 Ok(Self {
584 lead_angle: gamma.to_radians(),
585 friction: cfg.non_negative("worm.friction_coefficient")?,
586 pressure_angle: alpha.to_radians(),
587 })
588 }
589
590 fn friction_angle(&self) -> f64 {
592 (self.friction / self.pressure_angle.cos()).atan()
593 }
594
595 pub fn efficiency(&self) -> f64 {
597 self.lead_angle.tan() / (self.lead_angle + self.friction_angle()).tan()
598 }
599
600 pub fn back_efficiency(&self) -> f64 {
602 (self.lead_angle - self.friction_angle()).tan() / self.lead_angle.tan()
603 }
604}
605
606#[derive(Debug, Clone, PartialEq)]
611pub struct StrainWave {
612 pub rated_torque: f64,
613 pub rated_speed: f64,
614 pub rated_life: f64,
615}
616
617impl StrainWave {
618 pub fn from_config(cfg: &Config) -> Result<Self> {
619 let p = |name: &str| cfg.positive(&format!("strain_wave.{name}"));
620 Ok(Self {
621 rated_torque: p("rated_torque_nm")?,
622 rated_speed: p("rated_input_speed_rpm")?,
623 rated_life: p("rated_life_h")?,
624 })
625 }
626
627 pub fn damage_rate(&self, torque: f64, input_rpm: f64) -> f64 {
629 input_rpm.abs() / self.rated_speed * (torque.abs() / self.rated_torque).powi(3) / self.rated_life
630 }
631}
632
633impl BallScrew {
639 pub fn signal_infos(&self, id: &str, key: &'static str) -> Vec<SignalInfo> {
640 vec![
641 SignalInfo::new(format!("screw.{id}.speed"), key, "quantity-screw-speed", "rpm"),
642 SignalInfo::new(format!("screw.{id}.dn"), key, "quantity-screw-dn", "mm rpm"),
643 SignalInfo::new(format!("screw.{id}.damage_rate"), key, "quantity-damage-rate", "1/h"),
644 ]
645 }
646
647 pub fn signals(&self, speed: f64, force: f64, out: &mut Vec<f64>) {
649 let rpm = speed * self.ratio() * 60.0 / (2.0 * PI);
650 out.extend([rpm, self.dn(rpm), self.damage_rate(force, rpm)]);
651 }
652
653 pub fn rating_checks(&self, id: &str, motor: usize, required_life_h: Option<f64>) -> Vec<RatingCheck> {
654 let check = |check: &'static str, signal: &str, limit: f64, life: bool| RatingCheck {
655 check,
656 signal: signal.into(),
657 motor: Some(motor),
658 limit,
659 life,
660 };
661 let force = format!("joint.{id}.force");
662 let mut out = vec![
663 check("screw-speed", &format!("screw.{id}.speed"), self.allowed_speed_rpm(), false),
664 check("screw-buckling", &force, self.allowed_buckling_force(), false),
665 check("screw-static", &force, self.allowed_static_force(), false),
666 ];
667 if self.max_dn > 0.0 {
668 out.push(check("screw-dn", &format!("screw.{id}.dn"), self.max_dn, false));
669 }
670 if let Some(life) = required_life_h {
671 out.push(check("screw-life", &format!("screw.{id}.damage_rate"), life, true));
672 }
673 out
674 }
675}
676
677impl RackPinion {
678 pub fn signal_info(&self, id: &str, key: &'static str) -> SignalInfo {
679 SignalInfo::new(format!("rack.{id}.feed_force"), key, "quantity-rack-feed-force", "N")
680 }
681
682 pub fn feed_force(force: f64, speed: f64, efficiency: f64) -> f64 {
686 if force * speed >= 0.0 { force / efficiency } else { force * efficiency }
687 }
688
689 pub fn radial_load(&self, tooth_force: f64) -> f64 {
694 let apart = self.pressure_angle.tan() / self.helix_angle.cos();
695 tooth_force.abs() * (1.0 + apart * apart).sqrt()
696 }
697
698 pub fn rating_checks(&self, id: &str, motor: usize) -> Vec<RatingCheck> {
700 vec![RatingCheck {
701 check: "rack-feed-force",
702 signal: format!("rack.{id}.feed_force"),
703 motor: Some(motor),
704 limit: self.allowed_force(),
705 life: false,
706 }]
707 }
708}
709
710impl StrainWave {
713 pub fn signal_info(&self, id: &str, key: &'static str) -> SignalInfo {
714 SignalInfo::new(format!("strain_wave.{id}.damage_rate"), key, "quantity-damage-rate", "1/h")
715 }
716
717 pub fn signal(&self, torque: f64, input_speed: f64) -> f64 {
718 self.damage_rate(torque, input_speed * 60.0 / (2.0 * PI))
719 }
720
721 pub fn rating_check(&self, id: &str, motor: usize, required_life_h: f64) -> RatingCheck {
722 RatingCheck {
723 check: "strain-wave-life",
724 signal: format!("strain_wave.{id}.damage_rate"),
725 motor: Some(motor),
726 limit: required_life_h,
727 life: true,
728 }
729 }
730}
731
732#[cfg(test)]
733mod tests {
734 use super::*;
735
736 #[test]
744 fn a_gear_at_the_bristle_cap_of_a_light_drum_stays_stable_and_closes_its_energy() {
745 let text = "format_version = 1\n[effects]\njoint_friction = false\nhard_stops = false\nmotor_friction = false\n\
746 torque_ripple = false\ngearbox_backlash = false\ngearbox_efficiency = true\ngearbox_drag = false\n\
747 motor_stiction = false\ngearbox_lost_motion = false\ngearbox_stiffness_curve = false\nthermal_feedback = false\n\
748 holding_brake = false\ngearbox_mesh_friction = true\n\
749 [motor]\nrotor_inertia_kgm2 = 1e-4\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\n\
750 friction_smoothing_rad_s = 1e-3\nfriction_breakaway_nm = 0.0\nfriction_stribeck_rad_s = 2.0\nripple_fraction = 0.0\n\
751 ripple_order = 6.0\ncogging_nm = 0.0\ncogging_order = 6.0\nbrake_torque_nm = 5.0\n\
752 [gearbox]\nratio = 20.0\nefficiency = 0.9\nbacklash_rad = 0.0\nstiffness_nm_rad = 2e5\ndamping_nm_s_rad = 5.0\n\
753 inertia_at_input_kgm2 = 1e-4\nefficiency_torque_nm = 100.0\nno_load_torque_nm = 0.0\nno_load_speed_rpm = 3000.0\n\
754 lost_motion_band_rad = 0.0\nhysteresis_rad = 0.0\nstiffness_t1_nm = 100.0\nstiffness_t2_nm = 100.0\n\
755 stiffness_k2_nm_rad = 2e5\nstiffness_k3_nm_rad = 2e5\n\
756 [joint]\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 1e-3\n\
757 min_angle_deg = -45.0\nmax_angle_deg = 90.0\nstop_stiffness_nm_rad = 1e5\nstop_damping_nm_s_rad = 0.0\n";
758 let cfg = Config::parse(text).unwrap();
759 let drum = Converter {
760 lever: 0.025,
761 stiffness: f64::INFINITY,
762 backlash: 0.0,
763 efficiency: 1.0,
764 inertia: 0.0,
765 damping_ratio: 0.0,
766 };
767 let mass = 0.32;
768 let joint = |output: f64| {
769 let mut j = RotaryJoint::from_config(&cfg).unwrap();
770 drum.apply_to(&cfg, &mut j, output).unwrap();
771 j
772 };
773 assert!((joint(f64::INFINITY).gearbox.mesh_stiffness / 3.2e8 - 1.0).abs() < 1e-12);
774 let mut j = joint(mass);
775 let cap = mass * (BRISTLE_RATE_MAX / 4.0).powi(2);
776 assert!((j.gearbox.mesh_stiffness / cap - 1.0).abs() < 1e-12 && (cap / 2e8 - 1.0).abs() < 1e-12);
777 let command = |t: f64| (std::f64::consts::TAU * 2.0 * t).sin();
778 let rates = |j: &RotaryJoint, s: [f64; 4], t: f64| {
779 let (gear, acc, _) = j.rotor(command(t), s[0], s[1], s[2], s[3], 0.0, false);
780 [s[1], acc, s[3], (gear.output + j.output_torque(s[2], s[3])) / mass]
781 };
782 let energy = |j: &RotaryJoint, s: [f64; 4]| {
783 0.5 * j.rotor_inertia * s[1] * s[1] + 0.5 * mass * s[3] * s[3] + j.gearbox.energy(s[0], s[2])
784 };
785 let power =
786 |j: &RotaryJoint, s: [f64; 4], t: f64| (command(t) * s[1], j.gearbox.loss_power(s[0], s[1], s[2], s[3]));
787 let (dt, mut s, mut t) = (15.625e-6, [0.0; 4], 0.0);
788 let (start, mut work, mut through, mut lost, mut peak) = (energy(&j, s), 0.0, 0.0, 0.0, 0.0f64);
789 for _ in 0..64000 {
790 let add = |s: [f64; 4], k: [f64; 4], h: f64| std::array::from_fn(|i| s[i] + h * k[i]);
791 let k1 = rates(&j, s, t);
792 let k2 = rates(&j, add(s, k1, 0.5 * dt), t + 0.5 * dt);
793 let k3 = rates(&j, add(s, k2, 0.5 * dt), t + 0.5 * dt);
794 let k4 = rates(&j, add(s, k3, dt), t + dt);
795 let (p0, l0) = power(&j, s, t);
796 s = std::array::from_fn(|i| s[i] + dt / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]));
797 t += dt;
798 let (p1, l1) = power(&j, s, t);
799 (work, through, lost) =
800 (work + 0.5 * dt * (p0 + p1), through + 0.5 * dt * (p0.abs() + p1.abs()), lost + 0.5 * dt * (l0 + l1));
801 j.gearbox.commit(s[0], s[2]);
802 peak = peak.max(s[3].abs());
803 }
804 let off = work - (energy(&j, s) - start) - lost;
805 println!(
806 "peak speed {peak:.4} m/s, work {work:.6} J, lost {lost:.6} J, off {off:.3e} J of {through:.6} J through"
807 );
808 assert!(s.iter().all(|x| x.is_finite()) && peak > 0.1 && peak < 2.0, "{s:?}, peak {peak} m/s");
809 assert!(lost > 0.0 && off.abs() < 1e-6 * lost, "off by {off} J, lost {lost} J of {through} J through");
810 }
811
812 fn screw() -> BallScrew {
813 BallScrew {
814 lead: 0.01,
815 nominal_diameter: 0.025,
816 root_diameter: 0.021,
817 length: 1.0,
818 mounting: Mounting::FixedSupported,
819 efficiency: 0.9,
820 back_efficiency: 0.9,
821 nut_stiffness: 5e8,
822 bearing_stiffness: 1e9,
823 preload: 500.0,
824 dynamic_rating: 15000.0,
825 static_rating: 30000.0,
826 load_factor: 1.2,
827 static_safety: 2.0,
828 speed_factor: 0.8,
829 buckling_safety: 2.0,
830 max_dn: 70000.0,
831 axial_damping_ratio: 0.0,
832 fixed_bearing_at: None,
833 }
834 }
835
836 fn close(a: f64, b: f64, what: &str) {
837 assert!((a / b - 1.0).abs() < 1e-4, "{what}: {a} against {b} by hand");
838 }
839
840 #[test]
847 fn a_ball_screw_has_the_hand_calculated_limits() {
848 let s = screw();
849 close(s.ratio(), 628.3185, "ratio");
850 close(s.critical_speed_rpm(), 3959.7, "critical speed");
851 close(s.allowed_speed_rpm(), 0.8 * 3959.7, "allowed speed");
852 close(s.buckling_load(), 39711.0, "buckling");
853 close(s.allowed_buckling_force(), 19855.5, "buckling allowed");
854 close(s.allowed_static_force(), 15000.0, "static");
855 close(s.inertia(), 3.0104e-4, "inertia");
856 close(s.stiffness(0.5), 9.9923e7, "stiffness");
857 close(s.preload_torque(), 0.11151, "preload drag");
858 close(s.dn(2000.0), 50000.0, "dn");
859 }
860
861 #[test]
866 fn the_screw_efficiency_follows_the_lead_angle_with_its_switch() {
867 close(BallScrew::lead_efficiency(0.01, 0.025, 0.003), 0.976607, "test screw");
868 close(BallScrew::lead_efficiency(0.04, 0.04, 0.003), 0.989717, "ISW screw");
869 let text = |on: bool| {
870 format!(
871 "format_version = 1\n[effects]\nscrew_lead_efficiency = {on}\n[screw]\nlead_m = 0.04\nnominal_diameter_m = 0.04\n\
872 root_diameter_m = 0.0337\nlength_m = 1.8\nmounting = \"fixed-supported\"\nefficiency = 0.9\n\
873 friction_coefficient = 0.003\nnut_stiffness_n_m = 5e8\nbearing_stiffness_n_m = 1e9\npreload_n = 500.0\n\
874 dynamic_load_rating_n = 15000.0\nstatic_load_rating_n = 30000.0\nload_factor = 1.2\n\
875 static_safety_factor = 2.0\ncritical_speed_factor = 0.8\nbuckling_safety_factor = 2.0\nmax_dn = 0.0\n"
876 )
877 };
878 let screw = |on| BallScrew::from_config(&Config::parse(&text(on)).unwrap()).unwrap();
879 assert_eq!(screw(false).efficiency, 0.9);
880 close(screw(true).efficiency, 0.989717, "from the config");
881 }
882
883 #[test]
886 fn the_screw_life_takes_preload_and_load_factor() {
887 let s = screw();
888 close(s.equivalent_load(1000.0), 1114.8, "preloaded");
889 close(s.equivalent_load(-2000.0), 2000.0, "lifted");
890 close(s.damage_rate(2000.0, -1000.0), 2.4576e-4, "damage");
891 assert_eq!(BallScrew { preload: 0.0, ..s }.equivalent_load(300.0), 300.0);
892 }
893
894 #[test]
896 fn a_helical_pinion_has_its_pitch_radius() {
897 let r = RackPinion {
898 module: 0.002,
899 teeth: 30.0,
900 helix_angle: 19.5283f64.to_radians(),
901 efficiency: 0.97,
902 stiffness: 1e8,
903 backlash: 0.0,
904 pinion_inertia: 1e-4,
905 rated_force: 3000.0,
906 service_factor: 1.5,
907 pressure_angle: 20f64.to_radians(),
908 damping_ratio: 0.0,
909 };
910 close(r.radius() * 2.0 * PI, 0.2, "travel per turn");
911 close(r.allowed_force(), 2000.0, "allowed force");
912 }
913
914 #[test]
917 fn a_worm_gear_has_the_hand_calculated_efficiencies() {
918 let w = WormGear { lead_angle: 5f64.to_radians(), friction: 0.05, pressure_angle: 20f64.to_radians() };
919 close(w.efficiency(), 0.61891, "forward");
920 close(w.back_efficiency(), 0.38997, "back");
921 assert!(WormGear { lead_angle: 2f64.to_radians(), ..w }.back_efficiency() < 0.0);
922 }
923
924 #[test]
926 fn a_strain_wave_gear_wears_by_the_cube_of_its_torque() {
927 let g = StrainWave { rated_torque: 50.0, rated_speed: 2000.0, rated_life: 7000.0 };
928 close(g.damage_rate(-100.0, 1000.0), 5.7143e-4, "damage");
929 }
930
931 #[test]
932 fn a_linear_motor_cogs_once_per_pole_pitch() {
933 close(LinearMotor { attraction: 0.0, pole_pitch: 0.024 }.cogging_order(), 261.799, "order");
934 }
935 #[test]
939 fn the_screw_reports_and_checks_by_hand() {
940 let s = screw();
941 let mut out = Vec::new();
942 s.signals(0.5, 2000.0, &mut out);
943 close(out[0], 3000.0, "rpm");
944 close(out[1], 75000.0, "dn");
945 close(out[2], 7.3728e-4, "damage");
946 assert_eq!(
947 s.signal_infos("3", "joint-3").iter().map(|i| i.id.as_str()).collect::<Vec<_>>(),
948 ["screw.3.speed", "screw.3.dn", "screw.3.damage_rate"]
949 );
950 let checks = s.rating_checks("3", 2, Some(20000.0));
951 let limit =
952 |id: &str| checks.iter().find(|c| c.check == id).map(|c| (c.limit, c.signal.clone(), c.life, c.motor));
953 assert_eq!(limit("screw-life"), Some((20000.0, "screw.3.damage_rate".into(), true, Some(2))));
954 close(limit("screw-speed").unwrap().0, 0.8 * 3959.7, "speed limit");
955 close(limit("screw-buckling").unwrap().0, 19855.5, "buckling limit");
956 assert_eq!(limit("screw-static").unwrap().1, "joint.3.force");
957 assert_eq!(limit("screw-dn").unwrap().0, 70000.0);
958 let plain = BallScrew { max_dn: 0.0, ..s }.rating_checks("3", 2, None);
959 assert!(plain.iter().all(|c| c.check != "screw-dn" && c.check != "screw-life"));
960 for c in &checks {
961 assert_eq!(c.life, crate::analysis::AT_LEAST.contains(&c.check), "{}", c.check);
962 }
963 }
964
965 #[test]
967 fn the_strain_wave_gear_reports_its_wear_from_the_input_speed() {
968 let g = StrainWave { rated_torque: 50.0, rated_speed: 2000.0, rated_life: 7000.0 };
969 close(g.signal(100.0, 1000.0 * 2.0 * PI / 60.0), 5.7143e-4, "damage");
970 let c = g.rating_check("2", 1, 15000.0);
971 assert!(
972 c.life && c.check == "strain-wave-life" && c.signal == "strain_wave.2.damage_rate" && c.limit == 15000.0
973 );
974 }
975
976 #[test]
977 fn a_rack_is_checked_against_its_feed_force_over_the_service_factor() {
978 let r = RackPinion {
979 module: 0.002,
980 teeth: 30.0,
981 helix_angle: 0.0,
982 efficiency: 0.97,
983 stiffness: 1e8,
984 backlash: 0.0,
985 pinion_inertia: 1e-4,
986 rated_force: 3000.0,
987 service_factor: 1.25,
988 pressure_angle: 20f64.to_radians(),
989 damping_ratio: 0.0,
990 };
991 let c = &r.rating_checks("1", 0)[0];
992 assert!(c.check == "rack-feed-force" && c.signal == "rack.1.feed_force" && c.limit == 2400.0 && !c.life);
993 close(RackPinion::feed_force(970.0, 1.0, 0.97), 1000.0, "driving");
995 close(RackPinion::feed_force(970.0, -1.0, 0.97), 940.9, "braking");
996 close(r.converter().lever, 0.03, "lever");
998 }
999
1000 #[test]
1004 fn the_screw_driven_back_loses_by_thks_back_efficiency_and_a_locking_one_is_refused() {
1005 assert!((BallScrew::lead_back_efficiency(0.04, 0.04, 0.003) - 0.989_630_2).abs() < 1e-7);
1006 let lead7 = 7f64.to_radians().tan() * PI * 0.04;
1007 assert!((BallScrew::lead_efficiency(lead7, 0.04, 0.003) - 0.975_790_1).abs() < 1e-7);
1008 assert!((BallScrew::lead_back_efficiency(lead7, 0.04, 0.003) - 0.975_207_7).abs() < 1e-7);
1009 assert!(BallScrew::lead_back_efficiency(0.003 * PI * 0.04, 0.04, 0.003).abs() < 1e-12);
1010 let text = |mu: f64| {
1011 format!(
1012 "format_version = 1\n[effects]\nscrew_lead_efficiency = true\n[screw]\nlead_m = 0.04\nnominal_diameter_m = 0.04\n\
1013 root_diameter_m = 0.0337\nlength_m = 1.8\nmounting = \"fixed-supported\"\nefficiency = 0.9\n\
1014 friction_coefficient = {mu}\nnut_stiffness_n_m = 5e8\nbearing_stiffness_n_m = 1e9\npreload_n = 500.0\n\
1015 dynamic_load_rating_n = 15000.0\nstatic_load_rating_n = 30000.0\nload_factor = 1.2\n\
1016 static_safety_factor = 2.0\ncritical_speed_factor = 0.8\nbuckling_safety_factor = 2.0\nmax_dn = 0.0\n"
1017 )
1018 };
1019 let screw = BallScrew::from_config(&Config::parse(&text(0.003)).unwrap()).unwrap();
1020 assert!((screw.back_efficiency - 0.989_630_2).abs() < 1e-7);
1021 let err = BallScrew::from_config(&Config::parse(&text(0.4)).unwrap()).unwrap_err();
1023 assert!(format!("{err:?}").contains("locks itself"), "{err:?}");
1024 }
1025
1026 #[test]
1032 fn a_converter_with_its_own_back_efficiency_loses_so_driven_back_and_the_budget_has_it() {
1033 let text = "format_version = 1\n[effects]\njoint_friction = false\nhard_stops = false\nmotor_friction = false\n\
1034 torque_ripple = false\ngearbox_backlash = false\ngearbox_efficiency = true\ngearbox_drag = false\n\
1035 motor_stiction = false\ngearbox_lost_motion = false\ngearbox_stiffness_curve = false\nthermal_feedback = false\n\
1036 holding_brake = false\ngearbox_mesh_friction = false\n\
1037 [motor]\nrotor_inertia_kgm2 = 1e-4\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\n\
1038 friction_smoothing_rad_s = 1e-3\nfriction_breakaway_nm = 0.0\nfriction_stribeck_rad_s = 2.0\nripple_fraction = 0.0\n\
1039 ripple_order = 6.0\ncogging_nm = 0.0\ncogging_order = 6.0\nbrake_torque_nm = 5.0\n\
1040 [gearbox]\nratio = 20.0\nefficiency = 0.9\nbacklash_rad = 0.0\nstiffness_nm_rad = 2e5\ndamping_nm_s_rad = 5.0\n\
1041 inertia_at_input_kgm2 = 1e-4\nefficiency_torque_nm = 100.0\nno_load_torque_nm = 0.0\nno_load_speed_rpm = 3000.0\n\
1042 lost_motion_band_rad = 0.0\nhysteresis_rad = 0.0\nstiffness_t1_nm = 100.0\nstiffness_t2_nm = 100.0\n\
1043 stiffness_k2_nm_rad = 2e5\nstiffness_k3_nm_rad = 2e5\n\
1044 [joint]\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 1e-3\n\
1045 min_angle_deg = -45.0\nmax_angle_deg = 90.0\nstop_stiffness_nm_rad = 1e5\nstop_damping_nm_s_rad = 0.0\n";
1046 let cfg = Config::parse(text).unwrap();
1047 let converter = Converter {
1048 lever: 1.0,
1049 stiffness: f64::INFINITY,
1050 backlash: 0.0,
1051 efficiency: 0.95,
1052 inertia: 0.0,
1053 damping_ratio: 0.0,
1054 };
1055 let make = |back: f64| {
1056 let mut j = RotaryJoint::from_config(&cfg).unwrap();
1057 converter.apply_back(&cfg, &mut j, f64::INFINITY, back).unwrap();
1058 j.gearbox
1059 };
1060 let (own, alike) = (make(0.9), make(0.95));
1061 assert!(
1062 (own.loss_factor(1.0, 1e3) - 0.855).abs() < 1e-12 && (alike.loss_factor(1.0, 1e3) - 0.855).abs() < 1e-12
1063 );
1064 assert!((own.loss_factor(1.0, -1e3) - 1.0 / 0.81).abs() < 1e-12, "{}", own.loss_factor(1.0, -1e3));
1065 assert!((alike.loss_factor(1.0, -1e3) - 1.0 / 0.855).abs() < 1e-12);
1066 let (ratio, out) = (own.ratio, -0.3);
1069 let loss = |g: &crate::mech::Gearbox| g.loss_power(ratio * (out + 5e-4), -2.0 * ratio, out, -2.0);
1070 assert!((loss(&own) - 200.0 * (1.0 / 0.81 - 1.0)).abs() < 1e-6, "{}", loss(&own));
1071 assert!((loss(&alike) - 200.0 * (1.0 / 0.855 - 1.0)).abs() < 1e-6, "{}", loss(&alike));
1072 }
1073
1074 #[test]
1078 fn the_presliding_stiffnesses_are_factors_on_k1_that_default_to_one() {
1079 let base = "format_version = 1\n[effects]\njoint_friction = false\nhard_stops = false\nmotor_friction = false\n\
1080 torque_ripple = false\ngearbox_backlash = false\ngearbox_efficiency = true\ngearbox_drag = false\n\
1081 motor_stiction = false\ngearbox_lost_motion = false\ngearbox_stiffness_curve = false\nthermal_feedback = false\n\
1082 holding_brake = false\ngearbox_mesh_friction = true\n\
1083 [motor]\nrotor_inertia_kgm2 = 1e-4\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\n\
1084 friction_smoothing_rad_s = 1e-3\nfriction_breakaway_nm = 0.0\nfriction_stribeck_rad_s = 2.0\nripple_fraction = 0.0\n\
1085 ripple_order = 6.0\ncogging_nm = 0.0\ncogging_order = 6.0\nbrake_torque_nm = 5.0\n\
1086 [gearbox]\nratio = 20.0\nefficiency = 0.9\nbacklash_rad = 0.0\nstiffness_nm_rad = 2e5\ndamping_nm_s_rad = 5.0\n\
1087 inertia_at_input_kgm2 = 1e-4\nefficiency_torque_nm = 100.0\nno_load_torque_nm = 0.0\nno_load_speed_rpm = 3000.0\n\
1088 lost_motion_band_rad = 0.0\nhysteresis_rad = 0.0\nstiffness_t1_nm = 100.0\nstiffness_t2_nm = 100.0\n\
1089 stiffness_k2_nm_rad = 2e5\nstiffness_k3_nm_rad = 2e5\n{extra}\
1090 [joint]\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 1e-3\n\
1091 min_angle_deg = -45.0\nmax_angle_deg = 90.0\nstop_stiffness_nm_rad = 1e5\nstop_damping_nm_s_rad = 0.0\n";
1092 let drum = Converter {
1093 lever: 0.025,
1094 stiffness: f64::INFINITY,
1095 backlash: 0.0,
1096 efficiency: 1.0,
1097 inertia: 0.0,
1098 damping_ratio: 0.0,
1099 };
1100 let make = |extra: &str| {
1101 let cfg = Config::parse(&base.replace("{extra}", extra)).unwrap();
1102 let mut j = RotaryJoint::from_config(&cfg).unwrap();
1103 drum.apply(&cfg, &mut j).unwrap();
1104 j.gearbox
1105 };
1106 let plain = make("");
1107 assert!(
1108 (plain.dahl_stiffness / 3.2e8 - 1.0).abs() < 1e-12 && (plain.mesh_stiffness / 3.2e8 - 1.0).abs() < 1e-12
1109 );
1110 let set = make("hysteresis_stiffness_factor = 3.0\nmesh_stiffness_factor = 0.5\n");
1111 assert!((set.dahl_stiffness / 9.6e8 - 1.0).abs() < 1e-12, "{}", set.dahl_stiffness);
1112 assert!((set.mesh_stiffness / 1.6e8 - 1.0).abs() < 1e-12, "{}", set.mesh_stiffness);
1113 }
1114
1115 #[test]
1125 fn the_gear_behind_a_converter_is_in_series_with_its_spring_over_the_band_and_the_hysteresis() {
1126 let text = "format_version = 1\n[effects]\njoint_friction = false\nhard_stops = false\nmotor_friction = false\n\
1127 torque_ripple = false\ngearbox_backlash = false\ngearbox_efficiency = false\ngearbox_drag = false\n\
1128 motor_stiction = false\ngearbox_lost_motion = true\ngearbox_stiffness_curve = false\nthermal_feedback = false\n\
1129 holding_brake = false\ngearbox_mesh_friction = false\n\
1130 [motor]\nrotor_inertia_kgm2 = 1e-4\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\n\
1131 friction_smoothing_rad_s = 1e-3\nfriction_breakaway_nm = 0.0\nfriction_stribeck_rad_s = 2.0\nripple_fraction = 0.0\n\
1132 ripple_order = 6.0\ncogging_nm = 0.0\ncogging_order = 6.0\nbrake_torque_nm = 5.0\n\
1133 [gearbox]\nratio = 20.0\nefficiency = 0.9\nbacklash_rad = 0.0\nstiffness_nm_rad = 2e5\ndamping_nm_s_rad = 5.0\n\
1134 inertia_at_input_kgm2 = 1e-4\nefficiency_torque_nm = 100.0\nno_load_torque_nm = 0.0\nno_load_speed_rpm = 3000.0\n\
1135 lost_motion_band_rad = BAND\nhysteresis_rad = 2e-4\nstiffness_t1_nm = 100.0\nstiffness_t2_nm = 100.0\n\
1136 stiffness_k2_nm_rad = 2e5\nstiffness_k3_nm_rad = 2e5\n\
1137 [joint]\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 1e-3\n\
1138 min_angle_deg = -45.0\nmax_angle_deg = 90.0\nstop_stiffness_nm_rad = 1e5\nstop_damping_nm_s_rad = 0.0\n";
1139 let screw = Converter {
1140 lever: 0.025,
1141 stiffness: 5e7,
1142 backlash: 0.0,
1143 efficiency: 1.0,
1144 inertia: 0.0,
1145 damping_ratio: 0.0,
1146 };
1147 let gear = |b: &str| {
1148 let cfg = Config::parse(&text.replace("BAND", b)).unwrap();
1149 let mut j = RotaryJoint::from_config(&cfg).unwrap();
1150 screw.apply(&cfg, &mut j).unwrap();
1151 j.gearbox
1152 };
1153 let g = gear("1e-4");
1154 let rel = |a: f64, b: f64| (a / b - 1.0).abs() < 1e-12;
1155 assert!(rel(g.stiffness, 1.0 / 2.3125e-8) && rel(g.band, 2.5e-6), "{} {}", g.stiffness, g.band);
1156 for (force, twist) in [(100.0, 3.25e-6), (400.0, 2.5e-6 + 8e-6), (800.0, 1.975e-5)] {
1157 assert!(rel(g.static_twist(force), twist), "{force}: {}", g.static_twist(force));
1158 assert!(rel(g.spring(twist).0, force), "{twist}: {}", g.spring(twist).0);
1159 }
1160 assert!(rel(g.hysteresis, 108.108_108_108_108_1) && rel(2.0 * g.hysteresis / g.stiffness, 5e-6));
1161 assert!(rel(g.dahl_stiffness, 1.0 / 2.15625e-8 - 1.0 / 2.3125e-8), "{}", g.dahl_stiffness);
1162 assert_eq!(gear("0.0").band, 0.0);
1163 }
1164
1165 #[test]
1182 fn the_gear_damper_behind_a_converter_bridges_the_gear_alone() {
1183 let text = "format_version = 1\n[effects]\njoint_friction = false\nhard_stops = false\nmotor_friction = false\n\
1184 torque_ripple = false\ngearbox_backlash = false\ngearbox_efficiency = false\ngearbox_drag = false\n\
1185 motor_stiction = false\ngearbox_lost_motion = false\ngearbox_stiffness_curve = false\nthermal_feedback = false\n\
1186 holding_brake = false\ngearbox_mesh_friction = false\n\
1187 [motor]\nrotor_inertia_kgm2 = 1e-4\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\n\
1188 friction_smoothing_rad_s = 1e-3\nfriction_breakaway_nm = 0.0\nfriction_stribeck_rad_s = 2.0\nripple_fraction = 0.0\n\
1189 ripple_order = 6.0\ncogging_nm = 0.0\ncogging_order = 6.0\nbrake_torque_nm = 5.0\n\
1190 [gearbox]\nratio = 1.0\nefficiency = 0.9\nbacklash_rad = 0.0\nstiffness_nm_rad = K1\ndamping_nm_s_rad = DAMPING\n\
1191 inertia_at_input_kgm2 = 1e-4\nefficiency_torque_nm = 100.0\nno_load_torque_nm = 0.0\nno_load_speed_rpm = 3000.0\n\
1192 lost_motion_band_rad = 0.0\nhysteresis_rad = 0.0\nstiffness_t1_nm = 100.0\nstiffness_t2_nm = 100.0\n\
1193 stiffness_k2_nm_rad = 100.0\nstiffness_k3_nm_rad = 100.0\n\
1194 [joint]\nfriction_coulomb_nm = 0.0\nfriction_viscous_nm_s_rad = 0.0\nfriction_smoothing_rad_s = 1e-3\n\
1195 min_angle_deg = -45.0\nmax_angle_deg = 90.0\nstop_stiffness_nm_rad = 1e5\nstop_damping_nm_s_rad = 0.0\n";
1196 let geared = |k1: &str, damping: &str, stiffness: f64, damping_ratio: f64| {
1197 let cfg = Config::parse(&text.replace("K1", k1).replace("DAMPING", damping)).unwrap();
1198 let mut j = RotaryJoint::from_config(&cfg).unwrap();
1199 let converter =
1200 Converter { lever: 0.01, stiffness, backlash: 0.0, efficiency: 1.0, inertia: 0.0, damping_ratio };
1201 converter.apply_to(&cfg, &mut j, 1.0).unwrap();
1202 j.gearbox
1203 };
1204 let gear = |damping: &str, stiffness: f64| geared("100.0", damping, stiffness, 0.0);
1205 let rel = |a: f64, b: f64, tol: f64| (a / b - 1.0).abs() < tol;
1206 let plain = gear("0.0", 1e6);
1208 assert!(plain.relax_stiffness == 0.0 && plain.damping == 0.0 && rel(plain.stiffness, 5e5, 1e-12));
1209 let rigid = gear("0.2828", f64::INFINITY);
1210 assert!(rigid.relax_stiffness == 0.0 && rel(rigid.damping, 2828.0, 1e-12) && rel(rigid.stiffness, 1e6, 1e-12));
1211 let fast = gear("0.001", 1e6);
1214 assert!(fast.relax_stiffness == 0.0 && rel(fast.damping, 2.5, 1e-12), "{}", fast.damping);
1215 let g = gear("0.2828", 1e6);
1216 assert_eq!(g.damping, 0.0);
1217 assert!(rel(g.relax_stiffness, 5e5, 1e-12) && rel(g.relax_time, 1.414e-3, 1e-12));
1218 let x = 1e-3;
1220 assert!(rel(g.static_twist(500.0), 1e-3, 1e-12));
1221 assert!(rel(g.torque_with(0.0, 0.0, -x, 0.0, g.arm_rest(0.0, -x)).output, 500.0, 1e-12));
1222 let decay = |g: &crate::mech::Gearbox| {
1225 let (mass, dt) = (1.0, 1e-6);
1226 let rates = |s: [f64; 3]| {
1227 let force = g.torque_with(0.0, 0.0, s[0], s[1], s[2]).output;
1228 [s[1], force / mass, g.arm(0.0, s[0], s[2]).1]
1229 };
1230 let energy = |s: [f64; 3]| 0.5 * mass * s[1] * s[1] + g.energy_with(0.0, s[0], s[2]);
1231 let u0 = g.arm_rest(0.0, -x);
1232 let (mut s, mut lost, start) = ([-x, 0.0, u0], 0.0, energy([-x, 0.0, u0]));
1233 let mut peaks = Vec::new();
1234 for _ in 0..80000 {
1235 let add = |s: [f64; 3], k: [f64; 3], h: f64| std::array::from_fn(|i| s[i] + h * k[i]);
1236 let k1 = rates(s);
1237 let k2 = rates(add(s, k1, 0.5 * dt));
1238 let k3 = rates(add(s, k2, 0.5 * dt));
1239 let k4 = rates(add(s, k3, dt));
1240 let l0 = g.loss_power_with(0.0, 0.0, s[0], s[1], s[2]);
1241 let next: [f64; 3] =
1242 std::array::from_fn(|i| s[i] + dt / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]));
1243 lost += 0.5 * dt * (l0 + g.loss_power_with(0.0, 0.0, next[0], next[1], next[2]));
1244 if s[1] > 0.0 && next[1] <= 0.0 {
1245 peaks.push(next[0]);
1246 }
1247 s = next;
1248 }
1249 assert!(peaks.len() >= 10, "{}", peaks.len());
1250 println!("peaks {peaks:?}");
1251 (peaks[8] / peaks[7], (start - energy(s) - lost) / start)
1252 };
1253 let (fall, off) = decay(&g);
1254 assert!(rel(fall, 0.355591, 2e-5) && off.abs() < 1e-9, "{fall} {off}");
1255 let both = geared("100.0", "0.2828", 1e6, 0.04);
1256 assert!(rel(both.damping, 77.799175, 1e-7) && rel(both.relax_stiffness, 446493.00, 1e-7), "{both:?}");
1257 assert!(rel(both.relax_time, 1.454e-3, 1e-12));
1258 let (fall, off) = decay(&both);
1259 assert!(rel(fall, 0.284213, 2e-5) && off.abs() < 1e-9, "{fall} {off}");
1260 let screw = geared("1e8", "0.0", 1e6, 0.04);
1261 let zeta = screw.damping_at(0.0) / (2.0 * screw.stiffness.sqrt());
1262 assert!(screw.relax_stiffness == 0.0 && rel(zeta, 0.04, 1e-5), "{zeta}");
1263 let w = 5e5f64.sqrt();
1265 assert!(rel(g.damping_at(w), 5e5 * 1.414e-3 / (1.0 + (w * 1.414e-3).powi(2)), 1e-12));
1266 let along = |k1: &str, damping: &str| {
1271 let cfg = Config::parse(&text.replace("K1", k1).replace("DAMPING", damping)).unwrap();
1272 let mut j = RotaryJoint::from_config(&cfg).unwrap();
1273 let travel = TravelCompliance {
1274 ae: 1e6,
1275 length: 1.0,
1276 both_ends: false,
1277 fixed_bearing_at: 0.0,
1278 reference: 1e-6,
1279 gear: [0.0; 2],
1280 converter: [0.0; 2],
1281 };
1282 let converter = Converter {
1283 lever: 0.01,
1284 stiffness: 1e6,
1285 backlash: 0.0,
1286 efficiency: 1.0,
1287 inertia: 0.0,
1288 damping_ratio: 0.04,
1289 };
1290 BackDriven { converter, back_efficiency: 1.0, travel: Some(travel) }.apply_to(&cfg, &mut j, 1.0).unwrap();
1291 j.gearbox
1292 };
1293 let screw = along("1e8", "0.0");
1294 for (q, k) in [(0.25, 4e6), (0.5, 2e6), (0.75, 1e6 / 0.75), (1.0, 1e6)] {
1295 let g = screw.at(q);
1296 let w = g.stiffness.sqrt();
1297 let zeta = g.damping_at(w) * w / (2.0 * g.stiffness);
1298 assert!(rel(g.stiffness, k, 1e-5) && rel(zeta, 0.04, 1e-5), "{q}: {} {zeta}", g.stiffness);
1299 }
1300 let both = along("100.0", "0.2828");
1302 let [b, arm, tau, _] = both.travel.unwrap().dampers(0.0).unwrap();
1303 assert!(both.relax_stiffness > 0.0 && rel(arm, both.relax_stiffness, 1e-12), "{both:?}");
1304 assert!(rel(b, both.damping, 1e-12) && rel(tau, both.relax_time, 1e-12));
1305 }
1306
1307 #[test]
1312 fn the_screw_converter_takes_the_softest_position_of_either_bearing_arrangement() {
1313 let free = screw();
1314 assert_eq!(free.softest_position(), 1.0);
1315 close(free.converter(free.softest_position()).stiffness, 5.8770e7, "fixed-supported far end");
1316 assert!((0..=100).all(|i| free.stiffness(0.01 * i as f64) >= free.stiffness(1.0) * (1.0 - 1e-12)));
1317 let fixed = BallScrew { mounting: Mounting::FixedFixed, ..screw() };
1318 assert_eq!(fixed.softest_position(), 0.5);
1319 close(fixed.converter(fixed.softest_position()).stiffness, 1.5376e8, "fixed-fixed middle");
1320 assert!((1..100).all(|i| fixed.stiffness(0.01 * i as f64) >= fixed.stiffness(0.5) * (1.0 - 1e-12)));
1321 }
1322
1323 #[test]
1329 fn the_screw_compliance_along_the_travel_is_the_stiffness_at_the_nut() {
1330 for mounting in [Mounting::FixedSupported, Mounting::FixedFixed] {
1331 let s = BallScrew { mounting, fixed_bearing_at: Some(-0.1), ..screw() };
1332 let t = s.travel(s.softest_position()).unwrap();
1333 for x in [0.05, 0.25, 0.5, 0.9] {
1334 let by_stiffness = 1.0 / s.stiffness(x) - 1.0 / s.stiffness(s.softest_position());
1335 assert!((t.delta(x - 0.1).0 - by_stiffness).abs() < 1e-20, "{mounting:?} at {x}");
1336 let h = 1e-6;
1337 let slope = (t.delta(x - 0.1 + h).0 - t.delta(x - 0.1 - h).0) / (2.0 * h);
1338 assert!((t.delta(x - 0.1).1 - slope).abs() < 1e-14, "{mounting:?} slope at {x}");
1339 }
1340 }
1341 let t = BallScrew { fixed_bearing_at: Some(-0.1), ..screw() }.travel(1.0).unwrap();
1342 close(t.delta(0.15).0, -1.0512e-8, "compliance less the far end's");
1343 close(t.delta(0.15).1, 1.4015e-8, "slope");
1344 assert!(screw().converter(1.0).travel.is_none());
1345 let text = |on: bool| {
1346 format!(
1347 "format_version = 1\n[effects]\nscrew_stiffness_with_position = {on}\n[screw]\nlead_m = 0.01\n\
1348 nominal_diameter_m = 0.025\nroot_diameter_m = 0.021\nlength_m = 1.0\nmounting = \"fixed-supported\"\n\
1349 efficiency = 0.9\nnut_stiffness_n_m = 5e8\nbearing_stiffness_n_m = 1e9\npreload_n = 0.0\n\
1350 dynamic_load_rating_n = 1e4\nstatic_load_rating_n = 2e4\nload_factor = 1.2\nstatic_safety_factor = 2.0\n\
1351 critical_speed_factor = 0.8\nbuckling_safety_factor = 2.0\nmax_dn = 0.0\nfixed_bearing_at_m = -0.1\n"
1352 )
1353 };
1354 let read = |on| BallScrew::from_config(&Config::parse(&text(on)).unwrap()).unwrap().fixed_bearing_at;
1355 assert_eq!((read(true), read(false)), (Some(-0.1), None));
1356 }
1357
1358 #[test]
1361 fn the_racks_pressure_angle_is_a_key_that_defaults_to_twenty_degrees() {
1362 let text = |extra: &str| {
1363 format!(
1364 "format_version = 1\n[rack]\nmodule_m = 0.002\nteeth = 30.0\nhelix_angle_deg = 0.0\nefficiency = 0.97\n\
1365 stiffness_n_m = 1e8\nbacklash_m = 0.0\npinion_inertia_kgm2 = 1e-4\nrated_feed_force_n = 3000.0\n\
1366 service_factor = 1.5\n{extra}"
1367 )
1368 };
1369 let rack = |extra: &str| RackPinion::from_config(&Config::parse(&text(extra)).unwrap()).unwrap();
1370 close(rack("").radial_load(1000.0), 1064.18, "default 20 degrees");
1371 close(rack("pressure_angle_deg = 25.0\n").radial_load(-1000.0), 1103.38, "25 degrees");
1372 assert!(RackPinion::from_config(&Config::parse(&text("pressure_angle_deg = 60.0\n")).unwrap()).is_err());
1373 }
1374}