1use crate::control::{Command, CommandError};
5use crate::sim::Sim;
6use sim_core::{
7 Config, ConfigError, LOSS_PREFIX, Machine, MachineEntry, Mode, RatingCheck, Rk4, SignalInfo, TORQUE_PARTS,
8 ThermalPart, advance,
9};
10
11#[derive(Debug, Clone, Default)]
13pub struct MotorLoad {
14 pub id: String,
16 pub peak_torque: f64,
17 pub rms_torque: f64,
18 pub cubic_mean_torque: f64,
21 pub peak_speed: f64,
22 pub utilisation: f64,
25 pub thermal_utilisation: f64,
27 pub rms_current: f64,
28 pub peak_current: f64,
33 pub winding_rise: f64,
35 pub thermal_current: f64,
38 pub load_angle: Option<f64>,
41 pub iron_loss: f64,
43 pub housing_rise: f64,
46 pub drive_overload: f64,
49 pub energy_in: f64,
51 pub energy_regenerated: f64,
52 pub peak_regenerated_power: f64,
55 pub largest_regeneration: f64,
56 pub regeneration_events: Vec<f64>,
61 pub dc_link_account: Option<LinkAccount>,
64 pub resistor_energy: f64,
68 pub peak_resistor_power: f64,
69 pub peak_dc_link_voltage: f64,
70 pub mains_energy: f64,
74 pub line_module_energy: f64,
75 pub peak_line_module_power: f64,
76 pub discharge_energy: f64,
79 pub gearbox_torque: Option<(f64, f64)>,
83 pub mean_speed: f64,
85 pub gearbox_life_torque: Option<f64>,
88 pub gearbox_torque_by_speed: Vec<f64>,
91 pub gearbox_torque_spectrum: Vec<f64>,
95 pub radial_load_equivalent: Option<f64>,
98 pub radial_load_peak: Option<f64>,
101 pub belt_wrap: Option<f64>,
104 pub torque_parts: Option<[(f64, f64); 4]>,
108 pub points: Vec<(f64, f64)>,
110}
111
112#[derive(Debug, Clone, PartialEq)]
114pub struct BudgetRow {
115 pub id: String,
118 pub owner_key: String,
120 pub quantity_key: String,
121 pub energy: f64,
123}
124
125#[derive(Debug, Clone, PartialEq)]
127pub struct EnergyBudget {
128 pub supply: f64,
131 pub rows: Vec<BudgetRow>,
132 pub shaft_work: f64,
135}
136
137impl EnergyBudget {
138 pub fn unaccounted(&self) -> f64 {
141 self.supply - self.rows.iter().map(|r| r.energy).sum::<f64>()
142 }
143
144 pub fn electrical_unaccounted(&self) -> f64 {
149 let electrical = |id: &str| {
150 id.starts_with("copper.")
151 || id.starts_with("emf.")
152 || matches!(id, "resistor" | "discharge" | "mains" | "line_module" | "windings" | "capacitors")
153 };
154 self.supply - self.shaft_work - self.rows.iter().filter(|r| electrical(&r.id)).map(|r| r.energy).sum::<f64>()
155 }
156}
157
158pub const BUDGET_TOLERANCE: f64 = 1e-3;
162
163pub const ELECTRICAL_TOLERANCE: f64 = 1e-6;
166
167#[derive(Debug, Clone, Default, PartialEq)]
169pub struct GuideLoad {
170 pub peak: f64,
172 pub equivalent: f64,
174 pub speed: Option<f64>,
176}
177
178#[derive(Debug, Clone, Default)]
179pub struct CycleLoad {
180 pub duration: f64,
181 pub belt_tension: Option<(f64, f64)>,
184 pub belt_slack_time: Option<f64>,
186 pub belt_tooth_jumps: Option<f64>,
188 pub belt_span_detuning: Option<f64>,
192 pub radial_load_peak: Option<f64>,
194 pub condition_peak: Option<f64>,
197 pub guide_load: Option<(f64, f64)>,
200 pub guide_speed: Option<f64>,
202 pub guides: Vec<GuideLoad>,
205 pub path_error_peak: f64,
210 pub path_error_rms: f64,
211 pub tracking_error_peak: f64,
212 pub dwell_error_peak: f64,
215 pub path_angle_error_peak: f64,
217 pub path_angle_error_rms: f64,
218 pub tracking_angle_error_peak: f64,
219 pub dwell_angle_error_peak: f64,
220 pub path_error_series: Vec<[f64; 3]>,
223 pub tripped: bool,
228 pub motors: Vec<MotorLoad>,
229 pub budget: Option<EnergyBudget>,
232 pub part_rises: Vec<(ThermalPart, f64)>,
235 pub checks: Vec<(RatingCheck, f64)>,
238 pub clearance: Option<f64>,
241 pub contact: Option<crate::Contact>,
242 pub own_clearance: Option<f64>,
245 pub braking_power_peak: f64,
249 pub warm_start: Option<WarmStart>,
252 pub conveyor: Option<ConveyorLoad>,
254 pub held_accelerations: Vec<[f64; 2]>,
258}
259
260fn cam_checks(machine: &dyn sim_core::Machine) -> Vec<(RatingCheck, f64)> {
264 let (axes, motors) = (machine.axes(), machine.motors().len());
265 let checks = ["cam-speed", "cam-acceleration", "cam-jerk"];
266 crate::control::cam_peaks(machine)
267 .into_iter()
268 .zip(axes)
269 .enumerate()
270 .flat_map(|(i, (peak, axis))| {
271 let limits = [axis.max_vel, axis.max_acc, axis.max_jerk];
272 (0..3).map(move |k| {
273 let motor = (axes.len() == motors).then_some(i);
274 (
275 RatingCheck { check: checks[k], signal: axis.id.to_string(), motor, limit: limits[k], life: false },
276 peak[k],
277 )
278 })
279 })
280 .collect()
281}
282
283#[derive(Debug, Clone, Copy, PartialEq)]
285pub struct ConveyorLoad {
286 pub picks_per_minute: f64,
288 pub tracking_peak: f64,
290 pub missed: u64,
292 pub missed_per_minute: f64,
295}
296
297pub const WARM_START_TOLERANCE_K: f64 = 0.1;
300
301pub const WARM_START_PASSES: usize = 4;
304
305pub const WARM_START_PERIOD_MOST: usize = 3;
307
308#[derive(Debug, Clone, Copy, PartialEq)]
319pub struct WarmStart {
320 pub passes: usize,
321 pub change: f64,
322 pub period: usize,
323 pub repeat: Option<f64>,
324}
325
326impl WarmStart {
327 pub fn converged(&self) -> bool {
328 self.change <= WARM_START_TOLERANCE_K
329 }
330}
331
332fn fed_back_rises(sim: &Sim) -> Vec<f64> {
335 let windings = if sim.control.drive_params().heating { &sim.control.drives[..] } else { &[] };
336 let parts = if sim.thermal_feedback { &sim.heated[..] } else { &[] };
337 windings.iter().map(|d| d.temperature_rise).chain(parts.iter().map(|h| h.rise)).collect()
338}
339
340fn settled_rises(sim: &Sim, load: &CycleLoad) -> Vec<f64> {
342 let windings = if sim.control.drive_params().heating { &load.motors[..] } else { &[] };
343 let parts = if sim.thermal_feedback { &load.part_rises[..] } else { &[] };
344 windings.iter().map(|m| m.winding_rise).chain(parts.iter().map(|(_, rise)| *rise)).collect()
345}
346
347fn set_rises(sim: &mut Sim, rises: &[f64]) {
349 let mut rises = rises.iter();
350 if sim.control.drive_params().heating {
351 let shares: Vec<f64> = (0..sim.control.drives.len())
352 .map(|k| sim.control.drive_params_of(k).thermal_nodes.map_or(1.0, |n| n.winding_share))
353 .collect();
354 for ((drive, rise), share) in sim.control.drives.iter_mut().zip(&mut rises).zip(shares) {
355 drive.temperature_rise = *rise;
356 drive.housing_rise = rise * (1.0 - share);
358 }
359 }
360 if sim.thermal_feedback {
361 for (part, rise) in sim.heated.iter_mut().zip(rises) {
362 part.rise = *rise;
363 }
364 }
365 sim.feed_temperatures_back();
366}
367
368#[allow(clippy::too_many_arguments)]
385fn warm_pass(
386 sim: &mut Sim,
387 started_at: &[f64],
388 load: &CycleLoad,
389 passes: usize,
390 before: &mut Option<(Vec<f64>, Vec<f64>)>,
391 period: &mut usize,
392 history: &mut Vec<Vec<f64>>,
393 mut repeat: Option<&mut Option<(Vec<f64>, WarmStart)>>,
394) -> Option<WarmStart> {
395 let settled = settled_rises(sim, load);
396 if let Some((first, done)) = repeat.as_mut().and_then(|r| r.take()) {
397 let apart = settled.iter().zip(&first).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
399 return Some(WarmStart { repeat: Some(apart), ..done });
400 }
401 let change = settled
402 .iter()
403 .zip(started_at)
404 .map(|(s, r)| if s.is_finite() { (s - r).abs() } else { f64::INFINITY })
405 .fold(0.0, f64::max);
406 let done = WarmStart { passes, change, period: *period, repeat: None };
407 if done.converged() || change.is_infinite() {
409 return Some(done);
410 }
411 if *period == 1 {
412 history.push(settled.clone());
413 }
414 if passes == WARM_START_PASSES {
415 let found = (*period == 1).then(|| period_of(history)).flatten();
416 let Some(p) = found else {
417 let Some(r) = repeat else { return Some(done) };
418 *r = Some((settled, done));
420 set_rises(sim, started_at);
421 return None;
422 };
423 let last = &history[history.len() - p..];
425 let mean: Vec<f64> = (0..settled.len()).map(|i| last.iter().map(|s| s[i]).sum::<f64>() / p as f64).collect();
426 (*period, *before) = (p, None);
427 set_rises(sim, &mean);
428 return None;
429 }
430 let next: Vec<f64> = (0..settled.len())
431 .map(|i| {
432 let (r, s) = (started_at[i], settled[i]);
433 let slope = before
434 .as_ref()
435 .filter(|(r0, _)| (r - r0[i]).abs() > 1e-9)
436 .map_or(0.0, |(r0, s0)| ((s - s0[i]) / (r - r0[i])).clamp(-20.0, 0.5));
437 (r + (s - r) / (1.0 - slope)).max(0.0)
438 })
439 .collect();
440 *before = Some((started_at.to_vec(), settled));
441 set_rises(sim, &next);
442 None
443}
444
445fn period_of(settled: &[Vec<f64>]) -> Option<usize> {
450 let apart = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0, f64::max);
451 let (k, warm) = (settled.len().checked_sub(1)?, 1);
452 let next = apart(&settled[k], &settled[k.checked_sub(1)?]);
453 (2..=WARM_START_PERIOD_MOST).find(|&p| k >= warm + p && apart(&settled[k], &settled[k - p]) < 0.25 * next)
454}
455
456pub fn repeating_peak(
465 o: &crate::drive::Overload,
466 start: [f64; 2],
467 samples: &[(f64, [f64; 2])],
468 (t_end, end): (f64, [f64; 2]),
469) -> f64 {
470 let decay = |node: usize, t: f64| (-t / o.node_time_constant(node)).exp();
471 let x0: [f64; 2] = std::array::from_fn(|n| {
472 let added = end[n] - start[n] * decay(n, t_end);
473 if t_end > 0.0 { added / (1.0 - decay(n, t_end)) } else { start[n] }
474 });
475 let at = |t: f64, x: [f64; 2]| (0..2).map(|n| x[n] + (x0[n] - start[n]) * decay(n, t)).sum::<f64>();
476 samples.iter().chain([(t_end, end)].iter()).map(|&(t, x)| at(t, x)).fold(x0[0] + x0[1], f64::max)
477}
478
479#[derive(Clone)]
483pub struct Tally {
484 loads: Vec<MotorLoad>,
485 pos: Vec<f64>,
486 speed: Vec<f64>,
487 steps: u64,
488 every: u64,
490 overload: Vec<([f64; 2], Vec<(f64, [f64; 2])>)>,
493 tensions: Vec<usize>,
494 radial: Vec<usize>,
496 guides: Vec<usize>,
497 slack: Option<usize>,
498 jumps: Vec<usize>,
501 jumps_start: f64,
502 detuning: Option<usize>,
503 condition: Option<usize>,
505 condition_peak: f64,
506 lowest_detuning: f64,
507 checks: Vec<(RatingCheck, usize, f64, f64)>,
510 plan_checks: Vec<(RatingCheck, usize, f64)>,
514 sample: Vec<f64>,
515 base_only: bool,
517 belt_tension: Option<(f64, f64)>,
518 radial_peak: f64,
519 guide_loads: Vec<(f64, f64)>,
522 guide_weights: Vec<f64>,
523 guide_axes: Vec<Option<usize>>,
525 guide_speeds: Vec<f64>,
526 pulley_radial: Vec<Option<usize>>,
528 radial_sums: Vec<(f64, f64)>,
529 radial_peaks: Vec<f64>,
531 gear_life: Vec<f64>,
533 gear_bands: Vec<Vec<f64>>,
534 gear_spectrum: Vec<Vec<f64>>,
536 slack_start: f64,
538 cubic: Vec<(f64, f64)>,
540 gear: Vec<Option<(usize, f64, f64)>>,
544 machine_signals: Vec<f64>,
545 parts: Vec<Option<[usize; 4]>>,
548 part_sums: Vec<[(f64, f64); 4]>,
549 losses: Vec<usize>,
554 lost: Vec<f64>,
555 energies: Vec<usize>,
556 start: (Vec<f64>, f64, f64, f64),
557 end: (f64, f64, f64),
560 crash: (f64, f64),
562 supply: f64,
563 copper: Vec<f64>,
564 emf: Vec<f64>,
567 resistor: f64,
568 discharge: f64,
570 drawn: f64,
571 mains: f64,
572 line_loss: f64,
573 work: f64,
575 budget_skip: u64,
576 heat: Vec<f64>,
578 views: bool,
581 braking: Vec<f64>,
583 braking_peak: f64,
585 path: std::collections::VecDeque<Vec<f64>>,
587 path_error: [(f64, f64, u64); 2],
589 path_series: Vec<[f64; 3]>,
591 tracking_error: [f64; 2],
592 dwell_error: [f64; 2],
593 groups: [Vec<usize>; 2],
595 pick_tracking: f64,
597 missed_before: u64,
598 cartesian: [Option<usize>; 3],
601 last_speed: Option<[f64; 3]>,
602 held: Vec<[f64; 2]>,
603}
604
605fn distance_to_piece(p: &[f64], a: &[f64], b: &[f64], axes: &[usize]) -> f64 {
607 let (ab, ap) = (|i: usize| b[i] - a[i], |i: usize| p[i] - a[i]);
609 let length = axes.iter().map(|&i| ab(i) * ab(i)).sum::<f64>();
610 let along =
611 if length > 0.0 { (axes.iter().map(|&i| ap(i) * ab(i)).sum::<f64>() / length).clamp(0.0, 1.0) } else { 0.0 };
612 axes.iter().map(|&i| (ap(i) - along * ab(i)).powi(2)).sum::<f64>().sqrt() + 0.0
614}
615
616impl Tally {
617 pub fn new(sim: &Sim, views: bool) -> Self {
618 let motors = sim.machine.motors().len();
619 let infos = sim.signal_infos();
620 let named = |start: &str, end: &str| -> Vec<usize> {
621 infos
622 .iter()
623 .enumerate()
624 .filter(|(_, s)| s.id.starts_with(start) && s.id.ends_with(end))
625 .map(|(i, _)| i)
626 .collect()
627 };
628 let guides = named("axis.", ".guide_load");
629 let own = sim.machine.signal_infos();
630 let gear = |motor: &sim_core::MotorInfo| {
631 Some((own.iter().position(|s| s.id == format!("gearbox.{}.output_torque", motor.id))?, 0.0, 0.0))
632 };
633 let parts = |motor: &sim_core::MotorInfo| -> Option<[usize; 4]> {
634 let found: Vec<usize> = TORQUE_PARTS
635 .iter()
636 .filter_map(|part| own.iter().position(|s| s.id == format!("motor.{}.torque_{part}", motor.id)))
637 .collect();
638 found.try_into().ok()
639 };
640 let own_named = |prefix: &str| {
642 own.iter()
643 .enumerate()
644 .filter(|(_, s)| views && s.id.starts_with(prefix))
645 .map(|(i, _)| i)
646 .collect::<Vec<_>>()
647 };
648 let (losses, energies) = (own_named(LOSS_PREFIX), own_named("energy."));
649 let mut machine_signals = Vec::new();
650 if views {
651 sim.machine.signals(&sim.state, &sim.machine_torque(), &mut machine_signals);
652 } else {
653 sim.machine.base_signals(&sim.state, &sim.machine_torque(), &mut machine_signals);
654 }
655 let (windings, capacitors) = stored_electrically(sim);
656 let (tensions, radial, slack, jumps, detuning) = (
657 named("belt.", ".tension"),
658 named("pulley.", ".radial_load"),
659 infos.iter().position(|s| s.id == "belt.slack_time"),
660 named("pulley.", ".tooth_jumps"),
661 infos.iter().position(|s| s.id == "belt.span_detuning"),
662 );
663 let mut base = Vec::new();
664 sim.sample_base(&mut base);
665 let condition = infos.iter().position(|s| s.id == "kinematics.condition");
666 let checks: Vec<(RatingCheck, usize, f64, f64)> = sim
667 .machine
668 .rating_checks()
669 .into_iter()
670 .filter_map(|c| Some((infos.iter().position(|s| s.id == c.signal)?, c)))
671 .map(|(i, c)| (c, i, 0.0, 0.0))
672 .collect();
673 let check_places: Vec<usize> = checks.iter().map(|c| c.1).collect();
674 let plan_checks = sim
675 .machine
676 .rating_checks()
677 .into_iter()
678 .enumerate()
679 .filter(|(_, c)| c.signal.starts_with("plan.") && !c.life)
680 .map(|(i, c)| (c, i, 0.0))
681 .collect();
682 let base_only = tensions
683 .iter()
684 .chain(&radial)
685 .chain(&guides)
686 .chain(&jumps)
687 .chain(&slack)
688 .chain(&detuning)
689 .chain(&condition)
690 .chain(&check_places)
691 .all(|&i| i < base.len());
692 Self {
693 gear: sim.machine.motors().iter().map(gear).collect(),
694 parts: sim.machine.motors().iter().map(|m| if views { parts(m) } else { None }).collect(),
695 part_sums: vec![[(0.0, 0.0); 4]; motors],
696 lost: vec![0.0; losses.len()],
697 start: (energies.iter().map(|&i| machine_signals[i]).collect(), windings, capacitors, sim.payload_energy),
698 end: (windings, capacitors, sim.payload_energy),
699 crash: (sim.crash_energy, sim.crash_energy),
700 losses,
701 energies,
702 supply: 0.0,
703 copper: vec![0.0; motors],
704 emf: vec![0.0; motors],
705 resistor: 0.0,
706 discharge: 0.0,
707 drawn: 0.0,
708 mains: 0.0,
709 line_loss: 0.0,
710 work: 0.0,
711 budget_skip: 0,
712 heat: vec![0.0; if sim.part_heating { sim.heated.len() } else { 0 }],
713 views,
714 machine_signals,
715 radial,
716 slack,
717 jumps,
718 jumps_start: 0.0,
719 detuning,
720 lowest_detuning: 1.0,
721 condition,
722 condition_peak: 0.0,
723 checks,
724 plan_checks,
725 radial_peak: 0.0,
726 guide_loads: vec![(0.0, 0.0); guides.len()],
727 guide_weights: vec![0.0; guides.len()],
728 guide_axes: guides
729 .iter()
730 .map(|&i| sim.machine.axes().iter().position(|a| infos[i].id == format!("axis.{}.guide_load", a.id)))
731 .collect(),
732 guide_speeds: vec![0.0; guides.len()],
733 pulley_radial: sim
734 .machine
735 .motors()
736 .iter()
737 .map(|m| infos.iter().position(|s| s.id == format!("pulley.{}.radial_load", m.id)))
738 .collect(),
739 radial_sums: vec![(0.0, 0.0); motors],
740 radial_peaks: vec![0.0; motors],
741 gear_life: vec![0.0; motors],
742 gear_bands: vec![Vec::new(); motors],
743 gear_spectrum: vec![Vec::new(); motors],
744 guides,
745 slack_start: 0.0,
746 cubic: vec![(0.0, 0.0); motors],
747 loads: sim
748 .machine
749 .motors()
750 .iter()
751 .enumerate()
752 .map(|(k, m)| MotorLoad {
753 id: m.id.to_string(),
754 dc_link_account: sim.control.dc_link_room(k).map(LinkAccount::new),
755 ..MotorLoad::default()
756 })
757 .collect(),
758 pos: {
759 let (mut pos, mut speed) = (vec![0.0; motors], vec![0.0; motors]);
760 sim.machine.motor_state(&sim.state, &mut pos, &mut speed);
761 pos
762 },
763 speed: vec![0.0; motors],
764 steps: 0,
765 every: (1e-3 / sim.dt).round().max(1.0) as u64,
766 overload: sim.control.drives.iter().map(|d| (d.overload_nodes(), Vec::new())).collect(),
767 tensions,
768 sample: Vec::new(),
769 base_only,
770 belt_tension: None,
771 braking: vec![0.0; motors],
772 braking_peak: 0.0,
773 path: std::collections::VecDeque::new(),
774 path_error: [(0.0, 0.0, 0); 2],
775 path_series: Vec::new(),
776 tracking_error: [0.0; 2],
777 dwell_error: [0.0; 2],
778 groups: [false, true].map(|turn| {
779 sim.machine
780 .axes()
781 .iter()
782 .enumerate()
783 .filter(|(_, a)| (a.unit == "rad") == turn)
784 .map(|(i, _)| i)
785 .collect()
786 }),
787 pick_tracking: 0.0,
788 missed_before: sim.control.conveyor().map_or(0, |(c, _)| c.missed),
789 cartesian: ["x", "y", "z"].map(|id| sim.machine.axes().iter().position(|a| a.id == id && a.unit == "m")),
790 last_speed: None,
791 held: Vec::new(),
792 }
793 }
794
795 fn sample_now(&mut self, sim: &Sim) {
796 if self.base_only { sim.sample_base(&mut self.sample) } else { sim.sample(&mut self.sample) }
797 }
798
799 pub fn step(&mut self, sim: &Sim) {
801 sim.machine.motor_state(&sim.state, &mut self.pos, &mut self.speed);
802 if let Some((conveyor, Some(pass))) = sim.control.conveyor()
803 && let Some(part) = conveyor.gripping(pass, sim.time())
804 {
805 let n = part.len();
806 let (mut tool, mut vel) = (vec![0.0; n], vec![0.0; n]);
807 sim.machine.tool_state(&sim.state, &mut tool, &mut vel);
808 let along: f64 = tool.iter().zip(&part).zip(&conveyor.direction).map(|((t, p), d)| (t - p) * d).sum();
809 self.pick_tracking = self.pick_tracking.max(along.abs());
810 }
811 let sampled = self.steps.is_multiple_of(self.every);
812 if sampled {
813 self.sample_now(sim);
814 for &i in &self.tensions {
815 let (low, high) = self.belt_tension.unwrap_or((self.sample[i], self.sample[i]));
816 self.belt_tension = Some((low.min(self.sample[i]), high.max(self.sample[i])));
817 }
818 for &i in &self.radial {
819 self.radial_peak = self.radial_peak.max(self.sample[i]);
820 }
821 for (peak, signal) in self.radial_peaks.iter_mut().zip(&self.pulley_radial) {
822 if let Some(i) = *signal {
823 *peak = peak.max(self.sample[i]);
824 }
825 }
826 if let Some(i) = self.condition {
827 self.condition_peak = self.condition_peak.max(self.sample[i]);
828 }
829 let axes = sim.machine.axes().len();
830 let (mut tool, mut rate) = (vec![0.0; axes], vec![0.0; axes]);
831 sim.machine.tool_state(&sim.state, &mut tool, &mut rate);
832 for (load, wrap) in self.loads.iter_mut().zip(sim.machine.belt_wraps(&tool)).filter(|(_, w)| w.is_finite())
834 {
835 load.belt_wrap = Some(load.belt_wrap.map_or(wrap, |least| least.min(wrap)));
836 }
837 for (_, i, peak, sum) in &mut self.checks {
838 (*peak, *sum) = (peak.max(self.sample[*i].abs()), *sum + self.sample[*i]);
839 }
840 if !self.plan_checks.is_empty() {
843 let mut rigid = Vec::new();
844 let c = &sim.control;
845 sim.machine.rigid_checks(&c.set_pos, &c.set_vel, &c.set_acc, &mut rigid);
846 for (_, i, peak) in &mut self.plan_checks {
847 if let Some(v) = rigid.get(*i).filter(|v| v.is_finite()) {
848 *peak = peak.max(v.abs());
849 }
850 }
851 }
852 for (k, (&i, (peak, cubed))) in self.guides.iter().zip(&mut self.guide_loads).enumerate() {
853 let weight = self.guide_axes[k].map_or(1.0, |a| rate[a].abs());
854 (*peak, *cubed) = (peak.max(self.sample[i]), *cubed + self.sample[i].powi(3) * weight);
855 self.guide_weights[k] += weight;
856 }
857 if let (0, Some(i)) = (self.steps, self.slack) {
858 self.slack_start = self.sample[i];
859 }
860 if self.steps == 0 {
861 self.jumps_start = self.jumps.iter().map(|&i| self.sample[i]).sum();
862 }
863 let steady = sim.control.set_acc.iter().all(|a| a.abs() <= 1e-9)
866 && sim.control.set_vel.iter().any(|v| v.abs() > 1e-9);
867 if let (true, Some(i)) = (steady, self.detuning) {
868 self.lowest_detuning = self.lowest_detuning.min(self.sample[i]);
869 }
870 let axes = sim.machine.axes().len();
873 let (mut tool, mut rate) = (vec![0.0; axes], vec![0.0; axes]);
874 sim.machine.tool_state(&sim.state, &mut tool, &mut rate);
875 for (axis, sum) in self.guide_axes.iter().zip(&mut self.guide_speeds) {
876 *sum += axis.map_or(0.0, |a| rate[a].abs());
877 }
878 if self.cartesian.iter().any(Option::is_some) {
879 let speed = self.cartesian.map(|i| i.map_or(0.0, |i| rate[i]));
880 let held = sim.control.payload_attached && !sim.control.gripper_acting();
881 if let (true, Some(last)) = (held, self.last_speed) {
882 let a: [f64; 3] = std::array::from_fn(|k| (speed[k] - last[k]) / (self.every as f64 * sim.dt));
883 self.held.push([a[2], a[0].hypot(a[1])]);
884 }
885 self.last_speed = Some(speed);
886 }
887 for (k, (signal, (cubed, weight))) in self.pulley_radial.iter().zip(&mut self.radial_sums).enumerate() {
888 if let Some(i) = *signal {
889 (*cubed, *weight) =
890 (*cubed + self.sample[i].powi(3) * self.speed[k].abs(), *weight + self.speed[k].abs());
891 }
892 }
893 let mut newest =
896 if self.path.len() >= 500 { self.path.pop_front().unwrap_or_default() } else { Vec::new() };
897 newest.resize(axes, 0.0);
898 sim.control.plan_now(sim.time(), &mut newest);
899 self.path.push_back(newest);
900 let now = self.path.back().unwrap();
901 let dwelling = sim.control.dwell_progress().is_some_and(|done| done >= 0.5);
906 let mut series = [sim.time(), 0.0, 0.0];
907 for (g, group) in self.groups.iter().enumerate() {
908 let mut off_path = distance_to_piece(&tool, now, now, group);
909 for (b, a) in self.path.iter().rev().zip(self.path.iter().rev().skip(1)) {
910 let beyond = group
911 .iter()
912 .map(|&i| (tool[i] - a[i]).abs() - (b[i] - a[i]).abs())
913 .fold(f64::NEG_INFINITY, f64::max);
914 if !(beyond > off_path + 1e-12) {
915 off_path = off_path.min(distance_to_piece(&tool, a, b, group));
916 }
917 }
918 let (peak, squares, count) = self.path_error[g];
919 self.path_error[g] = (peak.max(off_path), squares + off_path * off_path, count + 1);
920 series[g + 1] = off_path;
921 self.tracking_error[g] = self.tracking_error[g].max(distance_to_piece(&tool, now, now, group));
922 if dwelling {
923 let target = sim.control.planned_pos();
924 self.dwell_error[g] = self.dwell_error[g].max(distance_to_piece(&tool, target, target, group));
925 }
926 }
927 self.path_series.push(series);
928 }
929 if self.views && (self.parts.iter().any(Option::is_some) || !self.losses.is_empty()) {
930 self.machine_signals.clear();
931 sim.machine.signals(&sim.state, &sim.machine_torque(), &mut self.machine_signals);
932 } else if self.gear.iter().any(Option::is_some) {
933 self.machine_signals.clear();
934 sim.machine.base_signals(&sim.state, &sim.machine_torque(), &mut self.machine_signals);
935 }
936 for (places, sums) in self.parts.iter().zip(&mut self.part_sums).filter_map(|(p, s)| Some((p.as_ref()?, s))) {
937 for (&i, (peak, squares)) in places.iter().zip(sums) {
938 let value = self.machine_signals[i];
939 (*peak, *squares) = (peak.max(value.abs()), *squares + value * value);
940 }
941 }
942 if self.steps >= self.budget_skip {
943 for (&i, lost) in self.losses.iter().zip(&mut self.lost) {
944 *lost += self.machine_signals[i] * sim.dt;
945 }
946 for (part, heat) in sim.heated.iter().zip(&mut self.heat) {
948 *heat += part.loss_power * sim.dt;
949 }
950 let drives = &sim.control.drives;
951 self.supply += drives.iter().map(|d| d.power).sum::<f64>() * sim.dt;
952 self.work += drives.iter().map(|d| d.shaft_power).sum::<f64>() * sim.dt;
953 for ((copper, emf), d) in self.copper.iter_mut().zip(&mut self.emf).zip(drives) {
954 *copper += d.copper_loss * sim.dt;
955 *emf += d.emf_loss * sim.dt;
956 }
957 let shared = sim.control.drive_params().shared_dc_link;
959 let link = |power: fn(&crate::drive::Drive) -> f64| -> f64 {
960 let total: f64 =
961 if shared { drives.first().map_or(0.0, power) } else { drives.iter().map(power).sum() };
962 total * sim.dt
963 };
964 self.resistor += link(|d| d.resistor_power);
965 self.discharge += drives.iter().map(|d| d.discharge_power).sum::<f64>() * sim.dt;
967 self.drawn += link(|d| d.rectifier_power);
968 self.mains += link(|d| d.mains_power);
969 self.line_loss += link(|d| d.line_loss);
970 if !self.losses.is_empty() {
971 let (windings, capacitors) = stored_electrically(sim);
972 self.end = (windings, capacitors, sim.payload_energy);
973 self.crash.1 = sim.crash_energy;
974 }
975 }
976 for (k, (i, peak, cubed)) in self.gear.iter_mut().enumerate().filter_map(|(k, gear)| Some((k, gear.as_mut()?)))
977 {
978 let (torque, speed) = (self.machine_signals[*i].abs(), self.speed[k].abs());
979 (*peak, *cubed) = (peak.max(torque), *cubed + torque.powi(3) * speed);
980 self.gear_life[k] += torque.powf(10.0 / 3.0) * speed;
981 let (bands, band) = (&mut self.gear_bands[k], ((speed / SPEED_BAND) as usize).min(4000));
983 if bands.len() <= band {
984 bands.resize(band + 1, 0.0);
985 }
986 bands[band] = bands[band].max(torque);
987 if torque >= TORQUE_FLOOR && speed > 0.0 {
988 let (spectrum, band) = (
989 &mut self.gear_spectrum[k],
990 (((torque / TORQUE_FLOOR).ln() / TORQUE_BAND.ln()) as usize).min(4000),
991 );
992 if spectrum.len() <= band {
993 spectrum.resize(band + 1, 0.0);
994 }
995 spectrum[band] += speed;
996 }
997 }
998 for (k, load) in self.loads.iter_mut().enumerate() {
999 let torque = sim.control.drives[k].torque;
1000 load.peak_torque = load.peak_torque.max(torque.abs());
1001 let (current, power) = (sim.control.drives[k].phase_current(), sim.control.drives[k].power);
1003 load.rms_current += current * current;
1004 let heating = sim.control.drives[k].thermal_current(sim.control.drive_params_of(k));
1005 load.thermal_current += heating * heating;
1006 if let crate::drive::Motor::Stepper(_) = sim.control.drive_params_of(k).motor {
1007 let angle = sim.control.drives[k].phases.load_angle.abs();
1008 load.load_angle = Some(load.load_angle.unwrap_or(0.0).max(angle));
1009 }
1010 load.peak_current = load.peak_current.max(current.abs());
1011 let own = sim.control.drive_params_of(k);
1013 if own.drive_max_current.is_finite() {
1014 load.peak_current = load.peak_current.max(own.current_for(sim.control.drives[k].torque_demand).abs());
1015 }
1016 let fed = -power * sim.dt;
1018 if self.braking[k] * fed < 0.0 {
1019 if let Some(account) = &mut load.dc_link_account {
1020 account.push(self.braking[k]);
1021 }
1022 self.braking[k] = 0.0;
1023 }
1024 self.braking[k] += fed;
1025 if power >= 0.0 {
1026 load.energy_in += power * sim.dt;
1027 } else {
1028 load.energy_regenerated -= power * sim.dt;
1029 load.peak_regenerated_power = load.peak_regenerated_power.max(-power);
1030 load.largest_regeneration = load.largest_regeneration.max(self.braking[k]);
1031 }
1032 load.rms_torque += torque * torque;
1033 load.iron_loss += sim.control.drives[k].iron_loss;
1034 self.cubic[k] =
1035 (self.cubic[k].0 + torque.abs().powi(3) * self.speed[k].abs(), self.cubic[k].1 + self.speed[k].abs());
1036 let drive = &sim.control.drives[k];
1037 load.resistor_energy += drive.resistor_power * sim.dt;
1038 load.discharge_energy += drive.discharge_power * sim.dt;
1039 load.peak_resistor_power = load.peak_resistor_power.max(drive.resistor_power);
1040 load.peak_dc_link_voltage = load.peak_dc_link_voltage.max(drive.dc_voltage);
1041 let efficiency = sim.control.drive_params_of(k).line_efficiency;
1044 let through = efficiency * drive.rectifier_power + drive.mains_power / efficiency;
1045 load.mains_energy += drive.mains_power * sim.dt;
1046 load.line_module_energy += through * sim.dt;
1047 load.peak_line_module_power = load.peak_line_module_power.max(through);
1048 load.peak_speed = load.peak_speed.max(self.speed[k].abs());
1049 let (low, high) = sim.control.motor_torque_curve(k, self.speed[k]);
1052 let demand = drive.torque_demand;
1053 let available = if demand >= 0.0 { high } else { -low };
1054 load.utilisation = load.utilisation.max(demand.abs() / available.max(1e-9));
1055 if sampled {
1056 load.points.push((self.speed[k], torque));
1057 if sim.control.drive_params_of(k).overload.is_some() {
1058 self.overload[k].1.push(((self.steps + 1) as f64 * sim.dt, drive.overload_nodes()));
1059 }
1060 }
1061 }
1062 let (drives, p) = (&sim.control.drives, sim.control.drive_params());
1063 let braking: f64 = match (p.dc_link, p.shared_dc_link) {
1064 (true, true) => drives.first().map_or(0.0, |d| d.resistor_power),
1065 (true, false) => drives.iter().map(|d| d.resistor_power).sum(),
1066 (false, _) => drives.iter().map(|d| (-d.power).max(0.0)).sum(),
1067 };
1068 self.braking_peak = self.braking_peak.max(braking);
1069 self.steps += 1;
1070 }
1071
1072 pub fn finish(mut self, sim: &Sim, duration: f64) -> CycleLoad {
1073 let steps = self.steps.max(1) as f64;
1074 for (k, load) in self.loads.iter_mut().enumerate() {
1075 load.rms_torque = (load.rms_torque / steps).sqrt();
1076 load.rms_current = (load.rms_current / steps).sqrt();
1077 if let (Some(account), true) = (&mut load.dc_link_account, self.braking[k] != 0.0) {
1078 account.push(self.braking[k]);
1079 }
1080 load.thermal_current = (load.thermal_current / steps).sqrt();
1081 load.iron_loss /= steps;
1082 load.cubic_mean_torque =
1083 if self.cubic[k].1 > 0.0 { (self.cubic[k].0 / self.cubic[k].1).cbrt() } else { 0.0 };
1084 load.gearbox_torque = self.gear[k].map(|(_, peak, cubed)| {
1085 (peak, if self.cubic[k].1 > 0.0 { (cubed / self.cubic[k].1).cbrt() } else { 0.0 })
1086 });
1087 load.mean_speed = self.cubic[k].1 / steps;
1088 load.gearbox_life_torque = self.gear[k]
1089 .map(|_| if self.cubic[k].1 > 0.0 { (self.gear_life[k] / self.cubic[k].1).powf(0.3) } else { 0.0 });
1090 load.gearbox_torque_by_speed = std::mem::take(&mut self.gear_bands[k]);
1091 load.gearbox_torque_spectrum = self.gear_spectrum[k].iter().map(|speed| speed / steps).collect();
1092 let (cubed, weight) = self.radial_sums[k];
1093 load.radial_load_equivalent =
1094 self.pulley_radial[k].map(|_| if weight > 0.0 { (cubed / weight).cbrt() } else { 0.0 });
1095 load.radial_load_peak = self.pulley_radial[k].map(|_| self.radial_peaks[k]);
1096 let p = sim.control.drive_params_of(k);
1097 load.winding_rise = p.settled_rise(load.thermal_current, load.iron_loss);
1098 if let (true, Some(n)) = (p.heating, &p.thermal_nodes) {
1101 let (s, iron) = (n.winding_share, p.iron_heating(load.iron_loss));
1102 load.housing_rise = load.winding_rise - s * (load.winding_rise - (1.0 - s) * iron);
1103 }
1104 if let Some(o) = &p.overload {
1105 let (start, samples) = &self.overload[k];
1106 let end = (self.steps as f64 * sim.dt, sim.control.drives[k].overload_nodes());
1107 load.drive_overload = repeating_peak(o, *start, samples, end);
1108 }
1109 load.thermal_utilisation = load.rms_torque / sim.control.drive_params_of(k).rated_torque;
1110 load.torque_parts =
1111 self.parts[k].map(|_| self.part_sums[k].map(|(peak, squares)| (peak, (squares / steps).sqrt())));
1112 load.peak_dc_link_voltage = load.peak_dc_link_voltage.max(sim.control.drives[k].dc_voltage);
1114 }
1115 self.sample_now(sim);
1116 let budget = self.budget(sim);
1117 let part_rises = sim
1118 .heated
1119 .iter()
1120 .zip(&self.heat)
1121 .map(|(h, heat)| (h.part.clone(), h.resistance * heat / duration))
1122 .collect();
1123 let samples = self.path_error[0].2.max(1) as f64;
1124 let equivalent = |g: usize| equivalent_load(self.guide_loads[g].1, self.guide_weights[g]);
1127 let speed = |g: usize| self.guide_axes[g].map(|_| self.guide_speeds[g] / samples);
1128 let wear = |g: usize| equivalent(g).powi(3) * speed(g).unwrap_or(1.0);
1129 let guide = (0..self.guide_loads.len()).max_by(|&a, &b| wear(a).total_cmp(&wear(b)));
1130 let peak = self.guide_loads.iter().map(|g| g.0).reduce(f64::max);
1131 let guide_load = guide.zip(peak).map(|(g, peak)| (peak, equivalent(g)));
1132 let guide_speed = guide.and_then(speed);
1133 let guides = (0..self.guide_loads.len())
1134 .map(|g| GuideLoad { peak: self.guide_loads[g].0, equivalent: equivalent(g), speed: speed(g) })
1135 .collect();
1136 CycleLoad {
1137 duration,
1138 belt_tension: self.belt_tension,
1139 belt_slack_time: self.slack.map(|i| self.sample[i] - self.slack_start),
1140 belt_tooth_jumps: (!self.jumps.is_empty())
1141 .then(|| self.jumps.iter().map(|&i| self.sample[i]).sum::<f64>() - self.jumps_start),
1142 belt_span_detuning: self.detuning.map(|_| self.lowest_detuning),
1143 radial_load_peak: (!self.radial.is_empty()).then_some(self.radial_peak),
1144 condition_peak: self.condition.map(|_| self.condition_peak),
1145 guide_load,
1146 guide_speed,
1147 guides,
1148 path_error_peak: self.path_error[0].0,
1149 path_error_rms: (self.path_error[0].1 / self.path_error[0].2.max(1) as f64).sqrt(),
1150 tracking_error_peak: self.tracking_error[0],
1151 dwell_error_peak: self.dwell_error[0],
1152 path_angle_error_peak: self.path_error[1].0 + 0.0,
1154 path_angle_error_rms: (self.path_error[1].1 / self.path_error[1].2.max(1) as f64).sqrt(),
1155 tracking_angle_error_peak: self.tracking_error[1] + 0.0,
1156 dwell_angle_error_peak: self.dwell_error[1] + 0.0,
1157 path_error_series: {
1158 let start = self.path_series.first().map_or(0.0, |s| s[0]);
1159 self.path_series.iter().map(|&[t, place, turn]| [t - start, place, turn]).collect()
1160 },
1161 tripped: sim.control.drives.iter().any(|d| d.tripped) || sim.control.fault.is_some(),
1162 motors: self.loads,
1163 budget,
1164 part_rises,
1165 checks: std::mem::take(&mut self.checks)
1166 .into_iter()
1167 .map(|(c, _, peak, sum)| {
1168 let value = if c.life { samples / sum } else { peak };
1169 (c, value)
1170 })
1171 .chain(std::mem::take(&mut self.plan_checks).into_iter().map(|(c, _, peak)| (c, peak)))
1172 .chain(cam_checks(sim.machine.as_ref()))
1173 .collect(),
1174 clearance: (!sim.obstacles.is_empty()).then_some(sim.least_clearance),
1175 contact: sim.contact.clone(),
1176 own_clearance: sim.own_parts.own.as_ref().map(|own| own.clearance),
1177 braking_power_peak: self.braking_peak,
1178 warm_start: None,
1179 conveyor: sim.control.conveyor().map(|(c, _)| {
1180 let missed = c.missed - self.missed_before;
1181 ConveyorLoad {
1182 picks_per_minute: 60.0 / duration,
1183 tracking_peak: self.pick_tracking,
1184 missed,
1185 missed_per_minute: (missed as f64 * 60.0 / duration)
1186 .max(c.offered_per_minute() - 60.0 / duration)
1187 .max(0.0),
1188 }
1189 }),
1190 held_accelerations: self.held,
1191 }
1192 }
1193
1194 fn budget(&self, sim: &Sim) -> Option<EnergyBudget> {
1196 if self.losses.is_empty() {
1197 return None;
1198 }
1199 let own = sim.machine.signal_infos();
1200 let (now, (windings, capacitors, payload)) = (&self.machine_signals, self.end);
1203 let row = |id: &str, owner_key: &str, quantity_key: &str, energy: f64| BudgetRow {
1204 id: id.into(),
1205 owner_key: owner_key.into(),
1206 quantity_key: quantity_key.into(),
1207 energy,
1208 };
1209 let mut rows: Vec<BudgetRow> = sim
1210 .machine
1211 .motors()
1212 .iter()
1213 .zip(&self.copper)
1214 .map(|(m, copper)| row(&format!("copper.{}", m.id), m.key, "budget-copper", *copper))
1215 .collect();
1216 rows.extend(
1218 sim.machine
1219 .motors()
1220 .iter()
1221 .zip(&self.emf)
1222 .filter(|(_, emf)| **emf != 0.0)
1223 .map(|(m, emf)| row(&format!("emf.{}", m.id), m.key, "budget-emf", *emf)),
1224 );
1225 let p = sim.control.drive_params();
1226 if p.dc_link {
1227 rows.push(row("resistor", "group-drive", "budget-resistor", self.resistor));
1228 rows.push(row("discharge", "group-drive", "budget-discharge", self.discharge));
1229 }
1230 if p.regenerative {
1231 rows.push(row("mains", "group-drive", "budget-mains", self.mains));
1232 }
1233 if p.dc_link {
1235 rows.push(row("line_module", "group-drive", "budget-line-module", self.line_loss));
1236 }
1237 rows.extend(
1238 self.losses
1239 .iter()
1240 .zip(&self.lost)
1241 .map(|(&i, lost)| row(&own[i].id, &own[i].owner_key, &own[i].quantity_key, *lost)),
1242 );
1243 rows.push(row("windings", "group-drive", "budget-windings", windings - self.start.1));
1244 if p.dc_link {
1245 rows.push(row("capacitors", "group-drive", "budget-capacitors", capacitors - self.start.2));
1246 }
1247 rows.extend(
1248 self.energies
1249 .iter()
1250 .zip(&self.start.0)
1251 .map(|(&i, start)| row(&own[i].id, &own[i].owner_key, &own[i].quantity_key, now[i] - start)),
1252 );
1253 rows.push(row("payload", "group-energy", "budget-payload", self.start.3 - payload));
1255 if sim.crash {
1257 rows.push(row("crash", "group-energy", "budget-crash", self.crash.1 - self.crash.0));
1258 }
1259 let supply = if p.dc_link { self.drawn } else { self.supply };
1262 Some(EnergyBudget { supply, rows, shaft_work: self.work })
1263 }
1264}
1265
1266fn stored_electrically(sim: &Sim) -> (f64, f64) {
1268 let p = sim.control.drive_params();
1269 let drives = &sim.control.drives;
1270 let windings = drives.iter().enumerate().map(|(k, d)| d.magnetic_energy(sim.control.drive_params_of(k))).sum();
1271 let capacitance =
1274 |k: usize| if p.shared_dc_link { p.dc_capacitance } else { sim.control.drive_params_of(k).dc_capacitance };
1275 let capacitors = drives.iter().enumerate().map(|(k, d)| 0.5 * capacitance(k) * d.dc_voltage * d.dc_voltage).sum();
1276 (windings, if p.dc_link { capacitors } else { 0.0 })
1277}
1278
1279pub fn analyse_cycle(sim: &mut Sim) -> Result<CycleLoad, CommandError> {
1293 analyse_cycle_with(sim, true)
1294}
1295
1296pub fn analyse_cycle_with(sim: &mut Sim, views: bool) -> Result<CycleLoad, CommandError> {
1299 check_cancelled();
1301 if let Some(points) = sim.plan_configured_path() {
1302 return analyse_trajectory_with(sim, points?, views);
1303 }
1304 sim.command(Command::StartCycle)?;
1305 let warm = sim.warm_start && !fed_back_rises(sim).is_empty();
1306 let mut tally = Tally::new(sim, views);
1307 let (mut passes, mut last, mut start) = (0usize, sim.control.cycle_passes(), 0.0);
1308 let (mut started_at, mut before) = (Vec::new(), None);
1309 let (mut spans, mut period, mut span_from, mut history) = (0usize, 1usize, 2usize, Vec::new());
1311 let (mut repeat, mut measured) = (None, None);
1312 loop {
1313 sim.step();
1314 let now = sim.control.cycle_passes();
1316 if now != last {
1317 passes += 1;
1318 let span_ends = passes == span_from + period;
1319 if warm && passes >= 3 && span_ends {
1320 let load = std::mem::replace(&mut tally, Tally::new(sim, views)).finish(sim, sim.time() - start);
1322 let was = period;
1323 let next = warm_pass(
1324 sim,
1325 &started_at,
1326 &load,
1327 spans,
1328 &mut before,
1329 &mut period,
1330 &mut history,
1331 Some(&mut repeat),
1332 );
1333 if let Some(warm_start) = next {
1334 let _ = sim.command(Command::Stop);
1335 let load = if warm_start.repeat.is_some() { measured.take().unwrap_or(load) } else { load };
1337 return Ok(CycleLoad { warm_start: Some(warm_start), ..load });
1338 }
1339 if repeat.is_some() {
1340 measured = Some(load);
1341 }
1342 spans = if period == was { spans + 1 } else { 0 };
1343 span_from = passes;
1344 }
1345 if passes == 2 || warm && passes > 2 && span_from == passes {
1346 started_at = fed_back_rises(sim);
1347 (start, tally) = (sim.time(), Tally::new(sim, views));
1350 tally.budget_skip = 1;
1351 } else if passes == 3 {
1352 break;
1353 }
1354 }
1355 last = now;
1356 if sim.time() > 600.0 {
1357 return Err(CommandError { key: "error-cycle-timeout" });
1358 }
1359 if !sim.control.busy() && sim.control.enabled() {
1361 return Err(CommandError { key: "error-conveyor-unreachable" });
1362 }
1363 tally.step(sim);
1364 if !sim.control.enabled() {
1366 break;
1367 }
1368 }
1369 let _ = sim.command(Command::Stop);
1370 if let (Some((_, done)), Some(load)) = (repeat, measured) {
1372 return Ok(CycleLoad { warm_start: Some(done), ..load });
1373 }
1374 let duration = sim.time() - start;
1375 let warm_start =
1378 (warm && passes > 2).then(|| WarmStart { passes: passes - 2, change: f64::INFINITY, period: 1, repeat: None });
1379 Ok(CycleLoad { warm_start, ..tally.finish(sim, duration) })
1380}
1381
1382pub fn analyse_trajectory(sim: &mut Sim, points: Vec<(f64, Vec<f64>)>) -> Result<CycleLoad, CommandError> {
1387 analyse_trajectory_with(sim, points, true)
1388}
1389
1390pub fn analyse_trajectory_with(
1392 sim: &mut Sim,
1393 points: Vec<(f64, Vec<f64>)>,
1394 views: bool,
1395) -> Result<CycleLoad, CommandError> {
1396 let end = points.last().map_or(0.0, |p| p.0) + 0.3;
1397 let warm = sim.warm_start && !fed_back_rises(sim).is_empty();
1398 let start_state = sim.snapshot();
1400 let mut before = None;
1401 for passes in 0.. {
1402 let started_at = fed_back_rises(sim);
1403 sim.command(Command::Trajectory(points.clone()))?;
1404 let (mut tally, start) = (Tally::new(sim, views), sim.time());
1405 while sim.time() - start < end {
1406 sim.step();
1407 tally.step(sim);
1408 }
1409 let load = tally.finish(sim, end);
1410 if !warm {
1411 return Ok(load);
1412 }
1413 if !sim.control.enabled() {
1414 return Ok(CycleLoad {
1415 warm_start: (passes > 0).then_some(WarmStart {
1416 passes,
1417 change: f64::INFINITY,
1418 period: 1,
1419 repeat: None,
1420 }),
1421 ..load
1422 });
1423 }
1424 let (mut period, mut history) = (1, Vec::new());
1426 if let Some(warm_start) =
1427 warm_pass(sim, &started_at, &load, passes, &mut before, &mut period, &mut history, None)
1428 {
1429 return Ok(CycleLoad { warm_start: Some(warm_start), ..load });
1430 }
1431 let rises = fed_back_rises(sim);
1432 sim.restore(&start_state).expect("a snapshot of this very simulation");
1433 set_rises(sim, &rises);
1434 }
1435 unreachable!()
1436}
1437
1438pub fn s1_torque(cfg: &Config, speed: f64) -> Result<Option<f64>, ConfigError> {
1444 let curve = crate::drive::s1_curve_of(cfg)?;
1445 if !curve.is_empty() {
1446 return Ok(Some(crate::drive::s1_interpolated(&curve, speed)));
1447 }
1448 if cfg.get("motor.stall_current_a").is_err() {
1449 return Ok(None);
1450 }
1451 let still = cfg.positive("motor.torque_constant_nm_a")? * cfg.positive("motor.stall_current_a")?;
1452 let (rated, rated_speed) = (cfg.positive("drive.rated_torque_nm")?, cfg.positive("drive.rated_speed_rad_s")?);
1453 Ok(Some(crate::drive::s1_line(still, rated, rated_speed, speed)))
1454}
1455
1456#[derive(Debug, Clone, PartialEq)]
1458pub struct Verdict {
1459 pub check: &'static str,
1461 pub motor: Option<usize>,
1463 pub value: f64,
1464 pub limit: f64,
1465 pub ok: bool,
1466}
1467
1468pub fn any_not_finite<'a>(verdicts: impl IntoIterator<Item = &'a Verdict>) -> bool {
1471 verdicts.into_iter().any(|v| !v.value.is_finite() || !v.limit.is_finite())
1472}
1473
1474pub const RATINGS_BEYOND_DEFAULT: [&str; 92] = [
1478 "ratings.guide_moment_x_nm",
1480 "ratings.guide_moment_y_nm",
1481 "ratings.guide_moment_z_nm",
1482 "joint.stop_min_deg",
1484 "joint.stop_max_deg",
1485 "ratings.guide_carriages",
1488 "ratings.guide_rail_length_m",
1489 "mass.guide_carriages_kg",
1490 "friction_x.seal_drag_n",
1491 "friction.seal_drag_n",
1492 "slide.seal_drag_n",
1493 "gearbox.hysteresis_stiffness_factor",
1495 "gearbox.mesh_stiffness_factor",
1496 "rack.pressure_angle_deg",
1497 "ratings.housing_max_rise_k",
1499 "motor.s1_curve_speed_rad_s",
1501 "motor.s1_curve_torque_nm",
1502 "ratings.max_stopping_distance_m",
1504 "ratings.max_stopping_angle_rad",
1505 "effects.gripper_time",
1507 "gripper",
1508 "gripper.kind",
1509 "gripper.close_s",
1510 "gripper.open_s",
1511 "gripper.cup_volume_m3",
1512 "gripper.generator_flow_m3_s",
1513 "gripper.vacuum_pa",
1514 "gripper.holding_pressure_pa",
1515 "gripper.vent_flow_m3_s",
1516 "gripper.release_pressure_pa",
1517 "gripper.cup_area_m2",
1518 "gripper.friction_coefficient",
1519 "ratings.gripper_safety_factor",
1520 "path",
1522 "path.file",
1523 "path.program",
1524 "path.time_optimal",
1525 "program",
1527 "program.orientation_speed_rad_s",
1528 "profile.feed_override",
1530 "ratings.settling_tolerance_rad",
1531 "ratings.tracking_tolerance_m",
1533 "ratings.tracking_tolerance_rad",
1534 "ratings.pulley_max_torque_nm",
1535 "ratings.motor_bearing_load_rating_n",
1536 "scene",
1538 "scene.meshes_dir",
1539 "conveyor",
1540 "conveyor.enabled",
1541 "conveyor.direction",
1542 "conveyor.speed_m_s",
1543 "conveyor.ramp_s",
1544 "conveyor.origin",
1545 "conveyor.length_m",
1546 "conveyor.pitch_s",
1547 "conveyor.arrivals_s",
1548 "conveyor.window_m",
1549 "conveyor.lift",
1550 "conveyor.grip_s",
1551 "conveyor.release_s",
1552 "conveyor.place",
1553 "conveyor.place_direction",
1554 "conveyor.place_speed_m_s",
1555 "conveyor.tracking_tolerance_m",
1556 "motor.kind",
1557 "motor.rotor_teeth",
1558 "motor.detent_torque_nm",
1559 "effects.detent_torque",
1560 "drive.microsteps",
1561 "drive.stepper_current_a",
1562 "motor.rotor_resistance_ohm",
1563 "motor.magnetizing_inductance_h",
1564 "motor.stator_leakage_inductance_h",
1565 "motor.rotor_leakage_inductance_h",
1566 "motor.rated_voltage_v",
1567 "motor.rated_frequency_hz",
1568 "drive.induction_control",
1569 "drive.vf_boost_v",
1570 "drive.vf_slip_compensation",
1571 "effects.thermal_growth",
1573 "effects.lead_error",
1574 "accuracy",
1575 "accuracy.axes",
1576 "accuracy.screw_expansion_per_k",
1577 "accuracy.belt_expansion_per_k",
1578 "ratings.max_positioning_error_m",
1579 "ratings.max_repeatability_m",
1580 "ratings.max_positioning_error_rad",
1581 "ratings.max_repeatability_rad",
1582 "ratings.drive_ambient_c",
1584 "ratings.drive_altitude_m",
1585 "ratings.drive_pulse_frequency_hz",
1586];
1587
1588fn at_most(check: &'static str, motor: Option<usize>, value: f64, limit: f64) -> Verdict {
1589 Verdict { check, motor, value, limit, ok: value <= limit }
1590}
1591
1592fn at_least(check: &'static str, motor: Option<usize>, value: f64, limit: f64) -> Verdict {
1593 Verdict { check, motor, value, limit, ok: value >= limit }
1594}
1595
1596pub const AT_LEAST: [&str; 11] = [
1599 "belt-least-tension",
1600 "pulley-bearing-life",
1601 "gearbox-life",
1602 "gearbox-gearing-life",
1603 "motor-bearing-life",
1604 "guide-life",
1605 "belt-span-resonance",
1606 "screw-life",
1607 "strain-wave-life",
1608 "collision",
1609 "self-collision",
1610];
1611
1612pub fn utilisation(v: &Verdict) -> f64 {
1616 if AT_LEAST.contains(&v.check) && v.value <= 0.0 {
1617 return f64::INFINITY;
1618 }
1619 if AT_LEAST.contains(&v.check) { v.limit / v.value } else { v.value / v.limit }
1620}
1621
1622pub fn verdicts(cfg: &Config, load: &CycleLoad) -> Result<Vec<Verdict>, ConfigError> {
1665 let cfg = &crate::catalog::parts_applied(cfg)?;
1666 for (name, value) in cfg.get("ratings").ok().and_then(|ratings| ratings.as_table()).into_iter().flatten() {
1670 if !value.is_array() && !value.is_table() {
1671 cfg.f64(&format!("ratings.{name}"))?;
1672 }
1673 }
1674 let rating = |name: &str| cfg.f64(&format!("ratings.{name}")).ok();
1675 let simulated = cfg.bool("effects.dc_link")?;
1676 let mut out = Vec::new();
1677 let line_up = cfg.get("drive.braking_module").is_ok() && cfg.bool("drive.braking_module")?;
1680 let mut line_up_brakes = false;
1681 let mut regenerated_excess = 0.0;
1682 let shared = cfg;
1683 for (k, m) in load.motors.iter().enumerate() {
1684 let cfg = &crate::catalog::motor_config(shared, &m.id)?;
1686 let rating = |name: &str| cfg.f64(&format!("ratings.{name}")).ok();
1687 let (bus, rated_rise) = (cfg.positive("drive.bus_voltage_v")?, cfg.positive("motor.rated_temperature_rise_k")?);
1688 out.push(at_most("motor-peak", Some(k), m.utilisation, 1.0));
1690 out.push(at_most("motor-thermal", Some(k), m.winding_rise, rated_rise));
1691 if let Some(angle) = m.load_angle {
1693 out.push(at_most("stepper-synchronism", Some(k), angle, std::f64::consts::FRAC_PI_2));
1694 }
1695 let servo = cfg.get("motor.kind").ok().and_then(|v| v.as_str()).is_none_or(|kind| kind == "servo");
1698 if let (true, Some(limit)) = (servo, s1_torque(cfg, m.mean_speed)?) {
1699 out.push(at_most("motor-s1", Some(k), m.rms_torque, limit));
1700 }
1701 if cfg.get("drive.max_speed_rad_s").is_ok() {
1703 out.push(at_most("motor-speed", Some(k), m.peak_speed, cfg.positive("drive.max_speed_rad_s")?));
1704 }
1705 if let Some(limit) = rating("drive_rated_current_a") {
1708 out.push(at_most("drive-current", Some(k), m.rms_current, limit));
1709 }
1710 if let Some(limit) = rating("drive_max_current_a") {
1711 out.push(at_most("drive-peak-current", Some(k), m.peak_current, limit));
1712 }
1713 if let Some(o) = crate::drive::Overload::from_config(cfg)? {
1716 out.push(at_most("drive-overload", Some(k), m.drive_overload, o.trip));
1717 }
1718 if let (Some((peak, _)), Some(limit)) = (m.gearbox_torque, rating("pulley_max_torque_nm")) {
1719 out.push(at_most("pulley-torque", Some(k), peak, limit));
1720 }
1721 if let (Some(peak), Some(limit)) = (m.radial_load_peak, rating("shaft_max_radial_load_n")) {
1723 out.push(at_most("gearbox-radial-load", Some(k), peak, limit));
1724 }
1725 if let (Some((_, cubic_mean)), Some(limit)) = (m.gearbox_torque, rating("gearbox_rated_torque_nm")) {
1726 out.push(at_most("gearbox-continuous", Some(k), cubic_mean, limit));
1727 }
1728 if let Some(limit) = rating("gearbox_max_input_speed_rpm") {
1729 out.push(at_most("gearbox-input-speed", Some(k), m.peak_speed * 30.0 / std::f64::consts::PI, limit));
1730 }
1731 if let (Some((peak, _)), Some(limit)) = (m.gearbox_torque, rating("gearbox_max_torque_nm")) {
1732 out.push(at_most("gearbox-peak", Some(k), peak, limit));
1733 }
1734 if reliability_factor(cfg).is_none() {
1736 return Err(ConfigError::Invalid("ratings.bearing_reliability_percent".into()));
1737 }
1738 lubrication(cfg)?;
1739 if let Some(required) = rating("required_life_h") {
1740 if let Some(life) = pulley_bearing_life_h(cfg, m) {
1741 out.push(at_least("pulley-bearing-life", Some(k), life, required));
1742 }
1743 if let Some(life) = gearbox_life_h(cfg, m) {
1744 out.push(at_least("gearbox-life", Some(k), life, required));
1745 }
1746 if let Some(life) = gearbox_gearing_life_h(cfg, m) {
1747 out.push(at_least("gearbox-gearing-life", Some(k), life, required));
1748 }
1749 if let Some(life) = motor_bearing_life_h(cfg, m) {
1750 out.push(at_least("motor-bearing-life", Some(k), life, required));
1751 }
1752 }
1753 if let Some(utilisation) = belt_tooth_utilisation(cfg, m)? {
1754 out.push(at_most("belt-tooth-load", Some(k), utilisation, 1.0));
1755 }
1756 if let (Some(capacitance), Some(threshold)) = (rating("dc_link_capacitance_uf"), rating("braking_threshold_v"))
1759 {
1760 if threshold <= bus {
1762 return Err(ConfigError::Invalid("ratings.braking_threshold_v".into()));
1763 }
1764 let room = 0.5 * capacitance * 1e-6 * (threshold * threshold - bus * bus);
1765 let (continuous, peak) = (rating("braking_resistor_continuous_w"), rating("braking_resistor_peak_w"));
1766 let (stored, resistor, mean_power, peak_power) = if simulated {
1768 let stored = 0.5 * capacitance * 1e-6 * (m.peak_dc_link_voltage.powi(2) - bus * bus);
1769 (stored, m.resistor_energy > 0.0, m.resistor_energy / load.duration, m.peak_resistor_power)
1770 } else {
1771 let (excess, fill) = match &m.dc_link_account {
1774 Some(account) if account.room == room => account.finish(),
1775 _ => resistor_excess(&m.regeneration_events, room),
1776 };
1777 regenerated_excess += excess;
1778 (fill, fill > room, excess / load.duration, m.peak_regenerated_power)
1779 };
1780 out.push(Verdict {
1782 check: "dc-link-energy",
1783 motor: Some(k),
1784 value: stored,
1785 limit: room,
1786 ok: !resistor || continuous.is_some(),
1787 });
1788 line_up_brakes |= resistor;
1789 if resistor && !line_up {
1790 if let Some(limit) = continuous {
1791 out.push(at_most("braking-resistor-continuous", Some(k), mean_power, limit));
1792 }
1793 if let Some(limit) = peak {
1794 out.push(at_most("braking-resistor-peak", Some(k), peak_power, limit));
1795 }
1796 }
1797 }
1798 if let (true, Some(limit)) = (simulated, rating("dc_link_overvoltage_v")) {
1800 out.push(at_most("dc-link-overvoltage", Some(k), m.peak_dc_link_voltage, limit));
1801 }
1802 if simulated && cfg.bool("effects.regenerative_supply")? {
1805 if let Some(limit) = rating("line_module_rated_power_w") {
1806 out.push(at_most("line-module-continuous", Some(k), m.line_module_energy / load.duration, limit));
1807 }
1808 if let Some(limit) = rating("line_module_max_power_w") {
1809 out.push(at_most("line-module-peak", Some(k), m.peak_line_module_power, limit));
1810 }
1811 }
1812 }
1813 if line_up && line_up_brakes {
1815 let shared = simulated && cfg.bool("effects.shared_dc_link")?;
1816 let energy: f64 = match (simulated, shared) {
1817 (true, true) => load.motors.first().map_or(0.0, |m| m.resistor_energy),
1818 (true, false) => load.motors.iter().map(|m| m.resistor_energy).sum(),
1819 (false, _) => regenerated_excess,
1820 };
1821 if let Some(limit) = rating("braking_resistor_continuous_w") {
1822 out.push(at_most("braking-resistor-continuous", None, energy / load.duration, limit));
1823 }
1824 if let Some(limit) = rating("braking_resistor_peak_w") {
1825 out.push(at_most("braking-resistor-peak", None, load.braking_power_peak, limit));
1826 }
1827 }
1828 if let Some(limit) = rating("settling_tolerance_m") {
1829 out.push(at_most("settling", None, load.dwell_error_peak, limit));
1830 }
1831 if let Some(limit) = rating("settling_tolerance_rad") {
1833 out.push(at_most("settling-angle", None, load.dwell_angle_error_peak, limit));
1834 }
1835 if let Some(limit) = rating("tracking_tolerance_m") {
1838 out.push(at_most("tracking", None, load.tracking_error_peak, limit));
1839 }
1840 if let Some(limit) = rating("tracking_tolerance_rad") {
1841 out.push(at_most("tracking-angle", None, load.tracking_angle_error_peak, limit));
1842 }
1843 if let (Some(crate::gripper::Gripper { hold: Some((hold, mu)), .. }), Some(factor)) =
1846 (crate::gripper::Gripper::from_config(cfg)?, rating("gripper_safety_factor"))
1847 {
1848 let (mass, g) = (crate::gripper::payload_mass(cfg)?, crate::gripper::gravity(cfg)?);
1849 let asked = load
1850 .held_accelerations
1851 .iter()
1852 .map(|&[up, side]| crate::gripper::demand(mass, [side, 0.0, up], g, mu))
1853 .fold(0.0, f64::max);
1854 out.push(at_most("gripper-hold", None, asked, hold / factor));
1855 }
1856 if let Some((slackest, tightest)) = load.belt_tension {
1857 if let Some(limit) = rating("belt_max_tension_n") {
1858 out.push(Verdict { check: "belt-tension", motor: None, value: tightest, limit, ok: tightest <= limit });
1859 }
1860 if let Some(limit) = rating("belt_min_tension_n") {
1861 let never_slack = load.belt_slack_time.is_none_or(|time| time <= 0.0);
1864 out.push(Verdict {
1865 check: "belt-least-tension",
1866 motor: None,
1867 value: slackest,
1868 limit,
1869 ok: slackest > limit && never_slack,
1870 });
1871 }
1872 }
1873 if let Some(jumps) = load.belt_tooth_jumps {
1874 out.push(at_most("belt-tooth-jump", None, jumps, 0.0));
1875 }
1876 if let (Some(detuning), Some(band)) = (load.belt_span_detuning, rating("belt_span_resonance_band")) {
1877 out.push(at_least("belt-span-resonance", None, detuning, band));
1878 }
1879 for (check, value) in &load.checks {
1882 let a1 = reliability_factor(cfg)
1883 .ok_or_else(|| ConfigError::Invalid("ratings.bearing_reliability_percent".into()))?;
1884 out.push(if check.life {
1885 at_least(check.check, check.motor, value * a1, check.limit)
1886 } else {
1887 at_most(check.check, check.motor, *value, check.limit)
1888 });
1889 }
1890 if let Some(clearance) = load.clearance {
1892 let limit = cfg.non_negative("profile.min_clearance_m")?;
1893 out.push(Verdict {
1894 check: "collision",
1895 motor: None,
1896 value: clearance,
1897 limit,
1898 ok: clearance >= limit && clearance > 0.0,
1899 });
1900 }
1901 if let Some(clearance) = load.own_clearance {
1902 let limit = cfg.non_negative("profile.min_clearance_m")?;
1903 out.push(Verdict {
1904 check: "self-collision",
1905 motor: None,
1906 value: clearance,
1907 limit,
1908 ok: clearance >= limit && clearance > 0.0,
1909 });
1910 }
1911 if let (Some(value), Some(limit)) = (load.condition_peak, rating("max_condition_number")) {
1912 out.push(at_most("singularity", None, value, limit));
1913 }
1914 let per_motor = load.motors.iter().any(|m| m.radial_load_peak.is_some());
1917 if let (Some(value), Some(limit), false) = (load.radial_load_peak, rating("shaft_max_radial_load_n"), per_motor) {
1918 out.push(at_most("gearbox-radial-load", None, value, limit));
1919 }
1920 if let (Some((peak, _)), Some(limit)) = (load.guide_load, rating("guide_max_load_n")) {
1921 out.push(at_most("guide-load", None, peak, limit));
1922 }
1923 if let (Some(life), Some(required)) = (guide_life_h(cfg, load), rating("required_life_h")) {
1924 out.push(at_least("guide-life", None, life, required));
1925 }
1926 if crate::sim::heats(cfg)? {
1929 for (kind, check) in [("gearbox", "gearbox-thermal"), ("guide", "guide-thermal")] {
1930 let hottest =
1931 load.part_rises.iter().filter(|(part, _)| part.kind == kind).map(|(_, rise)| *rise).reduce(f64::max);
1932 if let Some(rise) = hottest {
1933 out.push(at_most(check, None, rise, cfg.positive(&format!("thermal.{kind}_max_rise_k"))?));
1934 }
1935 }
1936 }
1937 if let Some(warm) = load.warm_start.filter(|w| w.change.is_finite()) {
1941 out.push(at_most("thermal-warm-start", None, warm.change, WARM_START_TOLERANCE_K));
1942 if let Some(apart) = warm.repeat {
1944 out.push(at_most("thermal-cycle-repeat", None, apart, WARM_START_TOLERANCE_K));
1945 }
1946 }
1947 if let Some(c) = load.conveyor {
1949 out.push(at_most("pick-tracking", None, c.tracking_peak, cfg.positive("conveyor.tracking_tolerance_m")?));
1950 out.push(at_most("parts-missed", None, c.missed_per_minute, 0.0));
1951 }
1952 Ok(out)
1953}
1954
1955fn equivalent_load(cubed_sum: f64, weight_sum: f64) -> f64 {
1958 if weight_sum > 0.0 { (cubed_sum / weight_sum).cbrt() } else { 0.0 }
1959}
1960
1961fn resistor_excess(events: &[f64], room: f64) -> (f64, f64) {
1968 let mut account = LinkAccount::new(room);
1969 events.iter().for_each(|&e| account.push(e));
1970 account.finish()
1971}
1972
1973#[derive(Debug, Clone, Default, PartialEq)]
1988pub struct LinkAccount {
1989 pub room: f64,
1991 prefix: Vec<f64>,
1993 grid: Vec<[f64; 3]>,
1996 low: f64,
1998 high: f64,
1999 met: bool,
2000 spilled: f64,
2002 most: f64,
2003}
2004
2005impl LinkAccount {
2006 pub fn new(room: f64) -> Self {
2007 Self { room, high: room, ..Default::default() }
2008 }
2009
2010 pub fn push(&mut self, e: f64) {
2012 let room = self.room;
2013 if self.met {
2014 let fill = (self.low + e).max(0.0);
2015 (self.spilled, self.most, self.low) =
2016 (self.spilled + (fill - room).max(0.0), self.most.max(fill), fill.min(room));
2017 return;
2018 }
2019 if self.grid.is_empty() {
2020 self.prefix.push(e);
2021 if self.prefix.len() > LINK_PREFIX_CAP {
2022 self.grid = (0..LINK_GRID)
2023 .map(|j| {
2024 let mut pass = [j as f64 * room / (LINK_GRID - 1) as f64, 0.0, 0.0];
2025 self.prefix.iter().for_each(|&e| link_step(&mut pass, e, room));
2026 pass
2027 })
2028 .collect();
2029 self.prefix = Vec::new();
2030 }
2031 } else {
2032 self.grid.iter_mut().for_each(|pass| link_step(pass, e, room));
2033 }
2034 let step = |fill: f64| (fill + e).max(0.0).min(room);
2035 (self.low, self.high) = (step(self.low), step(self.high));
2036 self.met = self.low == self.high;
2038 }
2039
2040 pub fn finish(&self) -> (f64, f64) {
2043 let mut pass = [self.low, self.spilled, self.most];
2044 self.prefix.iter().for_each(|&e| link_step(&mut pass, e, self.room));
2045 if self.grid.len() >= 2 {
2046 let at = self.low / self.room * (self.grid.len() - 1) as f64;
2048 let j = (at.floor() as usize).min(self.grid.len() - 2);
2049 let (u, [a, b]) = (at - j as f64, [self.grid[j], self.grid[j + 1]]);
2050 let between = |q: usize| a[q] + u * (b[q] - a[q]);
2051 (pass[1], pass[2]) = (pass[1] + between(1), pass[2].max(between(2)));
2052 }
2053 (pass[1], pass[2])
2054 }
2055}
2056
2057pub const LINK_PREFIX_CAP: usize = 1 << 17;
2060
2061pub const LINK_GRID: usize = 257;
2063
2064fn link_step(pass: &mut [f64; 3], e: f64, room: f64) {
2066 let fill = (pass[0] + e).max(0.0);
2067 pass[2] = pass[2].max(fill);
2068 pass[1] += (fill - room).max(0.0);
2069 pass[0] = fill.min(room);
2070}
2071
2072pub fn guide_life_km(cfg: &Config, load: &CycleLoad) -> Option<f64> {
2082 let rating = cfg.f64("ratings.guide_dynamic_load_rating_n").ok()?;
2083 guides_of(load).iter().map(|g| (rating / g.equivalent).powi(3) * 50.0).reduce(f64::min)
2084}
2085
2086pub fn guide_life_h(cfg: &Config, load: &CycleLoad) -> Option<f64> {
2090 let rating = cfg.f64("ratings.guide_dynamic_load_rating_n").ok()?;
2091 let a1 = reliability_factor(cfg)?;
2092 let hours = |g: &GuideLoad| -> Option<f64> {
2093 Some((rating / g.equivalent).powi(3) * 50.0 * 1e3 / (g.speed? * 3600.0) * a1)
2094 };
2095 guides_of(load).iter().filter_map(hours).reduce(f64::min)
2096}
2097
2098fn guides_of(load: &CycleLoad) -> Vec<GuideLoad> {
2101 if !load.guides.is_empty() {
2102 return load.guides.clone();
2103 }
2104 load.guide_load
2105 .map(|(peak, equivalent)| GuideLoad { peak, equivalent, speed: load.guide_speed })
2106 .into_iter()
2107 .collect()
2108}
2109
2110pub const SPEED_BAND: f64 = 5.0;
2112
2113pub fn rating_life_h(c: f64, p: f64, rpm: f64) -> f64 {
2116 (c / p).powi(3) * 1e6 / (60.0 * rpm)
2117}
2118
2119pub fn reliability_factor(cfg: &Config) -> Option<f64> {
2124 let Ok(r) = cfg.f64("ratings.bearing_reliability_percent") else { return Some(1.0) };
2125 (90.0..=99.95).contains(&r).then(|| 0.95 * ((100.0 / r).ln() / (100.0_f64 / 90.0).ln()).powf(2.0 / 3.0) + 0.05)
2126}
2127
2128fn own_ratio(cfg: &Config, m: &MotorLoad) -> f64 {
2132 let own = crate::catalog::motor_config(cfg, &m.id);
2133 own.as_ref().ok().unwrap_or(cfg).f64("gearbox.ratio").unwrap_or(1.0)
2134}
2135
2136fn output_rpm(cfg: &Config, m: &MotorLoad) -> f64 {
2138 m.mean_speed * 30.0 / std::f64::consts::PI / own_ratio(cfg, m)
2139}
2140
2141pub fn pulley_bearing_life_h(cfg: &Config, m: &MotorLoad) -> Option<f64> {
2148 let c = cfg.f64("ratings.pulley_bearing_load_rating_n").ok()?;
2149 let (p, rpm) = (m.radial_load_equivalent?, output_rpm(cfg, m));
2150 Some(reliability_factor(cfg)? * pulley_bearing_a_iso(cfg, p, rpm)? * rating_life_h(c, p, rpm))
2151}
2152
2153pub fn pulley_bearing_a_iso(cfg: &Config, p: f64, rpm: f64) -> Option<f64> {
2157 Some(match lubrication(cfg).ok()? {
2158 Some(l) => life_modification_factor(
2159 l.viscosity / reference_viscosity(rpm, l.mean_diameter_mm),
2160 l.contamination * l.fatigue_limit / p,
2161 ),
2162 None => 1.0,
2163 })
2164}
2165
2166#[derive(Debug, Clone, Copy, PartialEq)]
2172pub struct Lubrication {
2173 pub viscosity: f64,
2174 pub contamination: f64,
2175 pub fatigue_limit: f64,
2176 pub mean_diameter_mm: f64,
2177}
2178
2179pub const LUBRICATION_KEYS: [&str; 4] = [
2181 "ratings.bearing_lubricant_viscosity_mm2_s",
2182 "ratings.bearing_contamination_factor",
2183 "ratings.pulley_bearing_fatigue_limit_n",
2184 "ratings.pulley_bearing_mean_diameter_mm",
2185];
2186
2187pub fn lubrication(cfg: &Config) -> Result<Option<Lubrication>, ConfigError> {
2190 if LUBRICATION_KEYS.iter().all(|key| cfg.get(key).is_err()) {
2191 return Ok(None);
2192 }
2193 let contamination = cfg.non_negative(LUBRICATION_KEYS[1])?;
2194 if contamination > 1.0 {
2195 return Err(ConfigError::Invalid(LUBRICATION_KEYS[1].into()));
2196 }
2197 let (viscosity, fatigue_limit, mean_diameter_mm) = (
2198 cfg.positive(LUBRICATION_KEYS[0])?,
2199 cfg.non_negative(LUBRICATION_KEYS[2])?,
2200 cfg.positive(LUBRICATION_KEYS[3])?,
2201 );
2202 Ok(Some(Lubrication { viscosity, contamination, fatigue_limit, mean_diameter_mm }))
2203}
2204
2205pub fn reference_viscosity(rpm: f64, mean_diameter_mm: f64) -> f64 {
2209 if rpm < 1000.0 {
2210 45000.0 * rpm.powf(-0.83) / mean_diameter_mm.sqrt()
2211 } else {
2212 4500.0 / rpm.sqrt() / mean_diameter_mm.sqrt()
2213 }
2214}
2215
2216pub fn life_modification_factor(kappa: f64, load_ratio: f64) -> f64 {
2221 let kappa = kappa.clamp(0.1, 4.0);
2224 let x = if kappa < 0.4 {
2225 2.5671 - 2.2649 / kappa.powf(0.054381)
2226 } else if kappa < 1.0 {
2227 2.5671 - 1.9987 / kappa.powf(0.19087)
2228 } else {
2229 2.5671 - 1.9987 / kappa.powf(0.071739)
2230 };
2231 let inner = 1.0 - x.max(0.0).powf(0.83) * load_ratio.cbrt();
2232 if inner <= 0.0 { 50.0 } else { (0.1 * inner.powf(-9.3)).min(50.0) }
2233}
2234
2235pub fn gearbox_life_h(cfg: &Config, m: &MotorLoad) -> Option<f64> {
2242 let (rated, reference) =
2243 (cfg.f64("ratings.gearbox_rated_torque_nm").ok()?, cfg.f64("ratings.gearbox_reference_speed_rpm").ok()?);
2244 Some(
2245 reliability_factor(cfg)? * 20000.0 * reference / output_rpm(cfg, m)
2246 * (rated / m.gearbox_life_torque?).powf(10.0 / 3.0),
2247 )
2248}
2249
2250const TORQUE_FLOOR: f64 = 0.1;
2253const TORQUE_BAND: f64 = 1.01;
2254
2255pub fn torque_band_floor(i: usize) -> f64 {
2257 TORQUE_FLOOR * TORQUE_BAND.powi(i as i32)
2258}
2259
2260pub const MAX_TORQUE_REVOLUTIONS: f64 = 30000.0;
2263
2264pub fn gearing_life_h(spectrum: impl IntoIterator<Item = (f64, f64)>, rated: f64, max: f64, exponent: f64) -> f64 {
2270 1.0 / spectrum
2272 .into_iter()
2273 .filter(|&(torque, _)| torque > rated)
2274 .map(|(torque, revolutions)| revolutions / (MAX_TORQUE_REVOLUTIONS * (max / torque).powf(exponent)))
2275 .fold(0.0, |sum, d| sum + d)
2276}
2277
2278pub fn gearbox_gearing_life_h(cfg: &Config, m: &MotorLoad) -> Option<f64> {
2287 let rating = |key: &str| cfg.f64(&format!("ratings.{key}")).ok();
2288 let (rated, max, exponent) = (
2289 rating("gearbox_rated_torque_nm")?,
2290 rating("gearbox_max_torque_nm")?,
2291 rating("gearbox_gearing_wohler_exponent")?,
2292 );
2293 m.gearbox_torque?;
2294 let per_hour = 3600.0 / (2.0 * std::f64::consts::PI) / own_ratio(cfg, m);
2295 let life = gearing_life_h(
2296 m.gearbox_torque_spectrum.iter().enumerate().map(|(i, speed)| (torque_band_floor(i + 1), speed * per_hour)),
2297 rated,
2298 max,
2299 exponent,
2300 );
2301 life.is_finite().then_some(life)
2302}
2303
2304pub fn motor_bearing_life_h(cfg: &Config, m: &MotorLoad) -> Option<f64> {
2312 let c = cfg.f64("ratings.motor_bearing_load_rating_n").ok()?;
2313 if own_ratio(cfg, m) != 1.0 {
2314 return None;
2315 }
2316 Some(reliability_factor(cfg)? * rating_life_h(c, m.radial_load_equivalent?, output_rpm(cfg, m)))
2317}
2318
2319pub fn belt_tooth_utilisation(cfg: &Config, m: &MotorLoad) -> Result<Option<f64>, ConfigError> {
2332 let Ok(rpm) = cfg.f64s("ratings.belt_tooth_load_rpm") else { return Ok(None) };
2333 let get = |key: &str| cfg.f64(key).ok();
2334 let (Some(width), Some(teeth), Some(factor), Some(radius)) = (
2335 get("ratings.belt_width_mm"),
2336 get("ratings.belt_teeth_in_mesh"),
2337 get("ratings.belt_service_factor"),
2338 get("geometry.pulley_radius_m"),
2339 ) else {
2340 return Ok(None);
2341 };
2342 let load = cfg.f64s("ratings.belt_tooth_load_n_cm")?;
2343 if load.len() != rpm.len() || rpm.is_empty() || rpm.windows(2).any(|w| w[0] >= w[1]) {
2344 return Err(ConfigError::Invalid("ratings.belt_tooth_load_rpm".into()));
2345 }
2346 if m.gearbox_torque.is_none() || (m.radial_load_equivalent.is_none() && m.belt_wrap.is_none()) {
2347 return Ok(None);
2348 }
2349 let allowed = |n: f64| -> f64 {
2350 let i = rpm.partition_point(|&r| r <= n);
2351 if i == 0 {
2352 load[0]
2353 } else if i == rpm.len() {
2354 load[i - 1]
2355 } else {
2356 load[i - 1] + (load[i] - load[i - 1]) * (n - rpm[i - 1]) / (rpm[i] - rpm[i - 1])
2357 }
2358 };
2359 let ratio = own_ratio(cfg, m);
2360 let teeth = match m.belt_wrap {
2361 Some(wrap) => wrap * radius / cfg.positive("belt.tooth_pitch_m")?,
2362 None => teeth,
2363 };
2364 let capacity = |n: f64| allowed(n) * width / 10.0 * teeth.min(12.0);
2365 let band_rpm = |i: usize| (i + 1) as f64 * SPEED_BAND * 30.0 / std::f64::consts::PI / ratio;
2366 Ok(Some(
2367 m.gearbox_torque_by_speed
2368 .iter()
2369 .enumerate()
2370 .map(|(i, torque)| torque / radius * factor / capacity(band_rpm(i)))
2371 .fold(0.0, f64::max),
2372 ))
2373}
2374
2375pub fn bounds(cfg: &Config) -> Result<Vec<(String, f64, f64)>, ConfigError> {
2386 fn walk(
2387 path: &str,
2388 value: &toml::Value,
2389 cfg: &Config,
2390 out: &mut Vec<(String, f64, f64)>,
2391 ) -> Result<(), ConfigError> {
2392 if let Some(table) = value.as_table() {
2393 return table.iter().try_for_each(|(key, v)| {
2394 walk(&if path.is_empty() { key.clone() } else { format!("{path}.{key}") }, v, cfg, out)
2395 });
2396 }
2397 cfg.f64(path)?;
2398 let whole = |v: f64| !cfg.get(path).is_ok_and(toml::Value::is_integer) || v.fract() == 0.0;
2400 match cfg.f64s(&format!("bounds.{path}"))?[..] {
2401 [low, high] if low <= high && whole(low) && whole(high) => out.push((path.into(), low, high)),
2402 _ => return Err(ConfigError::Invalid(format!("bounds.{path}"))),
2403 }
2404 Ok(())
2405 }
2406 let mut out = Vec::new();
2407 if let Ok(table) = cfg.get("bounds") {
2408 walk("", table, cfg, &mut out)?;
2409 }
2410 out.retain(|(path, ..)| !effect_off(cfg, path));
2411 Ok(out)
2412}
2413
2414pub(crate) fn followed(cfg: &Config, resolved: &Config, bounds: &[(String, f64, f64)]) -> Vec<(String, f64, f64)> {
2418 let own = |c: &Config, path: &str| match c.f64s(&format!("bounds.{path}")).as_deref() {
2419 Ok([low, high]) => Some((*low, *high)),
2420 _ => None,
2421 };
2422 bounds
2423 .iter()
2424 .map(|(path, low, high)| {
2425 let (low, high) = match (own(cfg, path), own(resolved, path)) {
2426 (Some(given), Some(now)) if given == (*low, *high) => now,
2427 _ => (*low, *high),
2428 };
2429 (path.clone(), low, high)
2430 })
2431 .collect()
2432}
2433
2434pub fn set_bounded(cfg: &mut Config, path: &str, value: f64) -> Result<(), ConfigError> {
2438 let value = if cfg.get(path)?.is_integer() {
2439 toml::Value::Integer(value.round() as i64)
2440 } else {
2441 toml::Value::Float(value)
2442 };
2443 cfg.set(path, value)
2444}
2445
2446const PATH_EFFECTS: [(&str, &[&str]); 38] = [
2450 ("follower.roller_width_m", &["follower_lift_off"]),
2451 ("follower.contact_", &["follower_lift_off"]),
2452 ("follower.guide_friction_n", &["follower_lift_off"]),
2453 ("thermal.", &["part_heating", "thermal_feedback"]),
2454 ("motor.pole_pairs", &["field_weakening"]),
2455 ("motor.d_inductance_h", &["field_weakening"]),
2456 ("motor.winding_resistance_share", &["motor_thermal_nodes"]),
2457 ("motor.winding_time_constant_s", &["motor_thermal_nodes"]),
2458 ("ratings.drive_base_load_current_a", &["drive_overload"]),
2459 ("ratings.drive_overload_time_constant_s", &["drive_overload"]),
2460 ("ratings.drive_max_current_time_s", &["drive_overload"]),
2461 ("ratings.drive_chip_", &["drive_overload"]),
2462 ("motor.magnet_temperature_coefficient_1_k", &["magnet_temperature"]),
2463 ("motor.stall_current_a", &["iron_loss"]),
2464 ("ratings.braking_resistor_time_constant_s", &["braking_resistor_heating"]),
2465 ("ratings.braking_resistor_rated_rise_k", &["braking_resistor_heating"]),
2466 ("thermal_feedback.", &["thermal_feedback"]),
2467 ("belt.tooth_jump_factor", &["belt_tooth_jump"]),
2468 ("ratings.line_module_efficiency", &["dc_link"]),
2469 ("ratings.dc_link_discharge_", &[]),
2470 ("brake.", &[]),
2472 ("motor.friction_breakaway_nm", &["motor_stiction"]),
2473 ("motor.friction_stribeck_rad_s", &["motor_stiction"]),
2474 ("slide.friction_breakaway_n", &["slide_presliding"]),
2475 ("slide.friction_stribeck_m_s", &["slide_presliding"]),
2476 ("slide.presliding_stiffness_n_m", &["slide_presliding"]),
2477 ("screw.friction_coefficient", &["screw_lead_efficiency"]),
2478 ("screw.fixed_bearing_at_m", &["screw_stiffness_with_position"]),
2479 ("gearbox.no_load_", &["gearbox_drag"]),
2480 ("gearbox.lost_motion_band_rad", &["gearbox_lost_motion"]),
2481 ("gearbox.hysteresis_rad", &["gearbox_lost_motion"]),
2482 ("gearbox.stiffness_t", &["gearbox_stiffness_curve"]),
2484 ("gearbox.stiffness_k", &["gearbox_stiffness_curve"]),
2485 ("base.", &["base_compliance"]),
2486 ("link_bending.", &["link_bending"]),
2487 ("beam.", &["beam_sag"]),
2488 ("tool_flex.z_axis_bending_stiffness_nm2", &["z_axis_bending"]),
2489 ("mass.elbow_twist_inertia_kgm2", &["arm_tube_inertia"]),
2490];
2491
2492fn effect_off(cfg: &Config, path: &str) -> bool {
2495 PATH_EFFECTS.iter().any(|(start, effects)| {
2496 path.starts_with(start) && !effects.iter().any(|effect| cfg.bool(&format!("effects.{effect}")).unwrap_or(false))
2497 })
2498}
2499
2500#[derive(Debug, Clone, PartialEq)]
2504pub struct Band {
2505 pub verdict: Verdict,
2506 pub low: f64,
2507 pub high: f64,
2508 pub ok: bool,
2510 pub share: f64,
2513}
2514
2515impl Band {
2516 pub fn share_shown(&self, decimals: i32) -> f64 {
2519 let scale = 10f64.powi(decimals);
2521 (self.share * scale + 1e-9).floor() / scale
2522 }
2523}
2524
2525fn judged(entry: &MachineEntry, cfg: &Config) -> Result<Vec<Verdict>, ConfigError> {
2527 let load = analyse_cycle_with(&mut Sim::new(entry, cfg)?, false).map_err(|e| ConfigError::Invalid(e.key.into()))?;
2528 verdicts(cfg, &load)
2529}
2530
2531fn judge_each(
2534 entry: &MachineEntry,
2535 count: usize,
2536 make: impl Fn(usize) -> Result<Config, ConfigError> + Sync,
2537) -> Vec<Result<Vec<Verdict>, ConfigError>> {
2538 on_all_cores(count, |run| make(run).and_then(|cfg| judged(entry, &cfg)))
2539}
2540
2541static MAX_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2543
2544pub fn set_max_threads(count: usize) {
2547 MAX_THREADS.store(count, std::sync::atomic::Ordering::Relaxed);
2548}
2549
2550fn threads() -> usize {
2552 match MAX_THREADS.load(std::sync::atomic::Ordering::Relaxed) {
2553 0 => std::thread::available_parallelism().map_or(1, |n| n.get()),
2554 count => count,
2555 }
2556}
2557
2558thread_local! {
2559 static JOB: std::cell::RefCell<Option<std::sync::Arc<Progress>>> = const { std::cell::RefCell::new(None) };
2561}
2562
2563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2566pub struct Cancelled;
2567
2568struct JobGuard(Option<std::sync::Arc<Progress>>);
2570
2571impl JobGuard {
2572 fn install(job: Option<std::sync::Arc<Progress>>) -> Self {
2573 JobGuard(JOB.with(|slot| slot.replace(job)))
2574 }
2575}
2576
2577impl Drop for JobGuard {
2578 fn drop(&mut self) {
2579 JOB.with(|slot| *slot.borrow_mut() = self.0.take());
2580 }
2581}
2582
2583fn current_job() -> Option<std::sync::Arc<Progress>> {
2584 JOB.with(|slot| slot.borrow().clone())
2585}
2586
2587pub fn with_progress<T>(progress: &std::sync::Arc<Progress>, job: impl FnOnce() -> T) -> Result<T, Cancelled> {
2590 let _guard = JobGuard::install(Some(progress.clone()));
2591 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)) {
2592 Ok(value) => Ok(value),
2593 Err(payload) if payload.is::<Cancelled>() => Err(Cancelled),
2594 Err(payload) => std::panic::resume_unwind(payload),
2595 }
2596}
2597
2598pub fn check_cancelled() {
2601 if current_job().is_some_and(|job| job.cancel.load(std::sync::atomic::Ordering::Relaxed)) {
2602 std::panic::resume_unwind(Box::new(Cancelled));
2603 }
2604}
2605
2606pub(crate) fn plan_steps(count: usize) {
2608 if let Some(job) = current_job() {
2609 job.total.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
2610 }
2611}
2612
2613pub(crate) fn step_done() {
2615 if let Some(job) = current_job() {
2616 job.done.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2617 }
2618}
2619
2620pub(crate) fn on_all_cores<T: Send>(count: usize, work: impl Fn(usize) -> T + Sync) -> Vec<T> {
2624 use std::sync::atomic::Ordering::Relaxed;
2625 let job = current_job();
2626 plan_steps(count);
2627 let cancelled = || job.as_ref().is_some_and(|job| job.cancel.load(Relaxed));
2628 let next = std::sync::atomic::AtomicUsize::new(0);
2629 let worker = || -> Vec<(usize, T)> {
2630 let _guard = JobGuard::install(job.clone());
2632 let mut done = Vec::new();
2633 loop {
2634 if cancelled() {
2635 return done;
2636 }
2637 let run = next.fetch_add(1, Relaxed);
2638 if run >= count {
2639 return done;
2640 }
2641 done.push((run, work(run)));
2642 step_done();
2643 }
2644 };
2645 let threads = threads().min(count.max(1));
2646 let mut runs: Vec<_> = if threads <= 1 {
2648 worker()
2649 } else {
2650 std::thread::scope(|scope| {
2651 let workers: Vec<_> = (0..threads).map(|_| scope.spawn(worker)).collect();
2652 let joined: Vec<_> = workers.into_iter().map(|worker| worker.join()).collect();
2654 let mut runs = Vec::new();
2655 for result in joined {
2656 match result {
2657 Ok(done) => runs.extend(done),
2658 Err(payload) if payload.is::<Cancelled>() => std::panic::resume_unwind(payload),
2659 Err(_) => panic!("a run of the cycle panicked"),
2660 }
2661 }
2662 runs
2663 })
2664 };
2665 if cancelled() {
2666 std::panic::resume_unwind(Box::new(Cancelled));
2667 }
2668 runs.sort_by_key(|(run, _)| *run);
2669 runs.into_iter().map(|(_, run)| run).collect()
2670}
2671
2672fn envelope(
2675 entry: &MachineEntry,
2676 cfg: &Config,
2677 count: usize,
2678 changed: impl Fn(usize) -> Result<Config, ConfigError> + Sync,
2679) -> Result<Vec<Band>, ConfigError> {
2680 bands_of(judge_each(entry, count + 1, |run| if run == 0 { Ok(cfg.clone()) } else { changed(run - 1) }))
2682}
2683
2684fn bands_of(runs: Vec<Result<Vec<Verdict>, ConfigError>>) -> Result<Vec<Band>, ConfigError> {
2686 let (total, mut bands, mut failed) = (runs.len(), Vec::<Band>::new(), Vec::<usize>::new());
2688 for run in runs {
2689 for v in run? {
2690 let fails = usize::from(!v.ok);
2691 match bands.iter().position(|b| b.verdict.check == v.check && b.verdict.motor == v.motor) {
2692 Some(k) => {
2693 let b = &mut bands[k];
2694 (b.low, b.high, b.ok) = (b.low.min(v.value), b.high.max(v.value), b.ok && v.ok);
2695 failed[k] += fails;
2696 }
2697 None => {
2698 bands.push(Band { low: v.value, high: v.value, ok: v.ok, share: 1.0, verdict: v });
2699 failed.push(fails);
2700 }
2701 }
2702 }
2703 }
2704 for (band, failed) in bands.iter_mut().zip(failed) {
2705 band.share = (total - failed) as f64 / total as f64;
2706 }
2707 Ok(bands)
2708}
2709
2710pub fn verdict_bands(
2718 entry: &MachineEntry,
2719 cfg: &Config,
2720 bounds: &[(String, f64, f64)],
2721) -> Result<Vec<Band>, ConfigError> {
2722 let resolved = &crate::catalog::resolve(entry, cfg)?;
2723 let (bounds, cfg) = (&followed(cfg, resolved, bounds), resolved);
2724 envelope(entry, cfg, 2 * bounds.len(), |run| {
2725 let ((path, low, high), mut changed) = (&bounds[run / 2], cfg.clone());
2726 set_bounded(&mut changed, path, if run % 2 == 0 { *low } else { *high })?;
2727 Ok(changed)
2728 })
2729}
2730
2731pub fn verdict_bands_sampled(
2745 entry: &MachineEntry,
2746 cfg: &Config,
2747 bounds: &[(String, f64, f64)],
2748 samples: usize,
2749 seed: u64,
2750) -> Result<Vec<Band>, ConfigError> {
2751 if samples == 0 {
2752 return Err(ConfigError::Invalid("samples".into()));
2753 }
2754 let resolved = &crate::catalog::resolve(entry, cfg)?;
2755 let (bounds, cfg) = (&followed(cfg, resolved, bounds), resolved);
2756 let mut random = sim_core::testkit::Noise(seed);
2757 let columns: Vec<Vec<f64>> = bounds
2758 .iter()
2759 .map(|(_, low, high)| {
2760 let mut values: Vec<f64> = (0..samples)
2761 .map(|part| low + (high - low) * (part as f64 + random.uniform()) / samples as f64)
2762 .collect();
2763 for i in (1..samples).rev() {
2764 values.swap(i, (random.uniform() * (i + 1) as f64) as usize);
2765 }
2766 values
2767 })
2768 .collect();
2769 envelope(entry, cfg, samples, |run| {
2770 let mut changed = cfg.clone();
2771 for ((path, ..), values) in bounds.iter().zip(&columns) {
2772 set_bounded(&mut changed, path, values[run])?;
2773 }
2774 Ok(changed)
2775 })
2776}
2777
2778#[derive(Debug, Clone, PartialEq)]
2782pub struct Worst {
2783 pub verdict: Verdict,
2784 pub high: Vec<Option<bool>>,
2785}
2786
2787pub const WORST_PASSES: usize = 3;
2789
2790fn badness(v: &Verdict) -> f64 {
2799 match v.check {
2800 "dc-link-energy" => v.value + if v.ok { 0.0 } else { 1e9 },
2802 _ if AT_LEAST.contains(&v.check) => v.limit - v.value,
2803 _ => v.value - v.limit,
2804 }
2805}
2806
2807pub fn verdict_worst(
2828 entry: &MachineEntry,
2829 cfg: &Config,
2830 bounds: &[(String, f64, f64)],
2831) -> Result<(Vec<Worst>, usize), ConfigError> {
2832 verdict_worst_and_bands(entry, cfg, bounds).map(|(worst, _, runs)| (worst, runs))
2833}
2834
2835pub fn verdict_worst_and_bands(
2838 entry: &MachineEntry,
2839 cfg: &Config,
2840 bounds: &[(String, f64, f64)],
2841) -> Result<(Vec<Worst>, Vec<Band>, usize), ConfigError> {
2842 worst_search(entry, cfg, bounds, &[], &|_| false)
2843}
2844
2845fn worst_search(
2851 entry: &MachineEntry,
2852 cfg: &Config,
2853 bounds: &[(String, f64, f64)],
2854 from: &[Worst],
2855 stop: &(dyn Fn(&Verdict) -> bool + Sync),
2856) -> Result<(Vec<Worst>, Vec<Band>, usize), ConfigError> {
2857 let resolved = &crate::catalog::resolve(entry, cfg)?;
2858 let (bounds, cfg) = (&followed(cfg, resolved, bounds), resolved);
2859 let n = bounds.len();
2860 let set = |cfg: &mut Config, i: usize, high: bool| {
2861 set_bounded(cfg, &bounds[i].0, if high { bounds[i].2 } else { bounds[i].1 })
2862 };
2863 let alone = judge_each(entry, 2 * n + 1, |run| {
2865 let mut changed = cfg.clone();
2866 if run > 0 {
2867 set(&mut changed, (run - 1) / 2, run % 2 == 0)?;
2868 }
2869 Ok(changed)
2870 });
2871 let bands = bands_of(alone.clone())?;
2872 let alone = alone.into_iter().collect::<Result<Vec<_>, _>>()?;
2873 let mut ids: Vec<(&'static str, Option<usize>)> = Vec::new();
2874 for v in alone.iter().flatten() {
2875 if !ids.contains(&(v.check, v.motor)) {
2876 ids.push((v.check, v.motor));
2877 }
2878 }
2879 let bad = |run: &[Verdict], id: (&str, Option<usize>)| {
2881 run.iter().find(|v| (v.check, v.motor) == id).map_or(f64::NEG_INFINITY, badness)
2882 };
2883 let mut corners: Vec<Vec<bool>> = ids
2884 .iter()
2885 .map(|&id| (0..n).map(|i| bad(&alone[2 * i + 2], id) >= bad(&alone[2 * i + 1], id)).collect())
2886 .collect();
2887 let moves: Vec<Vec<usize>> = ids
2888 .iter()
2889 .map(|&id| (0..n).filter(|&i| bad(&alone[2 * i + 2], id) != bad(&alone[2 * i + 1], id)).collect())
2890 .collect();
2891
2892 let warm: Vec<Option<Vec<bool>>> = ids
2894 .iter()
2895 .zip(&corners)
2896 .map(|(&id, sign)| {
2897 let w = from.iter().find(|w| (w.verdict.check, w.verdict.motor) == id && w.high.len() == n)?;
2898 Some(w.high.iter().zip(sign).map(|(h, s)| h.unwrap_or(*s)).collect())
2899 })
2900 .collect();
2901
2902 let mut seen: std::collections::HashMap<Vec<bool>, Vec<Verdict>> = std::collections::HashMap::new();
2903 let mut runs = alone.len();
2904 let mut stopped = alone.iter().flatten().any(stop);
2905 let mut run_corners = |wanted: Vec<Vec<bool>>,
2907 seen: &mut std::collections::HashMap<Vec<bool>, Vec<Verdict>>|
2908 -> Result<bool, ConfigError> {
2909 let mut new: Vec<Vec<bool>> = Vec::new();
2910 for corner in wanted {
2911 if !seen.contains_key(&corner) && !new.contains(&corner) {
2912 new.push(corner);
2913 }
2914 }
2915 let judged = judge_each(entry, new.len(), |k| {
2916 let mut changed = cfg.clone();
2917 for (i, high) in new[k].iter().enumerate() {
2918 set(&mut changed, i, *high)?;
2919 }
2920 Ok(changed)
2921 });
2922 runs += new.len();
2923 let mut hit = false;
2924 for (corner, verdicts) in new.into_iter().zip(judged) {
2925 let verdicts = verdicts?;
2926 hit |= verdicts.iter().any(stop);
2927 seen.insert(corner, verdicts);
2928 }
2929 Ok(hit)
2930 };
2931 if !stopped {
2932 stopped = run_corners(corners.iter().cloned().chain(warm.iter().flatten().cloned()).collect(), &mut seen)?;
2933 for (k, warm) in warm.into_iter().enumerate() {
2934 if let Some(warm) = warm.filter(|w| bad(&seen[w], ids[k]) > bad(&seen[&corners[k]], ids[k])) {
2935 corners[k] = warm;
2936 }
2937 }
2938 }
2939 let flipped = |corner: &[bool], flips: &[usize]| {
2940 let mut out = corner.to_vec();
2941 for &i in flips {
2942 out[i] = !out[i];
2943 }
2944 out
2945 };
2946 for _ in 0..WORST_PASSES {
2947 if stopped {
2948 break;
2949 }
2950 let singles: Vec<Vec<bool>> = (0..ids.len())
2951 .flat_map(|k| moves[k].iter().map(|&i| flipped(&corners[k], &[i])).collect::<Vec<_>>())
2952 .collect();
2953 if run_corners(singles, &mut seen)? {
2954 break;
2955 }
2956 let worse: Vec<Vec<usize>> = (0..ids.len())
2958 .map(|k| {
2959 moves[k]
2960 .iter()
2961 .copied()
2962 .filter(|&i| bad(&seen[&flipped(&corners[k], &[i])], ids[k]) > bad(&seen[&corners[k]], ids[k]))
2963 .collect()
2964 })
2965 .collect();
2966 stopped = run_corners(
2967 (0..ids.len()).filter(|&k| worse[k].len() > 1).map(|k| flipped(&corners[k], &worse[k])).collect(),
2968 &mut seen,
2969 )?;
2970 let mut changed = false;
2971 for k in 0..ids.len() {
2972 let candidates = worse[k]
2973 .iter()
2974 .map(|&i| flipped(&corners[k], &[i]))
2975 .chain((worse[k].len() > 1).then(|| flipped(&corners[k], &worse[k])));
2976 if let Some(best) = candidates.max_by(|a, b| bad(&seen[a], ids[k]).total_cmp(&bad(&seen[b], ids[k]))) {
2977 corners[k] = best;
2978 changed = true;
2979 }
2980 }
2981 if !changed {
2982 break;
2983 }
2984 }
2985 let alone_at = |run: usize| -> Vec<Option<bool>> {
2988 (0..n).map(|i| (run > 0 && (run - 1) / 2 == i).then_some(run.is_multiple_of(2))).collect()
2989 };
2990 let worst = ids
2991 .iter()
2992 .filter_map(|&id| {
2993 let corners = seen.iter().map(|(corner, run)| (corner.iter().map(|&h| Some(h)).collect::<Vec<_>>(), run));
2994 let candidates = corners.chain(alone.iter().enumerate().map(|(r, run)| (alone_at(r), run)));
2995 let (high, run) =
2996 candidates.max_by(|a, b| bad(a.1, id).total_cmp(&bad(b.1, id)).then_with(|| b.0.cmp(&a.0)))?;
2997 let verdict = run.iter().find(|v| (v.check, v.motor) == id)?.clone();
2998 Some(Worst { verdict, high })
2999 })
3000 .collect();
3001 Ok((worst, bands, runs))
3002}
3003
3004#[derive(Debug, Clone)]
3009pub struct Optimised {
3010 pub before: CycleLoad,
3011 pub after: CycleLoad,
3012 pub changes: Vec<(String, String, String)>,
3013 pub lifts: Vec<LiftChange>,
3014 pub runs: usize,
3015 pub robust: Option<Robust>,
3017 pub front: Vec<FrontPoint>,
3020}
3021
3022#[derive(Debug, Clone, Copy, PartialEq)]
3027pub struct OptimiseOptions {
3028 pub max_runs: usize,
3029 pub robust: bool,
3030 pub pareto: bool,
3031 pub worst: bool,
3032}
3033
3034#[derive(Debug, Clone, PartialEq)]
3042pub struct Robust {
3043 pub nominal_duration: f64,
3044 pub nominal_fails: Vec<&'static str>,
3045 pub excused: Vec<&'static str>,
3046 pub steps_back: usize,
3047 pub runs: usize,
3048 pub worst: bool,
3049}
3050
3051#[derive(Debug, Clone, PartialEq)]
3055pub struct FrontPoint {
3056 pub duration: f64,
3057 pub energy: f64,
3058 pub utilisation: f64,
3059 pub factors: [f64; 3],
3060 pub blending: bool,
3061 pub shaping: bool,
3062}
3063
3064pub fn supply_energy(cfg: &Config, load: &CycleLoad) -> f64 {
3075 let net: f64 = load.motors.iter().map(|m| m.energy_in - m.energy_regenerated).sum();
3076 let shared = cfg.bool("effects.shared_dc_link").unwrap_or(false);
3077 let links: Vec<&MotorLoad> =
3079 if shared { load.motors.iter().take(1).collect() } else { load.motors.iter().collect() };
3080 let burned: f64 = links.iter().map(|m| m.resistor_energy).sum();
3081 if !cfg.bool("effects.dc_link").unwrap_or(false) {
3082 return net + burned;
3083 }
3084 let bled: f64 = load.motors.iter().map(|m| m.discharge_energy).sum();
3085 let line: f64 = links
3086 .iter()
3087 .map(|m| {
3088 let own = if shared { None } else { crate::catalog::motor_config(cfg, &m.id).ok() };
3089 let eta = own.as_ref().unwrap_or(cfg).positive("ratings.line_module_efficiency").unwrap_or(1.0);
3090 let fed = m.mains_energy / eta;
3091 (1.0 / eta - 1.0) * (m.line_module_energy - fed) + (1.0 - eta) * fed
3092 })
3093 .sum();
3094 net + burned + bled + line
3095}
3096
3097pub fn non_dominated(points: &[FrontPoint]) -> Vec<FrontPoint> {
3100 let figures: Vec<Vec<f64>> = points.iter().map(|p| vec![p.duration, p.energy, p.utilisation]).collect();
3101 let mut front: Vec<FrontPoint> = non_dominated_indices(&figures).into_iter().map(|i| points[i].clone()).collect();
3102 front.sort_by(|a, b| a.duration.total_cmp(&b.duration));
3103 front
3104}
3105
3106pub fn non_dominated_indices(figures: &[Vec<f64>]) -> Vec<usize> {
3110 let beats = |a: &[f64], b: &[f64]| a.iter().zip(b).all(|(x, y)| x <= y) && a != b;
3111 let mut front: Vec<usize> = Vec::new();
3112 for (i, p) in figures.iter().enumerate() {
3113 if !figures.iter().any(|q| beats(q, p)) && !front.iter().any(|&k| figures[k] == *p) {
3114 front.push(i);
3115 }
3116 }
3117 front
3118}
3119
3120#[derive(Debug, Clone, PartialEq)]
3126pub struct LiftChange {
3127 pub segments: [usize; 3],
3128 pub before: f64,
3129 pub after: f64,
3130 pub via: Option<Vec<Vec<f64>>>,
3131 pub corners: Option<f64>,
3134}
3135
3136struct Lift {
3144 segments: [usize; 3],
3145 from: Vec<f64>,
3146 to: Vec<f64>,
3147 height: f64,
3148 up: f64,
3149 lowest: f64,
3150 needed: f64,
3151 over: Option<Vec<f64>>,
3152 profile: Option<Vec<Vec<f64>>>,
3153 payload: bool,
3154}
3155
3156fn lifts(cfg: &Config, clearance: f64) -> Result<Vec<Lift>, ConfigError> {
3161 let segments = cfg.array("cycle.segment")?;
3162 let n = segments.len();
3163 let target = |i: usize| -> Option<Vec<f64>> {
3164 segments[i]
3165 .get("target")?
3166 .as_array()?
3167 .iter()
3168 .map(|v| v.as_float().or_else(|| v.as_integer().map(|i| i as f64)))
3169 .collect()
3170 };
3171 let plain = |i: usize| segments[i].get("via").is_none();
3172 let quiet = |i: usize| {
3173 segments[i].get("dwell_s").and_then(|d| d.as_float().or_else(|| d.as_integer().map(|i| i as f64))) == Some(0.0)
3174 && segments[i].get("payload") == segments[(i + n - 1) % n].get("payload")
3175 };
3176 let mut out = Vec::new();
3177 if n < 3 {
3178 return Ok(out);
3179 }
3180 for a in 0..n {
3181 let (b, c) = ((a + 1) % n, (a + 2) % n);
3182 let (Some(from), Some(lift), Some(traverse), Some(to)) =
3183 (target((a + n - 1) % n), target(a), target(b), target(c))
3184 else {
3185 continue;
3186 };
3187 let z = from.len().wrapping_sub(1);
3188 if from.len() < 2 || [&lift, &traverse, &to].iter().any(|p| p.len() != from.len()) {
3189 continue;
3190 }
3191 let along_z = |p: &[f64], q: &[f64]| p[..z] == q[..z] && p[z] != q[z];
3192 let height = lift[z];
3193 let up = (height - from[z]).signum();
3194 if !(along_z(&from, &lift)
3195 && traverse[z] == height
3196 && traverse[..z] != lift[..z]
3197 && along_z(&traverse, &to)
3198 && (height - to[z]).signum() == up)
3199 {
3200 continue;
3201 }
3202 if !(quiet(a) && quiet(b) && plain(a) && plain(b) && plain(c)) {
3203 continue;
3204 }
3205 let lowest = if up > 0.0 { from[z].max(to[z]) + clearance } else { from[z].min(to[z]) - clearance };
3206 let lowest = if (lowest - height).abs() < 1e-9 { height } else { lowest };
3208 if up * (height - lowest) >= 0.0 {
3210 let payload = segments[a].get("payload").and_then(|p| p.as_bool()).unwrap_or(true);
3212 out.push(Lift {
3213 segments: [a, b, c],
3214 from,
3215 to,
3216 height,
3217 up,
3218 lowest,
3219 needed: lowest,
3220 over: None,
3221 profile: None,
3222 payload,
3223 });
3224 }
3225 }
3226 Ok(out)
3227}
3228
3229fn over_obstacles(
3236 machine: &mut dyn sim_core::Machine,
3237 obstacles: &[sim_core::Obstacle],
3238 lift: &Lift,
3239 clearance: f64,
3240 axis: &sim_core::AxisInfo,
3241) -> Option<(f64, Option<Vec<f64>>)> {
3242 let z = lift.from.len() - 1;
3243 machine.set_payload_attached(lift.payload);
3244 let machine: &dyn sim_core::Machine = machine;
3245 let gap_at = |height: f64| {
3246 let at = |p: &[f64]| -> Vec<f64> { p[..z].iter().copied().chain([height]).collect() };
3247 let mut check = crate::collision::PlanCheck::default();
3248 crate::collision::check_path(machine, obstacles, &[at(&lift.from), at(&lift.to)], &mut check);
3249 (check.clearance, check.nearest)
3250 };
3251 let (mut height, mut best) = (lift.lowest, None::<(f64, Option<Vec<f64>>)>);
3252 for _ in 0..40 {
3253 let (gap, nearest) = gap_at(height);
3254 if gap >= clearance - 1e-9 && best.as_ref().is_none_or(|(b, _)| lift.up * (height - b) < 0.0) {
3255 best = Some((height, nearest));
3256 }
3257 let next = lift.lowest + lift.up * (lift.up * (height - lift.lowest) + clearance - gap).max(0.0);
3259 if !gap.is_finite()
3260 || (gap - clearance).abs() <= 1e-9
3261 || next == height
3262 || !(axis.min..=axis.max).contains(&next)
3263 {
3264 break;
3265 }
3266 height = next;
3267 }
3268 best.map(|(height, nearest)| (height, if height == lift.lowest { None } else { nearest }))
3269}
3270
3271fn profile(
3277 machine: &mut dyn sim_core::Machine,
3278 obstacles: &[sim_core::Obstacle],
3279 lift: &Lift,
3280 clearance: f64,
3281 axis: &sim_core::AxisInfo,
3282) -> Option<Vec<Vec<f64>>> {
3283 let z = lift.from.len() - 1;
3284 let at = |s: f64, height: f64| -> Vec<f64> {
3285 (0..z).map(|i| lift.from[i] + s * (lift.to[i] - lift.from[i])).chain([height]).collect()
3286 };
3287 let width = (0..z).map(|i| (lift.to[i] - lift.from[i]).powi(2)).sum::<f64>().sqrt();
3288 let steps = (width / 1e-3).ceil().max(1.0) as usize;
3289 let mut stretches: Vec<(f64, f64, f64)> = Vec::new();
3290 for one in obstacles.chunks(1) {
3291 let (height, over) = over_obstacles(machine, one, lift, clearance, axis)?;
3292 if over.is_none() {
3293 continue;
3294 }
3295 machine.set_payload_attached(lift.payload);
3296 let near = (0..=steps).map(|k| k as f64 / steps as f64).filter(|&s| {
3297 let mut check = crate::collision::PlanCheck::default();
3298 crate::collision::check_path(&*machine, one, &[at(s, lift.lowest)], &mut check);
3299 check.clearance < clearance - 1e-9
3300 });
3301 let (first, last) = near.fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), s| (a.min(s), b.max(s)));
3302 if first <= last {
3303 stretches.push((first, last, height));
3304 }
3305 }
3306 stretches.sort_by(|a, b| a.0.total_cmp(&b.0));
3307 let mut merged: Vec<(f64, f64, f64)> = Vec::new();
3308 for (first, last, height) in stretches {
3309 match merged.last_mut() {
3310 Some(m) if first <= m.1 => {
3311 (m.1, m.2) = (m.1.max(last), if lift.up > 0.0 { m.2.max(height) } else { m.2.min(height) })
3312 }
3313 _ => merged.push((first, last, height)),
3314 }
3315 }
3316 (merged.len() >= 2)
3317 .then(|| merged.iter().flat_map(|&(first, last, height)| [at(first, height), at(last, height)]).collect())
3318}
3319
3320fn raised(points: &[Vec<f64>], by: f64) -> Vec<Vec<f64>> {
3322 points
3323 .iter()
3324 .map(|p| p.iter().enumerate().map(|(i, x)| if i + 1 == p.len() { x + by } else { *x }).collect())
3325 .collect()
3326}
3327
3328fn smoothed_profile(
3333 machine: &mut dyn sim_core::Machine,
3334 obstacles: &[sim_core::Obstacle],
3335 lift: &Lift,
3336 clearance: f64,
3337 planned: (&[sim_core::AxisInfo], f64, f64),
3338) -> Option<(Vec<Vec<f64>>, f64)> {
3339 let (axes, cycle, tolerance) = planned;
3340 let points = profile(machine, obstacles, lift, clearance, &axes[lift.from.len() - 1])?;
3341 let mut by = 0.0;
3342 for _ in 0..4 {
3343 let via = raised(&points, lift.up * by);
3344 let at = (lift.lowest, None);
3345 let gap = planned_clearance(axes, cycle, tolerance, lift, at, &via, (&mut *machine, obstacles, clearance))?;
3346 if gap >= clearance - 1e-9 {
3347 return Some((points, by));
3348 }
3349 by += clearance - gap + 1e-6;
3350 }
3351 None
3352}
3353
3354pub fn lift_profiles(entry: &MachineEntry, cfg: &Config) -> Result<Vec<([usize; 3], Vec<Vec<f64>>, f64)>, ConfigError> {
3359 let mut probe = Sim::new(entry, cfg)?;
3360 let clearance = cfg.non_negative("profile.min_clearance_m")?;
3361 let (cycle, tolerance) = (cfg.positive("profile.cycle_s")?, cfg.non_negative("profile.path_tolerance_m")?);
3362 let (axes, obstacles) = (probe.machine.axes().to_vec(), probe.obstacles.clone());
3363 let mut out = Vec::new();
3364 for lift in lifts(cfg, clearance)?.iter().filter(|_| !obstacles.is_empty()) {
3365 let planned = (axes.as_slice(), cycle, tolerance);
3366 if let Some((points, by)) = smoothed_profile(probe.machine.as_mut(), &obstacles, lift, clearance, planned) {
3367 out.push((lift.segments, points, by));
3368 }
3369 }
3370 Ok(out)
3371}
3372
3373fn cycle_with(
3376 cfg: &Config,
3377 lifts: &[Lift],
3378 heights: &[f64],
3379 vias: &[Option<Vec<Vec<f64>>>],
3380 corners: &[Option<f64>],
3381) -> Result<toml::Value, ConfigError> {
3382 let mut segments = cfg.array("cycle.segment")?.clone();
3383 let number_list = |p: &[f64]| toml::Value::Array(p.iter().map(|x| toml::Value::Float(*x)).collect());
3384 let mut dropped = Vec::new();
3385 for (((lift, &height), via), corner) in lifts.iter().zip(heights).zip(vias).zip(corners) {
3386 let [a, b, c] = lift.segments;
3387 let at_height = |p: &[f64]| {
3388 let mut p = p.to_vec();
3389 *p.last_mut().unwrap_or(&mut 0.0) = height;
3390 p
3391 };
3392 match via {
3393 None => {
3394 for i in [a, b] {
3395 let old = segments[i].get("target").and_then(|t| t.as_array()).cloned().unwrap_or_default();
3396 let pose: Vec<f64> =
3397 old.iter().filter_map(|v| v.as_float().or_else(|| v.as_integer().map(|i| i as f64))).collect();
3398 if let Some(t) = segments[i].as_table_mut() {
3399 t.insert("target".into(), number_list(&at_height(&pose)));
3400 }
3401 }
3402 }
3403 Some(points) => {
3404 let via = toml::Value::Array(
3405 std::iter::once(at_height(&lift.from))
3406 .chain(points.iter().cloned())
3407 .chain([at_height(&lift.to)])
3408 .map(|p| number_list(&p))
3409 .collect(),
3410 );
3411 if let Some(t) = segments[c].as_table_mut() {
3412 t.insert("via".into(), via);
3413 if let Some(corner) = corner {
3414 t.insert("corners_m".into(), toml::Value::Float(*corner));
3415 }
3416 }
3417 dropped.extend([a, b]);
3418 }
3419 }
3420 }
3421 let kept = segments.into_iter().enumerate().filter(|(i, _)| !dropped.contains(i)).map(|(_, s)| s).collect();
3422 Ok(toml::Value::Array(kept))
3423}
3424
3425fn clears(
3430 axes: &[sim_core::AxisInfo],
3431 cycle: f64,
3432 tolerance: f64,
3433 lift: &Lift,
3434 height: (f64, Option<f64>),
3435 via: &[Vec<f64>],
3436 bodies: (&mut dyn sim_core::Machine, &[sim_core::Obstacle], f64),
3437) -> bool {
3438 let clearance = bodies.2;
3439 planned_clearance(axes, cycle, tolerance, lift, height, via, bodies).is_some_and(|gap| gap >= clearance - 1e-9)
3440}
3441
3442fn planned_clearance(
3447 axes: &[sim_core::AxisInfo],
3448 cycle: f64,
3449 tolerance: f64,
3450 lift: &Lift,
3451 (height, corner): (f64, Option<f64>),
3452 via: &[Vec<f64>],
3453 bodies: (&mut dyn sim_core::Machine, &[sim_core::Obstacle], f64),
3454) -> Option<f64> {
3455 let points = lift_path(axes, cycle, tolerance, lift, (height, corner), via)?;
3456 let (machine, obstacles, _) = bodies;
3457 if obstacles.is_empty() {
3458 return Some(f64::INFINITY);
3459 }
3460 machine.set_payload_attached(lift.payload);
3461 let mut check = crate::collision::PlanCheck::default();
3462 let poses: Vec<Vec<f64>> =
3463 std::iter::once(lift.from.clone()).chain(points.into_iter().map(|(_, pose)| pose)).collect();
3464 crate::collision::check_path(&*machine, obstacles, &poses, &mut check);
3465 Some(check.clearance)
3466}
3467
3468fn lift_path(
3471 axes: &[sim_core::AxisInfo],
3472 cycle: f64,
3473 tolerance: f64,
3474 lift: &Lift,
3475 (height, corner): (f64, Option<f64>),
3476 via: &[Vec<f64>],
3477) -> Option<Vec<(f64, Vec<f64>)>> {
3478 let z = lift.from.len() - 1;
3479 let at_height = |p: &[f64]| {
3480 let mut p = p.to_vec();
3481 p[z] = height;
3482 p
3483 };
3484 let via: Vec<Vec<f64>> =
3485 std::iter::once(at_height(&lift.from)).chain(via.iter().cloned()).chain([at_height(&lift.to)]).collect();
3486 let (pieces, rounded) = match corner {
3487 Some(corner) => {
3488 (crate::control::lines_through(&via, &lift.to), crate::path::Tolerance { path: tolerance, corner })
3489 }
3490 None => (crate::control::via_pieces(&via, &lift.to), tolerance.into()),
3491 };
3492 let points = crate::path::plan(axes, &lift.from, &pieces, cycle, rounded, crate::path::ARC_SLACK).ok()?;
3493 let across: Vec<f64> = (0..z).map(|i| lift.to[i] - lift.from[i]).collect();
3494 let width = across.iter().map(|d| d * d).sum::<f64>();
3495 let above = points.iter().all(|(_, pose)| {
3496 let along = (0..z).map(|i| (pose[i] - lift.from[i]) * across[i]).sum::<f64>() / width;
3497 along <= 0.0 || along >= 1.0 || lift.up * (pose[z] - lift.lowest) >= -tolerance - 1e-9
3498 });
3499 above.then_some(points)
3500}
3501
3502pub fn optimise_cycle(entry: &MachineEntry, cfg: &Config, max_runs: usize) -> Result<Optimised, ConfigError> {
3529 optimise_cycle_with(entry, cfg, &OptimiseOptions { max_runs, robust: false, pareto: false, worst: false })
3530}
3531
3532fn fastest_passing<T, E>(
3538 top: usize,
3539 mut pass: impl FnMut(usize) -> Result<Option<T>, E>,
3540) -> Result<Option<(usize, T)>, E> {
3541 for k in (1..=top).rev() {
3542 if let Some(passed) = pass(k)? {
3543 return Ok(Some((k, passed)));
3544 }
3545 }
3546 Ok(None)
3547}
3548
3549pub fn second_shaper_frequency(machine: &dyn Machine, pose: &[f64], cfg: &Config) -> Result<Option<f64>, ConfigError> {
3554 let (first, configured) =
3555 (cfg.positive("profile.shaper_frequency_hz")?, cfg.non_negative("profile.shaper2_frequency_hz")?);
3556 if configured > 0.0 {
3557 return Ok(Some(configured));
3558 }
3559 let second = machine.sway_modes(pose).get(1).map(|mode| mode.hz);
3560 Ok(second.or(machine.resonance_hz(pose).filter(|f| (f / first - 1.0).abs() > 0.1)))
3561}
3562
3563pub fn optimise_cycle_with(
3578 entry: &MachineEntry,
3579 cfg: &Config,
3580 options: &OptimiseOptions,
3581) -> Result<Optimised, ConfigError> {
3582 let max_runs = options.max_runs;
3583 let mut probe = Sim::new(entry, cfg)?;
3584 let clearance = cfg.non_negative("profile.min_clearance_m")?;
3585 let conveyor = probe.control.conveyor().is_some() || probe.path.is_some();
3588 let mut lifts = if conveyor { Vec::new() } else { lifts(cfg, clearance)? };
3589 let corner_s = cfg.non_negative("profile.corner_tolerance_m")?;
3592 let allowed = if probe.path.is_some() { cfg.non_negative("profile.path_tolerance_m")?.max(corner_s) } else { 0.0 };
3593 let (cycle_s, tolerance) = (cfg.positive("profile.cycle_s")?, cfg.non_negative("profile.path_tolerance_m")?);
3594 let axis_infos = probe.machine.axes().to_vec();
3595 let obstacles = probe.obstacles.clone();
3596 if !obstacles.is_empty() {
3597 for lift in &mut lifts {
3598 let axis = &axis_infos[lift.from.len() - 1];
3599 (lift.needed, lift.over) = over_obstacles(probe.machine.as_mut(), &obstacles, lift, clearance, axis)
3600 .unwrap_or((lift.height, None));
3601 let planned = (axis_infos.as_slice(), cycle_s, tolerance);
3602 lift.profile = smoothed_profile(probe.machine.as_mut(), &obstacles, lift, clearance, planned)
3603 .map(|(points, by)| raised(&points, lift.up * by));
3604 }
3605 }
3606 let resonance = probe.machine.resonance_hz(probe.control.planned_pos());
3607 let configured = cfg.non_negative("profile.shaper2_frequency_hz")?;
3608 let second_frequency = second_shaper_frequency(probe.machine.as_ref(), probe.control.planned_pos(), cfg)?;
3609 let limits = ["max_velocity_{unit}_s", "max_acceleration_{unit}_s2", "max_jerk_{unit}_s3"];
3612 #[derive(Clone, PartialEq)]
3614 struct Setting {
3615 factors: [f64; 3],
3616 blending: bool,
3617 shaping: bool,
3618 follows: bool,
3619 second: bool,
3620 heights: Vec<f64>,
3621 vias: Vec<Option<Vec<Vec<f64>>>>,
3622 corners: Vec<Option<f64>>,
3624 tolerances: [f64; 2],
3626 }
3627 let build = |setting: &Setting| -> Result<Config, ConfigError> {
3628 let mut changed = cfg.clone();
3629 let [path, corner] = setting.tolerances;
3630 changed.set_text(&format!("profile.path_tolerance_m = {path:?}"))?;
3631 changed.set_text(&format!("profile.corner_tolerance_m = {corner:?}"))?;
3632 for axis in &axis_infos {
3633 for (limit, factor) in limits.iter().zip(setting.factors) {
3634 let path = format!("axis.{}.{}", axis.id, limit.replace("{unit}", axis.unit));
3635 changed.set_text(&format!("{path} = {:?}", cfg.positive(&path)? * factor))?;
3636 }
3637 }
3638 changed.set_text(&format!("effects.corner_blending = {}", setting.blending))?;
3639 changed.set_text(&format!("effects.input_shaping = {}", setting.shaping))?;
3640 changed.set_text(&format!("effects.shaper_follows_pose = {}", setting.follows))?;
3641 changed.set_text(&format!(
3642 "profile.shaper2_frequency_hz = {:?}",
3643 if setting.second { second_frequency.unwrap_or(0.0) } else { 0.0 }
3644 ))?;
3645 if setting.heights.iter().zip(&lifts).any(|(h, lift)| *h != lift.height)
3646 || setting.vias.iter().any(Option::is_some)
3647 {
3648 changed
3649 .set("cycle.segment", cycle_with(cfg, &lifts, &setting.heights, &setting.vias, &setting.corners)?)?;
3650 }
3651 Ok(changed)
3652 };
3653 let runs = std::cell::Cell::new(0usize);
3654 let passed = std::cell::RefCell::new(Vec::<FrontPoint>::new());
3656 let evaluate = |setting: &Setting| -> Option<(CycleLoad, Vec<&'static str>, Option<FrontPoint>)> {
3659 let changed = build(setting).ok()?;
3660 let mut sim = Sim::new(entry, &changed).ok()?;
3661 let load = analyse_cycle_with(&mut sim, false).ok()?;
3662 let failed: Vec<&'static str> =
3663 verdicts(&changed, &load).ok()?.iter().filter(|v| !v.ok).map(|v| v.check).collect();
3664 let point = failed.is_empty().then(|| {
3665 let utilisation = load.motors.iter().fold(0.0, |a: f64, m| a.max(m.utilisation));
3666 let (factors, blending, shaping) = (setting.factors, setting.blending, setting.shaping);
3667 FrontPoint {
3668 duration: load.duration,
3669 energy: supply_energy(&changed, &load),
3670 utilisation,
3671 factors,
3672 blending,
3673 shaping,
3674 }
3675 });
3676 Some((load, failed, point))
3677 };
3678 let count = |result: Option<(CycleLoad, Vec<&'static str>, Option<FrontPoint>)>| {
3680 runs.set(runs.get() + 1);
3681 let (load, failed, point) = result?;
3682 passed.borrow_mut().extend(point);
3683 Some((load, failed))
3684 };
3685 let judged = |setting: &Setting| -> Option<(CycleLoad, Vec<&'static str>)> { count(evaluate(setting)) };
3686 let start = Setting {
3687 factors: [1.0; 3],
3688 blending: cfg.bool("effects.corner_blending")?,
3689 shaping: cfg.bool("effects.input_shaping")?,
3690 follows: cfg.bool("effects.shaper_follows_pose")?,
3691 second: configured > 0.0,
3692 heights: lifts.iter().map(|lift| lift.height).collect(),
3693 vias: vec![None; lifts.len()],
3694 corners: vec![None; lifts.len()],
3695 tolerances: [tolerance, corner_s],
3696 };
3697 let before = match judged(&start) {
3698 Some((load, failed)) if failed.is_empty() => load,
3699 Some((_, failed)) => {
3700 return Err(ConfigError::Part("error-cycle-fails-already", failed.join(", ")));
3701 }
3702 None => {
3704 let changed = build(&start)?;
3705 let why =
3706 |e: CommandError| ConfigError::Invalid(format!("the cycle as configured does not run: {}", e.key));
3707 verdicts(&changed, &analyse_cycle_with(&mut Sim::new(entry, &changed)?, false).map_err(why)?)?;
3708 return Err(ConfigError::Invalid("the cycle as configured cannot be judged".into()));
3709 }
3710 };
3711 let raised_by = |setting: &Setting, lack: f64| {
3713 let mut higher = setting.clone();
3714 for (k, lift) in
3715 lifts.iter().enumerate().filter(|(k, lift)| lift.over.is_some() && setting.heights[*k] != lift.height)
3716 {
3717 higher.heights[k] += lift.up * lack;
3718 for z in higher.vias[k].iter_mut().flatten().filter_map(|point| point.last_mut()) {
3719 *z += lift.up * lack;
3720 }
3721 }
3722 higher
3723 };
3724 let (mut best, mut best_load) = (start.clone(), before.clone());
3725 let mut accepted = vec![(start.clone(), before.clone())];
3728 let mut improved = true;
3729 while improved {
3730 improved = false;
3731 let mut candidates = Vec::new();
3733 let lower = |setting: &Setting, k: usize, height: f64| {
3734 let mut lower = setting.clone();
3735 lower.heights[k] = height;
3736 lower
3737 };
3738 if lifts.iter().zip(&best.heights).filter(|(lift, h)| **h != lift.needed).count() > 1 {
3739 candidates.push(Setting { heights: lifts.iter().map(|lift| lift.needed).collect(), ..best.clone() });
3740 }
3741 for (k, lift) in lifts.iter().enumerate().filter(|(k, lift)| best.heights[*k] != lift.needed) {
3742 candidates.push(lower(&best, k, lift.needed));
3743 candidates.push(lower(&best, k, 0.5 * (best.heights[k] + lift.needed)));
3744 }
3745 candidates.push(Setting { blending: !best.blending, ..best.clone() });
3746 for k in (0..2).filter(|&k| best.tolerances[k] < allowed) {
3748 let mut tolerances = best.tolerances;
3749 tolerances[k] = allowed;
3750 candidates.push(Setting { tolerances, ..best.clone() });
3751 }
3752 if best.shaping {
3753 candidates.push(Setting { shaping: false, ..best.clone() });
3754 }
3755 if best.second {
3756 candidates.push(Setting { second: false, ..best.clone() });
3757 }
3758 for i in 0..3 {
3759 for step in [1.5, 1.2] {
3760 let mut faster = best.clone();
3761 faster.factors[i] *= step;
3762 candidates.push(faster);
3763 }
3764 }
3765 for (k, lift) in lifts.iter().enumerate() {
3767 let z = lift.from.len() - 1;
3768 let width = (0..z).map(|i| (lift.to[i] - lift.from[i]).powi(2)).sum::<f64>().sqrt();
3769 let with_via = |via: Option<Vec<Vec<f64>>>| {
3770 let mut out = best.clone();
3771 (out.vias[k], out.corners[k]) = (via, None);
3772 out
3773 };
3774 match &best.vias[k] {
3775 None => {
3776 let above = lift.up * (best.heights[k] - lift.lowest);
3780 if above > 0.0 {
3781 let mut rounded = with_via(Some(Vec::new()));
3782 rounded.corners[k] = Some(3.0 * above / 16.0);
3783 candidates.push(rounded);
3784 }
3785 for above in [0.5, 0.25, 0.125] {
3786 let mut via: Vec<f64> = (0..z).map(|i| 0.5 * (lift.from[i] + lift.to[i])).collect();
3787 via.push(best.heights[k] + lift.up * above * width);
3788 candidates.push(with_via(Some(vec![via])));
3789 }
3790 for above in [0.0, 0.125] {
3792 if let Some(over) = &lift.over {
3793 let via =
3794 over[..z].iter().copied().chain([lift.needed + lift.up * above * width]).collect();
3795 candidates.push(Setting {
3796 heights: lower(&best, k, lift.lowest).heights,
3797 ..with_via(Some(vec![via]))
3798 });
3799 }
3800 }
3801 if let Some(points) = &lift.profile {
3803 candidates.push(Setting {
3804 heights: lower(&best, k, lift.lowest).heights,
3805 ..with_via(Some(points.clone()))
3806 });
3807 }
3808 }
3809 Some(points) => {
3811 for via in points.iter().filter(|_| points.len() == 1) {
3812 for step in [0.125, 1.0 / 32.0] {
3813 for axis in 0..=z {
3814 for sign in [-1.0, 1.0] {
3815 let mut moved = via.clone();
3816 moved[axis] += sign * step * width;
3817 candidates.push(with_via(Some(vec![moved])));
3818 }
3819 }
3820 }
3821 }
3822 candidates.push(with_via(None));
3823 }
3824 }
3825 }
3826 let machine = probe.machine.as_mut();
3828 candidates.retain(|c| {
3829 lifts.iter().enumerate().all(|(k, lift)| {
3830 c.vias[k].as_ref().is_none_or(|via| {
3831 clears(
3832 &axis_infos,
3833 cycle_s,
3834 tolerance,
3835 lift,
3836 (c.heights[k], c.corners[k]),
3837 via,
3838 (&mut *machine, &obstacles, clearance),
3839 )
3840 })
3841 })
3842 });
3843 let tries_of = |candidate: Setting, best: f64, budget: usize| {
3847 let mut done = Vec::new();
3848 let mut tries = std::collections::VecDeque::from([candidate]);
3849 let mut raised = 0;
3850 while let Some(setting) = tries.pop_front() {
3851 if done.len() >= budget {
3852 break;
3853 }
3854 let result = evaluate(&setting);
3855 let Some((load, failed, _)) = &result else {
3856 done.push((setting, result));
3857 continue;
3858 };
3859 if failed.is_empty() && load.duration < best - 1e-4 {
3860 done.push((setting, result));
3861 break;
3862 }
3863 if !failed.is_empty() && failed.iter().all(|check| *check == "settling" || *check == "settling-angle") {
3864 if !setting.shaping {
3865 tries.push_back(Setting { shaping: true, follows: false, ..setting.clone() });
3866 if resonance.is_some() {
3867 tries.push_back(Setting { shaping: true, follows: true, ..setting.clone() });
3868 }
3869 } else if second_frequency.is_some() && !setting.second {
3870 tries.push_back(Setting { second: true, ..setting.clone() });
3871 }
3872 }
3873 let lack = load.clearance.map_or(f64::INFINITY, |run| clearance - run + 1e-6);
3877 if *failed == ["collision"] && raised < 2 && lack < 1e-3 {
3878 let higher = raised_by(&setting, lack);
3879 if higher != setting {
3880 raised += 1;
3881 tries.push_back(higher);
3882 }
3883 }
3884 done.push((setting, result));
3885 }
3886 done
3887 };
3888 let (mut from, mut batch) = (0, 1);
3893 'candidates: while from < candidates.len() {
3894 let chunk = &candidates[from..(from + batch).min(candidates.len())];
3895 (from, batch) = (from + chunk.len(), (2 * batch).min(threads().max(1)));
3896 let budget = max_runs.saturating_sub(runs.get());
3897 let best_duration = best_load.duration;
3898 let tried = on_all_cores(chunk.len(), |i| tries_of(chunk[i].clone(), best_duration, budget));
3899 for (setting, result) in tried.into_iter().flatten() {
3900 if runs.get() >= max_runs {
3901 break 'candidates;
3902 }
3903 let Some((load, failed)) = count(result) else { continue };
3904 if failed.is_empty() && load.duration < best_load.duration - 1e-4 {
3905 accepted.push((setting.clone(), load.clone()));
3906 (best, best_load, improved) = (setting, load, true);
3907 break 'candidates;
3908 }
3909 }
3910 }
3911 }
3912 let mut robust = None;
3913 if options.robust && options.worst {
3914 let (mut corner_runs, last) = (0, accepted.len() - 1);
3915 let mut at_worst = |setting: &Setting,
3918 ignore: Option<&[&'static str]>,
3919 from: &[Worst]|
3920 -> Result<(Vec<&'static str>, f64, Vec<Worst>), ConfigError> {
3921 let changed = build(setting)?;
3922 let stop = |v: &Verdict| ignore.is_some_and(|ignore| !v.ok && !ignore.contains(&v.check));
3923 let (worst, _, runs) = worst_search(entry, &changed, &bounds(&changed)?, from, &stop)?;
3924 corner_runs += runs;
3925 let least =
3926 worst.iter().find(|w| w.verdict.check == "collision").map_or(f64::INFINITY, |w| w.verdict.value);
3927 let mut out: Vec<&'static str> = worst.iter().filter(|w| !w.verdict.ok).map(|w| w.verdict.check).collect();
3928 out.sort();
3929 out.dedup();
3930 Ok((out, least, worst))
3931 };
3932 let (nominal_fails, _, mut from) = at_worst(&best, Some(&[]), &[])?;
3933 let excused = match (nominal_fails.is_empty(), last) {
3934 (true, _) => Vec::new(),
3935 (false, 0) => nominal_fails.clone(),
3936 (false, _) => at_worst(&accepted[0].0, None, &from)?.0,
3937 };
3938 let judged_on = |checks: &[&'static str]| -> Vec<&'static str> {
3939 checks.iter().copied().filter(|c| !excused.contains(c)).collect()
3940 };
3941 let mut pass = |k: usize, from: &[Worst]| -> Result<(Option<(Setting, CycleLoad)>, Vec<Worst>), ConfigError> {
3944 let (fails, least, worst) = at_worst(&accepted[k].0, Some(&excused), from)?;
3945 let failing = judged_on(&fails);
3946 if failing.is_empty() {
3947 return Ok((Some(accepted[k].clone()), worst));
3948 }
3949 if failing == ["collision"] && clearance - least < 1e-3 {
3950 let higher = raised_by(&accepted[k].0, clearance - least + 1e-6);
3951 if higher != accepted[k].0
3952 && let Some((load, _)) = judged(&higher).filter(|(_, failed)| failed.is_empty())
3953 && judged_on(&at_worst(&higher, Some(&excused), &worst)?.0).is_empty()
3954 {
3955 return Ok((Some((higher, load)), worst));
3956 }
3957 }
3958 Ok((None, worst))
3959 };
3960 let (lo, result) = if nominal_fails.is_empty() {
3964 (last, (best.clone(), best_load.clone()))
3965 } else {
3966 let top =
3967 if matches!(judged_on(&nominal_fails)[..], [] | ["collision"]) { last } else { last.saturating_sub(1) };
3968 let found = fastest_passing(top, |k| {
3969 let (passed, worst) = pass(k, &from)?;
3970 from = worst;
3971 Ok(passed)
3972 })?;
3973 found.unwrap_or_else(|| (0, accepted[0].clone()))
3974 };
3975 let (nominal_duration, steps_back) = (best_load.duration, last - lo);
3976 (best, best_load) = result;
3977 robust = Some(Robust { nominal_duration, nominal_fails, excused, steps_back, runs: corner_runs, worst: true });
3978 } else if options.robust {
3979 let mut band_runs = 0;
3980 let mut fails = |setting: &Setting| -> Result<(Vec<&'static str>, f64), ConfigError> {
3982 let changed = build(setting)?;
3983 let bounded = bounds(&changed)?;
3984 band_runs += 2 * bounded.len() + 1;
3985 let bands = verdict_bands(entry, &changed, &bounded)?;
3986 let least = bands.iter().find(|b| b.verdict.check == "collision").map_or(f64::INFINITY, |b| b.low);
3987 let mut out: Vec<&'static str> = bands.into_iter().filter(|b| !b.ok).map(|b| b.verdict.check).collect();
3988 out.sort();
3989 out.dedup();
3990 Ok((out, least))
3991 };
3992 let last = accepted.len() - 1;
3993 let (nominal_fails, mut least) = fails(&best)?;
3994 let excused = match (nominal_fails.is_empty(), last) {
3995 (true, _) => Vec::new(),
3996 (false, 0) => nominal_fails.clone(),
3997 (false, _) => fails(&accepted[0].0)?.0,
3998 };
3999 let judged_on = |checks: &[&'static str]| -> Vec<&'static str> {
4000 checks.iter().copied().filter(|c| !excused.contains(c)).collect()
4001 };
4002 let (mut k, mut failing) = (last, judged_on(&nominal_fails));
4005 let result = loop {
4006 if failing.is_empty() {
4007 break accepted[k].clone();
4008 }
4009 if failing == ["collision"] && clearance - least < 1e-3 {
4012 let higher = raised_by(&accepted[k].0, clearance - least + 1e-6);
4013 if higher != accepted[k].0
4014 && let Some((load, _)) = judged(&higher).filter(|(_, failed)| failed.is_empty())
4015 && judged_on(&fails(&higher)?.0).is_empty()
4016 {
4017 break (higher, load);
4018 }
4019 }
4020 if k <= 1 {
4021 k = 0;
4022 break accepted[0].clone();
4023 }
4024 k -= 1;
4025 let (checks, at_k) = fails(&accepted[k].0)?;
4026 (failing, least) = (judged_on(&checks), at_k);
4027 };
4028 let (nominal_duration, steps_back) = (best_load.duration, last - k);
4029 (best, best_load) = result;
4030 robust = Some(Robust { nominal_duration, nominal_fails, excused, steps_back, runs: band_runs, worst: false });
4031 }
4032 let mut front = Vec::new();
4033 if options.pareto {
4034 let [v, a, j] = best.factors;
4035 let slower: Vec<Setting> = [0.8, 0.6, 0.4]
4036 .into_iter()
4037 .flat_map(|f| [[v, a * f, j * f], [v * f, a * f, j * f]])
4038 .map(|factors| Setting { factors, ..best.clone() })
4039 .collect();
4040 for result in on_all_cores(slower.len(), |i| evaluate(&slower[i])) {
4042 count(result);
4043 }
4044 front = non_dominated(&passed.borrow());
4045 }
4046 let (from, to) = (build(&start)?, build(&best)?);
4047 let mut changes: Vec<(String, String, String)> = to
4048 .leaves()
4049 .into_iter()
4050 .zip(from.leaves())
4051 .filter(|((_, after), (_, before))| after != before)
4052 .map(|((path, after), (_, before))| (path, before.to_string(), after.to_string()))
4053 .collect();
4054 let (old_cycle, new_cycle) = (from.get("cycle.segment")?, to.get("cycle.segment")?);
4055 if old_cycle != new_cycle {
4056 changes.push(("cycle.segment".into(), old_cycle.to_string(), new_cycle.to_string()));
4057 }
4058 let lifts = lifts
4059 .iter()
4060 .enumerate()
4061 .filter(|(k, lift)| best.heights[*k] != lift.height || best.vias[*k].is_some())
4062 .map(|(k, lift)| LiftChange {
4063 segments: lift.segments,
4064 before: lift.height,
4065 after: best.heights[k],
4066 via: best.vias[k].clone().filter(|_| best.corners[k].is_none()),
4067 corners: best.corners[k],
4068 })
4069 .collect();
4070 Ok(Optimised { before, after: best_load, changes, lifts, runs: runs.get(), robust, front })
4071}
4072
4073const NOT_MACHINE_DATA: [&str; 1] = ["ratings.bearing_reliability_percent"];
4076
4077#[derive(Debug, Clone)]
4079pub struct Sensitivity {
4080 pub path: String,
4081 pub value: f64,
4082 pub bounds: (f64, f64),
4084 pub low: CycleLoad,
4085 pub high: CycleLoad,
4086}
4087
4088impl Sensitivity {
4089 pub fn changes(&self, nominal: &CycleLoad) -> [f64; 6] {
4092 let change = |a: f64, b: f64| if b.abs() > 1e-12 { a / b - 1.0 } else { 0.0 };
4093 let per_motor = |load: &CycleLoad, pick: fn(&MotorLoad) -> f64| -> f64 {
4094 load.motors
4095 .iter()
4096 .zip(&nominal.motors)
4097 .map(|(m, n)| change(pick(m), pick(n)))
4098 .fold(0.0, |a: f64, b| if b.abs() > a.abs() { b } else { a })
4099 };
4100 [
4101 per_motor(&self.low, |m| m.peak_torque),
4102 per_motor(&self.high, |m| m.peak_torque),
4103 per_motor(&self.low, |m| m.rms_torque),
4104 per_motor(&self.high, |m| m.rms_torque),
4105 change(self.low.duration, nominal.duration),
4106 change(self.high.duration, nominal.duration),
4107 ]
4108 }
4109
4110 pub fn strength(&self, nominal: &CycleLoad) -> f64 {
4112 self.changes(nominal).iter().fold(0.0, |a: f64, b| a.max(b.abs()))
4113 }
4114}
4115
4116pub fn sensitivity(
4123 entry: &MachineEntry,
4124 cfg: &Config,
4125 paths: &[String],
4126 delta: f64,
4127) -> Result<(CycleLoad, Vec<Sensitivity>), ConfigError> {
4128 let cfg = &crate::catalog::resolve(entry, cfg)?;
4129 let configured = bounds(cfg)?;
4130 let run = |cfg: &Config| -> Option<CycleLoad> { analyse_cycle_with(&mut Sim::new(entry, cfg).ok()?, false).ok() };
4131 let varied: Vec<(&String, f64, (f64, f64))> = paths
4133 .iter()
4134 .filter(|path| !effect_off(cfg, path) && !NOT_MACHINE_DATA.contains(&path.as_str()))
4135 .filter_map(|path| {
4136 let value = cfg.f64(path).ok()?;
4137 let bound = configured.iter().find(|b| b.0 == *path).map(|b| (b.1, b.2));
4138 if bound.is_none() && value == 0.0 {
4140 return None;
4141 }
4142 Some((path, value, bound.unwrap_or((value * (1.0 - delta), value * (1.0 + delta)))))
4143 })
4144 .collect();
4145 let mut runs = on_all_cores(2 * varied.len() + 1, |k| {
4147 if k == 0 {
4148 return run(cfg);
4149 }
4150 let (path, _, bounds) = varied[(k - 1) / 2];
4151 let mut changed = cfg.clone();
4152 set_bounded(&mut changed, path, if k % 2 == 1 { bounds.0 } else { bounds.1 }).ok()?;
4153 run(&changed)
4154 })
4155 .into_iter();
4156 let nominal = runs.next().flatten().ok_or_else(|| ConfigError::Invalid("cycle".into()))?;
4157 let mut out = Vec::new();
4158 for (path, value, bounds) in varied {
4159 if let (Some(low), Some(high)) = (runs.next().flatten(), runs.next().flatten()) {
4160 out.push(Sensitivity { path: path.clone(), value, bounds, low, high });
4161 }
4162 }
4163 Ok((nominal, out))
4164}
4165
4166#[derive(Debug, Clone, Copy)]
4168pub struct SweepPoint {
4169 pub frequency: f64,
4170 pub gain: f64,
4172 pub phase_deg: f64,
4173}
4174
4175pub const SWEEP_POINTS: usize = 120;
4178
4179pub fn default_sweep_amplitude(entry: &MachineEntry, cfg: &Config) -> Result<f64, ConfigError> {
4186 let cfg = crate::catalog::resolve(entry, cfg)?;
4187 Ok((0.4 * cfg.positive("drive.peak_torque_nm")?).min(1.5))
4188}
4189
4190pub fn frequency_sweep(
4195 entry: &MachineEntry,
4196 cfg: &Config,
4197 motor: usize,
4198 frequencies: &[f64],
4199 amplitude: f64,
4200) -> Result<Vec<SweepPoint>, ConfigError> {
4201 let cfg = &crate::catalog::resolve(entry, cfg)?;
4202 let (dt, substeps) = (cfg.positive("sim.dt_s")?, cfg.positive("sim.substeps")? as u32);
4203 let at_rest = || -> Result<_, ConfigError> {
4205 let machine = (entry.build)(cfg)?;
4206 let motors = machine.motors().len();
4207 if motor >= motors {
4208 return Err(ConfigError::Invalid("motor".into()));
4209 }
4210 let (mut start, mut hold) = (Vec::new(), vec![0.0; motors]);
4211 machine.equilibrium(&crate::sim::start_pose(cfg, machine.as_ref())?, &mut start, &mut hold);
4212 Ok((machine, start, hold))
4213 };
4214 at_rest()?;
4215 check_frequencies(frequencies)?;
4216 on_all_cores(frequencies.len(), |i| {
4217 let (frequency, (machine, start, hold)) = (frequencies[i], at_rest()?);
4218 let motors = hold.len();
4219 let mut rk = Rk4::new(start.len());
4220 let (mut pos, mut speed) = (vec![0.0; motors], vec![0.0; motors]);
4221 let omega = std::f64::consts::TAU * frequency;
4222 let period = 1.0 / frequency;
4224 let settle = (0.3 / period).ceil().max(5.0) * period;
4225 let measure = (0.2 / period).ceil().max(5.0) * period;
4226 let (settle_steps, measure_steps) = ((settle / dt).round() as u64, (measure / dt).round() as u64);
4227 let (mut state, mut torque) = (start.clone(), hold.clone());
4228 let (mut in_phase, mut quadrature) = (0.0, 0.0);
4229 for step in 0..settle_steps + measure_steps {
4230 let t = (step as f64 + 0.5) * dt;
4231 torque[motor] = hold[motor] + amplitude * (omega * t).sin();
4232 advance(machine.as_ref(), &mut rk, &mut state, &torque, dt, substeps);
4233 if step >= settle_steps {
4234 machine.motor_state(&state, &mut pos, &mut speed);
4235 let t = (step + 1) as f64 * dt;
4236 in_phase += speed[motor] * (omega * t).sin();
4237 quadrature += speed[motor] * (omega * t).cos();
4238 }
4239 }
4240 let (a, b) = (2.0 * in_phase / measure_steps as f64, 2.0 * quadrature / measure_steps as f64);
4241 Ok(SweepPoint { frequency, gain: a.hypot(b) / amplitude, phase_deg: b.atan2(a).to_degrees() })
4242 })
4243 .into_iter()
4244 .collect()
4245}
4246
4247pub(crate) fn check_frequencies(frequencies: &[f64]) -> Result<(), ConfigError> {
4249 if frequencies.iter().all(|f| f.is_finite() && *f > 0.0) {
4250 Ok(())
4251 } else {
4252 Err(ConfigError::Invalid("frequency".into()))
4253 }
4254}
4255
4256pub fn modes_along(machine: &dyn Machine, pose: &[f64], axis: usize, points: usize) -> Vec<(f64, Vec<Mode>)> {
4260 let info = &machine.axes()[axis];
4261 (0..points)
4262 .map(|i| {
4263 let mut at = pose.to_vec();
4264 at[axis] = info.min + (info.max - info.min) * i as f64 / (points.max(2) - 1) as f64;
4265 (at[axis], machine.modes(&at))
4266 })
4267 .collect()
4268}
4269
4270pub fn small_amplitude_along(
4273 machine: &dyn Machine,
4274 pose: &[f64],
4275 axis: usize,
4276 rows: &[(f64, Vec<Mode>)],
4277) -> Option<Vec<Vec<Mode>>> {
4278 let small: Vec<Vec<Mode>> = rows
4279 .iter()
4280 .map(|(position, _)| {
4281 let mut at = pose.to_vec();
4282 at[axis] = *position;
4283 machine.modes_small_amplitude(&at)
4284 })
4285 .collect();
4286 let same = |a: &[Mode], b: &[Mode]| a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.hz == b.hz);
4287 (!rows.iter().zip(&small).all(|((_, large), small)| same(large, small))).then_some(small)
4288}
4289
4290pub fn log_spaced(from: f64, to: f64, points: usize) -> Vec<f64> {
4292 (0..points).map(|i| from * (to / from).powf(i as f64 / (points.max(2) - 1) as f64)).collect()
4293}
4294
4295#[derive(Debug, Clone)]
4300pub struct StepResponse {
4301 pub size: f64,
4302 pub trace: Vec<(f64, f64)>,
4304 pub rise_time: f64,
4306 pub overshoot: f64,
4308 pub settling_time: f64,
4310}
4311
4312fn settled(entry: &MachineEntry, cfg: &Config, axis: usize) -> Result<(Sim, f64), ConfigError> {
4314 check_cancelled();
4315 let mut sim = Sim::new(entry, cfg)?;
4316 if axis >= sim.machine.axes().len() {
4317 return Err(ConfigError::Invalid("axis".into()));
4318 }
4319 sim.run(0.05, |_| {});
4320 let position = tool_position(&sim, axis);
4321 Ok((sim, position))
4322}
4323
4324fn tool_position(sim: &Sim, axis: usize) -> f64 {
4325 let n = sim.machine.axes().len();
4326 let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
4327 sim.machine.tool_state(&sim.state, &mut pos, &mut vel);
4328 pos[axis]
4329}
4330
4331pub fn step_response(
4334 entry: &MachineEntry,
4335 cfg: &Config,
4336 axis: usize,
4337 size: f64,
4338 seconds: f64,
4339) -> Result<StepResponse, ConfigError> {
4340 let (mut sim, start) = settled(entry, cfg, axis)?;
4341 sim.control.setpoint_offset[axis] = size;
4342 let (t0, every) = (sim.time(), (0.25e-3 / sim.dt).round().max(1.0) as u64);
4343 let mut trace = vec![(0.0, 0.0)];
4344 sim.run(seconds, |s| {
4345 if s.step % every == 0 {
4346 trace.push((s.time() - t0, tool_position(s, axis) - start));
4347 }
4348 });
4349 let relative = |fraction: f64| trace.iter().find(|(_, y)| y / size >= fraction).map_or(f64::NAN, |(t, _)| *t);
4350 let overshoot = trace.iter().map(|(_, y)| y / size - 1.0).fold(0.0, f64::max);
4351 let settling_time = trace.iter().rev().find(|(_, y)| (y / size - 1.0).abs() > 0.02).map_or(0.0, |(t, _)| *t);
4352 Ok(StepResponse { size, rise_time: relative(0.9) - relative(0.1), overshoot, settling_time, trace })
4353}
4354
4355pub fn closed_loop_response(
4359 entry: &MachineEntry,
4360 cfg: &Config,
4361 axis: usize,
4362 frequencies: &[f64],
4363 amplitude: f64,
4364) -> Result<Vec<SweepPoint>, ConfigError> {
4365 check_frequencies(frequencies)?;
4366 on_all_cores(frequencies.len(), |i| {
4367 let frequency = frequencies[i];
4368 let (mut sim, start) = settled(entry, cfg, axis)?;
4369 let (omega, t0, dt) = (std::f64::consts::TAU * frequency, sim.time(), sim.dt);
4370 let period = 1.0 / frequency;
4372 let whole = |seconds: f64| ((seconds / period).ceil().max(4.0) * period / dt).round() as u64;
4373 let (settle_steps, measure_steps) = (whole(0.3), whole(0.3));
4374 let (mut in_phase, mut quadrature) = (0.0, 0.0);
4375 for step in 0..settle_steps + measure_steps {
4376 sim.control.setpoint_offset[axis] = amplitude * (omega * (sim.time() - t0)).sin();
4377 sim.step();
4378 if step >= settle_steps {
4379 let (t, y) = (sim.time() - t0, tool_position(&sim, axis) - start);
4380 in_phase += y * (omega * t).sin();
4381 quadrature += y * (omega * t).cos();
4382 }
4383 }
4384 let (a, b) = (2.0 * in_phase / measure_steps as f64, 2.0 * quadrature / measure_steps as f64);
4385 Ok(SweepPoint { frequency, gain: a.hypot(b) / amplitude, phase_deg: b.atan2(a).to_degrees() })
4386 })
4387 .into_iter()
4388 .collect()
4389}
4390
4391pub fn bandwidth(points: &[SweepPoint]) -> Option<f64> {
4394 let limit = std::f64::consts::FRAC_1_SQRT_2;
4395 let below = points.iter().position(|p| p.gain < limit)?;
4396 let (a, b) = (points.get(below.checked_sub(1)?)?, &points[below]);
4397 let share = (a.gain - limit) / (a.gain - b.gain);
4398 Some(a.frequency * (b.frequency / a.frequency).powf(share))
4399}
4400
4401#[derive(Debug, Clone, Copy, PartialEq)]
4405pub struct LoopPoint {
4406 pub frequency: f64,
4407 pub re: f64,
4408 pub im: f64,
4409 pub sensitivity: f64,
4410 pub plant: [f64; 2],
4413}
4414
4415pub fn velocity_loop_response(
4429 entry: &MachineEntry,
4430 cfg: &Config,
4431 motor: usize,
4432 frequencies: &[f64],
4433 amplitude: f64,
4434) -> Result<Vec<LoopPoint>, ConfigError> {
4435 check_frequencies(frequencies)?;
4436 let cfg = &lossless(cfg)?;
4437 frequencies.iter().map(|&frequency| loop_point(settled(entry, cfg, 0)?.0, motor, frequency, amplitude)).collect()
4438}
4439
4440fn lossless(cfg: &Config) -> Result<Config, ConfigError> {
4442 let mut lossless = cfg.clone();
4443 if lossless.get("effects.gearbox_efficiency").is_ok() {
4444 lossless.set_text("effects.gearbox_efficiency = false")?;
4445 }
4446 Ok(lossless)
4447}
4448
4449fn loop_point(mut sim: Sim, motor: usize, frequency: f64, amplitude: f64) -> Result<LoopPoint, ConfigError> {
4451 if motor >= sim.control.drives.len() {
4452 return Err(ConfigError::Invalid("motor".into()));
4453 }
4454 sim.control.unrounded_encoders();
4456 let every = (sim.control.drive_params().velocity_cycle / sim.dt).round() as u64;
4457 let (omega, t0, period) = (std::f64::consts::TAU * frequency, sim.time(), 1.0 / frequency);
4458 let whole = |seconds: f64| ((seconds / period).ceil().max(5.0) * period / sim.dt).round() as u64;
4459 let (settle_steps, total) = (whole(0.1), whole(0.1) + whole(0.1));
4460 let (mut u_ab, mut e_ab, mut samples) = ([0.0; 2], [0.0; 2], 0.0);
4461 let (mut torque_ab, mut speed_ab) = ([0.0; 2], [0.0; 2]);
4462 let (mut seen, mut limited, mut pos, mut speed) =
4463 (Vec::new(), false, vec![0.0; sim.control.drives.len()], vec![0.0; sim.control.drives.len()]);
4464 for step in 0..total {
4465 let due = sim.step.is_multiple_of(every);
4466 let (s, c) = (omega * (sim.time() - t0)).sin_cos();
4467 if due {
4468 sim.control.drives[motor].torque_injection = amplitude * s;
4469 }
4470 sim.step();
4471 if due {
4472 sim.machine.motor_state(&sim.state, &mut pos, &mut speed);
4474 let (p, drive) = (sim.control.drive_params_of(motor), &sim.control.drives[motor]);
4475 let (low, high) = p.torque_range_at(speed[motor], drive.max_voltage(p));
4476 let e = drive.torque_demand + drive.torque_injection;
4477 limited |= !(low < e && e < high);
4478 if step >= settle_steps {
4479 let u = drive.torque_demand;
4480 (u_ab[0], u_ab[1], e_ab[0], e_ab[1]) =
4481 (u_ab[0] + u * s, u_ab[1] + u * c, e_ab[0] + e * s, e_ab[1] + e * c);
4482 samples += 1.0;
4483 seen.push((s, c, e));
4484 let (t, v) = (drive.torque, speed[motor]);
4485 (torque_ab[0], torque_ab[1], speed_ab[0], speed_ab[1]) =
4486 (torque_ab[0] + t * s, torque_ab[1] + t * c, speed_ab[0] + v * s, speed_ab[1] + v * c);
4487 }
4488 }
4489 }
4490 let (u, e) =
4492 ([2.0 * u_ab[0] / samples, 2.0 * u_ab[1] / samples], [2.0 * e_ab[0] / samples, 2.0 * e_ab[1] / samples]);
4493 let mean = seen.iter().map(|(_, _, x)| x).sum::<f64>() / samples;
4496 let rest = (seen.iter().map(|(s, c, x)| (x - mean - e[0] * s - e[1] * c).powi(2)).sum::<f64>() / samples).sqrt();
4497 let e2 = e[0] * e[0] + e[1] * e[1];
4498 let (re, im) = if limited || !(rest < amplitude) {
4499 (f64::NAN, f64::NAN)
4500 } else {
4501 (-(u[0] * e[0] + u[1] * e[1]) / e2, -(u[1] * e[0] - u[0] * e[1]) / e2)
4502 };
4503 let (t, v) = (torque_ab, speed_ab);
4505 let t2 = (t[0] * t[0] + t[1] * t[1]) * if re.is_nan() { f64::NAN } else { 1.0 };
4506 let plant = [(v[0] * t[0] + v[1] * t[1]) / t2, (v[1] * t[0] - v[0] * t[1]) / t2];
4507 Ok(LoopPoint { frequency, re, im, sensitivity: e2.sqrt() / amplitude, plant })
4508}
4509
4510#[derive(Debug, Clone, Copy, PartialEq)]
4512pub struct LoopMargins {
4513 pub crossover_hz: f64,
4515 pub phase_margin_deg: f64,
4521 pub gain_margin_db: f64,
4527 pub valid: bool,
4530 pub peak_sensitivity: f64,
4533 pub peak_frequency_hz: f64,
4534 pub hammering: Option<Hammering>,
4537 pub play_margin_db: f64,
4541}
4542
4543impl LoopMargins {
4544 pub fn stable(&self) -> bool {
4548 self.valid && !(self.phase_margin_deg <= 0.0) && self.gain_margin_db > 0.0 && self.hammering.is_none()
4549 }
4550}
4551
4552pub fn loop_margins(points: &[LoopPoint]) -> LoopMargins {
4556 let measured = |p: &&LoopPoint| p.re.is_finite() && p.im.is_finite();
4557 let mut m = LoopMargins {
4558 crossover_hz: f64::NAN,
4559 phase_margin_deg: f64::NAN,
4560 gain_margin_db: f64::INFINITY,
4561 valid: points.iter().all(|p| measured(&p)),
4562 peak_sensitivity: 0.0,
4563 peak_frequency_hz: f64::NAN,
4564 hammering: None,
4565 play_margin_db: f64::NAN,
4566 };
4567 let points: Vec<&LoopPoint> = points.iter().filter(measured).collect();
4568 for p in &points {
4569 if p.sensitivity > m.peak_sensitivity {
4570 (m.peak_sensitivity, m.peak_frequency_hz) = (p.sensitivity, p.frequency);
4571 }
4572 }
4573 if !m.valid {
4574 (m.phase_margin_deg, m.gain_margin_db) = (f64::NAN, f64::NAN);
4575 return m;
4576 }
4577 let mut phase: Vec<f64> = Vec::with_capacity(points.len());
4579 for p in &points {
4580 let raw = p.im.atan2(p.re).to_degrees();
4581 phase.push(phase.last().map_or(raw, |last| raw + 360.0 * ((last - raw) / 360.0).round()));
4582 }
4583 let gain: Vec<f64> = points.iter().map(|p| p.re.hypot(p.im).ln()).collect();
4584 let crossovers: Vec<(usize, f64)> = (1..points.len())
4586 .filter(|&i| gain[i - 1].signum() != gain[i].signum())
4587 .map(|i| (i, gain[i - 1] / (gain[i - 1] - gain[i])))
4588 .collect();
4589 let shift = phase.first().map_or(0.0, |p| -360.0 * ((p - 90.0) / 360.0).ceil());
4593 phase.iter_mut().for_each(|p| *p += shift);
4594 for &(i, share) in &crossovers {
4600 let turned = 180.0 + phase[i - 1] + (phase[i] - phase[i - 1]) * share;
4601 let margin = (turned - 360.0 * ((turned - 180.0) / 360.0).ceil()).abs();
4602 if !(margin >= m.phase_margin_deg) {
4603 (m.phase_margin_deg, m.crossover_hz) =
4604 (margin, points[i - 1].frequency * (points[i].frequency / points[i - 1].frequency).powf(share));
4605 }
4606 }
4607 const PAIRED: f64 = 1.05;
4619 let (mut open, mut ahead, mut worst) = (Vec::new(), None::<f64>, f64::INFINITY);
4620 let samples: Vec<(f64, f64, f64)> = points
4621 .first()
4622 .map(|p| (p.frequency, 0.0, gain[0]))
4623 .into_iter()
4624 .chain(
4625 points
4626 .iter()
4627 .map(|p| p.frequency)
4628 .zip(phase.iter().copied().zip(gain.iter().copied()))
4629 .map(|(f, (p, g))| (f, p, g)),
4630 )
4631 .collect();
4632 for w in samples.windows(2) {
4633 let ((_, pa, ga), (fb, pb, gb)) = (w[0], w[1]);
4634 let at = |level: f64| ga + (gb - ga) * (pa - level) / (pa - pb);
4635 let mut level = -180.0 + 360.0 * ((pa + 180.0) / 360.0).floor();
4636 while pb < level && level <= pa {
4637 let g = at(level);
4638 if g <= 0.0 {
4639 worst = worst.min(-g);
4640 } else if !ahead.is_some_and(|rise| fb <= rise * PAIRED) {
4641 open.push(g);
4642 }
4643 ahead = None;
4644 level -= 360.0;
4645 }
4646 level += 360.0;
4647 while pa < level && level <= pb {
4648 ahead = (at(level) > 0.0 && open.pop().is_none()).then_some(fb);
4649 level += 360.0;
4650 }
4651 }
4652 m.gain_margin_db = open.iter().fold(worst, |w, g| w.min(-g)) * 20.0 / std::f64::consts::LN_10;
4653 if m.gain_margin_db < 0.0 {
4654 m.phase_margin_deg = -m.phase_margin_deg;
4655 }
4656 m
4657}
4658
4659pub const LOOP_FLOOR_HZ: f64 = 1.0;
4662
4663pub fn loop_frequencies(cfg: &Config) -> Result<Vec<f64>, ConfigError> {
4666 Ok(log_spaced(10.0, 0.25 / cfg.positive("drive.velocity_cycle_s")?, 60))
4667}
4668
4669pub fn loop_amplitude(entry: &MachineEntry, cfg: &Config, id: &str) -> Result<f64, ConfigError> {
4672 let own = crate::catalog::motor_config(&crate::catalog::resolve(entry, cfg)?, id)?;
4673 Ok(0.1 * own.positive("drive.rated_torque_nm")?)
4674}
4675
4676pub const REFINE_TURN_DEG: f64 = 30.0;
4681pub const REFINE_GAIN_DB: f64 = 3.0;
4682pub const REFINE_CLOSEST: f64 = 1.001;
4685pub const REFINE_ROUNDS: usize = 8;
4687
4688pub fn refinement(points: &[(f64, [f64; 2])]) -> Vec<f64> {
4692 points
4693 .windows(2)
4694 .filter_map(|w| {
4695 let ((fa, a), (fb, b)) = (w[0], w[1]);
4696 let turn = (a[0] * b[1] - a[1] * b[0]).atan2(a[0] * b[0] + a[1] * b[1]).to_degrees().abs();
4698 let change = 20.0 * (b[0].hypot(b[1]) / a[0].hypot(a[1])).log10().abs();
4699 ((turn > REFINE_TURN_DEG || change > REFINE_GAIN_DB) && fb / fa > REFINE_CLOSEST).then(|| (fa * fb).sqrt())
4700 })
4701 .collect()
4702}
4703
4704#[derive(Debug, Default)]
4707pub struct Progress {
4708 pub done: std::sync::atomic::AtomicUsize,
4709 pub total: std::sync::atomic::AtomicUsize,
4710 pub cancel: std::sync::atomic::AtomicBool,
4711}
4712
4713pub const CANCELLED: &str = "cancelled";
4715
4716pub fn velocity_loop_responses(
4723 entry: &MachineEntry,
4724 configs: &[Config],
4725 progress: &Progress,
4726) -> Result<Vec<Vec<Vec<LoopPoint>>>, ConfigError> {
4727 use std::sync::atomic::Ordering::Relaxed;
4728 let first = &crate::catalog::resolve(entry, configs.first().ok_or_else(|| ConfigError::Invalid("config".into()))?)?;
4729 let frequencies = loop_frequencies(first)?;
4730 let spacing = frequencies[1] / frequencies[0];
4731 let machine = (entry.build)(first)?;
4732 let amplitudes =
4733 machine.motors().iter().map(|m| loop_amplitude(entry, first, m.id)).collect::<Result<Vec<_>, _>>()?;
4734 let range = frequencies[0]..=frequencies[frequencies.len() - 1];
4735 let mut own: Vec<Vec<f64>> = Vec::with_capacity(configs.len());
4737 for cfg in configs {
4738 let modes = if cfg.bool("effects.payload").ok() == first.bool("effects.payload").ok() {
4740 machine.modes(&cfg.f64s("start.pose")?)
4741 } else {
4742 (entry.build)(&crate::catalog::resolve(entry, cfg)?)?.modes(&cfg.f64s("start.pose")?)
4743 };
4744 own.push(frequencies.iter().copied().chain(modes.iter().map(|m| m.hz).filter(|f| range.contains(f))).collect());
4745 }
4746 let motors = machine.motors().len();
4747 let lossless = configs.iter().map(lossless).collect::<Result<Vec<_>, _>>()?;
4750 let starts = on_all_cores(configs.len(), |run| settled(entry, &lossless[run], 0).map(|(sim, _)| sim.snapshot()))
4751 .into_iter()
4752 .collect::<Result<Vec<_>, _>>()?;
4753 let counted = current_job().is_some_and(|job| std::ptr::eq(&*job, progress));
4756 let measure = |jobs: &[(usize, usize, f64)]| -> Result<Vec<LoopPoint>, ConfigError> {
4757 if !counted {
4758 progress.total.fetch_add(jobs.len(), Relaxed);
4759 }
4760 on_all_cores(jobs.len(), |j| {
4761 if progress.cancel.load(Relaxed) {
4762 return Err(ConfigError::Invalid(CANCELLED.into()));
4763 }
4764 let (run, motor, frequency) = jobs[j];
4765 check_frequencies(&[frequency])?;
4766 let mut sim = Sim::new(entry, &lossless[run])?;
4767 sim.restore(&starts[run])?;
4768 let point = loop_point(sim, motor, frequency, amplitudes[motor]);
4769 if !counted {
4770 progress.done.fetch_add(1, Relaxed);
4771 }
4772 point
4773 })
4774 .into_iter()
4775 .collect()
4776 };
4777 let mut curves = vec![vec![Vec::<LoopPoint>::new(); motors]; configs.len()];
4778 let mut jobs = Vec::new();
4779 for run in 0..configs.len() {
4780 for motor in 0..motors {
4781 jobs.extend(own[run].iter().map(|&f| (run, motor, f)));
4782 }
4783 }
4784 for round in 0..=REFINE_ROUNDS {
4785 for (&(run, motor, _), point) in jobs.iter().zip(measure(&jobs)?) {
4786 curves[run][motor].push(point);
4787 }
4788 if round == 0 {
4792 loop {
4793 jobs.clear();
4794 for (run, per_motor) in curves.iter().enumerate() {
4795 for (motor, curve) in per_motor.iter().enumerate() {
4796 let low = curve.iter().min_by(|a, b| a.frequency.total_cmp(&b.frequency)).unwrap();
4797 if low.re.hypot(low.im) < 1.0 && low.frequency / spacing >= LOOP_FLOOR_HZ {
4798 jobs.push((run, motor, low.frequency / spacing));
4799 }
4800 }
4801 }
4802 if jobs.is_empty() {
4803 break;
4804 }
4805 for (&(run, motor, _), point) in jobs.iter().zip(measure(&jobs)?) {
4806 curves[run][motor].push(point);
4807 }
4808 }
4809 }
4810 jobs.clear();
4811 for (run, per_motor) in curves.iter_mut().enumerate() {
4812 for (motor, curve) in per_motor.iter_mut().enumerate() {
4813 curve.sort_by(|a, b| a.frequency.total_cmp(&b.frequency));
4814 if round < REFINE_ROUNDS {
4815 let of = |value: fn(&LoopPoint) -> [f64; 2]| {
4816 refinement(&curve.iter().map(|p| (p.frequency, value(p))).collect::<Vec<_>>())
4817 };
4818 let mut more = of(|p| [p.re, p.im]);
4819 more.extend(of(|p| p.plant));
4820 more.sort_by(f64::total_cmp);
4821 more.dedup();
4822 jobs.extend(more.into_iter().map(|f| (run, motor, f)));
4823 }
4824 }
4825 }
4826 if jobs.is_empty() {
4827 break;
4828 }
4829 }
4830 Ok(curves)
4831}
4832
4833pub fn margin_poses(cfg: &Config) -> Result<Vec<Vec<f64>>, ConfigError> {
4837 Ok(margin_states(cfg)?.into_iter().map(|(pose, _)| pose).collect())
4838}
4839
4840pub fn margin_payloads(cfg: &Config) -> Result<Vec<bool>, ConfigError> {
4844 Ok(margin_states(cfg)?.into_iter().map(|(_, payload)| payload).collect())
4845}
4846
4847fn margin_states(cfg: &Config) -> Result<Vec<(Vec<f64>, bool)>, ConfigError> {
4848 let mut states = vec![(cfg.f64s("start.pose")?, true)];
4849 let has_payload = cfg.bool("effects.payload").unwrap_or(false);
4850 let number = |v: &toml::Value| v.as_float().or_else(|| v.as_integer().map(|i| i as f64));
4851 for segment in cfg.array("cycle.segment").into_iter().flatten() {
4852 let target: Vec<f64> =
4853 segment.get("target").and_then(|t| t.as_array()).into_iter().flatten().filter_map(number).collect();
4854 let payload = !has_payload || segment.get("payload").and_then(|p| p.as_bool()).unwrap_or(true);
4855 let state = (target, payload);
4856 if state.0.len() == states[0].0.len() && !states.contains(&state) {
4857 states.push(state);
4858 }
4859 }
4860 Ok(states)
4861}
4862
4863fn at_pose(cfg: &Config, pose: &[f64], payload: bool) -> Result<Config, ConfigError> {
4866 let mut at = cfg.clone();
4867 at.set_text(&format!("start.pose = {pose:?}"))?;
4868 if !payload {
4869 at.set_text("effects.payload = false")?;
4870 }
4871 Ok(at)
4872}
4873
4874pub fn velocity_loop_margins(
4881 entry: &MachineEntry,
4882 cfg: &Config,
4883 bounds: &[(String, f64, f64)],
4884) -> Result<Vec<(String, Vec<LoopMargins>)>, ConfigError> {
4885 let resolved = &crate::catalog::resolve(entry, cfg)?;
4886 let (bounds, cfg) = (&followed(cfg, resolved, bounds), resolved);
4887 let mut runs = vec![(String::new(), cfg.clone())];
4888 let (poses, payloads) = (margin_poses(cfg)?, margin_payloads(cfg)?);
4889 for (pose, &payload) in poses.iter().zip(&payloads).skip(1) {
4890 let text: Vec<String> = pose.iter().map(|x| format!("{x}")).collect();
4891 let off = if payload { "" } else { " effects.payload=false" };
4892 runs.push((format!("start.pose=[{}]{off}", text.join(" ")), at_pose(cfg, pose, payload)?));
4893 }
4894 for (path, low, high) in bounds {
4895 for value in [low, high] {
4896 let mut changed = cfg.clone();
4897 set_bounded(&mut changed, path, *value)?;
4898 runs.push((format!("{path}={value:?}"), changed));
4899 }
4900 }
4901 let mut configs: Vec<Config> = runs.iter().map(|(_, c)| c.clone()).collect();
4902 let count = configs.len();
4904 let play = cfg.bool("effects.gearbox_backlash").unwrap_or(false);
4905 if play {
4906 for run in 0..count {
4907 let mut closed = configs[run].clone();
4908 closed.set_text("effects.gearbox_backlash = false")?;
4909 configs.push(closed);
4910 }
4911 }
4912 let responses = velocity_loop_responses(entry, &configs, &Progress::default())?;
4913 let motors = responses.first().map_or(0, Vec::len);
4914 let pose_of = |run: usize| if run < poses.len() { run } else { 0 };
4915 let hammering = on_all_cores(count * motors, |j| {
4916 let found = hammering_at(entry, &configs[j / motors], j % motors)?;
4917 Ok(found.map(|h| Hammering { pose: pose_of(j / motors), ..h }))
4918 })
4919 .into_iter()
4920 .collect::<Result<Vec<_>, ConfigError>>()?;
4921 Ok(runs
4922 .into_iter()
4923 .zip(&responses)
4924 .enumerate()
4925 .map(|(run, ((name, _), curves))| {
4926 let margins = curves.iter().enumerate().map(|(motor, points)| LoopMargins {
4927 hammering: hammering[run * motors + motor],
4928 play_margin_db: if play { play_margin(points, &responses[count + run][motor]) } else { f64::NAN },
4929 ..loop_margins(points)
4930 });
4931 (name, margins.collect())
4932 })
4933 .collect())
4934}
4935
4936pub fn play_margin(play: &[LoopPoint], closed: &[LoopPoint]) -> f64 {
4956 type Cx = [f64; 2];
4957 let mul = |a: Cx, b: Cx| [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]];
4958 let div = |a: Cx, b: Cx| {
4959 let n = b[0] * b[0] + b[1] * b[1];
4960 [(a[0] * b[0] + a[1] * b[1]) / n, (a[1] * b[0] - a[0] * b[1]) / n]
4961 };
4962 let add = |a: Cx, b: Cx| [a[0] + b[0], a[1] + b[1]];
4963 let sub = |a: Cx, b: Cx| [a[0] - b[0], a[1] - b[1]];
4964 let valid = |p: &LoopPoint| [p.re, p.im, p.plant[0], p.plant[1]].iter().all(|x| x.is_finite());
4965 if play.len() < 2 || closed.len() < 2 || !play.iter().chain(closed).all(valid) {
4966 return f64::NAN;
4967 }
4968 let same = closed.iter().all(|c| {
4969 play.iter()
4970 .find(|p| p.frequency == c.frequency)
4971 .is_none_or(|p| (p.re - c.re).hypot(p.im - c.im) <= 1e-3 * c.re.hypot(c.im))
4972 });
4973 if same {
4974 return f64::NAN;
4975 }
4976 let tau = std::f64::consts::TAU;
4977 let s = |f: f64| [0.0, tau * f];
4978 let inertia = |p: &LoopPoint| div([1.0, 0.0], p.plant)[1] / (tau * p.frequency);
4980 let mut upper: Vec<f64> = play[play.len() / 2..].iter().map(inertia).collect();
4981 upper.sort_by(f64::total_cmp);
4982 let rotor = upper[upper.len() / 2];
4983 let load = inertia(closed.iter().min_by(|a, b| a.frequency.total_cmp(&b.frequency)).unwrap()) - rotor;
4984 if !(rotor > 0.0 && load > 0.0) {
4985 return f64::NAN;
4986 }
4987 let mut rows: Vec<(f64, f64, f64, Cx)> = Vec::with_capacity(closed.len());
4989 for p in closed {
4990 let (sv, plant) = (s(p.frequency), p.plant);
4991 let c = div([p.re, p.im], plant);
4992 let ls = mul([load, 0.0], sv);
4993 let load_side = sub(div([1.0, 0.0], plant), mul([rotor, 0.0], sv));
4994 let y = div(mul(load_side, ls), sub(ls, load_side));
4995 let raw = c[1].atan2(c[0]);
4996 let phase = rows.last().map_or(raw, |r| raw + tau * ((r.2 - raw) / tau).round());
4997 rows.push((p.frequency.ln(), c[0].hypot(c[1]).ln(), phase, y));
4998 }
4999 let (low, high) = (rows[0].0, rows[rows.len() - 1].0);
5000 const FINE: usize = 3000;
5001 let fine: Vec<(f64, Cx, Cx)> = (0..FINE)
5002 .map(|i| {
5003 let x = low + (high - low) * i as f64 / (FINE - 1) as f64;
5004 let k = rows.partition_point(|r| r.0 <= x).clamp(1, rows.len() - 1);
5005 let (a, b) = (&rows[k - 1], &rows[k]);
5006 let t = if b.0 > a.0 { ((x - a.0) / (b.0 - a.0)).clamp(0.0, 1.0) } else { 0.0 };
5007 let (gain, phase) = ((a.1 + (b.1 - a.1) * t).exp(), a.2 + (b.2 - a.2) * t);
5008 (x.exp(), [gain * phase.cos(), gain * phase.sin()], add(a.3, mul([t, 0.0], sub(b.3, a.3))))
5009 })
5010 .collect();
5011 (0..=300)
5012 .map(|j| {
5013 let kappa = 10f64.powf(-3.0 + 3.0 * j as f64 / 300.0);
5014 let points: Vec<LoopPoint> = fine
5015 .iter()
5016 .map(|&(f, c, y)| {
5017 let (sv, ky) = (s(f), mul([kappa, 0.0], y));
5018 let ls = mul([load, 0.0], sv);
5019 let impedance = add(mul([rotor, 0.0], sv), div(mul(ky, ls), add(ky, ls)));
5020 let plant = div([1.0, 0.0], impedance);
5021 let l = mul(c, plant);
5022 LoopPoint { frequency: f, re: l[0], im: l[1], sensitivity: 1.0 / (1.0 + l[0]).hypot(l[1]), plant }
5023 })
5024 .collect();
5025 loop_margins(&points).gain_margin_db
5026 })
5027 .fold(f64::INFINITY, f64::min)
5028}
5029
5030#[derive(Debug, Clone, Copy, PartialEq)]
5034pub struct Hammering {
5035 pub frequency_hz: f64,
5036 pub torque_nm: f64,
5037 pub pose: usize,
5038}
5039
5040pub const HAMMER_SWEEP_S: f64 = 0.2;
5042pub const HAMMER_WINDOW_S: f64 = 0.1;
5043
5044fn after_a_sweep(sim: &mut Sim, motor: usize, amplitude: f64) -> [(f64, usize, f64); 3] {
5049 let every = (sim.control.drive_params().velocity_cycle / sim.dt).round() as u64;
5050 let (f0, f1) = (10.0, 0.25 / sim.control.drive_params().velocity_cycle);
5051 let (t0, k) = (sim.time(), (f1 / f0).ln());
5052 let mut windows: [Vec<f64>; 3] = Default::default();
5053 loop {
5054 let t = sim.time() - t0;
5055 let window = ((t - HAMMER_SWEEP_S) / HAMMER_WINDOW_S).floor();
5056 if window >= 3.0 {
5057 break;
5058 }
5059 let due = sim.step.is_multiple_of(every);
5060 if due {
5061 let phase = std::f64::consts::TAU * f0 * HAMMER_SWEEP_S / k * ((k * t / HAMMER_SWEEP_S).exp() - 1.0);
5063 sim.control.drives[motor].torque_injection = if t < HAMMER_SWEEP_S { amplitude * phase.sin() } else { 0.0 };
5064 }
5065 sim.step();
5066 if due && window >= 0.0 {
5067 windows[window as usize].push(sim.control.drives[motor].torque_demand);
5068 }
5069 }
5070 windows.map(|seen| {
5071 let mean = seen.iter().sum::<f64>() / seen.len() as f64;
5072 let rms = (seen.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / seen.len() as f64).sqrt();
5073 let crossings = seen.windows(2).filter(|w| (w[0] > mean) != (w[1] > mean)).count();
5074 (rms, crossings, seen.iter().map(|x| (x - mean).abs()).fold(0.0, f64::max))
5075 })
5076}
5077
5078pub fn backlash_hammering(entry: &MachineEntry, cfg: &Config, motor: usize) -> Result<Option<Hammering>, ConfigError> {
5090 let (poses, payloads) = (margin_poses(cfg)?, margin_payloads(cfg)?);
5091 let found = on_all_cores(poses.len(), |k| hammering_at(entry, &at_pose(cfg, &poses[k], payloads[k])?, motor));
5092 let mut worst: Option<Hammering> = None;
5093 for (pose, h) in found.into_iter().enumerate() {
5094 if let Some(h) = h?
5095 && worst.is_none_or(|w| h.torque_nm > w.torque_nm)
5096 {
5097 worst = Some(Hammering { pose, ..h });
5098 }
5099 }
5100 Ok(worst)
5101}
5102
5103fn hammering_at(entry: &MachineEntry, cfg: &Config, motor: usize) -> Result<Option<Hammering>, ConfigError> {
5105 if !cfg.bool("effects.gearbox_backlash").unwrap_or(false) {
5106 return Ok(None);
5107 }
5108 let cfg = lossless(&crate::catalog::resolve(entry, cfg)?)?;
5109 let run = |cfg: &Config| -> Result<_, ConfigError> {
5110 let (mut sim, _) = settled(entry, cfg, 0)?;
5111 let id = sim.machine.motors().get(motor).ok_or_else(|| ConfigError::Invalid("motor".into()))?.id;
5112 let rated = 10.0 * loop_amplitude(entry, cfg, id)?;
5113 let [_, early, late] = after_a_sweep(&mut sim, motor, rated);
5114 Ok((early.0 > 0.1 * rated && late.0 > 0.1 * rated && late.0 > 0.5 * early.0).then_some(late))
5115 };
5116 let Some((_, crossings, peak)) = run(&cfg)? else { return Ok(None) };
5117 let mut without = cfg;
5118 without.set_text("effects.gearbox_backlash = false")?;
5119 if run(&without)?.is_some() {
5120 return Ok(None);
5121 }
5122 Ok(Some(Hammering { frequency_hz: crossings as f64 / (2.0 * HAMMER_WINDOW_S), torque_nm: peak, pose: 0 }))
5123}
5124
5125#[derive(Debug, Clone)]
5127pub struct Comparison {
5128 pub signals: Vec<SignalInfo>,
5129 pub on: Vec<Vec<f64>>,
5132 pub off: Vec<Vec<f64>>,
5133}
5134
5135impl Comparison {
5136 pub fn difference(&self, signal: usize) -> (f64, f64) {
5139 let (mut peak, mut sum, mut n) = (0f64, 0.0, 0usize);
5140 for (a, b) in self.on.iter().zip(&self.off) {
5141 let d = a[signal] - b[signal];
5142 (peak, sum, n) = (peak.max(d.abs()), sum + d * d, n + 1);
5143 }
5144 (peak, if n > 0 { (sum / n as f64).sqrt() } else { 0.0 })
5145 }
5146}
5147
5148pub fn record_cycle(entry: &MachineEntry, cfg: &Config) -> Result<Vec<Vec<f64>>, ConfigError> {
5151 let mut sim = Sim::new(entry, cfg)?;
5152 let refused = |e: CommandError| ConfigError::Invalid(e.key.into());
5153 sim.command(Command::StartCycle).map_err(refused)?;
5154 let every = ((1e-3 / sim.dt).round() as u64).max(1);
5155 let (mut passes, mut last, mut start, mut rows, mut sample) =
5156 (0, sim.control.cycle_passes(), None, Vec::new(), Vec::new());
5157 loop {
5158 sim.step();
5159 let now = sim.control.cycle_passes();
5160 if now != last {
5161 passes += 1;
5162 if passes == 2 {
5163 start = Some(sim.step);
5164 } else if passes == 3 {
5165 break;
5166 }
5167 }
5168 last = now;
5169 if sim.time() > 600.0 {
5170 return Err(refused(CommandError { key: "error-cycle-timeout" }));
5171 }
5172 if let Some(first) = start.filter(|first| (sim.step - first) % every == 0) {
5173 sim.sample(&mut sample);
5174 sample[0] = (sim.step - first) as f64 * sim.dt;
5175 rows.push(sample.clone());
5176 }
5177 if !sim.control.enabled() {
5179 break;
5180 }
5181 }
5182 Ok(rows)
5183}
5184
5185pub fn compare_configs(entry: &MachineEntry, on: &Config, off: &Config) -> Result<Comparison, ConfigError> {
5188 let signals = Sim::new(entry, on)?.signal_infos();
5189 let (with, without) = if std::thread::available_parallelism().is_err() {
5190 (record_cycle(entry, on), record_cycle(entry, off))
5191 } else {
5192 std::thread::scope(|scope| {
5193 let with = scope.spawn(|| record_cycle(entry, on));
5194 let without = record_cycle(entry, off);
5195 (with.join().expect("a run of the cycle panicked"), without)
5196 })
5197 };
5198 Ok(Comparison { signals, on: with?, off: without? })
5199}
5200
5201pub fn compare_effect(entry: &MachineEntry, cfg: &Config, effect: &str) -> Result<Comparison, ConfigError> {
5203 let path = format!("effects.{effect}");
5204 cfg.bool(&path)?;
5205 let (mut on, mut off) = (cfg.clone(), cfg.clone());
5206 on.set_text(&format!("{path} = true"))?;
5207 off.set_text(&format!("{path} = false"))?;
5208 compare_configs(entry, &on, &off)
5209}
5210
5211#[cfg(test)]
5212mod tests {
5213 use super::*;
5214 use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
5215
5216 fn job() -> std::sync::Arc<Progress> {
5217 std::sync::Arc::new(Progress::default())
5218 }
5219
5220 #[test]
5222 fn a_job_counts_its_runs() {
5223 let progress = job();
5224 let out = with_progress(&progress, || on_all_cores(40, |i| i * 2));
5225 assert_eq!(out, Ok((0..40).map(|i| i * 2).collect::<Vec<_>>()));
5226 assert_eq!((progress.total.load(Relaxed), progress.done.load(Relaxed)), (40, 40));
5227 }
5228
5229 #[test]
5231 fn without_a_job_runs_are_as_before() {
5232 assert_eq!(on_all_cores(10, |i| i + 1), (1..=10).collect::<Vec<_>>());
5233 check_cancelled();
5234 let progress = job();
5235 with_progress(&progress, || ()).unwrap();
5236 assert!(current_job().is_none());
5237 assert_eq!(on_all_cores(3, |i| i), vec![0, 1, 2]);
5238 assert_eq!(progress.total.load(Relaxed), 0);
5239 }
5240
5241 #[test]
5244 fn a_cancelled_job_stops_taking_runs() {
5245 let progress = job();
5246 let started = AtomicUsize::new(0);
5247 let out = with_progress(&progress, || {
5248 on_all_cores(1000, |i| {
5249 started.fetch_add(1, Relaxed);
5250 if i == 5 {
5251 progress.cancel.store(true, Relaxed);
5252 }
5253 std::thread::sleep(std::time::Duration::from_millis(1));
5254 })
5255 });
5256 assert_eq!(out, Err(Cancelled));
5257 let started = started.load(Relaxed);
5258 assert!(started < 6 + threads() + 2, "{started} runs started");
5259 assert!(progress.done.load(Relaxed) <= started && progress.done.load(Relaxed) < 1000);
5260 }
5261
5262 #[test]
5264 fn a_nested_batch_is_cancelled_too() {
5265 let progress = job();
5266 let started = AtomicUsize::new(0);
5267 let out = with_progress(&progress, || {
5268 on_all_cores(4, |_| {
5269 on_all_cores(500, |i| {
5270 started.fetch_add(1, Relaxed);
5271 if i == 3 {
5272 progress.cancel.store(true, Relaxed);
5273 }
5274 std::thread::sleep(std::time::Duration::from_millis(1));
5275 })
5276 })
5277 });
5278 assert_eq!(out, Err(Cancelled));
5279 assert!(started.load(Relaxed) < 4 * 500);
5280 }
5281
5282 #[test]
5284 fn a_job_cancelled_before_its_start_runs_nothing() {
5285 let progress = job();
5286 progress.cancel.store(true, Relaxed);
5287 let started = AtomicUsize::new(0);
5288 let out = with_progress(&progress, || {
5289 on_all_cores(50, |_| {
5290 started.fetch_add(1, Relaxed);
5291 })
5292 });
5293 assert_eq!((out, started.load(Relaxed)), (Err(Cancelled), 0));
5294 }
5295
5296 #[test]
5299 fn a_real_panic_stays_a_panic() {
5300 let progress = job();
5301 let in_job = std::panic::catch_unwind(|| with_progress(&progress, || -> u8 { panic!("model failed") }));
5302 assert!(in_job.is_err_and(|p| !p.is::<Cancelled>()));
5303 let in_run = std::panic::catch_unwind(|| {
5304 with_progress(&progress, || {
5305 on_all_cores(8, |i| {
5306 if i == 2 {
5307 panic!("run failed")
5308 }
5309 })
5310 })
5311 });
5312 assert!(in_run.is_err_and(|p| !p.is::<Cancelled>()));
5313 assert!(current_job().is_none());
5314 }
5315
5316 #[test]
5318 fn check_cancelled_raises_only_in_a_cancelled_job() {
5319 check_cancelled();
5320 let progress = job();
5321 assert_eq!(with_progress(&progress, check_cancelled), Ok(()));
5322 progress.cancel.store(true, Relaxed);
5323 assert_eq!(with_progress(&progress, check_cancelled), Err(Cancelled));
5324 check_cancelled();
5325 }
5326
5327 #[test]
5329 fn sequential_steps_are_counted_in_the_job() {
5330 let progress = job();
5331 with_progress(&progress, || {
5332 plan_steps(3);
5333 (0..3).for_each(|_| step_done());
5334 })
5335 .unwrap();
5336 assert_eq!((progress.total.load(Relaxed), progress.done.load(Relaxed)), (3, 3));
5337 }
5338
5339 #[test]
5341 fn a_verdict_that_is_not_finite_is_found() {
5342 let row = |value: f64, limit: f64| Verdict { check: "motor-thermal", motor: None, value, limit, ok: false };
5343 assert!(!any_not_finite(&[row(435.1, 1.0), row(0.0, 2.0)]));
5344 assert!(any_not_finite(&[row(1.0, 2.0), row(f64::INFINITY, 2.0)]));
5345 assert!(any_not_finite(&[row(f64::NAN, 2.0)]));
5346 assert!(any_not_finite(&[row(1.0, f64::NAN)]));
5347 }
5348
5349 #[test]
5353 fn the_warm_start_finds_the_period_of_a_cycle() {
5354 let rises = |r: &[f64]| r.iter().map(|&x| vec![x, 50.0]).collect::<Vec<_>>();
5355 assert_eq!(period_of(&rises(&[90.0, 102.3, 92.2, 101.9, 92.4])), Some(2));
5356 assert_eq!(period_of(&rises(&[60.0, 100.0, 90.0, 80.0, 100.0])), Some(3));
5357 assert_eq!(period_of(&rises(&[60.0, 105.0, 100.0, 97.5, 96.25])), None);
5358 assert_eq!(period_of(&rises(&[60.0, 110.0, 100.0, 92.5, 96.25])), None);
5359 assert_eq!(period_of(&rises(&[100.0, 90.0, 80.0, 100.0])), None);
5361 }
5362
5363 #[test]
5366 fn the_fastest_passing_step_is_found_where_pass_and_fail_do_not_follow_the_steps() {
5367 let mut judged = Vec::new();
5368 let passes = [true, true, false, true, false, false];
5369 let found = fastest_passing(5, |k| -> Result<_, ()> {
5370 judged.push(k);
5371 Ok(passes[k].then_some(k * 10))
5372 });
5373 assert_eq!((found, judged), (Ok(Some((3, 30))), vec![5, 4, 3]));
5374 let mut count = 0;
5375 assert_eq!(fastest_passing(5, |_| -> Result<Option<()>, ()> { Ok((count += 1, None).1) }), Ok(None));
5376 assert_eq!(count, 5);
5377 }
5378
5379 #[test]
5385 fn the_supply_energy_has_the_line_modules_loss() {
5386 let cfg = Config::parse(
5387 "format_version = 1
5388[effects]
5389dc_link = true
5390regenerative_supply = true
5391[ratings]
5392line_module_efficiency = 0.9
5393",
5394 )
5395 .unwrap();
5396 let motor = MotorLoad {
5397 energy_in: 100.0,
5398 energy_regenerated: 40.0,
5399 mains_energy: 36.0,
5400 line_module_energy: 142.0,
5401 discharge_energy: 2.0,
5402 ..MotorLoad::default()
5403 };
5404 let load = CycleLoad { motors: vec![motor], ..CycleLoad::default() };
5405 assert!((supply_energy(&cfg, &load) - (102.0 / 0.9 - 36.0)).abs() < 1e-9, "{}", supply_energy(&cfg, &load));
5406 let off = Config::parse("format_version = 1\n[effects]\ndc_link = false\n").unwrap();
5407 assert!((supply_energy(&off, &load) - 60.0).abs() < 1e-12);
5408 }
5409
5410 #[test]
5413 fn tracking_is_judged_where_a_limit_is_set() {
5414 let load = CycleLoad { tracking_error_peak: 2e-4, tracking_angle_error_peak: 3e-3, ..CycleLoad::default() };
5415 let base = "format_version = 1\n[effects]\ndc_link = false\npart_heating = false\nthermal_feedback = false\n";
5416 let checks = |text: &str| -> Vec<(&'static str, bool)> {
5417 let cfg = Config::parse(text).unwrap();
5418 verdicts(&cfg, &load)
5419 .unwrap()
5420 .into_iter()
5421 .filter(|v| v.check.starts_with("tracking"))
5422 .map(|v| (v.check, v.ok))
5423 .collect()
5424 };
5425 assert!(checks(base).is_empty());
5426 let set = format!("{base}[ratings]\ntracking_tolerance_m = 1e-4\ntracking_tolerance_rad = 5e-3\n");
5427 assert_eq!(checks(&set), [("tracking", false), ("tracking-angle", true)]);
5428 }
5429
5430 #[test]
5440 fn refinement_finds_a_sharp_resonance_the_coarse_sweep_misses() {
5441 let (j1, j2, k, c) = (1e-4, 3e-4, 300.0, 0.003);
5442 let plant = |f: f64| {
5443 let w = std::f64::consts::TAU * f;
5444 let (nr, ni) = (k - j2 * w * w, c * w);
5445 let (a, b) = (k * (j1 + j2) - j1 * j2 * w * w, c * (j1 + j2) * w);
5447 let (dr, di) = (-w * b, w * a);
5448 let d2 = dr * dr + di * di;
5449 (f, [(nr * dr + ni * di) / d2, (ni * dr - nr * di) / d2])
5450 };
5451 let magnitude = |p: &(f64, [f64; 2])| p.1[0].hypot(p.1[1]);
5452 let peak =
5453 |points: &[(f64, [f64; 2])]| *points.iter().max_by(|a, b| magnitude(a).total_cmp(&magnitude(b))).unwrap();
5454 let close = |value: f64, expected: f64, share: f64, what: &str| {
5455 assert!((value / expected - 1.0).abs() < share, "{what}: {value} against {expected}")
5456 };
5457 close(magnitude(&plant(2000.0 / std::f64::consts::TAU)), 187.50, 1e-3, "|P| at the resonance");
5458 let mut points: Vec<_> = log_spaced(10.0, 2000.0, 60).into_iter().map(plant).collect();
5459 assert!(magnitude(&peak(&points)) < 0.25 * 187.5, "the coarse sweep sees the peak: {:?}", peak(&points));
5460 for _ in 0..REFINE_ROUNDS {
5461 let more = refinement(&points);
5462 points.extend(more.into_iter().map(plant));
5463 points.sort_by(|a, b| a.0.total_cmp(&b.0));
5464 }
5465 let top = peak(&points);
5466 close(top.0, 318.310, 2e-3, "resonance");
5467 close(magnitude(&top), 187.50, 0.03, "peak");
5468 let bottom = *points.iter().min_by(|a, b| magnitude(a).total_cmp(&magnitude(b))).unwrap();
5469 close(bottom.0, 159.155, 2e-3, "anti-resonance");
5470 assert!(points.len() < 60 + 80, "{} points", points.len());
5472 assert!(
5473 points.iter().filter(|p| p.0 < 100.0 || p.0 > 700.0).count()
5474 == log_spaced(10.0, 2000.0, 60).iter().filter(|f| **f < 100.0 || **f > 700.0).count()
5475 );
5476 }
5477
5478 #[test]
5484 fn a_lift_with_rounded_corners_keeps_above_the_lowest_height() {
5485 let axis = |id| sim_core::AxisInfo {
5486 id,
5487 key: "",
5488 unit: "m",
5489 min: -1.0,
5490 max: 1.0,
5491 max_vel: 1.0,
5492 max_acc: 10.0,
5493 max_jerk: 200.0,
5494 };
5495 let axes = [axis("x"), axis("z")];
5496 let lift = Lift {
5497 segments: [0, 1, 2],
5498 from: vec![0.0, 0.0],
5499 to: vec![0.4, 0.0],
5500 height: 0.3,
5501 up: 1.0,
5502 lowest: 0.25,
5503 needed: 0.25,
5504 over: None,
5505 profile: None,
5506 payload: true,
5507 };
5508 let path = |corner: f64| lift_path(&axes, 1e-3, 0.0, &lift, (0.3, Some(corner)), &[]);
5509 let lowest = |points: &[(f64, Vec<f64>)]| {
5510 points.iter().filter(|(_, p)| p[0] > 1e-9 && p[0] < 0.4 - 1e-9).map(|(_, p)| p[1]).fold(1.0, f64::min)
5511 };
5512 let rounded = path(3.0 * 0.05 / 16.0).expect("keeps to lowest");
5513 assert!((lowest(&rounded) - 0.25).abs() < 1e-3, "{}", lowest(&rounded));
5514 assert!(path(1.5 * 3.0 * 0.05 / 16.0).is_none());
5515 }
5516
5517 #[test]
5525 fn the_lives_and_the_tooth_load_are_the_hand_calculated_ones() {
5526 let cfg = Config::parse(
5527 "format_version = 1\n[gearbox]\nratio = 5.0\n[geometry]\npulley_radius_m = 0.02\n[ratings]\npulley_bearing_load_rating_n = 8469.0\ngearbox_rated_torque_nm = 40.0\n\
5528 gearbox_reference_speed_rpm = 175.0\nguide_dynamic_load_rating_n = 5000.0\nbelt_tooth_load_rpm = [0.0, 100.0, 1000.0]\n\
5529 belt_tooth_load_n_cm = [35.0, 34.0, 26.0]\nbelt_width_mm = 25.0\nbelt_service_factor = 1.4\nbelt_teeth_in_mesh = 14.0\nbearing_reliability_percent = 90.0\n",
5530 )
5531 .unwrap();
5532 let mut bands = vec![0.0; 200];
5533 bands[9] = 2.0;
5534 let m = MotorLoad {
5535 mean_speed: 500.0 * std::f64::consts::PI / 30.0,
5536 radial_load_equivalent: Some(600.0),
5537 gearbox_life_torque: Some(20.0),
5538 gearbox_torque: Some((2.0, 1.0)),
5539 gearbox_torque_by_speed: bands.clone(),
5540 ..MotorLoad::default()
5541 };
5542 let close = |a: f64, b: f64, what: &str| assert!((a / b - 1.0).abs() < 1e-5, "{what}: {a} against {b} by hand");
5543 close(rating_life_h(8469.0, 600.0, 100.0), 468696.16, "rating life");
5544 close(pulley_bearing_life_h(&cfg, &m).unwrap(), 468696.16, "pulley bearing");
5545 close(gearbox_life_h(&cfg, &m).unwrap(), 352777.89, "gearbox");
5546 close(belt_tooth_utilisation(&cfg, &m).unwrap().unwrap(), 0.137073, "tooth load");
5547 bands[199] = 1.6;
5548 close(
5549 belt_tooth_utilisation(&cfg, &MotorLoad { gearbox_torque_by_speed: bands, ..m.clone() }).unwrap().unwrap(),
5550 112.0 / 780.0,
5551 "tooth load beyond the table",
5552 );
5553 let load = CycleLoad {
5554 duration: 1.0,
5555 belt_tension: None,
5556 belt_slack_time: None,
5557 belt_tooth_jumps: None,
5558 belt_span_detuning: None,
5559 radial_load_peak: None,
5560 condition_peak: None,
5561 guide_load: Some((1500.0, 1000.0)),
5562 guide_speed: Some(0.25),
5563 guides: Vec::new(),
5564 path_error_peak: 0.0,
5565 path_error_rms: 0.0,
5566 tracking_error_peak: 0.0,
5567 dwell_error_peak: 0.0,
5568 path_angle_error_peak: 0.0,
5569 path_angle_error_rms: 0.0,
5570 tracking_angle_error_peak: 0.0,
5571 dwell_angle_error_peak: 0.0,
5572 path_error_series: Vec::new(),
5573 tripped: false,
5574 motors: vec![m.clone()],
5575 budget: None,
5576 part_rises: Vec::new(),
5577 checks: Vec::new(),
5578 clearance: None,
5579 contact: None,
5580 own_clearance: None,
5581 braking_power_peak: 0.0,
5582 warm_start: None,
5583 conveyor: None,
5584 held_accelerations: Vec::new(),
5585 };
5586 close(guide_life_km(&cfg, &load).unwrap(), 6250.0, "guide km");
5587 close(guide_life_h(&cfg, &load).unwrap(), 6944.444, "guide h");
5588 let guide = |equivalent: f64, speed: f64| GuideLoad { peak: equivalent, equivalent, speed: Some(speed) };
5591 let two = CycleLoad { guides: vec![guide(2000.0, 0.1), guide(1000.0, 3.0)], ..load.clone() };
5592 close(guide_life_km(&cfg, &two).unwrap(), 781.25, "lowest guide km");
5593 close(guide_life_h(&cfg, &two).unwrap(), 578.704, "lowest guide h");
5594 assert_eq!(belt_tooth_utilisation(&cfg, &MotorLoad { gearbox_torque: None, ..m.clone() }).unwrap(), None);
5596 assert_eq!(pulley_bearing_life_h(&cfg, &MotorLoad { radial_load_equivalent: None, ..m.clone() }), None);
5597 assert_eq!(
5598 gearbox_life_h(
5599 &Config::parse("format_version = 1\n[ratings]\ngearbox_rated_torque_nm = 40.0\n").unwrap(),
5600 &m
5601 ),
5602 None
5603 );
5604 let mut reliable = cfg.clone();
5607 for (percent, a1) in [(95.0, 0.637912), (99.0, 0.248332), (99.95, 0.076832)] {
5608 reliable.set_text(&format!("ratings.bearing_reliability_percent = {percent:?}")).unwrap();
5609 close(reliability_factor(&reliable).unwrap(), a1, "a1");
5610 close(pulley_bearing_life_h(&reliable, &m).unwrap(), a1 * 468696.16, "pulley bearing with a1");
5611 close(gearbox_life_h(&reliable, &m).unwrap(), a1 * 352777.89, "gearbox with a1");
5612 close(guide_life_h(&reliable, &load).unwrap(), a1 * 6944.444, "guide with a1");
5613 }
5614 assert_eq!(reliability_factor(&cfg), Some(1.0));
5615 assert_eq!(reliability_factor(&Config::parse("format_version = 1\n").unwrap()), Some(1.0));
5616 reliable.set_text("ratings.bearing_reliability_percent = 89.0").unwrap();
5618 assert_eq!(pulley_bearing_life_h(&reliable, &m), None);
5619 let mut bad = cfg.clone();
5621 bad.set_text("ratings.belt_tooth_load_rpm = [0.0, 1000.0, 100.0]").unwrap();
5622 assert!(belt_tooth_utilisation(&bad, &m).is_err());
5623 let v = at_least("guide-life", None, 6944.444, 20000.0);
5625 assert!(!v.ok && (utilisation(&v) - 2.88).abs() < 0.001 && (badness(&v) - 13055.556).abs() < 0.001);
5626 }
5627
5628 #[test]
5632 fn an_at_least_check_at_or_below_zero_is_infinitely_far_over() {
5633 let pushed = Verdict { check: "belt-least-tension", motor: None, value: -12.0, limit: 0.5, ok: false };
5634 assert_eq!(utilisation(&pushed), f64::INFINITY);
5635 assert_eq!(utilisation(&Verdict { value: 0.0, ..pushed.clone() }), f64::INFINITY);
5636 assert_eq!(utilisation(&Verdict { value: 2.0, ok: true, ..pushed }), 0.25);
5637 }
5638
5639 #[test]
5648 fn a_iso_is_the_hand_calculated_one_of_iso_281() {
5649 let close = |a: f64, b: f64, what: &str| assert!((a / b - 1.0).abs() < 1e-5, "{what}: {a} against {b} by hand");
5650 close(reference_viscosity(100.0, 36.0), 164.082122, "ν1 below 1000 r/min");
5651 close(reference_viscosity(1000.0, 36.0), 23.717082, "ν1 from 1000 r/min");
5652 for (kappa, a_iso) in [
5653 (1.0, 3.276474),
5654 (0.2, 0.198152),
5655 (0.5, 0.610291),
5656 (2.0, 6.035768),
5657 (4.0, 11.060568),
5658 (8.0, 11.060568),
5659 (0.05, 0.100176),
5660 ] {
5661 close(life_modification_factor(kappa, 0.125), a_iso, &format!("a_ISO at κ {kappa}"));
5662 }
5663 assert!(
5665 (life_modification_factor(0.4 - 1e-9, 0.125) / life_modification_factor(0.4, 0.125) - 1.0).abs() < 1e-3
5666 );
5667 assert!(
5668 (life_modification_factor(1.0 - 1e-9, 0.125) / life_modification_factor(1.0, 0.125) - 1.0).abs() < 1e-5
5669 );
5670 assert_eq!(life_modification_factor(4.0, 2.0), 50.0);
5671 let text = "format_version = 1\n[gearbox]\nratio = 5.0\n[ratings]\npulley_bearing_load_rating_n = 8469.0\nbearing_lubricant_viscosity_mm2_s = 120.0\n\
5672 bearing_contamination_factor = 0.5\npulley_bearing_fatigue_limit_n = 150.0\npulley_bearing_mean_diameter_mm = 36.0\n";
5673 let cfg = Config::parse(text).unwrap();
5674 let m = MotorLoad {
5675 mean_speed: 500.0 * std::f64::consts::PI / 30.0,
5676 radial_load_equivalent: Some(600.0),
5677 ..MotorLoad::default()
5678 };
5679 close(pulley_bearing_life_h(&cfg, &m).unwrap(), 728945.29, "pulley bearing with a_ISO");
5680 let partial = Config::parse(&text.replace("pulley_bearing_mean_diameter_mm = 36.0\n", "")).unwrap();
5682 assert!(
5683 matches!(lubrication(&partial), Err(ConfigError::Missing(key)) if key == "ratings.pulley_bearing_mean_diameter_mm")
5684 );
5685 assert_eq!(pulley_bearing_life_h(&partial, &m), None);
5686 let mut dirty = cfg.clone();
5687 dirty.set_text("ratings.bearing_contamination_factor = 1.5").unwrap();
5688 assert!(
5689 matches!(lubrication(&dirty), Err(ConfigError::Invalid(key)) if key == "ratings.bearing_contamination_factor")
5690 );
5691 let bare = Config::parse(
5692 "format_version = 1\n[gearbox]\nratio = 5.0\n[ratings]\npulley_bearing_load_rating_n = 8469.0\n",
5693 )
5694 .unwrap();
5695 close(pulley_bearing_life_h(&bare, &m).unwrap(), 468696.16, "pulley bearing without a_ISO");
5696 }
5697
5698 #[test]
5707 fn the_gearing_life_is_the_hand_calculated_damage_sum() {
5708 let close = |a: f64, b: f64, what: &str| assert!((a / b - 1.0).abs() < 1e-6, "{what}: {a} against {b} by hand");
5709 close(
5710 gearing_life_h([(30.0, 5000.0), (48.0, 1000.0), (60.0, 100.0)], 40.0, 64.0, 6.0),
5711 122.014741,
5712 "two levels",
5713 );
5714 assert_eq!(gearing_life_h([(30.0, 5000.0), (40.0, 5000.0)], 40.0, 64.0, 6.0), f64::INFINITY);
5715 close(gearing_life_h([(64.0, 30000.0)], 40.0, 64.0, 6.0), 1.0, "at M2max");
5717 let text = "format_version = 1\n[gearbox]\nratio = 5.0\n[ratings]\ngearbox_rated_torque_nm = 40.0\ngearbox_max_torque_nm = 64.0\n\
5718 gearbox_gearing_wohler_exponent = 6.0\n";
5719 let cfg = Config::parse(text).unwrap();
5720 let rad_s = |rev_h: f64| rev_h * std::f64::consts::TAU * 5.0 / 3600.0;
5721 let mut spectrum = vec![0.0; 700];
5722 (spectrum[573], spectrum[620], spectrum[642]) = (rad_s(5000.0), rad_s(1000.0), rad_s(100.0));
5723 let m =
5724 MotorLoad { gearbox_torque: Some((60.0, 40.0)), gearbox_torque_spectrum: spectrum, ..MotorLoad::default() };
5725 close(torque_band_floor(621), 48.258422, "band 620's upper torque");
5726 close(gearbox_gearing_life_h(&cfg, &m).unwrap(), 118.971035, "through the spectrum");
5727 let below = MotorLoad { gearbox_torque_spectrum: m.gearbox_torque_spectrum[..600].to_vec(), ..m.clone() };
5729 assert_eq!(gearbox_gearing_life_h(&cfg, &below), None);
5730 assert_eq!(gearbox_gearing_life_h(&cfg, &MotorLoad { gearbox_torque: None, ..m.clone() }), None);
5732 let without = Config::parse(&text.replace("gearbox_gearing_wohler_exponent = 6.0\n", "")).unwrap();
5733 assert_eq!(gearbox_gearing_life_h(&without, &m), None);
5734 }
5735
5736 #[test]
5740 fn the_motor_bearing_life_is_the_hand_calculated_one() {
5741 let cfg = Config::parse(
5742 "format_version = 1\n[gearbox]\nratio = 1.0\n[ratings]\nmotor_bearing_load_rating_n = 13103.7\n",
5743 )
5744 .unwrap();
5745 let m = MotorLoad {
5746 mean_speed: 1000.0 * std::f64::consts::PI / 30.0,
5747 radial_load_equivalent: Some(600.0),
5748 ..MotorLoad::default()
5749 };
5750 let life = motor_bearing_life_h(&cfg, &m).unwrap();
5751 assert!((life / 173611.11 - 1.0).abs() < 1e-5, "{life} against 173611 h by hand");
5752 let mut geared = cfg.clone();
5753 geared.set_text("gearbox.ratio = 5.0").unwrap();
5754 assert_eq!(motor_bearing_life_h(&geared, &m), None);
5755 assert_eq!(motor_bearing_life_h(&cfg, &MotorLoad { radial_load_equivalent: None, ..m }), None);
5756 }
5757
5758 #[test]
5761 fn each_motor_gets_its_own_gearbox_ratio() {
5762 let cfg = Config::parse(
5763 "format_version = 1\n[gearbox]\nratio = 5.0\n[gearbox.b]\nratio = 10.0\n[ratings]\npulley_bearing_load_rating_n = 8469.0\nbearing_reliability_percent = 90.0\n",
5764 )
5765 .unwrap();
5766 let motor = |id: &str| MotorLoad {
5767 id: id.into(),
5768 mean_speed: 500.0 * std::f64::consts::PI / 30.0,
5769 radial_load_equivalent: Some(600.0),
5770 ..MotorLoad::default()
5771 };
5772 assert!((output_rpm(&cfg, &motor("a")) - 100.0).abs() < 1e-9);
5773 assert!((output_rpm(&cfg, &motor("b")) - 50.0).abs() < 1e-9);
5774 let (a, b) =
5775 (pulley_bearing_life_h(&cfg, &motor("a")).unwrap(), pulley_bearing_life_h(&cfg, &motor("b")).unwrap());
5776 assert!((a / 468696.16 - 1.0).abs() < 1e-5 && (b / a - 2.0).abs() < 1e-9, "{a} and {b}");
5777 }
5778
5779 #[test]
5786 fn a_guide_load_is_weighted_with_distance_and_the_resistor_takes_what_the_link_cannot() {
5787 assert!((equivalent_load(100f64.powi(3) + 200f64.powi(3) * 3.0, 4.0) - 184.2).abs() < 0.01);
5788 assert_eq!(equivalent_load(0.0, 0.0), 0.0);
5789 let close = |(a, b): (f64, f64), (c, d): (f64, f64)| assert!((a - c).abs() < 1e-12 && (b - d).abs() < 1e-12);
5790 close(resistor_excess(&[5.0, -10.0, 1.5, -10.0, 3.0, -10.0], 2.0), (4.0, 5.0));
5791 close(resistor_excess(&[5.0, -1.0, 1.5, -1.0, 3.0, -10.0], 2.0), (5.5, 5.0));
5792 close(resistor_excess(&[1.5, -3.0, 1.0], 2.0), (0.5, 2.5));
5793 assert_eq!(resistor_excess(&[], 2.0), (0.0, 0.0));
5794 }
5795
5796 #[test]
5801 fn the_dc_link_account_matches_two_passes_over_the_list_and_stays_bounded() {
5802 let two_passes = |events: &[f64], room: f64| {
5803 let (mut fill, mut excess, mut most) = (0.0f64, 0.0, 0.0f64);
5804 for (i, &e) in events.iter().chain(events).enumerate() {
5805 fill = (fill + e).max(0.0);
5806 if i >= events.len() {
5807 most = most.max(fill);
5808 excess += (fill - room).max(0.0);
5809 }
5810 fill = fill.min(room);
5811 }
5812 (excess, most)
5813 };
5814 let mut events = vec![0.3, -0.05, 2.5, -0.2];
5815 events.extend((0..100_000).map(|i| if i % 2 == 0 { 1e-4 } else { -1.2e-4 }));
5816 events.extend([1.7, -0.4, 3.1, -5.0]);
5817 for room in [0.5, 2.0, 10.0] {
5818 let mut account = LinkAccount::new(room);
5819 events.iter().for_each(|&e| account.push(e));
5820 let ((a, b), (c, d)) = (account.finish(), two_passes(&events, room));
5821 assert!((a - c).abs() < 1e-9 && (b - d).abs() < 1e-12, "room {room}: {a} {b} against {c} {d}");
5822 assert!(room > 2.0 || account.prefix.len() == 3, "room {room}: {} stretches kept", account.prefix.len());
5824 }
5825 }
5826
5827 #[test]
5834 fn a_dc_link_that_never_empties_nor_fills_keeps_a_bounded_account_at_both_ends() {
5835 let two_passes = |events: &[f64], room: f64| {
5836 let mut pass = [0.0, 0.0, 0.0];
5837 events.iter().for_each(|&e| link_step(&mut pass, e, room));
5838 pass[1..].fill(0.0);
5839 events.iter().for_each(|&e| link_step(&mut pass, e, room));
5840 (pass[1], pass[2])
5841 };
5842 let room = 10.0;
5843 let noise = (0..400_000).map(|i| if i % 2 == 0 { 1e-4 } else { -1e-4 });
5844 let cases = [
5845 (0.3, vec![], false, (0.0, 0.6001)),
5846 (9.99, vec![], false, (9.9801, 19.98)),
5847 (0.3, vec![12.0, -20.0], true, (2.3, 12.3)),
5848 ];
5849 for (start, end, meets, by_hand) in cases {
5850 let events: Vec<f64> = std::iter::once(start).chain(noise.clone()).chain(end).collect();
5851 let mut account = LinkAccount::new(room);
5852 events.iter().for_each(|&e| account.push(e));
5853 assert!(account.prefix.is_empty() && account.grid.len() == LINK_GRID && account.met == meets);
5854 let ((a, b), (c, d)) = (account.finish(), two_passes(&events, room));
5855 assert!((c - by_hand.0).abs() < 1e-9 && (d - by_hand.1).abs() < 1e-9, "{start}: {c} {d}");
5856 let tolerance = if meets { 1e-9 } else { room / (2.0 * (LINK_GRID - 1) as f64) };
5857 assert!((a - c).abs() <= tolerance && (b - d).abs() <= tolerance, "{start}: {a} {b} against {c} {d}");
5858 }
5859 }
5860
5861 #[test]
5865 fn a_loop_without_a_gain_crossover_is_judged_on_its_gain_margin() {
5866 let m = |phase: f64, gain: f64, valid: bool| LoopMargins {
5867 crossover_hz: f64::NAN,
5868 phase_margin_deg: phase,
5869 gain_margin_db: gain,
5870 valid,
5871 peak_sensitivity: 1.0,
5872 peak_frequency_hz: 10.0,
5873 hammering: None,
5874 play_margin_db: f64::NAN,
5875 };
5876 assert!(m(f64::NAN, 20.0, true).stable());
5877 let hammering = Some(Hammering { frequency_hz: 645.0, torque_nm: 0.7, pose: 0 });
5878 assert!(!LoopMargins { hammering, ..m(40.0, 6.0, true) }.stable());
5879 assert!(!m(f64::NAN, -1.0, true).stable());
5880 assert!(!m(f64::NAN, f64::NAN, true).stable());
5881 assert!(!m(-5.0, 20.0, true).stable() && m(40.0, 6.0, true).stable() && !m(40.0, 6.0, false).stable());
5882 }
5883
5884 #[test]
5888 fn margins_of_an_integrator_with_dead_time_are_the_hand_calculated_ones() {
5889 let (fc, tau) = (100.0, 1e-3);
5890 let points: Vec<LoopPoint> = log_spaced(10.0, 1000.0, 400)
5891 .into_iter()
5892 .map(|f| {
5893 let w = std::f64::consts::TAU * f;
5894 let (gain, phase) = (fc / f, -std::f64::consts::FRAC_PI_2 - w * tau);
5895 let (re, im) = (gain * phase.cos(), gain * phase.sin());
5896 LoopPoint { frequency: f, re, im, sensitivity: 1.0 / (1.0 + re).hypot(im), plant: [0.0; 2] }
5897 })
5898 .collect();
5899 let m = loop_margins(&points);
5900 assert!((m.crossover_hz - fc).abs() < 0.1, "crossover {} Hz", m.crossover_hz);
5901 assert!((m.phase_margin_deg - 54.0).abs() < 0.1, "phase margin {}", m.phase_margin_deg);
5902 assert!((m.gain_margin_db - 20.0 * 2.5f64.log10()).abs() < 0.01, "gain margin {}", m.gain_margin_db);
5903 let m =
5906 loop_margins(&points[..10].iter().map(|p| LoopPoint { re: 2.0 + p.re.abs(), ..*p }).collect::<Vec<_>>());
5907 assert!(m.phase_margin_deg.is_nan() && m.gain_margin_db.is_infinite() && m.crossover_hz.is_nan() && m.stable());
5908 }
5909
5910 #[test]
5915 fn margins_are_signed_and_say_an_unstable_loop_is_unstable() {
5916 let response = |fc: f64, tau: f64| -> Vec<LoopPoint> {
5917 log_spaced(10.0, 2000.0, 1000)
5918 .into_iter()
5919 .map(|f| {
5920 let (gain, phase) = (fc / f, -std::f64::consts::FRAC_PI_2 - std::f64::consts::TAU * f * tau);
5921 let (re, im) = (gain * phase.cos(), gain * phase.sin());
5922 LoopPoint { frequency: f, re, im, sensitivity: 1.0 / (1.0 + re).hypot(im), plant: [0.0; 2] }
5923 })
5924 .collect()
5925 };
5926 for (fc, tau, phase, gain) in [
5927 (100.0, 0.5e-3, 72.0, 13.979),
5928 (200.0, 0.5e-3, 54.0, 7.959),
5929 (300.0, 1e-3, -18.0, -1.584),
5930 (400.0, 1e-3, -54.0, -4.082),
5931 ] {
5932 let m = loop_margins(&response(fc, tau));
5933 assert!(
5934 (m.phase_margin_deg - phase).abs() < 0.1 && (m.gain_margin_db - gain).abs() < 0.01 && m.valid,
5935 "{fc} Hz, {tau} s: {m:?}"
5936 );
5937 }
5938 let mut points = response(100.0, 0.5e-3);
5939 points[500].re = f64::NAN;
5940 let m = loop_margins(&points);
5941 assert!(!m.valid && !m.stable() && m.phase_margin_deg.is_nan() && m.gain_margin_db.is_nan(), "{m:?}");
5942 }
5943
5944 fn loop_points(frequencies: Vec<f64>, l: impl Fn(f64) -> (f64, f64)) -> Vec<LoopPoint> {
5946 frequencies
5947 .into_iter()
5948 .map(|f| {
5949 let (gain, phase) = l(std::f64::consts::TAU * f);
5950 let (re, im) = (gain * phase.cos(), gain * phase.sin());
5951 LoopPoint { frequency: f, re, im, sensitivity: 1.0 / (1.0 + re).hypot(im), plant: [0.0; 2] }
5952 })
5953 .collect()
5954 }
5955
5956 #[test]
5962 fn a_conditionally_stable_loop_is_stable() {
5963 let (a, b, c) = (std::f64::consts::TAU * 300.0, std::f64::consts::TAU * 30.0, std::f64::consts::TAU * 3000.0);
5964 for (k, phase, hz) in [(3e5, 30.7, 589.0), (6.1e5, 41.6, 1002.0), (1.2e6, 42.4, 1710.0)] {
5965 let m = loop_margins(&loop_points(log_spaced(10.0, 2000.0, 60), |w| {
5966 let gain = k * (1.0 + (w / a).powi(2)) / (w * (1.0 + (w / b).powi(2)) * (1.0 + (w / c).powi(2)).sqrt());
5967 (gain, 2.0 * (w / a).atan() - std::f64::consts::FRAC_PI_2 - 2.0 * (w / b).atan() - (w / c).atan())
5968 }));
5969 assert!(
5970 m.stable()
5971 && m.gain_margin_db.is_infinite()
5972 && (m.phase_margin_deg - phase).abs() < 0.3
5973 && (m.crossover_hz / hz - 1.0).abs() < 0.01,
5974 "K {k}: {m:?}"
5975 );
5976 }
5977 }
5978
5979 #[test]
5983 fn a_lead_with_positive_phase_at_the_first_point_keeps_its_phase_margin() {
5984 let w = |n: f64| std::f64::consts::TAU * n;
5985 let m = loop_margins(&loop_points(log_spaced(1.0, 10000.0, 200), |x| {
5986 let lag = |n: f64| (1.0 + (x / w(n)).powi(2)).sqrt();
5987 (
5988 3.0 * lag(5.0) / (lag(50.0) * lag(200.0) * lag(400.0)),
5989 (x / w(5.0)).atan() - (x / w(50.0)).atan() - (x / w(200.0)).atan() - (x / w(400.0)).atan(),
5990 )
5991 }));
5992 assert!(
5993 m.stable()
5994 && m.gain_margin_db.is_infinite()
5995 && (m.phase_margin_deg - 24.0).abs() < 0.2
5996 && (m.crossover_hz / 1516.0 - 1.0).abs() < 0.01,
5997 "{m:?}"
5998 );
5999 }
6000
6001 #[test]
6007 fn a_crossover_with_phase_lead_before_the_one_that_counts_does_not_turn_the_phase() {
6008 let m = loop_margins(&loop_points(log_spaced(10.0, 2000.0, 60), |w| {
6009 let pair = |wn: f64| {
6010 let (re, im) = (1.0 - (w / wn).powi(2), 0.1 * w / wn);
6011 (re.hypot(im), im.atan2(re))
6012 };
6013 let ((zg, zp), (pg, pp)) = (pair(std::f64::consts::TAU * 14.0), pair(std::f64::consts::TAU * 40.0));
6014 (std::f64::consts::TAU * 9.7 / w * zg / pg, -std::f64::consts::FRAC_PI_2 + zp - pp - w * 1e-3)
6015 }));
6016 assert!((m.phase_margin_deg - 58.1).abs() < 0.5 && (m.crossover_hz / 94.3 - 1.0).abs() < 0.02, "{m:?}");
6017 }
6018
6019 fn points_of(rows: &[(f64, f64, f64)]) -> Vec<LoopPoint> {
6021 rows.iter()
6022 .map(|&(f, gain, deg)| {
6023 let (re, im) = (gain * deg.to_radians().cos(), gain * deg.to_radians().sin());
6024 LoopPoint { frequency: f, re, im, sensitivity: 1.0 / (1.0 + re).hypot(im), plant: [0.0; 2] }
6025 })
6026 .collect()
6027 }
6028
6029 #[test]
6036 fn a_resonance_beyond_the_phase_crossing_inside_the_unit_circle_keeps_the_loop_stable() {
6037 let rows: Vec<(f64, f64, f64)> = log_spaced(10.0, 2000.0, 400)
6038 .into_iter()
6039 .map(|f| {
6040 let lift = 1.0 + 24.0 * (-((f - 1500.0) / 60.0).powi(2)).exp();
6041 let turn = -90.0 * (((f - 1500.0) / 40.0).tanh() + 1.0);
6042 (f, 100.0 / f * lift, -135.0 - 90.0 * (f / 100.0).log10() + turn)
6043 })
6044 .collect();
6045 let m = loop_margins(&points_of(&rows));
6046 assert!(
6047 m.stable() && (m.phase_margin_deg - 45.0).abs() < 0.1 && (m.crossover_hz / 100.0 - 1.0).abs() < 1e-3,
6048 "{m:?}"
6049 );
6050 assert!((m.gain_margin_db - 10.0).abs() < 0.05, "{m:?}");
6051 }
6052
6053 #[test]
6060 fn a_rise_beyond_minus_one_before_its_fall_undoes_it() {
6061 let mut rows = vec![(10.0, 30.0, 80.0), (10.4, 30.0, 200.0), (10.6, 30.0, 150.0), (11.5, 30.0, 80.0)];
6062 rows.extend([(12.0, 30.0, 0.0), (12.5, 30.0, -90.0)]);
6063 rows.extend(log_spaced(13.0, 2000.0, 100).into_iter().map(|f| (f, 100.0 / f, -135.0)));
6064 let m = loop_margins(&points_of(&rows));
6065 assert!(m.stable() && m.gain_margin_db.is_infinite() && (m.phase_margin_deg - 45.0).abs() < 0.1, "{m:?}");
6066 }
6067
6068 #[test]
6072 fn a_rise_beyond_minus_one_does_not_undo_a_fall_far_above_it() {
6073 let mut rows = vec![(10.0, 30.0, 80.0), (10.4, 30.0, 200.0)];
6074 rows.extend(log_spaced(11.0, 3000.0, 200).into_iter().map(|f| {
6075 let gain = 2.0 * (300.0 / f.max(300.0)).powf(0.5f64.ln() / 0.3f64.ln());
6077 (f, gain, if f < 300.0 { 200.0 } else { 150.0 })
6078 }));
6079 let m = loop_margins(&points_of(&rows));
6080 assert!(
6081 !m.stable() && (m.gain_margin_db + 6.02).abs() < 0.1 && (m.phase_margin_deg + 30.0).abs() < 0.1,
6082 "{m:?}"
6083 );
6084 }
6085
6086 #[test]
6091 fn the_tooth_load_counts_the_teeth_in_mesh_from_the_wrap() {
6092 let cfg = Config::parse(
6093 "format_version = 1
6094[gearbox]
6095ratio = 5.0
6096[geometry]
6097pulley_radius_m = 0.02
6098[belt]
6099tooth_pitch_m = 0.005
6100[ratings]
6101 belt_tooth_load_rpm = [0.0, 100.0, 1000.0]
6102belt_tooth_load_n_cm = [35.0, 34.0, 26.0]
6103belt_width_mm = 25.0
6104belt_service_factor = 1.4
6105 belt_teeth_in_mesh = 14.0
6106",
6107 )
6108 .unwrap();
6109 let mut bands = vec![0.0; 200];
6110 bands[9] = 2.0;
6111 let m = MotorLoad {
6112 gearbox_torque: Some((2.0, 1.0)),
6113 gearbox_torque_by_speed: bands,
6114 belt_wrap: Some(2.0),
6115 ..MotorLoad::default()
6116 };
6117 let close = |a: f64, b: f64| assert!((a / b - 1.0).abs() < 1e-5, "{a} against {b} by hand");
6118 close(belt_tooth_utilisation(&cfg, &m).unwrap().unwrap(), 0.205610);
6119 close(
6120 belt_tooth_utilisation(&cfg, &MotorLoad { belt_wrap: Some(std::f64::consts::PI), ..m.clone() })
6121 .unwrap()
6122 .unwrap(),
6123 0.137073,
6124 );
6125 }
6126
6127 #[test]
6132 fn the_front_keeps_the_points_no_other_beats_in_every_figure() {
6133 let point = |duration: f64, energy: f64, utilisation: f64| FrontPoint {
6134 duration,
6135 energy,
6136 utilisation,
6137 factors: [1.0; 3],
6138 blending: false,
6139 shaping: false,
6140 };
6141 let (a, b, c, d, f) = (
6142 point(1.0, 3.0, 0.5),
6143 point(2.0, 2.0, 0.5),
6144 point(2.0, 3.0, 0.5),
6145 point(3.0, 1.0, 0.9),
6146 point(1.0, 3.0, 0.6),
6147 );
6148 let front = non_dominated(&[d.clone(), c, b.clone(), a.clone(), a.clone(), f]);
6149 assert_eq!(front, [a, b, d]);
6150 }
6151}