Skip to main content

sim_app/
model.rs

1//! Everything the interface shows and edits, without any drawing: the chosen machine and language,
2//! the config being edited, the scope history, tuning and analysis results. The window code only draws
3//! this and calls its methods.
4
5use crate::runs::{Channel, History, Quantity, Run, RunKind, RunStore, Units, plot_line};
6use crate::session::{Event, Request, Session, extend_trail};
7use sim_components::analysis::{
8    Band, Cancelled, Comparison, CycleLoad, MotorLoad, OptimiseOptions, Optimised, Progress, Sensitivity, Verdict,
9    any_not_finite, compare_effect, with_progress,
10};
11use sim_components::analysis::{
12    SWEEP_POINTS, StepResponse, SweepPoint, bandwidth, closed_loop_response, default_sweep_amplitude, frequency_sweep,
13    log_spaced, modes_along, step_response,
14};
15use sim_components::analysis::{
16    Worst, analyse_cycle, analyse_trajectory, belt_tooth_utilisation, bounds, gearbox_gearing_life_h, gearbox_life_h,
17    guide_life_h, guide_life_km, motor_bearing_life_h, optimise_cycle_with, pulley_bearing_life_h, record_cycle,
18    sensitivity, verdict_bands, verdict_bands_sampled, verdict_worst_and_bands, verdicts,
19};
20use sim_components::catalog::Candidate;
21use sim_components::identify::{
22    AxisFit, BELT_STIFFNESS_KEY, JointFit, MoveStiffness, SweepFit, fit_joints, fit_move_stiffness, fit_rigid,
23    fit_sweep, parse_sweep, resonance,
24};
25use sim_components::import::{Mapping, decode, import};
26use sim_components::motor_fit::{Identified, QUANTITIES};
27use sim_components::trace::{Trace, TraceError, differences, overlay_csv, per_axis_fit, replay};
28use sim_components::{Command, CommandError, Sim, path};
29use sim_core::{
30    Config, ConfigError, Machine, MachineEntry, Mode, Scene, SignalInfo, TEMPERATURE_PREFIX, TORQUE_PARTS, Translations,
31};
32use sim_machines::{MACHINES, translations};
33use std::collections::VecDeque;
34use std::sync::atomic::Ordering::Relaxed;
35use std::sync::mpsc::{Receiver, TryRecvError, channel};
36use std::sync::{Arc, Mutex};
37use toml::Value;
38
39/// Samples kept for the scopes: one minute at one per millisecond.
40pub const HISTORY: usize = 60_000;
41
42/// A message for the user, as a translation key and its argument.
43pub type Message = (&'static str, String);
44
45/// One group of the parameter panel: a config table and its scalar values.
46pub struct ParamGroup {
47    pub key: String,
48    /// (config path, label key, value)
49    pub params: Vec<(String, String, Value)>,
50}
51
52pub struct ScopeLine {
53    /// Index into the signal list.
54    pub signal: usize,
55    /// A setpoint or command, drawn dashed in the colour of the actual value it belongs to.
56    pub reference: bool,
57}
58
59/// One scope: one quantity for every axis or motor, actual values together with their setpoints.
60pub struct Scope {
61    pub quantity_key: String,
62    pub unit: String,
63    pub lines: Vec<ScopeLine>,
64    pub visible: bool,
65}
66
67/// What a trace did inside the visible time window.
68#[derive(Debug, Clone, Copy, PartialEq)]
69pub struct Stats {
70    pub min: f64,
71    pub max: f64,
72    pub rms: f64,
73}
74
75/// The answer of one axis's position loop to a step and to sines, for choosing gains.
76pub struct Tuning {
77    pub axis: usize,
78    pub step: StepResponse,
79    pub response: Vec<SweepPoint>,
80    pub bandwidth: Option<f64>,
81    /// The modes the machine reports at `MODE_POINTS` places over the axis's stroke, the other axes at the start pose
82    /// (`analysis::modes_along`): empty lists where it reports none.
83    pub modes: Vec<(f64, Vec<Mode>)>,
84}
85
86/// How many places over the stroke the tuning help asks the machine for its modes.
87pub const MODE_POINTS: usize = 41;
88
89/// A background job the window shows progress for and can cancel.
90#[derive(Debug, Clone, Copy, PartialEq)]
91pub enum JobRef {
92    Analysis(Analysis),
93    View(crate::search_views::ViewJob),
94    Tuning,
95    Report,
96    Bands,
97}
98
99/// What the analysis panel can compute. Each takes seconds, so each runs in a thread of its own.
100#[derive(Debug, Clone, Copy, PartialEq)]
101pub enum Analysis {
102    /// The cycle's loads, judged against what the parts allow.
103    Cycle,
104    /// The cycle again with each bounded parameter at its low and its high bound.
105    Sensitivity,
106    /// A shorter cycle that still passes every check.
107    Optimise,
108    /// The catalogue motors the inputs ask for, each tried on the cycle.
109    Search,
110    /// A path from a file: planned, run and judged.
111    Path,
112    /// A drive trace from a file: replayed, and the config fitted to it.
113    Trace,
114    /// The open-loop frequency response of the mechanics, from each motor's torque to its speed.
115    Sweep,
116    /// The belt stiffness fitted to a measured frequency response from a file.
117    SweepFit,
118    /// The cycle with one effect on and off, overlaid.
119    Compare,
120}
121
122/// What the analysis panel is asked with, as typed.
123#[derive(Debug, Clone, PartialEq)]
124pub struct Inputs {
125    /// The cycle analysis also runs the cycle with every bounded value at its bounds, for the error bands.
126    pub bands: bool,
127    /// For the error bands: how often the cycle is run with all bounded values between their bounds at once.
128    /// 0: each value alone at its low and at its high bound.
129    pub samples: usize,
130    /// With the error bands: also search per check for the worst corner of the bounds (`verdict_worst`).
131    pub worst: bool,
132    /// Motor search: a supply of `SUPPLIES`, how the article numbers start, a gearbox series or nothing, and whether
133    /// every axis of the catalogue of the machine's kind is tried too (`search_axes`).
134    pub supply: String,
135    pub series: String,
136    pub gearboxes: String,
137    pub axes: bool,
138    /// The search's other options, the ratio sweep and the kinematics comparison (`search_views`).
139    pub search: crate::search_views::SearchInputs,
140    /// The path tab's maps of peak torque and following error (`search_views::move_map`).
141    pub map: crate::search_views::MapInputs,
142    /// Path: the file, whether it holds poses at times and not lines and arcs, and whether lines and arcs
143    /// are timed as fast as the motors allow and not within the axis limits.
144    pub path_file: String,
145    pub path_timed: bool,
146    pub time_optimal: bool,
147    pub trace_file: String,
148    /// A mapping file for a vendor's trace export (`sim-cli --map`); "" for a trace in the simulator's columns.
149    pub trace_map: String,
150    /// Also the belts' stiffness from the trace's moves (`sim-cli fit --stiffness`): some twenty replays more.
151    pub trace_stiffness: bool,
152    /// The config file to open or save.
153    pub config_file: String,
154    /// Part names as typed, in the order of `PARTS`: motor article, supply, gearbox, drive, belt and axis; "" for none.
155    pub parts: [String; 6],
156    /// Frequency response: lowest and highest frequency in Hz, number of frequencies and torque amplitude in
157    /// N m, as `sim-cli sweep` takes them. The amplitude is also the one a measured sweep was taken with.
158    pub sweep_from: f64,
159    pub sweep_to: f64,
160    pub sweep_count: usize,
161    pub sweep_amplitude: f64,
162    /// A measured frequency response (`frequency_hz`, `gain_rad_s_per_nm`) and the motor it was taken on.
163    pub sweep_file: String,
164    pub sweep_motor: usize,
165    /// The effect comparison: the effect switched (its name in `[effects]`), and the quantity of the scope overlaid.
166    pub compare_effect: String,
167    pub compare_quantity: String,
168    /// The height of the workspace map's slice, in the unit of the third axis; `None`: the middle of its range.
169    pub workspace_z: Option<f64>,
170    /// What the workspace map is coloured by, and what the path in the 3D view is (`None`: planned and travelled
171    /// path as two plain lines).
172    pub workspace_by: crate::insight::WorkspaceColour,
173    pub path_colour: Option<crate::insight::PathQuantity>,
174    /// The sample of the coloured path whose values are read out (a click on the path, or its worst point).
175    pub path_probe: Option<usize>,
176    /// The parameter panel's "path = value" field, applied by `set_value`.
177    pub assignment: String,
178    /// The parameter panel's filter: the parameters whose label or dotted path hold it (`param_matches`) are listed.
179    pub param_filter: String,
180    /// For a run of another config (`record_run`): assignments as `--set` takes them, separated by `;`, and a config
181    /// or machine file to start from ("" for the config shown).
182    pub run_set: String,
183    pub run_file: String,
184}
185
186/// The supplies the motor catalogue has data for: the S210 at 230 V and 400 V, and the S120.
187pub const SUPPLIES: &[&str] = sim_components::catalog::SUPPLIES;
188
189/// A path as it was planned, run on a simulation of its own and judged.
190pub struct PathRun {
191    pub points: Vec<(f64, Vec<f64>)>,
192    /// The planned poses as places in the 3D scene (`Machine::scene_point`), for drawing the path there.
193    /// Empty for a machine without that mapping.
194    pub scene_line: Vec<[f64; 3]>,
195    pub load: CycleLoad,
196    pub verdicts: Vec<Verdict>,
197    /// How far the planned path is off the given one, at most: transition curves and arcs off their stated end. That of
198    /// the worst run for a program.
199    pub deviation: f64,
200    /// The deviation of each run of a program from its pieces (one value for a path of one run).
201    pub deviations: Vec<f64>,
202    /// The motors' torque-speed curves, for its operating points (`torque_speed_curves`).
203    pub curves: Curves,
204    /// The path as it was run, every signal once per millisecond, with the analysis's distance to the path
205    /// (`Run::off_path`): what the 3D view colours the path by (`Model::path_colours`).
206    pub run: Run,
207}
208
209/// Per motor its torque-speed chart (`charts::TorqueSpeed`), from its own drive (`Run::torque_speed`).
210pub type Curves = Vec<sim_components::charts::TorqueSpeed>;
211
212/// A trace replayed and fitted: per motor the RMS and peak difference between the trace and its replay, of
213/// torque and of following error, and per axis the fit (none for an axis the trace does not move both ways), or
214/// on a machine that is fitted in its motors' coordinates (`per_axis_fit` false) that fit in `joints` and no `fits`.
215/// With the trace and its replay, for the overlay, and per motor what the trace says by itself
216/// (`sim-cli identify`: inertia, friction, the loops' lags). Where it was asked for, the belts' stiffness from the
217/// trace's moves, or why the trace gives none.
218pub struct TraceFit {
219    pub differences: Vec<[f64; 4]>,
220    pub fits: Vec<Option<AxisFit>>,
221    pub joints: Option<Option<JointFit>>,
222    pub stiffness: Option<Result<MoveStiffness, TraceError>>,
223    pub identified: Vec<Identified>,
224    pub measured: Trace,
225    pub simulated: Trace,
226}
227
228#[allow(clippy::large_enum_variant)] // one per finished job, sent once over a channel, never stored in bulk
229enum Report {
230    /// With the error bands, where they were asked for, and the number of samples they are of (0: each
231    /// bounded value alone at its bounds).
232    /// And the worst corners, where they were searched, with the paths of the bounds they name; and the cycle as a
233    /// run for the run store.
234    Cycle(CycleLoad, Vec<Verdict>, Option<Vec<Band>>, usize, Curves, Option<(Vec<Worst>, Vec<String>)>, Run),
235    Sensitivity(CycleLoad, Vec<Sensitivity>),
236    Optimised(Optimised),
237    /// With the supply that was searched.
238    Search(crate::search_views::Found, String),
239    /// With the path as a run for the run store.
240    Path(PathRun, Run),
241    Trace(TraceFit),
242    Sweep(Vec<Vec<SweepPoint>>),
243    /// With the motor the sweep was taken on.
244    SweepFit(usize, SweepFit),
245    /// With the effect that was switched.
246    Compare(String, Comparison),
247}
248
249/// A background computation: its thread runs as a job (`with_progress`), so the analyses count its runs in `progress`
250/// and stop at its `cancel`. Dropping a `Job` cancels it: its result has nowhere to go any more (the machine switched,
251/// a file opened, the window closed).
252pub(crate) struct Job<T> {
253    answer: Mutex<Receiver<Result<T, Message>>>,
254    pub(crate) progress: Arc<Progress>,
255}
256
257/// What a cancelled job says: not an error, the earlier results stay as they were.
258fn cancelled_message() -> Message {
259    ("ui-job-cancelled", String::new())
260}
261
262impl<T: Send + 'static> Job<T> {
263    /// Runs `work` in a thread of its own, given the job's progress for work that counts by itself.
264    pub(crate) fn spawn(work: impl FnOnce(&Progress) -> Result<T, Message> + Send + 'static) -> Self {
265        let (send, receive) = channel();
266        let progress = Arc::new(Progress::default());
267        let watch = progress.clone();
268        std::thread::spawn(move || {
269            let _ =
270                send.send(with_progress(&watch, || work(&watch)).unwrap_or_else(|Cancelled| Err(cancelled_message())));
271        });
272        Job { answer: Mutex::new(receive), progress }
273    }
274}
275
276impl<T> Job<T> {
277    /// Stops the job: its runs not yet started are not started, and what it answers is not taken in.
278    pub(crate) fn cancel(&self) {
279        self.progress.cancel.store(true, Relaxed);
280    }
281
282    /// A job over a channel somebody else answers on (a test's).
283    #[cfg(test)]
284    fn of(receiver: Receiver<Result<T, Message>>) -> Self {
285        Job { answer: Mutex::new(receiver), progress: Arc::default() }
286    }
287}
288
289impl<T> Drop for Job<T> {
290    fn drop(&mut self) {
291        self.cancel();
292    }
293}
294
295/// What a background job has answered, if it has. A job whose thread is gone without an answer (it
296/// panicked) answers with a message, so that it does not leave a spinner turning for ever. A cancelled job answers
297/// at once; its thread ends with the runs under way, and what it finds is dropped.
298pub(crate) fn answer<T>(job: &Job<T>) -> Option<Result<T, Message>> {
299    if job.progress.cancel.load(Relaxed) {
300        return Some(Err(cancelled_message()));
301    }
302    match job.answer.lock().map(|job| job.try_recv()) {
303        Ok(Err(TryRecvError::Empty)) => None,
304        Ok(Ok(answer)) => Some(answer),
305        _ => Some(Err(("ui-job-ended", String::new()))),
306    }
307}
308
309/// A table for the window to draw as it is, the header first. Every cell is text in the chosen language.
310pub type Table = Vec<Vec<String>>;
311
312/// The table headers of the analysis panel, as translation keys.
313const CYCLE_KEYS: [&str; 15] = [
314    "ui-analysis-cycle-time",
315    "ui-analysis-duration",
316    "ui-analysis-path-deviation",
317    "ui-analysis-path-error",
318    "ui-analysis-tracking-error",
319    "ui-analysis-dwell-error",
320    "ui-analysis-path-angle-error",
321    "ui-analysis-tracking-angle-error",
322    "ui-analysis-dwell-angle-error",
323    "ui-analysis-belt-min",
324    "ui-analysis-slack-time",
325    "ui-analysis-radial-load",
326    "ui-analysis-guide-load",
327    "ui-analysis-guide-life",
328    "ui-analysis-guide-life-h",
329];
330/// One row per figure, one column per motor.
331const MOTOR_KEYS: [&str; 12] = [
332    "ui-analysis-peak-torque",
333    "ui-analysis-rms-torque",
334    "ui-analysis-cubic-torque",
335    "ui-analysis-winding-rise",
336    "ui-analysis-energy-in",
337    "ui-analysis-energy-back",
338    "ui-analysis-resistor-energy",
339    "ui-analysis-resistor-power",
340    "ui-analysis-dc-link-peak",
341    "ui-analysis-mains-energy",
342    "ui-analysis-housing-rise",
343    "ui-analysis-drive-overload",
344];
345/// Rows of the motor table that a machine or a config may lack: the lives in hours and the belt's tooth load.
346const LIFE_KEYS: [&str; 5] = [
347    "ui-analysis-pulley-bearing-life",
348    "ui-analysis-gearbox-life",
349    "ui-analysis-gearbox-gearing-life",
350    "ui-analysis-motor-bearing-life",
351    "ui-analysis-belt-tooth",
352];
353const VERDICT_KEYS: [&str; 5] =
354    ["ui-analysis-check", "ui-analysis-motor", "ui-analysis-value", "ui-analysis-limit", "ui-analysis-result"];
355const BAND_KEYS: [&str; 6] = [
356    "ui-analysis-check",
357    "ui-analysis-motor",
358    "ui-analysis-band-low",
359    "ui-analysis-band-high",
360    "ui-analysis-band-worst",
361    "ui-analysis-band-share",
362];
363const WORST_KEYS: [&str; 7] = [
364    "ui-analysis-check",
365    "ui-analysis-motor",
366    "ui-analysis-worst-value",
367    "ui-analysis-limit",
368    "ui-analysis-result",
369    "ui-analysis-worst-high",
370    "ui-analysis-worst-low",
371];
372const SEARCH_KEYS: [&str; 8] = [
373    "ui-analysis-motor",
374    "ui-search-gearbox",
375    "ui-search-axis",
376    "ui-search-mass",
377    "ui-search-cost",
378    "ui-analysis-result",
379    "ui-search-tightest",
380    "ui-search-share",
381];
382const TRACE_KEYS: [&str; 4] =
383    ["ui-trace-torque-rms", "ui-trace-torque-peak", "ui-trace-error-rms", "ui-trace-error-peak"];
384const FIT_KEYS: [&str; 4] = ["ui-trace-quantity", "ui-trace-config", "ui-trace-fitted", "ui-trace-error"];
385/// The label of a quantity of `JointFit`: `ui-trace-` and its name with dashes.
386fn joint_label(quantity: &str) -> String {
387    format!("ui-trace-{}", quantity.replace('_', "-"))
388}
389/// The four values of `AxisFit`, in its order.
390const FIT_QUANTITIES: [&str; 4] = ["ui-trace-mass", "ui-trace-viscous", "ui-trace-coulomb", "ui-trace-constant"];
391/// The labels of `identify::FRICTION_DETAILS`: `ui-trace-` and the quantity with dashes.
392const FIT_DETAIL_KEYS: [&str; 3] =
393    ["ui-trace-held-force-n", "ui-trace-breakaway-force-n", "ui-trace-presliding-stiffness-n-m"];
394/// The table of what the trace says per motor by itself.
395const IDENTIFY_KEYS: [&str; 5] =
396    ["ui-analysis-motor", "ui-trace-quantity", "ui-identify-value", "ui-trace-error", "ui-identify-interval"];
397/// Rows of the frequency response's table and of its fit.
398const SWEEP_KEYS: [&str; 2] = ["ui-sweep-resonance", "ui-sweep-damping"];
399/// The operating points: motor, speed, torque.
400const POINTS_KEYS: [&str; 3] = ["ui-analysis-motor", "ui-points-speed", "ui-points-torque"];
401/// The overlay's quantities, in the order of `Model::overlay`.
402const OVERLAY_KEYS: [&str; 3] = ["ui-overlay-torque", "ui-overlay-speed", "ui-overlay-error"];
403
404/// The labels of the run store and its comparison, the kinds of run and the quantities compared among them.
405const RUN_KEYS: [&str; 27] = [
406    "ui-run-motor-side",
407    "ui-run-live",
408    "ui-run-ghost",
409    "ui-run-cycle",
410    "ui-run-path",
411    "ui-run-trace",
412    "ui-run-tool-error",
413    "ui-run-default",
414    "ui-run-measured",
415    "ui-run-replayed",
416    "ui-run-reference",
417    "ui-run-verdicts",
418    "ui-run-peak-speed",
419    "ui-run-peak-error",
420    "ui-run-rms-error",
421    "ui-run-thermal-use",
422    "ui-run-peak-use",
423    "ui-run-energy",
424    "ui-run-tool-error-peak",
425    "ui-run-tool-error-rms",
426    "ui-plot-saved",
427    "quantity-torque",
428    "quantity-speed",
429    "quantity-following-error",
430    "ui-exported",
431    "ui-points-speed-rpm",
432    "ui-overlay-speed-rpm",
433];
434
435/// The overlay of a replayed trace, per quantity of `OVERLAY_KEYS` and per motor: (time, measured) and (time,
436/// simulated).
437pub type Overlay = Vec<(&'static str, Vec<[Vec<[f64; 2]>; 2]>)>;
438
439/// What the views work out from the history or the config, kept until what it was worked out from changes: a frame
440/// asks for them some sixty times a second, and building the machine from the config takes milliseconds.
441#[derive(Default)]
442struct Cache {
443    /// The statistics of every signal over the scopes' window (`Model::stats`), for the view they were taken of
444    /// (`Model::view_key`).
445    stats: Option<((u64, u64, u64), Arc<Vec<Option<Stats>>>)>,
446    /// The machine the config builds, for the views that ask it (friction, thermal parts, belt sections, workspace).
447    machine: Option<(Config, Option<Box<dyn Machine>>)>,
448    /// Each motor's highest rotor speed, for the config (`Model::motor_speeds`).
449    motor_speed: Option<(Config, Vec<f64>)>,
450    /// The workspace map, for the config, the height asked for and the grid.
451    workspace: Option<((Config, Option<u64>, usize), Option<Arc<WorkspaceSlice>>)>,
452    /// The coloured path, for the quantity and the path run (the address and length of its time column).
453    path: Option<((crate::insight::PathQuantity, usize, usize), Option<Arc<crate::insight::PathColours>>)>,
454}
455
456/// The overlay of a replayed trace (`Overlay`).
457fn overlay_of(fit: &TraceFit) -> Overlay {
458    let time = &fit.measured.time;
459    let line = |values: &[f64]| time.iter().zip(values).map(|(t, v)| [*t, *v]).collect::<Vec<_>>();
460    let columns = |m: &sim_components::trace::MotorTrace| [m.torque.clone(), m.speed.clone(), m.following_error()];
461    let pairs: Vec<_> =
462        fit.measured.motors.iter().zip(&fit.simulated.motors).map(|(m, s)| (columns(m), columns(s))).collect();
463    OVERLAY_KEYS
464        .iter()
465        .enumerate()
466        .map(|(q, key)| (*key, pairs.iter().map(|(m, s)| [line(&m[q]), line(&s[q])]).collect()))
467        .collect()
468}
469
470/// A short label for a config: the values it has other than the machine's default config, the first three of them
471/// as `path=value` and how many more; "default" where none.
472pub fn config_label(entry: &MachineEntry, config: &Config, tr: &Translations) -> String {
473    let default = entry.config();
474    let changed: Vec<String> = config
475        .leaves()
476        .into_iter()
477        .filter(|(path, value)| default.get(path).ok() != Some(value))
478        .map(|(path, value)| format!("{path}={value}"))
479        .collect();
480    match changed.len() {
481        0 => tr.tr("ui-run-default").to_string(),
482        1..=3 => changed.join(", "),
483        n => format!("{} +{}", changed[..3].join(", "), n - 3),
484    }
485}
486
487/// One plot of the run comparison: one quantity of every shown run, and each run's difference from the reference
488/// (`RunStore::against_reference`).
489pub struct RunPlot {
490    pub quantity: Quantity,
491    /// The quantity with its unit.
492    pub title: String,
493    pub lines: Vec<RunLine>,
494    pub differences: Vec<RunLine>,
495}
496
497/// One line of a `RunPlot`: of which run (its place in the store) and motor (its colour), named, and its points.
498pub struct RunLine {
499    pub run: usize,
500    pub motor: usize,
501    pub name: String,
502    pub points: Vec<[f64; 2]>,
503}
504
505/// A run of `kind` from the rows `sim` gave, judged by `verdicts`, labelled with the machine, the kind and `label`.
506fn judged_run(
507    kind: RunKind,
508    label: &str,
509    sim: &mut Sim,
510    entry: &'static MachineEntry,
511    rows: &[Vec<f64>],
512    verdicts: &[Verdict],
513    tr: &Translations,
514) -> Run {
515    let label = format!("{} · {} · {label}", tr.tr(entry.key), tr.tr(kind.key()));
516    let run =
517        Run::from_rows(label, kind, entry.id, sim.signal_infos(), sim.machine.motors(), rows.iter().map(Vec::as_slice));
518    Run { verdicts: Some(verdicts.to_vec()), ..run.rated(sim) }
519}
520
521/// The configured cycle of `config` as a judged run: its samples as the analysis measures it and its checks, the two
522/// runs side by side.
523fn cycle_run(entry: &'static MachineEntry, config: &Config, tr: &Translations) -> Result<Run, Message> {
524    let refused = |e: ConfigError| (e.key(), e.detail().to_string());
525    let mut sim = Sim::new(entry, config).map_err(refused)?;
526    let (load, rows) = std::thread::scope(|scope| {
527        let rows = scope.spawn(|| record_cycle(entry, config));
528        (analyse_cycle(&mut sim), rows.join().unwrap_or_else(|_| Ok(Vec::new())))
529    });
530    let (load, rows) = (load.map_err(|e| (e.key, String::new()))?, rows.map_err(refused)?);
531    let verdicts = verdicts(config, &load).map_err(refused)?;
532    Ok(judged_run(RunKind::Cycle, &config_label(entry, config, tr), &mut sim, entry, &rows, &verdicts, tr))
533}
534
535/// A simulation of `config` whose planned setpoint stands at `pose` (a running machine's setpoint), and the config it
536/// starts from. The planning model puts the tool at `start.pose` and its setpoint one rest sag off it (0.26 mm on the
537/// planar delta): the tool is moved by what is left until the setpoint is `pose`. A `pose` the machine cannot start
538/// at is refused; a push that would put the tool past a stroke's end puts it at that end (the setpoint then stands up
539/// to a sag off `pose` along that axis, where no tool on the stroke can put it). A push off the machine's envelope
540/// (not a stroke's end) keeps the last start: the tool moves less than a sag between two of them.
541pub fn start_at_setpoint(
542    entry: &'static MachineEntry,
543    config: &Config,
544    pose: &[f64],
545) -> Result<(Sim, Config), ConfigError> {
546    let mut from_here = config.clone();
547    from_here.set_text(&format!("start.pose = {pose:?}"))?;
548    let mut sim = Sim::new(entry, &from_here)?;
549    let mut tool = pose.to_vec();
550    for _ in 0..8 {
551        let off: Vec<f64> = pose.iter().zip(sim.control.planned_pos()).map(|(want, is)| want - is).collect();
552        if off.iter().all(|d| d.abs() < 1e-10) {
553            break;
554        }
555        tool.iter_mut().zip(&off).for_each(|(t, d)| *t += d);
556        tool.iter_mut().zip(sim.machine.axes()).for_each(|(t, a)| *t = t.clamp(a.min, a.max));
557        let mut closer = from_here.clone();
558        closer.set_text(&format!("start.pose = {tool:?}"))?;
559        let Ok(started) = Sim::new(entry, &closer) else { break };
560        // At a stroke's end the push cannot close the gap: the plan is as close as it gets.
561        let settled = started.control.planned_pos() == sim.control.planned_pos();
562        (sim, from_here) = (started, closer);
563        if settled {
564            break;
565        }
566    }
567    Ok((sim, from_here))
568}
569
570/// Runs `points` on a simulation of `config` and keeps every signal once per millisecond until the trajectory is
571/// through, the time from its start: the path as a run.
572fn record_path(sim: &mut Sim, points: Vec<(f64, Vec<f64>)>) -> Result<Vec<Vec<f64>>, CommandError> {
573    let end = points.last().map_or(0.0, |(t, _)| *t);
574    sim.command(Command::Trajectory(points))?;
575    let (start, every) = (sim.time(), ((1e-3 / sim.dt).round() as u64).max(1));
576    let (mut rows, mut sample) = (Vec::new(), Vec::new());
577    // Until the plan is through and a tenth of a second on, for the tool to settle; at most a minute past its end.
578    while (sim.control.busy() || sim.time() - start < end + 0.1) && sim.time() - start < end + 60.0 {
579        sim.step();
580        if sim.step.is_multiple_of(every) {
581            sim.sample(&mut sample);
582            rows.push(sample.clone());
583        }
584    }
585    Ok(rows)
586}
587/// Messages of the analysis panel, and the reasons a search gives for a motor it did not run.
588const NOTES: [&str; 31] = [
589    "ui-overlay-exported",
590    "ui-report-written",
591    "ui-report-failed",
592    "ui-config-opened",
593    "ui-config-saved",
594    "ui-config-save-failed",
595    "ui-simulation-ended",
596    "ui-job-ended",
597    "ui-analysis-stale",
598    "ui-analysis-tripped",
599    "ui-drive-tripped",
600    "ui-drive-fault",
601    "ui-drive-stopped",
602    "ui-search-bad-supply",
603    "ui-search-none",
604    "ui-search-no-gearbox",
605    "ui-search-refused",
606    "ui-search-limit-motor-speed",
607    "ui-search-limit-motor-torque",
608    "ui-search-axis-stroke",
609    "ui-search-axis-payload",
610    "ui-search-axis-speed",
611    "ui-search-bad-duty",
612    "ui-search-bad-rank",
613    "ui-search-motor-axes",
614    "ui-search-unknown-machine",
615    "ui-map-move-too-long",
616    "ui-map-bad-plane",
617    "ui-file-unreadable",
618    "ui-file-line",
619    "ui-analysis-figure",
620];
621/// The names of `[parts]`; a motor of the search goes into the first three, its drive and axis into two more.
622const PARTS: [&str; 6] = sim_components::catalog::PART_KEYS;
623const SENSITIVITY_KEYS: [&str; 6] = [
624    "ui-analysis-parameter",
625    "ui-analysis-low",
626    "ui-analysis-high",
627    "ui-analysis-peak-change",
628    "ui-analysis-rms-change",
629    "ui-analysis-time-change",
630];
631const OPTIMISED_KEYS: [&str; 3] = ["ui-analysis-setting", "ui-analysis-before", "ui-analysis-after"];
632/// Every check a cycle can be judged by (`verdicts`); each has a label "check-<name>".
633const CHECKS: [&str; 56] = [
634    "motor-peak",
635    "motor-thermal",
636    "stepper-synchronism",
637    "motor-s1",
638    "motor-speed",
639    "pulley-torque",
640    "gearbox-continuous",
641    "gearbox-peak",
642    "dc-link-energy",
643    "braking-resistor-continuous",
644    "braking-resistor-peak",
645    "settling",
646    "settling-angle",
647    "tracking",
648    "tracking-angle",
649    "belt-tension",
650    "belt-least-tension",
651    "gearbox-input-speed",
652    "gearbox-radial-load",
653    "guide-load",
654    "dc-link-overvoltage",
655    "gearbox-thermal",
656    "guide-thermal",
657    "line-module-continuous",
658    "line-module-peak",
659    "pulley-bearing-life",
660    "gearbox-life",
661    "gearbox-gearing-life",
662    "motor-bearing-life",
663    "guide-life",
664    "belt-tooth-load",
665    "belt-tooth-jump",
666    "belt-span-resonance",
667    "drive-current",
668    "drive-peak-current",
669    "drive-overload",
670    "singularity",
671    "screw-speed",
672    "screw-dn",
673    "screw-buckling",
674    "screw-static",
675    "screw-life",
676    "rack-feed-force",
677    "strain-wave-life",
678    "gantry-sync",
679    "cam-speed",
680    "cam-acceleration",
681    "cam-jerk",
682    "collision",
683    "self-collision",
684    "thermal-warm-start",
685    "thermal-cycle-repeat",
686    "pick-tracking",
687    "parts-missed",
688    "cushion-energy",
689    "load-factor",
690];
691/// The parts of a motor's torque in the effect view, in the order of `TORQUE_PARTS`, and the torque itself.
692const BREAKDOWN_KEYS: [&str; 5] = [
693    "quantity-torque-inertia",
694    "quantity-torque-gravity",
695    "quantity-torque-friction",
696    "quantity-torque-rest",
697    "quantity-torque",
698];
699/// The parts of a friction force, in the order of `Machine::friction_curve`.
700const FRICTION_KEYS: [&str; 3] =
701    ["quantity-friction-coulomb", "quantity-friction-viscous", "quantity-friction-stiction"];
702/// The labels of the effect view's tables and of the rows of an energy budget that the machine does not name.
703const EFFECT_KEYS: [&str; 22] = [
704    "ui-effects-part",
705    "ui-effects-peak",
706    "ui-effects-rms",
707    "ui-effects-item",
708    "ui-effects-energy",
709    "ui-effects-share",
710    "ui-effects-now",
711    "ui-effects-total",
712    "quantity-friction-speed",
713    "quantity-friction-load-scale",
714    "budget-supply",
715    "budget-unaccounted",
716    "budget-copper",
717    "budget-emf",
718    "budget-resistor",
719    "budget-windings",
720    "budget-capacitors",
721    "budget-mains",
722    "budget-line-module",
723    "budget-payload",
724    "budget-crash",
725    "budget-discharge",
726];
727
728/// The labels of the thermal, belt and comparison views.
729const VIEW_KEYS: [&str; 30] = [
730    "ui-effects-component",
731    "ui-effects-signal",
732    "ui-effects-thermal",
733    "ui-effects-thermal-hint",
734    "ui-effects-thermal-off",
735    "ui-effects-rise",
736    "ui-effects-settles",
737    "ui-effects-rated",
738    "ui-effects-of-rated",
739    "ui-effects-over-rating",
740    "ui-effects-settled-of-rated",
741    "ui-effects-cold",
742    "ui-effects-above",
743    "ui-effects-belt",
744    "ui-effects-belt-hint",
745    "ui-effects-section",
746    "ui-effects-tension",
747    "ui-effects-pretension",
748    "ui-effects-rating",
749    "ui-effects-stretch",
750    "ui-effects-slack",
751    "ui-effects-double",
752    "ui-effects-compare",
753    "ui-effects-compare-hint",
754    "ui-effects-effect",
755    "ui-effects-quantity",
756    "ui-effects-run-compare",
757    "ui-effects-difference-peak",
758    "ui-effects-difference-rms",
759    "ui-effects-off",
760];
761
762/// The part colours live in the core, so that the browser's 3D view (sim-wasm) colours as this one does.
763pub use sim_core::scene::{heat_color, part_color};
764
765/// The temperatures in the effect view: one line per winding and, with effects.part_heating or thermal_feedback, per
766/// heated part, over the scopes' window, and the table of where each is now, where it settles on the analysed cycle and
767/// what it is rated for.
768pub struct ThermalView {
769    /// Per motor winding and heated part its name and the points (time, temperature rise in K).
770    pub lines: Vec<(String, Vec<[f64; 2]>)>,
771    pub table: Table,
772    /// Neither the windings nor the parts warm (effects.winding_heating, part_heating and thermal_feedback off).
773    pub off: bool,
774}
775
776/// The belt sections in the effect view: tension and stretch per section over the scopes' window, the pretension and
777/// the rating to compare them with, and the table of the newest sample.
778pub struct BeltView {
779    /// Per section its name and the points (time, tension in N) and (time, stretch in mm).
780    pub tension: Vec<(String, Vec<[f64; 2]>)>,
781    pub stretch: Vec<(String, Vec<[f64; 2]>)>,
782    pub pretension: f64,
783    /// `ratings.belt_max_tension_n`, where the config has it.
784    pub rating: Option<f64>,
785    pub table: Table,
786    /// The titles of the two plots with their units, and the ends of the 3D view's colour scale (no tension, twice
787    /// the pretension) with their numbers.
788    pub titles: [String; 2],
789    pub scale: [String; 2],
790}
791
792/// The effect comparison: one scope's quantity with the effect on (solid) and off (dashed), and per line the peak and
793/// RMS of the difference.
794pub struct CompareView {
795    /// The effect's label, and the quantity with its unit.
796    pub effect: String,
797    pub title: String,
798    /// Per signal of the quantity its owner's name and the points (time, value) on and off.
799    pub lines: Vec<(String, Vec<[f64; 2]>, Vec<[f64; 2]>)>,
800    pub table: Table,
801}
802
803/// A horizontal slice through what the machine can reach, for the workspace map (`Model::workspace_slice`).
804pub struct WorkspaceSlice {
805    /// The span of the first two axes the grid covers, (low, high) each, and the slice's height on the third.
806    pub x: (f64, f64),
807    pub y: (f64, f64),
808    pub z: f64,
809    /// Nodes per side: node (i, j) is at x.0 + i (x.1 - x.0) / (n - 1), and likewise in y with j.
810    pub n: usize,
811    /// Per node, row after row (j outer): the condition number there, `INFINITY` out of reach of the kinematics, and
812    /// whether the machine goes there (`Machine::unreachable` has nothing against it: within the envelope and the
813    /// joints' stops, and not near a singularity).
814    pub nodes: Vec<(f64, bool)>,
815    /// Where the colour scale ends: `ratings.max_condition_number`, or 10 where the config has none.
816    pub limit: f64,
817    /// The range the height can be chosen in: the third axis's.
818    pub heights: (f64, f64),
819    /// Per node as `nodes`, the largest tool acceleration the motors can give there in the worst direction, m/s^2
820    /// (`insight::worst_acceleration`, with each motor's peak torque); NaN out of reach.
821    pub acceleration: Vec<f64>,
822}
823
824/// One friction contact in the effect view.
825pub struct FrictionView {
826    /// Whose it is, translated.
827    pub title: String,
828    /// Steady sliding over the speed, with the levels at the guide load of the newest sample: the friction force
829    /// and its Coulomb, viscous and stiction parts, each with its label.
830    pub curves: [(String, Vec<[f64; 2]>); 4],
831    /// Where the contact is now, by the newest sample: (speed, friction force).
832    pub now: Option<[f64; 2]>,
833    /// The newest sample as a table: speed, the three parts, the friction force and the load factor.
834    pub table: Table,
835    /// A joint's bearings: the speed is an angular speed (rad/s) and the force a torque (N m).
836    pub rotary: bool,
837}
838
839/// The most stretches a band over a trace is drawn in (`Model::band_plots`): each is a filled shape of its own.
840pub const BAND_BUCKETS: usize = 600;
841
842/// Rows of the sensitivity ranking that are shown: the parameters that matter most.
843const TOP_ROWS: usize = 8;
844
845/// How many edits of the config `Model::undo` goes back.
846const UNDO_STEPS: usize = 50;
847
848/// Edits of one value this close together are one step: a drag changes it every frame.
849const SAME_EDIT: std::time::Duration = std::time::Duration::from_millis(600);
850
851/// A number at a readable length, whatever its size: four digits and at most three decimals, so 12.5 reads
852/// as 12.50 and 1912.141 as 1912, and 0.0000312 as 3.12e-5; at least three digits, as the exponent has, so 0.0146
853/// reads as 0.0146 and not 0.015. Narrow, so that the tables fit the panel.
854pub fn short(value: f64) -> String {
855    match value.abs() {
856        0.0 => "0.000".into(),
857        size if (0.01..1e5).contains(&size) => {
858            let at = |exponent: i32| format!("{value:.*}", (3 - exponent).clamp(0, 3).max(2 - exponent) as usize);
859            let exponent = size.log10().floor() as i32;
860            let text = at(exponent);
861            // Rounding up into the next power of ten (9.9996) leaves one digit too many.
862            let carried = text.parse::<f64>().is_ok_and(|r| r.abs() >= 10f64.powi(exponent + 1));
863            if carried { at(exponent + 1) } else { text }
864        }
865        _ => format!("{value:.2e}"),
866    }
867}
868
869/// A check's value and limit as `short` writes them; a failing one that would read the same gets as many digits as
870/// it takes to tell them apart (1.0004 against 1.000).
871pub fn short_pair(value: f64, limit: f64, ok: bool) -> (String, String) {
872    let (a, b) = (short(value), short(limit));
873    if ok || a != b || value == limit {
874        return (a, b);
875    }
876    let digits = (4..=17).find(|d| format!("{value:.*e}", d - 1) != format!("{limit:.*e}", d - 1)).unwrap_or(17);
877    (format!("{value:.*e}", digits - 1), format!("{limit:.*e}", digits - 1))
878}
879
880pub struct Model {
881    pub entry: &'static MachineEntry,
882    pub lang: &'static str,
883    pub tr: Translations,
884    /// The config as edited. The simulation may yet refuse the last edits.
885    pub config: Config,
886    /// The text the config was read from (the machine's default or a file), whose comments and layout a
887    /// saved file keeps.
888    config_text: String,
889    /// The file the config was last opened from or saved to ("" for none): apart from the field a path is typed
890    /// into, which may name a file about to be opened. A JSON machine file is held here too (to be reopened at the
891    /// next start), though Save does not write over it (`save_target`).
892    pub file: String,
893    /// The last config the simulation took, to go back to when it refuses one, and the configs sent to it
894    /// that it has not answered yet, oldest first.
895    accepted: Config,
896    sent: VecDeque<Config>,
897    /// The config as last opened, saved or taken from the machine's default: `dirty` is a difference from it.
898    clean: Config,
899    /// The machine's default config, which `changed_params` compares with.
900    default: Config,
901    /// The configs before each edit (`UNDO_STEPS` at most, oldest first) and those undone, for `undo` and `redo`.
902    undone: Vec<Config>,
903    redone: Vec<Config>,
904    /// The path and time of the last edit of one value, so that a drag is one step (`record_edit`).
905    last_edit: Option<(String, std::time::Instant)>,
906    pub session: Session,
907    /// The end of the simulation thread has been reported.
908    ended: bool,
909    pub scopes: Vec<Scope>,
910    pub history: History,
911    /// The scopes' window as it was when they were frozen; the simulation runs on meanwhile. Only the window is kept,
912    /// not the whole history, which on the six-axis arm is a hundred megabytes.
913    pub frozen: Option<History>,
914    /// How often the scopes were frozen, so that a cache tells one frozen window from the next.
915    freezes: u64,
916    /// The runs kept for comparing (`runs`), and the units speeds and lengths are shown in.
917    pub runs: RunStore,
918    pub units: Units,
919    /// Runs being recorded (`record_run`), and CSV files being written (`export_traces`, `export_overlay`).
920    run_jobs: Vec<Job<Run>>,
921    export_jobs: Vec<Job<Message>>,
922    /// The replayed trace's overlay, worked out once when the trace arrives.
923    overlay: Overlay,
924    cache: Mutex<Cache>,
925    /// Seconds of history the scopes show.
926    pub window_s: f64,
927    pub scene: Scene,
928    pub paused: bool,
929    pub speed: f64,
930    /// How many times larger the 3D view draws the parts' deflections (`Scene::exaggeration`).
931    pub exaggeration: f64,
932    /// Target of the next point-to-point move, per axis.
933    pub target: Vec<f64>,
934    pub messages: Vec<Message>,
935    pub tuning_axis: usize,
936    pub tuning: Option<Tuning>,
937    tuning_job: Option<Job<Tuning>>,
938    /// The sizing report being written; answers with the message to show.
939    report_job: Option<Job<Message>>,
940    pub inputs: Inputs,
941    /// Results of the analysis panel, each for the config as it was when it was asked for.
942    /// With the motors' torque-speed curves, to plot the operating points over.
943    pub cycle_report: Option<(CycleLoad, Vec<Verdict>, Curves)>,
944    /// The checks of the cycle with their error bands, where the cycle was analysed with them.
945    pub bands: Option<Vec<Band>>,
946    /// How many samples those bands are of; 0: each bounded value alone at its low and at its high bound.
947    pub band_samples: usize,
948    /// Per check the worst corner of the bounds found, and the paths of the bounds in the order its `high` has them.
949    pub worst: Option<(Vec<Worst>, Vec<String>)>,
950    /// The cycle as configured and the varied parameters, strongest first.
951    pub sensitivity: Option<(CycleLoad, Vec<Sensitivity>)>,
952    pub optimised: Option<Optimised>,
953    /// The motors of the search as ranked, and the supply they were searched for.
954    pub candidates: Option<(Vec<Candidate>, String)>,
955    pub path_run: Option<PathRun>,
956    /// Where the tool has been in the 3D scene since the machine took the planned path, a point per 0.1 mm of
957    /// travel and the newest `session::TRAIL` of them: the path it really took, to draw beside the planned one. `None`
958    /// before the machine has taken a path (it may refuse it), and after a reconfigure or the start of a cycle.
959    pub trail: Option<Vec<[f64; 3]>>,
960    pub trace_fit: Option<TraceFit>,
961    /// Per motor the frequency response, at the frequencies `inputs` gave when it was asked for.
962    pub sweeps: Option<Vec<Vec<SweepPoint>>>,
963    /// The measured response's fit, and the motor it was taken on.
964    pub sweep_fit: Option<(usize, SweepFit)>,
965    /// The effect comparison, with the effect that was switched.
966    pub comparison: Option<(String, Comparison)>,
967    /// The search's views, the ratio sweep, the kinematics comparison and the path tab's move maps (`search_views`).
968    pub views: crate::search_views::Views,
969    /// The loop-response tab's measurement and its result (`frequency`).
970    pub loop_response: crate::frequency::LoopResponse,
971    /// Per kind of analysis (`Analysis as usize`) the config its result was computed for. A result says
972    /// nothing about another config: it is marked (`outdated`), and nothing of it is applied to one.
973    computed_for: [Option<Config>; 9],
974    /// The jobs under way, each with the config it was started with.
975    analysis_jobs: Vec<(Analysis, Config, Job<Report>)>,
976    /// The mode list, the band runs over the cycle's traces and their job (`insight`).
977    pub insight: crate::insight::Insight,
978}
979
980/// A config without the names of its motor, gearbox and drive: what a motor search does not depend on, because it puts its
981/// own in (the drive the catalogue pairs with each motor). The belt and axis the config names are part of what it
982/// searches on, so naming an axis of the axis search marks the search as computed for an earlier configuration.
983fn without_parts(config: &Config) -> Config {
984    let mut out = config.clone();
985    for key in &PARTS[..4] {
986        let _ = out.set_text(&format!("parts.{key} = \"\""));
987    }
988    out
989}
990
991/// The config as a file: `text`, the file it was read from, with every value the config has changed written
992/// in place, so that its comments and layout stay. Where that does not give the config back (an array was
993/// changed), the config is written plainly, without comments.
994fn saved_text(config: &Config, text: &str) -> Result<String, Message> {
995    let plain = config.to_text().map_err(|e| (e.key(), e.detail().to_string()))?;
996    let (Ok(doc), Ok(old)) = (toml_edit::Document::parse(text), Config::parse(text)) else { return Ok(plain) };
997    // Each new value replaces the old one's text: a document written out anew would group dotted keys that the file
998    // has apart (`ratings.a`, `thermal.b`, `ratings.c` in `[bounds]`), and so change its order.
999    let mut edits = Vec::new();
1000    for (path, value) in config.leaves() {
1001        if old.get(&path).ok() == Some(&value) {
1002            continue;
1003        }
1004        let new = match value {
1005            Value::Float(x) => toml_edit::Value::from(x),
1006            Value::Integer(n) => toml_edit::Value::from(n),
1007            Value::Boolean(on) => toml_edit::Value::from(on),
1008            Value::String(name) => toml_edit::Value::from(name),
1009            _ => return Ok(plain),
1010        };
1011        // The span is the value's own text: the comment behind it stays.
1012        let span = path
1013            .split('.')
1014            .try_fold(doc.as_item(), |item, key| item.get(key))
1015            .and_then(toml_edit::Item::as_value)
1016            .and_then(toml_edit::Value::span);
1017        let Some(span) = span else { return Ok(plain) };
1018        edits.push((span, new.to_string()));
1019    }
1020    edits.sort_by_key(|(span, _)| std::cmp::Reverse(span.start));
1021    let mut kept = text.to_string();
1022    for (span, new) in edits {
1023        kept.replace_range(span, &new);
1024    }
1025    Ok(if Config::parse(&kept).as_ref() == Ok(config) { kept } else { plain })
1026}
1027
1028fn texts(lang: &str, entry: &MachineEntry) -> Translations {
1029    let mut tr = translations(lang, entry);
1030    crate::I18N.iter().filter(|(l, _)| *l == lang).for_each(|(_, text)| tr.add(text));
1031    tr
1032}
1033
1034/// The quantity a setpoint or command belongs to: "position-setpoint" is drawn with "position".
1035fn actual_quantity(quantity_key: &str) -> Option<&str> {
1036    quantity_key.strip_suffix("-setpoint").or_else(|| quantity_key.strip_suffix("-command"))
1037}
1038
1039/// The scopes follow from the signal list alone: one per quantity, in order of first appearance,
1040/// with setpoints and commands joined to the quantity they ask for.
1041fn scopes_for(signals: &[SignalInfo]) -> Vec<Scope> {
1042    const SHOWN_AT_START: [&str; 4] =
1043        ["quantity-position", "quantity-following-error", "quantity-speed", "quantity-torque"];
1044    let mut scopes: Vec<Scope> = Vec::new();
1045    for (i, signal) in signals.iter().enumerate().filter(|(_, s)| s.id != "time") {
1046        let actual = actual_quantity(&signal.quantity_key)
1047            .filter(|a| signals.iter().any(|s| s.quantity_key == *a && s.unit == signal.unit));
1048        let key = actual.unwrap_or(&signal.quantity_key);
1049        let line = ScopeLine { signal: i, reference: actual.is_some() };
1050        match scopes.iter_mut().find(|s| s.quantity_key == key && s.unit == signal.unit) {
1051            Some(scope) => scope.lines.push(line),
1052            None => scopes.push(Scope {
1053                quantity_key: key.into(),
1054                unit: signal.unit.clone(),
1055                lines: vec![line],
1056                visible: SHOWN_AT_START.contains(&key),
1057            }),
1058        }
1059    }
1060    scopes
1061}
1062
1063/// A factor and an SI prefix that bring a value of this size into a readable range:
1064/// 0.00004 m reads as 40 µm.
1065pub fn display_scale(peak: f64, unit: &str) -> (f64, &'static str) {
1066    // Only plain SI units take a prefix: not %, 1/h, deg or rpm.
1067    const PREFIXED: [&str; 17] = [
1068        "m", "s", "N", "W", "V", "A", "J", "Hz", "rad", "N m", "m/s", "m/s2", "m/s²", "rad/s", "rad/s2", "rad/s²",
1069        "N m/rad",
1070    ];
1071    match peak {
1072        _ if !PREFIXED.contains(&unit) || peak == 0.0 || !peak.is_finite() => (1.0, ""),
1073        p if p < 1e-3 => (1e6, "µ"),
1074        p if p < 0.1 => (1e3, "m"),
1075        p if p >= 1e4 => (1e-3, "k"),
1076        _ => (1.0, ""),
1077    }
1078}
1079
1080impl Model {
1081    pub fn new(entry: &'static MachineEntry, lang: &'static str) -> Self {
1082        Self::with_config(entry, lang, entry.config(), entry.default_config.into())
1083            .expect("default config of a registered machine must run")
1084    }
1085
1086    /// The machine running `config`, which was read from `text`.
1087    fn with_config(
1088        entry: &'static MachineEntry,
1089        lang: &'static str,
1090        config: Config,
1091        text: String,
1092    ) -> Result<Self, ConfigError> {
1093        let session = Session::start(entry, &config)?;
1094        let sweep_amplitude = default_sweep_amplitude(entry, &config)?;
1095        let mut model = Self {
1096            entry,
1097            lang,
1098            tr: texts(lang, entry),
1099            scopes: scopes_for(&session.signals),
1100            accepted: config.clone(),
1101            sent: VecDeque::new(),
1102            clean: config.clone(),
1103            default: entry.config(),
1104            undone: Vec::new(),
1105            redone: Vec::new(),
1106            last_edit: None,
1107            config,
1108            config_text: text,
1109            file: String::new(),
1110            session,
1111            ended: false,
1112            history: History::new(HISTORY),
1113            frozen: None,
1114            freezes: 0,
1115            runs: RunStore::default(),
1116            units: Units::default(),
1117            run_jobs: Vec::new(),
1118            export_jobs: Vec::new(),
1119            overlay: Vec::new(),
1120            cache: Mutex::default(),
1121            window_s: 5.0,
1122            scene: Scene::default(),
1123            paused: false,
1124            speed: 1.0,
1125            exaggeration: 1.0,
1126            target: Vec::new(),
1127            messages: Vec::new(),
1128            tuning_axis: 0,
1129            tuning: None,
1130            tuning_job: None,
1131            report_job: None,
1132            inputs: Inputs {
1133                bands: false,
1134                samples: 0,
1135                worst: false,
1136                supply: SUPPLIES[1].into(),
1137                series: String::new(),
1138                gearboxes: String::new(),
1139                axes: false,
1140                search: Default::default(),
1141                map: Default::default(),
1142                path_file: String::new(),
1143                path_timed: false,
1144                time_optimal: false,
1145                trace_file: String::new(),
1146                trace_map: String::new(),
1147                trace_stiffness: false,
1148                config_file: String::new(),
1149                parts: Default::default(),
1150                sweep_from: 5.0,
1151                sweep_to: 500.0,
1152                sweep_count: SWEEP_POINTS,
1153                sweep_amplitude,
1154                sweep_file: String::new(),
1155                sweep_motor: 0,
1156                compare_effect: String::new(),
1157                compare_quantity: "quantity-torque".into(),
1158                workspace_z: None,
1159                workspace_by: Default::default(),
1160                path_colour: None,
1161                path_probe: None,
1162                assignment: String::new(),
1163                param_filter: String::new(),
1164                run_set: String::new(),
1165                run_file: String::new(),
1166            },
1167            cycle_report: None,
1168            bands: None,
1169            band_samples: 0,
1170            worst: None,
1171            sensitivity: None,
1172            optimised: None,
1173            candidates: None,
1174            path_run: None,
1175            trail: None,
1176            trace_fit: None,
1177            sweeps: None,
1178            sweep_fit: None,
1179            comparison: None,
1180            computed_for: Default::default(),
1181            analysis_jobs: Vec::new(),
1182            views: Default::default(),
1183            loop_response: Default::default(),
1184            insight: Default::default(),
1185        };
1186        model.target = model.config.f64s("start.pose").unwrap_or_default();
1187        model.show_parts();
1188        // Guide friction to compare where the config has it, else the first effect.
1189        let effects: Vec<String> =
1190            model.effects().into_iter().map(|(path, ..)| path["effects.".len()..].to_string()).collect();
1191        model.inputs.compare_effect =
1192            effects.iter().find(|e| *e == "guide_friction").or(effects.first()).cloned().unwrap_or_default();
1193        Ok(model)
1194    }
1195
1196    /// Switching machine restarts the simulation with that machine's default config.
1197    pub fn set_machine(&mut self, entry: &'static MachineEntry) {
1198        let fresh = Self::new(entry, self.lang);
1199        self.restart(fresh);
1200    }
1201
1202    /// Puts a freshly started model in place of this one, keeping how the window is set up and the fields as
1203    /// typed, except those that belong to the machine and config left: the config file (Save would write the
1204    /// new config over it), a motor number the new machine may not have, and the sweep amplitude where it is
1205    /// still the default for the old motors.
1206    fn restart(&mut self, fresh: Self) {
1207        let (paused, speed, exaggeration, window, inputs) =
1208            (self.paused, self.speed, self.exaggeration, self.window_s, self.inputs.clone());
1209        let old_amplitude = default_sweep_amplitude(self.entry, &self.config).ok();
1210        // The runs kept are compared across machines and configs: they stay, as do the units.
1211        let (runs, units, run_jobs) = (std::mem::take(&mut self.runs), self.units, std::mem::take(&mut self.run_jobs));
1212        *self = fresh;
1213        (self.runs, self.units, self.run_jobs) = (runs, units, run_jobs);
1214        let parts = std::mem::take(&mut self.inputs.parts);
1215        let sweep_motor = inputs.sweep_motor.min(self.session.motors.len().saturating_sub(1));
1216        let sweep_amplitude = if old_amplitude == Some(inputs.sweep_amplitude) {
1217            self.inputs.sweep_amplitude
1218        } else {
1219            inputs.sweep_amplitude
1220        };
1221        let config_file = String::new();
1222        let compare_effect = if self.config.bool(&format!("effects.{}", inputs.compare_effect)).is_ok() {
1223            inputs.compare_effect.clone()
1224        } else {
1225            self.inputs.compare_effect.clone()
1226        };
1227        (self.window_s, self.inputs) =
1228            (window, Inputs { parts, config_file, sweep_motor, sweep_amplitude, compare_effect, ..inputs });
1229        self.set_paused(paused);
1230        self.set_speed(speed);
1231        self.set_exaggeration(exaggeration);
1232    }
1233
1234    /// The part fields show the parts the config names.
1235    fn show_parts(&mut self) {
1236        for (field, key) in self.inputs.parts.iter_mut().zip(PARTS) {
1237            *field =
1238                self.config.get(&format!("parts.{key}")).ok().and_then(|name| name.as_str()).unwrap_or("").to_string();
1239        }
1240    }
1241
1242    /// Opens a config file for the machine shown: it replaces the running config, as switching machine does.
1243    /// A file that cannot be read, or that the machine refuses, is reported and the running config stays.
1244    /// A config of another machine (one this machine refuses and that one reads) switches to that machine.
1245    /// A machine file (one with a `[machine]` table, or any `.json`; see docs/machine-files.md) brings its own
1246    /// machine and replaces the machine shown too.
1247    pub fn open_config(&mut self, path: &str) {
1248        let json = path.to_ascii_lowercase().ends_with(".json");
1249        let machine_file = json
1250            || std::fs::read_to_string(path)
1251                .ok()
1252                .and_then(|text| Config::parse(&text).ok())
1253                .is_some_and(|c| c.get("machine").is_ok_and(|m| m.is_table()));
1254        if machine_file {
1255            let opened = sim_machines::load_file(std::path::Path::new(path))
1256                .map_err(|e| {
1257                    (
1258                        e.error.key(),
1259                        format!("{}{}: {}", path, e.line.map_or(String::new(), |l| format!(":{l}")), e.error.detail()),
1260                    )
1261                })
1262                .and_then(|entry| {
1263                    Self::with_config(entry, self.lang, entry.config(), entry.default_config.to_string())
1264                        .map_err(|e| (e.key(), e.detail().to_string()))
1265                });
1266            return match opened {
1267                Ok(fresh) => {
1268                    self.restart(fresh);
1269                    // A JSON file is held as TOML: Save does not write that over it.
1270                    self.inputs.config_file = if json { String::new() } else { path.into() };
1271                    self.file = path.into();
1272                    self.say(("ui-machine-file-opened", path.into()));
1273                }
1274                Err(message) => self.say(message),
1275            };
1276        }
1277        let opened = std::fs::read_to_string(path)
1278            .map_err(|e| ("ui-file-unreadable", format!("{path}: {e}")))
1279            .and_then(|text| {
1280                let entry = match sim_components::load_config(self.entry, &text) {
1281                    Ok(_) => self.entry,
1282                    Err(e) => *MACHINES
1283                        .iter()
1284                        .find(|m| sim_components::load_config(m, &text).is_ok())
1285                        .ok_or_else(|| (e.key(), e.detail().to_string()))?,
1286                };
1287                let config =
1288                    sim_components::load_config(entry, &text).map_err(|e| (e.key(), e.detail().to_string()))?;
1289                Self::with_config(entry, self.lang, config, text).map_err(|e| (e.key(), e.detail().to_string()))
1290            });
1291        match opened {
1292            Ok(fresh) => {
1293                self.restart(fresh);
1294                self.inputs.config_file = path.into();
1295                self.file = path.into();
1296                self.say(("ui-config-opened", path.into()));
1297            }
1298            Err(message) => self.say(message),
1299        }
1300    }
1301
1302    /// Writes the config as edited to a file: over the text it was read from, so that the comments and layout
1303    /// of that file stay, wherever only values have changed.
1304    /// A file that holds a config of another machine is not overwritten.
1305    pub fn save_config(&mut self, path: &str) {
1306        let other_machine = std::fs::read_to_string(path)
1307            .ok()
1308            .filter(|old| sim_components::load_config(self.entry, old).is_err())
1309            .and_then(|old| {
1310                MACHINES.iter().find(|m| m.id != self.entry.id && sim_components::load_config(m, &old).is_ok())
1311            });
1312        if let Some(other) = other_machine {
1313            let name = self.tr.tr(other.key).to_string();
1314            return self.say(("ui-config-other-machine", format!("{path}: {name}")));
1315        }
1316        let written = saved_text(&self.config, &self.config_text).and_then(|text| {
1317            std::fs::write(path, &text).map_err(|e| ("ui-config-save-failed", format!("{path}: {e}")))?;
1318            Ok(text)
1319        });
1320        match written {
1321            Ok(text) => {
1322                self.config_text = text;
1323                self.clean = self.config.clone();
1324                self.inputs.config_file = path.into();
1325                self.file = path.into();
1326                self.say(("ui-config-saved", path.into()));
1327            }
1328            Err(message) => self.say(message),
1329        }
1330    }
1331
1332    /// Names the parts typed in `inputs.parts` in the config and applies it to the running simulation, as
1333    /// the motor search's button does. A name the catalogue does not have is refused, and so is any name in a
1334    /// config without `[parts]`, as on the command line.
1335    pub fn apply_parts(&mut self) {
1336        let names = self.inputs.parts.clone().map(|name| name.trim().to_string());
1337        if !names[1].is_empty() && !SUPPLIES.contains(&names[1].as_str()) {
1338            return self.say(("ui-search-bad-supply", names[1].clone()));
1339        }
1340        self.name_parts(names.each_ref().map(String::as_str));
1341    }
1342
1343    pub fn set_language(&mut self, lang: &'static str) {
1344        self.lang = lang;
1345        self.tr = texts(lang, self.entry);
1346    }
1347
1348    pub fn set_paused(&mut self, paused: bool) {
1349        self.paused = paused;
1350        self.session.send(Request::Pause(paused));
1351    }
1352
1353    pub fn set_speed(&mut self, speed: f64) {
1354        self.speed = speed;
1355        self.session.send(Request::Speed(speed));
1356    }
1357
1358    pub fn set_exaggeration(&mut self, factor: f64) {
1359        self.exaggeration = factor.clamp(1.0, 1.0e4);
1360        self.session.send(Request::Exaggeration(self.exaggeration));
1361    }
1362
1363    /// Adds a message, unless it only repeats the last one: a refusal that comes back with every edit
1364    /// would otherwise bury everything else.
1365    fn say(&mut self, message: Message) {
1366        if self.messages.last() != Some(&message) {
1367            self.messages.push(message);
1368        }
1369    }
1370
1371    /// The axis limits that ask too much of the motors, in place of those reported before.
1372    fn say_limits(&mut self, violations: Vec<sim_components::LimitViolation>) {
1373        self.messages.retain(|(key, _)| !key.starts_with("limit-"));
1374        for v in violations {
1375            let motor = self.tr.tr(self.session.motors[v.motor].key).to_string();
1376            self.say((v.key, format!("{motor}: {:.4} > {:.4}", v.needed, v.allowed)));
1377        }
1378    }
1379
1380    /// Sends the config as edited to the running simulation. Its answer comes with `poll`.
1381    fn reconfigure(&mut self) {
1382        self.sent.push_back(self.config.clone());
1383        self.session.send(Request::Reconfigure(self.config.clone()));
1384    }
1385
1386    /// Edits one config value and applies the config to the running simulation.
1387    pub fn set_param(&mut self, path: &str, value: Value) {
1388        let before = self.config.clone();
1389        match sim_components::set_config(self.entry, &mut self.config, path, value) {
1390            Ok(()) => {
1391                self.record_edit(before, Some(path));
1392                self.reconfigure();
1393            }
1394            Err(e) => self.say((e.key(), e.detail().into())),
1395        }
1396    }
1397
1398    /// Notes `before` as the state an edit leaves, for `undo`; `same` names the value the edit changed, where
1399    /// repeated edits of it are one step. An edit that changed nothing is none.
1400    fn record_edit(&mut self, before: Config, same: Option<&str>) {
1401        let now = std::time::Instant::now();
1402        let repeated = same.is_some_and(|path| {
1403            self.last_edit.as_ref().is_some_and(|(last, at)| last == path && now.duration_since(*at) < SAME_EDIT)
1404        });
1405        self.last_edit = same.map(|path| (path.to_string(), now));
1406        if before == self.config || repeated {
1407            return;
1408        }
1409        self.redone.clear();
1410        self.undone.push(before);
1411        if self.undone.len() > UNDO_STEPS {
1412            self.undone.remove(0);
1413        }
1414    }
1415
1416    /// Where Save puts the config without asking: the file last opened or saved to, but not a JSON machine file (the
1417    /// config is written as TOML); `None` where the file dialog is to be asked.
1418    pub fn save_target(&self) -> Option<String> {
1419        Some(self.file.clone()).filter(|f| !f.is_empty() && !f.to_ascii_lowercase().ends_with(".json"))
1420    }
1421
1422    /// Where the file dialog starts when Save is asked for over an open and `save_target` has no file: beside the JSON
1423    /// machine file the config came from, as TOML; nowhere for a config from no file (not the field, which names the
1424    /// file about to be opened).
1425    pub fn save_suggestion(&self) -> String {
1426        if self.file.is_empty() {
1427            return String::new();
1428        }
1429        std::path::Path::new(&self.file).with_extension("toml").display().to_string()
1430    }
1431
1432    /// The config differs from what was last opened, saved or taken from the machine's default.
1433    pub fn dirty(&self) -> bool {
1434        self.config != self.clean
1435    }
1436
1437    pub fn can_undo(&self) -> bool {
1438        !self.undone.is_empty()
1439    }
1440
1441    pub fn can_redo(&self) -> bool {
1442        !self.redone.is_empty()
1443    }
1444
1445    /// Takes the last edit of the config back, and applies the config to the running simulation.
1446    pub fn undo(&mut self) {
1447        self.step_history(true);
1448    }
1449
1450    /// Does the edit again that `undo` took back.
1451    pub fn redo(&mut self) {
1452        self.step_history(false);
1453    }
1454
1455    fn step_history(&mut self, back: bool) {
1456        // A state equal to the present one (an edit the simulation refused and rolled back) is no step.
1457        while let Some(state) = if back { self.undone.pop() } else { self.redone.pop() } {
1458            if state == self.config {
1459                continue;
1460            }
1461            let from = std::mem::replace(&mut self.config, state);
1462            let to = if back { &mut self.redone } else { &mut self.undone };
1463            to.push(from);
1464            self.last_edit = None;
1465            self.reconfigure();
1466            self.show_parts();
1467            return;
1468        }
1469    }
1470
1471    /// Applies one `path = value` (TOML value) to the config and the running simulation, as `sim-cli --set` does:
1472    /// a key the config does not have, a value of another type or text that is no assignment is refused with the
1473    /// CLI's message; a value the simulation refuses (outside a bound) comes back with `poll`, as with any edit.
1474    pub fn set_value(&mut self, assignment: &str) {
1475        let before = self.config.clone();
1476        match sim_components::set_config_text(self.entry, &mut self.config, assignment) {
1477            Ok(()) => {
1478                self.record_edit(before, None);
1479                self.reconfigure();
1480            }
1481            Err(e) => self.say((e.key(), e.detail().into())),
1482        }
1483    }
1484
1485    /// `sim-app --set path=value`, each in turn, before the window opens: the machine restarts with them, and a
1486    /// saved file still has the comments and order of the one read. The first refusal is returned, with nothing
1487    /// applied.
1488    pub fn set_at_start(&mut self, assignments: &[String]) -> Result<(), Message> {
1489        if assignments.is_empty() {
1490            return Ok(());
1491        }
1492        let refused = |e: ConfigError| (e.key(), e.detail().to_string());
1493        let mut config = self.config.clone();
1494        for assignment in assignments {
1495            sim_components::set_config_text(self.entry, &mut config, assignment).map_err(refused)?;
1496        }
1497        let fresh = Self::with_config(self.entry, self.lang, config, self.config_text.clone()).map_err(refused)?;
1498        let (file, opened) = (self.inputs.config_file.clone(), self.file.clone());
1499        self.restart(fresh);
1500        (self.inputs.config_file, self.file) = (file, opened);
1501        Ok(())
1502    }
1503
1504    pub fn command(&mut self, command: Command) {
1505        self.session.send(Request::Command(command));
1506    }
1507
1508    /// Takes in what the simulation and a running tuning job have produced since the last frame.
1509    pub fn poll(&mut self) {
1510        for event in self.session.drain() {
1511            match event {
1512                Event::Sample(sample) => self.history.push(&sample),
1513                Event::Scene(scene) => self.scene = scene,
1514                Event::TrailStart(at) => self.trail = at.map(|at| vec![at]),
1515                // Not after `clear`: the result the trail belonged to is gone.
1516                Event::Trail(points) => {
1517                    if let Some(trail) = &mut self.trail {
1518                        extend_trail(trail, &points);
1519                    }
1520                }
1521                Event::Refused(key, detail) => self.say((key, detail)),
1522                Event::Limits(violations) => self.say_limits(violations),
1523                Event::Configured(answer) => {
1524                    let config = self.sent.pop_front();
1525                    match answer {
1526                        Ok(violations) => {
1527                            self.accepted = config.unwrap_or_else(|| self.accepted.clone());
1528                            self.say_limits(violations);
1529                        }
1530                        // The refused value goes, or it would stay in the config and have every later edit
1531                        // refused with it.
1532                        Err(message) => {
1533                            self.config = self.accepted.clone();
1534                            self.say(message);
1535                        }
1536                    }
1537                    // With every answer in, the config shown is the one the simulation runs.
1538                    if self.sent.is_empty() {
1539                        self.config = self.accepted.clone();
1540                    }
1541                }
1542            }
1543        }
1544        if self.session.ended() && !self.ended {
1545            self.ended = true;
1546            self.say(("ui-simulation-ended", String::new()));
1547        }
1548        if let Some(result) = self.report_job.as_ref().and_then(answer) {
1549            self.report_job = None;
1550            self.say(result.unwrap_or_else(|message| message));
1551        }
1552        let mut said = Vec::new();
1553        self.export_jobs.retain(|job| answer(job).map(|r| said.push(r.unwrap_or_else(|m| m))).is_none());
1554        let mut recorded = Vec::new();
1555        self.run_jobs.retain(|job| answer(job).map(|r| recorded.push(r)).is_none());
1556        for result in recorded {
1557            match result {
1558                Ok(run) => self.runs.add(run),
1559                Err(message) => said.push(message),
1560            }
1561        }
1562        said.into_iter().for_each(|message| self.say(message));
1563        if let Some(result) = self.tuning_job.as_ref().and_then(answer) {
1564            self.tuning_job = None;
1565            match result {
1566                Ok(tuning) => self.tuning = Some(tuning),
1567                Err(message) => self.say(message),
1568            }
1569        }
1570        for message in self.views.poll() {
1571            self.say(message);
1572        }
1573        if let Some(message) = self.loop_response.poll() {
1574            self.say(message);
1575        }
1576        if let Some(result) = self.insight.band_job.as_ref().and_then(answer) {
1577            self.insight.band_job = None;
1578            match result {
1579                Ok(runs) => self.insight.band_runs = Some(runs),
1580                Err(message) => self.say(message),
1581            }
1582        }
1583        // A job stays until it has answered.
1584        let mut reports = Vec::new();
1585        self.analysis_jobs.retain(|(kind, config, job)| {
1586            answer(job).map(|report| reports.push((*kind, config.clone(), report))).is_none()
1587        });
1588        for (kind, config, report) in reports {
1589            let report = match report {
1590                Ok(report) => report,
1591                Err(message) => {
1592                    self.say(message);
1593                    continue;
1594                }
1595            };
1596            let tripped = |load: &CycleLoad| load.tripped.then_some(("ui-analysis-tripped", String::new()));
1597            let note = match report {
1598                Report::Cycle(load, verdicts, bands, samples, curve, worst, run) => {
1599                    self.runs.add(run);
1600                    let banded = bands.iter().flatten().map(|b| &b.verdict);
1601                    let unstable = any_not_finite(verdicts.iter().chain(banded));
1602                    // Once per analysis: here, where the result comes in, not where it is drawn.
1603                    if unstable {
1604                        self.say(("verdict-not-finite", String::new()));
1605                    }
1606                    let note = tripped(&load);
1607                    (self.cycle_report, self.bands, self.band_samples, self.worst) =
1608                        (Some((load, verdicts, curve)), bands, samples, worst);
1609                    note
1610                }
1611                Report::Sensitivity(nominal, rows) => {
1612                    self.sensitivity = Some((nominal, rows));
1613                    None
1614                }
1615                Report::Optimised(found) => {
1616                    self.optimised = Some(found);
1617                    None
1618                }
1619                Report::Search(found, supply) => {
1620                    self.views.curves = found.curves;
1621                    self.candidates = Some((found.candidates, supply));
1622                    None
1623                }
1624                Report::Path(run, recorded) => {
1625                    self.runs.add(recorded);
1626                    // The machine runs the path as well, if it is still the machine the path was planned
1627                    // for. It refuses by itself where it has moved since, or is busy.
1628                    let stale = config != self.config;
1629                    if !stale {
1630                        self.command(Command::Trajectory(run.points.clone()));
1631                    }
1632                    let note = tripped(&run.load).or(stale.then_some(("ui-analysis-stale", String::new())));
1633                    self.path_run = Some(run);
1634                    note
1635                }
1636                Report::Trace(fit) => {
1637                    self.overlay = overlay_of(&fit);
1638                    let file = std::path::Path::new(&self.inputs.trace_file).file_name().map(|f| f.to_string_lossy());
1639                    let file = file.unwrap_or_default();
1640                    for (trace, key) in [(&fit.measured, "ui-run-measured"), (&fit.simulated, "ui-run-replayed")] {
1641                        let label = format!("{file} · {}", self.tr.tr(key));
1642                        self.runs.add(Run::from_trace(label, self.entry.id, &self.session.motors, trace));
1643                    }
1644                    self.trace_fit = Some(fit);
1645                    None
1646                }
1647                Report::Sweep(sweeps) => {
1648                    self.sweeps = Some(sweeps);
1649                    None
1650                }
1651                Report::SweepFit(motor, fit) => {
1652                    self.sweep_fit = Some((motor, fit));
1653                    None
1654                }
1655                Report::Compare(effect, comparison) => {
1656                    self.comparison = Some((effect, comparison));
1657                    None
1658                }
1659            };
1660            self.computed_for[kind as usize] = Some(config);
1661            if let Some(note) = note {
1662                self.say(note);
1663            }
1664        }
1665    }
1666
1667    /// Where the machine's setpoint stands, by the newest sample.
1668    fn standing(&self) -> Option<Vec<f64>> {
1669        let row = self.history.back()?;
1670        let signal = |axis: &sim_core::AxisInfo| -> Option<usize> {
1671            self.session.signals.iter().position(|s| s.id == format!("axis.{}.position_setpoint", axis.id))
1672        };
1673        self.session.axes.iter().map(|axis| Some(row[signal(axis)?])).collect()
1674    }
1675
1676    // ---------------------------------------------------------------------------------------
1677    // Scopes
1678
1679    /// Freezing keeps the traces in the window as they are for a closer look; the simulation runs on.
1680    pub fn set_frozen(&mut self, frozen: bool) {
1681        self.freezes += 1;
1682        self.frozen = frozen.then(|| self.history.tail(self.window_start(&self.history)));
1683    }
1684
1685    /// The first sample of `rows` in the scopes' window: the last `window_s` seconds.
1686    fn window_start(&self, rows: &History) -> usize {
1687        rows.first_at(rows.back().map_or(0.0, |last| last[0] - self.window_s))
1688    }
1689
1690    /// The rows the scopes show: the last `window_s` seconds of the live or the frozen history.
1691    pub fn visible_rows(&self) -> impl DoubleEndedIterator<Item = &[f64]> + ExactSizeIterator + Clone {
1692        let rows = self.frozen.as_ref().unwrap_or(&self.history);
1693        rows.iter().skip(self.window_start(rows))
1694    }
1695
1696    /// What the scopes show, as a key for caches: the frozen window or the live history's newest sample, and the
1697    /// window's length.
1698    fn view_key(&self) -> (u64, u64, u64) {
1699        let rows = self.frozen.as_ref().unwrap_or(&self.history);
1700        (self.freezes, rows.pushed(), self.window_s.to_bits())
1701    }
1702
1703    /// What a trace did in the scopes' window. All signals' are worked out in one pass over the window and kept while
1704    /// the scopes show the same, so a frame with many lines does not go over the window once per line.
1705    pub fn stats(&self, signal: usize) -> Option<Stats> {
1706        self.all_stats().get(signal).copied().flatten()
1707    }
1708
1709    fn all_stats(&self) -> Arc<Vec<Option<Stats>>> {
1710        let key = self.view_key();
1711        let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
1712        if let Some((kept, stats)) = &cache.stats
1713            && *kept == key
1714        {
1715            return stats.clone();
1716        }
1717        let width = self.session.signals.len();
1718        let (mut min, mut max, mut sum, mut n) =
1719            (vec![f64::INFINITY; width], vec![f64::NEG_INFINITY; width], vec![0.0; width], 0);
1720        for row in self.visible_rows() {
1721            for (i, &v) in row.iter().enumerate().take(width) {
1722                (min[i], max[i], sum[i]) = (min[i].min(v), max[i].max(v), sum[i] + v * v);
1723            }
1724            n += 1;
1725        }
1726        let stats: Arc<Vec<_>> = Arc::new(
1727            (0..width)
1728                .map(|i| (n > 0).then(|| Stats { min: min[i], max: max[i], rms: (sum[i] / n as f64).sqrt() }))
1729                .collect(),
1730        );
1731        cache.stats = Some((key, stats.clone()));
1732        stats
1733    }
1734
1735    /// Writes what the scopes show (every signal, the visible time window) as CSV, in the background: a minute of the
1736    /// six-axis arm is some hundred megabytes of text. The message comes with `poll`.
1737    pub fn export_traces(&mut self, path: &std::path::Path) {
1738        let header: Vec<String> = self.session.signals.iter().map(|s| format!("{}[{}]", s.id, s.unit)).collect();
1739        let rows: Vec<f64> = self.visible_rows().flatten().copied().collect();
1740        let (path, width) = (path.to_path_buf(), header.len().max(1));
1741        self.write_in_background(move || {
1742            use std::io::Write;
1743            let write = || -> std::io::Result<()> {
1744                let mut file = std::io::BufWriter::new(std::fs::File::create(&path)?);
1745                writeln!(file, "{}", header.join(","))?;
1746                for row in rows.chunks(width) {
1747                    let cells: Vec<String> = row.iter().map(|v| format!("{v:.9e}")).collect();
1748                    writeln!(file, "{}", cells.join(","))?;
1749                }
1750                file.flush()
1751            };
1752            match write() {
1753                Ok(()) => Ok(("ui-exported", path.display().to_string())),
1754                Err(e) => Err(("ui-export-failed", format!("{}: {e}", path.display()))),
1755            }
1756        });
1757    }
1758
1759    /// Runs `write` in a thread of its own; what it says comes with `poll`.
1760    fn write_in_background(&mut self, write: impl FnOnce() -> Result<Message, Message> + Send + 'static) {
1761        self.export_jobs.push(Job::spawn(move |_| write()));
1762    }
1763
1764    /// CSV files still being written.
1765    pub fn exporting(&self) -> bool {
1766        !self.export_jobs.is_empty()
1767    }
1768
1769    // ---------------------------------------------------------------------------------------
1770    // Runs
1771
1772    /// `run` with what the config's machine says about its motors and resonances (`Run::rated`).
1773    pub fn rated(&self, run: Run) -> Run {
1774        self.rated_with(run, &self.config)
1775    }
1776
1777    /// `rated` for a run made with another config of this machine (the compared ghost's).
1778    pub fn rated_with(&self, run: Run, config: &Config) -> Run {
1779        match Sim::new(self.entry, config) {
1780            Ok(mut sim) => run.rated(&mut sim),
1781            Err(_) => run,
1782        }
1783    }
1784
1785    /// Keeps what the scopes show (the live or frozen window) as a run.
1786    pub fn keep_live(&mut self) {
1787        let end = self.visible_rows().last().map_or(0.0, |row| row[0]);
1788        let label = format!(
1789            "{} · {} · {:.1} s",
1790            self.tr.tr(RunKind::Live.key()),
1791            config_label(self.entry, &self.config, &self.tr),
1792            end
1793        );
1794        let (signals, motors) = (self.session.signals.clone(), &self.session.motors);
1795        let run = Run::from_rows(label, RunKind::Live, self.entry.id, signals, motors, self.visible_rows());
1796        self.runs.add(self.rated(run));
1797    }
1798
1799    /// Records the configured cycle of another config as a run, in the background: the config shown, or the config or
1800    /// machine file `file` (of any machine), with each of `assignments` applied as `sim-cli --set` does (separated by
1801    /// `;` or new lines), e.g. another motor through `parts.motor = "1FK2208-4AF"` or another gain. A file or an
1802    /// assignment that is refused is said, and nothing runs.
1803    pub fn record_run(&mut self, assignments: &str, file: &str) {
1804        let base =
1805            if file.trim().is_empty() { Ok((self.entry, self.config.clone())) } else { self.config_of(file.trim()) };
1806        let made = base.and_then(|(entry, mut config)| {
1807            for assignment in assignments.split([';', '\n']).map(str::trim).filter(|a| !a.is_empty()) {
1808                sim_components::set_config_text(entry, &mut config, assignment)
1809                    .map_err(|e| (e.key(), e.detail().to_string()))?;
1810            }
1811            Ok((entry, config))
1812        });
1813        let (entry, config) = match made {
1814            Ok(made) => made,
1815            Err(message) => return self.say(message),
1816        };
1817        let tr = self.tr.clone();
1818        self.run_jobs.push(Job::spawn(move |_| cycle_run(entry, &config, &tr)));
1819    }
1820
1821    /// Runs still being recorded.
1822    pub fn recording_runs(&self) -> bool {
1823        !self.run_jobs.is_empty()
1824    }
1825
1826    /// The machine and config of a config or machine file, as `open_config` reads it, without opening it.
1827    fn config_of(&self, path: &str) -> Result<(&'static MachineEntry, Config), Message> {
1828        let text =
1829            std::fs::read(path).map(|b| decode(&b)).map_err(|e| ("ui-file-unreadable", format!("{path}: {e}")))?;
1830        let machine_file = path.to_ascii_lowercase().ends_with(".json")
1831            || Config::parse(&text).ok().is_some_and(|c| c.get("machine").is_ok_and(|m| m.is_table()));
1832        if machine_file {
1833            let entry = sim_machines::load_file(std::path::Path::new(path))
1834                .map_err(|e| (e.error.key(), format!("{path}: {}", e.error.detail())))?;
1835            return Ok((entry, entry.config()));
1836        }
1837        let refused = |e: ConfigError| (e.key(), format!("{path}: {}", e.detail()));
1838        let entry = std::iter::once(self.entry)
1839            .chain(MACHINES.iter().copied())
1840            .find(|m| sim_components::load_config(m, &text).is_ok())
1841            .ok_or_else(|| sim_components::load_config(self.entry, &text).err().map(refused).unwrap_or_default())?;
1842        Ok((entry, sim_components::load_config(entry, &text).map_err(refused)?))
1843    }
1844
1845    /// The shown runs per quantity of `Quantity::ALL` that one of them has (see `RunPlot`), in the chosen units.
1846    pub fn run_plots(&self) -> Vec<RunPlot> {
1847        let reference = self.runs.reference();
1848        let mut plots = Vec::new();
1849        for quantity in Quantity::ALL {
1850            let (factor, unit) = self.units.scale(quantity.unit());
1851            let scaled = |values: &[f64], time: &[f64]| plot_line(time.len(), |n| [time[n], values[n] * factor]);
1852            let mut lines = Vec::new();
1853            let mut differences = Vec::new();
1854            for (i, run) in self.runs.iter().enumerate().filter(|(i, _)| self.runs.shown(*i)) {
1855                for channel in run.channels().into_iter().filter(|c| c.quantity == quantity) {
1856                    let Some(values) = run.channel(channel) else { continue };
1857                    let name = self.run_line_name(run, channel);
1858                    lines.push(RunLine {
1859                        run: i,
1860                        motor: channel.motor,
1861                        name: name.clone(),
1862                        points: scaled(&values, run.time()),
1863                    });
1864                    if let Some(aligned) =
1865                        self.runs.against_reference(i, channel).filter(|_| self.runs.shown(reference))
1866                    {
1867                        differences.push(RunLine {
1868                            run: i,
1869                            motor: channel.motor,
1870                            name,
1871                            points: scaled(&aligned.difference, &aligned.time),
1872                        });
1873                    }
1874                }
1875            }
1876            if !lines.is_empty() {
1877                let title = format!("{} [{unit}]", self.tr.tr(quantity.key()));
1878                plots.push(RunPlot { quantity, title, lines, differences });
1879            }
1880        }
1881        plots
1882    }
1883
1884    /// "Motor A · run label" for a line of a run, or the run's label alone for the tool's error.
1885    fn run_line_name(&self, run: &Run, channel: Channel) -> String {
1886        match channel.quantity {
1887            Quantity::ToolError if run.tool_error_is_motor_side() => {
1888                format!("{} · {}", run.label, self.tr.tr("ui-run-motor-side"))
1889            }
1890            Quantity::ToolError => run.label.clone(),
1891            _ => {
1892                let id = format!("motor.{}.{}", run.motors[channel.motor], channel.quantity.signal().unwrap_or(""));
1893                let owner = run.signals.iter().find(|s| s.id == id).map_or(String::new(), |s| s.owner_key.clone());
1894                format!("{} · {}", self.tr.tr(&owner), run.label)
1895            }
1896        }
1897    }
1898
1899    /// The key figures of the kept runs side by side (`runs::Figures`): one column per run, the reference marked, then
1900    /// one column per other run with its value less the reference's ("Δ label"; for the verdicts, the failed checks
1901    /// less the reference's), in the chosen units. `None` with no run kept.
1902    pub fn runs_table(&self) -> Option<Table> {
1903        if self.runs.is_empty() {
1904            return None;
1905        }
1906        let tr = |key: &str| self.tr.tr(key).to_string();
1907        let figures: Vec<_> = self.runs.iter().map(Run::figures).collect();
1908        let mut header = vec![tr("ui-analysis-figure")];
1909        for (i, run) in self.runs.iter().enumerate() {
1910            let mark =
1911                if i == self.runs.reference() { format!(" ({})", tr("ui-run-reference")) } else { String::new() };
1912            header.push(format!("{}{mark}", run.label));
1913        }
1914        let reference = self.runs.reference();
1915        let others: Vec<usize> = (0..self.runs.len()).filter(|i| *i != reference).collect();
1916        header.extend(others.iter().map(|&i| format!("Δ {}", self.runs.get(i).map_or("", |r| r.label.as_str()))));
1917        let mut table = vec![header];
1918        let cell = |value: Option<f64>| value.map_or(String::new(), short);
1919        let signed = |d: f64| if d > 0.0 { format!("+{}", short(d)) } else { short(d) };
1920        // A row of numbers: each run's value, then each other run's less the reference's.
1921        let row = |table: &mut Table, label: String, values: Vec<Option<f64>>| {
1922            let differences = others.iter().map(|&i| match (values[i], values[reference]) {
1923                (Some(value), Some(of_reference)) => signed(value - of_reference),
1924                _ => String::new(),
1925            });
1926            table.push([vec![label], values.iter().map(|v| cell(*v)).collect(), differences.collect()].concat());
1927        };
1928        row(&mut table, tr("ui-analysis-duration"), figures.iter().map(|f| Some(f.duration)).collect());
1929        let failed = |i: usize| figures[i].verdicts.map(|(_, failed)| failed as f64);
1930        let verdicts =
1931            figures.iter().map(|f| f.verdicts.map_or(String::new(), |(ok, failed)| format!("{ok} / {failed}")));
1932        let failed_more =
1933            others.iter().map(|&i| failed(i).zip(failed(reference)).map_or(String::new(), |(a, b)| signed(a - b)));
1934        table.push([vec![tr("ui-run-verdicts")], verdicts.collect(), failed_more.collect()].concat());
1935        let motors = figures.iter().map(|f| f.motors.len()).max().unwrap_or(0);
1936        let (speed, speed_unit) = self.units.scale("rad/s");
1937        for k in 0..motors {
1938            let name = self
1939                .runs
1940                .iter()
1941                .find_map(|run| {
1942                    let id = format!("motor.{}.torque", run.motors.get(k)?);
1943                    run.signals.iter().find(|s| s.id == id).map(|s| tr(&s.owner_key))
1944                })
1945                .unwrap_or_else(|| format!("{}", k + 1));
1946            // A linear motor's numbers are in N, m/s and m.
1947            let linear = self.session.motor_linear.get(k).copied().unwrap_or(false);
1948            let (speed, speed_unit) = if linear { (1.0, "m/s".to_string()) } else { (speed, speed_unit.clone()) };
1949            let length = if linear { "m" } else { "rad" };
1950            let rows: [(&str, String, fn(&crate::runs::MotorFigures) -> Option<f64>, f64); 8] = [
1951                ("ui-analysis-peak-torque", "N m".into(), |m| Some(m.peak_torque), 1.0),
1952                ("ui-analysis-rms-torque", "N m".into(), |m| Some(m.rms_torque), 1.0),
1953                ("ui-run-peak-speed", speed_unit, |m| Some(m.peak_speed), speed),
1954                ("ui-run-peak-error", length.into(), |m| Some(m.peak_error), 1.0),
1955                ("ui-run-rms-error", length.into(), |m| Some(m.rms_error), 1.0),
1956                ("ui-run-thermal-use", "%".into(), |m| m.utilisation.map(|u| u.0), 100.0),
1957                ("ui-run-peak-use", "%".into(), |m| m.utilisation.map(|u| u.1), 100.0),
1958                ("ui-run-energy", "J".into(), |m| m.energy, 1.0),
1959            ];
1960            for (key, unit, value, factor) in rows {
1961                let cells = figures.iter().map(|f| f.motors.get(k).and_then(value).map(|v| v * factor));
1962                // The unit, unless the label has it already (the torques' are the analysis tables').
1963                let label = tr(key);
1964                let label = if label.contains('[') { label } else { format!("{label} [{unit}]") };
1965                let label = if linear { label.replace("[N m]", "[N]") } else { label };
1966                row(&mut table, format!("{name} · {label}"), cells.collect());
1967            }
1968        }
1969        let (length, length_unit) = self.units.scale("m");
1970        for (key, value) in [
1971            ("ui-run-tool-error-peak", figures.iter().map(|f| f.tool_error_peak).collect::<Vec<_>>()),
1972            ("ui-run-tool-error-rms", figures.iter().map(|f| f.tool_error_rms).collect()),
1973        ] {
1974            // A run without setpoint signals has only the drives' following error: its values get a row of their own.
1975            let side: Vec<bool> = self.runs.iter().map(Run::tool_error_is_motor_side).collect();
1976            for motor_side in [false, true] {
1977                let values: Vec<Option<f64>> =
1978                    value.iter().zip(&side).map(|(v, s)| v.filter(|_| *s == motor_side).map(|v| v * length)).collect();
1979                if values.iter().any(Option::is_some) || (!motor_side && !side.contains(&true)) {
1980                    let name = if motor_side { format!("{} · {}", tr(key), tr("ui-run-motor-side")) } else { tr(key) };
1981                    row(&mut table, format!("{name} [{length_unit}]"), values);
1982                }
1983            }
1984        }
1985        Some(table)
1986    }
1987
1988    pub fn report_running(&self) -> bool {
1989        self.report_job.is_some()
1990    }
1991
1992    /// Writes the sizing report of the config as it is now (`sim_components::report`) to `path`, as PDF for a name
1993    /// ending in .pdf and as HTML otherwise, with the error bands where the analysis panel asks for them. In the
1994    /// background: the cycle and the bands take a while.
1995    pub fn export_report(&mut self, path: &str) {
1996        let (entry, config, text, lang, tr) =
1997            (self.entry, self.config.clone(), self.config_text.clone(), self.lang, self.tr.clone());
1998        let source = if self.inputs.config_file.is_empty() {
1999            tr.tr("report-default-config").to_string()
2000        } else {
2001            self.inputs.config_file.clone()
2002        };
2003        let (bands, path) = (self.inputs.bands, path.to_string());
2004        self.report_job = Some(Job::spawn(move |_| {
2005            let write = || -> Result<Message, Message> {
2006                let report = sim_components::report::make(entry, &text, &source, &config, &config, bands, &tr)
2007                    .map_err(|e| (e.key(), e.detail().to_string()))?;
2008                let bytes =
2009                    if path.to_lowercase().ends_with(".pdf") { report.pdf() } else { report.html(lang).into_bytes() };
2010                std::fs::write(&path, bytes).map_err(|e| ("ui-report-failed", format!("{path}: {e}")))?;
2011                Ok(("ui-report-written", path.clone()))
2012            };
2013            write()
2014        }));
2015    }
2016
2017    // ---------------------------------------------------------------------------------------
2018    // Tuning
2019
2020    pub fn tuning_running(&self) -> bool {
2021        self.tuning_job.is_some()
2022    }
2023
2024    /// Measures step and frequency response of one axis with the config as it is now, in the
2025    /// background on a simulation of its own. The running machine is not disturbed.
2026    pub fn run_tuning(&mut self, axis: usize) {
2027        let (entry, config) = (self.entry, self.config.clone());
2028        self.tuning_axis = axis;
2029        self.tuning_job = Some(Job::spawn(move |_| {
2030            let measure = || -> Result<Tuning, sim_core::ConfigError> {
2031                let step = step_response(entry, &config, axis, 0.001, 0.5)?;
2032                let response = closed_loop_response(entry, &config, axis, &log_spaced(1.0, 200.0, 40), 0.0005)?;
2033                let sim = Sim::new(entry, &config)?;
2034                // At the configured start pose, where the tool stands: the plan at rest is the motors' pose by the
2035                // rigid kinematics, off it by the belt's stretch (46 um in Z on the shipped gantry's belts).
2036                let modes = modes_along(sim.machine.as_ref(), &config.f64s("start.pose")?, axis, MODE_POINTS);
2037                Ok(Tuning { axis, step, bandwidth: bandwidth(&response), response, modes })
2038            };
2039            measure().map_err(|e| (e.key(), e.detail().to_string()))
2040        }));
2041    }
2042
2043    // ---------------------------------------------------------------------------------------
2044    // Analysis
2045
2046    pub fn analysis_running(&self) -> bool {
2047        !self.analysis_jobs.is_empty() || self.views.any_running() || self.insight.band_job.is_some()
2048    }
2049
2050    pub fn running(&self, kind: Analysis) -> bool {
2051        self.analysis_jobs.iter().any(|job| job.0 == kind)
2052    }
2053
2054    /// Any background job is still under way: its answer comes with `poll`, which the window must go on calling, so
2055    /// it does not idle meanwhile (`update_mode` in main.rs).
2056    pub fn working(&self) -> bool {
2057        self.exporting()
2058            || self.recording_runs()
2059            || self.report_running()
2060            || self.tuning_running()
2061            || self.analysis_running()
2062            || self.loop_response.running()
2063    }
2064
2065    /// The progress (runs done and planned so far, the plan grows as the job goes) and the cancel switch of a
2066    /// background job under way; `None` where there is none.
2067    pub fn job_progress(&self, job: JobRef) -> Option<Arc<Progress>> {
2068        match job {
2069            JobRef::Analysis(kind) => self.analysis_jobs.iter().find(|j| j.0 == kind).map(|j| j.2.progress.clone()),
2070            JobRef::View(kind) => self.views.progress(kind),
2071            JobRef::Tuning => self.tuning_job.as_ref().map(|j| j.progress.clone()),
2072            JobRef::Report => self.report_job.as_ref().map(|j| j.progress.clone()),
2073            JobRef::Bands => self.insight.band_job.as_ref().map(|j| j.progress.clone()),
2074        }
2075    }
2076
2077    /// Runs done and planned of a job under way. Planned 0: it has not counted anything yet.
2078    pub fn job_counts(&self, job: JobRef) -> Option<(usize, usize)> {
2079        self.job_progress(job).map(|p| (p.done.load(Relaxed), p.total.load(Relaxed)))
2080    }
2081
2082    /// Stops a background job: it stops starting runs and `poll` takes it as ended, with a message that it was
2083    /// cancelled; what was computed before stays as it was. A run already started is not interrupted.
2084    pub fn cancel_job(&self, job: JobRef) {
2085        if let Some(progress) = self.job_progress(job) {
2086            progress.cancel.store(true, Relaxed);
2087        }
2088    }
2089
2090    pub fn has_result(&self, kind: Analysis) -> bool {
2091        self.computed_for[kind as usize].is_some()
2092    }
2093
2094    /// The result of this kind was computed for a config that has been changed since. A motor search does
2095    /// not depend on the parts the config names, so naming one of its motors does not outdate it.
2096    pub fn outdated(&self, kind: Analysis) -> bool {
2097        self.computed_for[kind as usize].as_ref().is_some_and(|config| match kind {
2098            Analysis::Search => without_parts(config) != without_parts(&self.config),
2099            _ => *config != self.config,
2100        })
2101    }
2102
2103    /// Starts one computation of the analysis panel with the config as it is now, in the background on
2104    /// simulations of its own, like the tuning measurement. The running machine is not disturbed.
2105    ///
2106    /// The search, the path and the trace take what `inputs` holds at this moment. A path is planned from
2107    /// where the machine stands, and when its analysis is back the machine runs it too (see `poll`).
2108    pub fn run_analysis(&mut self, kind: Analysis) {
2109        let (entry, config, inputs) = (self.entry, self.config.clone(), self.inputs.clone());
2110        if kind == Analysis::Search && crate::search_views::supplies(&inputs.search.vendor, &inputs.supply).is_empty() {
2111            return self.say(("ui-search-bad-supply", inputs.supply));
2112        }
2113        let (standing, motors, tr) = (self.standing(), self.session.motors.clone(), self.tr.clone());
2114        let linear = self.session.motor_linear.first().copied().unwrap_or(false);
2115        let started = self.config.clone();
2116        let job = Job::spawn(move |_| {
2117            // The failing checks of `error-cycle-fails-already` come as ids: said by their labels.
2118            let refused = |e: ConfigError| match e.key() {
2119                key @ "error-cycle-fails-already" => {
2120                    (key, sim_components::report::check_labels(e.detail(), linear, &tr))
2121                }
2122                key => (key, e.detail().to_string()),
2123            };
2124            let command = |e: CommandError| (e.key, String::new());
2125            // As the command line reads them (`import::decode`): a file saved by Excel starts with a byte order mark,
2126            // or is UTF-16, which read as text gave "error-trace-column: time".
2127            let read = |file: &str| {
2128                std::fs::read(file)
2129                    .map(|bytes| decode(&bytes))
2130                    .map_err(|e| ("ui-file-unreadable", format!("{file}: {e}")))
2131            };
2132            let label = config_label(entry, &config, &tr);
2133            let run = || -> Result<Report, Message> {
2134                Ok(match kind {
2135                    Analysis::Cycle => {
2136                        let mut sim = Sim::new(entry, &config).map_err(refused)?;
2137                        // The cycle's samples for the run store, beside the analysis: its pass is the one analysed.
2138                        let (load, rows) = std::thread::scope(|scope| {
2139                            let rows = scope.spawn(|| record_cycle(entry, &config));
2140                            (analyse_cycle(&mut sim), rows.join().unwrap_or_else(|_| Ok(Vec::new())))
2141                        });
2142                        let (load, rows) = (load.map_err(command)?, rows.map_err(refused)?);
2143                        let verdicts = verdicts(&config, &load).map_err(refused)?;
2144                        // Two more cycles per bounded value, or one per sample (always with the same seed, so
2145                        // that asking again gives the same bands).
2146                        let banded = |bounds: Vec<(String, f64, f64)>| match inputs.samples {
2147                            0 => verdict_bands(entry, &config, &bounds),
2148                            samples => verdict_bands_sampled(entry, &config, &bounds, samples, 1),
2149                        };
2150                        // The search for the worst corners, beside the bands. Its first runs are those of the bands at
2151                        // their bounds, which it gives back, so that they are not run twice.
2152                        let (bands, worst) = if inputs.bands && inputs.worst {
2153                            let bounded = bounds(&config).map_err(refused)?;
2154                            let (worst, at_bounds, _) =
2155                                verdict_worst_and_bands(entry, &config, &bounded).map_err(refused)?;
2156                            let bands = if inputs.samples == 0 {
2157                                at_bounds
2158                            } else {
2159                                banded(bounded.clone()).map_err(refused)?
2160                            };
2161                            (Some(bands), Some((worst, bounded.into_iter().map(|bound| bound.0).collect())))
2162                        } else {
2163                            (
2164                                if inputs.bands {
2165                                    Some(banded(bounds(&config).map_err(refused)?).map_err(refused)?)
2166                                } else {
2167                                    None
2168                                },
2169                                None,
2170                            )
2171                        };
2172                        let run = judged_run(RunKind::Cycle, &label, &mut sim, entry, &rows, &verdicts, &tr);
2173                        let run = Run { off_path: load.path_error_series.clone(), ..run };
2174                        Report::Cycle(load, verdicts, bands, inputs.samples, run.torque_speed(), worst, run)
2175                    }
2176                    Analysis::Sensitivity => {
2177                        // The values the config calls uncertain: those it gives bounds. Two cycles each.
2178                        let paths: Vec<String> =
2179                            bounds(&config).map_err(refused)?.into_iter().map(|bound| bound.0).collect();
2180                        let (nominal, mut rows) = sensitivity(entry, &config, &paths, 0.2).map_err(refused)?;
2181                        rows.sort_by(|a, b| b.strength(&nominal).total_cmp(&a.strength(&nominal)));
2182                        Report::Sensitivity(nominal, rows)
2183                    }
2184                    // With the error bands ticked the result has to pass in them too; the front comes with six cycles more.
2185                    Analysis::Optimise => Report::Optimised(
2186                        optimise_cycle_with(
2187                            entry,
2188                            &config,
2189                            &OptimiseOptions {
2190                                max_runs: 40,
2191                                robust: inputs.bands,
2192                                pareto: true,
2193                                worst: inputs.bands && inputs.worst,
2194                            },
2195                        )
2196                        .map_err(refused)?,
2197                    ),
2198                    Analysis::Search => {
2199                        Report::Search(crate::search_views::run_search(entry, &config, &inputs)?, inputs.supply.clone())
2200                    }
2201                    Analysis::Path => {
2202                        let unreadable = |line: String| ("ui-file-line", format!("{}: {line}", inputs.path_file));
2203                        let text = read(&inputs.path_file)?;
2204                        let (mut sim, from_here) = match &standing {
2205                            Some(pose) => start_at_setpoint(entry, &config, pose).map_err(refused)?,
2206                            None => (Sim::new(entry, &config).map_err(refused)?, config.clone()),
2207                        };
2208                        let (points, deviations) = if inputs.path_timed {
2209                            (path::parse_trajectory(&text).map_err(unreadable)?, vec![0.0])
2210                        } else {
2211                            // A path file, or a G-code or robot program (`program::read`, by the file's extension),
2212                            // a robot's reorientation at the config's `program.orientation_speed_rad_s`.
2213                            let speed = sim_components::program::orientation_speed_of(&config).map_err(refused)?;
2214                            let runs = sim_components::program::read_with(
2215                                &inputs.path_file,
2216                                &text,
2217                                sim.machine.axes(),
2218                                sim.control.planned_pos(),
2219                                speed,
2220                            )
2221                            .map_err(|e| ("ui-file-line", format!("{}:{}: {}", inputs.path_file, e.line, e.detail)))?;
2222                            match sim_components::program::as_path(&runs) {
2223                                Some(pieces) => (
2224                                    sim.plan_path(pieces, inputs.time_optimal).map_err(command)?,
2225                                    vec![sim.path_deviation(pieces, inputs.time_optimal).map_err(command)?],
2226                                ),
2227                                // A program: the deviation of each run from its pieces, each from where the one
2228                                // before ends.
2229                                None => (
2230                                    sim.plan_program(&runs, inputs.time_optimal).map_err(command)?,
2231                                    sim.program_deviations(&runs, inputs.time_optimal).map_err(command)?,
2232                                ),
2233                            }
2234                        };
2235                        let deviation = deviations.iter().copied().fold(0.0, f64::max);
2236                        let scene_line = points.iter().filter_map(|(_, pose)| sim.machine.scene_point(pose)).collect();
2237                        // The path's samples for the run store, on a simulation of its own that starts as this one.
2238                        let mut again = Sim::new(entry, &from_here).map_err(refused)?;
2239                        let rows = record_path(&mut again, points.clone()).map_err(command)?;
2240                        let load = analyse_trajectory(&mut sim, points.clone()).map_err(command)?;
2241                        let verdicts = verdicts(&config, &load).map_err(refused)?;
2242                        let file = std::path::Path::new(&inputs.path_file).file_name().map(|f| f.to_string_lossy());
2243                        let label = format!("{} · {label}", file.unwrap_or_default());
2244                        let recorded = judged_run(RunKind::Path, &label, &mut again, entry, &rows, &verdicts, &tr);
2245                        let recorded = Run { off_path: load.path_error_series.clone(), ..recorded };
2246                        Report::Path(
2247                            PathRun {
2248                                points,
2249                                scene_line,
2250                                load,
2251                                verdicts,
2252                                deviation,
2253                                deviations,
2254                                curves: recorded.torque_speed(),
2255                                run: recorded.clone(),
2256                            },
2257                            recorded,
2258                        )
2259                    }
2260                    Analysis::Trace => {
2261                        let unfit = |e: TraceError| (e.key, e.detail);
2262                        // A vendor's export through its mapping, whose motors are the machine's in its order.
2263                        let (measured, setpoints) = if inputs.trace_map.is_empty() {
2264                            let measured = Trace::parse(&read(&inputs.trace_file)?, &motors).map_err(unfit)?;
2265                            let none = vec![None; measured.motors.len()];
2266                            (measured, none)
2267                        } else {
2268                            let imported = import(
2269                                &read(&inputs.trace_file)?,
2270                                &Mapping::parse(&read(&inputs.trace_map)?).map_err(unfit)?,
2271                            )
2272                            .map_err(unfit)?;
2273                            if imported.trace.motors.len() != motors.len() {
2274                                return Err((
2275                                    "error-import-map",
2276                                    format!("{} [[motor]] for {} motors", imported.trace.motors.len(), motors.len()),
2277                                ));
2278                            }
2279                            (imported.trace, imported.torque_setpoints)
2280                        };
2281                        let simulated = replay(entry, &config, &measured).map_err(unfit)?;
2282                        let per_axis = per_axis_fit((entry.build)(&config).map_err(refused)?.as_ref());
2283                        let fits =
2284                            if per_axis { fit_rigid(entry, &config, &measured).map_err(unfit)? } else { Vec::new() };
2285                        let joints =
2286                            if per_axis { None } else { Some(fit_joints(entry, &config, &measured).map_err(unfit)?) };
2287                        let stiffness = inputs
2288                            .trace_stiffness
2289                            .then(|| fit_move_stiffness(entry, &config, &measured, BELT_STIFFNESS_KEY));
2290                        let identified = measured
2291                            .motors
2292                            .iter()
2293                            .zip(&setpoints)
2294                            .map(|(m, s)| Identified::of(&measured.time, m, s.as_deref()))
2295                            .collect();
2296                        Report::Trace(TraceFit {
2297                            differences: differences(&measured, &simulated),
2298                            fits,
2299                            joints,
2300                            stiffness,
2301                            identified,
2302                            measured,
2303                            simulated,
2304                        })
2305                    }
2306                    Analysis::Sweep => {
2307                        let frequencies = log_spaced(inputs.sweep_from, inputs.sweep_to, inputs.sweep_count);
2308                        let sweep =
2309                            |motor: usize| frequency_sweep(entry, &config, motor, &frequencies, inputs.sweep_amplitude);
2310                        Report::Sweep((0..motors.len()).map(sweep).collect::<Result<_, _>>().map_err(refused)?)
2311                    }
2312                    Analysis::SweepFit => {
2313                        let measured = parse_sweep(&read(&inputs.sweep_file)?).map_err(|e| (e.key, e.detail))?;
2314                        let fit = fit_sweep(entry, &config, inputs.sweep_motor, &measured, inputs.sweep_amplitude)
2315                            .map_err(refused)?;
2316                        Report::SweepFit(inputs.sweep_motor, fit.ok_or(("fit-no-resonance", String::new()))?)
2317                    }
2318                    Analysis::Compare => Report::Compare(
2319                        inputs.compare_effect.clone(),
2320                        compare_effect(entry, &config, &inputs.compare_effect).map_err(refused)?,
2321                    ),
2322                })
2323            };
2324            run()
2325        });
2326        self.analysis_jobs.push((kind, started, job));
2327    }
2328
2329    /// Forgets the result of one kind of analysis.
2330    pub fn clear(&mut self, kind: Analysis) {
2331        match kind {
2332            Analysis::Cycle => (self.cycle_report, self.bands, self.worst) = (None, None, None),
2333            Analysis::Sensitivity => self.sensitivity = None,
2334            Analysis::Optimise => self.optimised = None,
2335            Analysis::Search => self.candidates = None,
2336            Analysis::Path => (self.path_run, self.trail) = (None, None),
2337            Analysis::Trace => (self.trace_fit, self.overlay) = (None, Vec::new()),
2338            Analysis::Sweep => self.sweeps = None,
2339            Analysis::SweepFit => self.sweep_fit = None,
2340            Analysis::Compare => self.comparison = None,
2341        }
2342        self.computed_for[kind as usize] = None;
2343    }
2344
2345    pub fn clear_analysis(&mut self) {
2346        [Analysis::Cycle, Analysis::Sensitivity, Analysis::Optimise].into_iter().for_each(|kind| self.clear(kind));
2347    }
2348
2349    /// Names a motor of the search (and its gearbox, where it was searched with one, its drive and its axis, where it
2350    /// was tried on one) in `[parts]` of the config and applies it to the running simulation: the row of `search_table`
2351    /// after the header. A row of an axis ruled out has no motor and names nothing. The
2352    /// candidate passed or failed on the config that was searched, so over a config changed since in
2353    /// anything but its part names nothing is applied.
2354    pub fn use_candidate(&mut self, row: usize) {
2355        let (Some((found, supply)), Some(searched)) = (&self.candidates, &self.computed_for[Analysis::Search as usize])
2356        else {
2357            return;
2358        };
2359        let Some(candidate) = found.get(row).filter(|c| !c.article.is_empty()) else { return };
2360        if self.outdated(Analysis::Search) {
2361            return self.say(("ui-analysis-stale", String::new()));
2362        }
2363        // A candidate without a gearbox of its own ran with the one the searched config names.
2364        // Where it has none of its own (gearbox, drive, axis), it ran with the one the searched config names.
2365        let own = |key: &str| {
2366            searched.get(&format!("parts.{key}")).ok().and_then(|name| name.as_str()).unwrap_or("").to_string()
2367        };
2368        let or_own = |name: &str, key: &str| if name.is_empty() { own(key) } else { name.to_string() };
2369        let names = [
2370            candidate.article.to_string(),
2371            // Searched at several supplies (a maker's), each candidate at its own.
2372            if candidate.supply.is_empty() { supply.clone() } else { candidate.supply.to_string() },
2373            or_own(&candidate.gearbox, "gearbox"),
2374            or_own(candidate.drive, "drive"),
2375            own("belt"),
2376            or_own(&candidate.axis, "axis"),
2377        ];
2378        self.name_parts(names.each_ref().map(String::as_str));
2379    }
2380
2381    /// Names motor, supply, gearbox, drive, belt and axis in `[parts]` of the config and applies it to the running
2382    /// simulation. Names the catalogue does not have are refused here, before the config changes.
2383    fn name_parts(&mut self, names: [&str; 6]) {
2384        let mut config = self.config.clone();
2385        let named =
2386            PARTS.iter().zip(names).try_for_each(|(key, name)| config.set_text(&format!("parts.{key} = {name:?}")));
2387        match named.and_then(|()| sim_components::catalog::resolve(self.entry, &config)) {
2388            Ok(_) => {
2389                let before = std::mem::replace(&mut self.config, config);
2390                self.record_edit(before, None);
2391                self.reconfigure();
2392                self.show_parts();
2393            }
2394            Err(e) => self.say((e.key(), e.detail().into())),
2395        }
2396    }
2397
2398    /// Puts the settings the optimiser found into the config and applies it to the running simulation.
2399    /// They are absolute values, found for the config the optimiser started with: over a config edited
2400    /// since they would undo an edit, or fail a check they were found to pass. Then nothing is applied; the
2401    /// result stays, for when the edit is taken back.
2402    pub fn apply_optimised(&mut self) {
2403        if self.optimised.is_some() && self.outdated(Analysis::Optimise) {
2404            return self.say(("ui-analysis-stale", String::new()));
2405        }
2406        let Some(found) = self.optimised.take() else { return };
2407        let before = self.config.clone();
2408        for (path, _, after) in &found.changes {
2409            if let Err(e) = self.config.set_text(&format!("{path} = {after}")) {
2410                self.say((e.key(), e.detail().into()));
2411            }
2412        }
2413        self.record_edit(before, None);
2414        self.reconfigure();
2415    }
2416
2417    fn header(&self, keys: &[&str]) -> Vec<String> {
2418        keys.iter().map(|key| self.tr.tr(key).to_string()).collect()
2419    }
2420
2421    /// "X axis · Highest velocity [m/s]" for `axis.x.max_velocity_m_s`, as the parameter panel names it.
2422    fn param_label(&self, path: &str) -> String {
2423        match path.rsplit_once('.') {
2424            Some(("effects", leaf)) => self.tr.tr(&format!("effect-{leaf}")).to_string(),
2425            Some((table, leaf)) => format!(
2426                "{} · {}",
2427                self.tr.tr(&format!("group-{}", table.replace('.', "-"))),
2428                self.tr.tr(&format!("param-{leaf}"))
2429            ),
2430            None => path.to_string(),
2431        }
2432    }
2433
2434    /// "Figure" and the name of every motor: the header of a table with one row per figure.
2435    fn per_motor(&self) -> Vec<String> {
2436        [
2437            self.header(&["ui-analysis-figure"]),
2438            self.session.motors.iter().map(|m| self.tr.tr(m.key).to_string()).collect(),
2439        ]
2440        .concat()
2441    }
2442
2443    fn result(&self, ok: bool) -> String {
2444        self.tr.tr(if ok { "ui-analysis-ok" } else { "ui-analysis-fail" }).to_string()
2445    }
2446
2447    /// A run as tables, each narrow enough for the panel: the figures of the machine, one per row; the load
2448    /// on the motors, one row per figure and one column per motor; one row per check with its value, its
2449    /// limit and the result; and where there are error bands, a fourth with the lowest and the highest
2450    /// value of every check, its worst-case result (also of a check that only a bound brings up) and the
2451    /// share of the runs it passed, in percent. A figure
2452    /// the machine does not report is left out. `deviation` is that of a path, which has no cycle time and no dwell.
2453    fn load_tables(
2454        &self,
2455        kind: Analysis,
2456        load: &CycleLoad,
2457        verdicts: &[Verdict],
2458        bands: Option<&[Band]>,
2459        deviation: Option<f64>,
2460    ) -> Vec<Table> {
2461        let tr = |key: &str| self.tr.tr(key).to_string();
2462        let path = deviation.is_some();
2463        // The lives read the ratings of the parts the config names, as the verdicts do.
2464        let resolved = sim_components::catalog::resolve(
2465            self.entry,
2466            self.computed_for[kind as usize].as_ref().unwrap_or(&self.config),
2467        )
2468        .ok();
2469        let life = resolved.as_ref().and_then(|cfg| guide_life_km(cfg, load));
2470        // In the order of `CYCLE_KEYS`; lengths in mm, angles in mrad (where the tool has axes in rad: else all 0).
2471        let turns = load.path_angle_error_peak > 0.0 || load.dwell_angle_error_peak > 0.0;
2472        let figures = [
2473            (!path).then_some(load.duration),
2474            path.then_some(load.duration),
2475            deviation.map(|d| d * 1e3),
2476            Some(load.path_error_peak * 1e3),
2477            path.then_some(load.tracking_error_peak * 1e3),
2478            (!path).then_some(load.dwell_error_peak * 1e3),
2479            turns.then_some(load.path_angle_error_peak * 1e3),
2480            (turns && path).then_some(load.tracking_angle_error_peak * 1e3),
2481            (turns && !path).then_some(load.dwell_angle_error_peak * 1e3),
2482            load.belt_tension.map(|(lowest, _)| lowest),
2483            load.belt_slack_time,
2484            load.radial_load_peak,
2485            load.guide_load.map(|(peak, _)| peak),
2486            life,
2487            resolved.as_ref().and_then(|cfg| guide_life_h(cfg, load)),
2488        ];
2489        let mut summary = vec![self.header(&["ui-analysis-figure", "ui-analysis-value"])];
2490        summary.extend(CYCLE_KEYS.iter().zip(figures).filter_map(|(key, value)| Some(vec![tr(key), short(value?)])));
2491        // In the order of `MOTOR_KEYS`.
2492        let values = |m: &MotorLoad| {
2493            [
2494                m.peak_torque,
2495                m.rms_torque,
2496                m.cubic_mean_torque,
2497                m.winding_rise,
2498                m.energy_in,
2499                m.energy_regenerated,
2500                m.resistor_energy,
2501                m.resistor_energy / load.duration,
2502                m.peak_dc_link_voltage,
2503                m.mains_energy,
2504                m.housing_rise,
2505                m.drive_overload,
2506            ]
2507        };
2508        let mut motors = vec![self.per_motor()];
2509        for (i, key) in MOTOR_KEYS.iter().enumerate() {
2510            motors.push([vec![tr(key)], load.motors.iter().map(|m| short(values(m)[i])).collect()].concat());
2511        }
2512        // In the order of `LIFE_KEYS`; a row only where some motor has the figure.
2513        let lives = |m: &MotorLoad| -> [Option<f64>; 5] {
2514            let Some(cfg) = &resolved else { return [None; 5] };
2515            [
2516                pulley_bearing_life_h(cfg, m),
2517                gearbox_life_h(cfg, m),
2518                gearbox_gearing_life_h(cfg, m),
2519                motor_bearing_life_h(cfg, m),
2520                belt_tooth_utilisation(cfg, m).ok().flatten(),
2521            ]
2522        };
2523        for (i, key) in LIFE_KEYS.iter().enumerate() {
2524            let row: Vec<Option<f64>> = load.motors.iter().map(|m| lives(m)[i]).collect();
2525            if row.iter().any(Option::is_some) {
2526                motors
2527                    .push([vec![tr(key)], row.into_iter().map(|v| v.map_or(String::new(), short)).collect()].concat());
2528            }
2529        }
2530        let motor = |k: usize| tr(self.session.motors[k].key);
2531        let named = |v: &Verdict| vec![tr(&self.check_key(v.check, v.motor)), v.motor.map_or(String::new(), motor)];
2532        let mut checks = vec![self.header(&VERDICT_KEYS)];
2533        checks.extend(verdicts.iter().map(|v| {
2534            let (value, limit) = short_pair(v.value, v.limit, v.ok);
2535            [named(v), vec![value, limit, self.result(v.ok)]].concat()
2536        }));
2537        let mut tables = vec![summary, motors, checks];
2538        if let Some(bands) = bands {
2539            let mut banded = vec![self.header(&BAND_KEYS)];
2540            banded.extend(bands.iter().map(|b| {
2541                [
2542                    named(&b.verdict),
2543                    vec![short(b.low), short(b.high), self.result(b.ok), short(100.0 * b.share_shown(4))],
2544                ]
2545                .concat()
2546            }));
2547            tables.push(banded);
2548        }
2549        tables
2550    }
2551
2552    /// The analysed cycle as the tables of `load_tables`. Empty until a cycle was analysed.
2553    pub fn cycle_tables(&self) -> Vec<Table> {
2554        let Some((load, verdicts, _)) = &self.cycle_report else { return Vec::new() };
2555        self.load_tables(Analysis::Cycle, load, verdicts, self.bands.as_deref(), None)
2556    }
2557
2558    /// The worst corners of the bounds, where the cycle was analysed with that search: per check and motor the worst
2559    /// value found, its limit there and the result, and which bounded values are at their high and which at their
2560    /// low bound (their config paths, separated by commas).
2561    pub fn worst_table(&self) -> Option<Table> {
2562        let (worst, paths) = self.worst.as_ref()?;
2563        let tr = |key: &str| self.tr.tr(key).to_string();
2564        let mut rows = vec![self.header(&WORST_KEYS)];
2565        for w in worst {
2566            let v = &w.verdict;
2567            let at = |high: bool| {
2568                paths
2569                    .iter()
2570                    .zip(&w.high)
2571                    .filter(|(_, h)| **h == Some(high))
2572                    .map(|(path, _)| path.as_str())
2573                    .collect::<Vec<_>>()
2574                    .join(", ")
2575            };
2576            let motor = v.motor.map_or(String::new(), |k| tr(self.session.motors[k].key));
2577            let (value, limit) = short_pair(v.value, v.limit, v.ok);
2578            rows.push(vec![
2579                tr(&self.check_key(v.check, v.motor)),
2580                motor,
2581                value,
2582                limit,
2583                self.result(v.ok),
2584                at(true),
2585                at(false),
2586            ]);
2587        }
2588        Some(rows)
2589    }
2590
2591    /// The label key of a check (`report::check_key`): the motor's kind decides its unit; without a motor the first one's.
2592    pub fn check_key(&self, check: &str, motor: Option<usize>) -> String {
2593        let linear = self.session.motor_linear.get(motor.unwrap_or(0)).copied().unwrap_or(false);
2594        sim_components::report::check_key(check, linear)
2595    }
2596
2597    /// The motors of the search as ranked: passing ones first, cheapest first. Per motor its gearbox and axis (empty:
2598    /// the config's own), the mass of motor and gearbox, the installed mass that stands in for the price
2599    /// (`Candidate::cost`), result, and the check nearest to its limit with value over limit, or why the cycle was
2600    /// not run. An axis ruled out by its catalogue numbers has a row without motor. No more columns than the panel is
2601    /// wide: the cycle analysis has the rest.
2602    pub fn search_table(&self) -> Option<Table> {
2603        let (found, _) = self.candidates.as_ref()?;
2604        let tr = |key: &str| self.tr.tr(key).to_string();
2605        let mut table = vec![self.header(&SEARCH_KEYS)];
2606        for c in found {
2607            let reason = format!("ui-search-{}", c.refused);
2608            let (check, share) = match (c.tightest(), &c.result) {
2609                (Some((check, share)), _) => (tr(&self.check_key(check, None)), short(share)),
2610                (None, Some(_)) => (String::new(), String::new()),
2611                (None, None) => (tr(if self.tr.has(&reason) { &reason } else { "ui-search-refused" }), String::new()),
2612            };
2613            let mass = |kg: f64| if kg.is_finite() { short(kg) } else { String::new() };
2614            table.push(vec![
2615                c.article.to_string(),
2616                c.gearbox.clone(),
2617                c.axis.clone(),
2618                mass(c.mass),
2619                mass(c.cost),
2620                self.result(c.passes()),
2621                check,
2622                share,
2623            ]);
2624        }
2625        Some(table)
2626    }
2627
2628    /// The path that was run as the three tables of `load_tables`. Empty until a path was run.
2629    pub fn path_tables(&self) -> Vec<Table> {
2630        let Some(run) = &self.path_run else { return Vec::new() };
2631        self.load_tables(Analysis::Path, &run.load, &run.verdicts, None, Some(run.deviation))
2632    }
2633
2634    /// The planned path for a plot, with the labels of its two directions: the second axis over the first,
2635    /// or on a machine with one axis its position over the time.
2636    pub fn path_plot(&self) -> Option<(String, String, Vec<[f64; 2]>)> {
2637        let run = self.path_run.as_ref()?;
2638        let axis = |i: usize| format!("{} [{}]", self.tr.tr(self.session.axes[i].key), self.session.axes[i].unit);
2639        Some(match self.session.axes.len() {
2640            1 => (
2641                self.tr.tr("ui-time").to_string(),
2642                axis(0),
2643                run.points.iter().map(|(time, pose)| [*time, pose[0]]).collect(),
2644            ),
2645            _ => (axis(0), axis(1), run.points.iter().map(|(_, pose)| [pose[0], pose[1]]).collect()),
2646        })
2647    }
2648
2649    /// The replayed trace as two tables: per motor how far the simulation is from the trace (torque and
2650    /// following error, RMS and peak of the difference), and per axis and fitted value what the config has,
2651    /// what the trace says and the standard error of that. Empty until a trace was replayed.
2652    pub fn trace_tables(&self) -> Vec<Table> {
2653        let Some(fit) = &self.trace_fit else { return Vec::new() };
2654        let tr = |key: &str| self.tr.tr(key).to_string();
2655        let mut replayed = vec![self.per_motor()];
2656        for (i, key) in TRACE_KEYS.iter().enumerate() {
2657            replayed.push([vec![tr(key)], fit.differences.iter().map(|d| short(d[i])).collect()].concat());
2658        }
2659        let mut fitted = vec![self.header(&FIT_KEYS)];
2660        for (axis, fit) in self.session.axes.iter().zip(&fit.fits) {
2661            let Some(fit) = fit else { continue };
2662            for (q, key) in FIT_QUANTITIES.iter().enumerate() {
2663                fitted.push(vec![
2664                    format!("{} · {}", tr(axis.key), tr(key)),
2665                    short(fit.config[q]),
2666                    short(fit.fitted[q]),
2667                    short(fit.error[q]),
2668                ]);
2669            }
2670            // The friction beyond its sliding level, where the trace tells it (`identify::friction_details`).
2671            for d in &fit.details {
2672                fitted.push(vec![
2673                    format!("{} · {}", tr(axis.key), tr(&format!("ui-trace-{}", d.quantity.replace('_', "-")))),
2674                    short(d.config),
2675                    short(d.fitted),
2676                    short(d.error),
2677                ]);
2678            }
2679        }
2680        // In the motors' coordinates: the payload's factor (or its step), then per motor, then per link by its name.
2681        for v in fit.joints.iter().flatten().flat_map(|j| &j.values) {
2682            let of = match self.session.motors.iter().find(|m| m.id == v.of) {
2683                Some(m) => tr(m.key),
2684                None if v.of == "payload" => tr("ui-trace-payload"),
2685                None => v.of.clone(),
2686            };
2687            fitted.push(vec![
2688                format!("{of} · {}", tr(&joint_label(v.quantity))),
2689                short(v.config),
2690                short(v.fitted),
2691                short(v.error),
2692            ]);
2693        }
2694        for (time, error) in fit.joints.iter().flatten().flat_map(|j| j.payload_steps.iter().copied()) {
2695            fitted.push(vec![tr("ui-trace-payload-step"), String::new(), short(time), short(error)]);
2696        }
2697        if let Some(Ok(s)) = &fit.stiffness {
2698            fitted.push(vec![tr("ui-trace-stiffness-factor"), short(1.0), short(s.factor), short(s.error)]);
2699        }
2700        let mut identified = vec![self.header(&IDENTIFY_KEYS)];
2701        for (motor, found) in self.session.motors.iter().zip(&fit.identified) {
2702            let named = |name: &str| (tr(motor.key), tr(&format!("identify-{name}")));
2703            for (name, e) in found.estimates() {
2704                let (low, high) = e.interval();
2705                let (motor, quantity) = named(name);
2706                identified.push(vec![
2707                    motor,
2708                    quantity,
2709                    short(e.value),
2710                    short(e.error),
2711                    format!("{} … {}", short(low), short(high)),
2712                ]);
2713            }
2714            for (name, value) in found.qualities() {
2715                let (motor, quantity) = named(name);
2716                identified.push(vec![motor, quantity, short(value), String::new(), String::new()]);
2717            }
2718        }
2719        vec![replayed, fitted, identified]
2720    }
2721
2722    /// What the fit says to change in the config, one line per value, and which axis it could not fit.
2723    pub fn trace_advice(&self) -> Vec<String> {
2724        let Some(fit) = &self.trace_fit else { return Vec::new() };
2725        let mut lines: Vec<(&str, String)> = self
2726            .session
2727            .axes
2728            .iter()
2729            .zip(&fit.fits)
2730            .flat_map(|(axis, fit)| match fit {
2731                Some(fit) => fit.advice(axis.id).to_vec(),
2732                None => vec![("fit-axis-skipped", axis.id.to_string())],
2733            })
2734            .collect();
2735        match &fit.joints {
2736            Some(Some(joints)) => lines.extend(joints.advice()),
2737            Some(None) => lines.push(("fit-joints-skipped", String::new())),
2738            None => {}
2739        }
2740        match &fit.stiffness {
2741            Some(Ok(s)) => lines.push(s.advice()),
2742            Some(Err(e)) => lines.push((e.key, e.detail.clone())),
2743            None => {}
2744        }
2745        lines.into_iter().map(|(key, detail)| self.tr.tr_arg(key, &detail)).collect()
2746    }
2747
2748    /// Measured against simulated, per quantity of `OVERLAY_KEYS` (torque, speed, following error at the motor)
2749    /// and per motor: (time, measured value) and (time, simulated value). Empty until a trace was replayed.
2750    /// Worked out once, when the trace arrives: a frame used to copy the whole trace for it.
2751    pub fn overlay(&self) -> &Overlay {
2752        &self.overlay
2753    }
2754
2755    /// Writes the overlay as `sim-cli replay --out` does, in the background; the message comes with `poll`.
2756    pub fn export_overlay(&mut self, path: &std::path::Path) {
2757        let Some(fit) = &self.trace_fit else { return };
2758        let ids: Vec<&str> = self.session.motors.iter().map(|m| m.id).collect();
2759        let (text, path) = (overlay_csv(&ids, &fit.measured, &fit.simulated), path.to_path_buf());
2760        self.write_in_background(move || match std::fs::write(&path, text) {
2761            Ok(()) => Ok(("ui-overlay-exported", path.display().to_string())),
2762            Err(e) => Err(("ui-export-failed", format!("{}: {e}", path.display()))),
2763        });
2764    }
2765
2766    /// The operating points of the analysed cycle, as `sim-cli analyze --points` writes them, motor after motor:
2767    /// how many there are, and the header with the rows in `rows`. `None` until a cycle was analysed.
2768    pub fn points_table(&self, rows: std::ops::Range<usize>) -> Option<(usize, Table)> {
2769        let (load, _, _) = self.cycle_report.as_ref()?;
2770        // A motor of the other kind than the header's gets its own units in its name cell.
2771        let header_linear = self.motors_linear();
2772        let all = self
2773            .session
2774            .motors
2775            .iter()
2776            .zip(&load.motors)
2777            .enumerate()
2778            .flat_map(|(k, (motor, m))| m.points.iter().map(move |p| (k, motor, p)));
2779        let shown = all.clone().skip(rows.start).take(rows.len()).map(|(k, motor, (speed, torque))| {
2780            let mut name = self.tr.tr(motor.key).to_string();
2781            if self.motor_is_linear(k) != header_linear {
2782                name = format!("{name} [{}; {}]", self.motor_speed_label(k), self.motor_torque_label(k));
2783            }
2784            vec![name, short(*speed * self.motor_speed_scale(k)), short(*torque)]
2785        });
2786        let mut header = self.header(&POINTS_KEYS);
2787        (header[1], header[2]) = (self.speed_label(), self.torque_label());
2788        Some((all.count(), [vec![header], shown.collect()].concat()))
2789    }
2790
2791    /// The label of the motor speed's axis in the unit chosen; m/s where every motor is linear.
2792    pub fn speed_label(&self) -> String {
2793        self.speed_label_of(self.motors_linear())
2794    }
2795
2796    /// The label of the motor torque's axis: a force in N where every motor is linear.
2797    pub fn torque_label(&self) -> String {
2798        self.torque_label_of(self.motors_linear())
2799    }
2800
2801    /// The speed axis label of a linear (m/s) or a rotary (rad/s or rpm) motor.
2802    fn speed_label_of(&self, linear: bool) -> String {
2803        let key = match () {
2804            _ if linear => "ui-points-speed-linear",
2805            _ if self.units.rpm => "ui-points-speed-rpm",
2806            _ => "ui-points-speed",
2807        };
2808        self.tr.tr(key).to_string()
2809    }
2810
2811    fn torque_label_of(&self, linear: bool) -> String {
2812        self.tr.tr(if linear { "ui-points-torque-linear" } else { "ui-points-torque" }).to_string()
2813    }
2814
2815    /// Whether motor `k` is linear (`Machine::motor_linear`).
2816    pub fn motor_is_linear(&self, k: usize) -> bool {
2817        self.session.motor_linear.get(k).copied().unwrap_or(false)
2818    }
2819
2820    /// The speed axis label of motor `k`'s chart: a machine with rotary and linear motors has each on its own unit.
2821    pub fn motor_speed_label(&self, k: usize) -> String {
2822        self.speed_label_of(self.motor_is_linear(k))
2823    }
2824
2825    /// The torque axis label of motor `k`'s chart.
2826    pub fn motor_torque_label(&self, k: usize) -> String {
2827        self.torque_label_of(self.motor_is_linear(k))
2828    }
2829
2830    /// Whether every motor of the machine is linear (`Machine::motor_linear`): speeds in m/s, forces in N.
2831    pub fn motors_linear(&self) -> bool {
2832        !self.session.motor_linear.is_empty() && self.session.motor_linear.iter().all(|l| *l)
2833    }
2834
2835    /// The factor of the motor speeds in the unit chosen: rpm applies to rotary motors only.
2836    pub fn speed_scale(&self) -> f64 {
2837        if self.motors_linear() { 1.0 } else { self.units.scale("rad/s").0 }
2838    }
2839
2840    /// The factor of motor `k`'s speeds: 1 for a linear motor (m/s), else the unit chosen.
2841    pub fn motor_speed_scale(&self, k: usize) -> f64 {
2842        if self.motor_is_linear(k) { 1.0 } else { self.units.scale("rad/s").0 }
2843    }
2844
2845    /// The operating points per motor as (speed, torque), and the torque-speed curves (`Curves`): of the analysed
2846    /// cycle (`Analysis::Cycle`) or of the path that was run (`Analysis::Path`). `None` until there is one.
2847    pub fn points_plot(&self, kind: Analysis) -> Option<(Vec<Vec<[f64; 2]>>, Curves)> {
2848        let (load, curves) = match kind {
2849            Analysis::Path => self.path_run.as_ref().map(|run| (&run.load, &run.curves))?,
2850            _ => self.cycle_report.as_ref().map(|(load, _, curves)| (load, curves))?,
2851        };
2852        // Speeds in the unit chosen (`units`).
2853        let points = load
2854            .motors
2855            .iter()
2856            .enumerate()
2857            .map(|(k, m)| {
2858                let rpm = self.motor_speed_scale(k);
2859                m.points.iter().map(|(speed, torque)| [*speed * rpm, *torque]).collect()
2860            })
2861            .collect();
2862        let curves = curves
2863            .iter()
2864            .enumerate()
2865            .map(|(k, chart)| crate::runs::scaled_speeds(chart, self.motor_speed_scale(k)))
2866            .collect();
2867        Some((points, curves))
2868    }
2869
2870    /// The parts of each motor's torque over the scopes' time window: per motor its name with the unit, and per
2871    /// part of `TORQUE_PARTS` and then the torque itself the label and the points (time, torque). Empty for a machine
2872    /// that does not report the parts.
2873    pub fn breakdown_lines(&self) -> Vec<(String, Vec<(String, Vec<[f64; 2]>)>)> {
2874        let signals = &self.session.signals;
2875        let rows: Vec<&[f64]> = self.visible_rows().collect();
2876        let lines = |motor: &sim_core::MotorInfo| -> Option<(String, Vec<(String, Vec<[f64; 2]>)>)> {
2877            let ids = TORQUE_PARTS
2878                .iter()
2879                .map(|part| format!("motor.{}.torque_{part}", motor.id))
2880                .chain([format!("motor.{}.torque", motor.id)]);
2881            let places: Vec<usize> = ids.map(|id| signals.iter().position(|s| s.id == id)).collect::<Option<_>>()?;
2882            let title = format!("{} [{}]", self.tr.tr(motor.key), signals[places[4]].unit);
2883            Some((
2884                title,
2885                places
2886                    .iter()
2887                    .zip(BREAKDOWN_KEYS)
2888                    .map(|(&i, key)| (self.tr.tr(key).to_string(), plot_line(rows.len(), |n| [rows[n][0], rows[n][i]])))
2889                    .collect(),
2890            ))
2891        };
2892        self.session.motors.iter().filter_map(lines).collect()
2893    }
2894
2895    /// The parts of each motor's torque over the analysed cycle: one row per part and one for the torque itself, per
2896    /// motor its peak and its RMS in N m. `None` until a cycle was analysed, and for a machine that does not report the
2897    /// parts.
2898    pub fn breakdown_table(&self) -> Option<Table> {
2899        let (load, _, _) = self.cycle_report.as_ref()?;
2900        let parts: Vec<[(f64, f64); 4]> = load.motors.iter().map(|m| m.torque_parts).collect::<Option<_>>()?;
2901        let tr = |key: &str| self.tr.tr(key).to_string();
2902        let mut header = vec![tr("ui-effects-part")];
2903        for motor in &self.session.motors {
2904            header.extend(["ui-effects-peak", "ui-effects-rms"].map(|key| format!("{} · {}", tr(motor.key), tr(key))));
2905        }
2906        let mut table = vec![header];
2907        for (i, key) in BREAKDOWN_KEYS.iter().enumerate() {
2908            let cells = load.motors.iter().zip(&parts).flat_map(|(m, p)| {
2909                let (peak, rms) = p.get(i).copied().unwrap_or((m.peak_torque, m.rms_torque));
2910                [short(peak), short(rms)]
2911            });
2912            table.push([vec![tr(key)], cells.collect()].concat());
2913        }
2914        Some(table)
2915    }
2916
2917    /// Where the energy drawn from the supply over the analysed cycle went: the supply, every row of the budget that
2918    /// is not exactly zero (an effect that is off), and what is not accounted for; in J and in percent of the supply.
2919    /// `None` until a cycle was analysed, and for a machine that does not report its losses.
2920    pub fn budget_table(&self) -> Option<Table> {
2921        let budget = self.cycle_report.as_ref()?.0.budget.as_ref()?;
2922        let tr = |key: &str| self.tr.tr(key).to_string();
2923        let line = |label: String, energy: f64| vec![label, short(energy), short(100.0 * energy / budget.supply)];
2924        let mut table = vec![
2925            self.header(&["ui-effects-item", "ui-effects-energy", "ui-effects-share"]),
2926            line(tr("budget-supply"), budget.supply),
2927        ];
2928        table.extend(
2929            budget
2930                .rows
2931                .iter()
2932                .filter(|r| r.energy != 0.0)
2933                .map(|r| line(format!("{} · {}", tr(&r.owner_key), tr(&r.quantity_key)), r.energy)),
2934        );
2935        table.push(line(tr("budget-unaccounted"), budget.unaccounted()));
2936        Some(table)
2937    }
2938
2939    /// The energy budget of the analysed cycle as a flow diagram, in three columns of (label, energy in J), every
2940    /// energy above zero. The first holds the supply and every store that gave energy back over the cycle (a row of the
2941    /// budget below zero); the second what the electrical side lost or stored (the rows `EnergyBudget::
2942    /// electrical_unaccounted` counts, and what that leaves), and last the shaft work, with what the machine's stores
2943    /// gave back; the third what the machine lost or stored, and what its own balance leaves. So the first column adds
2944    /// up to the second, the second's last to the third, and the second and third less what the first has beyond the
2945    /// supply are the supply, as the budget's rows and what it leaves unaccounted are. Rows that are exactly zero (an
2946    /// effect that is off) are left out, as in `budget_table`. `None` where that has nothing.
2947    pub fn budget_flows(&self) -> Option<[Vec<(String, f64)>; 3]> {
2948        let budget = self.cycle_report.as_ref()?.0.budget.as_ref()?;
2949        let tr = |key: &str| self.tr.tr(key).to_string();
2950        let electrical = |id: &str| {
2951            id.starts_with("copper.")
2952                || id.starts_with("emf.")
2953                || matches!(id, "resistor" | "discharge" | "mains" | "line_module" | "windings" | "capacitors")
2954        };
2955        let unaccounted = |energy: f64| (tr("budget-unaccounted"), energy);
2956        let stage = |side: bool, rest: f64| -> Vec<(String, f64)> {
2957            let rows = budget.rows.iter().filter(|r| r.energy != 0.0 && electrical(&r.id) == side);
2958            rows.map(|r| (format!("{} · {}", tr(&r.owner_key), tr(&r.quantity_key)), r.energy))
2959                .chain([unaccounted(rest)])
2960                .collect()
2961        };
2962        let electrical_rest = budget.electrical_unaccounted();
2963        let (supplied, machine) = (stage(true, electrical_rest), stage(false, budget.unaccounted() - electrical_rest));
2964        let given_back = |items: &[(String, f64)]| {
2965            items.iter().filter(|(_, e)| *e < 0.0).map(|(label, e)| (label.clone(), -e)).collect::<Vec<_>>()
2966        };
2967        let taken = |items: &[(String, f64)]| items.iter().filter(|(_, e)| *e > 0.0).cloned().collect::<Vec<_>>();
2968        let back: f64 = given_back(&machine).iter().map(|(_, e)| e).sum();
2969        let first = [vec![(tr("budget-supply"), budget.supply)], given_back(&supplied), given_back(&machine)].concat();
2970        let second = [taken(&supplied), vec![(tr("ui-effects-shaft-work"), budget.shaft_work + back)]].concat();
2971        Some([first, second, taken(&machine)])
2972    }
2973
2974    /// A horizontal slice through what the machine can reach, at the height `inputs.workspace_z` (the middle of the
2975    /// third axis's range where it is `None`, and within that range), for the workspace map: per node of a grid the
2976    /// condition number of the kinematics there (`Machine::condition`). The grid spans the first two axes' ranges and
2977    /// half of their width beyond each end, so that the reach shows where it goes past the travel range. `None` for a
2978    /// machine with fewer than three axes or no condition to tell, and for a config it does not build.
2979    /// Worked out once per config, height and grid: 3721 nodes each frame cost the path tab its frame rate.
2980    pub fn workspace_slice(&self, n: usize) -> Option<Arc<WorkspaceSlice>> {
2981        let key = (self.config.clone(), self.inputs.workspace_z.map(f64::to_bits), n);
2982        if let Some((kept, slice)) = &self.cache.lock().unwrap_or_else(|e| e.into_inner()).workspace
2983            && *kept == key
2984        {
2985            return slice.clone();
2986        }
2987        let slice = self.with_machine(|machine| self.workspace_of(machine, n)).flatten().map(Arc::new);
2988        self.cache.lock().unwrap_or_else(|e| e.into_inner()).workspace = Some((key, slice.clone()));
2989        slice
2990    }
2991
2992    fn workspace_of(&self, machine: &dyn Machine, n: usize) -> Option<WorkspaceSlice> {
2993        let axes = machine.axes();
2994        let heights = (axes.get(2)?.min, axes[2].max);
2995        let z = self.inputs.workspace_z.unwrap_or((heights.0 + heights.1) / 2.0).clamp(heights.0, heights.1);
2996        machine.condition(&[0.0, 0.0, z])?;
2997        // Each motor's peak torque, from its own drive (`Run::rated` takes it so too).
2998        let sim = Sim::new(self.entry, &self.config).ok()?;
2999        let peak: Vec<f64> = (0..machine.motors().len()).map(|k| sim.control.drive_params_of(k).peak_torque).collect();
3000        let slice = crate::insight::workspace_slice(machine, z, n, &peak)?;
3001        let nodes = slice.condition.iter().copied().zip(slice.goes.iter().copied()).collect();
3002        let (x, y, acceleration) = (slice.x, slice.y, slice.acceleration);
3003        let limit = self.config.f64("ratings.max_condition_number").unwrap_or(10.0);
3004        Some(WorkspaceSlice { x, y, z, n, nodes, limit, heights, acceleration })
3005    }
3006
3007    /// Per friction contact of the machine its curve of steady sliding and where it is now (see `FrictionView`). The
3008    /// curve runs over the axis's speed limit both ways, with its points closer together near standstill, where the
3009    /// Stribeck drop is. Empty for a machine that tells no contacts, or a config it does not build.
3010    pub fn friction_views(&self) -> Vec<FrictionView> {
3011        let motor_speed = self.motor_speeds();
3012        self.with_machine(|machine| self.friction_of(machine, &motor_speed)).unwrap_or_default()
3013    }
3014
3015    /// Each motor's highest rotor speed from its own drive (`DriveParams::max_speed`), once per config: building the
3016    /// simulation takes longer than a frame. Empty for a config that does not start.
3017    fn motor_speeds(&self) -> Vec<f64> {
3018        let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
3019        if cache.motor_speed.as_ref().is_none_or(|(config, _)| *config != self.config) {
3020            let speeds = Sim::new(self.entry, &self.config).map_or_else(
3021                |_| Vec::new(),
3022                |sim| (0..sim.machine.motors().len()).map(|k| sim.control.drive_params_of(k).max_speed).collect(),
3023            );
3024            cache.motor_speed = Some((self.config.clone(), speeds));
3025        }
3026        cache.motor_speed.as_ref().map(|(_, speeds)| speeds.clone()).unwrap_or_default()
3027    }
3028
3029    fn friction_of(&self, machine: &dyn Machine, motor_speed: &[f64]) -> Vec<FrictionView> {
3030        let tr = |key: &str| self.tr.tr(key).to_string();
3031        let value = |id: String| -> Option<f64> {
3032            Some(self.history.back()?[self.session.signals.iter().position(|s| s.id == id)?])
3033        };
3034        let views = machine.friction_contacts().into_iter().enumerate().map(|(i, contact)| {
3035            let get = |part: &str| value(format!("{}.friction_{part}", contact.id));
3036            let scale = get("load_scale").unwrap_or(1.0);
3037            // The machine's own limit where it has one (a joint: its motor's top speed over the gearbox), else the
3038            // contact's axis, else the fastest axis (a carriage on no axis of its own).
3039            let fastest = self.session.axes.iter().map(|a| a.max_vel).fold(0.0, f64::max);
3040            let top = machine.friction_speed_limit(i, motor_speed).unwrap_or_else(|| {
3041                self.session.axes.iter().find(|a| a.key == contact.owner_key).map_or(fastest, |a| a.max_vel)
3042            });
3043            let rotary = machine.friction_rotary(i);
3044            let (speed_unit, force_unit) = if rotary { ("rad/s", "N m") } else { ("m/s", "N") };
3045            let speeds = (1..=100)
3046                .rev()
3047                .map(|j| -top * (j as f64 / 100.0).powi(3))
3048                .chain((1..=100).map(|j| top * (j as f64 / 100.0).powi(3)));
3049            let mut points: [Vec<[f64; 2]>; 4] = Default::default();
3050            for v in speeds {
3051                let parts = machine.friction_curve(i, v, scale);
3052                points[0].push([v, parts.iter().sum()]);
3053                (0..3).for_each(|k| points[k + 1].push([v, parts[k]]));
3054            }
3055            let labels = [tr("ui-effects-total")].into_iter().chain(FRICTION_KEYS.map(tr));
3056            let split: Option<Vec<f64>> = ["coulomb", "viscous", "stiction"].iter().map(|part| get(part)).collect();
3057            let (speed, total) = (get("speed"), split.as_ref().map(|s| s.iter().sum::<f64>()));
3058            let mut table = vec![self.header(&["ui-effects-part", "ui-effects-now"])];
3059            let cell = |value: Option<f64>| value.map_or(String::new(), short);
3060            table.push(vec![format!("{} [{speed_unit}]", tr("quantity-friction-speed")), cell(speed)]);
3061            for (k, key) in FRICTION_KEYS.iter().enumerate() {
3062                table.push(vec![format!("{} [{force_unit}]", tr(key)), cell(split.as_ref().map(|s| s[k]))]);
3063            }
3064            let total_key = if rotary { "ui-effects-total-torque" } else { "ui-effects-total" };
3065            table.push(vec![format!("{} [{force_unit}]", tr(total_key)), cell(total)]);
3066            table.push(vec![tr("quantity-friction-load-scale"), cell(get("load_scale"))]);
3067            let mut curves = labels.zip(points);
3068            FrictionView {
3069                title: tr(contact.owner_key),
3070                curves: std::array::from_fn(|_| curves.next().unwrap()),
3071                now: speed.zip(total).map(|(v, f)| [v, f]),
3072                table,
3073                rotary,
3074            }
3075        });
3076        views.collect()
3077    }
3078
3079    /// `f` of the machine as the config builds it, for what it tells the views; `None` for a config it does not build.
3080    /// The machine is built once per config, not once per view and frame.
3081    fn with_machine<T>(&self, f: impl FnOnce(&dyn Machine) -> T) -> Option<T> {
3082        let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
3083        if cache.machine.as_ref().is_none_or(|(config, _)| *config != self.config) {
3084            let built =
3085                sim_components::catalog::resolve(self.entry, &self.config).and_then(|cfg| (self.entry.build)(&cfg));
3086            cache.machine = Some((self.config.clone(), built.ok()));
3087        }
3088        let machine = cache.machine.as_ref().and_then(|(_, m)| m.as_deref())?;
3089        Some(f(machine))
3090    }
3091
3092    /// The newest sample of a signal, by its id.
3093    fn latest(&self, id: &str) -> Option<f64> {
3094        Some(self.history.back()?[self.session.signals.iter().position(|s| s.id == id)?])
3095    }
3096
3097    /// The points (time, value times `scale`) of a signal over the scopes' window, its peaks kept (`plot_line`).
3098    fn line_of(&self, id: &str, scale: f64) -> Vec<[f64; 2]> {
3099        let Some(i) = self.session.signals.iter().position(|s| s.id == id) else { return Vec::new() };
3100        let rows: Vec<&[f64]> = self.visible_rows().collect();
3101        plot_line(rows.len(), |n| [rows[n][0], rows[n][i] * scale])
3102    }
3103
3104    /// The thermal view (see `ThermalView`). The windings are rated for `motor.rated_temperature_rise_k`, the parts
3105    /// for `thermal.<kind>_max_rise_k`; a part settles at its thermal resistance times its mean loss over the analysed
3106    /// cycle (`CycleLoad::part_rises`), a winding at `MotorLoad::winding_rise`. The share of the rating is that of the
3107    /// settled rise, which is what the verdicts judge (the rise now is a climb of many minutes); above 100 % it is
3108    /// marked.
3109    pub fn thermal_view(&self) -> ThermalView {
3110        let tr = |key: &str| self.tr.tr(key).to_string();
3111        let on = |effect: &str| self.config.bool(&format!("effects.{effect}")).unwrap_or(false);
3112        let load = self.cycle_report.as_ref().map(|r| &r.0);
3113        let kelvin = |key: &str, unit: &str| format!("{} [{unit}]", tr(key));
3114        let mut table = vec![vec![
3115            tr("ui-effects-component"),
3116            kelvin("ui-effects-now", "K"),
3117            kelvin("ui-effects-settles", "K"),
3118            kelvin("ui-effects-rated", "K"),
3119            kelvin("ui-effects-settled-of-rated", "%"),
3120        ]];
3121        let mut lines = Vec::new();
3122        let mut add = |name: String, id: String, settles: Option<f64>, rated: Option<f64>| {
3123            let now = self.latest(&id);
3124            let share = settles.zip(rated).map(|(settles, rated)| 100.0 * settles / rated);
3125            let mut row: Vec<String> = [name.clone()]
3126                .into_iter()
3127                .chain([now, settles, rated, share].map(|v| v.map_or(String::new(), short)))
3128                .collect();
3129            if share.is_some_and(|share| share > 100.0) {
3130                row[4] = format!("{} {}", row[4], tr("ui-effects-over-rating"));
3131            }
3132            table.push(row);
3133            lines.push((name, self.line_of(&id, 1.0)));
3134        };
3135        let winding_rated = self.config.positive("motor.rated_temperature_rise_k").ok();
3136        for (k, motor) in self.session.motors.iter().enumerate() {
3137            let settles = load.and_then(|l| l.motors.get(k)).map(|m| m.winding_rise);
3138            add(
3139                format!("{} · {}", tr(motor.key), tr("quantity-winding-temperature")),
3140                format!("motor.{}.winding_temperature", motor.id),
3141                settles,
3142                winding_rated,
3143            );
3144        }
3145        // The temperature feedback warms the parts too (`sim::heats`).
3146        let parts = on("part_heating") || on("thermal_feedback");
3147        if parts {
3148            for part in self.with_machine(|m| m.thermal_parts()).unwrap_or_default() {
3149                let key = |name: &str| format!("thermal.{}_{name}", part.kind);
3150                let settles =
3151                    load.and_then(|l| l.part_rises.iter().find(|(p, _)| p.id == part.id)).map(|(_, rise)| *rise);
3152                let name = format!("{} · {}", tr(part.owner_key), tr(&format!("quantity-{}-temperature", part.kind)));
3153                add(
3154                    name,
3155                    format!("{TEMPERATURE_PREFIX}{}", part.id),
3156                    settles,
3157                    self.config.positive(&key("max_rise_k")).ok(),
3158                );
3159            }
3160        }
3161        ThermalView { lines, table, off: !on("winding_heating") && !parts }
3162    }
3163
3164    /// The belt view (see `BeltView`); `None` for a machine that tells no belt sections. Stretch in mm.
3165    pub fn belt_view(&self) -> Option<BeltView> {
3166        let sections = self.with_machine(|m| m.belt_sections())?;
3167        let pretension = sections.first()?.pretension;
3168        let rating = self.config.positive("ratings.belt_max_tension_n").ok();
3169        let tr = |key: &str| self.tr.tr(key).to_string();
3170        let unit = |key: &str, unit: &str| format!("{} [{unit}]", tr(key));
3171        let mut table = vec![vec![
3172            tr("ui-effects-section"),
3173            unit("ui-effects-tension", "N"),
3174            unit("ui-effects-pretension", "N"),
3175            unit("ui-effects-rating", "N"),
3176            unit("ui-effects-of-rated", "%"),
3177            unit("ui-effects-stretch", "mm"),
3178        ]];
3179        let (mut tension, mut stretch) = (Vec::new(), Vec::new());
3180        for section in &sections {
3181            let (pull, long) = (format!("{}.tension", section.id), format!("{}.stretch", section.id));
3182            let now = self.latest(&pull);
3183            let cells = [
3184                now,
3185                Some(section.pretension),
3186                rating,
3187                now.zip(rating).map(|(t, r)| 100.0 * t / r),
3188                self.latest(&long).map(|e| e * 1e3),
3189            ];
3190            table.push(
3191                [tr(section.owner_key)].into_iter().chain(cells.map(|v| v.map_or(String::new(), short))).collect(),
3192            );
3193            tension.push((tr(section.owner_key), self.line_of(&pull, 1.0)));
3194            stretch.push((tr(section.owner_key), self.line_of(&long, 1e3)));
3195        }
3196        let titles = [unit("ui-effects-tension", "N"), unit("ui-effects-stretch", "mm")];
3197        let scale = [
3198            format!("{} 0 N", tr("ui-effects-slack")),
3199            format!("{} {:.0} N", tr("ui-effects-double"), 2.0 * pretension),
3200        ];
3201        Some(BeltView { tension, stretch, pretension, rating, table, titles, scale })
3202    }
3203
3204    /// The effect comparison (see `CompareView`) for the quantity `inputs.compare_quantity`; `None` before one was run,
3205    /// and for a quantity the comparison has no signal of.
3206    pub fn compare_view(&self) -> Option<CompareView> {
3207        let (effect, found) = self.comparison.as_ref()?;
3208        let tr = |key: &str| self.tr.tr(key).to_string();
3209        let scope = scopes_for(&found.signals).into_iter().find(|s| s.quantity_key == self.inputs.compare_quantity)?;
3210        let unit = |key: &str| format!("{} [{}]", tr(key), scope.unit);
3211        let mut table =
3212            vec![vec![tr("ui-effects-signal"), unit("ui-effects-difference-peak"), unit("ui-effects-difference-rms")]];
3213        let mut lines = Vec::new();
3214        for line in scope.lines.iter().filter(|l| !l.reference) {
3215            let i = line.signal;
3216            let points = |rows: &Vec<Vec<f64>>| plot_line(rows.len(), |n| [rows[n][0], rows[n][i]]);
3217            let name = tr(&found.signals[i].owner_key);
3218            let (peak, rms) = found.difference(i);
3219            table.push(vec![name.clone(), short(peak), short(rms)]);
3220            lines.push((name, points(&found.on), points(&found.off)));
3221        }
3222        Some(CompareView {
3223            effect: tr(&format!("effect-{effect}")),
3224            title: format!("{} [{}]", tr(&scope.quantity_key), scope.unit),
3225            lines,
3226            table,
3227        })
3228    }
3229
3230    /// One row per figure, one column per motor: the resonance of the load on the belt in each frequency
3231    /// response (`identify::resonance`), and its damping ratio. Empty where a response has no dip with both
3232    /// flanks. `None` until a sweep was run.
3233    pub fn sweep_table(&self) -> Option<Table> {
3234        let sweeps = self.sweeps.as_ref()?;
3235        let found: Vec<_> = sweeps.iter().map(|points| resonance(points)).collect();
3236        let cells = |value: fn(&sim_components::identify::Resonance) -> f64| {
3237            found.iter().map(move |r| r.as_ref().map_or(String::new(), |r| short(value(r))))
3238        };
3239        let rows = [
3240            (SWEEP_KEYS[0], cells(|r| r.frequency).collect::<Vec<_>>()),
3241            (SWEEP_KEYS[1], cells(|r| r.damping).collect()),
3242        ];
3243        Some(
3244            [
3245                vec![self.per_motor()],
3246                rows.into_iter().map(|(key, cells)| [vec![self.tr.tr(key).to_string()], cells].concat()).collect(),
3247            ]
3248            .concat(),
3249        )
3250    }
3251
3252    /// The fit of a measured frequency response, as `sim-cli fit --sweep` writes it: resonance and damping of
3253    /// the config's own response and of the measured one, and the standard error of the frequency.
3254    pub fn sweep_fit_table(&self) -> Option<Table> {
3255        let (motor, fit) = self.sweep_fit.as_ref()?;
3256        let name = |key: &str| format!("{} · {}", self.tr.tr(self.session.motors[*motor].key), self.tr.tr(key));
3257        Some(vec![
3258            self.header(&FIT_KEYS),
3259            vec![
3260                name(SWEEP_KEYS[0]),
3261                short(fit.config.frequency),
3262                short(fit.fitted.frequency),
3263                short(fit.fitted.frequency_error),
3264            ],
3265            vec![name(SWEEP_KEYS[1]), short(fit.config.damping), short(fit.fitted.damping), String::new()],
3266        ])
3267    }
3268
3269    /// What the fit of a measured frequency response says to change in the config.
3270    pub fn sweep_fit_advice(&self) -> Option<String> {
3271        let (key, detail) = self.sweep_fit.as_ref()?.1.advice();
3272        Some(self.tr.tr_arg(key, &detail))
3273    }
3274
3275    /// The parameters the cycle depends on most, strongest first: the low and high value each was run
3276    /// with, and what that did to peak torque, RMS torque and cycle time, in percent.
3277    pub fn sensitivity_table(&self) -> Option<Table> {
3278        let (nominal, rows) = self.sensitivity.as_ref()?;
3279        let mut table = vec![self.header(&SENSITIVITY_KEYS)];
3280        for row in rows.iter().take(TOP_ROWS) {
3281            let c = row.changes(nominal).map(|change| change * 100.0);
3282            let pair = |low: f64, high: f64| format!("{low:+.1} / {high:+.1}");
3283            table.push(vec![
3284                self.param_label(&row.path),
3285                short(row.bounds.0),
3286                short(row.bounds.1),
3287                pair(c[0], c[1]),
3288                pair(c[2], c[3]),
3289                pair(c[4], c[5]),
3290            ]);
3291        }
3292        Some(table)
3293    }
3294
3295    /// The optimiser's result: cycle time and settling before and after, and every setting it would change.
3296    pub fn optimised_table(&self) -> Option<Table> {
3297        let found = self.optimised.as_ref()?;
3298        let mut table = vec![self.header(&OPTIMISED_KEYS)];
3299        table.push(vec![
3300            self.tr.tr("ui-analysis-cycle-time").to_string(),
3301            short(found.before.duration),
3302            short(found.after.duration),
3303        ]);
3304        table.push(vec![
3305            self.tr.tr("ui-analysis-dwell-error").to_string(),
3306            short(found.before.dwell_error_peak * 1e3),
3307            short(found.after.dwell_error_peak * 1e3),
3308        ]);
3309        if found.before.dwell_angle_error_peak > 0.0 {
3310            table.push(vec![
3311                self.tr.tr("ui-analysis-dwell-angle-error").to_string(),
3312                short(found.before.dwell_angle_error_peak * 1e3),
3313                short(found.after.dwell_angle_error_peak * 1e3),
3314            ]);
3315        }
3316        // The new cycle itself is applied whole; its lifts say what changed in it (segments counted from 1).
3317        for (path, before, after) in found.changes.iter().filter(|c| c.0 != "cycle.segment") {
3318            table.push(vec![self.param_label(path), before.clone(), after.clone()]);
3319        }
3320        for lift in &found.lifts {
3321            let segments = lift.segments.map(|i| (i + 1).to_string()).join(", ");
3322            table.push(vec![self.tr.tr_arg("optimised-lift", &segments), short(lift.before), short(lift.after)]);
3323            if let Some(via) = &lift.via {
3324                table.push(vec![
3325                    self.tr.tr_arg("optimised-via", &segments),
3326                    String::new(),
3327                    via.iter()
3328                        .map(|point| point.iter().map(|x| short(*x)).collect::<Vec<_>>().join(", "))
3329                        .collect::<Vec<_>>()
3330                        .join("; "),
3331                ]);
3332            }
3333        }
3334        // Judged in the error bands: the fastest setting on the config as written, what it fails there, and what the
3335        // cycle as configured fails there already (not judged).
3336        if let Some(robust) = &found.robust {
3337            let checks = |checks: &[&str]| {
3338                checks.iter().map(|c| self.tr.tr(&self.check_key(c, None)).to_string()).collect::<Vec<_>>().join(", ")
3339            };
3340            table.push(vec![
3341                self.tr.tr("optimised-fastest").to_string(),
3342                String::new(),
3343                short(robust.nominal_duration),
3344            ]);
3345            table.push(vec![
3346                self.tr
3347                    .tr(if robust.worst { "optimised-fastest-fails-worst" } else { "optimised-fastest-fails" })
3348                    .to_string(),
3349                String::new(),
3350                checks(&robust.nominal_fails),
3351            ]);
3352            let excused = if robust.worst { "optimised-excused-worst" } else { "optimised-excused" };
3353            table.push(vec![self.tr.tr(excused).to_string(), String::new(), checks(&robust.excused)]);
3354        }
3355        Some(table)
3356    }
3357
3358    /// The optimiser's front of energy against cycle time (`Optimised::front`): (cycle time, energy per cycle) of each
3359    /// point, and the result's cycle time.
3360    pub fn optimised_front(&self) -> Option<(Vec<[f64; 2]>, f64)> {
3361        let found = self.optimised.as_ref().filter(|found| !found.front.is_empty())?;
3362        Some((found.front.iter().map(|p| [p.duration, p.energy]).collect(), found.after.duration))
3363    }
3364
3365    // ---------------------------------------------------------------------------------------
3366    // Labels and panels
3367
3368    /// "X axis · Following error [m]"
3369    pub fn signal_label(&self, signal: &SignalInfo) -> String {
3370        format!("{} · {} [{}]", self.tr.tr(&signal.owner_key), self.tr.tr(&signal.quantity_key), signal.unit)
3371    }
3372
3373    /// The effect switches: (config path, label key, on).
3374    pub fn effects(&self) -> Vec<(String, String, bool)> {
3375        let leaves = self.config.leaves().into_iter();
3376        leaves
3377            .filter_map(|(path, value)| {
3378                Some((path.clone(), format!("effect-{}", path.strip_prefix("effects.")?), value.as_bool()?))
3379            })
3380            .collect()
3381    }
3382
3383    /// The parameter panel: every numeric config value, grouped by its table.
3384    pub fn param_groups(&self) -> Vec<ParamGroup> {
3385        let mut groups: Vec<ParamGroup> = Vec::new();
3386        for (path, value) in self.config.leaves() {
3387            let Some((table, leaf)) = path.rsplit_once('.') else { continue };
3388            if table == "effects" || !(value.is_float() || value.is_integer()) {
3389                continue;
3390            }
3391            let key = format!("group-{}", table.replace('.', "-"));
3392            let param = (path.clone(), format!("param-{leaf}"), value);
3393            match groups.iter_mut().find(|g| g.key == key) {
3394                Some(group) => group.params.push(param),
3395                None => groups.push(ParamGroup { key, params: vec![param] }),
3396            }
3397        }
3398        groups
3399    }
3400
3401    /// Whether the parameter `path` is listed under `filter`: its label (in the language shown) or its dotted path
3402    /// holds the filter, in any case. An empty filter lists all.
3403    pub fn param_matches(&self, path: &str, filter: &str) -> bool {
3404        let wanted = filter.trim().to_lowercase();
3405        wanted.is_empty()
3406            || path.to_lowercase().contains(&wanted)
3407            || self.param_label(path).to_lowercase().contains(&wanted)
3408    }
3409
3410    /// The values of the config that differ from the machine's default: the dotted path, its label, the default
3411    /// and the value now, in the config's order. Values the default does not have (a machine file's extra keys) are
3412    /// listed with the default as `None`.
3413    pub fn changed_params(&self) -> Vec<(String, String, Option<Value>, Value)> {
3414        self.config
3415            .leaves()
3416            .into_iter()
3417            .filter_map(|(path, value)| {
3418                let default = self.default.get(&path).ok().cloned();
3419                (default.as_ref() != Some(&value)).then(|| (path.clone(), self.param_label(&path), default, value))
3420            })
3421            .collect()
3422    }
3423
3424    // ---------------------------------------------------------------------------------------
3425    // The mode list, the coloured path and the bands over the cycle's traces (`insight`)
3426
3427    /// The machine's modes at the pose its setpoint stands at (where it starts, before any sample), each with its shape
3428    /// and the stiffness it lives in (`insight::mode_views`), for the mode list. The 3D view goes back to the machine's
3429    /// own mode.
3430    pub fn find_modes(&mut self) {
3431        let pose = self.standing().or_else(|| self.config.f64s("start.pose").ok()).unwrap_or_default();
3432        match crate::insight::mode_views(self.entry, &self.config, &pose) {
3433            Ok(views) => {
3434                let small = crate::insight::build(self.entry, &self.config)
3435                    .map(|m| m.modes_small_amplitude(&pose).iter().map(|m| m.hz).collect::<Vec<_>>())
3436                    .ok();
3437                let views_hz: Vec<f64> = views.iter().map(|v| v.hz).collect();
3438                self.insight.small_modes = small.filter(|s| *s != views_hz);
3439                self.insight.modes = Some((self.config.clone(), views));
3440            }
3441            Err(e) => self.say((e.key(), e.detail().to_string())),
3442        }
3443        self.pick_mode(None);
3444    }
3445
3446    /// Shows mode `i` of the mode list swinging in the 3D view; `None`, the machine's own (`Machine::mode_shape`).
3447    pub fn pick_mode(&mut self, i: Option<usize>) {
3448        let shape = i.and_then(|i| Some(self.insight.modes.as_ref()?.1.get(i)?.shape.clone()));
3449        self.insight.picked = i.filter(|_| shape.is_some());
3450        self.session.send(Request::ModeShape(shape));
3451    }
3452
3453    /// The mode list was found for a config that has changed since.
3454    pub fn modes_outdated(&self) -> bool {
3455        self.insight.modes.as_ref().is_some_and(|(config, _)| *config != self.config)
3456    }
3457
3458    /// The mode list as a table: per mode its frequency and damping (in %) as the machine reports them, the mode of the
3459    /// linearised model its shape is of where it is that one's, where the shape comes from, and the kinds of stiffness
3460    /// that hold at least 5 % of its strain energy, largest first. `None` before the modes were asked for.
3461    pub fn modes_table(&self) -> Option<Table> {
3462        let (_, modes) = self.insight.modes.as_ref()?;
3463        let tr = |key: &str| self.tr.tr(key).to_string();
3464        // The small-amplitude frequency (a gearbox's hysteresis stiffness) beside the reported one, where it differs.
3465        let small = self.insight.small_modes.as_ref();
3466        let mut keys = vec!["ui-modes-mode", "ui-modes-hz"];
3467        keys.extend(small.map(|_| "ui-modes-small-hz"));
3468        keys.extend(["ui-modes-damping", "ui-modes-linear", "ui-modes-shape", "ui-modes-stiffness"]);
3469        let mut table = vec![self.header(&keys)];
3470        for (i, m) in modes.iter().enumerate() {
3471            let linear = m.linear.map_or(String::new(), |l| format!("{} · {}", short(l.hz), short(100.0 * l.damping)));
3472            let source = tr(if m.from_machine { "ui-modes-from-machine" } else { "ui-modes-from-linear" });
3473            let stiffness: Vec<String> = m
3474                .stiffness
3475                .iter()
3476                .filter(|(_, share)| *share >= 0.05)
3477                .map(|(kind, share)| format!("{} {:.0} %", tr(&format!("ui-modes-stiffness-{kind}")), 100.0 * share))
3478                .collect();
3479            let mut row = vec![(i + 1).to_string(), short(m.hz)];
3480            row.extend(small.map(|s| s.get(i).map_or(String::new(), |hz| short(*hz))));
3481            row.extend([short(100.0 * m.damping), linear, source, stiffness.join(", ")]);
3482            table.push(row);
3483        }
3484        Some(table)
3485    }
3486
3487    /// What the path that was run can be coloured by: the quantities its run has (`PathQuantity::values`).
3488    pub fn path_quantities(&self) -> Vec<crate::insight::PathQuantity> {
3489        use crate::insight::PathQuantity::*;
3490        let Some(run) = self.path_run.as_ref().map(|p| &p.run) else { return Vec::new() };
3491        let belts =
3492            self.with_machine(|m| m.belt_sections().iter().map(|b| b.id).collect::<Vec<_>>()).unwrap_or_default();
3493        let all = [PathError, TrackingError, Speed].into_iter().chain((0..run.motors.len()).map(Utilisation));
3494        all.chain([BeltTension]).filter(|q| q.values(run, &belts).is_some()).collect()
3495    }
3496
3497    /// A quantity's label: motor k's utilisation with the motor's name.
3498    pub fn path_quantity_label(&self, quantity: crate::insight::PathQuantity) -> String {
3499        let label = self.tr.tr(quantity.key()).to_string();
3500        match quantity {
3501            crate::insight::PathQuantity::Utilisation(k) => match self.session.motors.get(k) {
3502                Some(motor) => format!("{label} · {}", self.tr.tr(motor.key)),
3503                None => label,
3504            },
3505            crate::insight::PathQuantity::TrackingError
3506                if self.path_run.as_ref().is_some_and(|p| p.run.tool_error_is_motor_side()) =>
3507            {
3508                format!("{label} ({})", self.tr.tr("ui-run-motor-side"))
3509            }
3510            _ => label,
3511        }
3512    }
3513
3514    /// The path that was run, coloured by `inputs.path_colour` (`insight::PathColours`): per millisecond of the run the
3515    /// tool's place in the scene (`Machine::scene_point` of the axes' positions) and the quantity's value there, and the
3516    /// sample of its highest value. `None` without a path, a quantity, or a place in the scene for the tool.
3517    pub fn path_colours(&self) -> Option<Arc<crate::insight::PathColours>> {
3518        let quantity = self.inputs.path_colour?;
3519        let run = &self.path_run.as_ref()?.run;
3520        let key = (quantity, run.time().as_ptr() as usize, run.time().len());
3521        if let Some((kept, colours)) = &self.cache.lock().unwrap_or_else(|e| e.into_inner()).path
3522            && *kept == key
3523        {
3524            return colours.clone();
3525        }
3526        let colours = self
3527            .with_machine(|machine| {
3528                let belts: Vec<&str> = machine.belt_sections().iter().map(|b| b.id).collect();
3529                let values = quantity.values(run, &belts)?;
3530                let axes = machine.axes();
3531                let columns: Vec<&[f64]> =
3532                    axes.iter().map(|a| run.column(&format!("axis.{}.position", a.id))).collect::<Option<_>>()?;
3533                let mut pose = vec![0.0; axes.len()];
3534                let points = (0..values.len())
3535                    .map(|i| {
3536                        pose.iter_mut().zip(&columns).for_each(|(p, c)| *p = c[i]);
3537                        machine.scene_point(&pose)
3538                    })
3539                    .collect::<Option<Vec<_>>>()?;
3540                let worst = (0..values.len()).max_by(|&a, &b| values[a].total_cmp(&values[b]))?;
3541                Some(Arc::new(crate::insight::PathColours {
3542                    quantity,
3543                    points,
3544                    time: run.time().to_vec(),
3545                    values,
3546                    worst,
3547                }))
3548            })
3549            .flatten();
3550        self.cache.lock().unwrap_or_else(|e| e.into_inner()).path = Some((key, colours.clone()));
3551        colours
3552    }
3553
3554    /// Every quantity of `path_quantities` at sample `i` of the path that was run, with the time, as a table of label,
3555    /// value and unit.
3556    pub fn path_values_at(&self, i: usize) -> Table {
3557        let Some(run) = self.path_run.as_ref().map(|p| &p.run) else { return Vec::new() };
3558        let belts =
3559            self.with_machine(|m| m.belt_sections().iter().map(|b| b.id).collect::<Vec<_>>()).unwrap_or_default();
3560        let mut table = vec![vec![
3561            self.tr.tr("ui-time").to_string(),
3562            run.time().get(i).map_or(String::new(), |t| short(*t)),
3563            "s".into(),
3564        ]];
3565        for quantity in self.path_quantities() {
3566            let value = quantity.values(run, &belts).and_then(|v| v.get(i).copied());
3567            // As the path tab's scale shows them: errors in mm, the utilisation in %.
3568            let (factor, unit) = match quantity.unit() {
3569                "" => (100.0, "%"),
3570                "m" => (1e3, "mm"),
3571                unit => (1.0, unit),
3572            };
3573            let shown = value.map(|v| v * factor);
3574            table.push(vec![self.path_quantity_label(quantity), shown.map_or(String::new(), short), unit.to_string()]);
3575        }
3576        table
3577    }
3578
3579    /// Runs the cycle with each bounded value at its bounds in the background and keeps their traces' envelope
3580    /// (`insight::band_runs`); the answer comes with `poll`.
3581    pub fn trace_bands(&mut self) {
3582        let (entry, config) = (self.entry, self.config.clone());
3583        self.insight.band_job = Some(Job::spawn(move |progress| {
3584            let runs =
3585                crate::insight::band_runs(entry, &config, progress).map_err(|e| (e.key(), e.detail().to_string()));
3586            runs.map(|runs| (config, runs))
3587        }));
3588    }
3589
3590    /// The bounds runs are being run.
3591    pub fn bands_tracing(&self) -> bool {
3592        self.insight.band_job.is_some()
3593    }
3594
3595    /// The bounds runs are of a config that has changed since.
3596    pub fn bands_outdated(&self) -> bool {
3597        self.insight.band_runs.as_ref().is_some_and(|(config, _)| *config != self.config)
3598    }
3599
3600    /// The traces of the bounds runs for the plots: per traced signal its title with the unit, the nominal trace
3601    /// (time, value) with its peaks kept (`plot_line`), and the envelope in at most `BAND_BUCKETS` stretches, each from
3602    /// its first time to the next one's with the lowest and highest value of the stretch: [t0, t1, low, high].
3603    pub fn band_plots(&self) -> Vec<(String, Vec<[f64; 2]>, Vec<[f64; 4]>)> {
3604        let Some((_, runs)) = &self.insight.band_runs else { return Vec::new() };
3605        runs.traces
3606            .iter()
3607            .map(|trace| {
3608                let title = self.signal_label(&trace.signal);
3609                let n = trace.low.len().min(trace.time.len());
3610                let nominal = plot_line(trace.nominal.len(), |i| [trace.time[i], trace.nominal[i]]);
3611                let every = n.div_ceil(BAND_BUCKETS).max(1);
3612                let stretches = (0..n)
3613                    .step_by(every)
3614                    .map(|from| {
3615                        let to = (from + every).min(n);
3616                        let low = trace.low[from..to].iter().copied().fold(f64::INFINITY, f64::min);
3617                        let high = trace.high[from..to].iter().copied().fold(f64::NEG_INFINITY, f64::max);
3618                        [trace.time[from], trace.time[to.min(n - 1)], low, high]
3619                    })
3620                    .collect();
3621                (title, nominal, stretches)
3622            })
3623            .collect()
3624    }
3625
3626    /// Per motor the operating points of the bounds runs (speed in the unit chosen, torque), for the cloud on the
3627    /// torque-speed view; empty before the bounds were run.
3628    pub fn band_points(&self) -> Vec<Vec<[f64; 2]>> {
3629        let Some((_, runs)) = &self.insight.band_runs else { return Vec::new() };
3630        runs.points
3631            .iter()
3632            .enumerate()
3633            .map(|(k, points)| {
3634                let rpm = self.motor_speed_scale(k);
3635                points.iter().map(|[w, t]| [w * rpm, *t]).collect()
3636            })
3637            .collect()
3638    }
3639
3640    /// Every translation key the panels and the 3D view can show for the current machine.
3641    pub fn keys_in_use(&self) -> Vec<String> {
3642        let mut keys = vec![self.entry.key.to_string()];
3643        keys.extend(MACHINES.iter().map(|m| m.key.to_string()));
3644        keys.extend(self.session.signals.iter().flat_map(|s| [s.owner_key.clone(), s.quantity_key.clone()]));
3645        keys.extend(self.scopes.iter().map(|s| s.quantity_key.clone()));
3646        keys.extend(self.scene.labels.iter().flat_map(|l| [l.owner_key.to_string(), l.unit_key.to_string()]));
3647        keys.extend(self.effects().into_iter().map(|(_, key, _)| key));
3648        for group in self.param_groups() {
3649            keys.push(group.key);
3650            keys.extend(group.params.into_iter().map(|(_, key, _)| key));
3651        }
3652        let headers = [
3653            &CYCLE_KEYS[..],
3654            &MOTOR_KEYS,
3655            &LIFE_KEYS,
3656            &VERDICT_KEYS,
3657            &BAND_KEYS,
3658            &WORST_KEYS,
3659            &SENSITIVITY_KEYS,
3660            &OPTIMISED_KEYS,
3661            &SEARCH_KEYS,
3662            &TRACE_KEYS,
3663            &FIT_KEYS,
3664            &FIT_QUANTITIES,
3665            &FIT_DETAIL_KEYS,
3666            &IDENTIFY_KEYS,
3667            &NOTES,
3668            &SWEEP_KEYS,
3669            &POINTS_KEYS,
3670            &OVERLAY_KEYS,
3671            &BREAKDOWN_KEYS,
3672            &FRICTION_KEYS,
3673            &EFFECT_KEYS,
3674            &VIEW_KEYS,
3675            &RUN_KEYS,
3676            &crate::insight::KEYS,
3677        ];
3678        keys.extend(headers.concat().into_iter().map(String::from));
3679        keys.extend(
3680            [
3681                "ui-analysis-ok",
3682                "ui-analysis-fail",
3683                "fit-axis-skipped",
3684                "fit-mass",
3685                "fit-viscous",
3686                "fit-coulomb",
3687                "fit-constant",
3688                "fit-stiffness",
3689                "fit-no-resonance",
3690            ]
3691            .map(String::from),
3692        );
3693        keys.extend(
3694            [
3695                "fit-joints-skipped",
3696                "fit-payload",
3697                "fit-joint-inertia",
3698                "fit-joint-viscous",
3699                "fit-joint-coulomb",
3700                "fit-joint-constant",
3701                "fit-alike",
3702                "fit-payload-step",
3703                "fit-axis-payload-step",
3704                "fit-link-mass",
3705                "fit-link-moment",
3706                "fit-combined",
3707                "fit-no-effect",
3708                "ui-trace-payload-step",
3709            ]
3710            .map(String::from),
3711        );
3712        keys.extend(
3713            [
3714                "fit-move-not-excited",
3715                "fit-move-no-key",
3716                "fit-move-stiffness",
3717                "ui-trace-payload",
3718                "ui-trace-stiffness-factor",
3719                "ui-trace-stiffness",
3720                "ui-trace-stiffness-hint",
3721            ]
3722            .map(String::from),
3723        );
3724        keys.extend(
3725            ["payload_factor"]
3726                .iter()
3727                .chain(&sim_components::identify::PAYLOAD_STEP_QUANTITIES)
3728                .chain(&sim_components::identify::JOINT_QUANTITIES)
3729                .chain(&sim_components::identify::LINK_QUANTITIES)
3730                .map(|q| joint_label(q)),
3731        );
3732        keys.extend(CHECKS.iter().map(|check| format!("check-{check}")));
3733        keys.extend(QUANTITIES.iter().map(|name| format!("identify-{name}")));
3734        keys.extend(["error-import-map", "error-import-signal", "error-import-unit"].map(String::from));
3735        let budget = self.cycle_report.as_ref().and_then(|(load, ..)| load.budget.as_ref());
3736        keys.extend(
3737            budget.into_iter().flat_map(|b| b.rows.iter().flat_map(|r| [r.owner_key.clone(), r.quantity_key.clone()])),
3738        );
3739        keys
3740    }
3741}
3742
3743#[cfg(test)]
3744mod tests {
3745    use super::*;
3746    use std::time::{Duration, Instant};
3747
3748    /// 9.9996 rounds up to 10.00 (four digits), not 10.000; a failing 1.0004 against 1.000 shows the difference
3749    /// (1.0004e0 against 1.0000e0), a passing one does not; only plain SI units take a prefix.
3750    #[test]
3751    fn numbers_keep_four_digits_and_failing_checks_show_their_difference() {
3752        assert_eq!(short(9.9996), "10.00");
3753        assert_eq!(short(1.0004), "1.000");
3754        assert_eq!(short_pair(1.0004, 1.0, false), ("1.0004e0".to_string(), "1.0000e0".to_string()));
3755        assert_eq!(short_pair(1.0004, 1.0, true), ("1.000".to_string(), "1.000".to_string()));
3756        assert_eq!(display_scale(0.05, "%"), (1.0, ""));
3757        assert_eq!(display_scale(0.05, "1/h"), (1.0, ""));
3758        assert_eq!(display_scale(0.05, "m"), (1e3, "m"));
3759    }
3760
3761    /// A background job whose thread ended without an answer (it panicked) left no message: the analysis
3762    /// was dropped without a word, and the tuning's spinner turned for ever.
3763    #[test]
3764    fn a_job_that_ends_without_an_answer_is_reported() {
3765        let mut model = Model::new(MACHINES[0], "en");
3766        // What is left of a thread that panicked: the receiving end of its channel.
3767        model.analysis_jobs.push((Analysis::Cycle, model.config.clone(), Job::of(channel().1)));
3768        model.tuning_job = Some(Job::of(channel().1));
3769        assert!(model.analysis_running() && model.tuning_running());
3770        model.poll();
3771        assert!(!model.analysis_running() && !model.tuning_running());
3772        assert_eq!(model.messages.last(), Some(&("ui-job-ended", String::new())), "{:?}", model.messages);
3773        // A job that answers is taken as before.
3774        let (result, job) = channel();
3775        result.send(Err(("error-busy", String::new()))).unwrap();
3776        model.analysis_jobs.push((Analysis::Cycle, model.config.clone(), Job::of(job)));
3777        model.poll();
3778        assert_eq!((model.analysis_running(), model.messages.last().unwrap().0), (false, "error-busy"));
3779    }
3780
3781    /// A simulation thread that is gone (it panicked) left a frozen view and no message. It is reported, once.
3782    #[test]
3783    fn a_simulation_thread_that_ends_is_reported_once() {
3784        let mut model = Model::new(MACHINES[0], "en");
3785        model.poll();
3786        let reports = |model: &Model| model.messages.iter().filter(|m| m.0 == "ui-simulation-ended").count();
3787        assert_eq!(reports(&model), 0);
3788        // The thread ends while the session lives, which nothing but a panic does to it otherwise.
3789        model.session.send(Request::Quit);
3790        let start = Instant::now();
3791        while !model.session.ended() && start.elapsed() < Duration::from_secs(5) {
3792            std::thread::sleep(Duration::from_millis(5));
3793        }
3794        model.poll();
3795        assert_eq!(reports(&model), 1, "{:?}", model.messages);
3796        model.command(Command::MoveTo(Vec::new()));
3797        model.set_param("no.such_value", Value::Float(1.0));
3798        model.poll();
3799        assert_eq!(reports(&model), 1, "{:?}", model.messages);
3800    }
3801}