1use sim_core::testkit::Noise;
16use sim_core::{Config, ConfigError};
17use std::collections::VecDeque;
18use std::f64::consts::TAU;
19
20type Result<T> = std::result::Result<T, ConfigError>;
21
22#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
23pub struct DriveParams {
24 pub kv: f64,
25 pub kp: f64,
26 pub ki: f64,
27 pub velocity_ff: f64,
29 pub torque_ff: f64,
30 pub kt: f64,
32 pub resistance: f64,
33 pub ke: f64,
36 pub max_voltage: f64,
39 pub fundamental_gain: f64,
44 pub current_kp: f64,
46 pub current_ki: f64,
47 pub current_cycle: f64,
48 pub peak_torque: f64,
49 pub rated_torque: f64,
51 pub rated_speed: f64,
52 pub no_load_speed: f64,
53 pub max_speed: f64,
57 pub limit: bool,
58 pub encoder_step: f64,
60 pub speed_from_positions: bool,
64 pub velocity_filter: f64,
66 pub torque_filter: f64,
67 pub notch: Option<[f64; 5]>,
68 pub velocity_cycle: f64,
69 pub current_delay: usize,
72 pub velocity_delay: usize,
73 pub inductance: f64,
75 pub pole_pairs: f64,
78 pub heating: bool,
81 pub rated_rise: f64,
82 pub housing_max_rise: f64,
85 pub rated_current: f64,
86 pub thermal_time_constant: f64,
87 pub start_rise: f64,
88 pub saturation: f64,
90 pub max_current: f64,
91 pub drive_max_current: f64,
95 pub dc_link: bool,
99 pub shared_dc_link: bool,
101 pub bus_voltage: f64,
102 pub dc_capacitance: f64,
103 pub braking_threshold: f64,
104 pub resistor_peak: f64,
105 pub overvoltage: f64,
106 pub discharge_time_constant: f64,
109 pub regenerative: bool,
112 pub line_max_power: f64,
113 pub line_efficiency: f64,
114 pub encoder_noise: f64,
117 pub current_noise: f64,
118 pub noise_seed: u64,
119 pub field_weakening: Option<FieldWeakening>,
121 pub overload: Option<Overload>,
123 pub thermal_nodes: Option<ThermalNodes>,
125 pub iron_loss_rated: f64,
134 pub iron_drag_rated: f64,
139 pub stall_current: f64,
140 pub static_torque: f64,
143 pub s1_curve: Vec<[f64; 2]>,
146 pub magnet_coefficient: f64,
149 pub resistor_heating: Option<ResistorHeating>,
151 pub precontrol: Precontrol,
153 pub motor: Motor,
155}
156
157#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
160pub enum Motor {
161 #[default]
162 Servo,
163 Stepper(crate::stepper::Stepper),
164 Induction(crate::induction::Induction),
165}
166
167impl Motor {
168 fn from_config(cfg: &Config) -> Result<Self> {
169 match cfg.get("motor.kind").ok().map(|v| v.as_str()) {
170 None | Some(Some("servo")) => Ok(Self::Servo),
171 Some(Some("stepper")) => Ok(Self::Stepper(crate::stepper::Stepper::from_config(cfg)?)),
172 Some(Some("induction")) => Ok(Self::Induction(crate::induction::Induction::from_config(cfg)?)),
173 _ => Err(ConfigError::Invalid("motor.kind".into())),
174 }
175 }
176
177 pub fn open_loop(&self) -> bool {
180 match self {
181 Self::Servo => false,
182 Self::Stepper(_) => true,
183 Self::Induction(m) => !m.field_oriented,
184 }
185 }
186}
187
188pub const WINDING_STATES: usize = 7;
192
193#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
195pub struct Phases {
196 pub x: [f64; 4],
198 pub u: [f64; 2],
200 pub integral: [f64; 2],
202 pub angle: f64,
204 pub speed: f64,
205 pub command: f64,
209 pub origin: f64,
210 #[serde(default)]
213 pub offset: f64,
214 pub electrical: f64,
215 pub load_angle: f64,
216 pub frame_speed: f64,
219 pub estimate: f64,
220}
221
222#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
225pub struct Precontrol {
226 pub fine_interpolation: bool,
231 pub constant_inertia: bool,
235 pub friction: Vec<[f64; 2]>,
238 #[serde(default)]
241 pub machine_friction: bool,
242 pub balance_time: f64,
246}
247
248impl Precontrol {
249 pub fn friction_at(&self, speed: f64) -> f64 {
252 let (s, mut last) = (speed.abs(), [0.0, 0.0]);
253 for &[v, t] in &self.friction {
254 if s <= v {
255 return (last[1] + (t - last[1]) * (s - last[0]) / (v - last[0])).copysign(speed);
256 }
257 last = [v, t];
258 }
259 last[1].copysign(speed)
260 }
261}
262
263#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
267pub struct ResistorHeating {
268 pub continuous_power: f64,
269 pub time_constant: f64,
270 pub rated_rise: f64,
271}
272
273impl ResistorHeating {
274 pub fn rise_after(&self, rise: f64, power: f64, dt: f64) -> f64 {
276 let target = self.rated_rise * power / self.continuous_power;
277 target + (rise - target) * (-dt / self.time_constant).exp()
278 }
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
290pub struct FieldWeakening {
291 pub pole_pairs: f64,
292 pub d_inductance: f64,
294}
295
296#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
304pub struct Overload {
305 pub rated_current: f64,
306 pub base_current: f64,
307 pub max_current: f64,
308 pub time_constant: f64,
309 pub trip: f64,
310 pub chip_share: f64,
311 pub chip_time_constant: f64,
312}
313
314impl Overload {
315 pub fn from_config(cfg: &Config) -> Result<Option<Self>> {
317 if !(cfg.get("effects.drive_overload").is_ok() && cfg.bool("effects.drive_overload")?) {
318 return Ok(None);
319 }
320 let rating = |leaf: &str| cfg.positive(&format!("ratings.{leaf}"));
321 let (rated_current, base_current) = (rating("drive_rated_current_a")?, rating("drive_base_load_current_a")?);
322 let max_current = rating("drive_max_current_a")?;
323 if base_current >= rated_current {
324 return Err(ConfigError::Invalid("ratings.drive_base_load_current_a".into()));
325 }
326 if max_current <= rated_current {
327 return Err(ConfigError::Invalid("ratings.drive_max_current_a".into()));
328 }
329 let time_constant = rating("drive_overload_time_constant_s")?;
330 let chip_share = cfg.non_negative("ratings.drive_chip_share")?;
331 if chip_share >= 1.0 {
332 return Err(ConfigError::Invalid("ratings.drive_chip_share".into()));
333 }
334 let chip_time_constant = rating("drive_chip_time_constant_s")?;
335 let mut o =
336 Self { rated_current, base_current, max_current, time_constant, trip: 0.0, chip_share, chip_time_constant };
337 let r2 = (max_current / rated_current).powi(2);
338 let t_max = rating("drive_max_current_time_s")?;
339 o.trip = r2 - (r2 - 1.0) * o.decay(t_max).iter().sum::<f64>();
340 Ok(Some(o))
341 }
342
343 fn decay(&self, dt: f64) -> [f64; 2] {
345 [
346 (1.0 - self.chip_share) * (-dt / self.time_constant).exp(),
347 self.chip_share * (-dt / self.chip_time_constant).exp(),
348 ]
349 }
350
351 pub fn nodes_after(&self, [slow, chip]: [f64; 2], current: f64, dt: f64) -> [f64; 2] {
353 let q = (current / self.rated_current).powi(2);
354 let (a, b) = ((1.0 - self.chip_share) * q, self.chip_share * q);
355 [a + (slow - a) * (-dt / self.time_constant).exp(), b + (chip - b) * (-dt / self.chip_time_constant).exp()]
356 }
357
358 pub fn node_time_constant(&self, node: usize) -> f64 {
360 if node == 0 { self.time_constant } else { self.chip_time_constant }
361 }
362
363 pub fn trip_time(&self, current: f64) -> f64 {
366 let q = (current / self.rated_current).powi(2);
367 let at = |t: f64| q - (q - 1.0) * self.decay(t).iter().sum::<f64>();
368 if at(1e9) < self.trip {
369 return f64::INFINITY;
370 }
371 let (mut lo, mut hi) = (0.0, 1e9);
372 for _ in 0..200 {
373 let mid = 0.5 * (lo + hi);
374 if at(mid) < self.trip { lo = mid } else { hi = mid }
375 }
376 hi
377 }
378}
379
380#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
385pub struct ThermalNodes {
386 pub winding_share: f64,
387 pub winding_time_constant: f64,
388}
389
390pub(crate) const COPPER: f64 = 0.0039;
392
393pub const WINDING_PER_DC_LINK: f64 = 1.224_744_871_391_589;
395
396const PHASE_PER_WINDING: f64 = 0.471_404_520_791_031_7;
398
399impl DriveParams {
400 pub fn from_config(cfg: &Config, dt: f64, velocity_cycle: f64) -> Result<Self> {
402 let on = |effect: &str| cfg.bool(&format!("effects.{effect}"));
403 let low_pass = |effect: &str, leaf: &str| -> Result<f64> {
404 let tau = cfg.positive(&format!("drive.{leaf}"))?;
405 Ok(if on(effect)? { 1.0 - (-velocity_cycle / tau).exp() } else { 1.0 })
406 };
407 let kp = cfg.positive("drive.velocity_kp_nm_s_rad")?;
408 let delay = |leaf: &str| -> Result<usize> {
409 let path = format!("drive.{leaf}");
410 let cycles = cfg.f64(&path)?;
411 if cycles < 0.0 || cycles.fract() != 0.0 || cycles > 1000.0 {
412 return Err(ConfigError::Invalid(path));
413 }
414 Ok(if on("drive_delay")? { cycles as usize } else { 0 })
415 };
416 let notch = match on("notch_filter")? {
419 true if cfg.non_negative("drive.notch_frequency_hz")? > 0.0 => {
420 let (f, bw) = (cfg.positive("drive.notch_frequency_hz")?, cfg.positive("drive.notch_bandwidth_hz")?);
421 Some(notch_coefficients(f, bw, velocity_cycle))
422 }
423 _ => None,
424 };
425 let (kt, resistance) = (cfg.positive("motor.torque_constant_nm_a")?, cfg.positive("motor.resistance_ohm")?);
426 let emf_constant = if cfg.get("drive.back_emf_constant_v_s_rad").is_ok() {
429 cfg.non_negative("drive.back_emf_constant_v_s_rad")?
430 } else {
431 0.0
432 };
433 let (rated_speed, no_load_speed) =
436 (cfg.positive("drive.rated_speed_rad_s")?, cfg.positive("drive.no_load_speed_rad_s")?);
437 if no_load_speed <= rated_speed {
438 return Err(ConfigError::Invalid("drive.no_load_speed_rad_s".into()));
439 }
440 let max_speed = if cfg.get("drive.max_speed_rad_s").is_ok() {
441 cfg.positive("drive.max_speed_rad_s")?
442 } else {
443 no_load_speed
444 };
445 let kt_at_max = cfg.positive("motor.torque_constant_at_max_current_nm_a")?;
446 if kt_at_max > kt {
447 return Err(ConfigError::Invalid("motor.torque_constant_at_max_current_nm_a".into()));
448 }
449 let current_kp = cfg.positive("drive.current_kp_v_a")?;
450 let bus_voltage = cfg.positive("drive.bus_voltage_v")?;
451 let dc_link = on("dc_link")?;
453 let rating = |leaf: &str| if dc_link { cfg.positive(&format!("ratings.{leaf}")) } else { Ok(0.0) };
454 let (braking_threshold, overvoltage) = (rating("braking_threshold_v")?, rating("dc_link_overvoltage_v")?);
455 if dc_link && !(bus_voltage < braking_threshold && braking_threshold < overvoltage) {
456 return Err(ConfigError::Invalid("ratings.braking_threshold_v".into()));
457 }
458 let noise = |leaf: &str| -> Result<f64> {
459 let path = format!("drive.{leaf}");
460 let value = cfg.f64(&path)?;
461 if !(value >= 0.0) {
462 return Err(ConfigError::Invalid(path));
463 }
464 Ok(if on("sensor_noise")? { value } else { 0.0 })
465 };
466 let seed = cfg.f64("drive.noise_seed")?;
467 if seed < 0.0 || seed.fract() != 0.0 {
468 return Err(ConfigError::Invalid("drive.noise_seed".into()));
469 }
470 let regenerative = dc_link && on("regenerative_supply")?;
473 let line = |leaf: &str| if regenerative { cfg.positive(&format!("ratings.{leaf}")) } else { Ok(1.0) };
474 let line_efficiency = if dc_link { cfg.positive("ratings.line_module_efficiency")? } else { 1.0 };
475 let drive_limit = cfg.get("effects.drive_current_limit").is_ok() && on("drive_current_limit")?;
477 if line_efficiency > 1.0 {
478 return Err(ConfigError::Invalid("ratings.line_module_efficiency".into()));
479 }
480 let switched =
482 |effect: &str| -> Result<bool> { Ok(cfg.get(&format!("effects.{effect}")).is_ok() && on(effect)?) };
483 let field_weakening = if switched("field_weakening")? {
484 Some(FieldWeakening {
485 pole_pairs: cfg.positive("motor.pole_pairs")?,
486 d_inductance: cfg.positive("motor.d_inductance_h")?,
487 })
488 } else {
489 None
490 };
491 let thermal_time_constant = cfg.positive("motor.thermal_time_constant_s")?;
492 let thermal_nodes = if switched("motor_thermal_nodes")? {
493 let share = cfg.positive("motor.winding_resistance_share")?;
494 let winding_time_constant = cfg.positive("motor.winding_time_constant_s")?;
495 if share >= 1.0 {
496 return Err(ConfigError::Invalid("motor.winding_resistance_share".into()));
497 }
498 if winding_time_constant >= share * thermal_time_constant {
500 return Err(ConfigError::Invalid("motor.winding_time_constant_s".into()));
501 }
502 Some(ThermalNodes { winding_share: share, winding_time_constant })
503 } else {
504 None
505 };
506 let model = cfg.get("drive.torque_feedforward_model").map(|v| v.as_str());
508 let constant_inertia = match model {
509 Err(_) | Ok(Some("rigid")) => false,
510 Ok(Some("inertia")) => true,
511 Ok(_) => return Err(ConfigError::Invalid("drive.torque_feedforward_model".into())),
512 };
513 let machine_friction = match cfg.get("drive.friction_feedforward_model").map(|v| v.as_str()) {
516 Err(_) | Ok(Some("characteristic")) => false,
517 Ok(Some("machine")) => true,
518 Ok(_) => return Err(ConfigError::Invalid("drive.friction_feedforward_model".into())),
519 } && switched("friction_feedforward")?;
520 let friction = if switched("friction_feedforward")? && !machine_friction {
521 let (speeds, torques) = (
522 cfg.f64s("drive.friction_feedforward_speed_rad_s")?,
523 cfg.f64s("drive.friction_feedforward_torque_nm")?,
524 );
525 if speeds.is_empty() || speeds.len() != torques.len() || torques.iter().any(|t| !(*t >= 0.0)) {
526 return Err(ConfigError::Invalid("drive.friction_feedforward_torque_nm".into()));
527 }
528 if !(speeds[0] > 0.0) || speeds.windows(2).any(|w| !(w[1] > w[0])) {
529 return Err(ConfigError::Invalid("drive.friction_feedforward_speed_rad_s".into()));
530 }
531 speeds.iter().zip(&torques).map(|(v, t)| [*v, *t]).collect()
532 } else {
533 Vec::new()
534 };
535 let precontrol = Precontrol {
536 fine_interpolation: switched("fine_interpolation")?,
537 constant_inertia,
538 friction,
539 machine_friction,
540 balance_time: if cfg.get("drive.precontrol_balance_s").is_ok() {
541 cfg.non_negative("drive.precontrol_balance_s")?
542 } else {
543 0.0
544 },
545 };
546 let stall_current = if switched("iron_loss")? { cfg.positive("motor.stall_current_a")? } else { 0.0 };
548 let rated_current = cfg.positive("motor.rated_current_a")?;
549 let rated_rise = cfg.positive("motor.rated_temperature_rise_k")?;
550 let magnet_coefficient =
551 if switched("magnet_temperature")? { cfg.f64("motor.magnet_temperature_coefficient_1_k")? } else { 0.0 };
552 if !(-0.01..=0.0).contains(&magnet_coefficient) {
553 return Err(ConfigError::Invalid("motor.magnet_temperature_coefficient_1_k".into()));
554 }
555 let resistor_heating = if dc_link && switched("braking_resistor_heating")? {
556 Some(ResistorHeating {
557 continuous_power: cfg.positive("ratings.braking_resistor_continuous_w")?,
558 time_constant: cfg.positive("ratings.braking_resistor_time_constant_s")?,
559 rated_rise: cfg.positive("ratings.braking_resistor_rated_rise_k")?,
560 })
561 } else {
562 None
563 };
564 let motor = Motor::from_config(cfg)?;
565 let servo = matches!(motor, Motor::Servo);
566 let saturation = if on("torque_saturation")? { 1.0 - kt_at_max / kt } else { 0.0 };
567 let max_current = cfg.positive("motor.max_current_a")?;
568 let iron_drag_rated = if servo && stall_current > 0.0 {
570 let air_gap = kt * rated_current * (1.0 - saturation * (rated_current / max_current).powi(2).min(1.0));
571 let friction = if cfg.bool("effects.motor_friction")? {
572 cfg.non_negative("motor.friction_coulomb_nm")?
573 * (rated_speed / cfg.positive("motor.friction_smoothing_rad_s")?).tanh()
574 + cfg.non_negative("motor.friction_viscous_nm_s_rad")? * rated_speed
575 } else {
576 0.0
577 };
578 (air_gap - cfg.positive("drive.rated_torque_nm")? - friction).max(0.0)
579 } else {
580 0.0
581 };
582 let fundamental_gain = match cfg.get("drive.overmodulation").is_ok() && cfg.bool("drive.overmodulation")? {
586 false => 1.0,
587 true if matches!(motor, Motor::Stepper(_)) => 4.0 / std::f64::consts::PI,
588 true => 2.0 * 3f64.sqrt() / std::f64::consts::PI,
589 };
590 let encoder_noise = noise("encoder_noise_counts")? * TAU / cfg.positive("drive.encoder_counts_per_rev")?;
591 let encoder_step =
592 if on("encoder_resolution")? { TAU / cfg.positive("drive.encoder_counts_per_rev")? } else { 0.0 };
593 Ok(Self {
594 iron_loss_rated: resistance
596 * (1.0 + COPPER * rated_rise)
597 * (stall_current * stall_current - rated_current * rated_current).max(0.0),
598 iron_drag_rated,
599 stall_current: match &motor {
602 Motor::Induction(m) => {
603 let warm = resistance * (1.0 + COPPER * rated_rise);
604 (m.rated_copper_loss(warm) / warm).sqrt()
605 }
606 _ if stall_current > 0.0 => stall_current,
607 _ => rated_current,
608 },
609 magnet_coefficient,
610 resistor_heating,
611 precontrol,
612 motor,
613 field_weakening,
614 overload: Overload::from_config(cfg)?,
615 thermal_nodes,
616 dc_link,
617 shared_dc_link: dc_link && on("shared_dc_link")?,
618 bus_voltage,
619 dc_capacitance: rating("dc_link_capacitance_uf")? * 1e-6,
620 braking_threshold,
621 resistor_peak: rating("braking_resistor_peak_w")?,
622 overvoltage,
623 discharge_time_constant: rating("dc_link_discharge_time_constant_s")?,
624 regenerative,
625 line_max_power: line("line_module_max_power_w")?,
626 line_efficiency,
627 encoder_noise,
628 current_noise: noise("current_noise_a")?,
629 noise_seed: seed as u64,
630 kt,
631 resistance,
632 ke: match on("back_emf")? {
633 false => 0.0,
634 true if servo && emf_constant > 0.0 => emf_constant,
635 true => kt,
636 },
637 s1_curve: s1_curve_of(cfg)?,
638 static_torque: if cfg.get("motor.stall_current_a").is_ok() {
639 kt * cfg.positive("motor.stall_current_a")?
640 } else {
641 0.0
642 },
643 max_voltage: if on("voltage_limit")? {
644 WINDING_PER_DC_LINK * fundamental_gain * bus_voltage
645 } else {
646 f64::INFINITY
647 },
648 fundamental_gain,
649 current_kp,
650 current_ki: current_kp / cfg.positive("drive.current_tn_s")?,
651 current_cycle: dt,
652 kv: cfg.positive("drive.kv_1_s")?,
653 kp,
654 ki: kp / cfg.positive("drive.velocity_tn_s")?,
655 velocity_ff: if on("velocity_feedforward")? {
656 cfg.non_negative("drive.velocity_feedforward_factor")?
657 } else {
658 0.0
659 },
660 torque_ff: if on("torque_feedforward")? {
661 cfg.non_negative("drive.torque_feedforward_factor")?
662 } else {
663 0.0
664 },
665 peak_torque: cfg.positive("drive.peak_torque_nm")?,
666 rated_torque: cfg.positive("drive.rated_torque_nm")?,
667 rated_speed,
668 no_load_speed,
669 max_speed,
670 limit: on("torque_limit")?,
671 encoder_step,
672 speed_from_positions: encoder_step > 0.0 || encoder_noise > 0.0,
673 velocity_filter: low_pass("velocity_filter", "velocity_filter_s")?,
674 torque_filter: low_pass("torque_filter", "torque_filter_s")?,
675 notch,
676 velocity_cycle,
677 current_delay: delay("current_delay_cycles")?,
678 velocity_delay: delay("velocity_delay_cycles")?,
679 inductance: cfg.positive("motor.inductance_h")?,
680 pole_pairs: match (&field_weakening, cfg.get("motor.pole_pairs")) {
681 (Some(fw), _) => fw.pole_pairs,
682 (None, Ok(_)) => cfg.positive("motor.pole_pairs")?,
683 (None, Err(_)) => 0.0,
684 },
685 heating: on("winding_heating")?,
686 rated_rise,
687 housing_max_rise: if cfg.get("ratings.housing_max_rise_k").is_ok() {
688 cfg.positive("ratings.housing_max_rise_k")?
689 } else {
690 rated_rise
691 },
692 rated_current,
693 thermal_time_constant,
694 start_rise: cfg.non_negative("motor.start_temperature_rise_k")?,
695 saturation,
696 max_current,
697 drive_max_current: if drive_limit && cfg.get("ratings.drive_max_current_a").is_ok() {
698 cfg.positive("ratings.drive_max_current_a")?
699 } else {
700 f64::INFINITY
701 },
702 })
703 }
704
705 pub fn torque_range(&self, speed: f64) -> (f64, f64) {
710 self.torque_range_at(speed, self.max_voltage)
711 }
712
713 pub fn torque_range_at(&self, speed: f64, max_voltage: f64) -> (f64, f64) {
715 let (low, high) =
716 if self.limit { self.torque_curve_at(speed, max_voltage) } else { (f64::NEG_INFINITY, f64::INFINITY) };
717 let curve_has_it = matches!(self.motor, Motor::Induction(_)) || (self.limit && self.field_weakening.is_some());
720 if self.drive_max_current.is_finite() && !curve_has_it {
721 let most = self.torque_of(self.drive_max_current);
722 (low.max(-most), high.min(most))
723 } else {
724 (low, high)
725 }
726 }
727
728 pub fn dc_gain(&self) -> f64 {
730 WINDING_PER_DC_LINK * self.fundamental_gain
731 }
732
733 pub fn iron_loss_at(&self, speed: f64) -> f64 {
738 if self.iron_loss_rated == 0.0 {
739 0.0
740 } else {
741 self.iron_loss_rated * (speed.abs() / self.rated_speed).powf(1.5)
742 }
743 }
744
745 pub fn iron_drag(&self, speed: f64) -> f64 {
750 if self.iron_drag_rated == 0.0 || speed == 0.0 {
751 0.0
752 } else {
753 self.iron_drag_rated * speed / (speed.abs() * self.rated_speed).sqrt()
754 }
755 }
756
757 pub fn resistance_at(&self, rise: f64) -> f64 {
759 self.resistance * (1.0 + COPPER * rise)
760 }
761
762 pub fn torque_of(&self, current: f64) -> f64 {
764 self.kt * current * (1.0 - self.saturation * (current / self.max_current).powi(2).min(1.0))
765 }
766
767 pub fn current_for(&self, torque: f64) -> f64 {
770 if self.saturation == 0.0 {
771 return torque / self.kt;
772 }
773 let (s, y) = (self.saturation, torque.abs() / (self.kt * self.max_current));
776 let top = (1.0 / (3.0 * s).sqrt()).min(1.0);
777 let mut x = top;
778 if y < top - s * top.powi(3) {
779 x = y;
780 for _ in 0..8 {
781 x += (y - x + s * x.powi(3)) / (1.0 - 3.0 * s * x * x);
782 }
783 }
784 (x * self.max_current).copysign(torque)
785 }
786
787 pub fn back_emf(&self, current: f64, speed: f64) -> f64 {
790 self.ke * speed * (1.0 - self.saturation * (current / self.max_current).powi(2).min(1.0))
791 }
792
793 pub fn winding_rates(
807 &self,
808 voltage: f64,
809 resistance: f64,
810 current: f64,
811 speed: f64,
812 d_current: f64,
813 flux: f64,
814 ) -> [f64; 4] {
815 let (coupling, d_power) = match &self.field_weakening {
816 Some(fw) => {
817 let w = fw.pole_pairs * speed;
818 (w * fw.d_inductance * d_current, (resistance * d_current - w * self.inductance * current) * d_current)
819 }
820 None => (0.0, 0.0),
821 };
822 let rate = (voltage - resistance * current - flux * self.back_emf(current, speed) - coupling) / self.inductance;
823 [
824 rate,
825 voltage * current + d_power,
826 resistance * (current * current + d_current * d_current),
827 (self.torque_with(current, d_current, flux) - self.iron_drag(speed)) * speed,
828 ]
829 }
830
831 pub fn torque_with(&self, current: f64, d_current: f64, flux: f64) -> f64 {
834 let reluctance = self
835 .field_weakening
836 .map_or(0.0, |fw| fw.pole_pairs * (fw.d_inductance - self.inductance) * d_current * current);
837 flux * self.torque_of(current) + reluctance
838 }
839
840 pub fn d_current_for(&self, q: f64, speed: f64, max_voltage: f64, limit: f64, resistance: f64, flux: f64) -> f64 {
854 let Some(fw) = &self.field_weakening else { return 0.0 };
855 let w = fw.pole_pairs * speed;
856 let (a, b, r) = (w * fw.d_inductance, w * self.inductance, resistance);
857 let c0 = r * q + flux * self.ke * speed;
858 let (qa, qb, qc) =
860 (a * a + r * r, 2.0 * (a * c0 - r * b * q), c0 * c0 + b * b * q * q - max_voltage * max_voltage);
861 if !(qc > 0.0) {
862 return 0.0;
863 }
864 let disc = qb * qb - 4.0 * qa * qc;
865 let d = if disc >= 0.0 { (-qb + disc.sqrt()) / (2.0 * qa) } else { -qb / (2.0 * qa) };
866 d.clamp(-limit, 0.0)
867 }
868
869 fn field_weakened_torque(&self, fw: &FieldWeakening, speed: f64, umax: f64, motoring: bool, imax: f64) -> f64 {
875 let r = self.resistance;
876 let w = fw.pole_pairs * speed;
877 let (a, b) = (w * fw.d_inductance, w * self.inductance);
878 let q_at = |d: f64| -> f64 {
880 let by_current = (imax * imax - d * d).max(0.0).sqrt();
881 if !umax.is_finite() {
882 return by_current;
883 }
884 let c1 = self.ke * speed + a * d;
887 let (qa, qb, qc) = (r * r + b * b, 2.0 * r * (c1 - b * d), c1 * c1 + r * r * d * d - umax * umax);
888 let disc = qb * qb - 4.0 * qa * qc;
889 if disc < 0.0 {
890 return 0.0;
891 }
892 let q = if motoring { (-qb + disc.sqrt()) / (2.0 * qa) } else { -(-qb - disc.sqrt()) / (2.0 * qa) };
893 q.clamp(0.0, by_current)
894 };
895 let torque = |d: f64| {
896 let q = if motoring { q_at(d) } else { -q_at(d) };
897 let t = self.torque_with(q, d, 1.0);
898 (if motoring { t } else { -t }).max(0.0)
899 };
900 let (mut lo, mut hi) = (-imax, 0.0);
901 let g = 0.5 * (5f64.sqrt() - 1.0);
902 let (mut x1, mut x2) = (hi - g * (hi - lo), lo + g * (hi - lo));
903 let (mut f1, mut f2) = (torque(x1), torque(x2));
904 for _ in 0..40 {
905 if f1 < f2 {
906 (lo, x1, f1) = (x1, x2, f2);
907 x2 = lo + g * (hi - lo);
908 f2 = torque(x2);
909 } else {
910 (hi, x2, f2) = (x2, x1, f1);
911 x1 = hi - g * (hi - lo);
912 f1 = torque(x1);
913 }
914 }
915 f1.max(f2).max(torque(0.0))
916 }
917
918 pub fn voltage_limited_current(&self, speed: f64, umax: f64, motoring: bool) -> f64 {
929 let (r, e) = (self.resistance, self.ke * speed);
930 let x = self.pole_pairs * speed * self.inductance;
931 let i = if x == 0.0 {
932 (if motoring { umax - e } else { umax + e }) / r
933 } else {
934 let (a, b) = (r * r + x * x, if motoring { r * e } else { -r * e });
935 (-b + (b * b - a * (e * e - umax * umax)).max(0.0).sqrt()) / a
936 };
937 i.clamp(0.0, self.max_current)
938 }
939
940 pub fn forced_braking_current(&self, speed: f64, umax: f64) -> f64 {
944 let (r, e) = (self.resistance, self.ke * speed);
945 if !(e > umax) {
946 return 0.0;
947 }
948 let x = self.pole_pairs * speed * self.inductance;
949 let a = r * r + x * x;
950 ((r * e - (a * umax * umax - x * x * e * e).max(0.0).sqrt()) / a).clamp(0.0, self.max_current)
951 }
952
953 pub fn settled_rise(&self, rms_current: f64, iron_loss: f64) -> f64 {
958 let q = self.rated_rise / (1.0 + COPPER * self.rated_rise) * (rms_current / self.stall_current).powi(2);
959 let iron = self.iron_heating(iron_loss) * self.thermal_nodes.map_or(1.0, |n| 1.0 - n.winding_share);
960 if COPPER * q < 1.0 { (q + iron) / (1.0 - COPPER * q) } else { f64::INFINITY }
961 }
962
963 pub fn rated_loss(&self) -> f64 {
966 self.resistance_at(self.rated_rise) * self.stall_current * self.stall_current
967 }
968
969 pub fn s1_torque(&self, speed: f64) -> f64 {
973 if !self.s1_curve.is_empty() {
974 return s1_interpolated(&self.s1_curve, speed);
975 }
976 let still = if self.static_torque > 0.0 { self.static_torque } else { self.rated_torque };
977 s1_line(still, self.rated_torque, self.rated_speed, speed)
978 }
979
980 pub fn iron_heating(&self, loss: f64) -> f64 {
982 self.rated_rise * loss / self.rated_loss()
983 }
984
985 pub fn torque_curve(&self, speed: f64) -> (f64, f64) {
989 self.torque_curve_at(speed, self.max_voltage)
990 }
991
992 pub fn torque_curve_at(&self, speed: f64, max_voltage: f64) -> (f64, f64) {
995 match &self.motor {
997 Motor::Stepper(s) => return s.torque_curve(self, speed, max_voltage / WINDING_PER_DC_LINK),
998 Motor::Induction(m) => return m.torque_curve(self, speed, max_voltage / WINDING_PER_DC_LINK),
999 Motor::Servo => {}
1000 }
1001 if let Some(fw) = &self.field_weakening {
1002 let imax = self.max_current.min(self.drive_max_current);
1003 let (motoring, braking) = (
1004 self.field_weakened_torque(fw, speed.abs(), max_voltage, true, imax).min(self.peak_torque),
1005 self.field_weakened_torque(fw, speed.abs(), max_voltage, false, imax).min(self.peak_torque),
1006 );
1007 return if speed >= 0.0 { (-braking, motoring) } else { (-motoring, braking) };
1008 }
1009 let printed = self.max_voltage / self.fundamental_gain;
1013 let (rated_speed, no_load_speed) = if max_voltage.is_finite() && printed.is_finite() && max_voltage != printed {
1014 (self.fade_speed(self.rated_speed, max_voltage), self.fade_speed(self.no_load_speed, max_voltage))
1015 } else {
1016 (self.rated_speed, self.no_load_speed)
1017 };
1018 let fade = ((no_load_speed - speed.abs()) / (no_load_speed - rated_speed).max(1e-12)).clamp(0.0, 1.0);
1019 let braking = if self.pole_pairs > 0.0 && max_voltage.is_finite() {
1022 self.peak_torque.min(self.torque_of(self.voltage_limited_current(speed.abs(), max_voltage, false)))
1023 } else {
1024 self.peak_torque
1025 };
1026 let motoring = self.peak_torque * fade;
1027 if speed >= 0.0 { (-braking, motoring) } else { (-motoring, braking) }
1028 }
1029
1030 fn fade_speed(&self, speed: f64, umax: f64) -> f64 {
1038 let printed = self.max_voltage / self.fundamental_gain;
1039 let proportional = speed * umax / printed;
1040 let i = self.voltage_limited_current(speed, printed, true);
1041 if self.ke <= 0.0 || i <= 1e-9 * self.max_current {
1042 return proportional;
1043 }
1044 let (r, x) = (self.resistance, self.pole_pairs * self.inductance * i);
1045 let at = |u: f64| {
1046 let (a, b, c) = (self.ke * self.ke + x * x, 2.0 * r * i * self.ke, r * r * i * i - u * u);
1047 if c >= 0.0 { 0.0 } else { (-b + (b * b - 4.0 * a * c).sqrt()) / (2.0 * a) }
1048 };
1049 let at_printed = at(printed);
1050 if at_printed > 0.0 { speed * at(umax) / at_printed } else { proportional }
1051 }
1052
1053 pub fn voltage_limited_torque(&self, speed: f64, dc_voltage: f64) -> (f64, f64) {
1060 match &self.motor {
1061 Motor::Stepper(s) => return s.torque_curve(self, speed, self.fundamental_gain * dc_voltage),
1062 Motor::Induction(m) => return m.torque_curve(self, speed, self.fundamental_gain * dc_voltage),
1063 Motor::Servo => {}
1064 }
1065 let umax = self.dc_gain() * dc_voltage;
1066 let (motoring, braking) = match &self.field_weakening {
1067 Some(fw) => (
1068 self.field_weakened_torque(fw, speed.abs(), umax, true, self.max_current),
1069 self.field_weakened_torque(fw, speed.abs(), umax, false, self.max_current),
1070 ),
1071 None => (
1072 self.torque_of(self.voltage_limited_current(speed.abs(), umax, true)),
1073 self.torque_of(self.voltage_limited_current(speed.abs(), umax, false)),
1074 ),
1075 };
1076 if speed >= 0.0 { (-braking, motoring) } else { (-motoring, braking) }
1077 }
1078
1079 pub fn motor_rates(&self, d: &Drive, w: &[f64], angle: f64, speed: f64, rates: &mut [f64]) -> f64 {
1083 match &self.motor {
1084 Motor::Servo => {
1085 let (i, flux) = (w[0], d.flux(self));
1086 rates[..4].copy_from_slice(&self.winding_rates(
1087 d.voltage,
1088 d.winding_resistance(self),
1089 i,
1090 speed,
1091 d.d_current,
1092 flux,
1093 ));
1094 rates[4..].fill(0.0);
1095 self.torque_with(i, d.d_current, flux) - self.iron_drag(speed)
1096 }
1097 Motor::Stepper(s) => s.rates(self, d, w, angle, speed, rates),
1098 Motor::Induction(m) => m.rates(self, d, w, speed, rates),
1099 }
1100 }
1101}
1102
1103pub fn s1_curve_of(cfg: &Config) -> Result<Vec<[f64; 2]>> {
1107 let (sk, tk) = ("motor.s1_curve_speed_rad_s", "motor.s1_curve_torque_nm");
1108 if cfg.get(sk).is_err() && cfg.get(tk).is_err() {
1109 return Ok(Vec::new());
1110 }
1111 let (speeds, torques) = (cfg.f64s(sk)?, cfg.f64s(tk)?);
1112 if speeds.is_empty() && torques.is_empty() {
1113 return Ok(Vec::new());
1114 }
1115 if speeds.len() != torques.len()
1116 || speeds.len() < 2
1117 || speeds.iter().chain(&torques).any(|x| !x.is_finite())
1118 || speeds[0] < 0.0
1119 || speeds.windows(2).any(|w| w[1] <= w[0])
1120 || torques.iter().any(|t| *t < 0.0)
1121 {
1122 return Err(ConfigError::Invalid(sk.into()));
1123 }
1124 Ok(speeds.into_iter().zip(torques).map(|(w, t)| [w, t]).collect())
1125}
1126
1127pub fn s1_interpolated(curve: &[[f64; 2]], speed: f64) -> f64 {
1130 let w = speed.abs();
1131 match curve.iter().position(|p| p[0] >= w) {
1132 Some(0) => curve[0][1],
1133 Some(k) => {
1134 let (a, b) = (curve[k - 1], curve[k]);
1135 a[1] + (b[1] - a[1]) * (w - a[0]) / (b[0] - a[0])
1136 }
1137 None => curve[curve.len() - 1][1],
1138 }
1139}
1140
1141pub fn s1_line(static_torque: f64, rated_torque: f64, rated_speed: f64, speed: f64) -> f64 {
1144 (static_torque + (rated_torque - static_torque) * speed.abs() / rated_speed).max(0.0)
1145}
1146
1147fn notch_coefficients(frequency: f64, bandwidth: f64, cycle: f64) -> [f64; 5] {
1149 let w0 = TAU * frequency * cycle;
1150 let alpha = w0.sin() / (2.0 * frequency / bandwidth);
1151 let a0 = 1.0 + alpha;
1152 [1.0 / a0, -2.0 * w0.cos() / a0, 1.0 / a0, -2.0 * w0.cos() / a0, (1.0 - alpha) / a0]
1153}
1154
1155#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)]
1162pub enum DriveMode {
1163 #[default]
1164 Position,
1165 Velocity(f64),
1166 Torque(f64),
1167}
1168
1169#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
1171pub struct Drive {
1172 pub pos_set: f64,
1173 pub vel_set: f64,
1175 pub acc_set: f64,
1176 pub since_setpoint: f64,
1178 pub torque_ff: f64,
1179 #[serde(default)]
1182 pub friction_ff: f64,
1183 pub position_setpoint: f64,
1186 pub following_error: f64,
1187 pub position_part: f64,
1189 pub feedforward_torque: f64,
1192 pub controller_torque: f64,
1193 pub speed_command: f64,
1194 pub torque_demand: f64,
1196 pub torque_command: f64,
1197 pub torque_injection: f64,
1200 pub torque: f64,
1201 pub current: f64,
1203 pub voltage: f64,
1204 pub power: f64,
1206 pub copper_loss: f64,
1208 pub shaft_power: f64,
1209 pub temperature_rise: f64,
1211 pub housing_rise: f64,
1213 pub d_current: f64,
1218 #[serde(default)]
1221 pub d_voltage: f64,
1222 pub overload_image: f64,
1225 pub overload_chip: f64,
1226 pub overloaded: bool,
1227 pub iron_loss: f64,
1229 #[serde(default)]
1234 pub emf_loss: f64,
1235 #[serde(default)]
1241 pub torque_hold: f64,
1242 pub resistor_rise: f64,
1244 pub enable_energy: f64,
1247 pub dc_voltage: f64,
1250 pub resistor_power: f64,
1251 pub tripped: bool,
1252 pub rectifier_power: f64,
1256 pub mains_power: f64,
1257 pub line_loss: f64,
1258 pub discharge_power: f64,
1261 pub noise: Noise,
1263 pub at_limit: bool,
1265 pub fault_speed: Option<f64>,
1269 pub pulses_off: bool,
1270 current_integral: f64,
1271 integral: f64,
1272 encoder: f64,
1273 last_encoder: f64,
1274 speed: f64,
1275 filtered: f64,
1276 notch: [f64; 4],
1277 voltage_queue: VecDeque<f64>,
1279 torque_queue: VecDeque<f64>,
1280 mode: DriveMode,
1281 retune: bool,
1284 pub phases: Phases,
1286}
1287
1288pub(crate) fn delayed<T: Clone>(queue: &mut VecDeque<T>, value: T, cycles: usize) -> T {
1290 queue.push_back(value);
1291 while queue.len() > cycles + 1 {
1292 queue.pop_front();
1293 }
1294 queue[0].clone()
1295}
1296
1297impl Drive {
1298 pub fn at_rest(p: &DriveParams, pos: f64, torque: f64, torque_ff: f64) -> Self {
1300 let encoder = quantise(pos, p.encoder_step);
1301 let mut drive = Self {
1302 pos_set: pos,
1303 position_setpoint: pos,
1304 torque_ff,
1305 feedforward_torque: p.torque_ff * torque_ff,
1306 controller_torque: torque - p.torque_ff * torque_ff,
1307 torque_demand: torque,
1308 torque_command: torque,
1309 torque,
1310 current: p.current_for(torque),
1311 temperature_rise: if p.heating { p.start_rise } else { 0.0 },
1312 housing_rise: match (p.heating, &p.thermal_nodes) {
1314 (true, Some(n)) => p.start_rise * (1.0 - n.winding_share),
1315 _ => 0.0,
1316 },
1317 dc_voltage: p.bus_voltage,
1318 noise: Noise(p.noise_seed),
1319 integral: torque - p.torque_ff * torque_ff,
1320 encoder,
1321 last_encoder: encoder,
1322 filtered: torque,
1323 notch: [torque; 4],
1324 voltage_queue: std::iter::repeat_n(0.0, p.current_delay).collect(),
1325 torque_queue: std::iter::repeat_n(torque, p.velocity_delay).collect(),
1326 ..Self::default()
1327 };
1328 match &p.motor {
1329 Motor::Stepper(s) => s.at_rest(&mut drive, p, pos),
1330 Motor::Induction(m) => m.at_rest(&mut drive, p, pos, torque),
1331 Motor::Servo => {}
1332 }
1333 drive.hold_current(p);
1334 drive
1335 }
1336
1337 pub fn winding_states(&self, p: &DriveParams) -> [f64; WINDING_STATES] {
1339 match p.motor {
1340 Motor::Servo => [self.current, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
1341 _ => {
1342 let x = self.phases.x;
1343 [x[0], 0.0, 0.0, 0.0, x[1], x[2], x[3]]
1344 }
1345 }
1346 }
1347
1348 pub fn winding_energy(&self, p: &DriveParams) -> f64 {
1351 match &p.motor {
1352 Motor::Induction(m) => m.stored_energy(&self.phases.x),
1353 _ => 0.5 * p.inductance * self.current * self.current,
1354 }
1355 }
1356
1357 pub fn magnetic_energy(&self, p: &DriveParams) -> f64 {
1360 self.winding_energy(p)
1361 }
1362
1363 pub fn detent_moved(&mut self, p: &DriveParams, before: f64) {
1367 if let Motor::Stepper(s) = &p.motor {
1368 let (after, origin) = (self.phases.angle, self.phases.origin);
1369 self.emf_loss = (s.detent_potential(after, origin) - s.detent_potential(before, origin)) / p.current_cycle;
1370 }
1371 }
1372
1373 pub fn hold_current(&mut self, p: &DriveParams) {
1378 let voltage = self.winding_resistance(p) * self.current;
1379 (self.voltage, self.current_integral) = (voltage, voltage);
1380 self.voltage_queue.iter_mut().for_each(|v| *v = voltage);
1381 }
1382
1383 pub fn encoder(&self) -> f64 {
1384 self.encoder
1385 }
1386
1387 pub fn mode(&self) -> DriveMode {
1388 self.mode
1389 }
1390
1391 pub fn set_mode(&mut self, mode: DriveMode) {
1396 if std::mem::discriminant(&mode) != std::mem::discriminant(&self.mode) {
1397 self.retune = true;
1398 }
1399 self.mode = mode;
1400 }
1401
1402 pub fn retune(&mut self) {
1404 self.retune = true;
1405 }
1406
1407 pub fn phase_current(&self) -> f64 {
1409 self.current.hypot(self.d_current)
1410 }
1411
1412 pub fn phase_voltage(&self, p: &DriveParams) -> f64 {
1417 match p.motor {
1418 Motor::Servo => self.voltage.hypot(self.d_voltage) * PHASE_PER_WINDING,
1419 _ => self.voltage,
1420 }
1421 }
1422
1423 pub fn thermal_current(&self, p: &DriveParams) -> f64 {
1426 match p.motor {
1427 Motor::Induction(_) => (self.copper_loss / self.winding_resistance(p)).sqrt(),
1428 _ => self.phase_current(),
1429 }
1430 }
1431
1432 pub fn measured_speed(&self) -> f64 {
1434 self.speed
1435 }
1436
1437 pub fn overload_nodes(&self) -> [f64; 2] {
1439 [self.overload_image - self.overload_chip, self.overload_chip]
1440 }
1441
1442 pub fn flux(&self, p: &DriveParams) -> f64 {
1448 if p.magnet_coefficient == 0.0 || !p.heating {
1449 return 1.0;
1450 }
1451 let (rise, rated) = match &p.thermal_nodes {
1454 Some(n) => (self.housing_rise, (1.0 - n.winding_share) * p.rated_rise),
1455 None => (self.temperature_rise, p.rated_rise),
1456 };
1457 1.0 + p.magnet_coefficient * (rise - rated)
1458 }
1459
1460 pub fn shift_encoder(&mut self, by: f64) {
1462 self.encoder += by;
1463 self.last_encoder += by;
1464 }
1465
1466 pub fn shift_setpoint(&mut self, by: f64) {
1468 self.pos_set += by;
1469 self.position_setpoint += by;
1470 }
1471
1472 pub fn read_encoder(&mut self, p: &DriveParams, pos: f64) {
1475 let noise = if p.encoder_noise > 0.0 { p.encoder_noise * self.noise.next() } else { 0.0 };
1476 self.encoder = quantise(pos + noise, p.encoder_step);
1477 }
1478
1479 pub fn position_loop(&mut self, p: &DriveParams, measured: f64, cycle: f64) {
1482 if self.mode != DriveMode::Position {
1483 (self.position_setpoint, self.following_error, self.position_part) = (measured, 0.0, 0.0);
1485 return;
1486 }
1487 let (c, t) = (&p.precontrol, self.since_setpoint);
1488 let target = if c.fine_interpolation {
1489 self.pos_set + (self.vel_set + 0.5 * self.acc_set * t) * t
1490 } else {
1491 self.pos_set
1492 };
1493 let share = if c.balance_time > 0.0 { 1.0 - (-cycle / c.balance_time).exp() } else { 1.0 };
1494 self.position_setpoint += share * (target - self.position_setpoint);
1495 self.following_error = self.position_setpoint - measured;
1496 self.position_part = p.kv * self.following_error;
1497 self.speed_command = self.position_part + p.velocity_ff * (self.vel_set + self.acc_set * t);
1498 }
1499
1500 pub fn max_voltage(&self, p: &DriveParams) -> f64 {
1502 if p.dc_link && p.max_voltage.is_finite() { p.dc_gain() * self.dc_voltage } else { p.max_voltage }
1503 }
1504
1505 pub fn velocity_loop(&mut self, p: &DriveParams, true_speed: f64) {
1507 let raw =
1509 if p.speed_from_positions { (self.encoder - self.last_encoder) / p.velocity_cycle } else { true_speed };
1510 self.last_encoder = self.encoder;
1511 self.speed += p.velocity_filter * (raw - self.speed);
1512
1513 let speed_set = self.vel_set + self.acc_set * self.since_setpoint;
1516 if p.motor.open_loop() {
1518 self.speed_command = match (self.fault_speed, self.mode) {
1519 (Some(speed), _) | (None, DriveMode::Velocity(speed)) => speed,
1520 _ => speed_set,
1521 };
1522 return;
1523 }
1524 let mode = if self.fault_speed.is_some() { DriveMode::Velocity(0.0) } else { self.mode };
1526 self.speed_command = match (self.fault_speed, mode) {
1527 (Some(speed), _) | (None, DriveMode::Velocity(speed)) => speed,
1528 _ => self.position_part + p.velocity_ff * speed_set,
1529 };
1530
1531 let error = self.speed_command - self.speed;
1532 let outside_torque = match mode {
1533 DriveMode::Torque(torque) => Some(torque),
1534 _ => None,
1535 };
1536 let feedforward = match mode {
1537 DriveMode::Position => {
1538 p.torque_ff * self.torque_ff + p.precontrol.friction_at(speed_set) + self.friction_ff
1539 }
1540 _ => 0.0,
1541 };
1542 if self.retune && outside_torque.is_none() {
1543 self.integral = self.controller_torque + self.feedforward_torque - feedforward - p.kp * error;
1544 self.retune = false;
1545 }
1546 self.controller_torque = outside_torque.unwrap_or(p.kp * error + self.integral);
1547 self.feedforward_torque = feedforward;
1548 let wanted = self.controller_torque + self.feedforward_torque;
1549 self.filtered += p.torque_filter * (wanted - self.filtered);
1550 let mut out = self.filtered;
1551 if let Some([b0, b1, b2, a1, a2]) = p.notch {
1552 let [x1, x2, y1, y2] = self.notch;
1553 out = b0 * self.filtered + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
1554 self.notch = [self.filtered, x1, out, y1];
1555 }
1556 let (mut low, mut high) = p.torque_range_at(self.speed, self.max_voltage(p));
1558 if let (true, Some(o), false) = (self.overloaded, &p.overload, matches!(p.motor, Motor::Induction(_))) {
1561 let most = p.torque_of(o.base_current);
1562 (low, high) = (low.max(-most), high.min(most));
1563 }
1564 self.torque_demand = out;
1565 self.at_limit = out + self.torque_injection > high || out + self.torque_injection < low;
1566 self.torque_command =
1567 delayed(&mut self.torque_queue, (out + self.torque_injection).clamp(low, high), p.velocity_delay);
1568 if outside_torque.is_none() && (out <= high || error < 0.0) && (out >= low || error > 0.0) {
1570 self.integral += p.ki * error * p.velocity_cycle;
1571 }
1572 }
1573
1574 pub fn current_control(&mut self, p: &DriveParams, speed: f64) {
1577 match &p.motor {
1578 Motor::Stepper(s) => return s.control(self, p),
1579 Motor::Induction(m) => return m.control(self, p, speed),
1580 Motor::Servo => {}
1581 }
1582 let measured = self.current + if p.current_noise > 0.0 { p.current_noise * self.noise.next() } else { 0.0 };
1583 let mut setpoint = p.current_for(self.torque_command);
1584 let max_voltage = self.max_voltage(p);
1585 let (resistance, flux, w) = (self.winding_resistance(p), self.flux(p), p.pole_pairs * speed);
1589 let steady_d = resistance * self.d_current - w * p.inductance * self.current;
1590 let (coupling, u_d) = match &p.field_weakening {
1591 Some(fw) => {
1592 let limit = p.max_current.min(p.drive_max_current);
1595 let mut q_ref = if self.current.abs() > setpoint.abs() { self.current } else { setpoint };
1596 let fits = |q: f64| {
1599 let (d, w) =
1600 (p.d_current_for(q, speed, max_voltage, limit, resistance, flux), fw.pole_pairs * speed);
1601 let (u_q, u_d) = (
1602 resistance * q + flux * p.ke * speed + w * fw.d_inductance * d,
1603 resistance * d - w * p.inductance * q,
1604 );
1605 q * q + d * d <= limit * limit && u_q * u_q + u_d * u_d <= max_voltage * max_voltage * (1.0 + 1e-9)
1606 };
1607 if !fits(q_ref) {
1608 let (mut lo, mut hi) = (0.0, q_ref.abs());
1609 for _ in 0..40 {
1610 let mid = 0.5 * (lo + hi);
1611 if fits(mid.copysign(q_ref)) { lo = mid } else { hi = mid }
1612 }
1613 q_ref = lo.copysign(q_ref);
1614 }
1615 let wanted_d = p.d_current_for(q_ref, speed, max_voltage, limit, resistance, flux);
1616 let lag = 1.0 - (-p.current_cycle * p.current_kp / fw.d_inductance).exp();
1620 let free = steady_d + fw.d_inductance * lag * (wanted_d - self.d_current) / p.current_cycle;
1621 let u_d = free.clamp(-max_voltage, max_voltage);
1622 if u_d == free {
1623 self.d_current += lag * (wanted_d - self.d_current);
1624 } else {
1625 self.d_current += (u_d - steady_d) * p.current_cycle / fw.d_inductance;
1626 }
1627 let q_most = (limit * limit - wanted_d * wanted_d).max(0.0).sqrt();
1630 setpoint = setpoint.clamp(-q_most, q_most);
1631 (w * fw.d_inductance * self.d_current, u_d)
1632 }
1633 None => {
1634 if p.limit && speed != 0.0 && max_voltage.is_finite() {
1637 let forced = p.forced_braking_current(speed.abs(), max_voltage);
1638 if forced > 0.0 && setpoint * speed.signum() > -forced {
1639 setpoint = -forced * speed.signum();
1640 }
1641 }
1642 (0.0, steady_d)
1643 }
1644 };
1645 let q_voltage = (max_voltage * max_voltage - u_d * u_d).max(0.0).sqrt();
1646 self.d_voltage = u_d;
1647 let error = setpoint - measured;
1648 self.iron_loss = p.iron_loss_at(speed);
1649 let back_emf = p.back_emf(self.current, speed) + coupling;
1652 let wanted = p.current_kp * error + self.current_integral + back_emf;
1653 let limited = wanted.clamp(-q_voltage, q_voltage);
1654 self.voltage = delayed(&mut self.voltage_queue, limited, p.current_delay);
1655 if wanted == limited {
1657 self.current_integral += p.current_ki * error * p.current_cycle;
1658 }
1659 }
1660
1661 pub fn winding_resistance(&self, p: &DriveParams) -> f64 {
1663 if p.heating { p.resistance_at(self.temperature_rise) } else { p.resistance }
1664 }
1665
1666 pub fn winding_stepped(&mut self, p: &DriveParams, current: f64, [electrical, copper, work]: [f64; 3]) {
1670 let dt = p.current_cycle;
1671 match &p.motor {
1672 Motor::Servo => {
1673 self.emf_loss = if p.ke > 0.0 && (p.ke != p.kt || p.iron_drag_rated > 0.0) {
1676 let stored = 0.5 * p.inductance * (current * current - self.current * self.current);
1677 (electrical - copper - work - stored) / dt
1678 } else {
1679 0.0
1680 };
1681 (self.current, self.torque) =
1682 (current, p.torque_with(current, self.d_current, self.flux(p)) - p.iron_drag(self.phases.speed))
1683 }
1684 Motor::Stepper(s) => s.stepped(self, p),
1685 Motor::Induction(m) => m.stepped(self, p),
1686 }
1687 (self.power, self.copper_loss, self.shaft_power, self.discharge_power) =
1689 ((electrical + std::mem::take(&mut self.enable_energy)) / dt, copper / dt, work / dt, 0.0);
1690 if p.dc_link && !p.shared_dc_link {
1692 self.own_dc_link(p);
1693 }
1694 self.warm(p);
1695 self.load_power_unit(p);
1696 }
1697
1698 fn load_power_unit(&mut self, p: &DriveParams) {
1701 if let Some(o) = &p.overload {
1702 let [slow, chip] = o.nodes_after(self.overload_nodes(), self.phase_current(), p.current_cycle);
1703 (self.overload_image, self.overload_chip) = (slow + chip, chip);
1704 if self.overload_image >= o.trip {
1705 self.overloaded = true;
1706 } else if self.overload_image <= 1.0 {
1707 self.overloaded = false;
1708 }
1709 }
1710 }
1711
1712 pub fn disabled_step(&mut self, p: &DriveParams, speed: f64) {
1723 let freewheeling = self.winding_energy(p);
1724 (self.phases.x, self.phases.u, self.phases.integral) = ([0.0; 4], [0.0; 2], [0.0; 2]);
1725 (self.torque, self.torque_command, self.torque_demand, self.current, self.voltage, self.d_voltage) =
1726 (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
1727 let drag = p.iron_drag(speed);
1728 (self.power, self.copper_loss, self.shaft_power, self.d_current, self.iron_loss) = (
1729 -freewheeling / p.current_cycle,
1730 0.0,
1731 -drag * speed,
1732 0.0,
1733 if matches!(p.motor, Motor::Servo) { p.iron_loss_at(speed) } else { 0.0 },
1734 );
1735 (self.torque, self.emf_loss) = (-drag, drag * speed);
1736 self.warm(p);
1737 self.load_power_unit(p);
1738 if p.dc_link {
1739 let before = self.dc_voltage;
1742 self.dc_voltage *= (-p.current_cycle / p.discharge_time_constant).exp();
1743 self.discharge_power =
1744 0.5 * p.dc_capacitance * (before * before - self.dc_voltage * self.dc_voltage) / p.current_cycle;
1745 if !p.shared_dc_link {
1746 self.own_dc_link(p);
1747 }
1748 }
1749 }
1750
1751 fn own_dc_link(&mut self, p: &DriveParams) {
1753 let stored = 0.5 * p.dc_capacitance * self.dc_voltage * self.dc_voltage;
1754 self.set_dc_link(p, dc_link_step(p, p.dc_capacitance, stored, self.power));
1755 }
1756
1757 fn set_dc_link(&mut self, p: &DriveParams, step: DcLinkStep) {
1758 (self.dc_voltage, self.resistor_power, self.rectifier_power, self.mains_power, self.line_loss) =
1759 (step.voltage, step.resistor, step.drawn, step.mains, step.line_loss);
1760 self.tripped |= self.dc_voltage > p.overvoltage;
1761 if let Some(r) = &p.resistor_heating {
1762 self.resistor_rise = r.rise_after(self.resistor_rise, self.resistor_power, p.current_cycle);
1763 }
1764 }
1765
1766 fn warm(&mut self, p: &DriveParams) {
1773 if p.heating {
1774 let (heating, iron) = (p.iron_heating(self.copper_loss), p.iron_heating(self.iron_loss));
1775 let dt = p.current_cycle;
1776 match &p.thermal_nodes {
1777 None => {
1778 self.temperature_rise += dt / p.thermal_time_constant * (heating + iron - self.temperature_rise)
1779 }
1780 Some(n) => {
1782 let (s, across) = (n.winding_share, self.temperature_rise - self.housing_rise);
1783 let housing_time = p.thermal_time_constant - n.winding_time_constant / s;
1784 self.temperature_rise += dt / n.winding_time_constant * (s * heating - across);
1785 self.housing_rise += dt / housing_time * (across / s - self.housing_rise / (1.0 - s) + iron);
1786 }
1787 }
1788 }
1789 }
1790}
1791
1792#[derive(Debug, Clone, Copy)]
1795struct DcLinkStep {
1796 voltage: f64,
1797 resistor: f64,
1798 drawn: f64,
1799 mains: f64,
1800 line_loss: f64,
1801}
1802
1803fn dc_link_step(p: &DriveParams, capacitance: f64, stored: f64, power: f64) -> DcLinkStep {
1806 let (at, dt) = (|voltage: f64| 0.5 * capacitance * voltage * voltage, p.current_cycle);
1809 let energy = stored - power * dt;
1810 let fed = if p.regenerative { (energy - at(p.bus_voltage)).clamp(0.0, p.line_max_power * dt) } else { 0.0 };
1813 let burned = (energy - fed - at(p.braking_threshold)).clamp(0.0, p.resistor_peak * dt);
1816 let left = energy - fed - burned;
1818 let (voltage, drawn) = if left > at(p.bus_voltage) {
1819 ((2.0 * left / capacitance).sqrt(), 0.0)
1820 } else {
1821 (p.bus_voltage, at(p.bus_voltage) - left)
1822 };
1823 DcLinkStep {
1826 voltage,
1827 resistor: burned / dt,
1828 drawn: drawn / p.line_efficiency / dt,
1829 mains: p.line_efficiency * fed / dt,
1830 line_loss: ((1.0 - p.line_efficiency) * fed + (1.0 / p.line_efficiency - 1.0) * drawn) / dt,
1831 }
1832}
1833
1834pub fn shared_dc_link(p: &DriveParams, drives: &mut [Drive]) {
1842 if drives.is_empty() {
1843 return;
1844 }
1845 let stored: f64 = drives.iter().map(|d| 0.5 * p.dc_capacitance * d.dc_voltage * d.dc_voltage).sum();
1846 let power: f64 = drives.iter().map(|d| d.power).sum();
1847 let step = dc_link_step(p, p.dc_capacitance * drives.len() as f64, stored, power);
1848 for drive in drives {
1849 drive.set_dc_link(p, step);
1850 }
1851}
1852
1853pub(crate) fn quantise(pos: f64, step: f64) -> f64 {
1854 if step > 0.0 { (pos / step).round() * step } else { pos }
1855}
1856
1857#[cfg(test)]
1858pub(crate) mod tests {
1859 use super::*;
1860
1861 pub(crate) fn params() -> DriveParams {
1863 DriveParams {
1864 kv: 50.0,
1865 kp: 0.08,
1866 ki: 8.0,
1867 velocity_ff: 0.0,
1868 torque_ff: 0.0,
1869 kt: 0.45,
1870 resistance: 4.0,
1871 ke: 0.45,
1872 max_voltage: 190.0,
1873 fundamental_gain: 1.0,
1874 current_kp: 40.0,
1876 current_ki: 40.0 / 2.5e-3,
1877 current_cycle: 62.5e-6,
1878 peak_torque: 3.8,
1879 rated_torque: 1.27,
1880 rated_speed: 314.0,
1881 no_load_speed: 420.0,
1882 max_speed: 420.0,
1883 limit: true,
1884 encoder_step: 0.0,
1885 speed_from_positions: false,
1886 velocity_filter: 1.0,
1887 torque_filter: 1.0,
1888 notch: None,
1889 velocity_cycle: 125e-6,
1890 current_delay: 0,
1891 velocity_delay: 0,
1892 inductance: 0.010,
1893 pole_pairs: 0.0,
1894 heating: false,
1895 rated_rise: 100.0,
1896 housing_max_rise: 100.0,
1897 rated_current: 1.27 / 0.45,
1898 thermal_time_constant: 1800.0,
1899 start_rise: 0.0,
1900 saturation: 0.0,
1901 max_current: 9.5,
1902 drive_max_current: f64::INFINITY,
1903 dc_link: false,
1904 shared_dc_link: false,
1905 bus_voltage: 190.0,
1906 dc_capacitance: 470e-6,
1907 braking_threshold: 250.0,
1908 resistor_peak: 500.0,
1909 overvoltage: 280.0,
1910 discharge_time_constant: 130.0,
1911 regenerative: false,
1912 line_max_power: 35000.0,
1913 line_efficiency: 0.98,
1914 encoder_noise: 0.0,
1915 current_noise: 0.0,
1916 noise_seed: 1,
1917 field_weakening: None,
1918 overload: None,
1919 thermal_nodes: None,
1920 precontrol: Precontrol::default(),
1921 motor: Motor::Servo,
1922 iron_loss_rated: 0.0,
1923 iron_drag_rated: 0.0,
1924 stall_current: 1.27 / 0.45,
1925 static_torque: 0.0,
1926 s1_curve: Vec::new(),
1927 magnet_coefficient: 0.0,
1928 resistor_heating: None,
1929 }
1930 }
1931
1932 impl Drive {
1933 fn current_loop(&mut self, p: &DriveParams, speed: f64) {
1936 self.current_control(p, speed);
1937 let (voltage, resistance, d_current, flux) =
1938 (self.voltage, self.winding_resistance(p), self.d_current, self.flux(p));
1939 let mut y = [self.current, 0.0, 0.0, 0.0];
1940 let mut rk = sim_core::Rk4::new(4);
1941 for _ in 0..4 {
1942 rk.step(
1943 |y, dy| dy.copy_from_slice(&p.winding_rates(voltage, resistance, y[0], speed, d_current, flux)),
1944 &mut y,
1945 p.current_cycle / 4.0,
1946 );
1947 }
1948 self.phases.speed = speed;
1949 self.winding_stepped(p, y[0], [y[1], y[2], y[3]]);
1950 }
1951 }
1952
1953 #[test]
1963 fn a_shared_dc_link_rises_by_the_net_energy_of_its_drives() {
1964 let run = |p: &DriveParams| {
1965 let mut drives = [Drive::at_rest(p, 0.0, -0.45, 0.0), Drive::at_rest(p, 0.0, 0.225, 0.0)];
1966 let mut burned = [0.0; 2];
1967 for _ in 0..(0.1 / p.current_cycle).round() as usize {
1968 drives.iter_mut().for_each(|d| d.current_loop(p, 100.0));
1969 if p.shared_dc_link {
1970 shared_dc_link(p, &mut drives);
1971 }
1972 for (burned, d) in burned.iter_mut().zip(&drives) {
1973 *burned += d.resistor_power * p.current_cycle;
1974 }
1975 }
1976 (drives, burned)
1977 };
1978 let apart = DriveParams { dc_link: true, ..params() };
1979 let (drives, burned) = run(&apart);
1980 assert!(
1981 (drives[0].dc_voltage - 231.40).abs() < 0.01 && drives[1].dc_voltage == 190.0 && burned == [0.0; 2],
1982 "{} V and {} V",
1983 drives[0].dc_voltage,
1984 drives[1].dc_voltage
1985 );
1986
1987 let shared = DriveParams { shared_dc_link: true, ..apart.clone() };
1988 let (drives, burned) = run(&shared);
1989 let by_hand = (2.0 * (2.0 * 8.4835 + 4.1 - 2.35) / 940e-6f64).sqrt();
1990 assert!(
1991 (by_hand - 199.56).abs() < 0.01 && (drives[0].dc_voltage - by_hand).abs() < 0.01,
1992 "{} V, by hand {by_hand} V",
1993 drives[0].dc_voltage
1994 );
1995 assert!(
1996 drives[1].dc_voltage == drives[0].dc_voltage
1997 && burned == [0.0; 2]
1998 && !drives[0].tripped
1999 && !drives[1].tripped
2000 );
2001 println!("separate 231.40 V and 190 V; shared {} V, by hand {by_hand} V", drives[0].dc_voltage);
2002
2003 let (drives, burned) = run(&DriveParams { braking_threshold: 195.0, ..shared.clone() });
2005 assert!(
2006 (drives[0].dc_voltage - 195.0).abs() < 1e-9 && drives[1].dc_voltage == drives[0].dc_voltage,
2007 "{} V",
2008 drives[0].dc_voltage
2009 );
2010 assert!((burned[0] - 0.845).abs() < 0.002 && burned[1] == burned[0], "{burned:?} J burned");
2011 let (drives, _) =
2013 run(&DriveParams { braking_threshold: 195.0, resistor_peak: 5.0, overvoltage: 198.0, ..shared.clone() });
2014 assert!(drives[0].tripped && drives[1].tripped);
2015 let (mut drives, _) = run(&apart);
2018 drives.iter_mut().for_each(|d| d.power = 0.0);
2019 shared_dc_link(&shared, &mut drives);
2020 assert!(
2021 (drives[0].dc_voltage - 211.72).abs() < 0.01 && drives[1].dc_voltage == drives[0].dc_voltage,
2022 "{} V",
2023 drives[0].dc_voltage
2024 );
2025 }
2026
2027 #[test]
2032 fn braking_energy_raises_the_dc_link_by_the_hand_calculated_voltage() {
2033 let p = DriveParams { dc_link: true, ..params() };
2034 let brake = |p: &DriveParams, seconds: f64| {
2035 let mut d = Drive::at_rest(p, 0.0, -0.45, 0.0);
2036 let (mut fed_back, mut burned) = (0.0, 0.0);
2037 for _ in 0..(seconds / p.current_cycle).round() as usize {
2038 d.current_loop(p, 100.0);
2039 fed_back -= d.power * p.current_cycle;
2040 burned += d.resistor_power * p.current_cycle;
2041 }
2042 (d, fed_back, burned)
2043 };
2044 let (d, fed_back, burned) = brake(&p, 0.1);
2045 assert!((fed_back - 4.1).abs() < 1e-9 && burned == 0.0, "{fed_back} J fed back, {burned} J burned");
2046 assert!((d.dc_voltage - 231.40).abs() < 0.01 && !d.tripped, "{} V", d.dc_voltage);
2047 assert!((0.5 * 470e-6 * (d.dc_voltage * d.dc_voltage - 190.0 * 190.0) - 4.1).abs() < 1e-9);
2048 let mut d = d;
2051 d.torque_command = 0.45;
2052 for _ in 0..1600 {
2053 d.current_loop(&p, 100.0);
2054 }
2055 assert_eq!(d.dc_voltage, 190.0);
2056 let (d, fed_back, burned) = brake(&p, 0.3);
2059 assert!(
2060 (d.dc_voltage - 250.0).abs() < 1e-9
2061 && (burned - (fed_back - 6.204)).abs() < 1e-9
2062 && (burned - 6.096).abs() < 1e-3,
2063 "{} V, {burned} J",
2064 d.dc_voltage
2065 );
2066 let weak = DriveParams { resistor_peak: 20.0, ..p.clone() };
2069 assert!(!brake(&weak, 0.32).0.tripped && brake(&weak, 0.34).0.tripped);
2070 let (mut d, ..) = brake(&p, 0.1);
2072 d.torque_command = 1000.0;
2073 d.current_loop(&p, 100.0);
2074 assert!((d.voltage - 283.41).abs() < 0.01, "{} V", d.voltage);
2075 let (d, ..) = brake(&DriveParams { dc_link: false, resistor_peak: 20.0, ..params() }, 0.34);
2077 assert!(d.dc_voltage == 190.0 && d.resistor_power == 0.0 && !d.tripped);
2078 }
2079
2080 #[test]
2087 fn a_regenerative_supply_feeds_back_into_the_mains_up_to_its_power() {
2088 let run = |p: &DriveParams, torque: f64| {
2089 let mut d = Drive::at_rest(p, 0.0, torque, 0.0);
2090 let (mut mains, mut lost, mut burned, mut drawn) = (0.0, 0.0, 0.0, 0.0);
2091 for _ in 0..1600 {
2092 d.current_loop(p, 100.0);
2093 (mains, lost, burned, drawn) = (
2094 mains + d.mains_power * p.current_cycle,
2095 lost + d.line_loss * p.current_cycle,
2096 burned + d.resistor_power * p.current_cycle,
2097 drawn + d.rectifier_power * p.current_cycle,
2098 );
2099 }
2100 (d, mains, lost, burned, drawn)
2101 };
2102 let p = DriveParams { dc_link: true, regenerative: true, ..params() };
2103 let (d, mains, lost, burned, drawn) = run(&p, -0.45);
2104 assert!(
2105 d.dc_voltage == 190.0
2106 && (mains - 4.018).abs() < 1e-9
2107 && (lost - 0.082).abs() < 1e-9
2108 && burned == 0.0
2109 && drawn == 0.0,
2110 "{} V, {mains} J, {lost} J",
2111 d.dc_voltage
2112 );
2113 let (d, mains, _, burned, _) = run(&DriveParams { line_max_power: 20.0, ..p.clone() }, -0.45);
2114 assert!(
2115 (d.dc_voltage - 212.217).abs() < 1e-3 && (mains - 1.96).abs() < 1e-9 && burned == 0.0,
2116 "{} V, {mains} J",
2117 d.dc_voltage
2118 );
2119 let (d, mains, lost, _, drawn) = run(&p, 0.45);
2120 assert!(
2121 d.dc_voltage == 190.0 && mains == 0.0 && (drawn - 5.0).abs() < 1e-9 && (lost - 0.1).abs() < 1e-9,
2122 "{drawn} J drawn, {lost} J lost"
2123 );
2124 let (_, _, lost, _, drawn) = run(&DriveParams { line_efficiency: 1.0, ..p.clone() }, 0.45);
2126 assert!((drawn - 4.9).abs() < 1e-9 && lost == 0.0, "{drawn} J drawn");
2127 }
2128
2129 #[test]
2138 fn speed_from_a_noisy_encoder_has_the_hand_calculated_rms() {
2139 let step = TAU / 1048576.0;
2140 let rms = |filter: f64| {
2141 let p = DriveParams {
2142 encoder_noise: 2.0 * step,
2143 speed_from_positions: true,
2144 velocity_filter: filter,
2145 ..params()
2146 };
2147 let mut d = Drive::at_rest(&p, 0.0, 0.0, 0.0);
2148 let mut sum = 0.0;
2149 for _ in 0..200_000 {
2150 d.read_encoder(&p, 0.0);
2151 d.velocity_loop(&p, 0.0);
2152 sum += d.speed * d.speed;
2153 }
2154 (sum / 200_000.0f64).sqrt()
2155 };
2156 let (raw, filtered) = (rms(1.0), rms(1.0 - (-125.0f64 / 200.0).exp()));
2157 assert!((raw - 0.1356).abs() < 0.02 * 0.1356, "{raw} rad/s unfiltered");
2158 assert!((filtered - 0.0509).abs() < 0.02 * 0.0509, "{filtered} rad/s filtered");
2159 let p = DriveParams { current_noise: 0.01, ..params() };
2161 let mut d = Drive::at_rest(&p, 0.0, 0.0, 0.0);
2162 d.current_loop(&p, 0.0);
2163 assert!(d.voltage != 0.0 && d.voltage.abs() < 6.0 * 0.4, "{} V", d.voltage);
2164 let mut d = Drive::at_rest(¶ms(), 0.0, 0.0, 0.0);
2166 d.read_encoder(¶ms(), 0.0);
2167 d.velocity_loop(¶ms(), 0.0);
2168 assert!(d.speed == 0.0 && d.noise.0 == 1);
2169 }
2170
2171 #[test]
2172 fn position_loop_is_kv_times_following_error_plus_feedforward() {
2173 let mut p = params();
2174 let mut d = Drive { pos_set: 1.0, vel_set: 10.0, ..Drive::default() };
2175 d.position_loop(&p, 0.9, 1e-3);
2176 assert!((d.following_error - 0.1).abs() < 1e-15 && (d.speed_command - 5.0).abs() < 1e-12);
2177 p.velocity_ff = 1.0;
2178 d.position_loop(&p, 0.9, 1e-3);
2179 assert!((d.speed_command - 15.0).abs() < 1e-12);
2180 }
2181
2182 #[test]
2186 fn fine_interpolation_runs_the_setpoint_on_between_profile_cycles() {
2187 let mut p = DriveParams { velocity_ff: 1.0, ..params() };
2188 let set = Drive { pos_set: 1.0, vel_set: 10.0, acc_set: 100.0, since_setpoint: 3e-3, ..Drive::default() };
2189 let mut held = set.clone();
2190 held.position_loop(&p, 1.0, 1e-3);
2191 assert_eq!((held.position_setpoint, held.following_error), (1.0, 0.0));
2192 p.precontrol.fine_interpolation = true;
2193 let mut d = set.clone();
2194 d.position_loop(&p, 1.0, 1e-3);
2195 assert!((d.position_setpoint - 1.03045).abs() < 1e-12 && (d.following_error - 0.03045).abs() < 1e-12);
2196 assert!((d.position_part - 1.5225).abs() < 1e-10 && (d.speed_command - (1.5225 + 10.3)).abs() < 1e-10);
2197 let (mut a, mut b) = (Drive { since_setpoint: 0.0, ..set.clone() }, Drive { since_setpoint: 0.0, ..set });
2199 a.position_loop(&p, 0.9, 1e-3);
2200 b.position_loop(&DriveParams { velocity_ff: 1.0, ..params() }, 0.9, 1e-3);
2201 assert_eq!(a.speed_command, b.speed_command);
2202 }
2203
2204 #[test]
2209 fn the_friction_feedforward_is_the_characteristic_at_the_speed_setpoint() {
2210 let c = Precontrol { friction: vec![[10.0, 0.2], [100.0, 0.3]], ..Precontrol::default() };
2211 assert!((c.friction_at(5.0) - 0.1).abs() < 1e-15 && (c.friction_at(-55.0) + 0.25).abs() < 1e-15);
2212 assert_eq!(
2213 (c.friction_at(200.0), c.friction_at(0.0), Precontrol::default().friction_at(50.0)),
2214 (0.3, 0.0, 0.0)
2215 );
2216 let p = DriveParams { torque_ff: 1.0, precontrol: c, ..params() };
2217 let mut d = Drive { vel_set: 4.0, acc_set: 1000.0, since_setpoint: 1e-3, torque_ff: 0.3, ..Drive::default() };
2218 d.velocity_loop(&p, 0.0);
2219 assert!((d.feedforward_torque - 0.4).abs() < 1e-12, "{}", d.feedforward_torque);
2220 assert!((d.controller_torque - 0.0).abs() < 1e-12 && (d.torque_demand - 0.4).abs() < 1e-12);
2221 }
2222
2223 #[test]
2226 fn balancing_lags_the_position_setpoint_by_its_time_constant() {
2227 let mut p = params();
2228 p.precontrol.balance_time = 1e-3;
2229 let mut d = Drive { pos_set: 1.0, ..Drive::default() };
2230 d.position_loop(&p, 0.0, 1e-3);
2231 assert!((d.position_setpoint - 0.632_120_558_8).abs() < 1e-9 && d.following_error == d.position_setpoint);
2232 d.position_loop(&p, 0.0, 1e-3);
2233 assert!((d.position_setpoint - 0.864_664_716_8).abs() < 1e-9);
2234 }
2235
2236 #[test]
2237 fn velocity_loop_is_pi_with_torque_feedforward() {
2238 let mut p = params();
2239 p.torque_ff = 1.0;
2240 let mut d = Drive { position_part: 10.0, torque_ff: 0.3, ..Drive::default() };
2241 d.velocity_loop(&p, 4.0);
2242 assert!((d.torque_command - (0.08 * 6.0 + 0.3)).abs() < 1e-12);
2243 d.velocity_loop(&p, 4.0);
2244 assert!((d.torque_command - (0.08 * 6.0 + 8.0 * 6.0 * 125e-6 + 0.3)).abs() < 1e-12);
2245 }
2246
2247 #[test]
2248 fn torque_limit_follows_the_torque_speed_curve() {
2249 let p = params();
2250 assert_eq!(p.torque_range(100.0), (-3.8, 3.8));
2251 let (low, high) = p.torque_range(367.0);
2253 assert!((high - 1.9).abs() < 1e-12 && low == -3.8);
2254 assert_eq!(p.torque_range(-500.0), (-0.0, 3.8));
2255 let mut d = Drive { position_part: 1000.0, ..Drive::default() };
2256 d.velocity_loop(&p, 0.0);
2257 assert_eq!(d.torque_command, 3.8);
2258 let before = d.integral;
2259 d.velocity_loop(&p, 0.0);
2260 assert_eq!(d.integral, before, "the integrator winds up at the limit");
2261 let unlimited = DriveParams { limit: false, ..params() };
2262 let mut d = Drive { position_part: 1000.0, ..Drive::default() };
2263 d.velocity_loop(&unlimited, 0.0);
2264 assert!(d.torque_command > 3.8);
2265 assert_eq!(unlimited.torque_curve(100.0), (-3.8, 3.8));
2266 }
2267
2268 #[test]
2273 fn the_drive_current_limit_holds_the_torque_to_the_lower_of_motor_and_drive() {
2274 let small = DriveParams { drive_max_current: 5.0, ..params() };
2275 assert_eq!(small.torque_range(100.0), (-2.25, 2.25));
2276 assert_eq!(small.torque_range(367.0), (-2.25, 1.9), "the torque-speed curve below the drive's limit");
2277 let mut d = Drive { position_part: 1000.0, ..Drive::default() };
2278 d.velocity_loop(&small, 0.0);
2279 let before = d.integral;
2280 d.velocity_loop(&small, 0.0);
2281 assert!(
2282 d.torque_command == 2.25
2283 && d.integral == before
2284 && (small.current_for(d.torque_command) - 5.0).abs() < 1e-12
2285 );
2286 assert_eq!(DriveParams { drive_max_current: 10.9, ..params() }.torque_range(100.0), (-3.8, 3.8));
2287 assert_eq!(DriveParams { limit: false, ..small.clone() }.torque_range(100.0), (-2.25, 2.25));
2288 assert_eq!(small.torque_curve(100.0), (-3.8, 3.8));
2290 }
2291
2292 #[test]
2293 fn velocity_feedforward_is_interpolated_between_profile_cycles() {
2294 let mut p = params();
2295 p.velocity_ff = 1.0;
2296 let mut d = Drive { vel_set: 10.0, acc_set: 1000.0, ..Drive::default() };
2297 d.velocity_loop(&p, 0.0);
2298 assert!((d.speed_command - 10.0).abs() < 1e-12);
2299 d.since_setpoint += 125e-6;
2301 d.velocity_loop(&p, 0.0);
2302 assert!((d.speed_command - (10.0 + 1000.0 * 125e-6)).abs() < 1e-12);
2303 }
2304
2305 #[test]
2306 fn current_follows_its_setpoint_with_the_tuned_time_constant() {
2307 let p = params();
2308 let mut d = Drive { torque_command: 0.45, ..Drive::default() };
2309 let mut peak = 0f64;
2312 for step in 1..=200 {
2313 d.current_loop(&p, 0.0);
2314 peak = peak.max(d.current);
2315 if step == 4 {
2316 assert!((d.current - 0.632).abs() < 0.05, "{} A after one time constant", d.current);
2317 }
2318 }
2319 assert!((d.current - 1.0).abs() < 1e-4 && peak < 1.01, "ends at {} A, peak {peak} A", d.current);
2320 assert!((d.torque - 0.45).abs() < 1e-4 && (d.voltage - 4.0).abs() < 1e-3);
2321 }
2322
2323 #[test]
2324 fn computation_delay_makes_the_current_loop_unstable_at_the_calculated_limit() {
2325 let largest_current = |cycles: usize| {
2329 let p = DriveParams { current_delay: cycles, max_voltage: f64::INFINITY, ..params() };
2330 let mut d = Drive { torque_command: 0.45, ..Drive::default() };
2331 let mut late = 0f64;
2332 for step in 0..4000 {
2333 d.current_loop(&p, 0.0);
2334 if step >= 3000 {
2335 late = late.max((d.current - 1.0).abs());
2336 }
2337 }
2338 late
2339 };
2340 assert!(largest_current(1) < 1e-6 && largest_current(4) < 1e-3, "{} A off with 4 cycles", largest_current(4));
2341 assert!(largest_current(7) > 10.0, "only {} A off with 7 cycles", largest_current(7));
2342 }
2343
2344 #[test]
2345 fn the_torque_setpoint_acts_one_velocity_cycle_late() {
2346 let p = DriveParams { velocity_delay: 1, ..params() };
2347 let mut d = Drive { position_part: 10.0, ..Drive::default() };
2348 d.velocity_loop(&p, 4.0);
2349 let first = d.torque_command;
2350 d.velocity_loop(&p, 4.0);
2351 assert!(
2353 (first - 0.08 * 6.0).abs() < 1e-12 && (d.torque_command - 0.08 * 6.0).abs() < 1e-12,
2354 "{first}, {}",
2355 d.torque_command
2356 );
2357 d.velocity_loop(&p, 4.0);
2358 assert!((d.torque_command - (0.08 * 6.0 + 8.0 * 6.0 * 125e-6)).abs() < 1e-12);
2359 }
2360
2361 #[test]
2362 fn the_winding_warms_to_the_rated_rise_at_the_rated_current() {
2363 let p = DriveParams { heating: true, thermal_time_constant: 0.5, max_voltage: f64::INFINITY, ..params() };
2365 let run = |current: f64, seconds: f64| {
2366 let mut d = Drive { torque_command: p.kt * current, ..Drive::default() };
2367 for _ in 0..(seconds / p.current_cycle) as usize {
2368 d.current_loop(&p, 0.0);
2369 }
2370 d
2371 };
2372 let (early, late) = (run(p.rated_current, 0.5), run(p.rated_current, 6.0));
2375 assert!((early.temperature_rise - 51.3).abs() < 0.5, "{} K after one time constant", early.temperature_rise);
2376 assert!((late.temperature_rise - 100.0).abs() < 0.2, "{} K in the end", late.temperature_rise);
2377 assert!((late.voltage / (4.0 * p.rated_current) - 1.39).abs() < 0.005, "{} V", late.voltage);
2379 let half = run(0.5 * p.rated_current, 6.0);
2382 assert!(
2383 (half.temperature_rise - 19.34).abs() < 0.05
2384 && (p.settled_rise(0.5 * p.rated_current, 0.0) - 19.34).abs() < 0.01,
2385 "{} K",
2386 half.temperature_rise
2387 );
2388 let cold = DriveParams { heating: false, ..p.clone() };
2390 let mut d = Drive { torque_command: 1.27, ..Drive::default() };
2391 for _ in 0..8000 {
2392 d.current_loop(&cold, 0.0);
2393 }
2394 assert_eq!(d.temperature_rise, 0.0);
2395 }
2396
2397 #[test]
2398 fn saturation_takes_torque_at_high_current_only() {
2399 let p = DriveParams { saturation: 1.0 - 0.40 / 0.45, ..params() };
2400 assert!((p.torque_of(9.5) - 0.40 * 9.5).abs() < 1e-12 && (p.torque_of(-9.5) + 0.40 * 9.5).abs() < 1e-12);
2401 assert!((p.torque_of(0.95) / (0.45 * 0.95) - (1.0 - (1.0 - 0.40 / 0.45) / 100.0)).abs() < 1e-12);
2403 assert_eq!(params().torque_of(9.5), 0.45 * 9.5);
2404 }
2405
2406 fn saturating() -> DriveParams {
2408 let kt = 6.0 / 4.7;
2409 DriveParams {
2410 kt,
2411 ke: kt,
2412 saturation: 1.0 - 18.0 / 15.1 / kt,
2413 max_current: 15.1,
2414 max_voltage: f64::INFINITY,
2415 peak_torque: 18.0,
2416 ..params()
2417 }
2418 }
2419
2420 #[test]
2423 fn the_maximum_torque_takes_the_maximum_current() {
2424 let p = saturating();
2425 let mut d = Drive { torque_command: 18.0, ..Drive::default() };
2426 for _ in 0..2000 {
2427 d.current_loop(&p, 0.0);
2428 }
2429 assert!((d.current - 15.1).abs() < 1e-6 && (d.torque - 18.0).abs() < 1e-6, "{} A, {} N m", d.current, d.torque);
2430 assert!((p.current_for(30.0) - 15.1).abs() < 1e-12 && (p.current_for(-30.0) + 15.1).abs() < 1e-12);
2432 assert!((Drive::at_rest(&p, 0.0, -18.0, 0.0).current + 15.1).abs() < 1e-9);
2434 for current in [0.5, 4.7, 10.0, -12.0, 15.1] {
2435 assert!((p.current_for(p.torque_of(current)) - current).abs() < 1e-9, "{current} A");
2436 }
2437 let steep = DriveParams { saturation: 0.4, ..p.clone() };
2440 assert!((steep.current_for(1e3) - 15.1 / 1.2f64.sqrt()).abs() < 1e-12);
2441 assert!(steep.torque_of(steep.current_for(1e3)) >= steep.torque_of(15.1));
2442 }
2443
2444 #[test]
2449 fn under_saturation_the_electrical_power_is_copper_loss_plus_shaft_power() {
2450 let p = saturating();
2451 let mut d = Drive { torque_command: 18.0, ..Drive::default() };
2452 for _ in 0..4000 {
2453 d.current_loop(&p, 100.0);
2454 }
2455 assert!((d.voltage - (60.4 + 1800.0 / 15.1)).abs() < 1e-3, "{} V", d.voltage);
2456 assert!(
2457 (d.power - (4.0 * 15.1 * 15.1 + d.torque * 100.0)).abs() < 1e-2 && (d.torque - 18.0).abs() < 1e-6,
2458 "{} W, {} N m",
2459 d.power,
2460 d.torque
2461 );
2462 }
2463
2464 #[test]
2465 fn back_emf_costs_voltage_and_the_bus_limits_torque_at_speed() {
2466 let p = params();
2467 let mut d = Drive { torque_command: 0.45, ..Drive::default() };
2469 for _ in 0..2000 {
2470 d.current_loop(&p, 100.0);
2471 }
2472 assert!((d.current - 1.0).abs() < 1e-4 && (d.voltage - 49.0).abs() < 1e-3, "{} A, {} V", d.current, d.voltage);
2473 let mut d = Drive { torque_command: 3.8, ..Drive::default() };
2475 for _ in 0..2000 {
2476 d.current_loop(&p, 400.0);
2477 }
2478 assert!((d.current - 2.5).abs() < 1e-6 && d.voltage == 190.0, "{} A, {} V", d.current, d.voltage);
2479 d.torque_command = 0.0;
2481 for _ in 0..32 {
2482 d.current_loop(&p, 400.0);
2483 }
2484 assert!(d.current.abs() < 0.2, "{} A", d.current);
2485 let free = DriveParams { ke: 0.0, max_voltage: f64::INFINITY, ..params() };
2487 let mut d = Drive { torque_command: 3.8, ..Drive::default() };
2488 for _ in 0..2000 {
2489 d.current_loop(&free, 400.0);
2490 }
2491 assert!((d.torque - 3.8).abs() < 1e-6);
2492 }
2493
2494 #[test]
2495 fn encoder_resolution_quantises_position_and_speed() {
2496 let mut p = params();
2497 (p.encoder_step, p.speed_from_positions) = (TAU / 4096.0, true);
2498 let mut d = Drive::at_rest(&p, 0.0, 0.0, 0.0);
2499 d.pos_set = 0.4 * p.encoder_step;
2500 d.read_encoder(&p, 0.0);
2501 d.position_loop(&p, d.encoder(), 1e-3);
2502 assert_eq!(d.following_error, 0.4 * p.encoder_step);
2503 d.read_encoder(&p, 0.3 * p.encoder_step);
2504 d.position_loop(&p, d.encoder(), 1e-3);
2505 assert_eq!(d.following_error, 0.4 * p.encoder_step, "a move below one count is invisible");
2506 d.read_encoder(&p, 1.2 * p.encoder_step);
2508 d.velocity_loop(&p, 123.0);
2509 assert!((d.speed - p.encoder_step / 125e-6).abs() < 1e-9);
2510 }
2511
2512 #[test]
2513 fn notch_removes_its_centre_frequency_and_passes_the_rest() {
2514 let gain_at = |frequency: f64| {
2515 let [b0, b1, b2, a1, a2] = notch_coefficients(60.0, 20.0, 125e-6);
2516 let (mut x, mut y, mut peak) = ([0.0; 2], [0.0; 2], 0f64);
2517 for n in 0..80_000 {
2518 let input = (TAU * frequency * n as f64 * 125e-6).sin();
2519 let out = b0 * input + b1 * x[0] + b2 * x[1] - a1 * y[0] - a2 * y[1];
2520 (x, y) = ([input, x[0]], [out, y[0]]);
2521 if n > 60_000 {
2522 peak = peak.max(out.abs());
2523 }
2524 }
2525 peak
2526 };
2527 assert!(gain_at(60.0) < 0.01, "{}", gain_at(60.0));
2528 assert!((gain_at(5.0) - 1.0).abs() < 0.02 && (gain_at(600.0) - 1.0).abs() < 0.02);
2529 for edge in [50.83, 70.83] {
2532 assert!((gain_at(edge) - std::f64::consts::FRAC_1_SQRT_2).abs() < 0.01, "{edge} Hz: {}", gain_at(edge));
2533 }
2534 }
2535
2536 #[test]
2537 fn a_drive_starts_holding_its_load() {
2538 let mut p = params();
2539 p.torque_ff = 1.0;
2540 let mut d = Drive::at_rest(&p, 2.0, 0.14, 0.137);
2541 d.read_encoder(&p, 2.0);
2542 d.position_loop(&p, d.encoder(), 1e-3);
2543 d.velocity_loop(&p, 0.0);
2544 d.current_loop(&p, 0.0);
2545 assert!((d.torque - 0.14).abs() < 1e-12 && (d.torque_command - 0.14).abs() < 1e-12);
2546 }
2547
2548 #[test]
2555 fn a_dc_link_ten_percent_low_lowers_the_velocity_loops_torque_limit_at_speed() {
2556 let bus = 190.0 / WINDING_PER_DC_LINK;
2557 let limit = |p: &DriveParams, dc: f64, speed: f64| {
2558 let mut d = Drive { dc_voltage: dc, integral: 100.0, ..Drive::default() };
2560 d.velocity_loop(p, speed);
2561 d.torque_command
2562 };
2563 let p = DriveParams { dc_link: true, bus_voltage: bus, ..weakening() };
2564 let (full, low) = (limit(&p, bus, 500.0), limit(&p, 0.9 * bus, 500.0));
2565 assert!((full - 3.4451).abs() < 1e-3 && (low - 3.16459).abs() < 1e-3, "{full} N m, {low} N m");
2566 let fade = DriveParams { field_weakening: None, ..p.clone() };
2567 let (full, low) = (limit(&fade, bus, 330.0), limit(&fade, 0.9 * bus, 330.0));
2568 assert!((full - 3.22642).abs() < 1e-4 && (low - 1.91195).abs() < 1e-4, "{full} N m, {low} N m");
2569 let nominal = DriveParams { dc_link: false, ..p.clone() };
2571 assert!((limit(&nominal, 0.9 * bus, 500.0) - 3.4451).abs() < 1e-3);
2572 }
2573
2574 fn weakening() -> DriveParams {
2577 DriveParams {
2578 resistance: 1e-6,
2579 field_weakening: Some(FieldWeakening { pole_pairs: 4.0, d_inductance: 0.010 }),
2580 ..params()
2581 }
2582 }
2583
2584 #[test]
2591 fn field_weakening_gives_the_hand_calculated_torque_above_the_voltage_limit() {
2592 let p = weakening();
2593 assert_eq!(DriveParams { field_weakening: None, ..p.clone() }.torque_curve(500.0).1, 0.0);
2594 let (low, high) = p.torque_curve(500.0);
2595 assert!((high - 3.4451).abs() < 1e-3, "{high} N m motoring at 500 rad/s");
2596 let back = p.torque_curve(-500.0);
2599 assert!((low + high).abs() < 1e-6 && back == (-high, -low), "{low} N m braking, {back:?} backwards");
2600 let resistive = DriveParams { resistance: 4.0, ..p.clone() };
2601 let (braking, motoring) = resistive.torque_curve(500.0);
2602 assert!(-braking > motoring, "{braking} N m braking, {motoring} N m motoring");
2603 assert_eq!(p.torque_curve(100.0), (-3.8, 3.8));
2605 assert!((p.d_current_for(7.6557, 500.0, 190.0, 9.5, p.resistance, 1.0) + 5.625).abs() < 1e-3);
2606 assert_eq!(p.d_current_for(1.0, 100.0, 190.0, 9.5, p.resistance, 1.0), 0.0, "45 V and 4 V reach");
2607
2608 let mut d = Drive { torque_command: high, ..Drive::default() };
2609 for _ in 0..4000 {
2610 d.current_loop(&p, 500.0);
2611 }
2612 let u_d = -20.0 * d.current;
2613 assert!(
2614 (d.current - 7.6557).abs() < 1e-3
2615 && (d.d_current + 5.625).abs() < 1e-3
2616 && (d.voltage.hypot(u_d) - 190.0).abs() < 0.1
2617 && (d.torque - high).abs() < 1e-3,
2618 "{} A, {} A, {} V, {} V",
2619 d.current,
2620 d.d_current,
2621 d.voltage,
2622 u_d
2623 );
2624 assert!((d.phase_current() - 9.5).abs() < 1e-3);
2626 assert!((d.power - d.copper_loss - d.shaft_power).abs() < 1e-3 * d.shaft_power, "{} W", d.power);
2628 }
2629
2630 #[test]
2638 fn the_winding_reactance_limits_the_torque_without_field_weakening() {
2639 let p = DriveParams { pole_pairs: 4.0, ..params() };
2640 let at = |speed: f64| p.voltage_limited_torque(speed, 190.0 / WINDING_PER_DC_LINK).1;
2641 for (speed, torque) in [(300.0, 3.474), (330.0, 2.709), (360.0, 1.956)] {
2642 assert!((at(speed) - torque).abs() < 1e-3, "{speed} rad/s: {} N m", at(speed));
2643 }
2644 assert!((params().voltage_limited_torque(300.0, 190.0 / WINDING_PER_DC_LINK).1 - 4.275).abs() < 1e-9);
2645 let mut d = Drive { torque_command: 3.474, ..Drive::default() };
2646 for _ in 0..4000 {
2647 d.current_loop(&p, 300.0);
2648 }
2649 assert!(
2650 (d.current - 7.7206).abs() < 0.05 && (d.voltage.hypot(d.d_voltage) - 190.0).abs() < 0.2,
2651 "{} A",
2652 d.current
2653 );
2654 assert!((d.d_voltage + 92.65).abs() < 0.5 && (d.phase_voltage(&p) - 89.57).abs() < 0.1, "{} V", d.d_voltage);
2655 for (speed, torque) in [(300.0, 3.474), (330.0, 2.709), (360.0, 1.956)] {
2657 let mut d = Drive { torque_command: 3.8, ..Drive::default() };
2658 for _ in 0..4000 {
2659 d.current_loop(&p, speed);
2660 }
2661 assert!((d.torque - torque).abs() < 0.01 * torque, "{speed} rad/s: {} N m", d.torque);
2662 }
2663 }
2664
2665 #[test]
2670 fn the_drives_current_limit_holds_the_phase_current_with_field_weakening() {
2671 let p = DriveParams { drive_max_current: 5.0, ..weakening() };
2672 let (_, high) = p.torque_range(500.0);
2673 assert!((high - 1.8865).abs() < 1e-3, "{high} N m");
2674 let mut d = Drive { torque_command: 2.25, ..Drive::default() };
2675 for _ in 0..4000 {
2676 d.current_loop(&p, 500.0);
2677 }
2678 assert!(d.phase_current() < 5.0 + 1e-3, "{} A", d.phase_current());
2679 }
2680
2681 #[test]
2691 fn the_current_circle_holds_the_q_reference_with_the_d_reference() {
2692 let p = DriveParams { drive_max_current: 5.0, pole_pairs: 4.0, ..weakening() };
2693 for (speed, d_ref, q_ref) in [(0.0, 0.0, 5.0), (500.0, -2.725, 4.1922)] {
2694 let mut d = Drive {
2695 torque_command: 2.25,
2696 current: 4.7,
2697 d_current: -2.0,
2698 current_integral: -50.0,
2699 ..Drive::default()
2700 };
2701 d.current_control(&p, speed);
2702 let moved = (d.current_integral + 50.0) / (p.current_ki * p.current_cycle);
2703 let wanted = p.d_current_for(q_ref, speed, 190.0, 5.0, p.resistance, 1.0);
2704 assert!((wanted - d_ref).abs() < 1e-3, "{speed} rad/s: d setpoint {wanted} A");
2705 assert!((4.7 + moved - q_ref).abs() < 1e-3, "{speed} rad/s: q reference {} A", 4.7 + moved);
2706 }
2707 }
2708
2709 #[test]
2719 fn braking_at_the_voltage_limit_does_not_run_away() {
2720 let fw = FieldWeakening { pole_pairs: 4.0, d_inductance: 0.010 };
2721 for saturation in [0.0, 1.0 - 0.40 / 0.45] {
2722 let p = DriveParams { pole_pairs: 4.0, field_weakening: Some(fw), saturation, ..params() };
2723 for speed in [380.0, 400.0, 420.0, 450.0] {
2724 let (low, high) = p.torque_curve(speed);
2725 for command in [-3.8, 3.8, low, high] {
2726 let mut d = Drive { torque_command: command, ..Drive::default() };
2727 let (mut torque, mut current, mut voltage) = (0.0f64, 0.0f64, 0.0f64);
2728 for _ in 0..8000 {
2729 d.current_loop(&p, speed);
2730 torque = torque.max(d.torque.abs());
2731 current = current.max(d.phase_current());
2732 voltage = voltage.max(d.voltage.hypot(d.d_voltage));
2733 }
2734 let settled = command.clamp(low, high);
2736 assert!(
2737 torque <= 3.8 * 1.001
2738 && current <= 9.5 + 1e-6
2739 && voltage <= 190.0 + 1e-9
2740 && (d.torque - settled).abs() < 1e-3 * settled.abs(),
2741 "{saturation} {speed} rad/s {command} N m: {torque} N m, {current} A, {voltage} V, {} N m",
2742 d.torque
2743 );
2744 }
2745 }
2746 }
2747 }
2748
2749 #[test]
2752 fn the_magnet_flux_is_one_at_the_rated_state_with_thermal_nodes() {
2753 let p = DriveParams {
2754 heating: true,
2755 magnet_coefficient: -1e-3,
2756 thermal_nodes: Some(ThermalNodes { winding_share: 0.25, winding_time_constant: 60.0 }),
2757 ..params()
2758 };
2759 let d = Drive { temperature_rise: 100.0, housing_rise: 75.0, ..Drive::default() };
2760 assert!((d.flux(&p) - 1.0).abs() < 1e-12, "{}", d.flux(&p));
2761 let one_node = DriveParams { thermal_nodes: None, ..p };
2762 assert!((d.flux(&one_node) - 1.0).abs() < 1e-12);
2763 }
2764
2765 #[test]
2780 fn the_d_q_model_holds_the_published_points_of_a_1fk7() {
2781 let kt = 3.0 / 2.2;
2782 let fw = FieldWeakening { pole_pairs: 4.0, d_inductance: 3.0 * 0.035 };
2783 let p = DriveParams {
2784 kt,
2785 ke: kt,
2786 resistance: 3.0 * 4.67,
2787 inductance: 3.0 * 0.035,
2788 max_voltage: WINDING_PER_DC_LINK * 600.0,
2789 max_current: 7.6,
2790 peak_torque: 10.5,
2791 rated_speed: 314.16,
2792 no_load_speed: WINDING_PER_DC_LINK * 600.0 / kt,
2793 field_weakening: Some(fw),
2794 ..params()
2795 };
2796 let rated = p.torque_of(2.0);
2797 assert!((rated / 2.6 - 1.0).abs() < 0.06 && p.torque_curve(314.16).1 >= rated, "{rated} N m");
2798 assert_eq!(p.d_current_for(2.0, 314.16, p.max_voltage, 7.6, p.resistance, 1.0), 0.0);
2799 let old = DriveParams { field_weakening: None, ..p.clone() };
2800 assert!(old.torque_curve(670.2).1 == 0.0 && p.torque_curve(670.2).1 > rated, "{:?}", p.torque_curve(670.2));
2801 let w = 4.0 * 942.5;
2804 let q_at = |d: f64| {
2805 let (mut lo, mut hi) = (0.0, (7.6f64 * 7.6 - d * d).max(0.0).sqrt());
2806 for _ in 0..40 {
2807 let mid = 0.5 * (lo + hi);
2808 let uq = p.resistance * mid + kt * 942.5 + w * fw.d_inductance * d;
2809 let ud = p.resistance * d - w * p.inductance * mid;
2810 if uq.hypot(ud) <= p.max_voltage { lo = mid } else { hi = mid }
2811 }
2812 lo
2813 };
2814 let best = (0..=7600).map(|k| -(k as f64) * 1e-3).max_by(|a, b| q_at(*a).total_cmp(&q_at(*b))).unwrap();
2815 assert!((best + 3.247).abs() < 0.01 * 3.247, "{best} A");
2816 assert!((p.torque_curve(942.5).1 - kt * q_at(best)).abs() < 1e-3, "{:?}", p.torque_curve(942.5));
2817 assert!((2f64.sqrt() * 0.8594 * 670.2 / 820.0 - 1.0).abs() < 0.01);
2818 }
2819
2820 #[test]
2827 fn a_step_at_twice_the_rated_current_clamps_after_the_hand_calculated_time() {
2828 let trip = 9.0 - 8.0 * (-0.025f64).exp();
2829 assert!((trip - 1.19752).abs() < 1e-5);
2830 let o = Overload {
2831 rated_current: 3.0,
2832 base_current: 2.6,
2833 max_current: 9.0,
2834 time_constant: 10.0,
2835 trip,
2836 chip_share: 0.0,
2837 chip_time_constant: 1.0,
2838 };
2839 let p = DriveParams { overload: Some(o), torque_ff: 1.0, drive_max_current: 9.0, ..params() };
2840 let mut d = Drive { torque_ff: 0.45 * 6.0, ..Drive::default() };
2841 let (mut clamped, mut released, mut t) = (None, None, 0.0);
2842 while t < 10.0 {
2843 d.velocity_loop(&p, 0.0);
2844 for _ in 0..2 {
2845 d.current_loop(&p, 0.0);
2846 t += p.current_cycle;
2847 }
2848 if clamped.is_none() && d.torque_command < 0.45 * 6.0 - 1e-9 {
2849 clamped = Some(t);
2850 assert!((d.torque_command - 0.45 * 2.6).abs() < 1e-12);
2851 }
2852 if clamped.is_some() && released.is_none() && d.torque_command == 0.45 * 6.0 {
2853 released = Some(t);
2854 }
2855 }
2856 let (clamped, released) = (clamped.unwrap(), released.unwrap());
2857 assert!((clamped - 3.558).abs() < 2e-3, "clamps after {clamped} s");
2858 assert!((released - clamped - 5.842).abs() < 3e-3, "released {} s later", released - clamped);
2860 let off = DriveParams { overload: None, ..p.clone() };
2862 let mut d = Drive { torque_ff: 0.45 * 6.0, ..Drive::default() };
2863 for _ in 0..40_000 {
2864 d.velocity_loop(&off, 0.0);
2865 d.current_loop(&off, 0.0);
2866 }
2867 assert!(d.torque_command == 0.45 * 6.0 && !d.overloaded && d.overload_image == 0.0);
2868 }
2869
2870 #[test]
2875 fn the_overload_image_of_a_repeated_cycle_peaks_at_the_hand_calculated_level() {
2876 let o = Overload {
2877 rated_current: 1.0,
2878 base_current: 0.85,
2879 max_current: 3.0,
2880 time_constant: 10.0,
2881 trip: 1.2,
2882 chip_share: 0.0,
2883 chip_time_constant: 1.0,
2884 };
2885 let pass = |current: &dyn Fn(f64) -> f64| {
2886 let (mut x, mut samples) = ([0.0; 2], Vec::new());
2887 for k in 1..=1000 {
2888 x = o.nodes_after(x, current(k as f64 * 1e-3 - 0.5e-3), 1e-3);
2889 samples.push((k as f64 * 1e-3, x));
2890 }
2891 let end = samples.pop().unwrap();
2892 crate::analysis::repeating_peak(&o, [0.0; 2], &samples, end)
2893 };
2894 assert!((pass(&|_| 1.5) - 2.25).abs() < 1e-9);
2895 assert!((pass(&|t| if t < 0.5 { 2.0 } else { 0.0 }) - 2.04999).abs() < 1e-4);
2896 }
2897
2898 #[test]
2906 fn three_thermal_nodes_settle_at_the_sum_of_the_resistances_and_step_as_by_hand() {
2907 let p = DriveParams {
2908 heating: true,
2909 thermal_time_constant: 1800.0,
2910 current_cycle: 1e-3,
2911 thermal_nodes: Some(ThermalNodes { winding_share: 0.25, winding_time_constant: 60.0 }),
2912 ..params()
2913 };
2914 let rated_loss = p.resistance_at(p.rated_rise) * p.rated_current * p.rated_current;
2915 let mut d = Drive { copper_loss: rated_loss, ..Drive::default() };
2916 let by_hand = |t: f64| 100.0 - 81.5696 * (-7.362_044e-4 * t).exp() - 18.4304 * (-1.934_927e-2 * t).exp();
2917 for step in 1..=20_000_000 {
2919 d.warm(&p);
2920 let t = step as f64 * 1e-3;
2921 if step == 60_000 || step == 1_800_000 {
2922 assert!((d.temperature_rise - by_hand(t)).abs() < 1e-3, "{} K at {t} s", d.temperature_rise);
2923 }
2924 }
2925 assert!((by_hand(60.0) - 16.18).abs() < 0.01 && (by_hand(1800.0) - 78.32).abs() < 0.01);
2926 assert!(
2927 (d.temperature_rise - 100.0).abs() < 1e-3 && (d.housing_rise - 75.0).abs() < 1e-3,
2928 "{} K, {} K",
2929 d.temperature_rise,
2930 d.housing_rise
2931 );
2932 assert!((p.settled_rise(p.rated_current, 0.0) - 100.0).abs() < 1e-9);
2934 let warm = DriveParams { start_rise: 40.0, ..p.clone() };
2936 assert_eq!(Drive::at_rest(&warm, 0.0, 0.0, 0.0).housing_rise, 30.0);
2937 }
2938
2939 #[test]
2948 fn the_voltage_limit_gives_the_hand_calculated_torque_from_r_l_and_the_dc_link() {
2949 let kt: f64 = 6.0 / 4.7;
2950 let inductance = kt * kt / (2.0 * 4.0 * 13.0);
2951 assert!((inductance - 0.015670).abs() < 1e-6);
2952 let p = DriveParams {
2953 kt,
2954 ke: kt,
2955 resistance: 2.0,
2956 inductance,
2957 max_voltage: WINDING_PER_DC_LINK * 540.0,
2958 max_current: 15.1,
2959 peak_torque: 18.0,
2960 rated_speed: 314.159,
2961 no_load_speed: WINDING_PER_DC_LINK * 540.0 / kt,
2962 field_weakening: Some(FieldWeakening { pole_pairs: 4.0, d_inductance: inductance }),
2963 ..params()
2964 };
2965 let (at_600, at_500) = (p.torque_curve(600.0).1, p.torque_curve(500.0).1);
2966 assert!((at_600 - 15.614).abs() < 2e-3 && (at_500 - 17.818).abs() < 2e-3, "{at_600} N m, {at_500} N m");
2967 let fade = DriveParams { field_weakening: None, ..p.clone() };
2968 assert!(fade.torque_curve(600.0).1 == 0.0 && (fade.torque_curve(500.0).1 - 1.595).abs() < 1e-3);
2969 let d = p.d_current_for(12.2309, 600.0, p.max_voltage, 15.1, p.resistance, 1.0);
2971 assert!((d + 8.855).abs() < 2e-3, "{d} A");
2972 }
2973
2974 #[test]
2982 fn the_d_current_follows_its_setpoint_with_the_current_loop_time_constant() {
2983 let p = weakening();
2984 let mut d = Drive { torque_command: p.torque_curve(500.0).1, ..Drive::default() };
2985 d.current_control(&p, 500.0);
2986 assert!((d.d_current + 1.1875).abs() < 1e-4 && (d.d_voltage + 190.0).abs() < 1e-9, "{} A", d.d_current);
2987 for _ in 1..4 {
2988 d.current_control(&p, 500.0);
2989 }
2990 assert!((d.d_current + 3.5289).abs() < 2e-4, "{} A", d.d_current);
2991 for _ in 4..40 {
2992 d.current_control(&p, 500.0);
2993 }
2994 assert!((d.d_current + 5.625 * (1.0 - (-10f64).exp())).abs() < 2e-3, "{} A", d.d_current);
2995 }
2996
2997 #[test]
3000 fn the_d_current_takes_the_warm_resistance() {
3001 let p = DriveParams { resistance: 4.0, heating: true, ..weakening() };
3002 let (cold, warm) = (
3003 p.d_current_for(5.0, 500.0, 190.0, 9.5, 4.0, 1.0),
3004 p.d_current_for(5.0, 500.0, 190.0, 9.5, p.resistance_at(100.0), 1.0),
3005 );
3006 assert!(warm < cold - 0.01, "{warm} A warm, {cold} A cold");
3007 let mut d = Drive { torque_command: 0.45 * 5.0, temperature_rise: 100.0, ..Drive::default() };
3008 for _ in 0..400 {
3009 d.current_control(&p, 500.0);
3010 }
3011 assert!((d.d_current - warm).abs() < 1e-6, "{} A against {warm} A", d.d_current);
3012 }
3013
3014 #[test]
3019 fn iron_loss_at_a_speed_is_the_hand_calculated_share_of_the_rated_loss() {
3020 let p = DriveParams {
3021 resistance: 4.0,
3022 rated_current: 2.5,
3023 stall_current: 3.0,
3024 iron_loss_rated: 4.0 * (1.0 + COPPER * 100.0) * (9.0 - 6.25),
3025 heating: true,
3026 current_cycle: 1e-3,
3027 thermal_time_constant: 100.0,
3028 ..params()
3029 };
3030 assert!((p.iron_loss_rated - 15.29).abs() < 1e-9);
3031 assert!((p.iron_loss_at(p.rated_speed / 4.0) - 1.911_25).abs() < 1e-9 && p.iron_loss_at(0.0) == 0.0);
3032 let at_rated = p.settled_rise(2.5, p.iron_loss_rated);
3033 assert!((at_rated - 100.0).abs() < 1e-9 && (p.settled_rise(3.0, 0.0) - 100.0).abs() < 1e-9, "{at_rated} K");
3034 let mut d = Drive::default();
3036 for _ in 0..2_000_000 {
3037 d.copper_loss = p.resistance_at(d.temperature_rise) * 2.5 * 2.5;
3038 d.iron_loss = p.iron_loss_at(p.rated_speed);
3039 d.warm(&p);
3040 }
3041 assert!((d.temperature_rise - 100.0).abs() < 1e-3, "{} K", d.temperature_rise);
3042 let off = DriveParams { iron_loss_rated: 0.0, stall_current: 2.5, ..p.clone() };
3044 assert!((off.settled_rise(2.5, 0.0) - 100.0).abs() < 1e-9);
3045 }
3046
3047 #[test]
3050 fn cold_magnets_give_the_hand_calculated_torque_per_amp() {
3051 let p = DriveParams { heating: true, magnet_coefficient: -0.0012, ..params() };
3052 let cold = Drive::default();
3053 assert!((cold.flux(&p) - 1.12).abs() < 1e-12);
3054 assert!((p.torque_with(2.0, 0.0, cold.flux(&p)) - 1.12 * 0.9).abs() < 1e-12);
3055 assert_eq!(Drive { temperature_rise: 100.0, ..Drive::default() }.flux(&p), 1.0);
3056 assert_eq!(cold.flux(&DriveParams { magnet_coefficient: 0.0, ..p.clone() }), 1.0);
3057 }
3058
3059 #[test]
3065 fn the_two_node_overload_image_trips_after_the_hand_calculated_time() {
3066 let mut o = Overload {
3067 rated_current: 3.0,
3068 base_current: 2.6,
3069 max_current: 9.0,
3070 time_constant: 10.0,
3071 trip: 0.0,
3072 chip_share: 0.3,
3073 chip_time_constant: 1.0,
3074 };
3075 o.trip = 9.0 - 8.0 * o.decay(0.25).iter().sum::<f64>();
3076 assert!((o.trip - 1.66914).abs() < 1e-5, "{}", o.trip);
3077 assert!((o.trip_time(6.0) - 0.8203).abs() < 1e-4, "{} s", o.trip_time(6.0));
3078 let one = Overload { chip_share: 0.0, trip: 9.0 - 8.0 * (-0.025f64).exp(), ..o };
3079 assert!((one.trip_time(6.0) - 0.6811).abs() < 1e-4 && o.trip_time(2.9) == f64::INFINITY);
3080 let p = DriveParams { overload: Some(o), torque_ff: 1.0, drive_max_current: 9.0, ..params() };
3082 let mut d = Drive { torque_ff: 0.45 * 6.0, overload_image: 1.0, overload_chip: 0.3, ..Drive::default() };
3083 let mut t = 0.0;
3084 while d.torque_command != 0.45 * 2.6 && t < 2.0 {
3085 d.velocity_loop(&p, 0.0);
3086 for _ in 0..2 {
3087 d.current_loop(&p, 0.0);
3088 t += p.current_cycle;
3089 }
3090 }
3091 assert!((t - 0.8203).abs() < 2e-3, "clamps after {t} s");
3093 }
3094
3095 #[test]
3099 fn the_braking_resistor_warms_by_the_hand_calculated_rise_in_a_pulse() {
3100 let r = ResistorHeating { continuous_power: 1500.0, time_constant: 60.0, rated_rise: 200.0 };
3101 let p = DriveParams { dc_link: true, resistor_heating: Some(r), ..params() };
3102 let mut d = Drive::default();
3103 let pulse = |d: &mut Drive, power: f64, seconds: f64| {
3104 for _ in 0..(seconds / p.current_cycle).round() as usize {
3105 let step = DcLinkStep { voltage: 190.0, resistor: power, drawn: 0.0, mains: 0.0, line_loss: 0.0 };
3106 d.set_dc_link(&p, step);
3107 }
3108 };
3109 pulse(&mut d, 100e3, 1.0);
3110 assert!((d.resistor_rise - 220.38).abs() < 0.01, "{} K", d.resistor_rise);
3111 pulse(&mut d, 0.0, 67.0);
3112 assert!((d.resistor_rise - 72.15).abs() < 0.01, "{} K", d.resistor_rise);
3113 assert!((r.rise_after(0.0, 1500.0, 1e6) - 200.0).abs() < 1e-9);
3115 }
3116
3117 #[test]
3123 fn a_back_emf_constant_apart_from_the_torque_constant_costs_voltage_and_books_the_difference() {
3124 let p = DriveParams { ke: 0.5, ..params() };
3125 let limited = p.voltage_limited_torque(340.0, 190.0 / WINDING_PER_DC_LINK);
3126 assert!((limited.1 - 2.25).abs() < 1e-9, "{limited:?}");
3127 let same = params().voltage_limited_torque(340.0, 190.0 / WINDING_PER_DC_LINK);
3128 assert!((same.1 - 4.1625).abs() < 1e-9, "{same:?}");
3129 let mut d = Drive::at_rest(&p, 0.0, 0.9, 0.0);
3130 d.current_loop(&p, 100.0);
3131 assert!((d.emf_loss - 10.0).abs() < 1e-6, "{} W", d.emf_loss);
3132 assert!((d.power - 116.0).abs() < 1e-6 && (d.power - d.copper_loss - d.shaft_power - d.emf_loss).abs() < 1e-6);
3133 let mut d = Drive::at_rest(¶ms(), 0.0, 0.9, 0.0);
3134 d.current_loop(¶ms(), 100.0);
3135 assert_eq!(d.emf_loss, 0.0);
3136 }
3137
3138 #[test]
3143 fn the_printed_s1_curve_is_read_linearly() {
3144 let c = [[0.0, 2.0], [100.0, 1.5], [300.0, 0.5]];
3145 assert_eq!(s1_interpolated(&c, 0.0), 2.0);
3146 assert!((s1_interpolated(&c, -200.0) - 1.0).abs() < 1e-12);
3147 assert_eq!(s1_interpolated(&c, 400.0), 0.5);
3148 assert_eq!(s1_interpolated(&[[50.0, 2.0], [100.0, 1.0]], 20.0), 2.0);
3149 let read = |speeds: &str, torques: &str| {
3150 s1_curve_of(
3151 &Config::parse(&format!(
3152 "format_version = 1\n[motor]\ns1_curve_speed_rad_s = {speeds}\ns1_curve_torque_nm = {torques}\n"
3153 ))
3154 .unwrap(),
3155 )
3156 };
3157 let curve = read("[0.0, 100.0, 300.0]", "[2.0, 1.5, 0.5]").unwrap();
3158 let p = DriveParams { s1_curve: curve, static_torque: 1.8, ..params() };
3159 assert!((p.s1_torque(-200.0) - 1.0).abs() < 1e-12 && p.s1_torque(0.0) == 2.0);
3160 assert!(read("[]", "[]").unwrap().is_empty());
3161 assert!(s1_curve_of(&Config::parse("format_version = 1\n").unwrap()).unwrap().is_empty());
3162 for (speeds, torques) in
3163 [("[0.0, 100.0]", "[2.0]"), ("[100.0, 50.0]", "[2.0, 1.0]"), ("[0.0, 1.0]", "[1.0, -1.0]")]
3164 {
3165 assert!(read(speeds, torques).is_err(), "{speeds} {torques}");
3166 }
3167 }
3168
3169 #[test]
3172 fn the_s1_torque_runs_from_the_static_torque_to_the_rated_one() {
3173 let p = DriveParams { static_torque: 1.8, ..params() };
3174 assert!((p.s1_torque(0.0) - 1.8).abs() < 1e-12 && (p.s1_torque(-314.0) - 1.27).abs() < 1e-12);
3175 assert!((p.s1_torque(157.0) - 1.535).abs() < 1e-12);
3176 assert_eq!(params().s1_torque(0.0), 1.27);
3177 }
3178
3179 #[test]
3188 fn the_iron_loss_drags_the_shaft_and_the_budget_closes_with_it() {
3189 let p = DriveParams {
3190 resistance: 4.0,
3191 rated_current: 2.5,
3192 stall_current: 3.0,
3193 iron_loss_rated: 4.0 * (1.0 + COPPER * 100.0) * (9.0 - 6.25),
3194 iron_drag_rated: 1.125 - 1.0 - 0.025,
3195 rated_speed: 314.0,
3196 ..params()
3197 };
3198 let (heat, drag) = (p.iron_loss_rated, 31.4);
3199 assert!((p.iron_drag(314.0) - 0.1).abs() < 1e-12 && (p.iron_drag(314.0) * 314.0 - drag).abs() < 1e-9);
3200 assert!((p.iron_drag(78.5) - 0.05).abs() < 1e-12 && (p.iron_drag(78.5) * 78.5 - 3.925).abs() < 1e-9);
3201 assert_eq!((p.iron_drag(-314.0), p.iron_drag(0.0)), (-p.iron_drag(314.0), 0.0));
3202 let mut rates = [0.0; WINDING_STATES];
3203 let drive = Drive { voltage: 30.0, ..Drive::default() };
3204 let shaft = p.motor_rates(&drive, &[2.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 0.0, 314.0, &mut rates);
3205 assert!((shaft - 1.025).abs() < 1e-9, "{shaft} N m");
3206 let r = p.winding_rates(30.0, 4.0, 2.5, 314.0, 0.0, 1.0);
3208 assert!((r[1] - r[2] - p.inductance * 2.5 * r[0] - r[3] - drag).abs() < 1e-9);
3209 let mut d = Drive::at_rest(&p, 0.0, 1.125, 0.0);
3211 d.current_loop(&p, 314.0);
3212 assert!((d.power - d.copper_loss - d.shaft_power - d.emf_loss).abs() < 1e-6, "{} W", d.power);
3213 assert!((d.emf_loss - drag).abs() < 1e-3 * drag && d.iron_loss == heat, "{} W", d.emf_loss);
3214 let mut off = Drive { current: 1.0, ..Drive::default() };
3215 off.disabled_step(&p, 314.0);
3216 assert!((off.torque + 0.1).abs() < 1e-12, "{} N m", off.torque);
3217 assert!((off.shaft_power + drag).abs() < 1e-9 && (off.emf_loss - drag).abs() < 1e-9 && off.iron_loss == heat);
3218 off.disabled_step(&p, 0.0);
3219 assert_eq!((off.torque, off.shaft_power, off.emf_loss), (0.0, 0.0, 0.0));
3220 }
3221
3222 #[test]
3227 fn the_d_current_keeps_the_unsaturated_back_emf() {
3228 let p = DriveParams { saturation: 0.2, ..weakening() };
3229 let d = p.d_current_for(5.0, 500.0, 190.0, 9.5, p.resistance, 1.0);
3230 assert!((d + 3.17225).abs() < 1e-4, "{d} A");
3231 let plain = weakening().d_current_for(5.0, 500.0, 190.0, 9.5, 1e-6, 1.0);
3232 assert!((plain + 3.17225).abs() < 1e-4, "{plain} A");
3233 }
3234
3235 #[test]
3242 fn braking_above_the_back_emf_equal_to_the_voltage_solves_the_voltage_circle() {
3243 let p = DriveParams { pole_pairs: 2.0, max_current: 20.0, ..params() };
3244 let (most, forced) = (p.voltage_limited_current(450.0, 190.0, false), p.forced_braking_current(450.0, 190.0));
3245 assert!((most - 12.7267).abs() < 1e-3 && (forced - 3.9743).abs() < 1e-3, "{most} A, {forced} A");
3246 for i in [most, forced] {
3247 assert!(((202.5 - 4.0 * i).powi(2) + (9.0 * i).powi(2) - 190.0 * 190.0).abs() < 1e-6);
3248 }
3249 let none = 4.0 * 225.0 / 116.0;
3250 assert!((p.voltage_limited_current(500.0, 190.0, false) - none).abs() < 1e-9);
3251 assert!((p.forced_braking_current(500.0, 190.0) - none).abs() < 1e-9);
3252 assert_eq!(p.forced_braking_current(300.0, 190.0), 0.0);
3254 let mut d = Drive { torque_command: 0.0, ..Drive::default() };
3255 for _ in 0..4000 {
3256 d.current_loop(&p, 450.0);
3257 }
3258 assert!((d.current + forced).abs() < 0.05, "{} A against -{forced} A", d.current);
3259 }
3260
3261 #[test]
3267 fn the_linear_fade_follows_r_and_ke_at_another_voltage() {
3268 let p = params();
3269 assert_eq!(p.torque_curve_at(300.0, 190.0).1, 3.8);
3270 let low = p.torque_curve_at(300.0, 152.0).1;
3271 let by_hand = 3.8 * (151.0 / 0.45 - 300.0) / (151.0 / 0.45 - 235.5);
3272 assert!((low - by_hand).abs() < 1e-6 && (low - 1.3504).abs() < 1e-3, "{low} N m");
3273 }
3274
3275 #[test]
3280 fn overmodulation_raises_the_voltage_limit_to_the_six_step_fundamental() {
3281 let gain = 2.0 * 3f64.sqrt() / std::f64::consts::PI;
3282 let p = DriveParams { fundamental_gain: gain, ..params() };
3283 let dc = 190.0 / WINDING_PER_DC_LINK;
3284 assert!((p.dc_gain() - gain * WINDING_PER_DC_LINK).abs() < 1e-15);
3285 let by_hand = 0.45 * (190.0 * gain - 198.0) / 4.0;
3286 assert!((p.voltage_limited_torque(440.0, dc).1 - by_hand).abs() < 1e-9 && (by_hand - 1.29431).abs() < 1e-5);
3287 assert_eq!(params().voltage_limited_torque(440.0, dc).1, 0.0);
3288 }
3289}