Skip to main content

sim_app/
search_views.rs

1//! The search workflow in the app beside the ranked table of the search tab: every option `sim-cli search` takes
2//! (`SearchInputs`), the figures of each candidate as a heat map of its checks (`heatmap`), cost against margin with the
3//! front (`scatter`), the top candidates' operating points on their torque-speed curves (`Found::curves`) and why each
4//! failed (`failures`); the sweep of a gear ratio or pulley radius (`sim-cli transmission`) and the comparison of
5//! kinematics on one task (`sim-cli compare-kinematics`); and for the path tab maps of peak torque and following error
6//! over a plane of the workspace, from a grid of short moves (`move_map`). The window draws them in `ui/search_views.rs`.
7
8use crate::model::{Curves, Inputs, Job, Message, Table, short};
9use sim_components::analysis::{Progress, Verdict, utilisation};
10use sim_components::catalog::{self, Candidate, Drives, Options, SUPPLIES, vendor_of};
11use sim_components::search::{self, KinematicsRow, Task, TransmissionSweep};
12use sim_components::{Command, Sim};
13use sim_core::{Config, ConfigError, MachineEntry, Translations};
14use sim_machines::MACHINES;
15use std::sync::Arc;
16use std::sync::atomic::Ordering::Relaxed;
17
18/// The search's options beyond those of `Inputs` (supply, series, gearbox series, axes), as `sim-cli search` takes them,
19/// and the inputs of the ratio sweep and of the kinematics comparison.
20#[derive(Debug, Clone, PartialEq)]
21pub struct SearchInputs {
22    /// A maker (`vendor_of`): every supply of that maker is searched, ranked together; "all" every supply of every
23    /// maker; "" the supply of `Inputs` alone.
24    pub vendor: String,
25    /// The drives tried with each motor (`--drives`).
26    pub drives: Drives,
27    /// The ranking of the passing ones (`--rank-by`, `search::parse_ranking`): "cost", or "cost=1,energy=0.5".
28    pub rank_by: String,
29    /// The duty mix beside the config shown, which is its first duty with weight 1: config files of the machine with
30    /// their weights, "file.toml=2; other.toml" (weight 1 without); "" for the config's cycle alone.
31    pub duties: String,
32    /// One motor of a machine with several (`--motor-id`); "" for every motor.
33    pub motor: String,
34    /// How many of the best candidates' operating points are drawn on their torque-speed curves.
35    pub top: usize,
36    /// Ratio sweep: `gearbox.ratio` or `geometry.pulley_radius_m`, swept from `from` to `to` (0 each: half and twice
37    /// the config's) in `count` values; with `snap` (a gearbox series) the catalogue gearboxes of it around the best ratio.
38    pub sweep_key: String,
39    pub sweep_from: f64,
40    pub sweep_to: f64,
41    pub sweep_count: usize,
42    pub sweep_snap: String,
43    /// Kinematics comparison: the task file (`search::Task`) and the machines' ids, separated by ","; "" for the
44    /// machine shown.
45    pub task_file: String,
46    pub machines: String,
47}
48
49impl Default for SearchInputs {
50    fn default() -> Self {
51        Self {
52            vendor: String::new(),
53            drives: Drives::Paired,
54            rank_by: "cost".into(),
55            duties: String::new(),
56            motor: String::new(),
57            top: 3,
58            sweep_key: "gearbox.ratio".into(),
59            sweep_from: 0.0,
60            sweep_to: 0.0,
61            sweep_count: 9,
62            sweep_snap: String::new(),
63            task_file: String::new(),
64            machines: String::new(),
65        }
66    }
67}
68
69/// The workspace maps of the path tab: the plane (two axes), the axis the short move goes along, how far (in its
70/// unit), and the nodes per side of the grid.
71#[derive(Debug, Clone, PartialEq)]
72pub struct MapInputs {
73    pub plane: [usize; 2],
74    pub axis: usize,
75    pub distance: f64,
76    pub n: usize,
77}
78
79impl Default for MapInputs {
80    fn default() -> Self {
81        Self { plane: [0, 1], axis: 0, distance: 0.0, n: 7 }
82    }
83}
84
85/// The makers of the supplies, each once, in the order of `SUPPLIES`.
86pub fn vendors() -> Vec<&'static str> {
87    let mut out: Vec<&'static str> = Vec::new();
88    for supply in SUPPLIES {
89        let vendor = vendor_of(supply);
90        if !out.contains(&vendor) {
91            out.push(vendor);
92        }
93    }
94    out
95}
96
97/// The supplies a search runs at: with a maker every one of that maker's ("all": every one), else `supply` alone.
98/// Empty where neither names one of `SUPPLIES`.
99pub fn supplies(vendor: &str, supply: &str) -> Vec<&'static str> {
100    SUPPLIES
101        .iter()
102        .copied()
103        .filter(|s| match vendor {
104            "" => *s == supply,
105            "all" => true,
106            vendor => vendor_of(s) == vendor,
107        })
108        .collect()
109}
110
111/// A search's result: the candidates ranked (`search::rank_by`), and for the first `SearchInputs::top` of them that ran
112/// their motor's torque-speed curves (`None` where its config does not build again).
113pub struct Found {
114    pub candidates: Vec<Candidate>,
115    pub curves: Vec<Option<Curves>>,
116}
117
118fn refused(e: ConfigError) -> Message {
119    (e.key(), e.detail().to_string())
120}
121
122/// The duty mix of `SearchInputs::duties` beside `config`, the first duty: each file read as a config of the machine
123/// with its parts resolved. Empty for none.
124fn duty_mix(entry: &MachineEntry, config: &Config, text: &str) -> Result<Vec<(Config, f64)>, Message> {
125    let files: Vec<&str> = text.split(';').map(str::trim).filter(|f| !f.is_empty()).collect();
126    if files.is_empty() {
127        return Ok(Vec::new());
128    }
129    let mut out = vec![(catalog::resolve(entry, config).map_err(refused)?, 1.0)];
130    for part in files {
131        let (file, weight) = part.rsplit_once('=').map_or((part, "1"), |(f, w)| (f.trim(), w.trim()));
132        let weight: f64 = weight
133            .parse()
134            .ok()
135            .filter(|w: &f64| *w > 0.0 && w.is_finite())
136            .ok_or_else(|| ("ui-search-bad-duty", part.to_string()))?;
137        let bytes = std::fs::read(file).map_err(|e| ("ui-file-unreadable", format!("{file}: {e}")))?;
138        let text = sim_components::import::decode(&bytes);
139        let cfg = sim_components::load_config(entry, &text).map_err(refused)?;
140        out.push((catalog::resolve(entry, &cfg).map_err(refused)?, weight));
141    }
142    Ok(out)
143}
144
145/// The search of the search tab, as `sim-cli search` runs it with the same options: at the supplies of `supplies`,
146/// with `inputs.series` and `inputs.gearboxes`, every axis (`inputs.axes`) or one motor, the drives and the duty mix of
147/// `SearchInputs`, ranked by its `rank_by`. A search that finds nothing to try says why.
148pub fn run_search(entry: &MachineEntry, config: &Config, inputs: &Inputs) -> Result<Found, Message> {
149    let s = &inputs.search;
150    let at = supplies(&s.vendor, &inputs.supply);
151    if at.is_empty() {
152        return Err(("ui-search-bad-supply", format!("{} {}", s.vendor, inputs.supply).trim().to_string()));
153    }
154    // No price list here: `price` would rank every candidate as unpriced, in the weight order without a word.
155    let by = search::parse_ranking(&s.rank_by)
156        .filter(|by| by.iter().all(|(c, _)| *c != search::Criterion::Price))
157        .ok_or_else(|| ("ui-search-bad-rank", s.rank_by.clone()))?;
158    let motor = Some(s.motor.trim()).filter(|m| !m.is_empty());
159    if motor.is_some() && inputs.axes {
160        return Err(("ui-search-motor-axes", String::new()));
161    }
162    let duties = duty_mix(entry, config, &s.duties)?;
163    // With a mix the first duty's config is searched on, as the command line does.
164    let config = duties.first().map_or(config, |(first, _)| first);
165    let (series, gearboxes) = (inputs.series.trim(), Some(inputs.gearboxes.trim()).filter(|g| !g.is_empty()));
166    let wanted = |article: &str| article.starts_with(series);
167    let options = Options { gearboxes, axes: inputs.axes, motor, drives: s.drives, duties: &duties };
168    let motors: Vec<&str> =
169        at.iter().flat_map(|supply| catalog::motor_articles_for(supply)).filter(|a| wanted(a)).collect();
170    // A gearbox series with nothing for any of them: the search would try each with the config's own gearbox instead
171    // (`catalog::search` since 14 November 2026), which is not what was asked.
172    let fits_none =
173        |series: &&str| motors.iter().all(|article| catalog::gearboxes_for_motor(article, series).is_empty());
174    if let Some(gearboxes) = gearboxes.filter(|g| !motors.is_empty() && fits_none(g)) {
175        return Err(("ui-search-no-gearbox", gearboxes.to_string()));
176    }
177    let mut found = catalog::search(entry, config, &at, &wanted, &options).map_err(refused)?;
178    if found.iter().all(|c| c.article.is_empty()) {
179        // Motors there are, so it is the gearbox series that has nothing for them.
180        return Err(match gearboxes.filter(|_| !motors.is_empty()) {
181            Some(gearboxes) => ("ui-search-no-gearbox", gearboxes.to_string()),
182            None => ("ui-search-none", series.to_string()),
183        });
184    }
185    search::rank_by(&mut found, &by);
186    let curves = found
187        .iter()
188        .filter(|c| c.result.is_some())
189        .take(s.top)
190        .map(|c| {
191            let sim = Sim::new(entry, &catalog::candidate_config(entry, config, c).ok()?).ok()?;
192            // One motor's search: that motor's own drive and motor data.
193            let k = sim.machine.motors().iter().position(|m| m.id == c.motor).unwrap_or(0);
194            let drive = sim.control.drive_params_of(k);
195            Some(vec![sim_components::charts::torque_speed(drive, sim_components::charts::dc_link_of(drive, None))])
196        })
197        .collect();
198    Ok(Found { candidates: found, curves })
199}
200
201/// The candidates × checks heat map: every check of any candidate in the order they first come up, and per candidate
202/// in the order of the ranking its utilisation of each (`Figures::checks`, above 1 it fails), NaN where it has none.
203pub struct Heatmap {
204    pub checks: Vec<&'static str>,
205    pub rows: Vec<Vec<f64>>,
206}
207
208pub fn heatmap(found: &[Candidate]) -> Heatmap {
209    let mut checks: Vec<&'static str> = Vec::new();
210    for (check, _) in found.iter().filter_map(|c| c.figures.as_ref()).flat_map(|f| &f.checks) {
211        if !checks.contains(check) {
212            checks.push(check);
213        }
214    }
215    let rows = found
216        .iter()
217        .map(|c| {
218            let of = |check: &str| c.figures.as_ref()?.checks.iter().find(|(k, _)| *k == check).map(|(_, u)| *u);
219            checks.iter().map(|check| of(check).unwrap_or(f64::NAN)).collect()
220        })
221        .collect();
222    Heatmap { checks, rows }
223}
224
225/// One candidate in the scatter of cost against margin: its place in the ranking, its cost (installed mass, kg), its
226/// worst margin (1 less the tightest check's utilisation: below 0 it fails), its energy per cycle (J, NaN without
227/// figures), whether it passes, and whether it is on the front (`search::front`).
228#[derive(Debug, Clone, PartialEq)]
229pub struct ScatterPoint {
230    pub index: usize,
231    pub cost: f64,
232    pub margin: f64,
233    pub energy: f64,
234    pub passes: bool,
235    pub front: bool,
236}
237
238/// The candidates that ran, finite in cost and margin (a tripped drive is infinitely far beyond), as `ScatterPoint`s.
239pub fn scatter(found: &[Candidate]) -> Vec<ScatterPoint> {
240    let front = search::front(found);
241    found
242        .iter()
243        .enumerate()
244        .filter_map(|(index, c)| {
245            let margin = 1.0 - c.tightest()?.1;
246            let energy = c.figures.as_ref().map_or(f64::NAN, |f| f.energy_j);
247            (margin.is_finite() && c.cost.is_finite()).then_some(ScatterPoint {
248                index,
249                cost: c.cost,
250                margin,
251                energy,
252                passes: c.passes(),
253                front: front[index],
254            })
255        })
256        .collect()
257}
258
259/// Why a candidate failed: its checks that fail, with value, limit and utilisation; empty for one that passes or did
260/// not run.
261pub fn failures(c: &Candidate) -> Vec<&Verdict> {
262    c.result.as_ref().map_or(Vec::new(), |(_, verdicts)| verdicts.iter().filter(|v| !v.ok).collect())
263}
264
265/// A failing check as a line: the check, the motor it concerns, value, limit and utilisation.
266pub fn failure_line(tr: &Translations, v: &Verdict, motor_keys: &[&str], linear: &[bool]) -> String {
267    let motor = v.motor.and_then(|m| motor_keys.get(m)).map_or(String::new(), |key| format!(" ({})", tr.tr(key)));
268    let (value, limit) = crate::model::short_pair(v.value, v.limit, v.ok);
269    format!(
270        "{}{motor}: {} / {} = {}",
271        tr.tr(&sim_components::report::check_key(v.check, v.motor.is_some_and(|m| linear.get(m) == Some(&true)))),
272        value,
273        limit,
274        short(utilisation(v))
275    )
276}
277
278/// The ratio sweep of the search tab, as `sim-cli transmission` runs it: `SearchInputs::sweep_key` from `sweep_from` to
279/// `sweep_to` (half and twice the config's where 0) in `sweep_count` values, and with `sweep_snap` the gearboxes of
280/// that series that fit the config's motor around the best ratio.
281pub fn ratio_sweep(entry: &MachineEntry, config: &Config, s: &SearchInputs) -> Result<TransmissionSweep, Message> {
282    let key = s.sweep_key.as_str();
283    let own = catalog::resolve(entry, config).and_then(|c| c.positive(key)).map_err(refused)?;
284    let (from, to) = (
285        if s.sweep_from > 0.0 { s.sweep_from } else { own / 2.0 },
286        if s.sweep_to > 0.0 { s.sweep_to } else { own * 2.0 },
287    );
288    let parts = catalog::Parts::of(config).map_err(refused)?;
289    let snap = Some(s.sweep_snap.trim())
290        .filter(|series| !series.is_empty() && !parts.motor.is_empty())
291        .map(|series| (series, parts.motor, parts.supply));
292    search::transmission_sweep(entry, config, key, (from, to, s.sweep_count), snap).map_err(refused)
293}
294
295/// The kinematics comparison of the search tab, as `sim-cli compare-kinematics` runs it: the task file mapped onto each
296/// machine of `SearchInputs::machines` (the one shown with `config`, the others with their default config), the search
297/// at the supplies of `supplies` with the series, gearbox series, drives and ranking of the search tab.
298pub fn compare(entry: &'static MachineEntry, config: &Config, inputs: &Inputs) -> Result<Vec<KinematicsRow>, Message> {
299    let s = &inputs.search;
300    let file = s.task_file.trim();
301    let bytes = std::fs::read(file).map_err(|e| ("ui-file-unreadable", format!("{file}: {e}")))?;
302    let task =
303        Task::parse(&sim_components::import::decode(&bytes)).map_err(|e| ("ui-file-line", format!("{file}: {e}")))?;
304    let ids: Vec<&str> = s.machines.split(',').map(str::trim).filter(|id| !id.is_empty()).collect();
305    let machines: Vec<(&MachineEntry, Config)> = if ids.is_empty() {
306        vec![(entry, config.clone())]
307    } else {
308        ids.iter()
309            .map(|id| match MACHINES.iter().copied().find(|m| m.id == *id) {
310                Some(m) if m.id == entry.id => Ok((m, config.clone())),
311                Some(m) => Ok((m, m.config())),
312                None => Err(("ui-search-unknown-machine", id.to_string())),
313            })
314            .collect::<Result<_, _>>()?
315    };
316    let at = supplies(&s.vendor, &inputs.supply);
317    if at.is_empty() {
318        return Err(("ui-search-bad-supply", inputs.supply.clone()));
319    }
320    // No price list here: `price` would rank every candidate as unpriced, in the weight order without a word.
321    let by = search::parse_ranking(&s.rank_by)
322        .filter(|by| by.iter().all(|(c, _)| *c != search::Criterion::Price))
323        .ok_or_else(|| ("ui-search-bad-rank", s.rank_by.clone()))?;
324    let series = inputs.series.trim();
325    let gearboxes = Some(inputs.gearboxes.trim()).filter(|g| !g.is_empty());
326    let options = Options { gearboxes, drives: s.drives, ..Options::default() };
327    let rows = search::compare_kinematics(
328        &task,
329        &machines,
330        &|_| at.clone(),
331        &|article: &str| article.starts_with(series),
332        &options,
333        &by,
334    );
335    Ok(rows)
336}
337
338/// The kinematics comparison side by side: a column per machine, a row per figure of its best candidate.
339pub fn kinematics_table(tr: &Translations, rows: &[KinematicsRow]) -> Table {
340    let keys = [
341        "ui-kinematics-machine",
342        "ui-analysis-result",
343        "ui-analysis-motor",
344        "ui-search-gearbox",
345        "ui-parts-drive",
346        "ui-search-supply",
347        "ui-search-cost",
348        "ui-kinematics-cycle",
349        "ui-kinematics-target",
350        "ui-kinematics-energy",
351        "ui-search-tightest",
352        "ui-search-share",
353        "ui-kinematics-thermal",
354        "ui-kinematics-error",
355        "ui-kinematics-inertia",
356        "ui-kinematics-passing",
357    ];
358    let mut columns: Vec<Vec<String>> = vec![keys.iter().map(|k| tr.tr(k).to_string()).collect()];
359    for row in rows {
360        let machine =
361            MACHINES.iter().find(|m| m.id == row.machine).map_or(row.machine.clone(), |m| tr.tr(m.key).into());
362        // The unit of "motor-speed" is the machine's motor kind (the default config builds, the kind does not vary).
363        let linear = MACHINES
364            .iter()
365            .find(|m| m.id == row.machine)
366            .is_some_and(|m| (m.build)(&m.config()).is_ok_and(|b| b.motor_linear(0)));
367        let target = row.target_s.map_or(String::new(), short);
368        let mut column = vec![machine];
369        match (&row.refused, &row.best) {
370            (Some(r), _) => column.push(format!("{}: {}", tr.tr(r.key), r.detail)),
371            (None, None) => column.push(tr.tr("ui-search-refused").into()),
372            (None, Some(c)) => {
373                let f = c.figures.clone().unwrap_or_default();
374                let (check, u) = c.tightest().map_or((String::new(), f64::NAN), |(k, u)| {
375                    (tr.tr(&sim_components::report::check_key(k, linear)).into(), u)
376                });
377                column.extend([
378                    tr.tr(if row.meets() { "ui-analysis-ok" } else { "ui-analysis-fail" }).to_string(),
379                    c.article.to_string(),
380                    c.gearbox.clone(),
381                    c.drive.to_string(),
382                    c.supply.to_string(),
383                    short(c.cost),
384                    short(f.cycle_s),
385                    target.clone(),
386                    short(f.energy_j),
387                    check,
388                    short(u),
389                    short(f.thermal),
390                    short(f.following_error_m * 1e6),
391                    short(f.inertia_ratio),
392                    format!("{} / {}", row.passing, row.tried),
393                ]);
394            }
395        }
396        column.resize(keys.len(), String::new());
397        columns.push(column);
398    }
399    (0..keys.len()).map(|i| columns.iter().map(|c| c[i].clone()).collect()).collect()
400}
401
402/// The workspace maps of the path tab: over the plane of the two axes `axes`, from `x` and `y` (low, high) in `n` nodes
403/// per side (node (i, j) at x.0 + i (x.1 - x.0) / (n - 1), j outer), per node the peak motor torque (N m, the highest of
404/// the motors) and the peak following error (of the axes in the unit of the moved axis) of a short move from there;
405/// NaN where the machine cannot start or make it.
406#[derive(Debug, Clone)]
407pub struct MoveMap {
408    pub axes: [usize; 2],
409    pub x: (f64, f64),
410    pub y: (f64, f64),
411    pub n: usize,
412    pub torque: Vec<f64>,
413    pub error: Vec<f64>,
414    /// The axis moved, and how far.
415    pub axis: usize,
416    pub distance: f64,
417}
418
419/// How long a short move may take, s, beyond which it counts as not made.
420const MOVE_LIMIT_S: f64 = 10.0;
421/// How long after the setpoint has arrived the move is watched, s: the settling belongs to it.
422const SETTLE_S: f64 = 0.1;
423
424/// One short move: the machine at rest at `from` (`start.pose`), moved point to point to `to` (`Command::MoveTo`)
425/// and watched until `SETTLE_S` after it has arrived. The peak motor torque, the highest of the motors (N m), and the
426/// peak following error of the axes in the unit of axis `unit_of`.
427pub fn short_move(
428    entry: &MachineEntry,
429    config: &Config,
430    from: &[f64],
431    to: &[f64],
432    unit_of: usize,
433) -> Result<(f64, f64), Message> {
434    let mut cfg = config.clone();
435    cfg.set_text(&format!("start.pose = {from:?}")).map_err(refused)?;
436    let mut sim = Sim::new(entry, &cfg).map_err(refused)?;
437    let infos = sim.signal_infos();
438    let unit = sim.machine.axes().get(unit_of).map(|a| a.unit.to_string()).unwrap_or_default();
439    let torques: Vec<usize> =
440        (0..infos.len()).filter(|&i| infos[i].id.starts_with("motor.") && infos[i].id.ends_with(".torque")).collect();
441    let errors: Vec<usize> = (0..infos.len())
442        .filter(|&i| {
443            infos[i].id.starts_with("axis.") && infos[i].id.ends_with(".following_error") && infos[i].unit == unit
444        })
445        .collect();
446    sim.command(Command::MoveTo(to.to_vec())).map_err(|e| (e.key, String::new()))?;
447    let (start, mut arrived, mut row) = (sim.time(), None, Vec::new());
448    let (mut torque, mut error) = (0.0f64, 0.0f64);
449    loop {
450        sim.step();
451        row.clear();
452        sim.sample(&mut row);
453        torque = torques.iter().map(|&i| row[i].abs()).fold(torque, f64::max);
454        error = errors.iter().map(|&i| row[i].abs()).fold(error, f64::max);
455        let now = sim.time();
456        if !sim.control.busy() {
457            let since = *arrived.get_or_insert(now);
458            if now - since >= SETTLE_S {
459                return Ok((torque, error));
460            }
461        }
462        if now - start > MOVE_LIMIT_S {
463            return Err(("ui-map-move-too-long", String::new()));
464        }
465    }
466}
467
468/// The nodes of a move map: the plane's axes over their travel, the other axes where the config starts them.
469fn map_nodes(
470    config: &Config,
471    axes: &[sim_core::AxisInfo],
472    m: &MapInputs,
473) -> Result<(Vec<f64>, (f64, f64), (f64, f64)), Message> {
474    let [a, b] = m.plane;
475    if a == b || a >= axes.len() || b >= axes.len() || m.axis >= axes.len() || m.n < 2 {
476        return Err(("ui-map-bad-plane", String::new()));
477    }
478    let base = config.f64s("start.pose").map_err(refused)?;
479    Ok((base, (axes[a].min, axes[a].max), (axes[b].min, axes[b].max)))
480}
481
482/// The distance a map's move goes when `MapInputs::distance` is 0: a tenth of the moved axis's travel.
483pub fn default_distance(axis: &sim_core::AxisInfo) -> f64 {
484    (axis.max - axis.min) / 10.0
485}
486
487/// The move map of `MapInputs`: from each node of the grid a short move (`short_move`) along `axis` by `distance` (a
488/// tenth of its travel where 0), backwards where forwards would leave the travel. The moves share the processors.
489pub fn move_map(entry: &MachineEntry, config: &Config, m: &MapInputs, progress: &Progress) -> Result<MoveMap, Message> {
490    let resolved = catalog::resolve(entry, config).map_err(refused)?;
491    let machine = (entry.build)(&resolved).map_err(refused)?;
492    let axes = machine.axes();
493    let (base, x, y) = map_nodes(config, axes, m)?;
494    let moved = &axes[m.axis];
495    let distance = if m.distance > 0.0 { m.distance } else { default_distance(moved) };
496    let n = m.n;
497    let at = |(low, high): (f64, f64), i: usize| low + (high - low) * i as f64 / (n - 1) as f64;
498    let poses: Vec<(Vec<f64>, Vec<f64>)> = (0..n * n)
499        .map(|k| {
500            let mut from = base.clone();
501            (from[m.plane[0]], from[m.plane[1]]) = (at(x, k % n), at(y, k / n));
502            let mut to = from.clone();
503            let ahead = from[m.axis] + distance;
504            to[m.axis] = if ahead <= moved.max { ahead } else { from[m.axis] - distance };
505            (from, to)
506        })
507        .collect();
508    let results = on_cores(poses.len(), progress, |k| short_move(entry, config, &poses[k].0, &poses[k].1, m.axis).ok())
509        .ok_or(("ui-job-cancelled", String::new()))?;
510    let (torque, error) = results.into_iter().map(|r| r.unwrap_or((f64::NAN, f64::NAN))).unzip();
511    Ok(MoveMap { axes: m.plane, x, y, n, torque, error, axis: m.axis, distance })
512}
513
514/// `work` for 0..count on every processor, the results in order, counted in `progress`; `None` where it was cancelled
515/// (no new run starts then).
516fn on_cores<T: Send>(count: usize, progress: &Progress, work: impl Fn(usize) -> T + Sync) -> Option<Vec<T>> {
517    progress.total.fetch_add(count, Relaxed);
518    let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(count.max(1));
519    let next = std::sync::atomic::AtomicUsize::new(0);
520    let mut out: Vec<(usize, T)> = std::thread::scope(|scope| {
521        let handles: Vec<_> = (0..threads)
522            .map(|_| {
523                scope.spawn(|| {
524                    let mut done = Vec::new();
525                    loop {
526                        let k = next.fetch_add(1, Relaxed);
527                        if k >= count || progress.cancel.load(Relaxed) {
528                            return done;
529                        }
530                        done.push((k, work(k)));
531                        progress.done.fetch_add(1, Relaxed);
532                    }
533                })
534            })
535            .collect();
536        handles.into_iter().flat_map(|h| h.join().unwrap_or_default()).collect()
537    });
538    out.sort_by_key(|(k, _)| *k);
539    (out.len() == count).then(|| out.into_iter().map(|(_, t)| t).collect())
540}
541
542/// The computations of these views beside the analysis panel's, each in a thread of its own.
543#[derive(Debug, Clone, Copy, PartialEq)]
544pub enum ViewJob {
545    Sweep,
546    Kinematics,
547    Map,
548}
549
550enum Done {
551    Sweep(TransmissionSweep),
552    Kinematics(Vec<KinematicsRow>),
553    Map(MoveMap),
554}
555
556/// What these views keep: the top candidates' curves of the last search, and the last ratio sweep, kinematics
557/// comparison and move map, each with the config it was computed for; and the jobs under way.
558#[derive(Default)]
559pub struct Views {
560    pub curves: Vec<Option<Curves>>,
561    pub sweep: Option<(Config, TransmissionSweep)>,
562    pub kinematics: Option<(Config, Vec<KinematicsRow>)>,
563    pub map: Option<(Config, MoveMap)>,
564    jobs: Vec<(ViewJob, Config, Job<Done>)>,
565}
566
567impl Views {
568    /// Starts one computation with the config and the inputs as they are now.
569    pub fn start(&mut self, kind: ViewJob, entry: &'static MachineEntry, config: &Config, inputs: &Inputs) {
570        let (config, inputs) = (config.clone(), inputs.clone());
571        let started = config.clone();
572        let job = Job::spawn(move |progress| match kind {
573            ViewJob::Sweep => ratio_sweep(entry, &config, &inputs.search).map(Done::Sweep),
574            ViewJob::Kinematics => compare(entry, &config, &inputs).map(Done::Kinematics),
575            ViewJob::Map => move_map(entry, &config, &inputs.map, progress).map(Done::Map),
576        });
577        self.jobs.push((kind, started, job));
578    }
579
580    /// The progress and cancel switch of the job of this kind under way.
581    pub fn progress(&self, kind: ViewJob) -> Option<Arc<Progress>> {
582        self.jobs.iter().find(|job| job.0 == kind).map(|job| job.2.progress.clone())
583    }
584
585    pub fn running(&self, kind: ViewJob) -> bool {
586        self.jobs.iter().any(|job| job.0 == kind)
587    }
588
589    pub fn any_running(&self) -> bool {
590        !self.jobs.is_empty()
591    }
592
593    /// Takes in what the jobs have answered; the messages of those that failed. A job whose thread is gone without an
594    /// answer (it panicked) answers with a message.
595    pub fn poll(&mut self) -> Vec<Message> {
596        let mut said = Vec::new();
597        let mut done = Vec::new();
598        self.jobs.retain(|(_, config, job)| {
599            let Some(answer) = crate::model::answer(job) else { return true };
600            done.push((config.clone(), answer));
601            false
602        });
603        for (config, answer) in done {
604            match answer {
605                Ok(Done::Sweep(s)) => self.sweep = Some((config, s)),
606                Ok(Done::Kinematics(rows)) => self.kinematics = Some((config, rows)),
607                Ok(Done::Map(map)) => self.map = Some((config, map)),
608                Err(message) => said.push(message),
609            }
610        }
611        said
612    }
613}