Skip to main content

sim_components/
stepper.rs

1//! Stepper motor (motor.kind = "stepper"): a two-phase hybrid stepper behind an open-loop step and direction drive.
2//!
3//! The motor in its usual sinusoidal form, with N rotor teeth and the rotor's electrical angle e = N (angle - origin):
4//!   torque = kt (i_b cos e - i_a sin e) - T_d sin 4e,
5//!   L di_a/dt = u_a - R i_a + kE w sin e,   L di_b/dt = u_b - R i_b - kE w cos e,
6//! kE = kt (the back-EMF powers the torque: e_a i_a + e_b i_b = torque w without the detent), the detent torque T_d
7//! (effects.detent_torque) with 4N periods a turn. R, L and kt are a phase's (`motor.resistance_ohm`, `inductance_h`,
8//! `torque_constant_nm_a`).
9//!
10//! The drive counts the position setpoint in microsteps, 2 pi / (4 N microsteps) each, and sets the current vector at
11//! that electrical angle with the amplitude `drive.stepper_current_a`: i_a = I cos e_c, i_b = I sin e_c. Then
12//! torque = kt I sin(e_c - e): the rotor sits on the "magnetic spring" of the holding torque kt I, its load angle
13//! e_c - e. Beyond the pull-out angle pi / 2 the spring weakens; past pi the rotor falls into the next equilibrium, four
14//! full steps on, and the drive, open loop, never learns of it.
15//!
16//! The chopper sets each base step the voltage that brings the phase currents to their setpoints by the step's end,
17//! against the back-EMF at its start, as a current-regulated chopper does over its PWM periods; the voltage vector is
18//! kept within the supply, the DC link voltage (`drive.bus_voltage_v`, the simulated link with effects.dc_link): a
19//! two-phase bridge gives a phase +-U. So the current falls short of its setpoint at speed, and the torque with it: the
20//! pull-out curve (`Stepper::pull_out`).
21
22use crate::drive::{Drive, DriveMode, DriveParams, WINDING_PER_DC_LINK, quantise};
23use sim_core::{Config, ConfigError};
24use std::f64::consts::TAU;
25
26type Result<T> = std::result::Result<T, ConfigError>;
27
28#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
29pub struct Stepper {
30    /// Rotor teeth N (50 for a 1.8 degree motor): 4 N full steps a turn.
31    pub teeth: f64,
32    /// effects.detent_torque: the detent torque's amplitude, N m; 0 off.
33    pub detent: f64,
34    /// One microstep at the motor, rad.
35    pub microstep: f64,
36    /// The current vector's amplitude the drive sets, A: sqrt 2 times a phase's current in a full step.
37    pub current: f64,
38}
39
40impl Stepper {
41    pub fn from_config(cfg: &Config) -> Result<Self> {
42        let teeth = cfg.positive("motor.rotor_teeth")?;
43        let microsteps = cfg.positive("drive.microsteps")?;
44        if microsteps.fract() != 0.0 || microsteps > 4096.0 {
45            return Err(ConfigError::Invalid("drive.microsteps".into()));
46        }
47        let detent = if cfg.get("effects.detent_torque").is_ok() && cfg.bool("effects.detent_torque")? {
48            cfg.non_negative("motor.detent_torque_nm")?
49        } else {
50            0.0
51        };
52        let current = cfg.positive("drive.stepper_current_a")?;
53        Ok(Self { teeth, detent, microstep: TAU / (4.0 * teeth * microsteps), current })
54    }
55
56    /// The torque of phase currents at the rotor's electrical angle `e`.
57    pub fn torque(&self, p: &DriveParams, [ia, ib]: [f64; 2], e: f64) -> f64 {
58        let (s, c) = e.sin_cos();
59        p.kt * (ib * c - ia * s) - self.detent * (4.0 * e).sin()
60    }
61
62    /// The holding torque: kt times the current the drive sets.
63    pub fn holding_torque(&self, p: &DriveParams) -> f64 {
64        p.kt * self.current
65    }
66
67    /// The drive enabled at `pos`: the windings count from there, a full step, and the current vector stands on it.
68    pub(crate) fn at_rest(&self, d: &mut Drive, p: &DriveParams, pos: f64) {
69        // The first enable puts the electrical zero (and the detent's) where the rotor stands; later ones keep it
70        // (`re_enabled`).
71        let x = [self.current, 0.0, 0.0, 0.0];
72        d.phases = crate::drive::Phases { x, angle: pos, command: pos, origin: pos, ..Default::default() };
73        (d.current, d.torque, d.torque_demand, d.torque_command, d.controller_torque) =
74            (self.current, 0.0, 0.0, 0.0, 0.0);
75        d.phases.u = [p.resistance * self.current, 0.0];
76    }
77
78    /// A drive enabled again with the grid `origin` it had (the electrical zero, the detent's too): the rotor stands at `pos`,
79    /// off the grid where it was turned meanwhile; the drive's count starts on the full step nearest to it, origin + n 2 pi /
80    /// (4 N), and its current vector stands there (`offset` is the count's distance from the controller's setpoint, which
81    /// starts at `pos`). The rotor is not moved: the magnetic spring pulls it there by the model's dynamics, from its load
82    /// angle (at most a half full step) on.
83    pub(crate) fn re_enabled(&self, d: &mut Drive, p: &DriveParams, pos: f64, origin: f64) {
84        let full = TAU / (4.0 * self.teeth);
85        let snapped = origin + ((pos - origin) / full).round() * full;
86        let e = (self.teeth * (snapped - origin)).rem_euclid(TAU);
87        let (s, c) = e.sin_cos();
88        let ph = &mut d.phases;
89        (ph.origin, ph.command, ph.offset, ph.electrical) = (origin, snapped, snapped - pos, e);
90        ph.x = [self.current * c, self.current * s, 0.0, 0.0];
91        ph.load_angle = e - self.teeth * (pos - origin);
92        ph.u = [p.resistance * self.current * c, p.resistance * self.current * s];
93    }
94
95    /// The detent torque's potential at the rotor angle `angle`, J: the torque is -T_d sin 4e (e = N (angle - origin)), so
96    /// U = -T_d cos(4e) / (4 N), whose angle derivative is T_d sin 4e. It is the magnets' energy (the torque is
97    /// conservative), enabled or not: the detent's work is part of the shaft's, and what the magnets give for it, the
98    /// change of U, is booked as it happens (`Drive::detent_moved`, `Drive::emf_loss`), never stored, so that nothing of
99    /// it appears or vanishes at an enable or a disable.
100    pub fn detent_potential(&self, angle: f64, origin: f64) -> f64 {
101        -self.detent * (4.0 * self.teeth * (angle - origin)).cos() / (4.0 * self.teeth)
102    }
103
104    /// The detent torque at the rotor angle `angle`, N m: -T_d sin 4e, the magnets' alone, with the drive enabled or not.
105    pub fn detent_torque(&self, angle: f64, origin: f64) -> f64 {
106        -self.detent * (4.0 * self.teeth * (angle - origin)).sin()
107    }
108
109    /// The rates of the windings (`DriveParams::motor_rates`): i_a in slot 0, i_b in slot 4.
110    pub(crate) fn rates(&self, p: &DriveParams, d: &Drive, w: &[f64], angle: f64, speed: f64, out: &mut [f64]) -> f64 {
111        let ([ia, ib], [ua, ub]) = ([w[0], w[4]], d.phases.u);
112        let e = self.teeth * (angle - d.phases.origin);
113        let (s, c) = e.sin_cos();
114        let (r, emf) = (d.winding_resistance(p), p.ke * speed);
115        let electromagnetic = p.kt * (ib * c - ia * s);
116        out[0] = (ua - r * ia + emf * s) / p.inductance;
117        out[4] = (ub - r * ib - emf * c) / p.inductance;
118        out[1] = ua * ia + ub * ib;
119        out[2] = r * (ia * ia + ib * ib);
120        // The shaft's work is the whole torque's; the detent's share of it the magnets give (`Drive::detent_moved`).
121        let torque = electromagnetic + self.detent_torque(angle, d.phases.origin);
122        out[3] = torque * speed;
123        out[5] = 0.0;
124        out[6] = 0.0;
125        torque
126    }
127
128    /// One base step of the drive: the step generator's angle, the current vector on its microstep, and the chopper's
129    /// voltages for the step.
130    pub(crate) fn control(&self, d: &mut Drive, p: &DriveParams) {
131        let dt = p.current_cycle;
132        // The step generator runs the setpoint on between profile cycles; a speed setpoint (velocity mode, a fault's
133        // stop ramp) it integrates.
134        d.phases.command = match (d.fault_speed, d.mode()) {
135            (None, DriveMode::Position) => {
136                let t = d.since_setpoint;
137                d.pos_set + d.phases.offset + (d.vel_set + 0.5 * d.acc_set * t) * t
138            }
139            _ => d.phases.command + d.speed_command * dt,
140        };
141        let (r, supply) = (d.winding_resistance(p), d.max_voltage(p) / WINDING_PER_DC_LINK);
142        let ph = &mut d.phases;
143        ph.electrical = self.teeth * quantise(ph.command - ph.origin, self.microstep);
144        let set = [self.current * ph.electrical.cos(), self.current * ph.electrical.sin()];
145        // The voltage that takes i to its setpoint over the step, i(dt) = i_inf + (i - i_inf) a, a = exp(-R dt / L),
146        // with i_inf = (u - emf) / R and the back-EMF of the step's start.
147        let e = self.teeth * (ph.angle - ph.origin);
148        let emf = [-p.ke * ph.speed * e.sin(), p.ke * ph.speed * e.cos()];
149        let a = (-r * dt / p.inductance).exp();
150        let mut u = [0.0; 2];
151        for k in 0..2 {
152            u[k] = emf[k] + r * (set[k] - a * ph.x[k]) / (1.0 - a);
153        }
154        // The vector is held within the supply: `drive.overmodulation` (`DriveParams::fundamental_gain`) lets a bridge driven
155        // into square waves give 4 / pi more, the fundamental only.
156        let norm = u[0].hypot(u[1]);
157        if norm > supply {
158            u = u.map(|v| v * supply / norm);
159        }
160        ph.u = u;
161        d.voltage = norm.min(supply);
162        d.iron_loss = 0.0;
163    }
164
165    /// The step done: the current vector's amplitude, the torque at the rotor's angle and the load angle.
166    pub(crate) fn stepped(&self, d: &mut Drive, p: &DriveParams) {
167        let ph = &mut d.phases;
168        let e = self.teeth * (ph.angle - ph.origin);
169        let i = [ph.x[0], ph.x[1]];
170        ph.load_angle = ph.electrical - e;
171        d.current = i[0].hypot(i[1]);
172        d.torque = self.torque(p, i, e);
173        // Open loop nothing asks for a torque: what it gives is judged against the pull-out curve.
174        (d.torque_demand, d.torque_command) = (d.torque, d.torque);
175    }
176
177    /// The pull-out torque at a speed, motoring, with the supply `supply` (infinite: no limit): the most torque a
178    /// steady run at that speed can have from currents within the drive's amplitude I and voltages within the supply.
179    /// In phasors at the electrical frequency N w, with the back-EMF E = kE w as the real axis and Z = R + j N w L, the
180    /// torque is kt Re(I) and V = Z I + E: Re(I) at its highest over the intersection of the disc |I| <= I and the disc
181    /// |I + E / Z| <= U / |Z|. Without detent torque, cold winding.
182    pub fn pull_out(&self, p: &DriveParams, speed: f64, supply: f64) -> f64 {
183        p.kt * most_in_phase(p, self, speed.abs(), supply, 1.0)
184    }
185
186    /// The braking counterpart of `pull_out`: the back-EMF helps the current.
187    pub fn braking(&self, p: &DriveParams, speed: f64, supply: f64) -> f64 {
188        p.kt * most_in_phase(p, self, speed.abs(), supply, -1.0)
189    }
190
191    /// (lowest, highest) torque at a speed, as `DriveParams::torque_curve`: the pull-out curve and its braking side.
192    pub fn torque_curve(&self, p: &DriveParams, speed: f64, supply: f64) -> (f64, f64) {
193        let (motoring, braking) = (self.pull_out(p, speed, supply), self.braking(p, speed, supply));
194        if speed >= 0.0 { (-braking, motoring) } else { (-motoring, braking) }
195    }
196}
197
198/// The highest Re(I) over |I| <= I_max and |Z I + sign E| <= U (see `Stepper::pull_out`).
199fn most_in_phase(p: &DriveParams, s: &Stepper, speed: f64, supply: f64, sign: f64) -> f64 {
200    let (limit, teeth) = (s.current, s.teeth);
201    if !supply.is_finite() {
202        return limit;
203    }
204    let (r, x, e) = (p.resistance, teeth * speed * p.inductance, sign * p.ke * speed);
205    let z2 = r * r + x * x;
206    // The voltage disc: centre -E / Z = -E (R - jX) / |Z|^2, radius U / |Z|.
207    let (cx, cy, rho) = (-e * r / z2, e * x / z2, supply / z2.sqrt());
208    let inside_voltage = |px: f64, py: f64| (px - cx).hypot(py - cy) <= rho * (1.0 + 1e-12);
209    let mut best = f64::NEG_INFINITY;
210    if inside_voltage(limit, 0.0) {
211        best = limit;
212    }
213    if (cx + rho).hypot(cy) <= limit {
214        best = best.max(cx + rho);
215    }
216    // Where the two circles cross.
217    let d = cx.hypot(cy);
218    if d > 0.0 && d <= limit + rho && d >= (limit - rho).abs() {
219        let a = (limit * limit - rho * rho + d * d) / (2.0 * d);
220        let h = (limit * limit - a * a).max(0.0).sqrt();
221        // Their real parts: the chord's middle a along the centre line, h either way across it.
222        let mx = a * cx / d;
223        best = best.max(mx + h * cy / d).max(mx - h * cy / d);
224    }
225    best.max(0.0)
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use crate::drive::{Motor, WINDING_STATES};
232    use sim_core::Rk4;
233
234    /// A NEMA 23 sized stepper of round numbers: N = 50, kt = kE = 0.5 N m/A, R = 1 Ohm, L = 2.5 mH, driven at 2 A on
235    /// 24 V: holding torque 1 N m. No detent unless a test sets it.
236    fn params() -> DriveParams {
237        DriveParams {
238            kt: 0.5,
239            ke: 0.5,
240            resistance: 1.0,
241            inductance: 2.5e-3,
242            rated_current: 2.0,
243            heating: false,
244            dc_link: false,
245            bus_voltage: 24.0,
246            max_voltage: WINDING_PER_DC_LINK * 24.0,
247            current_cycle: 62.5e-6,
248            motor: Motor::Stepper(Stepper {
249                teeth: 50.0,
250                detent: 0.0,
251                microstep: TAU / (4.0 * 50.0 * 16.0),
252                current: 2.0,
253            }),
254            ..crate::drive::tests::params()
255        }
256    }
257
258    fn stepper(p: &DriveParams) -> &Stepper {
259        let Motor::Stepper(s) = &p.motor else { unreachable!() };
260        s
261    }
262
263    /// The motor on a rigid inertia `j` with viscous friction `b` and a load torque `load(t)`, its drive commanding
264    /// `set(t)` = (position, speed, acceleration) every millisecond, integrated as `Sim::step` does: windings and
265    /// mechanics through each base step together. Returns per base step (time, angle, speed, load angle, current).
266    fn run(
267        p: &DriveParams,
268        j: f64,
269        b: f64,
270        load: impl Fn(f64) -> f64,
271        set: impl Fn(f64) -> [f64; 3],
272        seconds: f64,
273    ) -> Vec<[f64; 5]> {
274        let s = stepper(p);
275        let mut d = Drive::at_rest(p, 0.0, 0.0, 0.0);
276        let dt = p.current_cycle;
277        let mut rk = Rk4::new(2 + WINDING_STATES);
278        let (mut angle, mut speed) = (0.0, 0.0);
279        let mut out = Vec::new();
280        let steps = (seconds / dt).round() as usize;
281        for n in 0..steps {
282            let t = n as f64 * dt;
283            if n % 16 == 0 {
284                [d.pos_set, d.vel_set, d.acc_set] = set(t);
285                d.since_setpoint = 0.0;
286            }
287            s.control(&mut d, p);
288            d.since_setpoint += dt;
289            let mut y = vec![angle, speed];
290            y.extend(d.winding_states(p));
291            let tl = load(t);
292            rk.step(
293                |y, dy| {
294                    let torque = p.motor_rates(&d, &y[2..], y[0], y[1], &mut dy[2..]);
295                    dy[0] = y[1];
296                    dy[1] = (torque - b * y[1] - tl) / j;
297                },
298                &mut y,
299                dt,
300            );
301            (angle, speed) = (y[0], y[1]);
302            let w = &y[2..];
303            (d.phases.x, d.phases.angle, d.phases.speed) = ([w[0], w[4], w[5], w[6]], angle, speed);
304            d.winding_stepped(p, w[0], [w[1], w[2], w[3]]);
305            out.push([t + dt, angle, speed, d.phases.load_angle, d.current]);
306        }
307        out
308    }
309
310    /// Holding torque by hand: kt I = 0.5 * 2 = 1 N m at the rated current, at a load angle of 90 degrees (one full step,
311    /// a quarter of an electrical turn, pi / 100 rad at the motor). The drive's currents settle at their setpoints.
312    #[test]
313    fn the_holding_torque_is_kt_times_the_rated_current() {
314        let p = params();
315        let s = stepper(&p);
316        assert!((s.holding_torque(&p) - 1.0).abs() < 1e-12);
317        let full_step = TAU / 200.0;
318        assert!((s.torque(&p, [2.0, 0.0], -50.0 * full_step) - 1.0).abs() < 1e-12);
319        // Against a load of 0.99 N m held at rest the rotor stands at asin(0.99) electrical behind its setpoint, by hand
320        // 81.9 degrees, 0.02858 rad at the motor; the load comes on over 0.2 s and viscous damping lets it settle.
321        let trace = run(&p, 1e-4, 2e-3, |t| 0.99 * (t / 0.2).min(1.0), |_| [0.0; 3], 0.6);
322        let [_, angle, _, load_angle, current] = *trace.last().unwrap();
323        assert!((load_angle - 0.99f64.asin()).abs() < 2e-3, "{load_angle}");
324        assert!((angle + 0.99f64.asin() / 50.0).abs() < 1e-4, "{angle}");
325        assert!((current - 2.0).abs() < 1e-6, "{current}");
326    }
327
328    /// The rotor on the magnetic spring: stiffness N T_hold = 50 N m/rad at small angles, so with J = 1e-4 kg m^2 it rings
329    /// at sqrt(50 / 1e-4) / 2 pi = 112.54 Hz after a microstep, undamped (the chopper takes the back-EMF out of the loop).
330    #[test]
331    fn the_rotor_rings_at_the_hand_calculated_resonance() {
332        let p = params();
333        let step = stepper(&p).microstep;
334        let trace = run(&p, 1e-4, 0.0, |_| 0.0, |_| [1.2 * step, 0.0, 0.0], 0.1);
335        // Crossings of the setpoint, rising.
336        let target = step;
337        let ups: Vec<f64> =
338            trace.windows(2).filter(|w| w[0][1] < target && w[1][1] >= target).map(|w| w[1][0]).collect();
339        assert!(ups.len() > 8, "{}", ups.len());
340        let f = (ups.len() - 1) as f64 / (ups.last().unwrap() - ups[0]);
341        let by_hand = (50.0 * 1.0 / 1e-4f64).sqrt() / TAU;
342        assert!((f - by_hand).abs() < 0.01 * by_hand, "{f} Hz against {by_hand} Hz");
343    }
344
345    /// The corner speeds by hand. Unloaded the rotor runs with its load angle near 0, so the back-EMF stands in phase with
346    /// L di/dt and a phase needs sqrt((R I)^2 + (N w L I + kE w)^2) volts. It reaches the 24 V supply at
347    /// w_c = sqrt(24^2 - 2^2) / (50 * 2.5e-3 * 2 + 0.5) = 31.89 rad/s (305 rpm): below it the current reaches its
348    /// setpoint, above it falls short. At the pull-out angle (90 degrees) the back-EMF stands in phase with the current,
349    /// and a phase needs sqrt((R I + kE w)^2 + (N w L I)^2): 24 V at 0.3125 w^2 + 2 w - 572 = 0, w = 39.70 rad/s, where the
350    /// pull-out torque starts to fall from the holding torque (`pull_out`).
351    #[test]
352    fn the_current_falls_short_above_the_hand_calculated_corner_speed() {
353        let p = params();
354        let corner = (24.0f64 * 24.0 - 4.0).sqrt() / (50.0 * 2.5e-3 * 2.0 + 0.5);
355        assert!((corner - 31.89).abs() < 0.01);
356        // At a constant speed, after a slow ramp up to it, the current amplitude over the last 0.1 s.
357        let amplitude = |speed: f64| {
358            let ramp = 0.5;
359            let set = move |t: f64| {
360                if t < ramp {
361                    [0.5 * speed / ramp * t * t, speed / ramp * t, speed / ramp]
362                } else {
363                    [0.5 * speed * ramp + speed * (t - ramp), speed, 0.0]
364                }
365            };
366            let trace = run(&p, 1e-4, 1e-4, |_| 0.0, set, ramp + 0.3);
367            trace[trace.len() - 1600..].iter().map(|r| r[4]).fold(f64::INFINITY, f64::min)
368        };
369        let (below, above) = (amplitude(0.9 * corner), amplitude(1.3 * corner));
370        assert!(below > 0.99 * 2.0, "{below} A at 0.9 w_c");
371        assert!(above < 0.95 * 2.0, "{above} A at 1.3 w_c");
372        let s = stepper(&p);
373        let torque_corner = (-2.0 + (4.0f64 + 4.0 * 0.3125 * 572.0).sqrt()) / (2.0 * 0.3125);
374        assert!((torque_corner - 39.70).abs() < 0.01);
375        assert!((s.pull_out(&p, 0.999 * torque_corner, 24.0) - 1.0).abs() < 1e-12);
376        let past = s.pull_out(&p, 1.1 * torque_corner, 24.0);
377        assert!(past < 0.98, "{past}");
378    }
379
380    /// A load above the holding torque, 1.3 N m for 30 ms, pulls the rotor out of its equilibrium; once it is gone the
381    /// rotor settles on another, a whole electrical turn on, 2 pi / N: four full steps per turn (detent torque on, which
382    /// has its equilibria at every full step, and it still lands on the four-step grid).
383    #[test]
384    fn a_load_above_the_holding_torque_slips_by_whole_multiples_of_four_full_steps() {
385        let mut p = params();
386        if let Motor::Stepper(s) = &mut p.motor {
387            s.detent = 0.05;
388        }
389        let trace = run(&p, 1e-4, 5e-3, |t| if t < 0.03 { 1.3 } else { 0.0 }, |_| [0.0; 3], 0.4);
390        let [_, angle, speed, load_angle, _] = *trace.last().unwrap();
391        let full_steps = -angle / (TAU / 200.0);
392        assert!(speed.abs() < 1e-2, "{speed}");
393        assert!(full_steps >= 3.9, "{full_steps} full steps");
394        assert!((full_steps / 4.0 - (full_steps / 4.0).round()).abs() < 0.01, "{full_steps} full steps");
395        assert!((load_angle / TAU - (load_angle / TAU).round()).abs() < 0.01 && load_angle > 1.0, "{load_angle}");
396    }
397
398    /// Acceleration ramps, jerk-limited (the acceleration rises over 0.2 s, two periods of the rotor on its spring), on
399    /// a load inertia of 0.01 kg m^2: one that needs 80 % of the pull-out torque at its end speed stays in step, one that
400    /// needs 110 % falls out. Below the corner speed (to 20 rad/s) the pull-out torque is the holding torque, 1 N m:
401    /// 80 rad/s^2 and 110 rad/s^2. Above it (to 55 rad/s) the pull-out curve's value there (`pull_out`), by hand 0.793 N m:
402    /// E = 27.5 V, X = 6.875 Ohm, the voltage disc's centre (-0.570, 3.917) A and radius 3.454 A cross the 2 A circle at
403    /// Re I = 1.586 A.
404    #[test]
405    fn a_ramp_beyond_the_pull_out_torque_stalls_and_one_at_80_percent_does_not() {
406        let p = params();
407        let s = stepper(&p);
408        let j = 0.01;
409        let stays_in_step = |torque: f64, end: f64| {
410            let (alpha, rise) = (torque / j, 0.2);
411            let set = move |t: f64| {
412                // Acceleration alpha * min(t / rise, 1).
413                if t < rise {
414                    [alpha * t.powi(3) / (6.0 * rise), alpha * t * t / (2.0 * rise), alpha * t / rise]
415                } else {
416                    let (x0, v0) = (alpha * rise * rise / 6.0, alpha * rise / 2.0);
417                    let tt = t - rise;
418                    [x0 + v0 * tt + 0.5 * alpha * tt * tt, v0 + alpha * tt, alpha]
419                }
420            };
421            // Until the setpoint's speed reaches `end`.
422            let seconds = 0.5 * rise + end / alpha;
423            let trace = run(&p, j, 0.0, |_| 0.0, set, seconds);
424            let reached = trace.iter().take_while(|r| r[3].abs() < std::f64::consts::PI).last().unwrap()[2];
425            (trace.iter().all(|r| r[3].abs() < std::f64::consts::PI), reached)
426        };
427        let below = s.pull_out(&p, 20.0, 24.0);
428        assert!((below - 1.0).abs() < 1e-12);
429        assert!(stays_in_step(0.8 * below, 20.0).0);
430        assert!(!stays_in_step(1.1 * below, 20.0).0);
431        let above = s.pull_out(&p, 55.0, 24.0);
432        assert!((above - 0.793).abs() < 1e-3, "{above}");
433        assert!(stays_in_step(0.8 * above, 55.0).0);
434        let (kept, reached) = stays_in_step(1.1 * above, 55.0);
435        assert!(!kept && reached < 55.0, "fell out at {reached} rad/s");
436    }
437
438    /// Disabled at a half step, enabled again: the grid (origin 0.3 rad here) is kept and the rotor, standing 1.4 full steps
439    /// off the origin, is pulled by the magnetic spring to the nearest full step of that grid, origin + 1 full step
440    /// (2 pi / 200 = 0.0314159 rad): after the ringing has died down (damping b / 2J = 10 / s, 1 s) the angle is
441    /// 0.3 + 0.0314159 within 1e-4 rad, a whole number of full steps from the origin. The drive's count is 0.4 full steps
442    /// behind the controller's setpoint, which holds where the rotor stood.
443    #[test]
444    fn an_enable_keeps_the_grid_and_pulls_the_rotor_to_the_nearest_full_step() {
445        let p = params();
446        let s = stepper(&p);
447        let (origin, full) = (0.3, TAU / 200.0);
448        let pos = origin + 1.4 * full;
449        let mut d = Drive::at_rest(&p, pos, 0.0, 0.0);
450        s.re_enabled(&mut d, &p, pos, origin);
451        assert!((d.phases.command - (origin + full)).abs() < 1e-12 && (d.phases.offset + 0.4 * full).abs() < 1e-12);
452        let (j, b, dt) = (1e-4, 2e-3, p.current_cycle);
453        let mut rk = Rk4::new(2 + WINDING_STATES);
454        let (mut angle, mut speed) = (pos, 0.0);
455        for n in 0..16_000 {
456            if n % 16 == 0 {
457                (d.pos_set, d.vel_set, d.acc_set, d.since_setpoint) = (pos, 0.0, 0.0, 0.0);
458            }
459            s.control(&mut d, &p);
460            d.since_setpoint += dt;
461            let mut y = vec![angle, speed];
462            y.extend(d.winding_states(&p));
463            rk.step(
464                |y, dy| {
465                    let torque = p.motor_rates(&d, &y[2..], y[0], y[1], &mut dy[2..]);
466                    (dy[0], dy[1]) = (y[1], (torque - b * y[1]) / j);
467                },
468                &mut y,
469                dt,
470            );
471            (angle, speed) = (y[0], y[1]);
472            let w = &y[2..];
473            (d.phases.x, d.phases.angle, d.phases.speed) = ([w[0], w[4], w[5], w[6]], angle, speed);
474            d.winding_stepped(&p, w[0], [w[1], w[2], w[3]]);
475        }
476        assert!((angle - (origin + full)).abs() < 1e-4, "{angle} rad against {}", origin + full);
477        assert!(((angle - origin) / full - 1.0).abs() < 4e-3, "{} full steps", (angle - origin) / full);
478    }
479
480    /// The detent's work inside one base step. The torque -T_d sin 4e is conservative with the potential
481    /// U = -T_d cos(4 N (angle - origin)) / (4 N) (dU/d angle = T_d sin 4e, so -dU/d angle is the torque). The shaft's
482    /// work is the whole torque's, the detent's included, and the magnets give the detent's: `emf_loss` over the step is
483    /// the change of U (`Drive::detent_moved`). Over a step electrical power - copper loss - the change of the winding's
484    /// energy - the shaft's work is 0 (the electrical side), the shaft's work is the rotor's kinetic energy (no friction,
485    /// no load), and so electrical - copper - winding - the magnets' - kinetic is 0, up to the integrator. T_d = 0.05 N m,
486    /// N = 50: the potential swings by 0.05 / 200 = 2.5 mJ over a quarter of the detent period; the step's change of it
487    /// is by hand U(angle end) - U(0.004), which the integrated shaft work beyond the electrical's matches.
488    #[test]
489    fn the_budget_closes_inside_one_step_with_the_detents_potential() {
490        let mut p = params();
491        if let Motor::Stepper(s) = &mut p.motor {
492            s.detent = 0.05;
493        }
494        let s = stepper(&p);
495        let (j, dt) = (1e-4, p.current_cycle);
496        let mut d = Drive::at_rest(&p, 0.0, 0.0, 0.0);
497        let (angle0, speed0) = (0.004, 8.0);
498        (d.phases.angle, d.phases.speed) = (angle0, speed0);
499        s.control(&mut d, &p);
500        let before = d.magnetic_energy(&p);
501        let mut rk = Rk4::new(2 + WINDING_STATES);
502        let mut y = vec![angle0, speed0];
503        y.extend(d.winding_states(&p));
504        rk.step(
505            |y, dy| {
506                let torque = p.motor_rates(&d, &y[2..], y[0], y[1], &mut dy[2..]);
507                (dy[0], dy[1]) = (y[1], torque / j);
508            },
509            &mut y,
510            dt,
511        );
512        let w = &y[2..];
513        (d.phases.x, d.phases.angle, d.phases.speed) = ([w[0], w[4], w[5], w[6]], y[0], y[1]);
514        d.winding_stepped(&p, w[0], [w[1], w[2], w[3]]);
515        d.detent_moved(&p, angle0);
516        let after = d.magnetic_energy(&p);
517        let kinetic = 0.5 * j * (y[1] * y[1] - speed0 * speed0);
518        let magnets = d.emf_loss * dt;
519        let by_hand = 0.05 / 200.0 * ((200.0 * angle0).cos() - (200.0 * y[0]).cos());
520        assert!((magnets - by_hand).abs() < 1e-15 && magnets.abs() > 1e-6, "{magnets} J against {by_hand} J");
521        let electrical = w[1] - w[2] - (after - before) - w[3] - magnets;
522        assert!(electrical.abs() < 1e-9, "{electrical} J of the electrical side open of {} J", w[1]);
523        let open = w[1] - w[2] - (after - before) - magnets - kinetic;
524        assert!(open.abs() < 1e-9, "{open} J unaccounted of {} J electrical", w[1]);
525        // The potential itself: -T_d / 200 at a detent minimum (4e = 0), +T_d / 200 half a period on.
526        assert!((s.detent_potential(0.0, 0.0) + 0.05 / 200.0).abs() < 1e-15);
527        assert!((s.detent_potential(TAU / 400.0, 0.0) - 0.05 / 200.0).abs() < 1e-15);
528    }
529}