Skip to main content

sim_app/
runs.rs

1//! Runs kept side by side for comparing them: the live session's scopes, the ghost run beside it, an analysed cycle,
2//! a path that was run, a replayed trace, and the cycle of another config or machine. Each holds every signal it has,
3//! sampled once per millisecond, with the time counted from its start. Runs of different machines are compared by
4//! quantity (`Channel`): a motor's torque, speed and following error by the motor's place in the machine's list, and
5//! the tool's position error. The views draw what this module gives them; it draws nothing itself.
6
7use 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
16/// At most this many stretches a drawn line is cut into (`peak_keeping`): two points each, some six thousand a line.
17pub const PLOT_BUCKETS: usize = 3000;
18/// How many poses along a run its modes are asked at (`Run::rated`): the start, the end and evenly between.
19pub const MODE_POSES: usize = 5;
20
21/// The points of a line for a plot: every point where there are few, else the lowest and highest of each of
22/// `PLOT_BUCKETS` stretches, so that a peak one sample wide still shows.
23pub fn plot_line(n: usize, point: impl Fn(usize) -> [f64; 2]) -> Vec<[f64; 2]> {
24    peak_keeping(n, point, PLOT_BUCKETS)
25}
26
27/// The samples of a session as one flat ring buffer: a row of every signal per sample, the newest `capacity` kept.
28/// One allocation of `capacity` rows in all, where a `Vec` per row cost a heap block per sample.
29#[derive(Debug, Clone, Default)]
30pub struct History {
31    data: Vec<f64>,
32    width: usize,
33    capacity: usize,
34    /// The row of the oldest sample, once the buffer is full.
35    head: usize,
36    len: usize,
37    /// Samples pushed since the start, dropped ones too: changes with every sample, for caches.
38    pushed: u64,
39}
40
41impl History {
42    pub fn new(capacity: usize) -> Self {
43        Self { capacity: capacity.max(1), ..Self::default() }
44    }
45
46    /// Adds the newest sample; past `capacity` the oldest goes. A row of another width than the ones before (another
47    /// machine) starts the buffer anew.
48    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    /// The `i`-th sample, oldest first.
77    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    /// The first sample whose time (column 0) is at or after `time`.
90    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    /// A copy of the samples from `from` on, as a buffer of their own.
104    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/// Where a run came from.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum RunKind {
114    /// The scopes' time window of the live session.
115    Live,
116    /// The window of the run beside it with one effect switched (the 3D view's ghost).
117    Ghost,
118    /// The configured cycle, as the analysis measures it (its second pass).
119    Cycle,
120    /// A path that was planned and run.
121    Path,
122    /// A trace from a file, or its replay.
123    Trace,
124}
125
126impl RunKind {
127    /// Its label's translation key.
128    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/// One run: every signal it has, once per millisecond, the time from its start.
140#[derive(Debug, Clone)]
141pub struct Run {
142    /// What the user reads: what was changed against the config shown, or the file.
143    pub label: String,
144    pub kind: RunKind,
145    /// The machine's id.
146    pub machine: &'static str,
147    pub signals: Vec<SignalInfo>,
148    /// The motors' ids, in the machine's order: how `Channel::motor` finds a motor's signals.
149    pub motors: Vec<String>,
150    /// Per motor its drive's rated (S1) and peak torque in N m, for the utilisation; empty where not known (a trace).
151    pub ratings: Vec<(f64, f64)>,
152    /// Per motor its drive, for the torque-speed chart and the utilisation (`charts`); empty where not known (a trace).
153    pub drives: Vec<DriveParams>,
154    /// The machine's resonances in Hz (`Machine::modes`) at the poses of `modes_along`, all of them, marked in the
155    /// spectrum: a mode that moves with the pose is a band of lines.
156    pub modes: Vec<f64>,
157    /// The resonances at a few poses along the run: (time in s from its start, Hz), the start first.
158    pub modes_along: Vec<(f64, Vec<f64>)>,
159    /// For an analysed cycle or path: the tool's distance to the path every millisecond as the analysis measured it
160    /// (`CycleLoad::path_error_series`, [time, place m, turn rad]); empty otherwise.
161    pub off_path: Vec<[f64; 3]>,
162    /// Per signal its values, the first the time in s from the run's start.
163    pub columns: Vec<Vec<f64>>,
164    /// The checks, for a run that was judged (a cycle or a path).
165    pub verdicts: Option<Vec<Verdict>>,
166}
167
168impl Run {
169    /// A run from rows of samples as the simulation gives them (`Sim::sample`), the time counted from the first.
170    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    /// A trace (measured, or its replay) as a run: per motor its angle, speed, torque and following error.
203    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    /// With what `sim`, of the machine and config the run is of, says about them: per motor its rated and peak torque
242    /// and its drive, and the machine's resonances along the run. The modes are asked at `MODE_POSES` poses along the
243    /// run (its start, its end and between), read from the tool's position signals, each with the payload as the run's
244    /// signal `payload` has it there (the machine is left with the run's last); a run without them (a trace) has the
245    /// modes at the pose `sim` stands at.
246    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    /// Per motor its torque-speed chart from its own drive, at the lowest DC link voltage the run saw
294    /// (`charts::dc_link_of`); empty where the run knows no drives.
295    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    /// The signal of this id, if the run has it.
310    pub fn column(&self, id: &str) -> Option<&[f64]> {
311        Some(&self.columns[self.signals.iter().position(|s| s.id == id)?])
312    }
313
314    /// The values of one quantity over the run, if the run has it: a motor's own signal, or the tool's position
315    /// error, the length of the axes' following errors over the axes in metres (`Channel`).
316    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    /// Per axis in metres the tool's position error, the plan now less the actual position (`charts::axis_errors`, as
333    /// the Views tab and the analysis have it); a run without setpoints gets the drives' following errors instead
334    /// (`tool_error_is_motor_side`).
335    fn tool_errors(&self) -> Vec<Cow<'_, [f64]>> {
336        // The encoder-side following error misses belt stretch and compliance; the plan less the position does not.
337        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    /// Whether the tool's error of this run is only the drives' following error (no setpoint signals to compare).
350    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    /// The channels this run has, motor after motor in the order of `Quantity::ALL`, then the tool's error.
359    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    /// The key figures (see `Figures`).
370    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                // The electrical energy the motor drew, net of what it gave back, by the trapezoid rule.
385                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/// What a motor did over a run.
413#[derive(Debug, Clone, Copy, PartialEq)]
414pub struct MotorFigures {
415    /// In N m.
416    pub peak_torque: f64,
417    pub rms_torque: f64,
418    /// In rad/s.
419    pub peak_speed: f64,
420    /// The motor's following error, in rad.
421    pub peak_error: f64,
422    pub rms_error: f64,
423    /// RMS torque over the rated torque and peak torque over the drive's peak, where the drive is known.
424    pub utilisation: Option<(f64, f64)>,
425    /// Electrical energy drawn net in J, where the run has the power.
426    pub energy: Option<f64>,
427}
428
429/// A run's key figures for the compare panel.
430#[derive(Debug, Clone, PartialEq)]
431pub struct Figures {
432    pub duration: f64,
433    pub motors: Vec<MotorFigures>,
434    /// The tool's position error (`Quantity::ToolError`) in m, where the run has it.
435    pub tool_error_peak: Option<f64>,
436    pub tool_error_rms: Option<f64>,
437    /// Checks passed and failed, for a run that was judged.
438    pub verdicts: Option<(usize, usize)>,
439}
440
441/// A quantity compared across runs.
442#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
443pub enum Quantity {
444    Torque,
445    Speed,
446    FollowingError,
447    /// The tool's position error: the length of the axes' following errors (those in metres).
448    ToolError,
449}
450
451impl Quantity {
452    pub const ALL: [Self; 4] = [Self::Torque, Self::Speed, Self::FollowingError, Self::ToolError];
453
454    /// The motor signal's name after `motor.<id>.`; `None` for the tool's error, which is worked out.
455    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    /// Its label's translation key.
474    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/// One quantity of one motor (the motor's place in its machine's list; ignored for the tool's error). Two runs are
485/// compared on the channels both have: of two machines with two and four motors, motors 0 and 1.
486#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
487pub struct Channel {
488    pub quantity: Quantity,
489    pub motor: usize,
490}
491
492/// One channel of two runs on the first's time: the second's values linearly between its samples, and the first less
493/// the second. Over the time both have; where one is longer, its rest is not compared.
494#[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    /// Peak and RMS of the difference.
504    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
511/// `a` and `b` on `a`'s time, both counted from their start (see `Aligned`); `None` where either lacks the channel.
512pub 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
534/// The channels two runs share: the alignment of `Channel`.
535pub 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
540/// How many runs the store keeps; the oldest goes for a newer one.
541pub const MAX_RUNS: usize = 8;
542
543/// The runs kept for comparing, oldest first, and which of them is the reference the others are compared with.
544#[derive(Debug, Clone, Default)]
545pub struct RunStore {
546    runs: Vec<(Run, bool)>,
547    reference: usize,
548}
549
550impl RunStore {
551    /// Keeps a run, shown; past `MAX_RUNS` the oldest goes (the reference stays the same run where it can). A run of
552    /// the same kind, machine and label (the same config run again) takes the place of the one before.
553    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    /// Whether run `i` is drawn.
595    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    /// The run `i` against the reference on one channel (`align`): `None` for the reference itself and where either
616    /// lacks the channel.
617    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
622/// The colour slot of a signal's owner, the same in every plot: an axis by its place in the machine's axes, a motor by
623/// its place in its motors (as plots of one value per motor colour them), anything else after those by its place
624/// among the other owners of `signals`. So motor 2 has one colour in the scopes, the torque-speed plot, the sweep and
625/// the run comparison.
626pub 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/// The units the plots and tables show speeds and lengths in: rpm in place of rad/s, mm in place of m. Off, a
644/// value keeps its SI unit, which the scopes scale by an SI prefix to a readable size (`display_scale`).
645#[derive(Debug, Clone, Copy, Default, PartialEq)]
646pub struct Units {
647    pub rpm: bool,
648    pub mm: bool,
649}
650
651impl Units {
652    /// The factor a value in `unit` is shown multiplied by, and the unit shown; `None` where the choice leaves it.
653    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    /// `of`, or the value as it is.
663    pub fn scale(self, unit: &str) -> (f64, String) {
664        self.of(unit).unwrap_or((1.0, unit.to_string()))
665    }
666}
667
668/// The travelled path's points up to `time` (all of them for `None`, live): what the 3D view draws while the timeline
669/// shows an older scene. The points are in time order.
670pub 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
677/// A torque-speed chart with its speeds times `factor` (`Units`), its torques as they are.
678pub 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    /// A belt axis stands 0.9 mm behind its setpoint at the tool while its encoder-side following error is 0.1 mm:
689    /// the tool error is setpoint minus position, 1.0000 - 0.9991 = 0.9 mm, not the 0.1 mm; without setpoint signals
690    /// it is the following error, and says so.
691    #[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}