Skip to main content

sim_components/
charts.rs

1//! The numbers behind the views that show a drive's real torque and the tool's real error, for the app and the sizing
2//! report alike: the torque-speed chart per motor with its limits, the RMS point, the tool's error split normal and
3//! tangential to the path, a histogram, the torque split stacked, the utilisation of the drive over time, and the
4//! spectrum. Everything works on a run's signals as columns (one value per millisecond, the first column the time).
5
6use crate::drive::{DriveParams, WINDING_PER_DC_LINK};
7use sim_core::{SignalInfo, TORQUE_PARTS};
8
9/// How many speeds the torque-speed chart's curves are sampled at, from the highest speed backwards to the highest
10/// forwards: odd, so that standstill is one of them.
11pub const CURVE_POINTS: usize = 241;
12
13/// A motor's torque-speed chart: lines of (speed rad/s, torque N m), each as [highest, lowest].
14#[derive(Debug, Clone, PartialEq)]
15pub struct TorqueSpeed {
16    /// What motor and drive give at most (`DriveParams::torque_curve`): the peak torque, faded or field-weakened.
17    pub peak: [Vec<[f64; 2]>; 2],
18    /// The continuous (S1) rating as the motor-s1 verdict has it (`analysis::s1_torque`): from k_t I_0 at standstill to the
19    /// rated torque at the rated speed, and on along that line.
20    pub s1: [Vec<[f64; 2]>; 2],
21    /// What the winding's voltage leaves at the DC link `dc_voltage` (`DriveParams::voltage_limited_torque`).
22    pub voltage: [Vec<[f64; 2]>; 2],
23    /// The torque of the drive's maximum current (`ratings.drive_max_current_a`); `None` without that limit.
24    pub current_limit: Option<f64>,
25    pub dc_voltage: f64,
26}
27
28/// The chart of `drive` with the DC link at `dc_voltage`, its curves sampled at `CURVE_POINTS` speeds up to a tenth
29/// beyond the highest of the no-load speed and the speed limit.
30// shortcut: no S3 line, as no catalogue the simulator reads gives S3 data; add it with that data.
31pub fn torque_speed(drive: &DriveParams, dc_voltage: f64) -> TorqueSpeed {
32    let top = 1.1 * drive.no_load_speed.max(drive.max_speed);
33    let speeds: Vec<f64> =
34        (0..CURVE_POINTS).map(|i| top * (2.0 * i as f64 / (CURVE_POINTS - 1) as f64 - 1.0)).collect();
35    let line = |f: &dyn Fn(f64) -> (f64, f64)| -> [Vec<[f64; 2]>; 2] {
36        let pairs: Vec<_> = speeds.iter().map(|&w| (w, f(w))).collect();
37        [pairs.iter().map(|&(w, (_, high))| [w, high]).collect(), pairs.iter().map(|&(w, (low, _))| [w, low]).collect()]
38    };
39    // The verdict's line, from the same source (`DriveParams::s1_torque`, `analysis::s1_torque`).
40    // Straight but for its kink at standstill and, where it falls to nothing before `top` (a static torque well above the
41    // rated one), at that speed; a printed curve kinks at each of its points.
42    let (still, rated) = (drive.s1_torque(0.0), drive.s1_torque(drive.rated_speed));
43    let zero = drive.rated_speed * still / (still - rated);
44    let mut speeds = vec![0.0, top];
45    if !drive.s1_curve.is_empty() {
46        speeds.splice(1..1, drive.s1_curve.iter().map(|p| p[0]).filter(|w| *w > 0.0 && *w < top));
47    } else if still > rated && zero < top {
48        speeds.insert(1, zero);
49    }
50    let speeds: Vec<f64> = speeds.iter().rev().map(|w| -w).chain(speeds[1..].iter().copied()).collect();
51    let s1 = |sign: f64| speeds.iter().map(|&w| [w, sign * drive.s1_torque(w)]).collect::<Vec<_>>();
52    TorqueSpeed {
53        peak: line(&|w| drive.torque_curve(w)),
54        s1: [s1(1.0), s1(-1.0)],
55        voltage: line(&|w| drive.voltage_limited_torque(w, dc_voltage)),
56        current_limit: drive.drive_max_current.is_finite().then(|| drive.torque_of(drive.drive_max_current)),
57        dc_voltage,
58    }
59}
60
61/// The DC link a run's chart is drawn at: the lowest the run's `dc_link_voltage` signal saw (the voltage limit binds
62/// hardest there), or the bus the drive is set to where the run has none.
63pub fn dc_link_of(drive: &DriveParams, dc_link: Option<&[f64]>) -> f64 {
64    dc_link.and_then(|v| v.iter().copied().filter(|u| *u > 0.0).reduce(f64::min)).unwrap_or(drive.bus_voltage)
65}
66
67/// The RMS point of a cycle, (mean |speed|, sqrt(mean torque²)): where the motor sits on its S1 curve thermally.
68/// Samples equally spaced in time, as a run's are.
69pub fn rms_point(speed: &[f64], torque: &[f64]) -> [f64; 2] {
70    let n = speed.len().min(torque.len()).max(1) as f64;
71    let mean = speed.iter().map(|w| w.abs()).sum::<f64>() / n;
72    [mean, (torque.iter().map(|t| t * t).sum::<f64>() / n).sqrt()]
73}
74
75/// An error vector split against the direction of motion: (normal, tangential). The normal part is the length of what
76/// is across the direction (the contour error), the tangential the signed part along it: with the error as setpoint
77/// less actual, positive is lagging behind. With no motion (`direction` zero) all of it is normal.
78pub fn split(error: &[f64], direction: &[f64]) -> (f64, f64) {
79    let length = direction.iter().map(|d| d * d).sum::<f64>().sqrt();
80    let total = error.iter().map(|e| e * e).sum::<f64>();
81    if length <= 0.0 {
82        return (total.sqrt(), 0.0);
83    }
84    let along = error.iter().zip(direction).map(|(e, d)| e * d).sum::<f64>() / length;
85    ((total - along * along).max(0.0).sqrt(), along)
86}
87
88/// The tool's real error over a run (`split`): the plan at each sample's time less where the tool really is (`axis_errors`;
89/// belt stretch and sag included, not the drives' encoder-side `following_error`), against the direction of
90/// their speed setpoints: of the axes in m (its place) in m, and of the axes in rad (its turn, an arm's
91/// orientation) the length in rad, apart, so that metres and radians are never added.
92#[derive(Debug, Clone, PartialEq, Default)]
93pub struct ToolError {
94    pub time: Vec<f64>,
95    /// Whether the machine has axes in m; without them `normal` and `tangential` are all zero.
96    pub place: bool,
97    pub normal: Vec<f64>,
98    pub tangential: Vec<f64>,
99    /// Empty on a machine without axes in rad.
100    pub angle: Vec<f64>,
101}
102
103/// Per axis whose unit is `unit`, the tool's error (docs/model-reference.md, "Tool position error"): the plan at the
104/// sample's time less where the tool is, `axis.<id>.position_setpoint` run on by `setpoint_age` with the speed and
105/// acceleration setpoints (`Controller::plan_now`, which the analysis measures against), less `axis.<id>.position`. A run
106/// without `setpoint_age` (a file from before it) has the age worked out from its own timing (`setpoint_age_of`). Each
107/// with its axis's speed setpoint, where the run has it.
108pub fn axis_errors<'a>(
109    signals: &[SignalInfo],
110    columns: &'a [Vec<f64>],
111    unit: &str,
112) -> Vec<(Vec<f64>, Option<&'a [f64]>)> {
113    let find = |id: &str| signals.iter().position(|s| s.id == id).map(|i| columns[i].as_slice());
114    let rebuilt = match find("setpoint_age") {
115        Some(_) => None,
116        None => {
117            let held: Vec<&[f64]> = (signals.iter().zip(columns))
118                .filter(|(s, _)| s.id.starts_with("axis.") && s.id.ends_with("_setpoint"))
119                .map(|(_, c)| c.as_slice())
120                .collect();
121            columns.first().map(|time| setpoint_age_of(time, &held))
122        }
123    };
124    let age = find("setpoint_age").or(rebuilt.as_deref());
125    signals
126        .iter()
127        .zip(columns)
128        .filter(|(s, _)| s.unit == unit && s.id.starts_with("axis.") && s.id.ends_with(".position"))
129        .filter_map(|(s, actual)| {
130            let set = find(&format!("{}_setpoint", s.id))?;
131            let (vel, acc) = (
132                find(&s.id.replace(".position", ".velocity_setpoint")),
133                find(&s.id.replace(".position", ".acceleration_setpoint")),
134            );
135            let error = (0..actual.len())
136                .map(|i| {
137                    let t = age.map_or(0.0, |a| a[i]);
138                    let at = |c: Option<&[f64]>| c.map_or(0.0, |c| c[i]);
139                    set[i] + (at(vel) + 0.5 * at(acc) * t) * t - actual[i]
140                })
141                .collect();
142            Some((error, vel))
143        })
144        .collect()
145}
146
147/// The signal `setpoint_age` of a run recorded without it, from the run's own timing: its times `time` (the simulation's,
148/// from 0) and its held setpoints `held`. The profile cycle T is the shortest time between two samples whose setpoints
149/// differ (the sample period where they differ at every sample or only once), and the controller sets them at every
150/// multiple of T in the step from there (`Controller::update`), after the sample of that moment (the CLI's `run` samples
151/// before each step): at t > 0 the age is t less the last multiple of T before it, (0, T], and 0 at t = 0. A run
152/// sampled at a multiple of its profile cycle above one (the CLI's `--every` past it) reads T as its sample period: the
153/// file does not hold the cycle then.
154pub fn setpoint_age_of(time: &[f64], held: &[&[f64]]) -> Vec<f64> {
155    let moved: Vec<f64> = (1..time.len()).filter(|&i| held.iter().any(|c| c[i] != c[i - 1])).map(|i| time[i]).collect();
156    let period = time.windows(2).map(|w| w[1] - w[0]).filter(|h| *h > 0.0).fold(f64::INFINITY, f64::min);
157    let between = moved.windows(2).map(|w| w[1] - w[0]).fold(f64::INFINITY, f64::min);
158    let cycle = if between.is_finite() { between.max(period) } else { period };
159    if !cycle.is_finite() {
160        return vec![0.0; time.len()];
161    }
162    // Ticks at whole multiples of the cycle, read with a tolerance for the times' rounding.
163    time.iter().map(|&t| if t <= 0.0 { 0.0 } else { t - cycle * ((t / cycle - 1e-6).ceil() - 1.0) }).collect()
164}
165
166/// The `ToolError` of a run's columns (`axis_errors`); `None` where the run has no axis positions with setpoints (a
167/// trace).
168pub fn tool_error(signals: &[SignalInfo], columns: &[Vec<f64>]) -> Option<ToolError> {
169    let axes = |unit: &str| axis_errors(signals, columns, unit);
170    let (place, turn) = (axes("m"), axes("rad"));
171    if place.is_empty() && turn.is_empty() {
172        return None;
173    }
174    let time = columns.first()?.clone();
175    let mut out = ToolError { time, place: !place.is_empty(), ..ToolError::default() };
176    for i in 0..out.time.len() {
177        let error: Vec<f64> = place.iter().map(|(e, _)| e[i]).collect();
178        let direction: Vec<f64> = place.iter().map(|(_, v)| v.map_or(0.0, |v| v[i])).collect();
179        let (normal, tangential) = split(&error, &direction);
180        out.normal.push(normal);
181        out.tangential.push(tangential);
182        if !turn.is_empty() {
183            out.angle.push(turn.iter().map(|(e, _)| e[i] * e[i]).sum::<f64>().sqrt());
184        }
185    }
186    Some(out)
187}
188
189/// A histogram of `values` in `bins` bins of equal width from the lowest to the highest: (lower edge, upper edge, how
190/// many). Empty for no values.
191pub fn histogram(values: &[f64], bins: usize) -> Vec<(f64, f64, usize)> {
192    let Some(low) = values.iter().copied().reduce(f64::min) else { return Vec::new() };
193    let high = values.iter().copied().fold(low, f64::max);
194    let (bins, width) = (bins.max(1), ((high - low) / bins.max(1) as f64).max(f64::MIN_POSITIVE));
195    let mut counts = vec![0; bins];
196    for v in values {
197        counts[(((v - low) / width) as usize).min(bins - 1)] += 1;
198    }
199    counts.into_iter().enumerate().map(|(i, n)| (low + i as f64 * width, low + (i + 1) as f64 * width, n)).collect()
200}
201
202/// A motor's torque split (`TORQUE_PARTS`, the signals `motor.<id>.torque_<part>`) as the run has it: (part, values),
203/// in the order of `TORQUE_PARTS`; empty where the machine reports none.
204pub fn torque_parts<'a>(
205    signals: &[SignalInfo],
206    columns: &'a [Vec<f64>],
207    motor: &str,
208) -> Vec<(&'static str, &'a [f64])> {
209    TORQUE_PARTS
210        .iter()
211        .filter_map(|part| {
212            let id = format!("motor.{motor}.torque_{part}");
213            signals.iter().position(|s| s.id == id).map(|i| (*part, columns[i].as_slice()))
214        })
215        .collect()
216}
217
218/// Parts stacked: the first, the first two added, and so on; the last line is their sum, the motor torque.
219pub fn stack(parts: &[&[f64]]) -> Vec<Vec<f64>> {
220    let mut sum = vec![0.0; parts.iter().map(|p| p.len()).min().unwrap_or(0)];
221    parts
222        .iter()
223        .map(|part| {
224            sum.iter_mut().zip(*part).for_each(|(s, p)| *s += p);
225            sum.clone()
226        })
227        .collect()
228}
229
230/// The torque the drive has available at a speed in the direction of `torque`: the torque-speed curve
231/// (`DriveParams::torque_curve`), and the torque of the drive's maximum current where that is lower.
232pub fn available_torque(drive: &DriveParams, speed: f64, torque: f64) -> f64 {
233    let (low, high) = drive.torque_curve(speed);
234    let curve = if torque >= 0.0 { high } else { -low };
235    if drive.drive_max_current.is_finite() { curve.min(drive.torque_of(drive.drive_max_current)) } else { curve }
236}
237
238/// How much of what is available at its speed a torque uses (`available_torque`): 1 is all of it. Infinite where
239/// nothing is available and some torque is asked.
240pub fn torque_utilisation(drive: &DriveParams, speed: f64, torque: f64) -> f64 {
241    let available = available_torque(drive, speed, torque);
242    if torque == 0.0 {
243        0.0
244    } else if available > 0.0 {
245        torque.abs() / available
246    } else {
247        f64::INFINITY
248    }
249}
250
251/// The current the winding may carry: the motor's maximum current, or the drive's where that is lower.
252pub fn current_limit(drive: &DriveParams) -> f64 {
253    drive.max_current.min(drive.drive_max_current)
254}
255
256/// One line of the utilisation timeline (`utilisation`): its name (a translation key) and its share of its limit per
257/// sample.
258pub type Share = (&'static str, Vec<f64>);
259
260/// A motor's utilisation over a run, each as a share of its limit, 1 at the limit: torque against what is available at
261/// its speed; the phase current (q and d) against `current_limit`; the drive's two overload image nodes against the
262/// image's trip level (with effects.drive_overload); winding and housing rise against the rated rise (the housing's
263/// against `ratings.housing_max_rise_k` where the config has it, else the same; with
264/// effects.winding_heating; the housing's with effects.motor_thermal_nodes); and the DC link voltage against the
265/// overvoltage trip, with the braking threshold below it. Only the lines whose signals the run has and whose effect
266/// was on.
267pub fn utilisation(drive: &DriveParams, signals: &[SignalInfo], columns: &[Vec<f64>], motor: &str) -> Vec<Share> {
268    let get = |name: &str| {
269        let id = format!("motor.{motor}.{name}");
270        signals.iter().position(|s| s.id == id).map(|i| columns[i].as_slice())
271    };
272    let mut out = Vec::new();
273    if let (Some(speed), Some(torque)) = (get("speed"), get("torque")) {
274        let share = speed.iter().zip(torque).map(|(w, t)| torque_utilisation(drive, *w, *t)).collect();
275        out.push(("charts-torque", share));
276    }
277    if let Some(current) = get("current") {
278        let d = get("d_current");
279        let limit = current_limit(drive);
280        let share = (0..current.len()).map(|i| current[i].hypot(d.map_or(0.0, |d| d[i])) / limit).collect();
281        out.push(("charts-current", share));
282    }
283    if let (Some(o), Some(image), Some(chip)) =
284        (&drive.overload, get("drive_overload_image"), get("drive_overload_chip"))
285    {
286        out.push(("charts-overload-slow", image.iter().zip(chip).map(|(i, c)| (i - c) / o.trip).collect()));
287        out.push(("charts-overload-chip", chip.iter().map(|c| c / o.trip).collect()));
288        // The trip is on their sum.
289        out.push(("charts-overload-total", image.iter().map(|i| i / o.trip).collect()));
290    }
291    if drive.heating {
292        if let Some(rise) = get("winding_temperature") {
293            out.push(("charts-winding", rise.iter().map(|r| r / drive.rated_rise).collect()));
294        }
295        if let (Some(_), Some(rise)) = (drive.thermal_nodes, get("housing_temperature")) {
296            out.push(("charts-housing", rise.iter().map(|r| r / drive.housing_max_rise).collect()));
297        }
298    }
299    if let (true, Some(u)) =
300        (drive.dc_link && drive.overvoltage.is_finite() && drive.overvoltage > 0.0, get("dc_link_voltage"))
301    {
302        out.push(("charts-dc-link", u.iter().map(|u| u / drive.overvoltage).collect()));
303    }
304    out
305}
306
307/// The DC link's braking threshold as a share of its overvoltage trip, for the utilisation timeline; `None` without
308/// the DC link simulated.
309pub fn braking_share(drive: &DriveParams) -> Option<f64> {
310    (drive.dc_link && drive.overvoltage.is_finite() && drive.overvoltage > 0.0)
311        .then(|| drive.braking_threshold / drive.overvoltage)
312}
313
314/// The amplitude spectrum of samples `dt` apart: (frequency Hz, amplitude) from 0 to the Nyquist frequency. Of the
315/// samples, zero-padded to a power of two, mean removed, through a Hann window; a sine of amplitude A on a bin gives A there.
316/// Empty for fewer than 8 samples.
317pub fn spectrum(values: &[f64], dt: f64) -> Vec<[f64; 2]> {
318    if values.len() < 8 {
319        return Vec::new();
320    }
321    let n = values.len().next_power_of_two();
322    let amplitudes = hann_amplitudes(values, n);
323    amplitudes.iter().enumerate().map(|(k, a)| [k as f64 / (n as f64 * dt), *a]).collect()
324}
325
326/// A spectrogram of samples `dt` apart: frames of `frame` samples (a power of two) every half frame, each frame's
327/// amplitudes as `spectrum` gives them. With the time of each frame's middle and the bin width in Hz.
328#[derive(Debug, Clone, PartialEq, Default)]
329pub struct Spectrogram {
330    pub times: Vec<f64>,
331    pub bin_hz: f64,
332    pub frames: Vec<Vec<f64>>,
333}
334
335/// The `Spectrogram` of `values`, whose first sample is at `start` s.
336pub fn spectrogram(values: &[f64], dt: f64, start: f64, frame: usize) -> Spectrogram {
337    let frame = frame.next_power_of_two().max(8);
338    let hop = frame / 2;
339    let mut out = Spectrogram { bin_hz: 1.0 / (frame as f64 * dt), ..Spectrogram::default() };
340    let mut at = 0;
341    while at + frame <= values.len() {
342        out.times.push(start + (at + frame / 2) as f64 * dt);
343        out.frames.push(hann_amplitudes(&values[at..at + frame], frame));
344        at += hop;
345    }
346    out
347}
348
349/// The amplitudes of bins 0 to n / 2 of the samples zero-padded to `n` (a power of two), mean removed, Hann-windowed over
350/// the real samples and scaled by 2 / the window's sum, so that a sine on a bin shows its amplitude.
351fn hann_amplitudes(values: &[f64], n: usize) -> Vec<f64> {
352    let m = values.len();
353    let mean = values.iter().sum::<f64>() / m as f64;
354    let window = |i: usize| 0.5 - 0.5 * (std::f64::consts::TAU * i as f64 / m as f64).cos();
355    let mut re: Vec<f64> = values.iter().enumerate().map(|(i, v)| (v - mean) * window(i)).collect();
356    re.resize(n, 0.0);
357    let mut im = vec![0.0; n];
358    fft(&mut re, &mut im);
359    let scale = 2.0 / (0..m).map(window).sum::<f64>();
360    (0..=n / 2).map(|k| re[k].hypot(im[k]) * scale).collect()
361}
362
363/// The discrete Fourier transform in place, radix 2 (the length a power of two): X_k = sum x_j e^(-2 pi i j k / n).
364fn fft(re: &mut [f64], im: &mut [f64]) {
365    let n = re.len();
366    let mut j = 0;
367    for i in 1..n {
368        let mut bit = n >> 1;
369        while j & bit != 0 {
370            j ^= bit;
371            bit >>= 1;
372        }
373        j |= bit;
374        if i < j {
375            re.swap(i, j);
376            im.swap(i, j);
377        }
378    }
379    let mut len = 2;
380    while len <= n {
381        let angle = -std::f64::consts::TAU / len as f64;
382        for start in (0..n).step_by(len) {
383            for k in 0..len / 2 {
384                let (wr, wi) = ((angle * k as f64).cos(), (angle * k as f64).sin());
385                let (a, b) = (start + k, start + k + len / 2);
386                let (tr, ti) = (re[b] * wr - im[b] * wi, re[b] * wi + im[b] * wr);
387                (re[b], im[b]) = (re[a] - tr, im[a] - ti);
388                (re[a], im[a]) = (re[a] + tr, im[a] + ti);
389            }
390        }
391        len <<= 1;
392    }
393}
394
395/// The voltage limit at a DC link, as the winding gets it (`WINDING_PER_DC_LINK`), for labels.
396pub fn winding_voltage(dc_voltage: f64) -> f64 {
397    WINDING_PER_DC_LINK * dc_voltage
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403    use crate::drive::FieldWeakening;
404
405    /// A drive without field weakening: kt = kE = 1 N m/A, R = 2 Ohm, 10 A at most, peak 10 N m, rated 4 N m at
406    /// 100 rad/s, no-load 200 rad/s, on a DC link of 300 V.
407    fn drive() -> DriveParams {
408        DriveParams {
409            kt: 1.0,
410            ke: 1.0,
411            resistance: 2.0,
412            max_current: 10.0,
413            saturation: 0.0,
414            peak_torque: 10.0,
415            rated_torque: 4.0,
416            rated_speed: 100.0,
417            no_load_speed: 200.0,
418            max_speed: 200.0,
419            bus_voltage: 300.0,
420            drive_max_current: f64::INFINITY,
421            field_weakening: None,
422            ..crate::drive::tests::params()
423        }
424    }
425
426    /// Without field weakening the steady winding meets R i + kE w = U: at 400 rad/s on 300 V the winding has
427    /// sqrt(3/2) * 300 = 367.42 V, so motoring i = (367.42 - 400) / 2 < 0, none; at 300 rad/s (367.42 - 300) / 2 =
428    /// 33.7 A, held at 10 A, 10 N m; at 360 rad/s 3.712 A, 3.712 N m. Braking at 360 rad/s: (367.42 + 360) / 2, held at
429    /// 10 A. The chart's curve at each of its speeds is the motor model's.
430    #[test]
431    fn the_voltage_limit_without_field_weakening_is_the_hand_calculated_one_and_the_chart_follows_it() {
432        let p = drive();
433        let u = WINDING_PER_DC_LINK * 300.0;
434        assert!((u - 367.423).abs() < 1e-3);
435        assert_eq!(p.voltage_limited_torque(400.0, 300.0).1, 0.0);
436        assert_eq!(p.voltage_limited_torque(300.0, 300.0).1, 10.0);
437        let at_360 = p.voltage_limited_torque(360.0, 300.0);
438        assert!((at_360.1 - (u - 360.0) / 2.0).abs() < 1e-12 && (at_360.1 - 3.7117).abs() < 1e-4, "{at_360:?}");
439        assert_eq!(at_360.0, -10.0);
440        assert_eq!(p.voltage_limited_torque(-360.0, 300.0), (-at_360.1, 10.0));
441        let chart = torque_speed(&p, 300.0);
442        assert_eq!(chart.voltage[0].len(), CURVE_POINTS);
443        for (high, low) in chart.voltage[0].iter().zip(&chart.voltage[1]) {
444            let (l, h) = p.voltage_limited_torque(high[0], 300.0);
445            assert!(high[1] == h && low[1] == l && high[0] == low[0]);
446        }
447        // Standstill is sampled, and the speeds reach 1.1 times the no-load speed.
448        assert!(chart.voltage[0].iter().any(|p| p[0] == 0.0));
449        assert!((chart.peak[0].last().unwrap()[0] - 220.0).abs() < 1e-9);
450    }
451
452    /// With field weakening the voltage limit at 540 V is the d-q model's of the drive's own test
453    /// (`the_voltage_limit_gives_the_hand_calculated_torque_from_r_l_and_the_dc_link`): 15.614 N m at 600 rad/s by hand,
454    /// and it does not stop at the peak torque, which `torque_curve` caps at.
455    #[test]
456    fn the_voltage_limit_with_field_weakening_is_the_d_q_models() {
457        let kt: f64 = 6.0 / 4.7;
458        let inductance = kt * kt / (2.0 * 4.0 * 13.0);
459        let p = DriveParams {
460            kt,
461            ke: kt,
462            inductance,
463            max_current: 15.1,
464            peak_torque: 12.0,
465            max_voltage: WINDING_PER_DC_LINK * 540.0,
466            field_weakening: Some(FieldWeakening { pole_pairs: 4.0, d_inductance: inductance }),
467            ..drive()
468        };
469        let at_600 = p.voltage_limited_torque(600.0, 540.0).1;
470        assert!((at_600 - 15.614).abs() < 2e-3, "{at_600} N m");
471        assert_eq!(p.torque_curve(600.0).1, 12.0);
472    }
473
474    /// The RMS point of speeds 1, -3, 2, 0 rad/s and torques 1, -2, 3, 0 N m: mean |speed| 6 / 4 = 1.5, RMS torque
475    /// sqrt((1 + 4 + 9 + 0) / 4) = sqrt(3.5) = 1.8708.
476    #[test]
477    fn the_rms_point_is_the_root_mean_square_torque_at_the_mean_speed() {
478        let [speed, torque] = rms_point(&[1.0, -3.0, 2.0, 0.0], &[1.0, -2.0, 3.0, 0.0]);
479        assert_eq!(speed, 1.5);
480        assert!((torque - 3.5f64.sqrt()).abs() < 1e-12 && (torque - 1.8708).abs() < 1e-4);
481    }
482
483    /// On a straight line along (3, 4) (unit (0.6, 0.8)) an error of (1, 0) mm: along it 0.6 mm (lagging), across it
484    /// sqrt(1 - 0.36) = 0.8 mm. An error of (0, 2) mm with the motion along x: 2 mm across, none along. Standing still,
485    /// all of it is across.
486    #[test]
487    fn a_known_offset_on_a_straight_line_splits_into_its_normal_and_tangential_parts() {
488        let (normal, along) = split(&[1e-3, 0.0], &[3.0, 4.0]);
489        assert!((normal - 0.8e-3).abs() < 1e-15 && (along - 0.6e-3).abs() < 1e-15, "{normal} {along}");
490        assert_eq!(split(&[0.0, 2e-3], &[0.5, 0.0]), (2e-3, 0.0));
491        let (normal, along) = split(&[-1e-3, 0.0], &[0.5, 0.0]);
492        assert!(normal == 0.0 && along == -1e-3);
493        assert_eq!(split(&[3e-3, 4e-3], &[0.0, 0.0]), (5e-3, 0.0));
494        // The same from a run's columns: two axes in m, the motion along x, the error 1 mm along and 2 mm across, each
495        // sample taken as its setpoints were set.
496        let signals = [
497            "time",
498            "setpoint_age",
499            "axis.x.position",
500            "axis.x.position_setpoint",
501            "axis.x.velocity_setpoint",
502            "axis.y.position",
503            "axis.y.position_setpoint",
504        ]
505        .map(|id| SignalInfo::new(id, "k", "q", if id == "time" { "s" } else { "m" }));
506        let columns = vec![
507            vec![0.0, 1e-3],
508            vec![0.0, 0.0],
509            vec![0.1, 0.2],
510            vec![0.101, 0.201],
511            vec![0.2, 0.2],
512            vec![0.0, 0.0],
513            vec![2e-3, -2e-3],
514        ];
515        let e = tool_error(&signals, &columns).unwrap();
516        let near = |v: &[f64], x: f64| v.iter().all(|v| (v - x).abs() < 1e-15);
517        assert!(near(&e.normal, 2e-3) && near(&e.tangential, 1e-3) && e.angle.is_empty() && e.place, "{e:?}");
518    }
519
520    /// A machine with one axis in rad only: no place, the error is the angle 0.01 rad (setpoint 0.2 less actual 0.19).
521    #[test]
522    fn a_machine_without_an_axis_in_metres_has_its_error_in_the_angle() {
523        let signals = ["time", "axis.a.position", "axis.a.position_setpoint"]
524            .map(|id| SignalInfo::new(id, "k", "q", if id == "time" { "s" } else { "rad" }));
525        let columns = vec![vec![0.0, 1e-3], vec![0.19, 0.19], vec![0.2, 0.2]];
526        let e = tool_error(&signals, &columns).unwrap();
527        assert!(!e.place && e.normal.iter().all(|v| *v == 0.0), "{e:?}");
528        assert!(e.angle.iter().all(|v| (v - 0.01).abs() < 1e-12), "{e:?}");
529    }
530
531    /// The setpoint held 0.8 ms at 1 m/s and 10 m/s²: the plan now is 0.1 + (1 + 5 * 0.0008) * 0.0008 = 0.1008032 m, so a
532    /// tool at 0.1008 m is 3.2 um behind it, not the 0.8 mm ahead of the held setpoint it reads as without the age.
533    #[test]
534    fn the_tool_error_is_against_the_plan_at_the_samples_time() {
535        let ids = ["time", "setpoint_age", "axis.x.position", "axis.x.position_setpoint", "axis.x.velocity_setpoint"];
536        let mut signals: Vec<SignalInfo> = ids.map(|id| SignalInfo::new(id, "k", "q", "m")).to_vec();
537        signals.push(SignalInfo::new("axis.x.acceleration_setpoint", "k", "q", "m/s²"));
538        let columns = vec![vec![0.0], vec![8e-4], vec![0.1008], vec![0.1], vec![1.0], vec![10.0]];
539        let e = tool_error(&signals, &columns).unwrap();
540        assert!((e.tangential[0] - 3.2e-6).abs() < 1e-12 && e.normal[0] < 1e-12, "{e:?}");
541        let held = tool_error(&signals[..1].iter().chain(&signals[2..]).cloned().collect::<Vec<_>>(), &{
542            let mut c = columns.clone();
543            c.remove(1);
544            c
545        })
546        .unwrap();
547        assert!((held.tangential[0] + 8e-4).abs() < 1e-12, "{held:?}");
548    }
549
550    /// Samples every 0.25 ms, the setpoint set at every whole ms after the sample of that moment: it changes at the
551    /// samples at 1.25 and 2.25 ms, so the cycle is 1 ms and the ages 0 (the start), 0.25, 0.5, 0.75, 1 ms, 0.25 ms, ...
552    /// Sampled every ms, the setpoints change at every sample and each is a whole cycle old.
553    #[test]
554    fn the_setpoint_age_of_a_run_without_it_follows_from_its_timing() {
555        let time: Vec<f64> = (0..13).map(|i| i as f64 * 2.5e-4).collect();
556        let set = [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0];
557        let age = setpoint_age_of(&time, &[&set]);
558        let by_hand = [0.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0].map(|a| a * 1e-3);
559        assert!(age.iter().zip(by_hand).all(|(a, b)| (a - b).abs() < 1e-15), "{age:?}");
560        let coarse = setpoint_age_of(&[0.0, 1e-3, 2e-3], &[&[0.0, 1.0, 2.0]]);
561        assert!(coarse.iter().zip([0.0, 1e-3, 1e-3]).all(|(a, b)| (a - b).abs() < 1e-15), "{coarse:?}");
562        assert_eq!(setpoint_age_of(&[0.0], &[&[0.0]]), [0.0]);
563    }
564
565    /// The drawn line read at a speed, straight between its points.
566    fn drawn(line: &[[f64; 2]], speed: f64) -> f64 {
567        let i = line.windows(2).position(|w| w[0][0] <= speed && speed <= w[1][0]).unwrap();
568        let ([a, ta], [b, tb]) = (line[i], line[i + 1]);
569        ta + (tb - ta) * (speed - a) / (b - a)
570    }
571
572    /// S1 from k_t I_0 = 0.45 * 4 = 1.8 N m at standstill to 1.2 N m at the rated 100 rad/s: at 150 rad/s the line has
573    /// 1.8 - 0.6 * 1.5 = 0.9 N m (the verdict's `s1_torque`), standstill 1.8, both directions; at 300 rad/s it reaches
574    /// nothing and stays there (a corner of the drawn line, not a line through it below 0).
575    #[test]
576    fn the_s1_line_runs_from_the_static_torque_to_the_rated_one_and_on() {
577        let p = DriveParams { kt: 0.45, static_torque: 1.8, rated_torque: 1.2, rated_speed: 100.0, ..drive() };
578        let c = torque_speed(&p, 300.0);
579        let top = c.s1[0].last().unwrap()[0];
580        assert!((drawn(&c.s1[0], 0.0) - 1.8).abs() < 1e-12 && (drawn(&c.s1[1], 0.0) + 1.8).abs() < 1e-12);
581        assert!((drawn(&c.s1[0], 150.0) - 0.9).abs() < 1e-9 && (drawn(&c.s1[0], -150.0) - 0.9).abs() < 1e-9);
582        for w in [250.0, 300.0, 0.5 * (300.0 + top), top].into_iter().filter(|w| *w <= top) {
583            assert!((drawn(&c.s1[0], w) - p.s1_torque(w)).abs() < 1e-9, "{w}: {:?}", c.s1[0]);
584        }
585    }
586
587    /// The housing's rise of 30 K against `ratings.housing_max_rise_k` = 60 K is 0.5 of it, the winding's 80 K against its
588    /// rated 100 K 0.8; without the key the housing is held against the winding's 100 K, 0.3, as before.
589    #[test]
590    fn the_housing_is_held_against_its_own_highest_rise() {
591        let signals = ["winding_temperature", "housing_temperature"]
592            .map(|q| SignalInfo::new(format!("motor.x.{q}"), "", "", "K"))
593            .to_vec();
594        let columns = vec![vec![80.0], vec![30.0]];
595        let nodes = Some(crate::drive::ThermalNodes { winding_share: 0.25, winding_time_constant: 60.0 });
596        let p =
597            DriveParams { heating: true, thermal_nodes: nodes, rated_rise: 100.0, housing_max_rise: 60.0, ..drive() };
598        let shares = |p: &DriveParams| utilisation(p, &signals, &columns, "x");
599        assert_eq!(shares(&p), [("charts-winding", vec![0.8]), ("charts-housing", vec![0.5])]);
600        assert_eq!(shares(&DriveParams { housing_max_rise: 100.0, ..p })[1], ("charts-housing", vec![0.3]));
601    }
602
603    /// A printed S1 curve, (0, 2.0), (50, 1.5), (150, 0.5) N m: the drawn line passes through each of its points both
604    /// ways (between them straight, as `s1_interpolated` reads it: at 100 rad/s 1.0 N m) and holds the last torque beyond,
605    /// up to the chart's top (220 rad/s for this drive).
606    #[test]
607    fn the_chart_draws_a_printed_s1_curve_through_its_points() {
608        let p = DriveParams { s1_curve: vec![[0.0, 2.0], [50.0, 1.5], [150.0, 0.5]], ..drive() };
609        let c = torque_speed(&p, 300.0);
610        let top = c.s1[0].last().unwrap()[0];
611        assert!(top > 150.0, "{top}");
612        for (w, t) in [(0.0, 2.0), (50.0, 1.5), (100.0, 1.0), (150.0, 0.5), (top, 0.5)] {
613            assert!((drawn(&c.s1[0], w) - t).abs() < 1e-12 && (drawn(&c.s1[0], -w) - t).abs() < 1e-12, "{w}: {c:?}");
614            assert!((drawn(&c.s1[1], w) + t).abs() < 1e-12, "{w}");
615        }
616    }
617
618    /// With effects.iron_loss off the drive's stall current is the rated one (2 A, `stall_current`), but the config's
619    /// `motor.stall_current_a` (4 A) still sets the verdict's static torque 0.45 * 4 = 1.8 N m: the chart draws that, 1.8 N m
620    /// at standstill and 1.2 N m at the rated speed, not a flat 1.2 N m. Without a stall current it is flat at the rated
621    /// torque.
622    #[test]
623    fn the_s1_line_takes_the_static_torque_from_the_stall_current_key_without_iron_loss() {
624        let p = DriveParams {
625            kt: 0.45,
626            stall_current: 2.0,
627            static_torque: 1.8,
628            rated_torque: 1.2,
629            rated_speed: 100.0,
630            ..drive()
631        };
632        assert!((p.s1_torque(0.0) - 1.8).abs() < 1e-12 && (p.s1_torque(-100.0) - 1.2).abs() < 1e-12);
633        let c = torque_speed(&p, 300.0);
634        assert!((drawn(&c.s1[0], 0.0) - 1.8).abs() < 1e-12);
635        let flat = DriveParams { static_torque: 0.0, ..p };
636        assert!((flat.s1_torque(0.0) - 1.2).abs() < 1e-12 && (flat.s1_torque(150.0) - 1.2).abs() < 1e-12);
637    }
638
639    /// 300 samples (not a power of two) of a sine of 0.3 on a bin of the padded 512: the whole run is used, so the
640    /// spectrum has 257 bins and the amplitude near the bin is 0.3 within the leakage of the zero padding.
641    #[test]
642    fn the_spectrum_pads_to_the_next_power_of_two_and_keeps_the_amplitude() {
643        let (dt, hz) = (1e-3, 100.0);
644        let values: Vec<f64> = (0..300).map(|i| 0.3 * (std::f64::consts::TAU * hz * i as f64 * dt).sin()).collect();
645        let s = spectrum(&values, dt);
646        assert_eq!(s.len(), 257);
647        let top = s.iter().max_by(|a, b| a[1].total_cmp(&b[1])).unwrap();
648        assert!((top[0] - hz).abs() < 4.0 && (top[1] - 0.3).abs() < 0.03, "{top:?}");
649    }
650
651    /// A sine of 0.3 on bin 50 of 1024 samples 1 ms apart, 48.828 Hz, plus an offset: the spectrum's highest bin is
652    /// bin 50 at 50 / 1.024 s, with the amplitude 0.3 (Hann, scaled by 2 / the window's sum).
653    #[test]
654    fn the_spectrum_of_a_pure_sine_lands_at_its_bin() {
655        let (n, dt, k) = (1024, 1e-3, 50.0);
656        let hz = k / (n as f64 * dt);
657        let values: Vec<f64> =
658            (0..n).map(|i| 2.0 + 0.3 * (std::f64::consts::TAU * hz * i as f64 * dt + 0.4).sin()).collect();
659        let s = spectrum(&values, dt);
660        assert_eq!(s.len(), n / 2 + 1);
661        let top = s.iter().enumerate().max_by(|a, b| a.1[1].total_cmp(&b.1[1])).unwrap();
662        assert_eq!(top.0, 50);
663        assert!((top.1[0] - 48.828125).abs() < 1e-9 && (top.1[1] - 0.3).abs() < 1e-9, "{:?}", top.1);
664        // The spectrogram's frames see the same bin: frames of 256 give bins 4 times wider, so bin 12.5, between 12 and 13.
665        let g = spectrogram(&values, dt, 0.0, 256);
666        assert_eq!((g.frames.len(), g.bin_hz), (7, 1.0 / 0.256));
667        let peak = g.frames[3].iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1)).unwrap().0;
668        assert!(peak == 12 || peak == 13);
669    }
670
671    /// Parts 1, -0.5 and 2 N m stack to 1, 0.5 and 2.5: the last is the sum.
672    #[test]
673    fn stacked_parts_end_at_their_sum() {
674        let parts: [&[f64]; 3] = [&[1.0, 0.0], &[-0.5, 1.0], &[2.0, -1.0]];
675        assert_eq!(stack(&parts), vec![vec![1.0, 0.0], vec![0.5, 1.0], vec![2.5, 0.0]]);
676    }
677
678    /// At 150 rad/s the peak fades linearly from 10 N m at 100 rad/s to none at 200 rad/s: 5 N m available, so 2.5 N m
679    /// uses half of it. Braking at that speed the full 10 N m is there: -2.5 N m uses a quarter. A drive limited to
680    /// 4 A (4 N m) leaves 4 N m: 2.5 / 4 = 0.625.
681    #[test]
682    fn the_utilisation_is_the_torque_over_what_is_available_at_that_speed() {
683        let p = drive();
684        assert_eq!(available_torque(&p, 150.0, 2.5), 5.0);
685        assert_eq!(torque_utilisation(&p, 150.0, 2.5), 0.5);
686        assert_eq!(torque_utilisation(&p, 150.0, -2.5), 0.25);
687        let limited = DriveParams { drive_max_current: 4.0, ..p };
688        assert_eq!(torque_utilisation(&limited, 150.0, 2.5), 0.625);
689        assert_eq!(current_limit(&limited), 4.0);
690        assert_eq!(torque_speed(&limited, 300.0).current_limit, Some(4.0));
691    }
692
693    /// Values 0, 1, 1, 2, 4 in 4 bins from 0 to 4: one each in [0, 1) and [2, 3), two in [1, 2), the top one in the last.
694    #[test]
695    fn a_histogram_counts_each_value_once() {
696        let h = histogram(&[0.0, 1.0, 1.0, 2.0, 4.0], 4);
697        assert_eq!(h.iter().map(|b| b.2).collect::<Vec<_>>(), vec![1, 2, 1, 1]);
698        assert_eq!((h[0].0, h[3].1), (0.0, 4.0));
699    }
700}