Skip to main content

sim_components/
induction.rs

1//! Induction motor on a frequency converter (motor.kind = "induction"): the standard d-q model, V/f control (open loop)
2//! or field-oriented control (rotor flux, under the drive's speed and position loops).
3//!
4//! The motor in a frame turning at the electrical speed w_k the converter sets (amplitude-invariant space vectors: a
5//! vector's length is a phase's amplitude), with stator and rotor flux as states, p pole pairs and the rotor's
6//! electrical speed w_r = p w:
7//!   dpsi_s/dt = u_s - R_s i_s - j w_k psi_s,   dpsi_r/dt = -R_r i_r - j (w_k - w_r) psi_r,
8//!   psi_s = L_s i_s + L_m i_r,   psi_r = L_m i_s + L_r i_r,   L_s = L_m + L_ss,  L_r = L_m + L_sr,
9//!   torque = 3/2 p (psi_s x i_s),   power 3/2 u_s . i_s,   copper loss 3/2 (R_s |i_s|^2 + R_r |i_r|^2).
10//! R_s is `motor.resistance_ohm` (a phase's, warming with effects.winding_heating), the rest the motor's own keys. The
11//! drive's `current` is the RMS phase current |i_s| / sqrt 2. The phase voltage's amplitude is at most U_dc / sqrt 3.
12//!
13//! V/f (`drive.induction_control = "vf"`): the frequency follows the speed setpoint, w_k = p w_set (plus the rated slip
14//! times the estimated torque over the rated torque with `drive.vf_slip_compensation`), the voltage rises with it from
15//! the boost `drive.vf_boost_v` at 0 Hz to the rated voltage at the rated frequency and stays there above (field
16//! weakening by itself). The rotor slips behind: the torque-slip curve of the equivalent circuit (Kloss).
17//!
18//! Field-oriented (`"foc"`): the drive models the rotor flux, dpsi/dt = (R_r / L_r) (L_m i_sd - psi), and turns its
19//! frame with it, w_k = w_r + R_r L_m i_sq / (L_r psi) (indirect: slip from the model). The flux setpoint is the rated
20//! one up to the rated frequency and falls with 1 / speed above (field weakening), and lower only where the converter's
21//! voltage U_dc / sqrt 3 and the current limit leave no room for the torque asked for at it (`control_flux`: the
22//! largest flux that does). The curve, the limit, takes the flux of the most torque, torque ~ psi i_q within the two
23//! circles (`flux_setpoint`); asked for the curve's torque the control sets that flux too, so that `torque_curve` is
24//! the torque the control delivers; the q current is held within what the flux leaves of the voltage circle
25//! (`voltage_iq`); torque = 3/2 p (L_m / L_r) psi i_sq.
26//! PI current controllers on i_sd and i_sq with the decoupling the model gives: sigma L_s di/dt = u - R_sigma i + ...,
27//! sigma = 1 - L_m^2 / (L_s L_r), R_sigma = R_s + (L_m / L_r)^2 R_r; tuned with Kp = sigma L_s / T and
28//! Tn = sigma L_s / R_sigma the current follows its setpoint with T. The speed and position loops above are the servo's.
29
30use crate::drive::{Drive, DriveParams, Phases};
31use sim_core::{Config, ConfigError};
32use std::f64::consts::{SQRT_2, TAU};
33
34type Result<T> = std::result::Result<T, ConfigError>;
35
36#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
37pub struct Induction {
38    pub pole_pairs: f64,
39    pub rotor_resistance: f64,
40    pub magnetizing: f64,
41    /// L_s and L_r, magnetizing plus leakage.
42    pub stator: f64,
43    pub rotor: f64,
44    /// Rated phase voltage's amplitude, rated electrical speed (2 pi f_N), rated slip's electrical speed.
45    pub rated_voltage: f64,
46    pub rated_frequency: f64,
47    pub rated_slip: f64,
48    /// Field-oriented control (`"foc"`), else V/f.
49    pub field_oriented: bool,
50    /// V/f: the boost's phase amplitude at 0 Hz, and whether the slip is compensated.
51    pub boost: f64,
52    pub slip_compensation: bool,
53    /// V/f slip compensation: the time constant of the filter on the estimated torque, s. `drive.slip_compensation_filter_s`;
54    /// absent, the rotor's own time constant L_r / R_r (the estimate then does not swing with the rotor).
55    pub slip_filter: f64,
56    /// The rotor flux at the rated voltage and frequency, unloaded: the field-oriented drive's setpoint.
57    pub rated_flux: f64,
58}
59
60/// Phase amplitude per line-to-line RMS voltage: sqrt 2 / sqrt 3.
61const PHASE_PER_LINE: f64 = 0.816_496_580_927_726;
62
63impl Induction {
64    pub fn from_config(cfg: &Config) -> Result<Self> {
65        let pole_pairs = cfg.positive("motor.pole_pairs")?;
66        let magnetizing = cfg.positive("motor.magnetizing_inductance_h")?;
67        let rated_frequency = TAU * cfg.positive("motor.rated_frequency_hz")?;
68        let field_oriented = match cfg.get("drive.induction_control").ok().and_then(|v| v.as_str()) {
69            Some("foc") => true,
70            Some("vf") => false,
71            _ => return Err(ConfigError::Invalid("drive.induction_control".into())),
72        };
73        // The name-plate speed against the synchronous one: the rated slip.
74        let rated_slip = rated_frequency - pole_pairs * cfg.positive("drive.rated_speed_rad_s")?;
75        if !(rated_slip > 0.0) {
76            return Err(ConfigError::Invalid("drive.rated_speed_rad_s".into()));
77        }
78        let mut m = Self {
79            pole_pairs,
80            rotor_resistance: cfg.positive("motor.rotor_resistance_ohm")?,
81            magnetizing,
82            stator: magnetizing + cfg.positive("motor.stator_leakage_inductance_h")?,
83            rotor: magnetizing + cfg.positive("motor.rotor_leakage_inductance_h")?,
84            rated_voltage: PHASE_PER_LINE * cfg.positive("motor.rated_voltage_v")?,
85            rated_frequency,
86            rated_slip,
87            field_oriented,
88            boost: PHASE_PER_LINE * cfg.non_negative("drive.vf_boost_v")?,
89            slip_compensation: cfg.bool("drive.vf_slip_compensation")?,
90            slip_filter: 0.0,
91            rated_flux: 0.0,
92        };
93        m.slip_filter = if cfg.get("drive.slip_compensation_filter_s").is_ok() {
94            cfg.positive("drive.slip_compensation_filter_s")?
95        } else {
96            m.rotor / m.rotor_resistance
97        };
98        let rs = cfg.positive("motor.resistance_ohm")?;
99        m.rated_flux = magnetizing * m.rated_voltage / rs.hypot(rated_frequency * m.stator);
100        Ok(m)
101    }
102
103    /// The model's currents from its fluxes [psi_sd, psi_sq, psi_rd, psi_rq]: (i_s, i_r) as [d, q].
104    pub fn currents(&self, x: &[f64; 4]) -> ([f64; 2], [f64; 2]) {
105        let (ls, lr, lm) = (self.stator, self.rotor, self.magnetizing);
106        let det = ls * lr - lm * lm;
107        let is = [(lr * x[0] - lm * x[2]) / det, (lr * x[1] - lm * x[3]) / det];
108        let ir = [(ls * x[2] - lm * x[0]) / det, (ls * x[3] - lm * x[1]) / det];
109        (is, ir)
110    }
111
112    /// The torque of the fluxes: 3/2 p (psi_s x i_s).
113    pub fn torque(&self, x: &[f64; 4]) -> f64 {
114        let (is, _) = self.currents(x);
115        1.5 * self.pole_pairs * (x[0] * is[1] - x[1] * is[0])
116    }
117
118    /// The magnetic energy, 3/4 (psi_s . i_s + psi_r . i_r).
119    pub fn stored_energy(&self, x: &[f64; 4]) -> f64 {
120        let (is, ir) = self.currents(x);
121        0.75 * (x[0] * is[0] + x[1] * is[1] + x[2] * ir[0] + x[3] * ir[1])
122    }
123
124    fn sigma_ls(&self) -> f64 {
125        self.stator - self.magnetizing * self.magnetizing / self.rotor
126    }
127
128    /// The highest phase amplitude the converter gives: U_dc / sqrt 3 (`Drive::max_voltage` is sqrt(3/2) U_dc).
129    fn supply(d: &Drive, p: &DriveParams) -> f64 {
130        d.max_voltage(p) / crate::drive::WINDING_PER_DC_LINK / 3f64.sqrt()
131    }
132
133    /// The flux setpoint at a shaft speed, for the stator resistance `rs`, the phase amplitude `supply` the converter has
134    /// and the phase current's amplitude limit `amplitude`: rated up to the rated frequency, then falling with 1 / speed
135    /// (field weakening by frequency), and, where the two circles leave more torque at a weaker flux, the flux of the most
136    /// torque. The torque is 3/2 p (L_m / L_r) psi i_q, so the flux psi maximises psi i_q(psi), i_q the most the current
137    /// circle (i_d = psi / L_m) and the voltage circle (`voltage_iq`, motoring) leave at it. That product rises and falls
138    /// once over the flux (a golden section finds its top); where the rated flux is the top (the voltage not binding, and
139    /// i_d at most the current's amplitude over sqrt 2) it is returned without a search.
140    fn flux_setpoint(&self, speed: f64, supply: f64, rs: f64, amplitude: f64) -> f64 {
141        let w_e = self.pole_pairs * speed.abs();
142        let cap = self.flux_cap(w_e);
143        let product = |flux: f64| self.torque_room(rs, supply, flux, w_e, true, amplitude);
144        let (i_d, limited) = (cap / self.magnetizing, self.iq_by_current(cap, amplitude));
145        if i_d * SQRT_2 <= amplitude && self.voltage_iq(rs, supply, cap, w_e, true, limited) >= limited {
146            return cap;
147        }
148        let g = 0.5 * (5f64.sqrt() - 1.0);
149        let (mut lo, mut hi) = (0.05 * cap, cap);
150        let (mut x1, mut x2) = (hi - g * (hi - lo), lo + g * (hi - lo));
151        let (mut f1, mut f2) = (product(x1), product(x2));
152        for _ in 0..28 {
153            if f1 < f2 {
154                (lo, x1, f1) = (x1, x2, f2);
155                x2 = lo + g * (hi - lo);
156                f2 = product(x2);
157            } else {
158                (hi, x2, f2) = (x2, x1, f1);
159                x1 = hi - g * (hi - lo);
160                f1 = product(x1);
161            }
162        }
163        if f1 >= f2 { x1 } else { x2 }
164    }
165
166    /// The rated flux up to the rated frequency, falling with 1 / the electrical speed `w_e` above it.
167    fn flux_cap(&self, w_e: f64) -> f64 {
168        self.rated_flux * (self.rated_frequency / w_e).min(1.0)
169    }
170
171    /// The q current's amplitude the current circle `amplitude` leaves at the flux `flux` (i_d = psi / L_m).
172    fn iq_by_current(&self, flux: f64, amplitude: f64) -> f64 {
173        (amplitude * amplitude - (flux / self.magnetizing).powi(2)).max(0.0).sqrt()
174    }
175
176    /// psi i_q at the flux `flux`, i_q the most both circles leave (motoring or generating): the torque over 3/2 p L_m / L_r.
177    fn torque_room(&self, rs: f64, supply: f64, flux: f64, w_r: f64, motoring: bool, amplitude: f64) -> f64 {
178        flux * self.voltage_iq(rs, supply, flux, w_r, motoring, self.iq_by_current(flux, amplitude))
179    }
180
181    /// The flux the control sets for the torque `torque` at a shaft speed: as a field-oriented drive does, the rated one
182    /// (`flux_cap` above the rated frequency) while the voltage and current circles leave room for that torque there, else
183    /// the largest weaker flux that does (between the cap and the flux of the most torque, psi i_q falls with the flux,
184    /// so a bracketed secant finds it). Beyond what any flux gives, the flux of the most torque, `flux_setpoint`: the
185    /// curve's flux, so that at the curve's torque the control and the curve meet.
186    fn control_flux(&self, torque: f64, speed: f64, supply: f64, rs: f64, amplitude: f64) -> f64 {
187        let w_e = self.pole_pairs * speed.abs();
188        let motoring = torque * speed >= 0.0;
189        let need = torque.abs() / (1.5 * self.pole_pairs * self.magnetizing / self.rotor);
190        let room = |flux: f64| self.torque_room(rs, supply, flux, w_e, motoring, amplitude);
191        let cap = self.flux_cap(w_e);
192        let at_cap = room(cap) - need;
193        if at_cap >= 0.0 {
194            return cap;
195        }
196        let top = self.flux_setpoint(speed, supply, rs, amplitude);
197        let at_top = room(top) - need;
198        if at_top <= 0.0 {
199            return top;
200        }
201        // The root of room - need between them, kept bracketed: the secant through the bracket's ends, the end kept twice
202        // in a row halved (Illinois): a handful of steps where a bisection took 30.
203        let (mut lo, mut hi, mut f_lo, mut f_hi, mut kept) = (top, cap, at_top, at_cap, 0);
204        for _ in 0..60 {
205            let x = (lo * f_hi - hi * f_lo) / (f_hi - f_lo);
206            let f = room(x) - need;
207            if f >= 0.0 {
208                (lo, f_lo) = (x, f);
209                if kept == 1 {
210                    f_hi *= 0.5;
211                }
212                kept = 1;
213            } else {
214                (hi, f_hi) = (x, f);
215                if kept == -1 {
216                    f_lo *= 0.5;
217                }
218                kept = -1;
219            }
220            // To 1e-10: the room's own rounding (`voltage_iq` to 1e-13 of the current) stops a tighter one short.
221            if f.abs() <= 1e-10 * need {
222                return x;
223            }
224            if hi - lo <= 1e-10 * cap {
225                break;
226            }
227        }
228        lo
229    }
230
231    /// The largest |i_q| up to `most` that the voltage circle `supply` leaves at the flux `flux` set (i_d = psi / L_m) in
232    /// the steady state at the rotor's electrical speed `w_r` >= 0, motoring (i_q with the speed) or generating. From the
233    /// model's steady voltage, with the frame at w_k = w_r + R_r (L_m / L_r) i_q / psi: u_d = R_s i_d - w_k sigma L_s i_q,
234    /// u_q = R_s i_q + w_k L_s i_d (psi_sd = L_s i_d). |u| rises with |i_q| here: Newton's method on |u|^2 = U^2, kept
235    /// within a bracket that a bisection step takes over from where Newton leaves it (a few steps instead of the 40 of a
236    /// bisection: the flux search calls this some thousand times per velocity cycle).
237    fn voltage_iq(&self, rs: f64, supply: f64, flux: f64, w_r: f64, motoring: bool, most: f64) -> f64 {
238        let (id, k, sl) = (flux / self.magnetizing, self.magnetizing / self.rotor, self.sigma_ls());
239        let s = if motoring { 1.0 } else { -1.0 };
240        let c = self.rotor_resistance * k / flux;
241        let limit = supply * supply;
242        // |u|^2 - U^2 and its derivative over m = |i_q|.
243        let f = |m: f64| {
244            let (iq, w_k) = (s * m, w_r + c * s * m);
245            let (ud, uq) = (rs * id - w_k * sl * iq, rs * iq + w_k * self.stator * id);
246            let (dud, duq) = (-sl * s * (c * s * m + w_k), rs * s + c * s * self.stator * id);
247            (ud * ud + uq * uq - limit, 2.0 * (ud * dud + uq * duq))
248        };
249        if f(most).0 <= 0.0 {
250            return most;
251        }
252        if f(0.0).0 > 0.0 {
253            return 0.0;
254        }
255        let (mut lo, mut hi, mut m) = (0.0, most, most);
256        for _ in 0..60 {
257            let (value, slope) = f(m);
258            if value <= 0.0 {
259                lo = m
260            } else {
261                hi = m
262            }
263            let newton = m - value / slope;
264            let next = if newton > lo && newton < hi { newton } else { 0.5 * (lo + hi) };
265            if (next - m).abs() <= 1e-13 * most || hi - lo <= 1e-13 * most {
266                break;
267            }
268            m = next;
269        }
270        // Within 1e-13 of the root, on either side of it.
271        m
272    }
273
274    /// The fluxes of a steady state in a frame turning at `w_k` with the rotor at the electrical speed `w_r`, under the
275    /// voltage `u` [d, q]: the equivalent circuit.
276    pub fn steady(&self, rs: f64, u: [f64; 2], w_k: f64, w_r: f64) -> [f64; 4] {
277        // In complex numbers: u = R_s i_s + j w_k psi_s, 0 = R_r i_r + j (w_k - w_r) psi_r.
278        // With psi = L i: u = (R_s + j w_k L_s) i_s + j w_k L_m i_r, 0 = j s L_m i_s + (R_r + j s L_r) i_r, s = w_k - w_r.
279        type C = (f64, f64);
280        let mul = |a: C, b: C| (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0);
281        let div = |a: C, b: C| {
282            let n = b.0 * b.0 + b.1 * b.1;
283            ((a.0 * b.0 + a.1 * b.1) / n, (a.1 * b.0 - a.0 * b.1) / n)
284        };
285        let s = w_k - w_r;
286        let (lm, ls, lr) = (self.magnetizing, self.stator, self.rotor);
287        // i_r = -j s L_m i_s / (R_r + j s L_r) = k i_s.
288        let k = div((0.0, -s * lm), (self.rotor_resistance, s * lr));
289        let z = mul((0.0, w_k * lm), k);
290        let z = (rs + z.0, w_k * ls + z.1);
291        let is = div((u[0], u[1]), z);
292        let ir = mul(k, is);
293        [ls * is.0 + lm * ir.0, ls * is.1 + lm * ir.1, lm * is.0 + lr * ir.0, lm * is.1 + lr * ir.1]
294    }
295
296    /// The breakdown torque at the electrical speed `w_e` with the phase amplitude `u`, from the equivalent circuit's
297    /// Thevenin form (R_s kept): 3/2 p / w_e U_th^2 / (2 (R_th + sqrt(R_th^2 + (X_th + X_sr)^2))).
298    pub fn breakdown(&self, rs: f64, u: f64, w_e: f64) -> f64 {
299        let (xm, xss, xsr) =
300            (w_e * self.magnetizing, w_e * (self.stator - self.magnetizing), w_e * (self.rotor - self.magnetizing));
301        let den = rs * rs + (xm + xss).powi(2);
302        let u_th2 = u * u * xm * xm / den;
303        // Z_th = j X_m (R_s + j X_ss) / (R_s + j (X_m + X_ss)).
304        let (r_th, x_th) = (rs * xm * xm / den, xm * (rs * rs + xss * (xm + xss)) / den);
305        1.5 * self.pole_pairs / w_e * u_th2 / (2.0 * (r_th + r_th.hypot(x_th + xsr)))
306    }
307
308    /// The V/f law: the phase amplitude at the electrical speed `w_k`.
309    fn vf_voltage(&self, w_k: f64) -> f64 {
310        self.boost + (self.rated_voltage - self.boost) * (w_k.abs() / self.rated_frequency).min(1.0)
311    }
312
313    /// The torque of the equivalent circuit's steady state (`steady`) under V/f at the stator frequency `w_s` with the rotor
314    /// at `w_r` (both electrical, signed), the converter's voltage `supply` at most.
315    fn vf_torque(&self, rs: f64, supply: f64, w_s: f64, w_r: f64) -> f64 {
316        let u = self.vf_voltage(w_s).min(supply);
317        self.torque(&self.steady(rs, [0.0, u], w_s, w_r))
318    }
319
320    /// (lowest, highest) torque at a speed with the DC link `dc_voltage`, as `DriveParams::torque_curve`: the breakdown
321    /// curve. V/f: the most the stator frequency can make of it, motoring (above the rotor's electrical speed) and
322    /// generating (below it) apart, each the maximum over the slip of the circuit's torque at the voltage V/f gives at
323    /// that frequency (`vf_extreme`): the breakdown torque at a fixed frequency is the one at the speed that frequency
324    /// belongs to only. Field-oriented the current limit at the flux the control sets (`flux_setpoint`), 3/2 p (L_m / L_r)
325    /// psi sqrt(I^2 - (psi / L_m)^2) for the amplitude I of the smaller of the motor's and the drive's maximum current,
326    /// within what the voltage circle leaves at that flux (`voltage_iq`), and the breakdown; and the peak torque.
327    pub fn torque_curve(&self, p: &DriveParams, speed: f64, dc_voltage: f64) -> (f64, f64) {
328        let w_e = (self.pole_pairs * speed.abs()).max(0.02 * self.rated_frequency);
329        let supply = dc_voltage / 3f64.sqrt();
330        let (motoring, generating) = if self.field_oriented {
331            let amplitude = SQRT_2 * p.max_current.min(p.drive_max_current);
332            let flux = self.flux_setpoint(speed, supply, p.resistance, amplitude);
333            let iq = (amplitude * amplitude - (flux / self.magnetizing).powi(2)).max(0.0).sqrt();
334            let w_r = self.pole_pairs * speed.abs();
335            let breakdown = self.breakdown(p.resistance, supply, w_e);
336            let torque = |motoring| {
337                let iq = self.voltage_iq(p.resistance, supply, flux, w_r, motoring, iq);
338                (1.5 * self.pole_pairs * self.magnetizing / self.rotor * flux * iq).min(breakdown)
339            };
340            (torque(true), torque(false))
341        } else {
342            let w_r = self.pole_pairs * speed.abs();
343            (self.vf_extreme(p.resistance, supply, w_r, true), self.vf_extreme(p.resistance, supply, w_r, false))
344        };
345        let (motoring, generating) = (motoring.min(p.peak_torque), generating.min(p.peak_torque));
346        if speed >= 0.0 { (-generating, motoring) } else { (-motoring, generating) }
347    }
348
349    /// V/f: the largest torque magnitude, motoring or generating, at the rotor's electrical speed `w_r` >= 0: the maximum
350    /// over the slip s = w_s - w_r (> 0 motoring, < 0 generating, the stator frequency down to and through 0 for
351    /// generating) of `vf_torque`. A scan over the slip, dense near 0, refined by golden section around its best.
352    fn vf_extreme(&self, rs: f64, supply: f64, w_r: f64, motoring: bool) -> f64 {
353        const N: usize = 96;
354        let span = 2.0 * (w_r + self.rated_frequency);
355        let sign = if motoring { 1.0 } else { -1.0 };
356        let at = |x: f64| {
357            // x in (0, 1]: the slip's magnitude span x^2; never exactly a stator frequency of 0.
358            let w_s = w_r + sign * span * x * x;
359            (sign * self.vf_torque(rs, supply, if w_s == 0.0 { 1e-6 } else { w_s }, w_r)).max(0.0)
360        };
361        let values: Vec<f64> = (1..=N).map(|n| at(n as f64 / N as f64)).collect();
362        let best = (0..N).max_by(|&a, &b| values[a].total_cmp(&values[b])).unwrap_or(0);
363        let (mut lo, mut hi) = ((best as f64) / N as f64, ((best + 2).min(N)) as f64 / N as f64);
364        let g = 0.5 * (5f64.sqrt() - 1.0);
365        let (mut x1, mut x2) = (hi - g * (hi - lo), lo + g * (hi - lo));
366        let (mut f1, mut f2) = (at(x1), at(x2));
367        for _ in 0..30 {
368            if f1 < f2 {
369                (lo, x1, f1) = (x1, x2, f2);
370                x2 = lo + g * (hi - lo);
371                f2 = at(x2);
372            } else {
373                (hi, x2, f2) = (x2, x1, f1);
374                x1 = hi - g * (hi - lo);
375                f1 = at(x1);
376            }
377        }
378        values[best].max(f1).max(f2)
379    }
380
381    /// The drive enabled: field-oriented, magnetized at the rated flux and giving `torque`, in the steady state at rest;
382    /// V/f unmagnetized (nothing flows until the converter puts out a voltage).
383    pub(crate) fn at_rest(&self, d: &mut Drive, p: &DriveParams, pos: f64, torque: f64) {
384        d.phases = Phases { angle: pos, ..Default::default() };
385        if !self.field_oriented {
386            (d.current, d.torque, d.torque_demand, d.torque_command) = (0.0, 0.0, 0.0, 0.0);
387            return;
388        }
389        let flux = self.rated_flux;
390        let (id, iq) =
391            (flux / self.magnetizing, torque / (1.5 * self.pole_pairs * self.magnetizing / self.rotor * flux));
392        let slip = self.rotor_resistance * self.magnetizing / self.rotor * iq / flux;
393        // The fluxes of that state: psi_r = flux on d, psi_s = sigma L_s i_s + (L_m / L_r) psi_r.
394        let k = self.magnetizing / self.rotor;
395        let x = [self.sigma_ls() * id + k * flux, self.sigma_ls() * iq, flux, 0.0];
396        let u = [p.resistance * id - slip * x[1], p.resistance * iq + slip * x[0]];
397        let ff = self.feedforward(slip, 0.0, [id, iq], flux);
398        d.phases.x = x;
399        d.phases.u = u;
400        d.phases.integral = [u[0] - ff[0], u[1] - ff[1]];
401        (d.phases.frame_speed, d.phases.estimate) = (slip, flux);
402        d.current = id.hypot(iq) / SQRT_2;
403    }
404
405    /// The decoupling the field-oriented current controllers add (see the module comment).
406    fn feedforward(&self, w_k: f64, w_r: f64, [id, iq]: [f64; 2], flux: f64) -> [f64; 2] {
407        let (sl, k) = (self.sigma_ls(), self.magnetizing / self.rotor);
408        [-w_k * sl * iq - k * self.rotor_resistance / self.rotor * flux, w_k * sl * id + k * w_r * flux]
409    }
410
411    /// The rates of the fluxes (`DriveParams::motor_rates`), [psi_sd, psi_sq, psi_rd, psi_rq] in slots 0, 4, 5, 6.
412    pub(crate) fn rates(&self, p: &DriveParams, d: &Drive, w: &[f64], speed: f64, out: &mut [f64]) -> f64 {
413        let x = [w[0], w[4], w[5], w[6]];
414        let (is, ir) = self.currents(&x);
415        let (u, w_k, rs, rr) = (d.phases.u, d.phases.frame_speed, d.winding_resistance(p), self.rotor_resistance);
416        let slip = w_k - self.pole_pairs * speed;
417        out[0] = u[0] - rs * is[0] + w_k * x[1];
418        out[4] = u[1] - rs * is[1] - w_k * x[0];
419        out[5] = -rr * ir[0] + slip * x[3];
420        out[6] = -rr * ir[1] - slip * x[2];
421        let torque = 1.5 * self.pole_pairs * (x[0] * is[1] - x[1] * is[0]);
422        out[1] = 1.5 * (u[0] * is[0] + u[1] * is[1]);
423        out[2] = 1.5 * (rs * (is[0] * is[0] + is[1] * is[1]) + rr * (ir[0] * ir[0] + ir[1] * ir[1]));
424        out[3] = torque * speed;
425        torque
426    }
427
428    /// One base step of the converter, with the speed the drive measured.
429    pub(crate) fn control(&self, d: &mut Drive, p: &DriveParams, speed: f64) {
430        let dt = p.current_cycle;
431        let supply = Self::supply(d, p);
432        let rs = d.winding_resistance(p);
433        let imax = p.overload.as_ref().filter(|_| d.overloaded).map_or(f64::INFINITY, |o| o.base_current);
434        let (is, _) = self.currents(&d.phases.x);
435        d.iron_loss = 0.0;
436        if !self.field_oriented {
437            // Slip compensation from the torque the converter estimates from its own power: the air gap's, (3/2 u . i
438            // less the stator's copper loss) over the frequency's synchronous speed.
439            let ph = &mut d.phases;
440            let synchronous = self.pole_pairs * d.speed_command;
441            let compensation =
442                if self.slip_compensation { self.rated_slip * ph.estimate / p.rated_torque } else { 0.0 };
443            let w_k = synchronous + compensation.copysign(synchronous);
444            let u = self.vf_voltage(w_k).min(supply);
445            ph.u = [0.0, u];
446            ph.frame_speed = w_k;
447            d.voltage = u;
448            return;
449        }
450        let ph = &mut d.phases;
451        let k = self.magnetizing / self.rotor;
452        // The drive's flux model, exact over the step for the d current held.
453        let tau = self.rotor / self.rotor_resistance;
454        let target = self.magnetizing * is[0];
455        ph.estimate = target + (ph.estimate - target) * (-dt / tau).exp();
456        let flux = ph.estimate.max(1e-3 * self.rated_flux);
457        let w_r = self.pole_pairs * speed;
458        ph.frame_speed = w_r + self.rotor_resistance * k * is[1] / flux;
459        // Setpoints: the flux's d current (rated, weakened only where the voltage runs out at the torque asked for,
460        // `control_flux`), the torque's q current, within the current limit (the drive's base load current while it is
461        // overloaded) and the voltage circle at that flux, motoring and generating apart; at the curve's torque the flux
462        // is the curve's (`torque_curve`).
463        let amplitude = SQRT_2 * p.max_current.min(p.drive_max_current).min(imax);
464        let flux_set = self.control_flux(d.torque_command, speed, supply, rs, amplitude);
465        let id_set = (flux_set / self.magnetizing).min(amplitude);
466        let iq_most = (amplitude * amplitude - id_set * id_set).max(0.0).sqrt();
467        let by_voltage = |motoring| self.voltage_iq(rs, supply, flux_set, w_r.abs(), motoring, iq_most);
468        let (with_speed, against_speed) = (by_voltage(true), by_voltage(false));
469        let (iq_high, iq_low) = if w_r >= 0.0 { (with_speed, against_speed) } else { (against_speed, with_speed) };
470        let iq_set = (d.torque_command / (1.5 * self.pole_pairs * k * flux)).clamp(-iq_low, iq_high);
471        let ff = self.feedforward(ph.frame_speed, w_r, is, flux);
472        let error = [id_set - is[0], iq_set - is[1]];
473        let wanted = [0, 1].map(|n| p.current_kp * error[n] + ph.integral[n] + ff[n]);
474        // Within the voltage circle, the d axis first.
475        let ud = wanted[0].clamp(-supply, supply);
476        let room = (supply * supply - ud * ud).max(0.0).sqrt();
477        let uq = wanted[1].clamp(-room, room);
478        for (n, u) in [ud, uq].into_iter().enumerate() {
479            if u == wanted[n] {
480                ph.integral[n] += p.current_ki * error[n] * dt;
481            }
482        }
483        ph.u = [ud, uq];
484        d.voltage = ud.hypot(uq);
485    }
486
487    /// The step done: the RMS phase current and the torque. V/f: the torque is what the drive gave, and its estimate for
488    /// the slip compensation.
489    pub(crate) fn stepped(&self, d: &mut Drive, p: &DriveParams) {
490        let x = d.phases.x;
491        let (is, _) = self.currents(&x);
492        d.current = is[0].hypot(is[1]) / SQRT_2;
493        d.torque = self.torque(&x);
494        if !self.field_oriented {
495            (d.torque_demand, d.torque_command) = (d.torque, d.torque);
496            let (u, w_k) = (d.phases.u, d.phases.frame_speed);
497            let air_gap =
498                1.5 * (u[0] * is[0] + u[1] * is[1]) - 1.5 * d.winding_resistance(p) * (is[0] * is[0] + is[1] * is[1]);
499            let raw = if w_k.abs() > 1e-6 { self.pole_pairs * air_gap / w_k } else { 0.0 };
500            // Filtered (unfiltered the compensation rang at a few hertz): first order, exactly per step.
501            let share = 1.0 - (-p.current_cycle / self.slip_filter).exp();
502            d.phases.estimate += share * (raw - d.phases.estimate);
503        }
504    }
505
506    /// The copper loss at the rated point of the name plate, from the equivalent circuit at the rated voltage, frequency
507    /// and slip, with the stator at `resistance` (warm): what brings the motor to its rated rise.
508    pub fn rated_copper_loss(&self, resistance: f64) -> f64 {
509        let w = self.rated_frequency;
510        let x = self.steady(resistance, [0.0, self.rated_voltage], w, w - self.rated_slip);
511        let (is, ir) = self.currents(&x);
512        1.5 * (resistance * (is[0] * is[0] + is[1] * is[1]) + self.rotor_resistance * (ir[0] * ir[0] + ir[1] * ir[1]))
513    }
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519    use crate::drive::{Motor, WINDING_PER_DC_LINK, WINDING_STATES};
520    use sim_core::Rk4;
521
522    /// A four-pole 1.5 kW motor of round numbers on 400 V, 50 Hz, 1440 rpm: R_s = 4.5 Ohm, R_r = 3.5 Ohm, L_m = 0.45 H,
523    /// both leakages 0.02 H; on a 600 V DC link (the 400 V line's peak, 565.7 V, and some). Field-oriented with T = 0.5 ms: sigma L_s = 0.47 - 0.45^2 / 0.47 =
524    /// 0.039149 H, Kp = 78.30 V/A, R_sigma = 4.5 + (0.45 / 0.47)^2 3.5 = 7.7085 Ohm, Tn = 5.0787 ms.
525    fn params(field_oriented: bool, rs: f64) -> DriveParams {
526        let mut m = Induction {
527            pole_pairs: 2.0,
528            rotor_resistance: 3.5,
529            magnetizing: 0.45,
530            stator: 0.47,
531            rotor: 0.47,
532            rated_voltage: PHASE_PER_LINE * 400.0,
533            rated_frequency: TAU * 50.0,
534            rated_slip: TAU * 50.0 - 2.0 * 1440.0 * TAU / 60.0,
535            field_oriented,
536            boost: 0.0,
537            slip_compensation: false,
538            slip_filter: 0.47 / 3.5,
539            rated_flux: 0.0,
540        };
541        m.rated_flux = m.magnetizing * m.rated_voltage / rs.hypot(m.rated_frequency * m.stator);
542        let kp = 0.039149 / 0.5e-3;
543        DriveParams {
544            resistance: rs,
545            heating: false,
546            dc_link: false,
547            bus_voltage: 600.0,
548            max_voltage: WINDING_PER_DC_LINK * 600.0,
549            current_kp: kp,
550            current_ki: kp / 5.0787e-3,
551            current_cycle: 62.5e-6,
552            max_current: 10.0,
553            drive_max_current: f64::INFINITY,
554            rated_torque: 10.0,
555            peak_torque: 30.0,
556            motor: Motor::Induction(m),
557            ..crate::drive::tests::params()
558        }
559    }
560
561    fn motor(p: &DriveParams) -> &Induction {
562        let Motor::Induction(m) = &p.motor else { unreachable!() };
563        m
564    }
565
566    /// The motor on an inertia `j` (infinite: the rotor held at `speed`) against `load(t)`, its converter stepped every
567    /// base step with `command(t, drive)` setting what it follows; integrated as `Sim::step` does. Returns per base
568    /// step (time, speed, torque, |rotor flux|).
569    fn run(
570        p: &DriveParams,
571        d: &mut Drive,
572        j: f64,
573        mut speed: f64,
574        load: impl Fn(f64) -> f64,
575        command: impl Fn(f64, &mut Drive),
576        seconds: f64,
577    ) -> Vec<[f64; 4]> {
578        let m = motor(p);
579        let dt = p.current_cycle;
580        let mut rk = Rk4::new(2 + WINDING_STATES);
581        let mut angle = 0.0;
582        let mut out = Vec::new();
583        for n in 0..(seconds / dt).round() as usize {
584            let t = n as f64 * dt;
585            command(t, d);
586            m.control(d, p, speed);
587            let mut y = vec![angle, speed];
588            y.extend(d.winding_states(p));
589            let tl = load(t);
590            rk.step(
591                |y, dy| {
592                    let torque = p.motor_rates(d, &y[2..], y[0], y[1], &mut dy[2..]);
593                    dy[0] = y[1];
594                    dy[1] = if j.is_finite() { (torque - tl) / j } else { 0.0 };
595                },
596                &mut y,
597                dt,
598            );
599            (angle, speed) = (y[0], y[1]);
600            let w = &y[2..];
601            (d.phases.x, d.phases.angle, d.phases.speed) = ([w[0], w[4], w[5], w[6]], angle, speed);
602            d.winding_stepped(p, w[0], [w[1], w[2], w[3]]);
603            out.push([t + dt, speed, d.torque, d.phases.x[2].hypot(d.phases.x[3])]);
604        }
605        out
606    }
607
608    /// Steady torque under V/f at rated voltage and frequency with the rotor held at `speed`: from the equivalent circuit's
609    /// fluxes (`steady`), which the integration then keeps (without R_s nothing damps the stator flux's transient).
610    fn steady_torque(p: &DriveParams, speed: f64) -> f64 {
611        let m = motor(p);
612        let mut d = Drive::at_rest(p, 0.0, 0.0, 0.0);
613        d.phases.x = m.steady(p.resistance, [0.0, m.rated_voltage], m.rated_frequency, m.pole_pairs * speed);
614        d.phases.frame_speed = m.rated_frequency;
615        let trace = run(p, &mut d, f64::INFINITY, speed, |_| 0.0, |_, d| d.speed_command = 50.0 * TAU / 2.0, 0.5);
616        trace.last().unwrap()[2]
617    }
618
619    /// The name plate by hand: 50 Hz on two pole pairs turn the field at 50 * 60 / 2 = 1500 rpm (157.08 rad/s); 1440 rpm
620    /// is a slip of (1500 - 1440) / 1500 = 4 %.
621    #[test]
622    fn synchronous_speed_and_rated_slip_come_from_the_name_plate() {
623        let p = params(false, 4.5);
624        let m = motor(&p);
625        assert!((m.rated_frequency / m.pole_pairs - 157.0796).abs() < 1e-4);
626        assert!((m.rated_slip / m.rated_frequency - 0.04).abs() < 1e-12);
627        // The model at the rated slip gives about the rated torque, 1.5 kW / 150.80 rad/s = 9.95 N m: within 10 % (the
628        // equivalent circuit is round numbers, not fitted to it).
629        let torque = steady_torque(&p, 1440.0 * TAU / 60.0);
630        assert!((torque - 9.95).abs() < 1.0, "{torque} N m");
631    }
632
633    /// Kloss by hand, with R_s = 0, where it is exact: the Thevenin source U_th = U X_m / (X_m + X_ss) = 326.60 * 141.37 /
634    /// 147.65 = 312.71 V, X_th = X_ss X_m / (X_m + X_ss) = 6.2832 * 141.37 / 147.65 = 6.0159 Ohm; breakdown slip
635    /// s_b = R_r / (X_th + X_sr) = 3.5 / 12.299 = 0.28457 and torque T_b = 3/2 p U_th^2 / (2 w (X_th + X_sr)) = 3 *
636    /// 312.71^2 / (2 * 314.16 * 12.299) = 37.97 N m; T = 2 T_b / (s / s_b + s_b / s). The model's steady torque at three
637    /// slips meets it. With R_s = 4.5 Ohm the Thevenin source has R_th = R_s X_m^2 / (R_s^2 + X_s^2) = 4.121 Ohm,
638    /// X_th = 6.141 Ohm and U_th = 312.55 V, and the breakdown torque 3/2 p / w U_th^2 / (2 (R_th + |R_th + j (X_th + X_sr)|))
639    /// = 0.0095493 * 97690.6 / (2 * (4.121 + 13.090)) = 27.10 N m (`breakdown`): Kloss's formula without R_s overstates it
640    /// by 40 %. The simplification holds for large motors, whose R_s is small against their reactances.
641    #[test]
642    fn the_torque_slip_curve_is_kloss_and_the_breakdown_is_the_equivalent_circuits() {
643        let p = params(false, 0.0);
644        let (tb, sb) = (37.97, 0.28457);
645        let w_sync = 157.0796;
646        for s in [0.02, sb, 0.6] {
647            let kloss = 2.0 * tb / (s / sb + sb / s);
648            let torque = steady_torque(&p, (1.0 - s) * w_sync);
649            assert!((torque / kloss - 1.0).abs() < 2e-3, "at s = {s}: {torque} N m against {kloss}");
650        }
651        let m = motor(&p);
652        assert!((m.breakdown(0.0, m.rated_voltage, TAU * 50.0) / tb - 1.0).abs() < 1e-3);
653        // With the stator's resistance: the curve's top, found by slips, is the Thevenin form's.
654        let p = params(false, 4.5);
655        let m = motor(&p);
656        let by_formula = m.breakdown(4.5, m.rated_voltage, TAU * 50.0);
657        assert!((by_formula - 27.10).abs() < 0.01, "{by_formula}");
658        let top = [0.2, 0.22, 0.24, 0.26, 0.28]
659            .map(|s| steady_torque(&p, (1.0 - s) * w_sync))
660            .into_iter()
661            .fold(0.0, f64::max);
662        assert!(top <= by_formula * 1.002 && top > 0.995 * by_formula, "{top} against {by_formula}");
663    }
664
665    /// Starting current by hand: rotor held, rated voltage and frequency. Z = R_s + j X_ss + j X_m || (R_r + j X_sr) with
666    /// X_m || (3.5 + j 6.2832) = (3.2071 + j 6.1047) Ohm, so Z = (7.7071 + j 12.388) Ohm, |Z| = 14.590 Ohm, and the
667    /// amplitude 326.60 / 14.590 = 22.385 A, 15.83 A RMS: 4.8 times the 3.3 A of the name plate.
668    #[test]
669    fn the_starting_current_is_the_equivalent_circuits() {
670        let p = params(false, 4.5);
671        let mut d = Drive::at_rest(&p, 0.0, 0.0, 0.0);
672        run(&p, &mut d, f64::INFINITY, 0.0, |_| 0.0, |_, d| d.speed_command = 157.0796, 1.0);
673        assert!((d.current / (22.385 / SQRT_2) - 1.0).abs() < 2e-3, "{} A", d.current);
674    }
675
676    /// Under V/f a load step of 5 N m at 50 Hz slows the rotor by the slip it needs: T = 3/2 p psi_r^2 w_slip / R_r
677    /// (steady, exact), so w_slip = 2 * 3.5 * 5 / (3 * 2 * 0.9950^2) = 5.894 rad/s electrical, 2.947 rad/s at the shaft,
678    /// with the rated flux psi_r = L_m U / |R_s + j w L_s| = 0.45 * 326.60 / 147.72 = 0.9950 Wb (unloaded; the load lowers
679    /// it by a few per cent, hence 6 %). With slip compensation the converter raises the frequency by the rated slip times
680    /// the torque over the rated one, 12.566 * 5 / 10 = 6.283 rad/s, and the shaft keeps its speed within 0.4 rad/s.
681    #[test]
682    fn under_v_f_a_load_step_costs_the_hand_calculated_slip() {
683        let drop = |compensated: bool| {
684            let mut p = params(false, 4.5);
685            if let Motor::Induction(m) = &mut p.motor {
686                m.slip_compensation = compensated;
687            }
688            let mut d = Drive::at_rest(&p, 0.0, 0.0, 0.0);
689            let load = |t: f64| if t > 1.5 { 5.0 } else { 0.0 };
690            let trace = run(&p, &mut d, 0.05, 157.0796, load, |_, d| d.speed_command = 157.0796, 3.0);
691            let at = |t: f64| trace[(t / p.current_cycle) as usize - 1][1];
692            at(1.5) - at(3.0)
693        };
694        let plain = drop(false);
695        assert!((plain / 2.947 - 1.0).abs() < 0.06, "{plain} rad/s");
696        let compensated = drop(true);
697        assert!(compensated.abs() < 0.4, "{compensated} rad/s");
698    }
699
700    /// The field-oriented curve on a 540 V link (phase amplitude 540 / sqrt 3 = 311.77 V, the 400 V plate needs 326.6 V)
701    /// is the torque the voltage leaves at the flux the control sets, the flux of the most torque. At the rated flux
702    /// 0.99488 Wb (i_d = 2.2108 A) the circle leaves 23.05 N m at 115 rad/s (w = 230 rad/s): i_q = 23.05 / (3 * 0.957447 *
703    /// 0.99488) = 8.066 A, slip 3.5 * 0.957447 * 8.066 / 0.99488 = 27.17 rad/s, w_k = 257.17: u_d = 4.5 * 2.2108 - 257.17 *
704    /// 0.039149 * 8.066 = -71.26 V, u_q = 4.5 * 8.066 + 257.17 * 0.47 * 2.2108 = 303.5 V, |u| = 311.8 V. A weaker flux gives
705    /// more: at 0.7743 Wb (i_d = 1.7207 A) i_q = 12.27 A (inside the current circle's sqrt(200 - 2.96) = 14.04 A), w_k =
706    /// 230 + 3.5 * 0.957447 * 12.27 / 0.7743 = 283.1, u_d = 4.5 * 1.7207 - 283.1 * 0.039149 * 12.27 = -128.3 V, u_q =
707    /// 4.5 * 12.27 + 283.1 * 0.47 * 1.7207 = 284.2 V, |u| = 311.8 V again, torque 3 * 0.957447 * 0.7743 * 12.27 = 27.29 N m
708    /// (a scan of the flux finds no more). At 140 rad/s the rated flux leaves 7.24 N m and 0.6499 Wb 20.68 N m. At 60 rad/s
709    /// the current circle alone binds: the rated flux stays.
710    #[test]
711    fn the_field_oriented_curve_follows_the_voltage_the_link_leaves() {
712        let p = params(true, 4.5);
713        let m = motor(&p);
714        let supply = 540.0 / 3f64.sqrt();
715        let high = m.torque_curve(&p, 115.0, 540.0).1;
716        assert!((high - 27.29).abs() < 0.3, "{high} N m");
717        let high = m.torque_curve(&p, 140.0, 540.0).1;
718        assert!((high - 20.68).abs() < 0.3, "{high} N m");
719        let amplitude = SQRT_2 * 10.0;
720        let flux = m.flux_setpoint(115.0, supply, 4.5, amplitude);
721        assert!((flux - 0.7743).abs() < 0.005, "{flux} Wb");
722        assert!((m.flux_setpoint(140.0, supply, 4.5, amplitude) - 0.6499).abs() < 0.005);
723        assert_eq!(m.flux_setpoint(60.0, supply, 4.5, amplitude), m.rated_flux);
724    }
725
726    /// The flux set is the top of psi i_q(psi): no flux of a fine grid up to the rated one (or the field-weakened cap) leaves
727    /// more of the product, at speeds with the voltage binding, on both links, and with a smaller drive current (a 6 A
728    /// drive, amplitude 8.485 A).
729    #[test]
730    fn the_flux_setpoint_is_the_flux_of_the_most_torque() {
731        let p = params(true, 4.5);
732        let m = motor(&p);
733        for (speed, link, amplitude) in
734            [(115.0, 540.0, 14.14), (140.0, 540.0, 14.14), (200.0, 600.0, 14.14), (130.0, 540.0, 8.485)]
735        {
736            let supply = link / 3f64.sqrt();
737            let w_e = m.pole_pairs * speed;
738            let cap = m.rated_flux * (m.rated_frequency / w_e).min(1.0);
739            let product = |flux: f64| {
740                let most = (amplitude * amplitude - (flux / m.magnetizing).powi(2)).max(0.0).sqrt();
741                flux * m.voltage_iq(4.5, supply, flux, w_e, true, most)
742            };
743            let set = m.flux_setpoint(speed, supply, 4.5, amplitude);
744            let best = (1..=2000).map(|n| product(cap * n as f64 / 2000.0)).fold(0.0, f64::max);
745            let got = product(set);
746            assert!(set <= cap && got >= best * (1.0 - 1e-4), "{speed} rad/s: {set} Wb, {got} against {best}");
747        }
748    }
749
750    /// V/f at fixed voltage and frequency, by the Thevenin form: the circuit's torque at the breakdown slip s_b = R_r /
751    /// sqrt(R_th^2 + (X_th + X_sr)^2) is `breakdown` (R_s = 4.5 Ohm at 50 Hz, 326.60 V: R_th = 4.121 Ohm, X_th + X_sr =
752    /// 6.141 + 6.283 = 12.424 Ohm, s_b = 3.5 / 13.09 = 0.2674 rad/s per rad/s, 84.0 rad/s of the 314.16), 27.10 N m. With the
753    /// rotor at w_r = 314.16 - 84.0 = 230.2 rad/s electrical the stator frequency of 50 Hz is one candidate of the V/f scan
754    /// (`vf_extreme`), so the scan's top is at least that breakdown; and it is the top of a dense sweep of the stator
755    /// frequency (20000 points) within the scan's refinement, 1e-3.
756    #[test]
757    fn the_v_f_scan_agrees_with_the_thevenin_breakdown_and_a_dense_sweep() {
758        let p = params(false, 4.5);
759        let m = motor(&p);
760        let (w_s, rs, u) = (m.rated_frequency, 4.5, m.rated_voltage);
761        let (xm, xss, xsr) = (w_s * m.magnetizing, w_s * (m.stator - m.magnetizing), w_s * (m.rotor - m.magnetizing));
762        let den = rs * rs + (xm + xss).powi(2);
763        let (r_th, x_th) = (rs * xm * xm / den, xm * (rs * rs + xss * (xm + xss)) / den);
764        let slip = w_s * m.rotor_resistance / r_th.hypot(x_th + xsr);
765        let breakdown = m.breakdown(rs, u, w_s);
766        assert!((m.vf_torque(rs, 1e9, w_s, w_s - slip) / breakdown - 1.0).abs() < 1e-6, "{slip}");
767        let w_r = w_s - slip;
768        let scan = m.vf_extreme(rs, 1e9, w_r, true);
769        assert!(scan >= breakdown * (1.0 - 1e-3), "{scan} against {breakdown}");
770        let dense = (1..=20_000)
771            .map(|n| m.vf_torque(rs, 1e9, w_r + 4.0 * m.rated_frequency * n as f64 / 20_000.0, w_r))
772            .fold(0.0, f64::max);
773        assert!((scan / dense - 1.0).abs() < 1e-3 && scan >= dense * (1.0 - 1e-3), "{scan} against {dense}");
774    }
775
776    /// The drive's current limit is the converter's, not a servo's torque constant: a 6 A drive (RMS, amplitude 8.485 A)
777    /// at 50 rad/s holds i_d = 0.99488 / 0.45 = 2.2108 A and i_q = sqrt(72 - 4.888) = 8.192 A, 3 * 0.957447 * 0.99488 *
778    /// 8.192 = 23.41 N m, where the servo constant (3.0 N m/A here) clamped at 18.0 N m.
779    #[test]
780    fn the_drive_current_limit_of_an_induction_motor_is_its_own_currents_torque() {
781        let p = DriveParams { drive_max_current: 6.0, kt: 3.0, ..params(true, 4.5) };
782        let high = p.torque_range_at(50.0, p.max_voltage).1;
783        assert!((high - 23.41).abs() < 0.1, "{high} N m");
784    }
785
786    /// V/f at low speed: the stator frequency runs ahead of the rotor, not at it. At 10 rad/s (w = 20 rad/s) the most the
787    /// circuit makes of the V/f voltage over the slip is 17.949 N m at a stator frequency of 198.3 rad/s (the old curve,
788    /// the breakdown at the frequency of the rotor, 7.79 N m): at 20 rad/s the voltage is 326.6 * 20 / 314.16 = 20.8 V,
789    /// little for the 4.5 Ohm stator, and more slip means more voltage with it. At 25 rad/s 19.552 N m (at 199.4 rad/s).
790    /// The figures are a sweep of 200 000 stator frequencies (w_r up to w_r + 4 w_N, no boost, as here) through the
791    /// per-phase circuit R_s + j w L_ss + j w L_m || (R_r w / (w - w_r) + j w L_sr), torque 3/2 p |i_r|^2 R_r / (s w), written
792    /// apart from `steady` (it gives the same to 1e-9); the audit's 18.88 and 20.53 N m were not the circuit's maximum.
793    #[test]
794    fn the_v_f_curve_is_the_maximum_over_the_slip() {
795        let p = params(false, 4.5);
796        let (low, high) = motor(&p).torque_curve(&p, 10.0, 540.0);
797        assert!((high - 17.949).abs() < 0.01, "{high} N m");
798        assert!(low < 0.0);
799        let (_, high) = motor(&p).torque_curve(&p, 25.0, 540.0);
800        assert!((high - 19.552).abs() < 0.01, "{high} N m");
801    }
802
803    /// The control keeps the rated flux at part load and weakens it only where the voltage binds at the torque asked for;
804    /// asked for the curve's torque it delivers it. On the 540 V link at 120 rad/s, 5 N m fit at the rated flux (the circle
805    /// leaves 20.03 N m there): the rated flux stays. At 110 to 150 rad/s the rotor held at speed and the curve's torque
806    /// commanded from the rated flux: after 1.5 s (11 rotor time constants) the torque is the curve's within 1 %.
807    #[test]
808    fn asked_for_the_curves_torque_the_field_oriented_control_delivers_it() {
809        let p = DriveParams { bus_voltage: 540.0, max_voltage: WINDING_PER_DC_LINK * 540.0, ..params(true, 4.5) };
810        let m = motor(&p);
811        let supply = 540.0 / 3f64.sqrt();
812        let amplitude = SQRT_2 * 10.0;
813        let at_rated = 3.0 * m.magnetizing / m.rotor * m.torque_room(4.5, supply, m.rated_flux, 240.0, true, amplitude);
814        assert!((at_rated - 20.03).abs() < 0.05, "{at_rated} N m");
815        assert_eq!(m.control_flux(5.0, 120.0, supply, 4.5, amplitude), m.rated_flux);
816        assert!(m.control_flux(25.0, 120.0, supply, 4.5, amplitude) < m.rated_flux);
817        for speed in [110.0, 120.0, 130.0, 140.0, 150.0] {
818            let curve = m.torque_curve(&p, speed, 540.0).1;
819            let mut d = Drive::at_rest(&p, 0.0, 0.0, 0.0);
820            let trace = run(&p, &mut d, f64::INFINITY, speed, |_| 0.0, |_, d| d.torque_command = curve, 1.5);
821            let delivered = trace.last().unwrap()[2];
822            assert!((delivered / curve - 1.0).abs() < 0.01, "{speed} rad/s: {delivered} N m of {curve}");
823        }
824    }
825
826    /// The V/f slip compensation's estimate of the air-gap torque is first order with `slip_filter`, exact per step: from 0 it
827    /// reaches (1 - exp(-dt / T)) of the raw value, for the rotor's own L_r / R_r = 0.47 / 3.5 s and for a key of 1 ms.
828    #[test]
829    fn the_slip_estimate_follows_the_filter_time_of_the_key() {
830        let p = params(false, 4.5);
831        let raw = |m: &Induction, d: &Drive| {
832            let (is, _) = m.currents(&d.phases.x);
833            let air_gap =
834                1.5 * (d.phases.u[0] * is[0] + d.phases.u[1] * is[1]) - 1.5 * 4.5 * (is[0] * is[0] + is[1] * is[1]);
835            m.pole_pairs * air_gap / d.phases.frame_speed
836        };
837        for tau in [0.47 / 3.5, 1e-3] {
838            let m = Induction { slip_filter: tau, ..motor(&p).clone() };
839            let mut d = Drive::at_rest(&p, 0.0, 0.0, 0.0);
840            d.phases = Phases::default();
841            (d.phases.x, d.phases.u, d.phases.frame_speed) = ([0.3, 0.1, 0.2, 0.05], [100.0, 20.0], 100.0);
842            let wanted = (1.0 - (-p.current_cycle / tau).exp()) * raw(&m, &d);
843            m.stepped(&mut d, &p);
844            assert!(
845                (d.phases.estimate - wanted).abs() < 1e-12 * wanted.abs().max(1.0),
846                "{} against {wanted}",
847                d.phases.estimate
848            );
849        }
850    }
851
852    /// Field-oriented from no flux: the d current steps to psi* / L_m within the current loop's 0.5 ms, and the rotor flux
853    /// follows with L_r / R_r = 0.47 / 3.5 = 134.3 ms: 63.2 % of it at one time constant, 95.0 % at three.
854    #[test]
855    fn the_rotor_flux_builds_with_l_r_over_r_r() {
856        let p = params(true, 4.5);
857        let m = motor(&p);
858        let mut d = Drive::at_rest(&p, 0.0, 0.0, 0.0);
859        d.phases = Phases::default();
860        let trace = run(&p, &mut d, f64::INFINITY, 0.0, |_| 0.0, |_, d| d.torque_command = 0.0, 0.45);
861        let tau = 0.47 / 3.5;
862        let at = |t: f64| trace[(t / p.current_cycle) as usize - 1][3] / m.rated_flux;
863        assert!((at(tau) - 0.632).abs() < 0.01, "{}", at(tau));
864        assert!((at(3.0 * tau) - 0.950).abs() < 0.01, "{}", at(3.0 * tau));
865    }
866
867    /// Field-oriented, magnetized, rotor held: a torque step of 5 N m answers as the current loop does, 63.2 % within its
868    /// T = sigma L_s / Kp = 0.5 ms, and holds it (the flux stays, the slip frequency keeps the frame on it).
869    #[test]
870    fn under_field_orientation_a_torque_step_answers_with_the_current_loops_time_constant() {
871        let p = params(true, 4.5);
872        let mut d = Drive::at_rest(&p, 0.0, 0.0, 0.0);
873        let trace = run(&p, &mut d, f64::INFINITY, 0.0, |_| 0.0, |_, d| d.torque_command = 5.0, 0.05);
874        let at = |t: f64| trace[(t / p.current_cycle).round() as usize - 1][2];
875        assert!((at(0.5e-3) / 5.0 - 0.632).abs() < 0.05, "{}", at(0.5e-3));
876        assert!((at(0.05) / 5.0 - 1.0).abs() < 2e-3, "{}", at(0.05));
877    }
878}