1use sim_components::Sim;
8use sim_components::analysis::Verdict;
9use sim_components::charts::{self, TorqueSpeed};
10use sim_components::drive::DriveParams;
11use sim_core::{AxisInfo, MotorInfo, SignalInfo};
12use std::borrow::Cow;
13
14pub use sim_components::report::peak_keeping;
15
16pub const PLOT_BUCKETS: usize = 3000;
18pub const MODE_POSES: usize = 5;
20
21pub fn plot_line(n: usize, point: impl Fn(usize) -> [f64; 2]) -> Vec<[f64; 2]> {
24 peak_keeping(n, point, PLOT_BUCKETS)
25}
26
27#[derive(Debug, Clone, Default)]
30pub struct History {
31 data: Vec<f64>,
32 width: usize,
33 capacity: usize,
34 head: usize,
36 len: usize,
37 pushed: u64,
39}
40
41impl History {
42 pub fn new(capacity: usize) -> Self {
43 Self { capacity: capacity.max(1), ..Self::default() }
44 }
45
46 pub fn push(&mut self, row: &[f64]) {
49 if row.len() != self.width {
50 *self = Self { pushed: self.pushed, ..Self::new(self.capacity) };
51 self.width = row.len();
52 }
53 if self.len < self.capacity {
54 self.data.extend_from_slice(row);
55 self.len += 1;
56 } else {
57 let w = self.width;
58 self.data[self.head * w..][..w].copy_from_slice(row);
59 self.head = (self.head + 1) % self.capacity;
60 }
61 self.pushed += 1;
62 }
63
64 pub fn len(&self) -> usize {
65 self.len
66 }
67
68 pub fn is_empty(&self) -> bool {
69 self.len == 0
70 }
71
72 pub fn pushed(&self) -> u64 {
73 self.pushed
74 }
75
76 pub fn get(&self, i: usize) -> Option<&[f64]> {
78 (i < self.len).then(|| &self.data[(self.head + i) % self.capacity * self.width..][..self.width])
79 }
80
81 pub fn back(&self) -> Option<&[f64]> {
82 self.len.checked_sub(1).and_then(|i| self.get(i))
83 }
84
85 pub fn iter(&self) -> impl DoubleEndedIterator<Item = &[f64]> + ExactSizeIterator + Clone {
86 (0..self.len).map(|i| &self.data[(self.head + i) % self.capacity * self.width..][..self.width])
87 }
88
89 pub fn first_at(&self, time: f64) -> usize {
91 let (mut low, mut high) = (0, self.len);
92 while low < high {
93 let mid = (low + high) / 2;
94 if self.data[(self.head + mid) % self.capacity * self.width] < time {
95 low = mid + 1;
96 } else {
97 high = mid;
98 }
99 }
100 low
101 }
102
103 pub fn tail(&self, from: usize) -> Self {
105 let mut out = Self::new((self.len - from.min(self.len)).max(1));
106 (from..self.len).filter_map(|i| self.get(i)).for_each(|row| out.push(row));
107 out
108 }
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum RunKind {
114 Live,
116 Ghost,
118 Cycle,
120 Path,
122 Trace,
124}
125
126impl RunKind {
127 pub fn key(self) -> &'static str {
129 match self {
130 Self::Live => "ui-run-live",
131 Self::Ghost => "ui-run-ghost",
132 Self::Cycle => "ui-run-cycle",
133 Self::Path => "ui-run-path",
134 Self::Trace => "ui-run-trace",
135 }
136 }
137}
138
139#[derive(Debug, Clone)]
141pub struct Run {
142 pub label: String,
144 pub kind: RunKind,
145 pub machine: &'static str,
147 pub signals: Vec<SignalInfo>,
148 pub motors: Vec<String>,
150 pub ratings: Vec<(f64, f64)>,
152 pub drives: Vec<DriveParams>,
154 pub modes: Vec<f64>,
157 pub modes_along: Vec<(f64, Vec<f64>)>,
159 pub off_path: Vec<[f64; 3]>,
162 pub columns: Vec<Vec<f64>>,
164 pub verdicts: Option<Vec<Verdict>>,
166}
167
168impl Run {
169 pub fn from_rows<'a>(
171 label: String,
172 kind: RunKind,
173 machine: &'static str,
174 signals: Vec<SignalInfo>,
175 motors: &[MotorInfo],
176 rows: impl IntoIterator<Item = &'a [f64]>,
177 ) -> Self {
178 let mut columns = vec![Vec::new(); signals.len()];
179 for row in rows {
180 columns.iter_mut().zip(row).for_each(|(column, v)| column.push(*v));
181 }
182 if let Some(&start) = columns.first().and_then(|time| time.first()) {
183 columns[0].iter_mut().for_each(|t| *t -= start);
184 }
185 let motors = motors.iter().map(|m| m.id.to_string()).collect();
186 Self {
187 label,
188 kind,
189 machine,
190 signals,
191 motors,
192 ratings: Vec::new(),
193 drives: Vec::new(),
194 modes: Vec::new(),
195 modes_along: Vec::new(),
196 off_path: Vec::new(),
197 columns,
198 verdicts: None,
199 }
200 }
201
202 pub fn from_trace(
204 label: String,
205 machine: &'static str,
206 motors: &[MotorInfo],
207 trace: &sim_components::trace::Trace,
208 ) -> Self {
209 let mut signals = vec![SignalInfo::new("time", "group-sim", "quantity-time", "s")];
210 let mut columns = vec![trace.time.iter().map(|t| t - trace.time.first().unwrap_or(&0.0)).collect()];
211 for (motor, m) in motors.iter().zip(&trace.motors) {
212 let named = |name: &str, unit: &str| {
213 let quantity = format!("quantity-{}", name.replace('_', "-"));
214 SignalInfo::new(format!("motor.{}.{name}", motor.id), motor.key, &quantity, unit)
215 };
216 signals.extend([
217 named("angle", "rad"),
218 named("speed", "rad/s"),
219 named("torque", "N m"),
220 named("following_error", "rad"),
221 ]);
222 columns.extend([m.angle.clone(), m.speed.clone(), m.torque.clone(), m.following_error()]);
223 }
224 let motors = motors.iter().map(|m| m.id.to_string()).collect();
225 Self {
226 label,
227 kind: RunKind::Trace,
228 machine,
229 signals,
230 motors,
231 ratings: Vec::new(),
232 drives: Vec::new(),
233 modes: Vec::new(),
234 modes_along: Vec::new(),
235 off_path: Vec::new(),
236 columns,
237 verdicts: None,
238 }
239 }
240
241 pub fn rated(self, sim: &mut Sim) -> Self {
247 let drives: Vec<DriveParams> =
248 (0..sim.machine.motors().len()).map(|k| sim.control.drive_params_of(k).clone()).collect();
249 let axes = sim.machine.axes().to_vec();
250 let columns: Option<Vec<&[f64]>> =
251 axes.iter().map(|a| self.column(&format!("axis.{}.position", a.id)).filter(|c| !c.is_empty())).collect();
252 let payload = self.column("payload").filter(|c| !c.is_empty());
253 let at = |i: usize| -> Option<(f64, Vec<f64>, Option<bool>)> {
254 let columns = columns.as_ref()?;
255 let held = payload.map(|c| c[i.min(c.len() - 1)] != 0.0);
256 Some((
257 self.time().get(i).copied().unwrap_or(0.0),
258 columns.iter().map(|c| c[i.min(c.len() - 1)]).collect(),
259 held,
260 ))
261 };
262 let last = columns.as_ref().and_then(|c| c.first()).map_or(0, |c| c.len() - 1);
263 let mut poses: Vec<_> = (0..MODE_POSES).filter_map(|n| at(last * n / (MODE_POSES - 1))).collect();
264 if poses.is_empty() {
265 let (mut pose, mut rate) = (vec![0.0; axes.len()], vec![0.0; axes.len()]);
266 sim.machine.tool_state(&sim.state, &mut pose, &mut rate);
267 poses.push((0.0, pose, None));
268 }
269 let modes_along: Vec<(f64, Vec<f64>)> = poses
270 .iter()
271 .map(|(t, pose, held)| {
272 if let Some(held) = held {
273 sim.machine.set_payload_attached(*held);
274 }
275 (*t, sim.machine.modes(pose).iter().map(|m| m.hz).collect())
276 })
277 .collect();
278 if let Some(held) = poses.last().and_then(|p| p.2) {
279 sim.machine.set_payload_attached(held);
280 }
281 let mut modes: Vec<f64> = modes_along.iter().flat_map(|(_, hz)| hz.iter().copied()).collect();
282 modes.sort_by(f64::total_cmp);
283 modes.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
284 Self {
285 ratings: drives.iter().map(|d| (d.rated_torque, d.peak_torque)).collect(),
286 drives,
287 modes,
288 modes_along,
289 ..self
290 }
291 }
292
293 pub fn torque_speed(&self) -> Vec<TorqueSpeed> {
296 self.drives
297 .iter()
298 .zip(&self.motors)
299 .map(|(d, id)| {
300 charts::torque_speed(d, charts::dc_link_of(d, self.column(&format!("motor.{id}.dc_link_voltage"))))
301 })
302 .collect()
303 }
304
305 pub fn time(&self) -> &[f64] {
306 &self.columns[0]
307 }
308
309 pub fn column(&self, id: &str) -> Option<&[f64]> {
311 Some(&self.columns[self.signals.iter().position(|s| s.id == id)?])
312 }
313
314 pub fn channel(&self, channel: Channel) -> Option<Cow<'_, [f64]>> {
317 match channel.quantity.signal() {
318 Some(name) => self.column(&format!("motor.{}.{name}", self.motors.get(channel.motor)?)).map(Cow::Borrowed),
319 None => {
320 let errors = self.tool_errors();
321 (!errors.is_empty()).then(|| {
322 Cow::Owned(
323 (0..self.time().len())
324 .map(|i| errors.iter().map(|e| e[i] * e[i]).sum::<f64>().sqrt())
325 .collect(),
326 )
327 })
328 }
329 }
330 }
331
332 fn tool_errors(&self) -> Vec<Cow<'_, [f64]>> {
336 let real: Vec<Cow<[f64]>> =
338 charts::axis_errors(&self.signals, &self.columns, "m").into_iter().map(|(e, _)| Cow::Owned(e)).collect();
339 if !real.is_empty() {
340 return real;
341 }
342 let signals = self.signals.iter().zip(&self.columns);
343 signals
344 .filter(|(s, _)| s.id.starts_with("axis.") && s.id.ends_with(".following_error") && s.unit == "m")
345 .map(|(_, c)| Cow::Borrowed(c.as_slice()))
346 .collect()
347 }
348
349 pub fn tool_error_is_motor_side(&self) -> bool {
351 let real = self
352 .signals
353 .iter()
354 .any(|s| s.id.starts_with("axis.") && s.id.ends_with(".position_setpoint") && s.unit == "m");
355 !real && !self.tool_errors().is_empty()
356 }
357
358 pub fn channels(&self) -> Vec<Channel> {
360 let mut out: Vec<Channel> = (0..self.motors.len())
361 .flat_map(|motor| Quantity::ALL[..3].iter().map(move |&quantity| Channel { quantity, motor }))
362 .filter(|c| self.channel(*c).is_some())
363 .collect();
364 let tool = Channel { quantity: Quantity::ToolError, motor: 0 };
365 out.extend(self.channel(tool).map(|_| tool));
366 out
367 }
368
369 pub fn figures(&self) -> Figures {
371 let time = self.time();
372 let duration = time.last().copied().unwrap_or(0.0);
373 let peak = |v: &[f64]| v.iter().fold(0f64, |p, x| p.max(x.abs()));
374 let rms =
375 |v: &[f64]| if v.is_empty() { 0.0 } else { (v.iter().map(|x| x * x).sum::<f64>() / v.len() as f64).sqrt() };
376 let of = |quantity: Quantity, motor: usize| self.channel(Channel { quantity, motor });
377 let motors = (0..self.motors.len())
378 .map(|k| {
379 let torque = of(Quantity::Torque, k).unwrap_or_default();
380 let error = of(Quantity::FollowingError, k).unwrap_or_default();
381 let speed = of(Quantity::Speed, k).unwrap_or_default();
382 let (peak_torque, rms_torque) = (peak(&torque), rms(&torque));
383 let utilisation = self.ratings.get(k).map(|&(rated, top)| (rms_torque / rated, peak_torque / top));
384 let power = self.column(&format!("motor.{}.electrical_power", self.motors[k]));
386 let energy = power
387 .map(|p| time.windows(2).zip(p.windows(2)).map(|(t, p)| (t[1] - t[0]) * (p[0] + p[1]) / 2.0).sum());
388 MotorFigures {
389 peak_torque,
390 rms_torque,
391 peak_speed: peak(&speed),
392 peak_error: peak(&error),
393 rms_error: rms(&error),
394 utilisation,
395 energy,
396 }
397 })
398 .collect();
399 let tool = self.channel(Channel { quantity: Quantity::ToolError, motor: 0 });
400 let verdicts =
401 self.verdicts.as_ref().map(|v| (v.iter().filter(|v| v.ok).count(), v.iter().filter(|v| !v.ok).count()));
402 Figures {
403 duration,
404 motors,
405 tool_error_peak: tool.as_deref().map(peak),
406 tool_error_rms: tool.as_deref().map(rms),
407 verdicts,
408 }
409 }
410}
411
412#[derive(Debug, Clone, Copy, PartialEq)]
414pub struct MotorFigures {
415 pub peak_torque: f64,
417 pub rms_torque: f64,
418 pub peak_speed: f64,
420 pub peak_error: f64,
422 pub rms_error: f64,
423 pub utilisation: Option<(f64, f64)>,
425 pub energy: Option<f64>,
427}
428
429#[derive(Debug, Clone, PartialEq)]
431pub struct Figures {
432 pub duration: f64,
433 pub motors: Vec<MotorFigures>,
434 pub tool_error_peak: Option<f64>,
436 pub tool_error_rms: Option<f64>,
437 pub verdicts: Option<(usize, usize)>,
439}
440
441#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
443pub enum Quantity {
444 Torque,
445 Speed,
446 FollowingError,
447 ToolError,
449}
450
451impl Quantity {
452 pub const ALL: [Self; 4] = [Self::Torque, Self::Speed, Self::FollowingError, Self::ToolError];
453
454 pub fn signal(self) -> Option<&'static str> {
456 match self {
457 Self::Torque => Some("torque"),
458 Self::Speed => Some("speed"),
459 Self::FollowingError => Some("following_error"),
460 Self::ToolError => None,
461 }
462 }
463
464 pub const fn unit(self) -> &'static str {
465 match self {
466 Self::Torque => "N m",
467 Self::Speed => "rad/s",
468 Self::FollowingError => "rad",
469 Self::ToolError => "m",
470 }
471 }
472
473 pub fn key(self) -> &'static str {
475 match self {
476 Self::Torque => "quantity-torque",
477 Self::Speed => "quantity-speed",
478 Self::FollowingError => "quantity-following-error",
479 Self::ToolError => "ui-run-tool-error",
480 }
481 }
482}
483
484#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
487pub struct Channel {
488 pub quantity: Quantity,
489 pub motor: usize,
490}
491
492#[derive(Debug, Clone, PartialEq)]
495pub struct Aligned {
496 pub time: Vec<f64>,
497 pub a: Vec<f64>,
498 pub b: Vec<f64>,
499 pub difference: Vec<f64>,
500}
501
502impl Aligned {
503 pub fn difference_peak_rms(&self) -> (f64, f64) {
505 let d = &self.difference;
506 let peak = d.iter().fold(0f64, |p, x| p.max(x.abs()));
507 (peak, if d.is_empty() { 0.0 } else { (d.iter().map(|x| x * x).sum::<f64>() / d.len() as f64).sqrt() })
508 }
509}
510
511pub fn align(a: &Run, b: &Run, channel: Channel) -> Option<Aligned> {
513 let (va, vb) = (a.channel(channel)?, b.channel(channel)?);
514 let (ta, tb) = (a.time(), b.time());
515 let end = *tb.last()?;
516 let mut out = Aligned { time: Vec::new(), a: Vec::new(), b: Vec::new(), difference: Vec::new() };
517 let mut j = 0;
518 for (&t, &x) in ta.iter().zip(va.iter()).take_while(|(t, _)| **t <= end) {
519 while j + 1 < tb.len() && tb[j + 1] < t {
520 j += 1;
521 }
522 let y = match tb.get(j + 1) {
523 Some(&t1) if t1 > tb[j] => vb[j] + (vb[j + 1] - vb[j]) * ((t - tb[j]) / (t1 - tb[j])).clamp(0.0, 1.0),
524 _ => vb[j],
525 };
526 out.time.push(t);
527 out.a.push(x);
528 out.b.push(y);
529 out.difference.push(x - y);
530 }
531 Some(out)
532}
533
534pub fn shared_channels(a: &Run, b: &Run) -> Vec<Channel> {
536 let theirs = b.channels();
537 a.channels().into_iter().filter(|c| theirs.contains(c)).collect()
538}
539
540pub const MAX_RUNS: usize = 8;
542
543#[derive(Debug, Clone, Default)]
545pub struct RunStore {
546 runs: Vec<(Run, bool)>,
547 reference: usize,
548}
549
550impl RunStore {
551 pub fn add(&mut self, run: Run) {
554 let same = |kept: &Run| kept.label == run.label && kept.kind == run.kind && kept.machine == run.machine;
555 if let Some(kept) = self.runs.iter_mut().find(|(kept, _)| same(kept)) {
556 kept.0 = run;
557 return;
558 }
559 if self.runs.len() == MAX_RUNS {
560 self.remove(0);
561 }
562 self.runs.push((run, true));
563 }
564
565 pub fn remove(&mut self, i: usize) {
566 if i < self.runs.len() {
567 self.runs.remove(i);
568 if self.reference > i || self.reference >= self.runs.len() {
569 self.reference = self.reference.saturating_sub(1);
570 }
571 }
572 }
573
574 pub fn clear(&mut self) {
575 *self = Self::default();
576 }
577
578 pub fn len(&self) -> usize {
579 self.runs.len()
580 }
581
582 pub fn is_empty(&self) -> bool {
583 self.runs.is_empty()
584 }
585
586 pub fn get(&self, i: usize) -> Option<&Run> {
587 self.runs.get(i).map(|(run, _)| run)
588 }
589
590 pub fn iter(&self) -> impl Iterator<Item = &Run> {
591 self.runs.iter().map(|(run, _)| run)
592 }
593
594 pub fn shown(&self, i: usize) -> bool {
596 self.runs.get(i).is_some_and(|(_, shown)| *shown)
597 }
598
599 pub fn set_shown(&mut self, i: usize, shown: bool) {
600 if let Some(run) = self.runs.get_mut(i) {
601 run.1 = shown;
602 }
603 }
604
605 pub fn reference(&self) -> usize {
606 self.reference
607 }
608
609 pub fn set_reference(&mut self, i: usize) {
610 if i < self.runs.len() {
611 self.reference = i;
612 }
613 }
614
615 pub fn against_reference(&self, i: usize, channel: Channel) -> Option<Aligned> {
618 (i != self.reference).then(|| align(self.get(i)?, self.get(self.reference)?, channel)).flatten()
619 }
620}
621
622pub fn owner_slot(owner_key: &str, signals: &[SignalInfo], axes: &[AxisInfo], motors: &[MotorInfo]) -> usize {
627 if let Some(k) = motors.iter().position(|m| m.key == owner_key) {
628 return k;
629 }
630 if let Some(i) = axes.iter().position(|a| a.key == owner_key) {
631 return i;
632 }
633 let mut others: Vec<&str> = Vec::new();
634 for s in signals {
635 let own = s.owner_key.as_str();
636 if !others.contains(&own) && !motors.iter().any(|m| m.key == own) && !axes.iter().any(|a| a.key == own) {
637 others.push(own);
638 }
639 }
640 axes.len().max(motors.len()) + others.iter().position(|o| *o == owner_key).unwrap_or(0)
641}
642
643#[derive(Debug, Clone, Copy, Default, PartialEq)]
646pub struct Units {
647 pub rpm: bool,
648 pub mm: bool,
649}
650
651impl Units {
652 pub fn of(self, unit: &str) -> Option<(f64, String)> {
654 let rpm = 60.0 / std::f64::consts::TAU;
655 match unit {
656 "rad/s" if self.rpm => Some((rpm, "rpm".into())),
657 "m" | "m/s" | "m/s²" if self.mm => Some((1e3, format!("m{unit}"))),
658 _ => None,
659 }
660 }
661
662 pub fn scale(self, unit: &str) -> (f64, String) {
664 self.of(unit).unwrap_or((1.0, unit.to_string()))
665 }
666}
667
668pub fn trail_until(points: &[crate::session::TrailPoint], time: Option<f64>) -> &[crate::session::TrailPoint] {
671 match time {
672 Some(time) => &points[..points.partition_point(|p| p.time <= time)],
673 None => points,
674 }
675}
676
677pub fn scaled_speeds(chart: &TorqueSpeed, factor: f64) -> TorqueSpeed {
679 let scale =
680 |lines: &[Vec<[f64; 2]>; 2]| lines.clone().map(|line| line.into_iter().map(|[w, t]| [w * factor, t]).collect());
681 TorqueSpeed { peak: scale(&chart.peak), s1: scale(&chart.s1), voltage: scale(&chart.voltage), ..chart.clone() }
682}
683
684#[cfg(test)]
685mod tests {
686 use super::*;
687
688 #[test]
692 fn the_tool_error_is_setpoint_minus_position_not_the_motor_side_error() {
693 let run = |ids: &[&str], row: &[f64]| {
694 let signals = ids.iter().map(|id| SignalInfo::new(*id, "owner", "quantity", "m")).collect();
695 Run::from_rows("run".into(), RunKind::Live, "m", signals, &[], [row])
696 };
697 let tool = Channel { quantity: Quantity::ToolError, motor: 0 };
698 let full = run(
699 &["time", "axis.x.position", "axis.x.position_setpoint", "axis.x.following_error"],
700 &[0.0, 0.9991, 1.0, 0.0001],
701 );
702 assert!((full.channel(tool).unwrap()[0] - 0.0009).abs() < 1e-12 && !full.tool_error_is_motor_side());
703 let bare = run(&["time", "axis.x.following_error"], &[0.0, 0.0001]);
704 assert!((bare.channel(tool).unwrap()[0] - 0.0001).abs() < 1e-12 && bare.tool_error_is_motor_side());
705 }
706}