1use crate::drive::{DriveParams, WINDING_PER_DC_LINK};
7use sim_core::{SignalInfo, TORQUE_PARTS};
8
9pub const CURVE_POINTS: usize = 241;
12
13#[derive(Debug, Clone, PartialEq)]
15pub struct TorqueSpeed {
16 pub peak: [Vec<[f64; 2]>; 2],
18 pub s1: [Vec<[f64; 2]>; 2],
21 pub voltage: [Vec<[f64; 2]>; 2],
23 pub current_limit: Option<f64>,
25 pub dc_voltage: f64,
26}
27
28pub 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 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
61pub 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
67pub 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
75pub 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#[derive(Debug, Clone, PartialEq, Default)]
93pub struct ToolError {
94 pub time: Vec<f64>,
95 pub place: bool,
97 pub normal: Vec<f64>,
98 pub tangential: Vec<f64>,
99 pub angle: Vec<f64>,
101}
102
103pub 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
147pub 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 time.iter().map(|&t| if t <= 0.0 { 0.0 } else { t - cycle * ((t / cycle - 1e-6).ceil() - 1.0) }).collect()
164}
165
166pub 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
189pub 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
202pub 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
218pub 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
230pub 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
238pub 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
251pub fn current_limit(drive: &DriveParams) -> f64 {
253 drive.max_current.min(drive.drive_max_current)
254}
255
256pub type Share = (&'static str, Vec<f64>);
259
260pub 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 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
307pub 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
314pub 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#[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
335pub 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
349fn 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
363fn 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
395pub 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 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 #[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 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 #[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 #[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 #[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 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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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}