1use sim_components::analysis::Progress;
6pub use sim_components::shapes::*;
7use sim_core::{Config, ConfigError, MachineEntry};
8use std::sync::atomic::Ordering::Relaxed;
9
10#[derive(Debug, Clone, Copy, PartialEq, Default)]
12pub enum WorkspaceColour {
13 #[default]
15 Condition,
16 Acceleration,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq)]
22pub enum PathQuantity {
23 PathError,
25 TrackingError,
27 Speed,
29 Utilisation(usize),
31 BeltTension,
33}
34
35impl PathQuantity {
36 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 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 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
104pub 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
110fn 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#[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#[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#[derive(Debug, Clone)]
142pub struct BandRuns {
143 pub runs: usize,
144 pub traces: Vec<BandTrace>,
145 pub points: Vec<Vec<[f64; 2]>>,
146}
147
148pub 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
163pub 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#[derive(Default)]
227pub struct Insight {
228 pub modes: Option<(Config, Vec<ModeView>)>,
229 pub small_modes: Option<Vec<f64>>,
231 pub picked: Option<usize>,
232 pub band_runs: Option<(Config, BandRuns)>,
233 pub(crate) band_job: Option<crate::model::Job<(Config, BandRuns)>>,
235}
236
237pub 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];