Skip to main content

sim_app/
insight.rs

1//! The app's side of the views of what the machine is (`sim_components::shapes`): what the workspace map and the path
2//! in the 3D view are coloured by, the path's values, and the cycle run with its bounded values at their bounds, kept
3//! as traces. Nothing here draws.
4
5use sim_components::analysis::Progress;
6pub use sim_components::shapes::*;
7use sim_core::{Config, ConfigError, MachineEntry};
8use std::sync::atomic::Ordering::Relaxed;
9
10/// What the workspace map colours each place by.
11#[derive(Debug, Clone, Copy, PartialEq, Default)]
12pub enum WorkspaceColour {
13    /// The condition number of the kinematics (`Machine::condition`).
14    #[default]
15    Condition,
16    /// The largest tool acceleration in the worst direction (`worst_acceleration`).
17    Acceleration,
18}
19
20/// What the path in the 3D view is coloured by along its length (`Model::path_colours`).
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub enum PathQuantity {
23    /// The tool's distance to the path, as the path's analysis measured it (`Run::off_path`), m.
24    PathError,
25    /// The tool's distance to where its setpoint is at the same moment (the axes' following errors in m), m.
26    TrackingError,
27    /// The tool's speed over the axes in m, m/s.
28    Speed,
29    /// Motor k's torque over what its drive gives at that speed (`charts::torque_utilisation`), 1 at the curve.
30    Utilisation(usize),
31    /// The highest tension of the machine's belt sections (`Machine::belt_sections`), N.
32    BeltTension,
33}
34
35impl PathQuantity {
36    /// Its label's translation key.
37    pub fn key(self) -> &'static str {
38        match self {
39            Self::PathError => "ui-colour-path-error",
40            Self::TrackingError => "ui-colour-tracking-error",
41            Self::Speed => "ui-colour-speed",
42            Self::Utilisation(_) => "ui-colour-utilisation",
43            Self::BeltTension => "ui-colour-belt-tension",
44        }
45    }
46
47    /// The unit its values are in.
48    pub fn unit(self) -> &'static str {
49        match self {
50            Self::PathError | Self::TrackingError => "m",
51            Self::Speed => "m/s",
52            Self::Utilisation(_) => "",
53            Self::BeltTension => "N",
54        }
55    }
56
57    /// Its values over `run`, one per sample, where the run has what it needs: `belts` are the ids of the machine's
58    /// belt sections, whose tension signals are `<id>.tension`.
59    pub fn values(self, run: &crate::runs::Run, belts: &[&str]) -> Option<Vec<f64>> {
60        use crate::runs::{Channel, Quantity};
61        let time = run.time();
62        let length = |columns: &[&[f64]]| -> Vec<f64> {
63            (0..time.len()).map(|i| linear_speed(columns.iter().map(|c| (true, c[i])))).collect()
64        };
65        match self {
66            Self::PathError => {
67                let off = &run.off_path;
68                (!off.is_empty()).then(|| time.iter().map(|&t| off[nearest(off, t)][1]).collect())
69            }
70            Self::TrackingError => run.channel(Channel { quantity: Quantity::ToolError, motor: 0 }).map(|c| c.to_vec()),
71            Self::Speed => {
72                let speeds: Vec<&[f64]> = run
73                    .signals
74                    .iter()
75                    .zip(&run.columns)
76                    .filter(|(s, _)| s.id.starts_with("axis.") && s.id.ends_with(".velocity") && s.unit == "m/s")
77                    .map(|(_, c)| c.as_slice())
78                    .collect();
79                (!speeds.is_empty()).then(|| length(&speeds))
80            }
81            Self::Utilisation(k) => {
82                let (drive, id) = (run.drives.get(k)?, run.motors.get(k)?);
83                let speed = run.column(&format!("motor.{id}.speed"))?;
84                let torque = run.column(&format!("motor.{id}.torque"))?;
85                Some(
86                    speed
87                        .iter()
88                        .zip(torque)
89                        .map(|(w, t)| sim_components::charts::torque_utilisation(drive, *w, *t))
90                        .collect(),
91                )
92            }
93            Self::BeltTension => {
94                let tensions: Vec<&[f64]> =
95                    belts.iter().filter_map(|id| run.column(&format!("{id}.tension"))).collect();
96                (!tensions.is_empty()).then(|| {
97                    (0..time.len()).map(|i| tensions.iter().map(|c| c[i]).fold(f64::NEG_INFINITY, f64::max)).collect()
98                })
99            }
100        }
101    }
102}
103
104/// The length of a vector of speeds that counts only those marked linear (m/s): a turning axis's rad/s does not add to
105/// a tool speed (`PathQuantity::Speed`, `Runner::trail_point`).
106pub fn linear_speed(speeds: impl IntoIterator<Item = (bool, f64)>) -> f64 {
107    speeds.into_iter().filter(|(linear, _)| *linear).map(|(_, v)| v * v).sum::<f64>().sqrt()
108}
109
110/// The place in `series` (sorted by its first entry, the time) whose time is nearest `t`.
111fn nearest(series: &[[f64; 3]], t: f64) -> usize {
112    let after = series.partition_point(|p| p[0] < t).min(series.len() - 1);
113    if after > 0 && (t - series[after - 1][0]).abs() <= (series[after][0] - t).abs() { after - 1 } else { after }
114}
115
116/// The path that was run in the 3D view, coloured by one quantity (`Model::path_colours`): per sample of the run the
117/// tool's place in the scene, the time and the value; and the sample with the highest value.
118#[derive(Debug, Clone)]
119pub struct PathColours {
120    pub quantity: PathQuantity,
121    pub points: Vec<[f64; 3]>,
122    pub time: Vec<f64>,
123    pub values: Vec<f64>,
124    pub worst: usize,
125}
126
127/// One traced signal of the cycle with the bounds runs' envelope (`BandRuns`): its signal, the time from the measured
128/// pass's start, the nominal trace and, at each sample, the lowest and highest value of the bounds runs.
129#[derive(Debug, Clone)]
130pub struct BandTrace {
131    pub signal: sim_core::SignalInfo,
132    pub time: Vec<f64>,
133    pub nominal: Vec<f64>,
134    pub low: Vec<f64>,
135    pub high: Vec<f64>,
136}
137
138/// The cycle run with each bounded value at its low and at its high bound, one at a time, as `verdict_bands` runs it,
139/// kept as traces: each motor's torque and following error and each belt section's tension, nominal and enveloped; and
140/// per motor the operating points (speed in rad/s, torque) of the bounds runs, every other millisecond.
141#[derive(Debug, Clone)]
142pub struct BandRuns {
143    pub runs: usize,
144    pub traces: Vec<BandTrace>,
145    pub points: Vec<Vec<[f64; 2]>>,
146}
147
148/// The configs of the bounds runs: `config` with its parts in and each bounded value (`analysis::bounds` of that) at
149/// its low and its high bound, one at a time. A bound whose low is its high moves nothing and runs nothing.
150pub fn bound_configs(entry: &MachineEntry, config: &Config) -> Result<Vec<Config>, ConfigError> {
151    let resolved = sim_components::catalog::resolve(entry, config)?;
152    let mut out = Vec::new();
153    for (path, low, high) in sim_components::analysis::bounds(&resolved)? {
154        for value in if low == high { vec![] } else { vec![low, high] } {
155            let mut changed = resolved.clone();
156            sim_components::analysis::set_bounded(&mut changed, &path, value)?;
157            out.push(changed);
158        }
159    }
160    Ok(out)
161}
162
163/// The bounds runs of `config`'s cycle (`BandRuns`), each recorded as `analysis::record_cycle` records the cycle, on all
164/// processors. `progress` counts the runs; a cancel ends the job (`check_cancelled`) between two rounds of them.
165pub fn band_runs(entry: &MachineEntry, config: &Config, progress: &Progress) -> Result<BandRuns, ConfigError> {
166    use sim_components::analysis::record_cycle;
167    let configs = bound_configs(entry, config)?;
168    let machine = build(entry, config)?;
169    let signals = sim_components::Sim::new(entry, config)?.signal_infos();
170    let mut ids: Vec<String> = Vec::new();
171    for motor in machine.motors() {
172        ids.extend(["torque", "following_error"].map(|q| format!("motor.{}.{q}", motor.id)));
173    }
174    ids.extend(machine.belt_sections().iter().map(|b| format!("{}.tension", b.id)));
175    let traced: Vec<usize> = ids.iter().filter_map(|id| signals.iter().position(|s| s.id == *id)).collect();
176    let motor_columns: Vec<Option<(usize, usize)>> = machine
177        .motors()
178        .iter()
179        .map(|m| {
180            let at = |q: &str| signals.iter().position(|s| s.id == format!("motor.{}.{q}", m.id));
181            Some((at("speed")?, at("torque")?))
182        })
183        .collect();
184    let nominal = record_cycle(entry, config)?;
185    let mut traces: Vec<BandTrace> = traced
186        .iter()
187        .map(|&i| BandTrace {
188            signal: signals[i].clone(),
189            time: nominal.iter().map(|row| row[0]).collect(),
190            nominal: nominal.iter().map(|row| row[i]).collect(),
191            low: Vec::new(),
192            high: Vec::new(),
193        })
194        .collect();
195    let mut points = vec![Vec::new(); motor_columns.len()];
196    let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).max(1);
197    progress.total.store(configs.len(), Relaxed);
198    for chunk in configs.chunks(threads) {
199        sim_components::analysis::check_cancelled();
200        let recorded: Vec<Result<Vec<Vec<f64>>, ConfigError>> = std::thread::scope(|scope| {
201            let runs: Vec<_> = chunk.iter().map(|cfg| scope.spawn(move || record_cycle(entry, cfg))).collect();
202            runs.into_iter()
203                .map(|run| run.join().unwrap_or_else(|_| Err(ConfigError::Invalid("bounds".into()))))
204                .collect()
205        });
206        progress.done.fetch_add(chunk.len(), Relaxed);
207        for rows in recorded {
208            let rows = rows?;
209            for (trace, &i) in traces.iter_mut().zip(&traced) {
210                let column: Vec<f64> = rows.iter().map(|row| row[i]).collect();
211                (trace.low, trace.high) =
212                    (envelope([&trace.low[..], &column[..]]).0, envelope([&trace.high[..], &column[..]]).1);
213            }
214            for (cloud, columns) in points.iter_mut().zip(&motor_columns) {
215                if let Some((speed, torque)) = columns {
216                    cloud.extend(rows.iter().step_by(2).map(|row| [row[*speed], row[*torque]]));
217                }
218            }
219        }
220    }
221    Ok(BandRuns { runs: configs.len(), traces, points })
222}
223
224/// What the model keeps for these views: the mode list with the config it was found for, the mode picked for the 3D
225/// view, and the bounds runs with the config they are of, and their job.
226#[derive(Default)]
227pub struct Insight {
228    pub modes: Option<(Config, Vec<ModeView>)>,
229    /// The small-amplitude frequencies of those modes (`Machine::modes_small_amplitude`), where they differ.
230    pub small_modes: Option<Vec<f64>>,
231    pub picked: Option<usize>,
232    pub band_runs: Option<(Config, BandRuns)>,
233    /// The job that runs them, answering with the config they are of.
234    pub(crate) band_job: Option<crate::model::Job<(Config, BandRuns)>>,
235}
236
237/// The labels these views take from the model.
238pub const KEYS: [&str; 23] = [
239    "ui-colour-utilisation",
240    "ui-modes",
241    "ui-modes-hint",
242    "ui-modes-find",
243    "ui-modes-mode",
244    "ui-modes-hz",
245    "ui-modes-small-hz",
246    "ui-modes-damping",
247    "ui-modes-linear",
248    "ui-modes-shape",
249    "ui-modes-from-machine",
250    "ui-modes-from-linear",
251    "ui-modes-stiffness",
252    "ui-modes-stiffness-belt",
253    "ui-modes-stiffness-gearbox",
254    "ui-modes-stiffness-guide",
255    "ui-modes-stiffness-frame",
256    "ui-modes-stiffness-base",
257    "ui-modes-stiffness-link",
258    "ui-colour-path-error",
259    "ui-colour-tracking-error",
260    "ui-colour-speed",
261    "ui-colour-belt-tension",
262];