1use 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#[derive(Debug, Clone, PartialEq)]
21pub struct SearchInputs {
22 pub vendor: String,
25 pub drives: Drives,
27 pub rank_by: String,
29 pub duties: String,
32 pub motor: String,
34 pub top: usize,
36 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 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#[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
85pub 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
97pub 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
111pub 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
122fn 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
145pub 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 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 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 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 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 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
201pub 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#[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
238pub 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
259pub 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
265pub 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
278pub 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
295pub 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 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
338pub 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 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#[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 pub axis: usize,
416 pub distance: f64,
417}
418
419const MOVE_LIMIT_S: f64 = 10.0;
421const SETTLE_S: f64 = 0.1;
423
424pub 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
468fn 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
482pub fn default_distance(axis: &sim_core::AxisInfo) -> f64 {
484 (axis.max - axis.min) / 10.0
485}
486
487pub 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
514fn 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#[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#[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 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 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 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}