1use 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
39pub const HISTORY: usize = 60_000;
41
42pub type Message = (&'static str, String);
44
45pub struct ParamGroup {
47 pub key: String,
48 pub params: Vec<(String, String, Value)>,
50}
51
52pub struct ScopeLine {
53 pub signal: usize,
55 pub reference: bool,
57}
58
59pub struct Scope {
61 pub quantity_key: String,
62 pub unit: String,
63 pub lines: Vec<ScopeLine>,
64 pub visible: bool,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq)]
69pub struct Stats {
70 pub min: f64,
71 pub max: f64,
72 pub rms: f64,
73}
74
75pub struct Tuning {
77 pub axis: usize,
78 pub step: StepResponse,
79 pub response: Vec<SweepPoint>,
80 pub bandwidth: Option<f64>,
81 pub modes: Vec<(f64, Vec<Mode>)>,
84}
85
86pub const MODE_POINTS: usize = 41;
88
89#[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#[derive(Debug, Clone, Copy, PartialEq)]
101pub enum Analysis {
102 Cycle,
104 Sensitivity,
106 Optimise,
108 Search,
110 Path,
112 Trace,
114 Sweep,
116 SweepFit,
118 Compare,
120}
121
122#[derive(Debug, Clone, PartialEq)]
124pub struct Inputs {
125 pub bands: bool,
127 pub samples: usize,
130 pub worst: bool,
132 pub supply: String,
135 pub series: String,
136 pub gearboxes: String,
137 pub axes: bool,
138 pub search: crate::search_views::SearchInputs,
140 pub map: crate::search_views::MapInputs,
142 pub path_file: String,
145 pub path_timed: bool,
146 pub time_optimal: bool,
147 pub trace_file: String,
148 pub trace_map: String,
150 pub trace_stiffness: bool,
152 pub config_file: String,
154 pub parts: [String; 6],
156 pub sweep_from: f64,
159 pub sweep_to: f64,
160 pub sweep_count: usize,
161 pub sweep_amplitude: f64,
162 pub sweep_file: String,
164 pub sweep_motor: usize,
165 pub compare_effect: String,
167 pub compare_quantity: String,
168 pub workspace_z: Option<f64>,
170 pub workspace_by: crate::insight::WorkspaceColour,
173 pub path_colour: Option<crate::insight::PathQuantity>,
174 pub path_probe: Option<usize>,
176 pub assignment: String,
178 pub param_filter: String,
180 pub run_set: String,
183 pub run_file: String,
184}
185
186pub const SUPPLIES: &[&str] = sim_components::catalog::SUPPLIES;
188
189pub struct PathRun {
191 pub points: Vec<(f64, Vec<f64>)>,
192 pub scene_line: Vec<[f64; 3]>,
195 pub load: CycleLoad,
196 pub verdicts: Vec<Verdict>,
197 pub deviation: f64,
200 pub deviations: Vec<f64>,
202 pub curves: Curves,
204 pub run: Run,
207}
208
209pub type Curves = Vec<sim_components::charts::TorqueSpeed>;
211
212pub 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)] enum Report {
230 Cycle(CycleLoad, Vec<Verdict>, Option<Vec<Band>>, usize, Curves, Option<(Vec<Worst>, Vec<String>)>, Run),
235 Sensitivity(CycleLoad, Vec<Sensitivity>),
236 Optimised(Optimised),
237 Search(crate::search_views::Found, String),
239 Path(PathRun, Run),
241 Trace(TraceFit),
242 Sweep(Vec<Vec<SweepPoint>>),
243 SweepFit(usize, SweepFit),
245 Compare(String, Comparison),
247}
248
249pub(crate) struct Job<T> {
253 answer: Mutex<Receiver<Result<T, Message>>>,
254 pub(crate) progress: Arc<Progress>,
255}
256
257fn cancelled_message() -> Message {
259 ("ui-job-cancelled", String::new())
260}
261
262impl<T: Send + 'static> Job<T> {
263 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 pub(crate) fn cancel(&self) {
279 self.progress.cancel.store(true, Relaxed);
280 }
281
282 #[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
295pub(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
309pub type Table = Vec<Vec<String>>;
311
312const 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];
330const 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];
345const 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"];
385fn joint_label(quantity: &str) -> String {
387 format!("ui-trace-{}", quantity.replace('_', "-"))
388}
389const FIT_QUANTITIES: [&str; 4] = ["ui-trace-mass", "ui-trace-viscous", "ui-trace-coulomb", "ui-trace-constant"];
391const FIT_DETAIL_KEYS: [&str; 3] =
393 ["ui-trace-held-force-n", "ui-trace-breakaway-force-n", "ui-trace-presliding-stiffness-n-m"];
394const IDENTIFY_KEYS: [&str; 5] =
396 ["ui-analysis-motor", "ui-trace-quantity", "ui-identify-value", "ui-trace-error", "ui-identify-interval"];
397const SWEEP_KEYS: [&str; 2] = ["ui-sweep-resonance", "ui-sweep-damping"];
399const POINTS_KEYS: [&str; 3] = ["ui-analysis-motor", "ui-points-speed", "ui-points-torque"];
401const OVERLAY_KEYS: [&str; 3] = ["ui-overlay-torque", "ui-overlay-speed", "ui-overlay-error"];
403
404const 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
435pub type Overlay = Vec<(&'static str, Vec<[Vec<[f64; 2]>; 2]>)>;
438
439#[derive(Default)]
442struct Cache {
443 stats: Option<((u64, u64, u64), Arc<Vec<Option<Stats>>>)>,
446 machine: Option<(Config, Option<Box<dyn Machine>>)>,
448 motor_speed: Option<(Config, Vec<f64>)>,
450 workspace: Option<((Config, Option<u64>, usize), Option<Arc<WorkspaceSlice>>)>,
452 path: Option<((crate::insight::PathQuantity, usize, usize), Option<Arc<crate::insight::PathColours>>)>,
454}
455
456fn 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
470pub 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
487pub struct RunPlot {
490 pub quantity: Quantity,
491 pub title: String,
493 pub lines: Vec<RunLine>,
494 pub differences: Vec<RunLine>,
495}
496
497pub struct RunLine {
499 pub run: usize,
500 pub motor: usize,
501 pub name: String,
502 pub points: Vec<[f64; 2]>,
503}
504
505fn 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
521fn 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
535pub 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 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
570fn 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 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}
587const 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];
621const 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"];
632const 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];
691const BREAKDOWN_KEYS: [&str; 5] = [
693 "quantity-torque-inertia",
694 "quantity-torque-gravity",
695 "quantity-torque-friction",
696 "quantity-torque-rest",
697 "quantity-torque",
698];
699const FRICTION_KEYS: [&str; 3] =
701 ["quantity-friction-coulomb", "quantity-friction-viscous", "quantity-friction-stiction"];
702const 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
728const 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
762pub use sim_core::scene::{heat_color, part_color};
764
765pub struct ThermalView {
769 pub lines: Vec<(String, Vec<[f64; 2]>)>,
771 pub table: Table,
772 pub off: bool,
774}
775
776pub struct BeltView {
779 pub tension: Vec<(String, Vec<[f64; 2]>)>,
781 pub stretch: Vec<(String, Vec<[f64; 2]>)>,
782 pub pretension: f64,
783 pub rating: Option<f64>,
785 pub table: Table,
786 pub titles: [String; 2],
789 pub scale: [String; 2],
790}
791
792pub struct CompareView {
795 pub effect: String,
797 pub title: String,
798 pub lines: Vec<(String, Vec<[f64; 2]>, Vec<[f64; 2]>)>,
800 pub table: Table,
801}
802
803pub struct WorkspaceSlice {
805 pub x: (f64, f64),
807 pub y: (f64, f64),
808 pub z: f64,
809 pub n: usize,
811 pub nodes: Vec<(f64, bool)>,
815 pub limit: f64,
817 pub heights: (f64, f64),
819 pub acceleration: Vec<f64>,
822}
823
824pub struct FrictionView {
826 pub title: String,
828 pub curves: [(String, Vec<[f64; 2]>); 4],
831 pub now: Option<[f64; 2]>,
833 pub table: Table,
835 pub rotary: bool,
837}
838
839pub const BAND_BUCKETS: usize = 600;
841
842const TOP_ROWS: usize = 8;
844
845const UNDO_STEPS: usize = 50;
847
848const SAME_EDIT: std::time::Duration = std::time::Duration::from_millis(600);
850
851pub 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 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
869pub 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 pub config: Config,
886 config_text: String,
889 pub file: String,
893 accepted: Config,
896 sent: VecDeque<Config>,
897 clean: Config,
899 default: Config,
901 undone: Vec<Config>,
903 redone: Vec<Config>,
904 last_edit: Option<(String, std::time::Instant)>,
906 pub session: Session,
907 ended: bool,
909 pub scopes: Vec<Scope>,
910 pub history: History,
911 pub frozen: Option<History>,
914 freezes: u64,
916 pub runs: RunStore,
918 pub units: Units,
919 run_jobs: Vec<Job<Run>>,
921 export_jobs: Vec<Job<Message>>,
922 overlay: Overlay,
924 cache: Mutex<Cache>,
925 pub window_s: f64,
927 pub scene: Scene,
928 pub paused: bool,
929 pub speed: f64,
930 pub exaggeration: f64,
932 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 report_job: Option<Job<Message>>,
940 pub inputs: Inputs,
941 pub cycle_report: Option<(CycleLoad, Vec<Verdict>, Curves)>,
944 pub bands: Option<Vec<Band>>,
946 pub band_samples: usize,
948 pub worst: Option<(Vec<Worst>, Vec<String>)>,
950 pub sensitivity: Option<(CycleLoad, Vec<Sensitivity>)>,
952 pub optimised: Option<Optimised>,
953 pub candidates: Option<(Vec<Candidate>, String)>,
955 pub path_run: Option<PathRun>,
956 pub trail: Option<Vec<[f64; 3]>>,
960 pub trace_fit: Option<TraceFit>,
961 pub sweeps: Option<Vec<Vec<SweepPoint>>>,
963 pub sweep_fit: Option<(usize, SweepFit)>,
965 pub comparison: Option<(String, Comparison)>,
967 pub views: crate::search_views::Views,
969 pub loop_response: crate::frequency::LoopResponse,
971 computed_for: [Option<Config>; 9],
974 analysis_jobs: Vec<(Analysis, Config, Job<Report>)>,
976 pub insight: crate::insight::Insight,
978}
979
980fn 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
991fn 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 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 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
1034fn actual_quantity(quantity_key: &str) -> Option<&str> {
1036 quantity_key.strip_suffix("-setpoint").or_else(|| quantity_key.strip_suffix("-command"))
1037}
1038
1039fn 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
1063pub fn display_scale(peak: f64, unit: &str) -> (f64, &'static str) {
1066 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 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 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 pub fn set_machine(&mut self, entry: &'static MachineEntry) {
1198 let fresh = Self::new(entry, self.lang);
1199 self.restart(fresh);
1200 }
1201
1202 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 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 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 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 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 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 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 fn say(&mut self, message: Message) {
1366 if self.messages.last() != Some(&message) {
1367 self.messages.push(message);
1368 }
1369 }
1370
1371 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 fn reconfigure(&mut self) {
1382 self.sent.push_back(self.config.clone());
1383 self.session.send(Request::Reconfigure(self.config.clone()));
1384 }
1385
1386 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 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 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 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 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 pub fn undo(&mut self) {
1447 self.step_history(true);
1448 }
1449
1450 pub fn redo(&mut self) {
1452 self.step_history(false);
1453 }
1454
1455 fn step_history(&mut self, back: bool) {
1456 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 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 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 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 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 Err(message) => {
1533 self.config = self.accepted.clone();
1534 self.say(message);
1535 }
1536 }
1537 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 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 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 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 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 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 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 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 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 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 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 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 pub fn exporting(&self) -> bool {
1766 !self.export_jobs.is_empty()
1767 }
1768
1769 pub fn rated(&self, run: Run) -> Run {
1774 self.rated_with(run, &self.config)
1775 }
1776
1777 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 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 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 pub fn recording_runs(&self) -> bool {
1823 !self.run_jobs.is_empty()
1824 }
1825
1826 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 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 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 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 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 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 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 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 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 pub fn tuning_running(&self) -> bool {
2021 self.tuning_job.is_some()
2022 }
2023
2024 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn overlay(&self) -> &Overlay {
2752 &self.overlay
2753 }
2754
2755 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 pub fn points_table(&self, rows: std::ops::Range<usize>) -> Option<(usize, Table)> {
2769 let (load, _, _) = self.cycle_report.as_ref()?;
2770 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 pub fn speed_label(&self) -> String {
2793 self.speed_label_of(self.motors_linear())
2794 }
2795
2796 pub fn torque_label(&self) -> String {
2798 self.torque_label_of(self.motors_linear())
2799 }
2800
2801 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 pub fn motor_is_linear(&self, k: usize) -> bool {
2817 self.session.motor_linear.get(k).copied().unwrap_or(false)
2818 }
2819
2820 pub fn motor_speed_label(&self, k: usize) -> String {
2822 self.speed_label_of(self.motor_is_linear(k))
2823 }
2824
2825 pub fn motor_torque_label(&self, k: usize) -> String {
2827 self.torque_label_of(self.motor_is_linear(k))
2828 }
2829
2830 pub fn motors_linear(&self) -> bool {
2832 !self.session.motor_linear.is_empty() && self.session.motor_linear.iter().all(|l| *l)
2833 }
2834
2835 pub fn speed_scale(&self) -> f64 {
2837 if self.motors_linear() { 1.0 } else { self.units.scale("rad/s").0 }
2838 }
2839
2840 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 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 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 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 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 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 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 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 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 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 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 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 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 fn latest(&self, id: &str) -> Option<f64> {
3094 Some(self.history.back()?[self.session.signals.iter().position(|s| s.id == id)?])
3095 }
3096
3097 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 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 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 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 §ions {
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn modes_outdated(&self) -> bool {
3455 self.insight.modes.as_ref().is_some_and(|(config, _)| *config != self.config)
3456 }
3457
3458 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 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 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 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 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 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 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 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 pub fn bands_tracing(&self) -> bool {
3592 self.insight.band_job.is_some()
3593 }
3594
3595 pub fn bands_outdated(&self) -> bool {
3597 self.insight.band_runs.as_ref().is_some_and(|(config, _)| *config != self.config)
3598 }
3599
3600 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 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 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 #[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 #[test]
3764 fn a_job_that_ends_without_an_answer_is_reported() {
3765 let mut model = Model::new(MACHINES[0], "en");
3766 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 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 #[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 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}