Skip to main content

sim_components/
drive.rs

1//! Servo drive: cascaded position (P, the Kv factor), velocity (PI) and current (PI) control on the
2//! motor's own encoder, with feedforward, measurement effects and torque limits. One switch each.
3//!
4//! The current controller works on the motor winding as a resistance and an inductance with the
5//! back-EMF of the turning rotor: L di/dt = u - R i - ke w, torque = kt i, and |u| limited by the
6//! DC link. With Kp = L / T and Tn = L / R the current follows its setpoint with time constant T.
7//! The controller holds its voltage over a base step, as an inverter holds it over a PWM period; the
8//! winding current is integrated over the step together with the mechanics (`Sim::step`), so that the
9//! electrical power and the work on the shaft come from the same integration.
10//!
11//! The one winding stands for the three phases: its current is the RMS phase current and u i is the
12//! electrical power, so u is three times the RMS phase voltage. A DC link U gives a phase amplitude of
13//! U / sqrt(3), that is U / sqrt(6) RMS: the winding gets sqrt(3/2) U at most (`WINDING_PER_DC_LINK`).
14
15use 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    /// Feedforward weights; 0 when switched off.
28    pub velocity_ff: f64,
29    pub torque_ff: f64,
30    /// Motor winding: torque per current and resistance (the inductance is below).
31    pub kt: f64,
32    pub resistance: f64,
33    /// Back-EMF per speed; 0 when switched off. The torque constant unless `drive.back_emf_constant_v_s_rad` gives
34    /// another (the maker's printed voltage constant, in the one winding's scale: sqrt(3) times the line-to-line one).
35    pub ke: f64,
36    /// Highest voltage at the winding, `WINDING_PER_DC_LINK` times the DC link voltage; infinite when the
37    /// limit is switched off.
38    pub max_voltage: f64,
39    /// `drive.overmodulation`: the fundamental of the six-step (square) wave over the sinusoidal limit, else 1: 2 sqrt 3 / pi
40    /// = 1.1027 for the three-phase bridge of a servo or induction motor, 4 / pi for a stepper's H-bridges. The model then
41    /// carries the fundamental only, without the square wave's harmonics (and their loss). `dc_gain` is it times
42    /// `WINDING_PER_DC_LINK`.
43    pub fundamental_gain: f64,
44    /// Current controller gains, and its cycle (the base step).
45    pub current_kp: f64,
46    pub current_ki: f64,
47    pub current_cycle: f64,
48    pub peak_torque: f64,
49    /// What the motor can give continuously: the limit for the RMS torque of a cycle.
50    pub rated_torque: f64,
51    pub rated_speed: f64,
52    pub no_load_speed: f64,
53    /// The highest speed the motor may turn at, `drive.max_speed_rad_s` (the catalogue's mechanical or inverter limit);
54    /// the no-load speed where the config leaves it out. The time-optimal plan keeps within it (`path`), "motor-speed"
55    /// judges a cycle against it where the config gives it, and `check_limits` warns of axis limits beyond it.
56    pub max_speed: f64,
57    pub limit: bool,
58    /// Encoder step in rad; 0 for an ideal encoder.
59    pub encoder_step: f64,
60    /// The velocity loop's speed is the encoder's difference per cycle (a real encoder: `encoder_step` or
61    /// `encoder_noise` above 0), else the true speed. Its own field so that the loop measurement can take the rounding
62    /// and the noise away and keep the difference (`Controller::unrounded_encoders`).
63    pub speed_from_positions: bool,
64    /// Low-pass gains per velocity cycle; 1 when the filter is off.
65    pub velocity_filter: f64,
66    pub torque_filter: f64,
67    pub notch: Option<[f64; 5]>,
68    pub velocity_cycle: f64,
69    /// Cycles between computing a value and it acting: of the current loop for the voltage, of the
70    /// velocity loop for the torque setpoint. 0 when the delay is switched off.
71    pub current_delay: usize,
72    pub velocity_delay: usize,
73    /// Winding inductance, for the winding's time constant once its resistance changes with temperature.
74    pub inductance: f64,
75    /// Pole pairs `motor.pole_pairs`, where the config has them (0 where it has none): the electrical speed w L i of the
76    /// servo winding's reactance takes the q axis's voltage (`current_control`, `voltage_limited_current`).
77    pub pole_pairs: f64,
78    /// Heating of the winding: whether it is on, the temperature rise at the rated current, the rated
79    /// current, the thermal time constant and the rise the simulation starts with.
80    pub heating: bool,
81    pub rated_rise: f64,
82    /// The housing's highest rise, K (`ratings.housing_max_rise_k`; absent: `rated_rise`), what the utilisation chart holds
83    /// its rise against.
84    pub housing_max_rise: f64,
85    pub rated_current: f64,
86    pub thermal_time_constant: f64,
87    pub start_rise: f64,
88    /// Saturation: the share of the torque constant lost at the maximum current; 0 when switched off.
89    pub saturation: f64,
90    pub max_current: f64,
91    /// effects.drive_current_limit: the drive's maximum output current, `ratings.drive_max_current_a`, A. The torque
92    /// setpoint is held to the torque of this current (`torque_range`), as the drive holds its current setpoint.
93    /// Infinite with the effect off or without the rating.
94    pub drive_max_current: f64,
95    /// DC link with a braking chopper: whether it is simulated, the voltage the rectifier holds, the
96    /// capacitance, the voltage at which the chopper switches the braking resistor in, the most the
97    /// resistor takes, and the voltage at which the drive trips.
98    pub dc_link: bool,
99    /// The drives of the machine share one DC link (`shared_dc_link`); only with `dc_link`.
100    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    /// Time constant R C with which a disabled drive's DC link discharges through its bleeder and the drive's own
107    /// consumption, down to the bus level the rectifier holds.
108    pub discharge_time_constant: f64,
109    /// Regenerative supply (`regenerative_supply`, only with `dc_link`): above the bus level the line module feeds
110    /// the DC link's energy back into the mains, up to `line_max_power`, of which `line_efficiency` arrives there.
111    pub regenerative: bool,
112    pub line_max_power: f64,
113    pub line_efficiency: f64,
114    /// Sensor noise, as standard deviations: on the measured position in rad and on the measured current.
115    /// 0 when switched off.
116    pub encoder_noise: f64,
117    pub current_noise: f64,
118    pub noise_seed: u64,
119    /// effects.field_weakening: the winding as the q axis of a d-q model, with a d current (`FieldWeakening`).
120    pub field_weakening: Option<FieldWeakening>,
121    /// effects.drive_overload: the drive's thermal image, which lowers its current limit (`Overload`).
122    pub overload: Option<Overload>,
123    /// effects.motor_thermal_nodes: winding and housing as two heat capacities (`ThermalNodes`); without it one.
124    pub thermal_nodes: Option<ThermalNodes>,
125    /// effects.iron_loss: hysteresis and eddy-current loss in the stator iron at the rated speed, W (`iron_loss_at`), and
126    /// the stall current `motor.stall_current_a`, at which the copper loss alone brings the winding to its rated rise.
127    /// The iron loss is what the copper loss at the rated speed leaves of that, R (I_0^2 - I_N^2): Siemens' rated and
128    /// static data both hold for the rated rise. 0 and the rated current with the effect off. This is the speed losses'
129    /// heat as the winding feels it, in copper-loss watts (`iron_heating`), not the power they take from the shaft
130    /// (`iron_drag_rated`): on the 144 1FK7/1FT7 rows with a printed resistance the printed torque gap (k_t I_N - M_N)
131    /// times the rated speed is a median 2.9 times it, and the printed efficiency's losses beyond copper side with the gap
132    /// (median 0.75 of it, 2.3 times this): iron and bearings heat the winding less than its own copper does.
133    pub iron_loss_rated: f64,
134    /// effects.iron_loss, a servo: the drag torque of the speed losses at the rated speed, N m (`iron_drag`): what the
135    /// printed rated point leaves of the torque constant times the rated current, k_t I_N (with saturation) - M_N, less
136    /// the shaft friction the model has of its own there (`motor.friction_*` with effects.motor_friction), at least 0;
137    /// so the shaft gives the printed rated torque at the rated current and speed. 0 with the effect off.
138    pub iron_drag_rated: f64,
139    pub stall_current: f64,
140    /// The static torque k_t I_0 of the S1 curve, from `motor.stall_current_a` whether or not effects.iron_loss is on; 0
141    /// where the config has no stall current (`s1_torque`).
142    pub static_torque: f64,
143    /// The S1 curve the config prints (`motor.s1_curve_speed_rad_s`, `motor.s1_curve_torque_nm`) as (speed, torque) points,
144    /// speeds rising; empty where it has none (`s1_torque` then takes the straight line).
145    pub s1_curve: Vec<[f64; 2]>,
146    /// effects.magnet_temperature: the magnets' flux per kelvin, `motor.magnet_temperature_coefficient_1_k` (negative); the
147    /// torque constant and back-EMF are the catalogue's at the rated rise and change with it (`Drive::flux`). 0 off.
148    pub magnet_coefficient: f64,
149    /// effects.braking_resistor_heating: the braking resistor's temperature (`ResistorHeating`); None without.
150    pub resistor_heating: Option<ResistorHeating>,
151    /// Fine interpolation, the torque feedforward's model, friction feedforward and balancing (`Precontrol`).
152    pub precontrol: Precontrol,
153    /// motor.kind: the motor the drive turns (`Motor`); the servo motor this module models by default.
154    pub motor: Motor,
155}
156
157/// motor.kind: "servo" (the default, the permanent-magnet servo motor of this module), "stepper" (`stepper::Stepper`
158/// behind an open-loop step and direction drive) or "induction" (`induction::Induction` on a frequency converter).
159#[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    /// Whether the drive runs the motor without its speed loop: the stepper's step generator and the induction motor's
178    /// V/f control follow the speed setpoint open loop, and take no torque setpoint.
179    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
188/// The electrical states of a winding in the integration of a base step (`Sim::step`), per drive: the first state, the
189/// electrical energy, the copper loss and the work on the shaft, then three more. The servo's one winding has its current
190/// first and the last three at rest; the other motors keep theirs in `Phases::x`.
191pub const WINDING_STATES: usize = 7;
192
193/// The state of a stepper's or an induction motor's windings and drive beside the servo's (`Motor`); unused for the servo.
194#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
195pub struct Phases {
196    /// The electrical states (stepper: i_a, i_b; induction: stator and rotor flux in d and q), as integrated.
197    pub x: [f64; 4],
198    /// The voltages held over the base step (stepper: phases a and b; induction: d and q).
199    pub u: [f64; 2],
200    /// The current controllers' integrators (induction, field-oriented).
201    pub integral: [f64; 2],
202    /// The rotor at the end of the last step: its angle and speed at the motor, rad and rad/s.
203    pub angle: f64,
204    pub speed: f64,
205    /// Stepper: the angle the step generator commands, rad at the motor; the angle the windings count from (where the
206    /// drive was enabled, on a full step); the electrical angle of the current vector, in whole microsteps; and the
207    /// load angle, that less the rotor's electrical angle (beyond the pull-out angle the rotor falls out of step).
208    pub command: f64,
209    pub origin: f64,
210    /// Stepper: how far the drive's own count stands from the controller's setpoint (rad at the motor), left by an
211    /// enable that pulled the rotor to the nearest full step of the grid (`Stepper::re_enabled`); 0 otherwise.
212    #[serde(default)]
213    pub offset: f64,
214    pub electrical: f64,
215    pub load_angle: f64,
216    /// Induction: the electrical speed of the frame the voltages are set in, rad/s, and the drive's estimate of the rotor
217    /// flux (field-oriented) or its estimate of the torque (V/f, for the slip compensation).
218    pub frame_speed: f64,
219    pub estimate: f64,
220}
221
222/// What the drive does with the setpoints between and beside the gains, as a SINAMICS S120/S210 in DSC is set up.
223/// The default is the drive before 14 November 2026: setpoint held, rigid model, no friction, no balancing.
224#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
225pub struct Precontrol {
226    /// effects.fine_interpolation: between profile cycles the position loop's setpoint runs on from the last
227    /// setpoints as pos + v t + a t^2 / 2, as the speed feedforward runs on as v + a t (its derivative), the drive's
228    /// fine interpolator. Off it is held for the profile cycle, as a position loop closed in the controller at the
229    /// IPO cycle sees it.
230    pub fine_interpolation: bool,
231    /// drive.torque_feedforward_model = "inertia": the torque feedforward is one moment of inertia per motor times the
232    /// motor's acceleration setpoint (S120 p1498 with p1428 speed/torque precontrol), the inertia the rigid model has
233    /// at the start pose; no gravity, no speed terms, no coupling. "rigid" (false): the rigid model's inverse dynamics.
234    pub constant_inertia: bool,
235    /// effects.friction_feedforward: the friction characteristic, (speed rad/s, torque N m) points at rising speeds
236    /// (S120 p3820-p3839); empty when off. See `friction_at`.
237    pub friction: Vec<[f64; 2]>,
238    /// effects.friction_feedforward with drive.friction_feedforward_model = "machine": in place of the characteristic,
239    /// the friction of the machine's own model at the planned speed (`Machine::steady_friction`, `Drive::friction_ff`).
240    #[serde(default)]
241    pub machine_friction: bool,
242    /// drive.precontrol_balance_s: the position setpoint passes a first-order lag of this time constant before the
243    /// position loop compares it, so that it arrives with the motor that the speed precontrol moves through the
244    /// closed speed loop (S120 p2536 balancing); 0 off.
245    pub balance_time: f64,
246}
247
248impl Precontrol {
249    /// The friction feedforward at a speed setpoint: linear between the points, from (0, 0) to the first, held
250    /// beyond the last, with the sign of the speed.
251    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/// effects.braking_resistor_heating: the braking resistor as one heat capacity, rise' = (rated_rise P / P_continuous -
264/// rise) / tau: at its continuous power it settles at its rated rise, and a peak of its peak power for the duty cycle the
265/// catalogue gives (`braking_s120.csv`) warms it within the time constant.
266#[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    /// The rise after `dt` at a constant `power`, exactly.
275    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/// effects.field_weakening: the permanent-magnet synchronous motor in d-q axes. The one winding is the q axis, scaled as
282/// the module comment says (current the RMS phase current, voltage three times the RMS phase voltage); the d axis is
283/// scaled alike, so that R, L and the voltage limit are the winding's and the flux linkage is ke / pole pairs. With the
284/// electrical speed w = pole pairs * shaft speed:
285///   u_q = R i_q + L_q di_q/dt + ke speed + w L_d i_d,   u_d = R i_d - w L_q i_q,   u_q^2 + u_d^2 <= U^2,
286///   torque = kt i_q + pole pairs (L_d - L_q) i_d i_q.
287/// Above base speed the drive sets a negative d current, the least that brings the voltage within the circle
288/// (`DriveParams::d_current_for`); i_q^2 + i_d^2 is the RMS phase current squared.
289#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
290pub struct FieldWeakening {
291    pub pole_pairs: f64,
292    /// d-axis inductance as the winding has it (three times the phase value); the q axis's is `DriveParams::inductance`.
293    pub d_inductance: f64,
294}
295
296/// effects.drive_overload: the drive's thermal image (i^2 t) of its power unit in two nodes, as the SINAMICS power units
297/// model a slow heat sink and the fast chips on it: x = x_s + x_c with x_s' = ((1 - w) q - x_s) / tau and
298/// x_c' = (w q - x_c) / tau_c, q = (i / I_rated)^2, w the chips' share of the rise (`chip_share`). x is 1 at the rated
299/// current held. At the trip level the drive lowers its current limit to the base load current, and holds it there until
300/// the image is back at 1. The trip level follows from the time the drive gives its maximum current from the rated load:
301/// trip = r^2 - (r^2 - 1) ((1 - w) exp(-t_max / tau) + w exp(-t_max / tau_c)) for r = I_max / I_rated. With w = 0 the
302/// one node of 14 November 2026.
303#[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    /// With effects.drive_overload on (off where the config has no switch), from the `[ratings]`.
316    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    /// The share of a step's difference each node keeps after `dt`: the slow node's weighted by 1 - w, the chips' by w.
344    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    /// The nodes [slow, chips] after `dt` at a constant `current`, exactly.
352    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    /// The time constant of node 0 (the slow one) or 1 (the chips).
359    pub fn node_time_constant(&self, node: usize) -> f64 {
360        if node == 0 { self.time_constant } else { self.chip_time_constant }
361    }
362
363    /// The time from the rated load held (image 1) until the image reaches the trip level at a constant `current`; infinite
364    /// where it never does. Bisection on the closed form x(t) = q - (q - 1) (decays summed).
365    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/// effects.motor_thermal_nodes: three nodes, winding, stator/housing and ambient, as two heat capacities in a chain.
381/// The resistances add up to the one-node model's, rated rise over rated loss, so the settled rises stay; the winding
382/// has the share `winding_share` of it (to the housing) and the time constant `winding_time_constant` against the
383/// housing. The heat capacities add up to the one-node model's too (thermal time constant over the resistance).
384#[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
390/// Resistance of copper rises by this share per kelvin.
391pub(crate) const COPPER: f64 = 0.0039;
392
393/// Winding voltage per DC link voltage, sqrt(3/2): see the module comment.
394pub const WINDING_PER_DC_LINK: f64 = 1.224_744_871_391_589;
395
396/// Phase amplitude per winding voltage: sqrt 2 / 3 (the winding's voltage is three times the RMS phase voltage).
397const PHASE_PER_WINDING: f64 = 0.471_404_520_791_031_7;
398
399impl DriveParams {
400    /// `dt` is the base step, which is also the current-loop cycle.
401    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        // A frequency of 0 is no notch: a motor of its own (`[drive.<id>]`) without a resonance where the notch is on
417        // for another.
418        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        // The back-EMF per speed of a servo winding, where the maker prints a voltage constant apart from the torque
427        // constant; none, or 0, leaves it equal to kt. A stepper's winding keeps one constant for both (`stepper`).
428        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        // The torque fades out between the two speeds; with the no-load speed at or below the rated one it
434        // would have no slope to fade on.
435        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        // The simulated DC link is built from the drive's ratings, which it then needs.
452        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        // The line module's power is needed only where it feeds back; its efficiency wherever the DC link is simulated,
471        // which it fills from the line through it.
472        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        // A config written before 13 November 2026 has no switch: the drive's limit is judged, not simulated.
476        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        // The three switches of 14 November 2026 read as off where a config has none; their keys only when on.
481        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            // The housing's heat capacity, (tau - tau_w / share) / R, has to be left over.
499            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        // The keys of 14 November 2026 for the loops: a config without them gets the drive as it was (`Precontrol`).
507        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        // Which friction the feedforward adds: the drive's recorded characteristic (no key: as before 15 November 2026),
514        // or the machine's own model at the planned speed.
515        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        // The switches below read as off where a config has none, as those above.
547        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        // The printed rated point's torque gap holds the iron's drag and the shaft's friction (`iron_drag_rated`).
569        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        // Absent: the sinusoidal limit, as before. A square wave's fundamental is 4 / pi of its height. A stepper's
583        // H-bridge gives a phase +-U, so sinusoidally U at most: 4 / pi more. A three-phase bridge's sinusoidal limit
584        // (space vector, `WINDING_PER_DC_LINK`) is U / sqrt 3 per phase and six-step's fundamental 2 U / pi: 2 sqrt 3 / pi.
585        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            // Copper at the rated rise; a rated current above the stall current (a misprint, see catalog) gives no iron loss.
595            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            // An induction motor's rotor heats it too: at the rated point the copper loss of both brings it to its rated
600            // rise, as the stall current's alone would (Drive::thermal_current).
601            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    /// Torque limits (lowest, highest) at a speed: the current limit everywhere, and in the
706    /// direction of rotation the torque-speed curve that the voltage limit leaves. With the drive's current limit
707    /// (effects.drive_current_limit) also the torque of the drive's maximum current, where that is the lower: the
708    /// current setpoint, the torque's, then stays within min(motor, drive maximum current).
709    pub fn torque_range(&self, speed: f64) -> (f64, f64) {
710        self.torque_range_at(speed, self.max_voltage)
711    }
712
713    /// `torque_range` with the winding getting `max_voltage` at most (the DC link's at the moment, `Drive::max_voltage`).
714    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        // The induction motor has no servo torque constant: its curve holds the drive's current itself
718        // (`Induction::torque_curve`), as the field-weakened curve does (`field_weakened_torque`, the current circle).
719        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    /// The winding's voltage limit per DC link voltage: `WINDING_PER_DC_LINK`, times `fundamental_gain`.
729    pub fn dc_gain(&self) -> f64 {
730        WINDING_PER_DC_LINK * self.fundamental_gain
731    }
732
733    /// effects.iron_loss: the iron loss at a speed, `iron_loss_rated` times (|speed| / rated speed)^1.5: hysteresis grows
734    /// with the frequency, eddy currents with its square. One exponent stands for both parts: no maker prints the split.
735    /// This is the heat the winding's thermal model takes (`Drive::iron_loss`, `iron_heating`); the power the shaft loses
736    /// to the same losses follows the same law from the printed torque gap (`iron_drag`).
737    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    /// effects.iron_loss: the drag torque of the speed losses on a servo's shaft, against the motion: `iron_drag_rated` at
746    /// the rated speed and P(w) / w with P = c |w|^1.5 over speed, written T_N w |w|^-0.5 / w_N^0.5 so that it is smooth
747    /// through 0 (0 at standstill, no sign jump). The shaft gets the air-gap torque less this, so shaft power = air-gap
748    /// power - this loss, with the drive disabled too.
749    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    /// Winding resistance at a temperature rise.
758    pub fn resistance_at(&self, rise: f64) -> f64 {
759        self.resistance * (1.0 + COPPER * rise)
760    }
761
762    /// Torque of a current: the torque constant, less what saturation takes at high current.
763    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    /// The current that gives a torque, the inverse of `torque_of`, up to the maximum current. Newton's
768    /// method from below: the curve bends down, so every step stays below the answer and none overshoots.
769    pub fn current_for(&self, torque: f64) -> f64 {
770        if self.saturation == 0.0 {
771            return torque / self.kt;
772        }
773        // In units of the maximum current and of the torque it would give unsaturated: y = x - s x^3.
774        // A curve that loses more than a third turns down before the maximum current; its top is the limit.
775        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    /// Back-EMF at a current and speed. The torque constant that saturation leaves is the back-EMF
788    /// constant too, so that the electrical power is the shaft power plus the copper loss.
789    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    /// The winding's rates at a moment of a base step, for the integrator (`Sim::step`), with the voltage and the
794    /// resistance held over the step: [di/dt, electrical power u i, copper loss R i^2, shaft power torque w]. With
795    /// the back-EMF on, u i = R i^2 + L i di/dt + torque w at every moment, so the winding's energy closes.
796    ///
797    /// With field weakening the d current `d_current` is held over the step as the controller set it (`FieldWeakening`):
798    /// it adds w L_d i_d to what the q axis meets, u_d i_d to the electrical power, R i_d^2 to the copper loss and the
799    /// reluctance torque to the shaft. u_q i_q + u_d i_d = R (i_q^2 + i_d^2) + L i_q di_q/dt + torque w still closes.
800    ///
801    /// With effects.iron_loss the shaft power is the air-gap power less the iron loss (`iron_drag` w): what the electrical
802    /// power leaves beyond copper, stored energy and shaft power is `Drive::emf_loss`, which then holds the iron loss.
803    ///
804    /// `flux` scales the torque constant and the back-EMF for the magnets' temperature (`Drive::flux`, 1 without
805    /// effects.magnet_temperature).
806    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    /// Torque of a q current and a d current: `torque_of` times the magnets' `flux`, plus the reluctance torque pole
832    /// pairs (L_d - L_q) i_d i_q with field weakening.
833    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    /// The d current the drive sets for a q current at a speed with the voltage `max_voltage`: none while
841    /// u_q^2 + u_d^2 (steady, `FieldWeakening`) stays within it, else the least negative one that brings it there, at
842    /// most `limit`. Where none does, the one that needs the least voltage. 0 without field weakening. With the winding's
843    /// `resistance` at its temperature and the magnets' `flux` (`Drive::flux`), as the winding has them.
844    ///
845    /// The back-EMF is the unsaturated k_E w: the drive's own model of the motor, which the winding's saturated back-EMF
846    /// (`back_emf`) undercuts, so the d current leaves a voltage reserve (at most the saturation's share of the
847    /// back-EMF: 11 % at the maximum current of the test motor, 17 % for the 1FK2106-6AF). Taken saturated (tried
848    /// 17 November 2026) the steady point sits on the voltage circle, where braking beyond the curve is unstable: the q
849    /// voltage that the circle leaves falls as the braking current rises (u_d = R i_d - w L i_q grows), faster than R and
850    /// the back-EMF's fall hold it; the test motor at 400 rad/s and -3.8 N m ran away to 18.8 A of its 9.5 A
851    /// (`braking_at_the_voltage_limit_does_not_run_away`). The torque-speed curve takes the same model, so it is what the
852    /// drive reaches: 3.6 % below the saturated optimum at 380 rad/s there (3.3255 against 3.4514 N m).
853    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        // (c0 + a d)^2 + (r d - b q)^2 = U^2 as a d^2 + b d + c = 0.
859        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    /// With field weakening: the most torque, motoring or braking (as a magnitude), at a speed of at least 0 within the
870    /// current circle of the motor's maximum current and the voltage circle of `max_voltage`, over every d current
871    /// from 0 to minus the maximum current (golden section; the torque rises to one top and falls).
872    /// `imax` is the radius of the current circle, the phase current's: the motor's maximum current, or the drive's where
873    /// that is lower (`torque_curve_at`).
874    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        // The q current the two circles leave at a d current, as a magnitude.
879        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            // (r q + c1)^2 + (r d - b q)^2 <= U^2 as qa q^2 + qb q + qc <= 0. The back-EMF unsaturated, as the drive's
885            // d current takes it (`d_current_for`): the curve is what the drive reaches.
886            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    /// Without field weakening: the largest current magnitude the voltage `umax` leaves at a speed of at least 0, within the
919    /// motor's maximum current, steady and cold. The q axis meets e = kE speed (motoring: R i + e; braking: e - R i) and
920    /// the d axis the reactance x i, x = p speed L (`current_control`): (R i + e)^2 + (x i)^2 <= U^2, so with
921    /// a = R^2 + x^2 and b = +-R e the root of a i^2 + 2 b i + e^2 - U^2 = 0, i = (-b + sqrt(b^2 - a (e^2 - U^2))) / a.
922    /// Without reactance that is (U - e) / R motoring and (U + e) / R braking.
923    ///
924    /// Braking above the speed where e alone exceeds U the same circle is solved, for the braking current i against e:
925    /// (e - R i)^2 + (x i)^2 <= U^2, an interval of currents [`forced_braking_current`, the root returned here]; the
926    /// smaller one is what the inverter's diodes force at a speed the voltage cannot hold (the uncontrolled generator).
927    /// Where the circle leaves none (x e > sqrt(a) U) the nearest current is returned, the circle's closest approach R e / a.
928    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    /// Braking above the speed where the back-EMF alone exceeds `umax`: the smallest braking current the voltage circle
941    /// (e - R i)^2 + (x i)^2 <= U^2 leaves, the one the rectifier diodes force, i = (R e - sqrt(a U^2 - x^2 e^2)) / a with
942    /// a = R^2 + x^2; the nearest current R e / a where the circle leaves none. 0 while e <= U (nothing is forced).
943    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    /// The temperature rise the winding settles at when a cycle with this RMS current and this mean iron loss
954    /// (effects.iron_loss, W) repeats for long: the copper loss, with the resistance at that temperature, against the loss
955    /// at the rated current (with the iron loss, at the stall current), plus the iron loss's share. That share is all of
956    /// it with one thermal node, and with effects.motor_thermal_nodes the housing's, 1 - s: the iron is in the stator.
957    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    /// The copper loss at which the winding settles at its rated rise: at the stall current with effects.iron_loss (the
964    /// iron loss is apart), else at the rated current, which then stands for both.
965    pub fn rated_loss(&self) -> f64 {
966        self.resistance_at(self.rated_rise) * self.stall_current * self.stall_current
967    }
968
969    /// The S1 torque at a speed, as the motor-s1 verdict has it (`analysis::s1_torque`) and the torque-speed chart draws it:
970    /// `s1_line` from the static torque k_t I_0 (`motor.stall_current_a`, read with effects.iron_loss off too); flat at the
971    /// rated torque where the config has no stall current.
972    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    /// A loss in the rise it would settle at alone, K: rated rise per `rated_loss`.
981    pub fn iron_heating(&self, loss: f64) -> f64 {
982        self.rated_rise * loss / self.rated_loss()
983    }
984
985    /// The same limits, whether or not the limit is switched on: what the motor and drive can give.
986    /// With field weakening the curve is the d-q model's (`FieldWeakening`), up to the peak torque; without it the
987    /// torque fades out linearly between the rated and the no-load speed.
988    pub fn torque_curve(&self, speed: f64) -> (f64, f64) {
989        self.torque_curve_at(speed, self.max_voltage)
990    }
991
992    /// `torque_curve` with the winding getting `max_voltage` at most. Without field weakening the fade's two speeds
993    /// scale with it against `max_voltage` (the back-EMF the voltage leaves room for).
994    pub fn torque_curve_at(&self, speed: f64, max_voltage: f64) -> (f64, f64) {
995        // A stepper's pull-out curve, an induction motor's breakdown curve.
996        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        // The printed fade at the config's voltage; at another one each of its two speeds moves to where the voltage
1010        // circle leaves the current of that point (`fade_speed`): the ratio of those speeds at the new and the printed
1011        // voltage, so R, L and kE enter. The printed voltage is the sinusoidal limit (without drive.overmodulation).
1012        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        // Braking holds the peak torque at every speed, as far as the voltage circle (the winding's reactance) lets a
1020        // current of that size be controlled: beyond it the q voltage cannot oppose the back-EMF and the current runs away.
1021        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    /// A speed of the printed fade (at the sinusoidal limit `max_voltage / fundamental_gain`) moved to the voltage `umax`:
1031    /// the speed at which the voltage circle (`voltage_limited_current`, motoring) leaves the current it leaves at `speed`
1032    /// with the printed voltage, times `speed` over the printed voltage's own such speed. That speed is the circle solved
1033    /// for w at the current i: (R i + kE w)^2 + (p w L i)^2 = U^2, A w^2 + B w + C = 0 with A = kE^2 + (p L i)^2,
1034    /// B = 2 R i kE, C = (R i)^2 - U^2 (the highest speed that still leaves i; where the current is clamped at the maximum,
1035    /// the end of that plateau). Without a back-EMF or where that current is 0 (the point sits at e = U) the speed
1036    /// scales with the voltage.
1037    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    /// The torque (lowest, highest) the winding's voltage leaves at a speed with a DC link of `dc_voltage`, within the
1054    /// motor's maximum current, steady and cold, whether or not the limit is switched on: the voltage-limit curve of the
1055    /// torque-speed chart. With field weakening the d-q model's (`torque_curve`'s, before the peak torque caps it);
1056    /// without it the winding has no d current, but its reactance is there: the steady voltage vector is
1057    /// (R i + kE speed, p speed L i) and the limit (R i + kE speed)^2 + (p speed L i)^2 <= U^2 in the direction of motion
1058    /// (`voltage_limited_current`; the pole pairs `motor.pole_pairs`, none without them: R i + kE speed <= U).
1059    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    /// The rates of drive `d`'s electrical states `w` (`WINDING_STATES`, as `Drive::winding_states` gives them) at a
1080    /// moment of a base step, with the rotor at `angle` and `speed` at the motor, into `rates`; returns the motor torque.
1081    /// The servo's are `winding_rates` and `torque_with`.
1082    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
1103/// The printed S1 curve of a config (`motor.s1_curve_speed_rad_s`, `motor.s1_curve_torque_nm`): the same number of points
1104/// each, at least two, finite, speeds rising from 0 or above, torques not negative. Empty where the config has neither
1105/// key or both empty: the straight line.
1106pub 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
1127/// The S1 torque at `speed` (either direction) from a printed curve: linear between its points, the first torque below
1128/// the first speed and the last one beyond the last (the curve ends where the maker's graph does).
1129pub 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
1141/// The S1 line: from the static torque at standstill straight to the rated torque at the rated speed, and on along that
1142/// line above it, never below 0.
1143pub 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
1147/// Biquad notch (b0, b1, b2, a1, a2), normalised by a0.
1148fn 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/// How a drive takes its command, as a servo drive's operating modes. `Position`: the controller's plan through the
1156/// position and velocity loops (the default). `Velocity`: a speed setpoint from outside, rad/s at the motor, for the
1157/// velocity loop; the position loop is bypassed. `Torque`: a torque setpoint from outside, N m at the motor, in place of
1158/// the velocity loop's output; both loops are bypassed. Either way the setpoint still passes the torque filter, notch,
1159/// torque limit and delay, the current loop, the winding and the DC link. Outside position mode the position setpoint
1160/// tracks the measured position (no following error), as a drive's tracking mode does.
1161#[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/// The loops and filters of one drive.
1170#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
1171pub struct Drive {
1172    pub pos_set: f64,
1173    /// Speed setpoint at the last profile cycle, and its rate until the next one.
1174    pub vel_set: f64,
1175    pub acc_set: f64,
1176    /// Time since the profile generator last wrote the setpoints; the controller adds a base step after each.
1177    pub since_setpoint: f64,
1178    pub torque_ff: f64,
1179    /// With `drive.friction_feedforward_model = "machine"` (`Precontrol::machine_friction`): the friction the machine's
1180    /// own model has at the planned speed (`Machine::steady_friction`), written with the setpoints; 0 otherwise.
1181    #[serde(default)]
1182    pub friction_ff: f64,
1183    /// The setpoint the position loop compared with at its last cycle: `pos_set` run on between profile cycles
1184    /// (`Precontrol::fine_interpolation`) and balanced (`Precontrol::balance_time`). `following_error` is from it.
1185    pub position_setpoint: f64,
1186    pub following_error: f64,
1187    /// The position loop's share of the speed command, Kv times the following error, held between its cycles.
1188    pub position_part: f64,
1189    /// The velocity loop's output at its last cycle in its two parts, before filters and limits: the feedforward
1190    /// (`torque_ff` weighted, and friction) and the PI controller's.
1191    pub feedforward_torque: f64,
1192    pub controller_torque: f64,
1193    pub speed_command: f64,
1194    /// What the velocity loop asks for, before the torque limit; `torque_command` is what the limit leaves of it.
1195    pub torque_demand: f64,
1196    pub torque_command: f64,
1197    /// A test signal added to what the velocity loop asks for, before the limit: the loop is measured by it
1198    /// (`analysis::velocity_loop_response`). Zero otherwise.
1199    pub torque_injection: f64,
1200    pub torque: f64,
1201    /// Winding current and the voltage the current controller applies.
1202    pub current: f64,
1203    pub voltage: f64,
1204    /// Electrical power into the winding, the mean u i over the last base step; negative while the motor feeds back.
1205    pub power: f64,
1206    /// Copper loss and the power the torque gave the shaft, means over the last step like `power`.
1207    pub copper_loss: f64,
1208    pub shaft_power: f64,
1209    /// Temperature of the winding above its surroundings.
1210    pub temperature_rise: f64,
1211    /// With effects.motor_thermal_nodes: temperature of the stator and housing above the surroundings; 0 without.
1212    pub housing_rise: f64,
1213    /// With effects.field_weakening: the d current, held over the base step like the voltage; 0 without. It follows the
1214    /// setpoint the drive works out (`DriveParams::d_current_for`) as the tuned current loop does, with the time constant
1215    /// L_d / Kp (the controller's Tn = L / R cancels the winding's own), exactly per step. The RMS phase current is the
1216    /// hypotenuse of it and `current` (`phase_current`).
1217    pub d_current: f64,
1218    /// The servo winding's d-axis voltage the current loop set with `voltage` (`current_control`), in the winding's units;
1219    /// 0 for the other motors and while disabled. `phase_voltage` is the vector of both.
1220    #[serde(default)]
1221    pub d_voltage: f64,
1222    /// With effects.drive_overload: the drive's thermal image (`Overload`), both nodes together, the chips' node alone,
1223    /// and whether it has lowered its current limit to the base load current.
1224    pub overload_image: f64,
1225    pub overload_chip: f64,
1226    pub overloaded: bool,
1227    /// With effects.iron_loss: the stator's iron loss over the last step, W, at the speed the step started with.
1228    pub iron_loss: f64,
1229    /// With a back-EMF constant other than the torque constant (`DriveParams::ke`): the electrical power the winding takes
1230    /// beyond the copper loss, the winding's stored energy and the shaft power over the last step, (kE - kt) i w, W. It
1231    /// is booked as a loss of its own in the energy budget (the magnets' and iron's, which the maker's two constants
1232    /// differ by); signed, as i w is. 0 for equal constants, a stepper and an induction motor.
1233    #[serde(default)]
1234    pub emf_loss: f64,
1235    /// The torque the machine's rigid model needs to hold the planned pose, where the feedforward is the constant inertia
1236    /// (`drive.torque_feedforward_model = "inertia"`: no gravity in `torque_ff`) and the torque-band monitor is on, plus
1237    /// with that monitor, on a machine that does not report its friction torque, the friction at the planned speed
1238    /// (`fault::Settings::torque_band`); 0 otherwise. What the monitor
1239    /// expects beside `torque_ff` (`fault::Watch::check`).
1240    #[serde(default)]
1241    pub torque_hold: f64,
1242    /// With effects.braking_resistor_heating: the braking resistor's temperature above its surroundings, K.
1243    pub resistor_rise: f64,
1244    /// The energy L i^2 / 2 a drive enabled without the DC link simulated put into its winding (`Control::hold_here`):
1245    /// drawn from the supply in the first step, booked there with the step's electrical power.
1246    pub enable_energy: f64,
1247    /// DC link voltage, the power the braking resistor burns, and whether the drive has tripped on
1248    /// overvoltage. With the DC link switched off the voltage stays at the bus level.
1249    pub dc_voltage: f64,
1250    pub resistor_power: f64,
1251    pub tripped: bool,
1252    /// With the DC link simulated: the power drawn from the line for the DC link, and with the regenerative supply the
1253    /// power fed back into the mains, over the last step; and what the line module lost either way
1254    /// (`ratings.line_module_efficiency`: of what it draws, the efficiency arrives in the DC link).
1255    pub rectifier_power: f64,
1256    pub mains_power: f64,
1257    pub line_loss: f64,
1258    /// With the DC link simulated and the drive off: what its discharge through the bleeder took out of the DC link over
1259    /// the last step, as a mean power (the rectifier draws it back while the link is held at the bus level).
1260    pub discharge_power: f64,
1261    /// The drive's own stream of sensor noise.
1262    pub noise: Noise,
1263    /// Whether the velocity loop's output was beyond the torque limit at its last cycle (`fault::Watch`).
1264    pub at_limit: bool,
1265    /// While the drive stops on a fault (`fault::Reaction`): the speed setpoint of its stop ramp, which the velocity
1266    /// loop follows without the position loop and without feedforward. And once its pulses are off: no voltage, no
1267    /// current, no torque, while the others may still be stopping.
1268    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    /// Values computed but not yet acting, oldest first.
1278    voltage_queue: VecDeque<f64>,
1279    torque_queue: VecDeque<f64>,
1280    mode: DriveMode,
1281    /// Set when the mode changes between position, velocity and torque: the next velocity loop that runs its PI sets
1282    /// the integrator so that its output is the torque last asked for (bumpless transfer, `set_mode`).
1283    retune: bool,
1284    /// A stepper's or an induction motor's windings and drive (`Phases`); unused for the servo.
1285    pub phases: Phases,
1286}
1287
1288/// `value` goes into the queue; what was computed `cycles` ago comes out.
1289pub(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    /// A drive at rest at `pos`, already delivering `torque` (so a hanging axis does not sag at start).
1299    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            // A winding started warm has its housing where that rise settles it.
1313            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    /// The electrical states this drive's winding starts a base step with, in the order of `WINDING_STATES`.
1338    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    /// The magnetic energy in the winding: L i^2 / 2 for the servo and the stepper (both phases), the induction motor's
1349    /// own (`induction::Induction::stored_energy`).
1350    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    /// The energy stored in the drive's field, `winding_energy`. A stepper's detent potential is not stored: its changes
1358    /// are booked as they happen (`detent_moved`), so that it neither appears nor vanishes at an enable or a disable.
1359    pub fn magnetic_energy(&self, p: &DriveParams) -> f64 {
1360        self.winding_energy(p)
1361    }
1362
1363    /// A stepper's base step done with the rotor from `before` to `phases.angle`: the detent's work is in the shaft's,
1364    /// and what the magnets gave for it, the change of `Stepper::detent_potential`, is the step's `emf_loss` (exact, the
1365    /// torque being conservative). Nothing for the other motors.
1366    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    /// The current loop holding its current at rest: the voltage R i, with the winding's resistance at its temperature,
1374    /// in its integrator, its output and its delay. Before 14 November 2026 the cold resistance, so a winding started
1375    /// or enabled warm began with a voltage step of (R(rise) - R) i (found by the closed-loop reference written in
1376    /// Python for one belt axis, see docs/validation.md).
1377    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    /// Switches the operating mode. A change between position, velocity and torque mode does not make the torque jump
1392    /// where the drive's own loops take over: the next velocity loop sets the PI integrator so that it asks for the
1393    /// torque it asked for last (`retune`). Into torque mode the outside setpoint acts at once, and the integrator is
1394    /// held meanwhile; a jump there is the outside controller's.
1395    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    /// The next velocity loop starts its PI from the torque last asked for (see `set_mode`).
1403    pub fn retune(&mut self) {
1404        self.retune = true;
1405    }
1406
1407    /// The RMS phase current: of the q current `current` and the d current together.
1408    pub fn phase_current(&self) -> f64 {
1409        self.current.hypot(self.d_current)
1410    }
1411
1412    /// `motor.<id>.voltage`, one meaning for every motor: the amplitude of the phase voltage's space vector, V. The
1413    /// induction motor's and the stepper's vectors are phase amplitudes already (`voltage`); the servo's one winding has
1414    /// three times the RMS phase voltage in each axis, so its vector (q `voltage`, d `d_voltage`) is multiplied by
1415    /// sqrt 2 / 3 (the DC link's sqrt(3/2) U gives U / sqrt 3).
1416    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    /// The current that heats the winding as the step's copper loss does, against `DriveParams::stall_current`: the phase
1424    /// current; for an induction motor, whose rotor is heated too, sqrt(copper loss / R_s).
1425    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    /// The speed the velocity loop measured at its last cycle, filtered.
1433    pub fn measured_speed(&self) -> f64 {
1434        self.speed
1435    }
1436
1437    /// The thermal image's nodes [slow, chips] (effects.drive_overload).
1438    pub fn overload_nodes(&self) -> [f64; 2] {
1439        [self.overload_image - self.overload_chip, self.overload_chip]
1440    }
1441
1442    /// The magnets' flux against the catalogue's (effects.magnet_temperature): 1 + coefficient (rise - rated rise), the
1443    /// catalogue's torque constant holding at the rated rise. The magnets sit in the rotor next to the stator: at the
1444    /// housing's rise with effects.motor_thermal_nodes, else at the winding's. 1 without the effect or without winding
1445    /// heating (the motor then stands at its rated rise throughout).
1446    /// shortcut: the rotor has no temperature of its own; give it a node if magnet heating by eddy currents matters.
1447    pub fn flux(&self, p: &DriveParams) -> f64 {
1448        if p.magnet_coefficient == 0.0 || !p.heating {
1449            return 1.0;
1450        }
1451        // With the nodes the housing settles at (1 - s) of the rise the winding has (`ThermalNodes`), so the rated state
1452        // has the housing at (1 - s) times the rated rise.
1453        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    /// Moves the encoder's readings so far by `by`, for a motor that was set elsewhere without turning there.
1461    pub fn shift_encoder(&mut self, by: f64) {
1462        self.encoder += by;
1463        self.last_encoder += by;
1464    }
1465
1466    /// Moves the position setpoints by `by`, for a motor that was set elsewhere without turning there.
1467    pub fn shift_setpoint(&mut self, by: f64) {
1468        self.pos_set += by;
1469        self.position_setpoint += by;
1470    }
1471
1472    /// Reads the motor encoder: the position as it reports it, with its noise, in whole counts. Once per base step in
1473    /// which a loop is due, so that the position and the velocity loop see the same sample (`encoder`).
1474    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    /// Position loop, every `cycle`: following error times Kv against the position setpoint (`position_setpoint`),
1480    /// with the measured position `measured`: the motor encoder's (`encoder`) or a load-side one's.
1481    pub fn position_loop(&mut self, p: &DriveParams, measured: f64, cycle: f64) {
1482        if self.mode != DriveMode::Position {
1483            // Tracking: the setpoint follows the actual position, so the loop asks for nothing.
1484            (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    /// The voltage limit of the winding: what the DC link has at this moment with effects.dc_link, else the nominal one.
1501    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    /// Velocity loop: PI on the measured speed (from `read_encoder`), plus torque feedforward, then filters and limits.
1506    pub fn velocity_loop(&mut self, p: &DriveParams, true_speed: f64) {
1507        // A real encoder gives positions only; the speed is their difference per cycle.
1508        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        // Velocity feedforward, interpolated between profile cycles. Holding it for a whole profile
1514        // cycle would make the speed command a staircase and the torque a sawtooth.
1515        let speed_set = self.vel_set + self.acc_set * self.since_setpoint;
1516        // Open loop (a stepper, V/f): the speed setpoint goes to the step generator or the frequency, no PI.
1517        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        // A fault's stop ramp wins over every mode.
1525        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        // The torque-speed curve at the DC link's voltage of the moment: a sagging DC link limits the torque at speed.
1557        let (mut low, mut high) = p.torque_range_at(self.speed, self.max_voltage(p));
1558        // An overloaded drive gives its base load current at most.
1559        // (The induction motor's converter holds it in its current setpoints, `Induction::control`.)
1560        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        // Anti-windup: the integrator stops while it would push further into the limit; in torque mode it is held.
1569        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    /// Current loop: PI on the winding current. The voltage it sets is held over the next base step, in which the
1575    /// integrator takes the winding through it (`DriveParams::winding_rates`); then `winding_stepped`.
1576    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        // The d axis first, the q axis gets what it leaves of the voltage circle. The d axis's steady voltage is
1586        // R i_d - w L i_q (w = p speed), the reactance of the q current with no d current (i_d = 0, the winding without
1587        // field weakening) and the reactance of the d current too with it.
1588        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                // The d current for this setpoint, with the winding warm as it is, for the larger of the setpoint and the
1593                // q current there is (an overshoot needs its weakening too).
1594                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                // A q current beyond what the two circles leave together (a setpoint above the curve) would take a d current
1597                // that fills the current circle and leaves no q at all: the d current is the one of the most q that fits.
1598                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                // The d axis follows it as the current loop does, with the voltage that takes i_d the lag's share this step
1617                // on top of the steady one: held within the circle, i_d moves as far as that voltage takes it, and the q
1618                // axis has no more than the rest of the circle, so that no state needs more than U.
1619                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                // The phase current's circle on the references, as a drive limits its current reference vector:
1628                // i_q,ref within what the d setpoint leaves of it. The currents follow through the loop.
1629                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                // Braking where e alone exceeds U: the diodes force the current the circle's smaller root gives, and the
1635                // drive's current limiting cannot command less (`forced_braking_current`).
1636                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        // The drive adds the back-EMF it expects at this speed, as real drives do. Without that the
1650        // integrator would have to follow every speed change, at the slow pace of L / R.
1651        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        // Anti-windup: the integrator stops while the bus voltage is used up.
1656        if wanted == limited {
1657            self.current_integral += p.current_ki * error * p.current_cycle;
1658        }
1659    }
1660
1661    /// The winding's resistance over the next base step: at the temperature the step starts with.
1662    pub fn winding_resistance(&self, p: &DriveParams) -> f64 {
1663        if p.heating { p.resistance_at(self.temperature_rise) } else { p.resistance }
1664    }
1665
1666    /// The base step done: the integrator has taken the winding through it (`DriveParams::winding_rates`) and left
1667    /// the current at its end and the electrical energy, the copper loss and the work on the shaft over it. Then the
1668    /// DC link of its own and the winding's heating.
1669    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                // What the winding took and neither the copper, the shaft nor the inductance's energy accounts for:
1674                // exact, as the integrator took all four through the step together.
1675                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        // A drive just enabled without the DC link simulated draws its winding's first L i^2 / 2 from the supply here.
1688        (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        // A DC link of its own. A shared one is stepped once all drives have had this step (`shared_dc_link`).
1691        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    /// effects.drive_overload: the step's phase current on the drive's thermal image; at the trip level the drive lowers
1699    /// its limit to the base load current, back at the level of the rated current it lifts it again.
1700    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    /// A base step with the drive disabled: no current, no torque. The winding cools and the DC link discharges
1713    /// through its bleeder, a shared one once all drives have had this step (`shared_dc_link`).
1714    ///
1715    /// A current still in the winding when the pulses stop freewheels through the inverter's diodes into the DC link,
1716    /// against its voltage: it is gone within microseconds, well inside the step, and its energy L i^2 / 2 goes to
1717    /// the DC link (as power fed back over this step; without the DC link simulated, back to the supply).
1718    ///
1719    /// `speed` is the rotor's, at the motor: a turning rotor has its iron loss and drag with the drive off (effects.iron_loss,
1720    /// `DriveParams::iron_drag`): `torque` is the drag, the shaft takes `-drag w` and the same power is heat in the iron
1721    /// (`iron_loss`; and `emf_loss`, the budget's row for it).
1722    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            // C dU/dt = -U / R_b: the voltage falls by exp(-dt / (R_b C)) per step, exactly. The rectifier catches it
1740            // at the bus level, a regenerative supply takes what is above.
1741            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    /// One step of a DC link of its own, with the electrical power of the step.
1752    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    /// The copper loss of the step warms the winding; at the rated current it balances at the rated rise. Without
1767    /// current (a disabled drive) the same model cools it.
1768    ///
1769    /// With effects.motor_thermal_nodes (`ThermalNodes`), in units of the rise the loss would settle at (P R): the winding
1770    /// tau_w dT_w/dt = s P R - (T_w - T_h), the housing (tau - tau_w / s) dT_h/dt = (T_w - T_h) / s - T_h / (1 - s)
1771    /// + P_iron R. With one node the iron loss (effects.iron_loss) adds to the copper loss.
1772    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                // The iron loss heats the stator, the housing's node.
1781                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/// What a DC link did over one base step: its voltage after it, and the powers over it of the braking resistor, of
1793/// the rectifier (drawn from the line), fed back into the mains and lost in the line module, drawing and feeding back.
1794#[derive(Debug, Clone, Copy)]
1795struct DcLinkStep {
1796    voltage: f64,
1797    resistor: f64,
1798    drawn: f64,
1799    mains: f64,
1800    line_loss: f64,
1801}
1802
1803/// One base step of a DC link of `capacitance` that holds the energy `stored` and takes `power` out (negative:
1804/// a motor feeds back).
1805fn dc_link_step(p: &DriveParams, capacitance: f64, stored: f64, power: f64) -> DcLinkStep {
1806    // The capacitors take what the motors feed back and give what they draw: C U dU/dt = -P.
1807    // In energy, C U^2 / 2, that is exact for any step; `at` is the energy at a voltage.
1808    let (at, dt) = (|voltage: f64| 0.5 * capacitance * voltage * voltage, p.current_cycle);
1809    let energy = stored - power * dt;
1810    // A regenerative supply holds the bus level from above too: it feeds the excess back into the mains as far as its
1811    // power goes, and of that its efficiency arrives there.
1812    let fed = if p.regenerative { (energy - at(p.bus_voltage)).clamp(0.0, p.line_max_power * dt) } else { 0.0 };
1813    // Above the threshold the chopper switches the braking resistor in, which burns the excess
1814    // as far as its peak power goes. Beyond that the voltage keeps rising.
1815    let burned = (energy - fed - at(p.braking_threshold)).clamp(0.0, p.resistor_peak * dt);
1816    // The rectifier feeds from the line as soon as the voltage would fall below the bus level.
1817    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    // The line module (or an S210's rectifier) loses its share either way: it draws drawn / efficiency from the line, and
1824    // of what it feeds back the efficiency arrives there. A step does one or the other, never both.
1825    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
1834/// One base step of the DC link that all `drives` share, after their current loops: one Line Module, one DC
1835/// link, as on a SINAMICS S120. What a braking motor feeds back, a motoring one draws; only the net power
1836/// charges the capacitors. The link has the capacitance of all drives together (each brings
1837/// `ratings.dc_link_capacitance_uf`), one chopper with one braking resistor of the `[ratings]` powers, and one
1838/// trip. Every drive shows the link's voltage, the powers of resistor, rectifier and line module and the trip as its own.
1839///
1840/// Links that were apart until now (the switch came on a running machine) put their energies together.
1841pub 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    /// A drive of round numbers for the unit tests (the charts' too).
1862    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            // Kp = L / T and Tn = L / R for T = 0.25 ms.
1875            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        /// The current loop and the winding at a speed held, as `Sim::step` takes the winding through a base step
1934        /// with the mechanics: four RK4 sub-steps of the same rates.
1935        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    /// A shared DC link against a hand calculation. Two motors turn at 100 rad/s. One brakes with 0.45 N m: 1 A
1954    /// against a back-EMF of 45 V, of which the winding keeps 4 V, so it feeds back 41 W, in 0.1 s 4.1 J. The
1955    /// other drives with 0.225 N m: 0.5 A at 45 V + 2 V = 47 V, 23.5 W, in 0.1 s 2.35 J.
1956    /// Each with a link of its own: the braking drive's 470 uF go from 190 V (8.4835 J) to
1957    /// sqrt(2 * 12.5835 J / 470 uF) = 231.40 V, and the motoring drive's link stays at 190 V, fed from the line.
1958    /// Sharing one link of 2 * 470 uF, the motoring drive takes its 2.35 J from what the other feeds back: the
1959    /// net 1.75 J on 2 * 8.4835 J give sqrt(2 * 18.717 J / 940 uF) = 199.56 V. With the chopper at 195 V
1960    /// (940 uF hold 17.872 J there) the one resistor burns 18.717 - 17.872 = 0.845 J, and a trip level of
1961    /// 198 V with a resistor too small for the 17.5 W trips both drives.
1962    #[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        // One chopper, one resistor: both drives report the same 0.845 J.
2004        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        // One trip.
2012        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        // Links that are joined while they differ put their energies together: 231.40 V and 190 V on 470 uF
2016        // each are 12.5835 J + 8.4835 J on 940 uF, 211.72 V.
2017        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    /// The DC link against a hand calculation. The motor turns at 100 rad/s and brakes with 0.45 N m: 1 A
2028    /// against a back-EMF of 45 V, of which the winding keeps R i = 4 V. The drive feeds back 41 V * 1 A =
2029    /// 41 W, in 0.1 s 4.1 J. 470 uF at 190 V hold C U^2 / 2 = 8.4835 J; with 4.1 J more the voltage is
2030    /// sqrt(2 * 12.5835 J / 470 uF) = 231.40 V.
2031    #[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        // Motoring with the same current draws R i + ke w = 49 V * 1 A from the capacitors, and the rectifier
2049        // holds the voltage at the bus level from below: after 0.1 s (4.9 J, more than was stored) it is 190 V.
2050        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        // Between 190 V and the threshold of 250 V the capacitors hold 470 uF (250^2 - 190^2) / 2 = 6.204 J.
2057        // In 0.3 s the motor feeds back 12.3 J: the chopper holds 250 V and the resistor burns the other 6.096 J.
2058        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        // A resistor that takes 20 W at most leaves 21 W to charge on: 280 V, 3.736 J above the threshold,
2067        // are reached 0.178 s after the 0.151 s that the threshold takes, and the drive trips.
2068        let weak = DriveParams { resistor_peak: 20.0, ..p.clone() };
2069        assert!(!brake(&weak, 0.32).0.tripped && brake(&weak, 0.34).0.tripped);
2070        // The voltage limit follows the DC link: at 231.4 V the winding gets sqrt(3/2) * 231.4 V = 283.4 V.
2071        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        // Switched off, the voltage stays at the bus level and nothing trips.
2076        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    /// The regenerative supply against a hand calculation. The motor brakes as in the test above and feeds back 41 W. The
2081    /// line module holds the DC link at 190 V and feeds them into the mains: 98 % of 41 W for 0.1 s is 4.018 J there and
2082    /// 0.082 J lost, and neither the capacitors nor the resistor take anything. With the line module's power limited to
2083    /// 20 W it feeds back 20 W (1.96 J of 2 J arrive) and the other 21 W charge the capacitors: 2.1 J more than 8.4835 J
2084    /// is sqrt(2 * 10.5835 J / 470 uF) = 212.217 V. Motoring, the motor takes 49 W out of the DC link and the line module
2085    /// loses its 2 % drawing them too: 49 W / 0.98 = 50 W from the line, 5 J in 0.1 s, of which 0.1 J are lost.
2086    #[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        // A line module without loss draws what the motor takes, 4.9 J (as before 14 November 2026).
2125        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    /// Sensor noise against a hand calculation. Each encoder reading is off by an independent error with
2130    /// standard deviation s. The speed is the difference of two readings over the velocity cycle T, so its
2131    /// error has s sqrt(2) / T. The velocity filter y += a (x - y) turns the readings n into
2132    /// y = (a / T) (n[k] - a sum over j >= 1 of (1 - a)^(j - 1) n[k - j]), with the variance
2133    /// (a s / T)^2 (1 + a^2 / (1 - (1 - a)^2)) = (a s / T)^2 * 2 / (2 - a): the filtered speed has the
2134    /// standard deviation (s / T) a sqrt(2 / (2 - a)).
2135    /// Two counts of a 2^20 encoder are s = 1.198e-5 rad, s / T = 0.0959 rad/s at T = 125 us: 0.1356 rad/s
2136    /// unfiltered, and with a = 1 - exp(-125 / 200) = 0.4647 filtered 0.0959 * 0.4647 * 1.1414 = 0.0509 rad/s.
2137    #[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        // Current noise reaches the voltage through the current controller's gain: 0.01 A * 40 V/A.
2160        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        // Without noise the encoder is exact and nothing is drawn from the generator.
2165        let mut d = Drive::at_rest(&params(), 0.0, 0.0, 0.0);
2166        d.read_encoder(&params(), 0.0);
2167        d.velocity_loop(&params(), 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    /// pos 1 rad, 10 rad/s, 100 rad/s^2, 3 ms after the profile cycle: 1 + 10 * 0.003 + 100 * 0.003^2 / 2 = 1.03045 rad
2183    /// with fine interpolation, the setpoint 1 rad held without. Measured at 1 rad: following error 0.03045 rad and
2184    /// Kv 50 * 0.03045 = 1.5225 rad/s; the speed feedforward at 1.0 runs on to 10 + 100 * 0.003 = 10.3 rad/s.
2185    #[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        // At the profile cycle itself the two agree: nothing changes where the position and profile cycles are equal.
2198        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    /// A characteristic of (10 rad/s, 0.2 N m) and (100 rad/s, 0.3 N m): 5 rad/s gives 0.2 * 5 / 10 = 0.1 N m (from
2205    /// (0, 0)), -55 rad/s gives -(0.2 + 0.1 * 45 / 90) = -0.25 N m, 200 rad/s the last point's 0.3 N m, standstill 0.
2206    /// In the velocity loop it is the feedforward at the speed setpoint, 4 + 1000 * 1 ms = 5 rad/s: 0.1 N m, beside the
2207    /// rigid model's 0.3 N m.
2208    #[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    /// Balancing with 1 ms at a 1 ms position cycle: a setpoint step from 0 to 1 rad arrives as 1 - e^-1 = 0.632121 rad
2224    /// after one cycle and 1 - e^-2 = 0.864665 rad after two.
2225    #[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        // Half way between rated and no-load speed, half the torque is left for accelerating.
2252        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    /// effects.drive_current_limit: a drive of 5 A holds the 0.45 N m/A motor to 0.45 * 5 = 2.25 N m, below the
2269    /// motor's 3.8 N m, and its velocity loop stops integrating there; the current setpoint is then 2.25 / 0.45 = 5 A.
2270    /// A drive of 10.9 A would allow 4.905 N m: the motor's 3.8 N m stays the limit. With the motor's limit off the
2271    /// drive's still holds.
2272    #[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        // What the motor and drive can give, which "motor-peak" judges against, is the motor's.
2289        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        // The controller advances the time since the setpoints, a base step at a time (two per velocity cycle).
2300        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        // Kp = L / T cancels the winding's own time constant: after T = 0.25 ms (4 steps) the
2310        // current is at about 63 % of its 1 A setpoint, and it settles there without overshoot.
2311        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        // With Kp = L / T the open loop is 1 / (T s): crossover at 1 / T with 90 degrees of phase left. A dead
2326        // time d takes d / T rad of it, and holding the voltage for a cycle another half cycle's worth. The
2327        // loop is stable up to d = (pi / 2) T - dt / 2 = 0.36 ms, which is 5.8 cycles of 62.5 us.
2328        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        // The first cycle has nothing older to act; the second acts what the first computed.
2352        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        // A short thermal time constant, so the test runs in a moment: 0.5 s is 8000 current cycles.
2364        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        // The cold winding has less resistance and so less loss: the rise follows tau dT/dt = 100 (1 + 0.0039 T) / 1.39 - T,
2373        // which approaches 100 K with the time constant 1.39 tau. After one tau that is 100 (1 - exp(-1 / 1.39)) = 51.3 K.
2374        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        // The warm winding has 39 % more resistance and needs that much more voltage for the same current.
2378        assert!((late.voltage / (4.0 * p.rated_current) - 1.39).abs() < 0.005, "{} V", late.voltage);
2379        // Half the current: a quarter of the loss, less the resistance that did not rise as far. By hand:
2380        // q = 100 / 1.39 / 4 = 17.99 K, settled at q / (1 - 0.0039 q) = 19.34 K.
2381        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        // Switched off, the winding stays as it is.
2389        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        // At a tenth of the maximum current a hundredth of the loss.
2402        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    /// The 1FK2205-4AF of the catalogue: 6 N m at 4.7 A at standstill, 18 N m at its maximum current of 15.1 A.
2407    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    /// The current setpoint is the inverse of the saturation curve. Commanding the maximum torque takes the
2421    /// maximum current; with the setpoint at torque / kt it was 18 / 1.277 = 14.1 A, which gives 16.9 N m.
2422    #[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        // More than the motor has is limited to the maximum current.
2431        assert!((p.current_for(30.0) - 15.1).abs() < 1e-12 && (p.current_for(-30.0) + 15.1).abs() < 1e-12);
2432        // A drive that starts holding a load starts with the current that holds it.
2433        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        // A curve that loses more than a third of its torque constant turns down before the maximum current:
2438        // with 40 % at 1 / sqrt(3 * 0.4) = 0.913 of it. More current would give less torque, so that is the limit.
2439        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    /// With saturation the back-EMF constant falls with the torque constant. At the maximum current and
2445    /// 100 rad/s the winding needs R i + (18 / 15.1) * 100 = 60.4 + 119.2 V, and it draws the copper loss
2446    /// R i^2 = 912 W plus the shaft power 18 N m * 100 rad/s. With the back-EMF at kt w it drew 128 W more
2447    /// that went nowhere.
2448    #[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        // At 100 rad/s the same 1 A needs R i + ke w = 4 V + 45 V.
2468        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        // At 400 rad/s the back-EMF is 180 V of the 190 V bus: 10 V / 4 Ohm = 2.5 A is all that is left.
2474        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        // The integrator did not wind up meanwhile: with the setpoint gone the current is back within 2 ms.
2480        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        // Without the limit and without back-EMF the full current flows at any speed.
2486        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        // One count per velocity cycle reads as step / cycle, whatever the true speed is.
2507        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        // The bandwidth is the -3 dB width, as Siemens' f_3dB = 2 D f (damping D = 20 / 120): by hand, the edges of
2530        // (s² + w0²) / (s² + 2 D w0 s + w0²) are at 10 ± sqrt(10² + 60²) Hz, 50.83 and 70.83 Hz, gain 1 / sqrt 2.
2531        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    /// The velocity loop's torque limit follows the DC link's voltage of the moment (the field weakening test's motor, R
2549    /// left out, at 500 rad/s). The DC link 10 % low gives the winding 171 V of 190: on the current circle of 9.5 A,
2550    /// (225 + 20 i_d)^2 + (20 i_q)^2 = 171^2 is 50625 + 9000 i_d + 400 * 90.25 = 29241, i_d = -57484 / 9000 = -6.38711 A,
2551    /// i_q = sqrt(90.25 - 40.79522) = 7.03241 A, 0.45 * 7.03241 = 3.16459 N m (3.4451 N m at the full 190 V). Without
2552    /// field weakening the fade's speeds scale by 0.9, to 282.6 and 378 rad/s: at 330 rad/s 3.8 * 48 / 95.4 =
2553    /// 1.91195 N m where the full voltage gives 3.8 * 90 / 106 = 3.22642 N m.
2554    #[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            // An integrator far beyond the limit: the loop asks for more than it may give.
2559            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        // Without the DC link simulated the nominal voltage holds, whatever the drive's DC link field says.
2570        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    /// The test motor with field weakening: 4 pole pairs, L_d = L_q = 10 mH, and a winding resistance small enough to
2575    /// leave out of the hand calculation.
2576    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    /// effects.field_weakening against a hand calculation. At 500 rad/s the back-EMF is 0.45 * 500 = 225 V, above the
2585    /// 190 V the winding gets: without field weakening there is no torque (the fade ends at 420 rad/s). With it, w L =
2586    /// 4 * 500 * 0.010 = 20 Ohm on both axes, and R = 0, the voltage circle is (225 + 20 i_d)^2 + (20 i_q)^2 <= 190^2,
2587    /// the current circle i_q^2 + i_d^2 <= 9.5^2. i_q is largest where they cross: 225^2 + 9000 i_d + 400 * 9.5^2 = 190^2,
2588    /// i_d = -50625 / 9000 = -5.625 A, i_q = sqrt(90.25 - 31.640625) = 7.6557 A, 0.45 * 7.6557 = 3.4451 N m. The current
2589    /// loop gets there: the drive sets i_d = -5.625 A for that setpoint and the voltage vector sits on the circle.
2590    #[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        // Braking the same: with R = 0 the voltage circle does not depend on the sign of i_q. With R = 4 Ohm the back-EMF
2597        // is partly spent in the resistance while braking, and braking has more torque than motoring.
2598        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        // Below base speed field weakening changes nothing.
2604        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        // The RMS phase current is the hypotenuse of both: 9.5 A, the current circle.
2625        assert!((d.phase_current() - 9.5).abs() < 1e-3);
2626        // The winding's energy closes with the d axis: electrical power = copper loss + shaft power (steady, R = 0).
2627        assert!((d.power - d.copper_loss - d.shaft_power).abs() < 1e-3 * d.shaft_power, "{} W", d.power);
2628    }
2629
2630    /// Without field weakening the winding's reactance is in the steady voltage: (R i + kE w)^2 + (p w L i)^2 <= U^2,
2631    /// the test motor (kt = kE = 0.45, R = 4 Ohm, L = 10 mH, 4 pole pairs, U = 190 V). At 300 rad/s kE w = 135 V and
2632    /// p w L = 12 Ohm: 160 i^2 + 1080 i + 18225 - 36100 = 0, i = (-540 + sqrt(291600 + 160 * 17875)) / 160 = 7.7206 A,
2633    /// 3.474 N m (without the reactance (190 - 135) / 4 = 13.75 A, held at 9.5 A: 4.275 N m). At 330 rad/s 2.709 N m,
2634    /// at 360 rad/s 1.956 N m. The loop gets there and its voltage vector sits on the circle: u_q = 4 * 7.7206 + 135 =
2635    /// 165.88 V, u_d = -12 * 7.7206 = -92.65 V, |u| = 190 V, a phase amplitude of 190 * sqrt 2 / 3 = 89.57 V
2636    /// (`phase_voltage`: U_dc / sqrt 3 for the DC link 190 / sqrt(3/2)).
2637    #[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        // The time simulation at constant speed, asked for the peak torque, settles at the limit at each speed (0.25 s).
2656        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    /// With field weakening the phase current, i_q and i_d together, stays within the drive's maximum current. The test
2666    /// motor with R left out on a 5 A drive at 500 rad/s: the circles (225 + 20 i_d)^2 + (20 i_q)^2 = 190^2 and
2667    /// i_q^2 + i_d^2 = 25 cross at 50625 + 9000 i_d + 10000 = 36100, i_d = -2.725 A, i_q = sqrt(25 - 7.4256) = 4.1922 A,
2668    /// 0.45 * 4.1922 = 1.8865 N m (the q current alone held to 5 A gave 2.25 N m and a phase current of about 5.9 A).
2669    #[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    /// The current circle holds the q reference with the d reference, as a drive limits its current reference vector:
2682    /// i_q,ref <= sqrt(I_max^2 - i_d,ref^2), whatever d current is there; the currents follow through the loop. The test
2683    /// motor (4 pole pairs, R left out) on a 5 A drive, asked for 5 A of q current, its d current at -2 A, one current
2684    /// cycle. The q reference shows in the PI's integrator: Ki * cycle = 16000 * 62.5 us = 1, so it moves by the error.
2685    /// At standstill the d setpoint is 0 and the q reference the whole 5 A (from the d current, -2 + 0.2212 * 2 =
2686    /// -1.5576 A after the cycle's lag share 1 - exp(-1/4), it was sqrt(25 - 1.5576^2) = 4.7512 A). At 500 rad/s the d
2687    /// setpoint is the circles' crossing, -2.725 A, and the q reference 4.1922 A (from the d current,
2688    /// -2 - 0.2212 * 0.725 = -2.1604 A, it was 4.5092 A). The integrator starts at -50 V so that the q voltage stays
2689    /// inside the circle (an integrator held at the voltage limit shows nothing).
2690    #[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    /// Braking or motoring at the peak torque near the top speed does not run away. The audit's case, the T-shaped belt gantry's
2710    /// motor (this test motor with field weakening, 190 V) with saturation off, a step to -3.8 N m held at 400 and
2711    /// 420 rad/s, gave -19.1 N m at 42.5 A of phase current before the d axis was held within the voltage circle (commit
2712    /// 1d098351). Now, stepped from rest to +-3.8 N m and to the curve's two torques (the velocity loop's clamp left out)
2713    /// at 380 to 450 rad/s, saturation on and off, for 0.5 s: the torque stays within the peak 3.8 N m (the step overshoots
2714    /// by 0.06 %), the phase current within the motor's 9.5 A and the voltage vector within the 190 V circle at every
2715    /// step, and the torque settles at the command or, beyond the curve, at the curve (3.612, 3.470, 3.335, 3.145 N m
2716    /// motoring without saturation: a command above the curve took a d current filling the current circle and fell to
2717    /// nil before the d current was set for the most q current that fits).
2718    #[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                    // It settles at the command, or at the curve where the command is beyond it.
2735                    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    /// The magnets' flux with the thermal nodes is 1 at the rated state: the housing then stands at (1 - s) of the
2750    /// winding's rated rise, 0.75 * 100 K = 75 K for s = 0.25 (the winding's rise 100 K was what the flux compared).
2751    #[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    /// The d-q model on a motor Siemens publishes R, L, ke and the pole pairs of: the 1FK7042-2AF7 on S120
2766    /// (catalog/siemens/motors_s120.csv and motors_s120_electrical.csv), at the DC link of 600 V its data sheet holds
2767    /// for: kt = 3.0 N m / 2.2 A = 1.364 N m/A, R = 3 * 4.67 Ohm, L = 3 * 35 mH, 4 pole pairs, 7.6 A, 10.5 N m at most.
2768    ///
2769    /// The S1 and peak torque-speed curves Siemens prints only as graphs (in the data sheets and manuals, not in the
2770    /// catalogue files), so the points checked are those the catalogue has. The S1 point, 2.6 N m at the rated 2.0 A
2771    /// and 314.16 rad/s: the model gives kt * 2.0 A = 2.73 N m, 5 % above (the tolerance stated: 6 %, about the
2772    /// difference between the static and the rated torque constant, 1.364 against 1.3 N m/A), and needs no field weakening
2773    /// there: R i + kt w = 456.6 V and w L i = 263.9 V make 527 V of the sqrt(3/2) * 600 = 734.8 V. Without field weakening
2774    /// the torque is gone at 734.8 / 1.364 = 538.9 rad/s; Siemens gives the motor up to 670.2 rad/s on S120 (n_max,inv)
2775    /// and the model with field weakening still has torque there. Towards high speed the best d current tends to the
2776    /// characteristic current -psi / L_d = -kt / (p L_d) = -1.364 / (4 * 0.105) = -3.247 A.
2777    /// n_max,inv itself is where the motor's no-load voltage, sqrt(2) * 0.8594 V s/rad * 670.2 rad/s = 814.6 V peak line to
2778    /// line, reaches the 820 V at which the S120 trips: the speed above which field weakening must not be lost.
2779    #[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        // At 942.5 rad/s, the mechanical limit: the largest q current on both circles for each d current, by bisection
2802        // on the voltage, and the d current where it is largest, by stepping through them.
2803        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    /// effects.drive_overload against a hand calculation, with the 3 A S120 Motor Module: rated 3 A, base load 2.6 A,
2821    /// 9 A for 0.25 s from the rated load, and a thermal image of 10 s. The trip level is 9 - 8 exp(-0.025) = 1.19752.
2822    /// A cold drive asked for 6 A, twice its rated current, fills its image as 4 (1 - exp(-t / 10 s)): it reaches the
2823    /// trip after -10 s ln(1 - 1.19752 / 4) = 3.558 s, and holds 2.6 A from then. The image then falls towards
2824    /// (2.6 / 3)^2 = 0.7511 and is back at 1 after -10 s ln((1 - 0.7511) / (1.19752 - 0.7511)) = 5.842 s, when the drive
2825    /// gives the 6 A again.
2826    #[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        // The image passes the trip by up to a velocity cycle (125 us at 0.28 /s), worth 22 s per unit on the way down.
2859        assert!((released - clamped - 5.842).abs() < 3e-3, "released {} s later", released - clamped);
2860        // Off, nothing clamps.
2861        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    /// The image's peak when a cycle repeats (`analysis::repeating_peak`), by hand: 1.5 times the rated current held for
2871    /// a 1 s pass from a cold image settles at 2.25. Twice the rated current for 0.5 s and nothing for 0.5 s, tau 10 s:
2872    /// the repeating start is x0 = 4 (1 - e) e / (1 - e^2) with e = exp(-0.05), 1.95001, and the peak, at 0.5 s,
2873    /// x0 e + 4 (1 - e) = 2.04999, a little above the mean of (i / I)^2, 2.
2874    #[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    /// effects.motor_thermal_nodes against a hand calculation. The winding has a quarter of the resistance (s = 0.25) and
2899    /// 60 s against the housing; the motor 1800 s, as the one node. At a loss that the one node settles at 100 K the
2900    /// winding settles at P (R_w + R_h) = 100 K too and the housing at P R_h = 75 K. On the way, with
2901    /// k = 1800 - 60 / 0.25 = 1560 s, the matrix [[-1/60, 1/60], [1/(0.25 k), -(1/0.25 + 1/0.75)/k]] has the eigenvalues
2902    /// -7.36204e-4 and -1.934927e-2 1/s (1358 s and 51.7 s), and from cold the winding is at
2903    /// 100 - 81.5696 exp(-t / 1358.3 s) - 18.4304 exp(-t / 51.68 s): 16.18 K after 60 s (the one node: 3.28 K) and
2904    /// 78.32 K after 1800 s (the one node: 63.21 K).
2905    #[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        // 20 000 s: 81.6 K exp(-20000 / 1358) = 3e-5 K are left of the slow part.
2918        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        // The settled rise the verdicts judge is the winding's, and the same as the one node's.
2933        assert!((p.settled_rise(p.rated_current, 0.0) - 100.0).abs() < 1e-9);
2934        // A winding started warm starts with its housing settled for it.
2935        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    /// The voltage-limit torque of the d-q model against a hand calculation, for the 1FK2205-4AF as the catalogue puts it
2940    /// on a 400 V line: kt = 6 N m / 4.7 A = 1.27660 N m/A, R = 2 Ohm (the config's estimate), 4 pole pairs, L_d = L_q =
2941    /// kt^2 / (2 * 4 * 13 N m) = 15.670 mH from Siemens' maximum short-circuit braking torque (`catalog::apply_motor`),
2942    /// 15.1 A, and the DC link of 540 V: the winding gets sqrt(3/2) * 540 = 661.38 V. At 600 rad/s the back-EMF alone,
2943    /// 765.96 V, is above it: without a d current no torque (and the old fade from 314.16 to 518.07 rad/s none either).
2944    /// By hand, stepping i_d from 0 to -15.1 A in 0.1 mA and taking for each the largest i_q on both circles (the
2945    /// quadratic (R i_q + kt w + w L i_d)^2 + (R i_d - w L i_q)^2 = U^2 with w = 4 * 600): the best is i_d = -8.855 A,
2946    /// i_q = 12.2309 A, 15.614 N m. At 500 rad/s it is 17.818 N m where the fade gave 1.595 N m.
2947    #[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        // The drive's d current for that q current at 600 rad/s is the hand calculation's.
2970        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    /// The d axis follows its setpoint as the tuned current loop does: with Kp = 40 V/A and L_d = 10 mH the time constant
2975    /// is L_d / Kp = 0.25 ms, four current cycles of 62.5 us. At 500 rad/s the setpoint is -5.625 A (the field weakening
2976    /// test); unbounded, from 0 the d current would be -5.625 (1 - exp(-1)) = -3.5557 A after four cycles, and -5.625
2977    /// (1 - exp(-10)) after forty. Before 14 November 2026 it was at -5.625 A in the first. The d voltage is held within the
2978    /// 190 V circle (the q current is 0 here, so the steady d voltage is R i_d, nil): the first cycle's share
2979    /// e = 1 - exp(-1/4) = 0.22120 of 5.625 A asks for L_d e 5.625 / 62.5 us = 199.1 V, so it moves 190 V * 62.5 us / 10 mH
2980    /// = 1.1875 A; then 0.22120 of what is left each cycle (157 V, 122 V, 96 V, within it): -2.1692, -2.9336, -3.5289 A.
2981    #[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    /// The d current takes the winding warm as it is: at 500 rad/s with R = 4 Ohm cold and 5.56 Ohm 100 K warm, the
2998    /// voltage circle asks for more d current warm, and the drive sets that one.
2999    #[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    /// effects.iron_loss against a hand calculation. R = 4 Ohm, warm at the rated 100 K: 5.56 Ohm. Stall current 3 A and
3015    /// rated current 2.5 A: the iron loss at the rated speed is 5.56 * (9 - 6.25) = 15.29 W, and at a quarter of the speed
3016    /// 15.29 * 0.25^1.5 = 1.911 W. At the rated current and speed the winding settles at the rated 100 K, copper and iron
3017    /// together, as Siemens' rated data say; at the stall current at standstill too.
3018    #[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        // The one node integrated to its end: copper at the rated current with its resistance warm, and the iron loss.
3035        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        // Off, the rated current alone brings the winding to 100 K (the iron loss lumped in), as before.
3043        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    /// effects.magnet_temperature: the catalogue's torque constant holds at the rated rise; a cold motor (0 K) with
3048    /// -0.12 %/K has 1 + 0.0012 * 100 = 1.12 times its flux: 12 % more torque per amp, and back-EMF.
3049    #[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    /// The two-node overload image against a hand calculation, on the 3 A S120 Motor Module of the one-node test: 9 A for
3060    /// 0.25 s from the rated load, slow node 10 s, chips 30 % of the rise with 1 s. Trip level
3061    /// 9 - 8 (0.7 exp(-0.025) + 0.3 exp(-0.25)) = 1.66914. From the rated load held (image 1: 0.7 + 0.3), 6 A fill it as
3062    /// 4 - 3 (0.7 exp(-t / 10 s) + 0.3 exp(-t / 1 s)): by bisection it reaches the trip after 0.8203 s, where the one
3063    /// node (trip 1.19752, 4 - 3 exp(-t / 10 s)) takes 0.6811 s.
3064    #[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        // The drive: the image starts at the rated load, the torque asks for 6 A; it clamps to 2.6 A at the trip.
3081        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        // The current reaches 6 A within a few cycles, and the clamp comes at the velocity cycle after the trip.
3092        assert!((t - 0.8203).abs() < 2e-3, "clamps after {t} s");
3093    }
3094
3095    /// effects.braking_resistor_heating against a hand calculation: the S120 Braking Module's resistor (1.5 kW continuous,
3096    /// 100 kW peak for 1 s in 68 s), a time constant of 60 s and 200 K at the continuous power. A pulse of its peak power
3097    /// for 1 s from cold: 200 * 100 / 1.5 * (1 - exp(-1 / 60)) = 220.38 K; 67 s later, the rest of its cycle, 72.15 K.
3098    #[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        // Held at the continuous power it settles at the rated rise.
3114        assert!((r.rise_after(0.0, 1500.0, 1e6) - 200.0).abs() < 1e-9);
3115    }
3116
3117    /// A back-EMF constant of 0.5 V s/rad beside the torque constant 0.45 N m/A (R = 4 Ohm, winding limit 190 V, no
3118    /// reactance without pole pairs). The voltage left at 340 rad/s is 190 - 0.5 * 340 = 20 V, so i = 20 / 4 = 5 A and
3119    /// 0.45 * 5 = 2.25 N m (with kE = kt: 190 - 153 = 37 V, 9.25 A, 4.1625 N m). Holding 2 A (0.9 N m) at 100 rad/s the
3120    /// winding needs u = R i + kE w = 8 + 50 = 58 V and takes 116 W: copper 4 * 4 = 16 W, shaft 0.45 * 2 * 100 = 90 W, and
3121    /// (kE - kt) i w = 0.05 * 2 * 100 = 10 W is the loss row's. With equal constants that row is exactly 0.
3122    #[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(&params(), 0.0, 0.9, 0.0);
3134        d.current_loop(&params(), 100.0);
3135        assert_eq!(d.emf_loss, 0.0);
3136    }
3137
3138    /// The printed S1 curve (0, 2.0), (100, 1.5), (300, 0.5): linear between its points, the last beyond the last, the
3139    /// same both ways: at 200 rad/s 1.5 - 0.5 * 100 / 200 = 1.0 N m; one starting at 50 rad/s holds its first torque below.
3140    /// The config's arrays are read so (`s1_curve_of`), become the drive's `s1_torque`; empty ones are the straight line,
3141    /// and arrays of different lengths, falling speeds or a negative torque are refused.
3142    #[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    /// The S1 line from the static torque (the stall current's, 1.8 N m here) to the rated torque at the rated speed:
3170    /// at the rated speed 314 rad/s the rated 1.27 N m, halfway 1.535 N m, and flat at the rated torque without a static one.
3171    #[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    /// effects.iron_loss as a drag on the shaft. k_t 0.45 N m/A at the rated current 2.5 A gives 1.125 N m in the air gap;
3180    /// a printed rated torque of 1.0 N m and a shaft friction of 0.025 N m at the rated speed 314 rad/s leave the drag
3181    /// T_N = 0.1 N m there (P = 31.4 W), at a quarter of the speed 0.1 * sqrt(0.25) = 0.05 N m (P = 3.925 W = 31.4 / 8),
3182    /// odd in the speed and 0 at standstill. At the rated current the shaft gets 1.125 - 0.1 = 1.025 N m, the printed
3183    /// 1.0 N m once the friction has its 0.025. The winding takes u i = R i^2 + L i di/dt + air-gap power: with the drag in
3184    /// the shaft's power, electrical power = copper + stored + shaft + 31.4 W, the last being `emf_loss` (equal
3185    /// constants). The heat the winding feels stays the thermal data's R (I_0^2 - I_N^2) = 15.29 W (I_0 = 3 A, R = 4 Ohm
3186    /// warm at 100 K). A disabled drive turning at the rated speed: torque -0.1 N m, shaft power -31.4 W, `emf_loss` 31.4 W.
3187    #[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        // The same instant's rates: u i - R i^2 - L i di/dt - shaft power = the drag's power.
3207        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        // Held for a step through the winding: the budget row holds the drag's power; the heat signal the thermal one.
3210        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    /// The d current takes the drive's unsaturated back-EMF (`d_current_for`): q = 5 A at 500 rad/s, e = 0.45 * 500 =
3223    /// 225 V, w L_d = 20 Ohm, w L q = 100 V, R = 0: the circle (e + 20 d)^2 + 100^2 = 190^2 gives e + 20 d =
3224    /// sqrt(26100) = 161.5549 V, d = (161.5549 - 225) / 20 = -3.17225 A, with 20 % saturation as without (the winding's
3225    /// saturated 212.53 V would want -2.54898 A: the 0.623 A more is the reserve).
3226    #[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    /// Braking above e = U. R = 4 Ohm, kE = 0.45, p = 2, L = 10 mH, U = 190 V, 20 A allowed. At 450 rad/s e = 202.5 V
3236    /// and x = 2 * 450 * 0.01 = 9 Ohm, a = 16 + 81 = 97: (202.5 - 4 i)^2 + (9 i)^2 = 190^2 is 97 i^2 - 1620 i + 4906.25 = 0,
3237    /// i = (1620 +- sqrt(2624400 - 1903625)) / 194 = (1620 +- 848.985) / 194 = 12.7267 A or 3.9743 A: the interval
3238    /// of braking currents the voltage leaves, the diodes force the smaller one. (Before: (U + e) / R = 98 A.) At 500 rad/s
3239    /// (e = 225 V, x = 10, a = 116) the circle leaves none: the nearest current is R e / a = 7.7586 A, both ways. The
3240    /// current loop asked for no torque at 450 rad/s brakes with the forced current.
3241    #[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        // Below e = U nothing is forced.
3253        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    /// The linear fade's speeds at another voltage. R = 4 Ohm, kE = 0.45, no reactance, 9.5 A allowed, printed fade 314 to
3262    /// 420 rad/s at 190 V. Rated point: the voltage leaves (190 - 141.3) / 4 = 12.2 A, clamped to 9.5 A, which it holds
3263    /// up to (190 - 38) / 0.45 = 337.78 rad/s; at 152 V (0.8) up to (152 - 38) / 0.45 = 253.33: ratio 0.75, so 235.5 rad/s.
3264    /// No-load point: (190 - 189) / 4 = 0.25 A, left up to 420 rad/s; at 152 V (152 - 1) / 0.45 = 335.56 rad/s.
3265    /// At 300 rad/s the torque is 3.8 (335.56 - 300) / (335.56 - 235.5) = 1.3504 N m (at 190 V the full 3.8 N m).
3266    #[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    /// drive.overmodulation on a three-phase bridge: the winding's limit is 2 sqrt 3 / pi = 1.10266 times the space-vector
3276    /// one (six-step's fundamental 2 U / pi over U / sqrt 3). At 440 rad/s, e = 198 V, R = 4 Ohm, without reactance:
3277    /// (190 * 1.10266 - 198) / 4 = (209.505 - 198) / 4 = 2.87625 A, 0.45 times that = 1.29431 N m (sinusoidal: 190 < 198,
3278    /// none).
3279    #[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}