Skip to main content

sim_components/
stop.rs

1//! How far a machine travels after a stop (`Command::Halt`), triggered at many moments of its cycle or path (`study`):
2//! where each axis is fastest, where the kinetic plus potential energy is largest, and on a grid between. Per moment the
3//! distances the tool and each axis travel, the stopping time, the peak deceleration, whether an axis went beyond its
4//! stroke into a hard stop, and the DC link's peak voltage and the braking resistor's energy; the worst moment judged.
5
6use crate::analysis::Verdict;
7use crate::control::{Command, StopCategory};
8use crate::sim::{Sim, Snapshot};
9use sim_core::{Config, ConfigError, MachineEntry};
10
11/// Why a moment was chosen.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Moment {
14    /// On the even grid over the pass.
15    Grid,
16    /// Where tool axis k is fastest.
17    Fastest(usize),
18    /// Where the machine's kinetic plus potential energy is largest.
19    Energy,
20}
21
22/// One stop: when it was triggered (s from the start of the run) and what it came to.
23#[derive(Debug, Clone, PartialEq)]
24pub struct Stop {
25    pub at: f64,
26    pub moment: Moment,
27    /// How far the tool got from where it was at the trigger, over the axes in metres (over all axes on a machine without
28    /// one), and each tool axis, in its unit: the farthest, not the path, so that ringing at the end does not add up.
29    pub tool_distance: f64,
30    pub axis_distance: Vec<f64>,
31    /// From the trigger until every axis stays below a hundredth of its speed limit, s.
32    pub time: f64,
33    /// The tool's largest deceleration over 1 ms, m/s^2 (over the axes as `tool_distance`).
34    pub peak_deceleration: f64,
35    /// An axis went beyond its stroke (into its hard stop).
36    pub hard_stop: bool,
37    /// The highest DC link voltage of the drives, V, and the energy their braking resistors took, J.
38    pub peak_dc_voltage: f64,
39    pub resistor_energy: f64,
40    /// A drive tripped on DC link overvoltage and the machine coasted from then on.
41    pub tripped: bool,
42}
43
44/// The stops of `study`, in the order of their moments, the index of the one with the longest tool distance, and the
45/// verdicts on it: `stopping-distance` against `ratings.max_stopping_distance_m` (where the config has it) and, with the
46/// DC link simulated, `stop-dc-link`, its peak voltage against the trip level, failed when a stop tripped a drive.
47#[derive(Debug, Clone, PartialEq)]
48pub struct Study {
49    pub stops: Vec<Stop>,
50    pub worst: usize,
51    pub verdicts: Vec<Verdict>,
52}
53
54/// The longest a stop is followed, s.
55const LONGEST_STOP_S: f64 = 3.0;
56/// How long every axis has to stay slow for the machine to count as stopped, s.
57const STANDING_S: f64 = 0.1;
58/// The longest pass of a cycle, s.
59const LONGEST_PASS_S: f64 = 60.0;
60
61/// The config's cycle, or its `[path]` (`sim::with_path`), run once; stops of `category` triggered at the moments where
62/// each tool axis is fastest, where the energy is largest, and at `grid` moments evenly over the pass (from its start).
63pub fn study(entry: &MachineEntry, cfg: &Config, category: StopCategory, grid: usize) -> Result<Study, ConfigError> {
64    let started = || -> Result<Sim, ConfigError> {
65        let mut sim = Sim::new(entry, cfg)?;
66        let command = match sim.plan_configured_path() {
67            Some(points) => Command::Trajectory(points.map_err(|e| ConfigError::Invalid(e.key.into()))?),
68            None => Command::StartCycle,
69        };
70        sim.command(command).map_err(|e| ConfigError::Invalid(e.key.into()))?;
71        Ok(sim)
72    };
73    // The pass: until the cycle starts again, or the path has run.
74    let mut sim = started()?;
75    let axes = sim.machine.axes().to_vec();
76    let every = (1e-3 / sim.dt).round().max(1.0) as u64;
77    let (mut pose, mut rate) = (vec![0.0; axes.len()], vec![0.0; axes.len()]);
78    let mut fastest = vec![(0.0f64, 0u64); axes.len()];
79    let mut energy = (f64::NEG_INFINITY, 0u64);
80    let path = sim.path.is_some();
81    while sim.time() < LONGEST_PASS_S && if path { sim.control.busy() } else { sim.control.cycle_passes() < 2 } {
82        sim.step();
83        if sim.step % every == 0 {
84            crate::analysis::check_cancelled();
85            sim.machine.tool_state(&sim.state, &mut pose, &mut rate);
86            for (best, v) in fastest.iter_mut().zip(&rate) {
87                if v.abs() > best.0 {
88                    *best = (v.abs(), sim.step);
89                }
90            }
91            let e = sim.machine.energy(&sim.state);
92            if e > energy.0 {
93                energy = (e, sim.step);
94            }
95        }
96    }
97    let pass = sim.step;
98    let mut moments: Vec<(u64, Moment)> = (0..grid).map(|i| (pass * i as u64 / grid as u64, Moment::Grid)).collect();
99    moments.extend(fastest.iter().enumerate().filter(|(_, f)| f.0 > 0.0).map(|(k, f)| (f.1, Moment::Fastest(k))));
100    moments.push((energy.1, Moment::Energy));
101    moments.sort_by_key(|m| m.0);
102    moments.dedup_by_key(|m| m.0);
103    // The run again, kept at each moment.
104    let mut sim = started()?;
105    let mut kept: Vec<Snapshot> = Vec::new();
106    // Each moment: kept on the run again, then stopped from.
107    crate::analysis::plan_steps(2 * moments.len());
108    for (step, _) in &moments {
109        while sim.step < *step {
110            sim.step();
111        }
112        crate::analysis::check_cancelled();
113        kept.push(sim.snapshot());
114        crate::analysis::step_done();
115    }
116    let stops: Vec<Stop> = moments
117        .iter()
118        .zip(&kept)
119        .map(|((_, moment), at)| {
120            crate::analysis::check_cancelled();
121            let stopped = stop(&mut sim, at, *moment, category);
122            crate::analysis::step_done();
123            stopped
124        })
125        .collect();
126    let worst =
127        (0..stops.len()).max_by(|&a, &b| stops[a].tool_distance.total_cmp(&stops[b].tool_distance)).unwrap_or(0);
128    let mut verdicts = Vec::new();
129    // The tool distance is in rad on a machine without an axis in m: it has its own limit.
130    let key = if axes.iter().any(|a| a.unit == "m") {
131        "ratings.max_stopping_distance_m"
132    } else {
133        "ratings.max_stopping_angle_rad"
134    };
135    if let (Ok(limit), Some(w)) = (cfg.f64(key), stops.get(worst)) {
136        let value = w.tool_distance;
137        verdicts.push(Verdict { check: "stopping-distance", motor: None, value, limit, ok: value <= limit });
138    }
139    let p = sim.control.drive_params();
140    if p.dc_link {
141        let value = stops.iter().map(|s| s.peak_dc_voltage).fold(0.0, f64::max);
142        let ok = !stops.iter().any(|s| s.tripped);
143        verdicts.push(Verdict { check: "stop-dc-link", motor: None, value, limit: p.overvoltage, ok });
144    }
145    Ok(Study { stops, worst, verdicts })
146}
147
148/// One stop of `category` from `at`, followed until the machine stands (or `LONGEST_STOP_S`).
149fn stop(sim: &mut Sim, at: &Snapshot, moment: Moment, category: StopCategory) -> Stop {
150    sim.restore(at).expect("a snapshot of this simulation");
151    let axes = sim.machine.axes().to_vec();
152    let metres: Vec<bool> = if axes.iter().any(|a| a.unit == "m") {
153        axes.iter().map(|a| a.unit == "m").collect()
154    } else {
155        vec![true; axes.len()]
156    };
157    let slack = sim.machine.setpoint_slack();
158    let shared = sim.control.drive_params().shared_dc_link;
159    let start = sim.time();
160    // A stop the controller refuses (the drives already off or stopping) leaves the machine as it goes.
161    let _ = sim.command(Command::Halt(category));
162    let (mut pose, mut rate) = (vec![0.0; axes.len()], vec![0.0; axes.len()]);
163    sim.machine.tool_state(&sim.state, &mut pose, &mut rate);
164    let mut result = Stop {
165        at: start,
166        moment,
167        tool_distance: 0.0,
168        axis_distance: vec![0.0; axes.len()],
169        time: 0.0,
170        peak_deceleration: 0.0,
171        hard_stop: false,
172        peak_dc_voltage: 0.0,
173        resistor_energy: 0.0,
174        tripped: false,
175    };
176    let speed = |rate: &[f64]| rate.iter().zip(&metres).filter(|(_, m)| **m).map(|(v, _)| v * v).sum::<f64>().sqrt();
177    let every = (1e-3 / sim.dt).round().max(1.0) as u64;
178    let (from, mut last) = (pose.clone(), rate.clone());
179    let (mut steps, mut still) = (0u64, 0.0);
180    while still < STANDING_S && (steps as f64) * sim.dt < LONGEST_STOP_S {
181        sim.step();
182        steps += 1;
183        sim.machine.tool_state(&sim.state, &mut pose, &mut rate);
184        let away: Vec<f64> = pose.iter().zip(&from).map(|(x, x0)| x - x0).collect();
185        result.tool_distance = result.tool_distance.max(speed(&away));
186        for (d, a) in result.axis_distance.iter_mut().zip(&away) {
187            *d = d.max(a.abs());
188        }
189        if steps % every == 0 {
190            let change: Vec<f64> = rate.iter().zip(&last).map(|(v, l)| v - l).collect();
191            result.peak_deceleration = result.peak_deceleration.max(speed(&change) / (every as f64 * sim.dt));
192            last.clone_from(&rate);
193        }
194        // A hundredth: a carriage ringing on its belt and brake after the torque is off is not travelling any more.
195        let moving = rate.iter().zip(&axes).any(|(v, a)| v.abs() >= 1e-2 * a.max_vel);
196        if moving {
197            (result.time, still) = (steps as f64 * sim.dt, 0.0);
198        } else {
199            still += sim.dt;
200        }
201        result.hard_stop |= pose.iter().zip(&axes).any(|(x, a)| *x < a.min - slack || *x > a.max + slack);
202        let drives = &sim.control.drives;
203        result.peak_dc_voltage = drives.iter().map(|d| d.dc_voltage).fold(result.peak_dc_voltage, f64::max);
204        let burned: f64 = if shared {
205            drives.first().map_or(0.0, |d| d.resistor_power)
206        } else {
207            drives.iter().map(|d| d.resistor_power).sum()
208        };
209        result.resistor_energy += burned * sim.dt;
210        result.tripped |= drives.iter().any(|d| d.tripped);
211    }
212    result
213}