Skip to main content

sim_components/
profile.rs

1//! Motion profiles: the jerk-limited seven-segment S-curve, the sin² profile (Bestehorn), the polynomial motion laws
2//! 3-4-5 and 4-5-6-7 of VDI 2143, braking slower or faster than speeding up, and synchronised multi-axis moves.
3//!
4//! A profile goes from rest to rest over a distance. The S-curve and the sin² profile speed up on a ramp, cruise and
5//! brake on a ramp of their own (`Profile::Ramps`), each ramp within its own acceleration limit; the polynomial laws
6//! run the whole distance in one law with no cruise. Any profile can be stretched in time (`Profile::stretched`):
7//! speed, acceleration and jerk limits scaled by 1/k, 1/k^2 and 1/k^3 give the same shape k times as long, which is how
8//! a planner synchronises moves to a common duration.
9
10use sim_core::AxisInfo;
11
12/// The shape of a move from rest to rest (`profile.shape`, or `shape` of a `[[cycle.segment]]`).
13#[derive(Debug, Clone, Copy, PartialEq, Default, serde::Serialize, serde::Deserialize)]
14pub enum Shape {
15    /// Seven segments: jerk up, constant acceleration, jerk down, cruise, and the same braking.
16    #[default]
17    SCurve,
18    /// The speed rises as sin² of time over the ramp (Bestehorn): peak acceleration (pi/2) v / T_ramp, peak jerk
19    /// (pi^2/2) v / T_ramp^2, at the ramp's ends.
20    SinSquared,
21    /// s = 10 u^3 - 15 u^4 + 6 u^5 over the whole move (VDI 2143): speed and acceleration zero at both ends.
22    Poly345,
23    /// s = 35 u^4 - 84 u^5 + 70 u^6 - 20 u^7: jerk zero at both ends too.
24    Poly4567,
25}
26
27impl Shape {
28    pub const NAMES: [&str; 4] = ["s-curve", "sin2", "poly345", "poly4567"];
29
30    pub fn from_name(name: &str) -> Option<Self> {
31        [Self::SCurve, Self::SinSquared, Self::Poly345, Self::Poly4567].into_iter().find(|s| s.name() == name)
32    }
33
34    pub fn name(&self) -> &'static str {
35        Self::NAMES[*self as usize]
36    }
37
38    /// For a polynomial law: the peaks of speed, acceleration and jerk over a move of 1 in a time of 1 (multiply by
39    /// h/T, h/T^2 and h/T^3). 3-4-5: s' = 30 u^2 (1-u)^2, 1.875 at u = 1/2; s'' = 60 u (1-u) (1-2u), 10/sqrt 3 at
40    /// u = (1 - 1/sqrt 3)/2; s''' 60 at the ends. 4-5-6-7: s' = 140 u^3 (1-u)^3, 2.1875; s'' = 420 u^2 (1-u)^2 (1-2u),
41    /// with x = u - 1/2 largest at x^2 = 1/20: 420 * 2 / (25 sqrt 20) = 7.5132; s''' = 840 u (1-u) (1 - 5u + 5u^2),
42    /// 52.5 at u = 1/2. `None` for the shapes with a cruise.
43    pub fn peaks(&self) -> Option<[f64; 3]> {
44        match self {
45            Self::Poly345 => Some([1.875, 10.0 / 3f64.sqrt(), 60.0]),
46            Self::Poly4567 => Some([2.1875, 33.6 / 20f64.sqrt(), 52.5]),
47            _ => None,
48        }
49    }
50
51    /// For a polynomial law: (s, s', s'', s''') at u in [0, 1] over a move of 1 in a time of 1.
52    pub fn law(&self, u: f64) -> [f64; 4] {
53        let u = u.clamp(0.0, 1.0);
54        let (u2, u3) = (u * u, u * u * u);
55        match self {
56            Self::Poly4567 => [
57                u3 * u * (35.0 - 84.0 * u + 70.0 * u2 - 20.0 * u3),
58                140.0 * u3 * (1.0 - u).powi(3),
59                420.0 * u2 * (1.0 - u).powi(2) * (1.0 - 2.0 * u),
60                840.0 * u * (1.0 - u) * (1.0 - 5.0 * u + 5.0 * u2),
61            ],
62            _ => [
63                u3 * (10.0 - 15.0 * u + 6.0 * u2),
64                30.0 * u2 * (1.0 - u).powi(2),
65                60.0 * u * (1.0 - u) * (1.0 - 2.0 * u),
66                60.0 - 360.0 * u + 360.0 * u2,
67            ],
68        }
69    }
70}
71
72/// The limits of a profile: speed, acceleration while speeding up, deceleration while braking (both positive), jerk.
73#[derive(Debug, Clone, Copy, PartialEq)]
74pub struct Limits {
75    pub vel: f64,
76    pub acc: f64,
77    pub dec: f64,
78    pub jerk: f64,
79}
80
81/// A ramp from rest to a speed `speed` in `time`: an S-curve's (jerk for `tj`, constant acceleration, jerk back for
82/// `tj`) or a sin²'s. It covers speed * time / 2 (both are symmetric about their middle).
83#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)]
84pub struct Ramp {
85    sine: bool,
86    time: f64,
87    tj: f64,
88}
89
90impl Ramp {
91    /// The shortest ramp to `speed` within the acceleration `acc` and the jerk `jerk`.
92    fn new(sine: bool, speed: f64, acc: f64, jerk: f64) -> Self {
93        if sine {
94            let pi = std::f64::consts::PI;
95            let time = (pi * speed / (2.0 * acc)).max(pi * (speed / (2.0 * jerk)).sqrt());
96            return Self { sine, time, tj: 0.0 };
97        }
98        // As SCurve::new: the acceleration limit reached, or not.
99        if speed * jerk < acc * acc {
100            let tj = (speed / jerk).sqrt();
101            Self { sine, time: 2.0 * tj, tj }
102        } else {
103            Self { sine, time: acc / jerk + speed / acc, tj: acc / jerk }
104        }
105    }
106
107    /// (position, velocity, acceleration, jerk) at t in [0, time] on the way to `speed`.
108    fn at(&self, speed: f64, t: f64) -> [f64; 4] {
109        let tt = self.time;
110        let t = t.clamp(0.0, tt);
111        if tt <= 0.0 {
112            return [0.0, speed, 0.0, 0.0];
113        }
114        if self.sine {
115            let w = std::f64::consts::PI / tt;
116            return [
117                speed * (t / 2.0 - (w * t).sin() / (2.0 * w)),
118                speed * (w * t / 2.0).sin().powi(2),
119                speed * w / 2.0 * (w * t).sin(),
120                speed * w * w / 2.0 * (w * t).cos(),
121            ];
122        }
123        let (tj, ta) = (self.tj, tt - 2.0 * self.tj);
124        let j = speed / (tj * (tj + ta));
125        let (mut p, mut v, mut a, mut left) = (0.0, 0.0, 0.0, t);
126        for (duration, jerk) in [(tj, j), (ta, 0.0), (tj, -j)] {
127            let h = left.min(duration);
128            p += v * h + a * h * h / 2.0 + jerk * h * h * h / 6.0;
129            v += a * h + jerk * h * h / 2.0;
130            a += jerk * h;
131            left -= h;
132            if left <= 0.0 {
133                return [p, v, a, jerk];
134            }
135        }
136        [p, v, a, 0.0]
137    }
138}
139
140/// A move from rest to rest over `dist` in one of the shapes.
141#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
142pub enum Profile {
143    /// The S-curve with the same acceleration and braking, in closed form.
144    SCurve(SCurve),
145    /// Speeding up to `speed`, cruising for `cruise` seconds, braking: the S-curve with braking of its own, and sin².
146    Ramps { dist: f64, speed: f64, up: Ramp, cruise: f64, down: Ramp },
147    /// A polynomial law over the whole move, `time` long.
148    Law { dist: f64, shape: Shape, time: f64 },
149}
150
151impl Default for Profile {
152    fn default() -> Self {
153        Self::SCurve(SCurve::default())
154    }
155}
156
157impl Profile {
158    /// The shortest move over `dist` in `shape` within `limits`. A polynomial law, which has no separate braking, keeps
159    /// the lower of the acceleration and the deceleration.
160    pub fn new(dist: f64, shape: Shape, limits: Limits) -> Self {
161        let Limits { vel, acc, dec, jerk } = limits;
162        if dist <= 0.0 {
163            return Self::default();
164        }
165        if let Some([cv, ca, cj]) = shape.peaks() {
166            let time = (cv * dist / vel).max((ca * dist / acc.min(dec)).sqrt()).max((cj * dist / jerk).cbrt());
167            return Self::Law { dist, shape, time };
168        }
169        let sine = shape == Shape::SinSquared;
170        if !sine && acc == dec {
171            return Self::SCurve(SCurve::new(dist, vel, acc, jerk));
172        }
173        let ramps = |v: f64| (Ramp::new(sine, v, acc, jerk), Ramp::new(sine, v, dec, jerk));
174        let covered = |v: f64| {
175            let (up, down) = ramps(v);
176            v * (up.time + down.time) / 2.0
177        };
178        // The cruise speed: the limit where the ramps fit the distance, else the speed at which they cover it alone
179        // (what they cover rises with the speed).
180        let speed = if covered(vel) <= dist {
181            vel
182        } else {
183            let (mut lo, mut hi) = (0.0, vel);
184            for _ in 0..200 {
185                let mid = 0.5 * (lo + hi);
186                if covered(mid) <= dist { lo = mid } else { hi = mid }
187            }
188            lo
189        };
190        let (up, down) = ramps(speed);
191        // What the ramps leave is cruised: on a short move a rounding of the bisection.
192        let cruise = if speed > 0.0 { ((dist - covered(speed)) / speed).max(0.0) } else { 0.0 };
193        Self::Ramps { dist, speed, up, cruise, down }
194    }
195
196    /// Time scaling: the move over `dist` in `shape` stretched to `duration` (no shorter than the shortest within
197    /// `limits`), with the limits scaled by 1/k, 1/k^2 and 1/k^3 for k = duration / shortest: the same shape, slower.
198    pub fn stretched(dist: f64, shape: Shape, limits: Limits, duration: f64) -> Self {
199        let shortest = Self::new(dist, shape, limits);
200        let k = duration / shortest.duration();
201        if !(k > 1.0 && k.is_finite()) {
202            return shortest;
203        }
204        let Limits { vel, acc, dec, jerk } = limits;
205        Self::new(dist, shape, Limits { vel: vel / k, acc: acc / (k * k), dec: dec / (k * k), jerk: jerk / k.powi(3) })
206    }
207
208    pub fn dist(&self) -> f64 {
209        match self {
210            Self::SCurve(c) => c.dist,
211            Self::Ramps { dist, .. } | Self::Law { dist, .. } => *dist,
212        }
213    }
214
215    pub fn duration(&self) -> f64 {
216        match self {
217            Self::SCurve(c) => c.duration(),
218            Self::Ramps { up, cruise, down, .. } => up.time + cruise + down.time,
219            Self::Law { time, .. } => *time,
220        }
221    }
222
223    /// Time to speed up to the highest speed (the first half of a polynomial law).
224    pub fn ramp(&self) -> f64 {
225        match self {
226            Self::SCurve(c) => c.ramp(),
227            Self::Ramps { up, .. } => up.time,
228            Self::Law { time, .. } => time / 2.0,
229        }
230    }
231
232    /// Time to brake from the highest speed.
233    pub fn brake(&self) -> f64 {
234        match self {
235            Self::SCurve(c) => c.ramp(),
236            Self::Ramps { down, .. } => down.time,
237            Self::Law { time, .. } => time / 2.0,
238        }
239    }
240
241    /// (position, velocity, acceleration, jerk) at time t.
242    pub fn at(&self, t: f64) -> (f64, f64, f64, f64) {
243        let end = (self.dist(), 0.0, 0.0, 0.0);
244        if t >= self.duration() {
245            return end;
246        }
247        let t = t.max(0.0);
248        match self {
249            Self::SCurve(c) => c.at(t),
250            Self::Law { dist, shape, time } => {
251                let [s, v, a, j] = shape.law(t / time);
252                (dist * s, dist * v / time, dist * a / (time * time), dist * j / time.powi(3))
253            }
254            Self::Ramps { speed, up, cruise, down, .. } => {
255                if t < up.time {
256                    let [p, v, a, j] = up.at(*speed, t);
257                    return (p, v, a, j);
258                }
259                let at_cruise = speed * up.time / 2.0;
260                let t = t - up.time;
261                if t < *cruise {
262                    return (at_cruise + speed * t, *speed, 0.0, 0.0);
263                }
264                let t = t - cruise;
265                let [p, v, a, j] = down.at(*speed, t);
266                (at_cruise + speed * cruise + speed * t - p, speed - v, -a, -j)
267            }
268        }
269    }
270}
271
272/// How the moves of a machine are shaped: the shape, the braking limit as a share of the acceleration limit
273/// (`profile.deceleration_ratio`), and an axis that lifts against gravity (`profile.vertical_axis`): its index, the
274/// sign of up along it, and the share of its acceleration limit it has upwards (`profile.up_acceleration_ratio`). And
275/// where the tool's orientation is a rotation vector rx, ry, rz whose flange has limits of its own (an arm in tool
276/// space, the checks "tool-angular-speed" and "tool-angular-acceleration"): the flange's angular speed (rad/s) and
277/// acceleration (rad/s^2), which the move keeps beside the axes' limits on the rotation vector (`spin_rates`).
278#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
279pub struct MotionLaw {
280    pub shape: Shape,
281    pub deceleration_ratio: f64,
282    pub vertical: Option<(usize, f64, f64)>,
283    #[serde(default)]
284    pub spin: Option<[f64; 2]>,
285}
286
287impl Default for MotionLaw {
288    fn default() -> Self {
289        Self { shape: Shape::SCurve, deceleration_ratio: 1.0, vertical: None, spin: None }
290    }
291}
292
293/// Of a move whose rotation vector runs straight from `from` by `delta` (rad, over its share s from 0 to 1): the most
294/// |w| per unit of ds/dt and the most |dw/ds| per unit of (ds/dt)^2 anywhere on it, w the flange's angular velocity
295/// (w = J(r) r', J the rotation vector's Jacobian, which is not 1 away from no turn: at r = (0, pi/2, 0) a rate of 1
296/// rad/s on rz alone spins it at 2 sqrt(2) / pi = 0.900 rad/s). So |w| <= g1 ds/dt and |dw/dt| <= g1 |d2s/dt2| + g2
297/// (ds/dt)^2. At 65 places along the move (the largest between them a rounding above), by `spin_at`.
298pub fn spin_rates(from: [f64; 3], delta: [f64; 3]) -> [f64; 2] {
299    let size = |v: [f64; 3]| v.iter().map(|x| x * x).sum::<f64>().sqrt();
300    let (mut g1, mut g2) = (0.0f64, 0.0f64);
301    for i in 0..=64 {
302        let [w, bend] = spin_at(from, delta, i as f64 / 64.0);
303        (g1, g2) = (g1.max(size(w)), g2.max(size(bend)));
304    }
305    [g1, g2]
306}
307
308/// At the share s of the move of `spin_rates`: w per unit of ds/dt and dw/ds per unit of (ds/dt)^2, as vectors, so that
309/// dw/dt = w d2s/dt2 + (dw/ds) (ds/dt)^2. From the turn between orientations 1e-6 apart, and its central differences
310/// over 1e-4.
311fn spin_at(from: [f64; 3], delta: [f64; 3], s: f64) -> [[f64; 3]; 2] {
312    use crate::rigid::{exp, log, matmul, transpose};
313    let at = |s: f64| -> [f64; 3] { std::array::from_fn(|i| from[i] + s * delta[i]) };
314    let spin = |s: f64| -> [f64; 3] {
315        let h = 1e-6;
316        log(&matmul(&exp(at(s + h)), &transpose(&exp(at(s - h))))).map(|v| v / (2.0 * h))
317    };
318    let k = 1e-4;
319    let (ahead, behind) = (spin(s + k), spin(s - k));
320    [spin(s), std::array::from_fn(|i| (ahead[i] - behind[i]) / (2.0 * k))]
321}
322
323/// `limits` (over a distance of 1) with the acceleration and the deceleration as high as |dw/dt| <= `most_a` allows
324/// over the profile itself. (most_a - g2 v_top^2) / g1 holds wherever (both parts at their most and in line); a profile
325/// has its most acceleration below its top speed, and the two parts of dw/dt (`spin_at`) point apart, so the room is
326/// raised, by halving up to the axes' own, while |w a + (dw/ds) v^2| at 1024 times of the profile stays within most_a
327/// less 1e-3 of it (for what falls between). The sum of the two peaks left mixed turns 0.92 to 0.94 of the limit.
328fn spun(limits: Limits, shape: Shape, from: [f64; 3], delta: [f64; 3], [g1, g2]: [f64; 2], most_a: f64) -> Limits {
329    let with = |room: f64| Limits { acc: limits.acc.min(room), dec: limits.dec.min(room), ..limits };
330    let fits = |room: f64| {
331        let profile = Profile::new(1.0, shape, with(room));
332        let (n, duration) = (1024, profile.duration());
333        (0..=n).all(|k| {
334            let (s, v, a, _) = profile.at(duration * k as f64 / n as f64);
335            let [w, bend] = spin_at(from, delta, s);
336            let rate: f64 = (0..3).map(|i| (w[i] * a + bend[i] * v * v).powi(2)).sum();
337            rate.sqrt() <= (1.0 - 1e-3) * most_a
338        })
339    };
340    let (mut low, mut high) = ((most_a - g2 * limits.vel * limits.vel) / g1, limits.acc.max(limits.dec));
341    if high <= low {
342        return limits;
343    }
344    if fits(high) {
345        return with(high);
346    }
347    for _ in 0..30 {
348        let mid = 0.5 * (low + high);
349        if fits(mid) { low = mid } else { high = mid }
350    }
351    with(low)
352}
353/// Seven-segment S-curve over a distance, from rest to rest:
354/// jerk up, constant acceleration, jerk down, cruise, and the mirror image.
355#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
356pub struct SCurve {
357    pub dist: f64,
358    jerk: f64,
359    /// Duration of each jerk segment, of each constant-acceleration segment, and of the cruise.
360    tj: f64,
361    ta: f64,
362    tv: f64,
363}
364
365impl SCurve {
366    pub fn new(dist: f64, max_vel: f64, max_acc: f64, max_jerk: f64) -> Self {
367        if dist <= 0.0 {
368            return Self::default();
369        }
370        let (v, a, j) = (max_vel, max_acc, max_jerk);
371        // Ramp to cruise speed: with or without reaching the acceleration limit.
372        let (mut tj, mut ta) = if v * j < a * a { ((v / j).sqrt(), 0.0) } else { (a / j, v / a - a / j) };
373        let peak = |tj: f64, ta: f64| j * tj * (tj + ta);
374        let ramps = |tj: f64, ta: f64| peak(tj, ta) * (2.0 * tj + ta);
375        let mut tv = 0.0;
376        if ramps(tj, ta) > dist {
377            // Too short to reach cruise speed: lower the peak speed.
378            let tja = a / j;
379            if dist >= 2.0 * j * tja.powi(3) {
380                tj = tja;
381                ta = 0.5 * (-3.0 * tj + (tj * tj + 4.0 * dist / a).sqrt());
382            } else {
383                tj = (dist / (2.0 * j)).cbrt();
384                ta = 0.0;
385            }
386        } else {
387            tv = (dist - ramps(tj, ta)) / peak(tj, ta);
388        }
389        Self { dist, jerk: j, tj, ta, tv }
390    }
391
392    pub fn duration(&self) -> f64 {
393        4.0 * self.tj + 2.0 * self.ta + self.tv
394    }
395
396    /// Time to accelerate to cruise speed, which is also the time to brake from it.
397    pub fn ramp(&self) -> f64 {
398        2.0 * self.tj + self.ta
399    }
400
401    /// (position, velocity, acceleration, jerk) at time t.
402    pub fn at(&self, t: f64) -> (f64, f64, f64, f64) {
403        if t >= self.duration() {
404            return (self.dist, 0.0, 0.0, 0.0);
405        }
406        let j = self.jerk;
407        let segments =
408            [(self.tj, j), (self.ta, 0.0), (self.tj, -j), (self.tv, 0.0), (self.tj, -j), (self.ta, 0.0), (self.tj, j)];
409        let (mut p, mut v, mut a, mut left) = (0.0, 0.0, 0.0, t.max(0.0));
410        for (duration, jerk) in segments {
411            let h = left.min(duration);
412            p += v * h + a * h * h / 2.0 + jerk * h * h * h / 6.0;
413            v += a * h + jerk * h * h / 2.0;
414            a += jerk * h;
415            left -= h;
416            if left <= 0.0 {
417                return (p, v, a, jerk);
418            }
419        }
420        (self.dist, 0.0, 0.0, 0.0)
421    }
422}
423
424/// A straight-line move of all axes that start and finish together.
425/// One profile runs the path from 0 to 1; its limits are the tightest of all axes.
426#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
427pub struct Move {
428    start: Vec<f64>,
429    target: Vec<f64>,
430    delta: Vec<f64>,
431    // Boxed: two moves sit in `control::Motion`, whose other variants are small.
432    curve: Box<Profile>,
433}
434
435impl Move {
436    /// The S-curve within the axes' limits, braking as it speeds up.
437    pub fn new(start: &[f64], target: &[f64], axes: &[AxisInfo]) -> Self {
438        Self::with_law(start, target, axes, &MotionLaw::default())
439    }
440
441    /// The move in `law`. Speeding up, each axis accelerates towards its target; braking, away from it. The vertical
442    /// axis has `up_ratio` of its limit where that is upwards, and braking has `deceleration_ratio` of every limit.
443    pub fn with_law(start: &[f64], target: &[f64], axes: &[AxisInfo], law: &MotionLaw) -> Self {
444        let delta: Vec<f64> = target.iter().zip(start).map(|(t, s)| t - s).collect();
445        let tightest = |limit: &dyn Fn(usize, &AxisInfo, f64) -> f64| {
446            axes.iter()
447                .enumerate()
448                .zip(&delta)
449                .filter(|(_, d)| **d != 0.0)
450                .map(|((i, a), d)| limit(i, a, d.signum()) / d.abs())
451                .fold(f64::INFINITY, f64::min)
452        };
453        // The acceleration limit of axis i for an acceleration in the direction `sign`.
454        let acc = |i: usize, a: &AxisInfo, sign: f64| match law.vertical {
455            Some((axis, up, ratio)) if axis == i && sign == up => a.max_acc * ratio,
456            _ => a.max_acc,
457        };
458        let moving = delta.iter().any(|d| *d != 0.0);
459        let curve = if moving {
460            let mut limits = Limits {
461                vel: tightest(&|_, a, _| a.max_vel),
462                acc: tightest(&|i, a, sign| acc(i, a, sign)),
463                dec: tightest(&|i, a, sign| acc(i, a, -sign) * law.deceleration_ratio),
464                jerk: tightest(&|_, a, _| a.max_jerk),
465            };
466            // The flange's spin: |w| <= g1 v, and |dw/dt| <= g1 |a| + g2 v^2 with half of its limit at most for the second.
467            // A tool with fewer turn axes (the five-axis arm's rx, ry) leaves the others to the joints, and the flange's
468            // spin judged is the part about the turns it has (`Pose::angular_motion`): the path with the others at 0.
469            let turn = ["rx", "ry", "rz"].map(|id| axes.iter().position(|a| a.id == id));
470            if let (Some([most_w, most_a]), true) = (law.spin, turn.iter().any(Option::is_some)) {
471                let (from, by) = (turn.map(|t| t.map_or(0.0, |i| start[i])), turn.map(|t| t.map_or(0.0, |i| delta[i])));
472                let [g1, g2] = spin_rates(from, by);
473                if g1 > 0.0 {
474                    let by_curve = if g2 > 0.0 { (0.5 * most_a / g2).sqrt() } else { f64::INFINITY };
475                    limits.vel = limits.vel.min(most_w / g1).min(by_curve);
476                    limits = spun(limits, law.shape, from, by, [g1, g2], most_a);
477                }
478            }
479            Profile::new(1.0, law.shape, limits)
480        } else {
481            Profile::default()
482        };
483        Self { start: start.to_vec(), target: target.to_vec(), delta, curve: Box::new(curve) }
484    }
485
486    pub fn duration(&self) -> f64 {
487        self.curve.duration()
488    }
489
490    /// Time to speed up to the highest speed.
491    pub fn ramp(&self) -> f64 {
492        self.curve.ramp()
493    }
494
495    /// Time to brake from the highest speed.
496    pub fn brake(&self) -> f64 {
497        self.curve.brake()
498    }
499
500    pub fn delta(&self) -> &[f64] {
501        &self.delta
502    }
503
504    pub fn at(&self, t: f64, pos: &mut [f64], vel: &mut [f64], acc: &mut [f64]) {
505        let (s, v, a, _) = if self.curve.dist() > 0.0 { self.curve.at(t) } else { (0.0, 0.0, 0.0, 0.0) };
506        for i in 0..pos.len() {
507            // At the end the target itself: start + (target - start) can be a rounding beyond it, and beyond the end of
508            // a stroke, where a path planned from there was refused (2.1000000000000005 rad for 2.1 on an arm's joint).
509            pos[i] = if s >= 1.0 { self.target[i] } else { self.start[i] + self.delta[i] * s };
510            vel[i] = self.delta[i] * v;
511            acc[i] = self.delta[i] * a;
512        }
513    }
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519
520    /// The flange's spin on moves timed by the axis limits (1.5 rad/s, 8 rad/s^2, 150 rad/s^3 on rx, ry, rz) with its own
521    /// limits of 1.5 rad/s and 8 rad/s^2, from the six-axis arm's home r = (0, pi/2, 0), measured on the setpoint once per
522    /// millisecond. 0.5 rad on rz alone: the rz limit binds, not the spin's: across the rotation vector the flange turns at
523    /// |J e_z| = sqrt((sin t / t)^2 + ((1 - cos t) / t)^2) = 2 sqrt(2) / pi = 0.9003 of its rate (t = pi/2), 1.3505 rad/s
524    /// at 1.5 rad/s on rz (0.9012 at the move's end, 1.3518), and the move takes as long without the spin's limits. Turns
525    /// on two and three axes, which the spin binds: within both limits and up to them (before 17 November the acceleration
526    /// reached 7.37 to 7.52 rad/s^2, the bound adding the peaks of its two parts).
527    #[test]
528    fn the_flanges_spin_on_a_move_uses_its_limits() {
529        use crate::rigid::{exp, log, matmul, transpose};
530        let axes: Vec<AxisInfo> = ["x", "y", "z", "rx", "ry", "rz"]
531            .iter()
532            .map(|id| AxisInfo {
533                id,
534                min: -10.0,
535                max: 10.0,
536                max_vel: 1.5,
537                max_acc: 8.0,
538                max_jerk: 150.0,
539                ..axis(1.0, 1.0)
540            })
541            .collect();
542        let start = [0.9, -0.3, 0.7, 0.0, std::f64::consts::FRAC_PI_2, 0.0];
543        for d in [[0.0, 0.0, 0.5], [0.5, 0.0, 0.5], [0.8, 0.6, 0.9], [1.0, 1.0, 1.0]] {
544            let target: Vec<f64> = (0..6).map(|i| start[i] + if i >= 3 { d[i - 3] } else { 0.0 }).collect();
545            let run = |spin| {
546                let m = Move::with_law(&start, &target, &axes, &MotionLaw { spin, ..Default::default() });
547                let (mut p, mut v, mut a) = (vec![0.0; 6], vec![0.0; 6], vec![0.0; 6]);
548                let (mut fastest, mut hardest, mut last) = (0.0f64, 0.0f64, None::<[f64; 3]>);
549                let (dt, h) = (1e-3, 1e-6);
550                for k in 0..=((m.duration() / dt) as usize + 1) {
551                    m.at(k as f64 * dt, &mut p, &mut v, &mut a);
552                    let turned = |by: f64| exp(std::array::from_fn(|i| p[i + 3] + by * v[i + 3]));
553                    let w = log(&matmul(&turned(h), &transpose(&turned(-h)))).map(|x| x / (2.0 * h));
554                    fastest = fastest.max(w.iter().map(|x| x * x).sum::<f64>().sqrt());
555                    if let Some(l) = last {
556                        hardest = hardest.max((0..3).map(|i| ((w[i] - l[i]) / dt).powi(2)).sum::<f64>().sqrt());
557                    }
558                    last = Some(w);
559                }
560                (m.duration(), fastest, hardest)
561            };
562            let ((time, fastest, hardest), (free, ..)) = (run(Some([1.5, 8.0])), run(None));
563            println!(
564                "turn {d:?}: {time:.4} s ({free:.4} s without), |w| {fastest:.4} rad/s, |dw/dt| {hardest:.4} rad/s^2"
565            );
566            assert!(fastest <= 1.5 * 1.001 && hardest <= 8.0 * 1.001, "{d:?}: {fastest} rad/s, {hardest} rad/s^2");
567            if d[0] == 0.0 {
568                assert_eq!(time, free, "the rz limit binds");
569                assert!(fastest > 1.5 * 2.0 * 2f64.sqrt() / std::f64::consts::PI && fastest < 1.3518, "{fastest}");
570            } else {
571                assert!(fastest > 0.995 * 1.5 && hardest > 0.995 * 8.0, "{d:?}: {fastest} rad/s, {hardest} rad/s^2");
572            }
573        }
574    }
575    /// Profile limits: velocity, acceleration and jerk never exceed their limits,
576    /// in every regime (cruise reached or not, acceleration limit reached or not).
577    #[test]
578    fn velocity_acceleration_and_jerk_stay_within_limits() {
579        let cases = [
580            (1.0, 0.8, 8.0, 100.0),   // all seven segments
581            (0.05, 0.8, 8.0, 100.0),  // no cruise, acceleration limit reached
582            (0.001, 0.8, 8.0, 100.0), // no cruise, acceleration limit not reached
583            (1.0, 0.2, 8.0, 100.0),   // cruise, acceleration limit not reached
584            (0.3, 2.0, 5.0, 20.0),
585            (1e-6, 1.0, 10.0, 100.0),
586        ];
587        for (dist, v, a, j) in cases {
588            let c = SCurve::new(dist, v, a, j);
589            let (n, t_end) = (20_000, c.duration());
590            let (mut v_peak, mut a_peak) = (0f64, 0f64);
591            let mut last = c.at(0.0);
592            for i in 1..=n {
593                let now = c.at(t_end * i as f64 / n as f64);
594                let h = t_end / n as f64;
595                assert!(now.1 >= -1e-12 && now.1 <= v * (1.0 + 1e-9), "{dist}: v {}", now.1);
596                assert!(now.2.abs() <= a * (1.0 + 1e-9), "{dist}: a {}", now.2);
597                assert!(now.3.abs() <= j, "{dist}: j {}", now.3);
598                // The reported derivatives are the real ones: check them against differences.
599                assert!(
600                    (now.0 - last.0 - 0.5 * (now.1 + last.1) * h).abs() <= 1e-9 * dist + j * h.powi(3),
601                    "{dist}: p/v"
602                );
603                assert!(((now.2 - last.2) / h).abs() <= j * (1.0 + 1e-6), "{dist}: da/dt {}", (now.2 - last.2) / h);
604                v_peak = v_peak.max(now.1);
605                a_peak = a_peak.max(now.2.abs());
606                last = now;
607            }
608            let end = c.at(t_end);
609            assert!((end.0 - dist).abs() < 1e-12 && end.1 == 0.0 && end.2 == 0.0);
610            let before_end = c.at(t_end * (1.0 - 1e-9));
611            assert!((before_end.0 - dist).abs() < 1e-9 * dist && before_end.1.abs() < 1e-6 * v);
612            assert!(v_peak > 0.0 && a_peak > 0.0);
613        }
614    }
615
616    #[test]
617    fn long_moves_use_the_limits_fully() {
618        let c = SCurve::new(1.0, 0.8, 8.0, 100.0);
619        let mid = c.at(c.duration() / 2.0);
620        assert!((mid.1 - 0.8).abs() < 1e-12 && mid.2.abs() < 1e-12);
621        // Hand calculation: tj = a/j = 0.08, ta = v/a - tj = 0.02, ramps cover v (2 tj + ta) = 0.144 m.
622        assert!((c.duration() - (4.0 * 0.08 + 2.0 * 0.02 + (1.0 - 0.144) / 0.8)).abs() < 1e-12);
623    }
624
625    fn axis(max_vel: f64, max_acc: f64) -> AxisInfo {
626        AxisInfo { id: "", key: "", unit: "m", min: 0.0, max: 1.0, max_vel, max_acc, max_jerk: 100.0 }
627    }
628
629    /// Synchronised moves: both axes finish together, on a straight line, each within its limits.
630    #[test]
631    fn synchronised_axes_finish_together_within_their_limits() {
632        let axes = [axis(0.8, 8.0), axis(0.4, 6.0)];
633        let m = Move::new(&[0.1, 0.1], &[0.9, 0.4], &axes);
634        let (mut p, mut v, mut a) = ([0.0; 2], [0.0; 2], [0.0; 2]);
635        let n = 5000;
636        let mut peak_v = [0f64; 2];
637        for i in 0..=n {
638            m.at(m.duration() * i as f64 / n as f64, &mut p, &mut v, &mut a);
639            for k in 0..2 {
640                assert!(v[k].abs() <= axes[k].max_vel * (1.0 + 1e-9) && a[k].abs() <= axes[k].max_acc * (1.0 + 1e-9));
641                peak_v[k] = peak_v[k].max(v[k]);
642            }
643            assert!(((p[0] - 0.1) * 0.3 - (p[1] - 0.1) * 0.8).abs() < 1e-12, "not on the straight line");
644        }
645        assert!((p[0] - 0.9).abs() < 1e-12 && (p[1] - 0.4).abs() < 1e-12 && v == [0.0; 2]);
646        // X is the limiting axis here (0.8 m at 0.8 m/s against 0.3 m at 0.4 m/s).
647        assert!((peak_v[0] - 0.8).abs() < 1e-9 && (peak_v[1] - 0.3).abs() < 1e-9, "{peak_v:?}");
648    }
649
650    /// Peaks of a profile over its duration, sampled: (speed, acceleration, deceleration, jerk), and its end.
651    fn peaks(p: &Profile) -> ([f64; 4], (f64, f64, f64, f64)) {
652        let (n, t_end) = (100_000, p.duration());
653        let mut peak = [0f64; 4];
654        for i in 0..=n {
655            let (_, v, a, j) = p.at(t_end * i as f64 / n as f64 * (1.0 - 1e-12));
656            peak = [peak[0].max(v), peak[1].max(a), peak[2].max(-a), peak[3].max(j.abs())];
657        }
658        (peak, p.at(t_end))
659    }
660
661    /// sin² (Bestehorn): the speed rises as v sin^2(pi t / (2 T)), so the acceleration v pi / (2 T) sin(pi t / T) peaks
662    /// at (pi/2) v / T. With v = 0.8 m/s, a = 8 m/s^2 and a jerk of 1000 m/s^3 the ramp is the longer of
663    /// pi v / (2 a) = 0.15708 s and pi sqrt(v / (2 j)) = 0.06283 s: 0.15708 s, and the peak (pi/2) 0.8 / 0.15708 = 8 m/s^2.
664    #[test]
665    fn the_sin2_profile_peaks_at_pi_half_v_over_its_ramp() {
666        let limits = Limits { vel: 0.8, acc: 8.0, dec: 8.0, jerk: 1000.0 };
667        let p = Profile::new(1.0, Shape::SinSquared, limits);
668        let t_acc = p.ramp();
669        assert!((t_acc - std::f64::consts::PI * 0.8 / 16.0).abs() < 1e-12, "{t_acc}");
670        let (peak, end) = peaks(&p);
671        assert!((peak[0] - 0.8).abs() < 1e-9, "{peak:?}");
672        assert!((peak[1] - std::f64::consts::FRAC_PI_2 * 0.8 / t_acc).abs() < 1e-6 && (peak[1] - 8.0).abs() < 1e-6);
673        // The ramps cover v T each half: 0.8 * 0.15708 = 0.12566 m, the rest is cruised at 0.8 m/s.
674        assert!((p.duration() - (2.0 * t_acc + (1.0 - 0.8 * t_acc) / 0.8)).abs() < 1e-12);
675        assert!((end.0 - 1.0).abs() < 1e-15 && end.1 == 0.0);
676        // A short move does not reach the speed: ramps alone, v T(v) = dist.
677        let short = Profile::new(0.01, Shape::SinSquared, limits);
678        let (peak, end) = peaks(&short);
679        assert!(peak[0] < 0.8 && peak[1] <= 8.0 * (1.0 + 1e-9) && peak[3] <= 1000.0 * (1.0 + 1e-9), "{peak:?}");
680        assert!((end.0 - 0.01).abs() < 1e-15);
681    }
682
683    /// 3-4-5 (VDI 2143): s = h (10 u^3 - 15 u^4 + 6 u^5), u = t / T. Its speed 30 h u^2 (1 - u)^2 / T peaks at u = 1/2 at
684    /// 30/16 h / T = 1.875 h / T. Speed bound here: h = 0.3 m at 0.5 m/s takes T = 1.875 * 0.3 / 0.5 = 1.125 s (the
685    /// acceleration's sqrt(5.7735 * 0.3 / 8) = 0.465 s and the jerk's cbrt(60 * 0.3 / 1000) = 0.262 s are shorter).
686    #[test]
687    fn the_345_law_peaks_at_1_875_h_over_t() {
688        let p = Profile::new(0.3, Shape::Poly345, Limits { vel: 0.5, acc: 8.0, dec: 8.0, jerk: 1000.0 });
689        assert!((p.duration() - 1.125).abs() < 1e-12, "{}", p.duration());
690        let (peak, end) = peaks(&p);
691        assert!((peak[0] - 1.875 * 0.3 / 1.125).abs() < 1e-9 && (peak[0] - 0.5).abs() < 1e-9, "{peak:?}");
692        // Acceleration 10 / sqrt 3 h / T^2 = 5.7735 * 0.3 / 1.265625 = 1.3685 m/s^2, jerk 60 h / T^3 = 12.642 m/s^3.
693        assert!((peak[1] - 5.773_502_7 * 0.3 / 1.125f64.powi(2)).abs() < 1e-6, "{peak:?}");
694        assert!((peak[3] - 60.0 * 0.3 / 1.125f64.powi(3)).abs() < 1e-6, "{peak:?}");
695        assert!((end.0 - 0.3).abs() < 1e-15 && end.1 == 0.0 && end.2 == 0.0);
696        // Velocity is the derivative of position (central difference at u = 0.3).
697        let (t, h) = (0.3 * 1.125, 1e-6);
698        assert!(((p.at(t + h).0 - p.at(t - h).0) / (2.0 * h) - p.at(t).1).abs() < 1e-6);
699    }
700
701    /// 4-5-6-7: speed 140 h u^3 (1-u)^3 / T, 2.1875 h / T at u = 1/2; acceleration 7.5132 h / T^2; jerk 52.5 h / T^3,
702    /// zero at both ends. Acceleration bound: h = 0.1 m at 2 m/s^2 takes sqrt(7.5132 * 0.1 / 2) = 0.6129 s.
703    #[test]
704    fn the_4567_law_has_no_jerk_at_its_ends() {
705        let p = Profile::new(0.1, Shape::Poly4567, Limits { vel: 5.0, acc: 2.0, dec: 3.0, jerk: 1000.0 });
706        let t = (33.6 / 20f64.sqrt() * 0.1 / 2.0).sqrt();
707        assert!((p.duration() - t).abs() < 1e-6, "{}", p.duration());
708        let (peak, _) = peaks(&p);
709        assert!((peak[0] - 2.1875 * 0.1 / t).abs() < 1e-6 && (peak[1] - 2.0).abs() < 1e-5, "{peak:?}");
710        assert!((peak[3] - 52.5 * 0.1 / t.powi(3)).abs() < 1e-4, "{peak:?}");
711        assert!(p.at(0.0).3.abs() < 1e-12 && p.at(t * (1.0 - 1e-9)).3.abs() < 1e-3);
712    }
713
714    /// Braking at half the acceleration: v = 0.8 m/s, a = 8, d = 4 m/s^2, j = 100 m/s^3. Speeding up reaches the
715    /// acceleration: tj = 0.08 s, ramp 0.08 + 0.8 / 8 = 0.18 s. Braking: tj = 4 / 100 = 0.04 s, ramp 0.04 + 0.8 / 4 = 0.24 s.
716    /// The ramps cover 0.8 (0.18 + 0.24) / 2 = 0.168 m of 1 m; the rest at 0.8 m/s takes 1.04 s: 1.46 s in all.
717    #[test]
718    fn braking_slower_than_speeding_up_takes_its_own_ramp() {
719        let p = Profile::new(1.0, Shape::SCurve, Limits { vel: 0.8, acc: 8.0, dec: 4.0, jerk: 100.0 });
720        assert!((p.ramp() - 0.18).abs() < 1e-12 && (p.brake() - 0.24).abs() < 1e-12);
721        assert!((p.duration() - 1.46).abs() < 1e-12, "{}", p.duration());
722        let (peak, end) = peaks(&p);
723        assert!((peak[1] - 8.0).abs() < 1e-9 && (peak[2] - 4.0).abs() < 1e-9 && peak[3] <= 100.0 + 1e-9, "{peak:?}");
724        assert!((end.0 - 1.0).abs() < 1e-15);
725        // With the same braking the general ramps give the closed form's S-curve.
726        let ramps =
727            Profile::new(1.0, Shape::SCurve, Limits { vel: 0.8, acc: 8.0, dec: 8.0 * (1.0 - 1e-15), jerk: 100.0 });
728        assert!((ramps.duration() - SCurve::new(1.0, 0.8, 8.0, 100.0).duration()).abs() < 1e-9);
729    }
730
731    /// Stretched to twice its time, a profile is the same shape at half the speed: the peak speed of a 3-4-5 law and of
732    /// an S-curve halves, the end stays.
733    #[test]
734    fn a_stretched_profile_is_the_same_shape_slower() {
735        let limits = Limits { vel: 0.8, acc: 8.0, dec: 8.0, jerk: 100.0 };
736        for shape in [Shape::SCurve, Shape::SinSquared, Shape::Poly345, Shape::Poly4567] {
737            let (fast, d) = (Profile::new(0.5, shape, limits), 0.5);
738            let slow = Profile::stretched(d, shape, limits, 2.0 * fast.duration());
739            assert!((slow.duration() - 2.0 * fast.duration()).abs() < 1e-9, "{shape:?}");
740            for u in [0.1, 0.37, 0.5, 0.8] {
741                let (a, b) = (fast.at(u * fast.duration()), slow.at(u * slow.duration()));
742                assert!((a.0 - b.0).abs() < 1e-9 && (a.1 - 2.0 * b.1).abs() < 1e-9, "{shape:?} {u}");
743            }
744        }
745    }
746
747    /// Lifting against gravity: z (axis 1, up = +) has half its acceleration upwards. Up, the move speeds up at
748    /// 3 m/s^2 and brakes (downwards) at 6; down it speeds up at 6 and brakes at 3. A trapezoid (high jerk) over 0.1 m
749    /// at up to 1 m/s: up, ramps of 1/3 and 1/6 s would cover 0.25 m, more than 0.1: no cruise, and v^2 (1/3 + 1/6) / 2
750    /// = 0.1 gives v = 0.6325 m/s, T = v (1/3 + 1/6) = 0.3162 s, the same down with the ramps swapped.
751    #[test]
752    fn a_vertical_axis_accelerates_slower_upwards() {
753        let axes = [axis(1.0, 6.0), AxisInfo { max_jerk: 1e9, ..axis(1.0, 6.0) }];
754        let law = MotionLaw { vertical: Some((1, 1.0, 0.5)), ..MotionLaw::default() };
755        let (up, down) = (
756            Move::with_law(&[0.0, 0.0], &[0.0, 0.1], &axes, &law),
757            Move::with_law(&[0.0, 0.1], &[0.0, 0.0], &axes, &law),
758        );
759        let v = (0.2f64 / 0.5).sqrt();
760        for m in [&up, &down] {
761            assert!((m.duration() - v * 0.5).abs() < 1e-6, "{}", m.duration());
762        }
763        assert!(up.ramp() > up.brake() && down.ramp() < down.brake());
764        assert!((up.ramp() - 2.0 * up.brake()).abs() < 1e-6);
765        let (mut p, mut vel, mut acc) = ([0.0; 2], [0.0; 2], [0.0; 2]);
766        up.at(up.ramp() / 2.0, &mut p, &mut vel, &mut acc);
767        assert!((acc[1] - 3.0).abs() < 1e-3, "{acc:?}");
768        down.at(down.ramp() / 2.0, &mut p, &mut vel, &mut acc);
769        assert!((acc[1] + 6.0).abs() < 1e-3, "{acc:?}");
770    }
771
772    #[test]
773    fn a_move_to_where_it_already_is_takes_no_time() {
774        let m = Move::new(&[0.3, 0.2], &[0.3, 0.2], &[axis(0.8, 8.0), axis(0.4, 6.0)]);
775        assert_eq!(m.duration(), 0.0);
776    }
777}