Skip to main content

sim_components/
cam.rs

1//! Electronic cam (a CAM table): the slave's position as a function of a master's, as a drive's cam technology runs it
2//! (SIMOTION, TIA Portal's technology objects, the "Kurvenscheibe"). The master is a virtual axis or the web or conveyor
3//! the slave works on; its speed sets how fast the slave moves: slave speed s'(m) m', acceleration s''(m) m'^2 + s'(m) m'',
4//! jerk s'''(m) m'^3 at steady master speed. Knows no machine.
5//!
6//! A cam is periodic: over one master `period` the slave rises by `advance` (0 for a slave that swings back, one turn for
7//! a knife that turns on). It is made of segments (`Segment`) with the motion laws of VDI 2143 (`Law`), or of a table of
8//! points (`parse_table`, `Cam::from_table`) through which a cubic runs.
9//!
10//! Where two segments meet, the slave's slope over the master is that of the one that sets it: a straight segment
11//! (`Law::Linear`, a synchronous run) or a dwell; between two motion laws the slave is at rest there (rest in rest). A
12//! motion law between neighbours that move (velocity in velocity, VDI 2143) keeps their slopes v0 and v1 at its ends and
13//! has no acceleration there: s(u) = dm (v0 u + (v1 - v0) g(u)) + c f(u), u the share of the segment run, f the law
14//! normalised from rest to rest, g(u) = u^3 - u^4 / 2 (whose slope 3 u^2 - 2 u^3 blends v0 into v1), and
15//! c = ds - dm (v0 + v1) / 2 what the law itself has to rise.
16//!
17//! The seam to `profile`: the polynomial laws (3-4-5, 4-5-6-7) and the sine laws are written here once more, normalised
18//! in `Law::normalised`; once `profile` has them as functions of a share of the run, that is the one place to call them.
19
20use sim_core::{Config, ConfigError};
21
22/// A motion law of VDI 2143, from rest to rest over u in [0, 1].
23#[derive(Debug, Clone, Copy, PartialEq)]
24pub enum Law {
25    /// The slave stands: its rise must be 0.
26    Dwell,
27    /// Constant slope (a synchronous run): rise / master span throughout.
28    Linear,
29    /// The 5th-order polynomial 10 u^3 - 15 u^4 + 6 u^5: peak slope 1.875, peak acceleration 5.774, jerk 60 at the ends.
30    Poly345,
31    /// The 7th-order polynomial 35 u^4 - 84 u^5 + 70 u^6 - 20 u^7: no jerk at the ends; peak slope 2.1875, acceleration
32    /// 7.513.
33    Poly4567,
34    /// The cycloid (inclined sine) u - sin(2 pi u) / (2 pi): peak slope 2, acceleration 2 pi, no acceleration at the ends.
35    Cycloid,
36    /// The simple sine (harmonic) (1 - cos(pi u)) / 2: peak slope pi / 2, but an acceleration of pi^2 / 2 at both ends,
37    /// a jump against a neighbour at rest.
38    Harmonic,
39}
40
41impl Law {
42    pub fn from_name(name: &str) -> Option<Self> {
43        Some(match name {
44            "dwell" => Self::Dwell,
45            "linear" => Self::Linear,
46            "3-4-5" => Self::Poly345,
47            "4-5-6-7" => Self::Poly4567,
48            "cycloid" => Self::Cycloid,
49            "harmonic" => Self::Harmonic,
50            _ => return None,
51        })
52    }
53
54    /// Whether the law sets its own slope (straight or standing) rather than taking its neighbours'.
55    fn straight(self) -> bool {
56        matches!(self, Self::Dwell | Self::Linear)
57    }
58
59    /// The law from rest to rest at the share u: [f, f', f'', f'''] over u.
60    pub fn normalised(self, u: f64) -> [f64; 4] {
61        use std::f64::consts::PI;
62        match self {
63            Self::Dwell => [0.0; 4],
64            Self::Linear => [u, 1.0, 0.0, 0.0],
65            Self::Poly345 => {
66                let (u2, u3) = (u * u, u * u * u);
67                [
68                    10.0 * u3 - 15.0 * u3 * u + 6.0 * u3 * u2,
69                    30.0 * u2 - 60.0 * u3 + 30.0 * u2 * u2,
70                    60.0 * u - 180.0 * u2 + 120.0 * u3,
71                    60.0 - 360.0 * u + 360.0 * u2,
72                ]
73            }
74            Self::Poly4567 => {
75                let (u2, u3, u4) = (u * u, u * u * u, u * u * u * u);
76                [
77                    35.0 * u4 - 84.0 * u4 * u + 70.0 * u4 * u2 - 20.0 * u4 * u3,
78                    140.0 * u3 - 420.0 * u4 + 420.0 * u4 * u - 140.0 * u4 * u2,
79                    420.0 * u2 - 1680.0 * u3 + 2100.0 * u4 - 840.0 * u4 * u,
80                    840.0 * u - 5040.0 * u2 + 8400.0 * u3 - 4200.0 * u4,
81                ]
82            }
83            Self::Cycloid => {
84                let w = 2.0 * PI;
85                [u - (w * u).sin() / w, 1.0 - (w * u).cos(), w * (w * u).sin(), w * w * (w * u).cos()]
86            }
87            Self::Harmonic => [
88                0.5 * (1.0 - (PI * u).cos()),
89                0.5 * PI * (PI * u).sin(),
90                0.5 * PI * PI * (PI * u).cos(),
91                -0.5 * PI * PI * PI * (PI * u).sin(),
92            ],
93        }
94    }
95}
96
97/// One segment of a cam: over `master` of the master the slave rises by `slave` along `law`.
98#[derive(Debug, Clone, Copy, PartialEq)]
99pub struct Segment {
100    pub master: f64,
101    pub slave: f64,
102    pub law: Law,
103}
104
105#[derive(Debug, Clone)]
106enum Piece {
107    /// A segment of a motion law from `m0` over `dm`, the slave from `s0` by `ds`, its slopes `v0` and `v1` at the ends.
108    Law { m0: f64, dm: f64, s0: f64, ds: f64, v0: f64, v1: f64, law: Law },
109    /// A cubic from (m0, s0) with slope k0 to (m0 + h, s1) with slope k1.
110    Cubic { m0: f64, h: f64, s0: f64, s1: f64, k0: f64, k1: f64 },
111}
112
113impl Piece {
114    fn start(&self) -> f64 {
115        match self {
116            Self::Law { m0, .. } | Self::Cubic { m0, .. } => *m0,
117        }
118    }
119
120    /// [s, s', s'', s'''] over the master at `m`, within the piece.
121    fn at(&self, m: f64) -> [f64; 4] {
122        match *self {
123            Self::Law { m0, dm, s0, ds, v0, v1, law } => {
124                let u = ((m - m0) / dm).clamp(0.0, 1.0);
125                if law == Law::Linear {
126                    return [s0 + ds * u, ds / dm, 0.0, 0.0];
127                }
128                let f = law.normalised(u);
129                let (g, g1, g2, g3) = (
130                    u * u * u - 0.5 * u * u * u * u,
131                    3.0 * u * u - 2.0 * u * u * u,
132                    6.0 * u - 6.0 * u * u,
133                    6.0 - 12.0 * u,
134                );
135                let (dv, c) = (v1 - v0, ds - dm * (v0 + v1) / 2.0);
136                [
137                    s0 + dm * (v0 * u + dv * g) + c * f[0],
138                    v0 + dv * g1 + c * f[1] / dm,
139                    dv * g2 / dm + c * f[2] / (dm * dm),
140                    dv * g3 / (dm * dm) + c * f[3] / (dm * dm * dm),
141                ]
142            }
143            Self::Cubic { m0, h, s0, s1, k0, k1 } => {
144                let u = ((m - m0) / h).clamp(0.0, 1.0);
145                let (u2, u3) = (u * u, u * u * u);
146                // Hermite basis: position and its rates over u, then over m.
147                let b = [
148                    [2.0 * u3 - 3.0 * u2 + 1.0, u3 - 2.0 * u2 + u, -2.0 * u3 + 3.0 * u2, u3 - u2],
149                    [6.0 * u2 - 6.0 * u, 3.0 * u2 - 4.0 * u + 1.0, -6.0 * u2 + 6.0 * u, 3.0 * u2 - 2.0 * u],
150                    [12.0 * u - 6.0, 6.0 * u - 4.0, -12.0 * u + 6.0, 6.0 * u - 2.0],
151                    [12.0, 6.0, -12.0, 6.0],
152                ];
153                let at = |r: [f64; 4]| r[0] * s0 + r[1] * h * k0 + r[2] * s1 + r[3] * h * k1;
154                [at(b[0]), at(b[1]) / h, at(b[2]) / (h * h), at(b[3]) / (h * h * h)]
155            }
156        }
157    }
158}
159
160/// A periodic cam: its pieces over one master period from 0, and what the slave rises by over the period.
161#[derive(Debug, Clone)]
162pub struct Cam {
163    pieces: Vec<Piece>,
164    pub period: f64,
165    pub advance: f64,
166}
167
168impl Cam {
169    /// The cam of `segments`, the slave starting at 0. An error says which segment (from 0) is wrong: a span that is not
170    /// positive, a dwell that rises, or two straight neighbours of different slopes (the slave's speed would jump).
171    pub fn from_segments(segments: &[Segment]) -> Result<Self, usize> {
172        let n = segments.len();
173        if n == 0 {
174            return Err(0);
175        }
176        for (i, s) in segments.iter().enumerate() {
177            if !(s.master > 0.0 && s.master.is_finite() && s.slave.is_finite()) || s.law == Law::Dwell && s.slave != 0.0
178            {
179                return Err(i);
180            }
181        }
182        let slope = |s: &Segment| if s.law == Law::Linear { s.slave / s.master } else { 0.0 };
183        // The slope where segment i ends and i + 1 begins (the last one meets the first: the cam goes round).
184        let mut junction = Vec::with_capacity(n);
185        for i in 0..n {
186            let (a, b) = (&segments[i], &segments[(i + 1) % n]);
187            junction.push(match (a.law.straight(), b.law.straight()) {
188                (true, true) if (slope(a) - slope(b)).abs() > 1e-9 * slope(a).abs().max(slope(b).abs()).max(1e-12) => {
189                    return Err((i + 1) % n);
190                }
191                (true, _) => slope(a),
192                (false, true) => slope(b),
193                (false, false) => 0.0,
194            });
195        }
196        let (mut m0, mut s0, mut pieces) = (0.0, 0.0, Vec::with_capacity(n));
197        for (i, s) in segments.iter().enumerate() {
198            let (v0, v1) = (junction[(i + n - 1) % n], junction[i]);
199            pieces.push(Piece::Law { m0, dm: s.master, s0, ds: s.slave, v0, v1, law: s.law });
200            m0 += s.master;
201            s0 += s.slave;
202        }
203        Self { pieces, period: m0, advance: s0 }.finite()
204    }
205
206    /// The cam through a table of points (master, slave, slope over the master where given), the master rising; the
207    /// last point closes the period (the master's span of the table is the period, the slave's its advance). Where a
208    /// row has no slope, the slopes are those of the periodic cubic spline through the points (the slave's acceleration
209    /// is then continuous), else a cubic runs between each two points with their slopes. An error names the row (from
210    /// 0) that is wrong: fewer than three points, a master that does not rise, slopes on some rows only, or
211    /// values so large or so close that the slopes overflow.
212    pub fn from_table(rows: &[(f64, f64, Option<f64>)]) -> Result<Self, usize> {
213        let n = rows.len();
214        if n < 3 {
215            return Err(n);
216        }
217        if let Some(i) = (1..n).find(|&i| !(rows[i].0 > rows[i - 1].0)) {
218            return Err(i);
219        }
220        let given = rows.iter().filter(|r| r.2.is_some()).count();
221        if given != 0 && given != n {
222            return Err(rows.iter().position(|r| r.2.is_none()).unwrap_or(0));
223        }
224        let (period, advance) = (rows[n - 1].0 - rows[0].0, rows[n - 1].1 - rows[0].1);
225        let slopes: Vec<f64> = if given == n {
226            rows.iter().map(|r| r.2.unwrap_or_default()).collect()
227        } else {
228            // Periodic spline over the n - 1 intervals: unknowns k_0 .. k_{n-2}, k_{n-1} = k_0. At each point the second
229            // derivative from the left equals that from the right:
230            // k_{i-1} / h_{i-1} + 2 k_i (1 / h_{i-1} + 1 / h_i) + k_{i+1} / h_i = 3 (d_{i-1} / h_{i-1} + d_i / h_i), d = rise / h.
231            let p = n - 1;
232            let h: Vec<f64> = (0..p).map(|i| rows[i + 1].0 - rows[i].0).collect();
233            let d: Vec<f64> = (0..p).map(|i| (rows[i + 1].1 - rows[i].1) / h[i]).collect();
234            let mut a = vec![0.0; p * p];
235            let mut b = vec![0.0; p];
236            for i in 0..p {
237                let before = (i + p - 1) % p;
238                a[i * p + before] += 1.0 / h[before];
239                a[i * p + i] += 2.0 * (1.0 / h[before] + 1.0 / h[i]);
240                a[i * p + (i + 1) % p] += 1.0 / h[i];
241                b[i] = 3.0 * (d[before] / h[before] + d[i] / h[i]);
242            }
243            let mut k = crate::chain::solve(&a, &b).ok_or(0usize)?;
244            k.push(k[0]);
245            k
246        };
247        let pieces = (0..n - 1)
248            .map(|i| Piece::Cubic {
249                m0: rows[i].0 - rows[0].0,
250                h: rows[i + 1].0 - rows[i].0,
251                s0: rows[i].1 - rows[0].1,
252                s1: rows[i + 1].1 - rows[0].1,
253                k0: slopes[i],
254                k1: slopes[i + 1],
255            })
256            .collect();
257        Self { pieces, period, advance }.finite()
258    }
259
260    /// The cam, or the first piece (from 0) whose slave position or rates at its ends are no finite numbers: points or
261    /// segments so large or so close that their slopes overflow.
262    fn finite(self) -> Result<Self, usize> {
263        let ends = |p: &Piece| match *p {
264            Piece::Law { m0, dm: h, .. } | Piece::Cubic { m0, h, .. } => [p.at(m0), p.at(m0 + h)],
265        };
266        match self.pieces.iter().position(|p| !ends(p).iter().flatten().all(|v| v.is_finite())) {
267            Some(i) => Err(i),
268            None if self.period.is_finite() && self.advance.is_finite() => Ok(self),
269            None => Err(0),
270        }
271    }
272
273    /// The cam of `<prefix>.table_file` (a CSV file of master, slave and an optional slope, see `parse_table`) where
274    /// that is not empty, else of the array `[[<prefix>.segment]]`, each with `master`, `slave` (in the master's and the
275    /// slave's units) and `law` (`Law::from_name`).
276    pub fn from_config(cfg: &Config, prefix: &str) -> Result<Self, ConfigError> {
277        let file = cfg.get(&format!("{prefix}.table_file"))?.as_str().unwrap_or_default().to_string();
278        if !file.is_empty() {
279            let bad = |detail: String| ConfigError::Invalid(format!("{prefix}.table_file: {file}: {detail}"));
280            let text = std::fs::read_to_string(&file).map_err(|e| bad(e.to_string()))?;
281            let rows = parse_table(&text).map_err(|line| bad(format!("line {line}")))?;
282            return Self::from_table(&rows).map_err(|row| bad(format!("row {row}")));
283        }
284        let key = format!("{prefix}.segment");
285        let number =
286            |v: Option<&toml::Value>| v.and_then(|v| v.as_float().or_else(|| v.as_integer().map(|i| i as f64)));
287        let segments = cfg
288            .array(&key)?
289            .iter()
290            .enumerate()
291            .map(|(i, s)| {
292                let law = s.get("law").and_then(|l| l.as_str()).and_then(Law::from_name);
293                match (number(s.get("master")), number(s.get("slave")), law) {
294                    (Some(master), Some(slave), Some(law)) => Ok(Segment { master, slave, law }),
295                    _ => Err(ConfigError::Invalid(format!("{key}[{i}]"))),
296                }
297            })
298            .collect::<Result<Vec<_>, _>>()?;
299        Self::from_segments(&segments).map_err(|i| ConfigError::Invalid(format!("{key}[{i}]")))
300    }
301
302    /// [s, s', s'', s'''] over the master at any master position: the period repeats, each time `advance` higher.
303    pub fn at(&self, m: f64) -> [f64; 4] {
304        let turns = (m / self.period).floor();
305        let r = m - turns * self.period;
306        let i = self.pieces.partition_point(|p| p.start() <= r).saturating_sub(1);
307        let mut out = self.pieces[i].at(r);
308        out[0] += turns * self.advance;
309        out
310    }
311
312    /// The highest slave speed, acceleration and jerk over a period at the steady master speed `speed`:
313    /// max |s'| v, max |s''| v^2, max |s'''| v^3, sampled at 4000 points and at every piece's ends.
314    pub fn peaks(&self, speed: f64) -> [f64; 3] {
315        let n = 4000;
316        let mut at: Vec<f64> = (0..=n).map(|i| self.period * i as f64 / n as f64).collect();
317        for p in &self.pieces {
318            // Just inside each end, where a law's jerk is highest.
319            at.extend([p.start() + 1e-9 * self.period, p.start() - 1e-9 * self.period]);
320        }
321        let mut peak = [0f64; 3];
322        for m in at.into_iter().filter(|m| (0.0..=self.period).contains(m)) {
323            let s = self.at(m);
324            for k in 0..3 {
325                peak[k] = peak[k].max(s[k + 1].abs() * speed.powi(k as i32 + 1));
326            }
327        }
328        peak
329    }
330}
331
332/// Rows of a cam table in CSV: master, slave and optionally the slope of the slave over the master, comma separated. A
333/// line that does not start with a number (a header, a comment beginning with `#`, an empty line) is skipped. An error
334/// gives the number of the line (from 1) that has a number first and then something that is not one (or is NaN or
335/// infinite), or too many fields.
336pub fn parse_table(text: &str) -> Result<Vec<(f64, f64, Option<f64>)>, usize> {
337    let mut rows = Vec::new();
338    for (i, line) in text.lines().enumerate() {
339        let mut fields = line.split(',').map(|f| f.trim().parse::<f64>());
340        let Some(Ok(master)) = fields.next() else { continue };
341        let rest: Vec<f64> = fields.collect::<Result<_, _>>().map_err(|_| i + 1)?;
342        if !master.is_finite() || rest.iter().any(|v| !v.is_finite()) {
343            return Err(i + 1);
344        }
345        match rest[..] {
346            [slave] => rows.push((master, slave, None)),
347            [slave, slope] => rows.push((master, slave, Some(slope))),
348            _ => return Err(i + 1),
349        }
350    }
351    Ok(rows)
352}
353
354/// The master's travel, speed and acceleration `t` seconds after it starts from rest: up to `speed` in `ramp` seconds by
355/// a sin^2 speed ramp (no jump in acceleration), steady, and from `stop` seconds on down to rest by the mirror ramp.
356/// A stop asked for during the run-up begins once the master is up to speed.
357pub fn master_at(speed: f64, ramp: f64, t: f64, stop: Option<f64>) -> [f64; 3] {
358    master_change(0.0, speed, ramp, t, stop)
359}
360
361/// The master's travel, speed and acceleration `t` seconds after its speed is set from `from` to `speed`: the same sin^2
362/// ramp between the two over `ramp` seconds (`master_at` is the one from rest), travel from (from + speed) ramp / 2 at
363/// its end; then steady, and from `stop` on down to rest from `speed`.
364pub fn master_change(from: f64, speed: f64, ramp: f64, t: f64, stop: Option<f64>) -> [f64; 3] {
365    use std::f64::consts::PI;
366    // The ramp of unit height from rest: travel, speed and acceleration.
367    let unit = |t: f64| -> [f64; 3] {
368        if ramp <= 0.0 || t >= ramp {
369            return [t - ramp / 2.0, 1.0, 0.0];
370        }
371        let w = PI / ramp;
372        [t / 2.0 - (w * t).sin() / (2.0 * w), (w * t / 2.0).sin().powi(2), w / 2.0 * (w * t).sin()]
373    };
374    let up = |t: f64| -> [f64; 3] {
375        let u = unit(t);
376        [from * t + (speed - from) * u[0], from + (speed - from) * u[1], (speed - from) * u[2]]
377    };
378    let t = t.max(0.0);
379    let Some(stop) = stop.map(|s| s.max(ramp)) else { return up(t) };
380    if t <= stop {
381        return up(t);
382    }
383    let base = up(stop)[0];
384    let tau = (t - stop).min(ramp);
385    if ramp <= 0.0 {
386        return [base, 0.0, 0.0];
387    }
388    // The run-up turned round: travel ramp / 2 at most, speed falling as cos^2.
389    let r = unit(tau);
390    [base + speed * (tau - r[0]), speed * (1.0 - r[1]), -speed * r[2]]
391}
392
393/// The slave's position, speed and acceleration from the cam's [s, s', s'', s'''] and the master's [m, m', m''].
394pub fn slave_motion(cam: [f64; 4], master: [f64; 3]) -> [f64; 3] {
395    [cam[0], cam[1] * master[1], cam[2] * master[1] * master[1] + cam[1] * master[2]]
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401
402    fn rest_to_rest(law: Law) -> Cam {
403        Cam::from_segments(&[Segment { master: 1.0, slave: 1.0, law }, Segment { master: 1.0, slave: -1.0, law }])
404            .unwrap()
405    }
406
407    /// 3-4-5 over a master span T at master speed V, rise h: the slave's peak speed is 1.875 h V / T, at mid-span, and its
408    /// peak acceleration 10 / sqrt(3) h V^2 / T^2 = 5.7735 h V^2 / T^2, at u = (3 - sqrt 3) / 6 = 0.2113. With h = 0.1 m,
409    /// T = 2 rad and V = 4 rad/s: 0.375 m/s and 5.7735 * 0.1 * 16 / 4 = 2.3094 m/s^2; the jerk at the start 60 h V^3 / T^3
410    /// = 60 * 0.1 * 64 / 8 = 48 m/s^3.
411    #[test]
412    fn a_3_4_5_segment_peaks_at_its_hand_worked_speed_acceleration_and_jerk() {
413        let cam = Cam::from_segments(&[
414            Segment { master: 2.0, slave: 0.1, law: Law::Poly345 },
415            Segment { master: 2.0, slave: -0.1, law: Law::Poly345 },
416        ])
417        .unwrap();
418        let [v, a, j] = cam.peaks(4.0);
419        assert!((v - 0.375).abs() < 1e-9, "{v}");
420        assert!((a - 0.1 * 16.0 / 4.0 * 10.0 / 3f64.sqrt()).abs() < 1e-5, "{a}");
421        assert!((a - 2.3094).abs() < 1e-4 && (j - 48.0).abs() < 1e-6, "{a} {j}");
422        // At mid-span half the rise, and the slope there 1.875 h / T.
423        let mid = cam.at(1.0);
424        assert!((mid[0] - 0.05).abs() < 1e-12 && (mid[1] - 1.875 * 0.1 / 2.0).abs() < 1e-12);
425    }
426
427    /// Every law rises from 0 to 1 at rest at both ends (the harmonic with its end accelerations), its rates the
428    /// differences of the one before.
429    #[test]
430    fn every_law_rises_by_one_from_rest_to_rest_with_consistent_rates() {
431        for law in [Law::Poly345, Law::Poly4567, Law::Cycloid, Law::Harmonic] {
432            let (start, end) = (law.normalised(0.0), law.normalised(1.0));
433            assert!(start[0].abs() < 1e-12 && (end[0] - 1.0).abs() < 1e-12, "{law:?}");
434            assert!(start[1].abs() < 1e-12 && end[1].abs() < 1e-12, "{law:?}");
435            let h = 1e-6;
436            for u in [0.1, 0.37, 0.5, 0.83] {
437                let (a, b) = (law.normalised(u - h), law.normalised(u + h));
438                for k in 0..3 {
439                    let diff = (b[k] - a[k]) / (2.0 * h);
440                    assert!((diff - law.normalised(u)[k + 1]).abs() < 1e-5 * (1.0 + diff.abs()), "{law:?} {k} {u}");
441                }
442            }
443        }
444        assert!((rest_to_rest(Law::Poly4567).peaks(1.0)[0] - 2.1875).abs() < 1e-9);
445        assert!((rest_to_rest(Law::Cycloid).peaks(1.0)[1] - std::f64::consts::TAU).abs() < 1e-6);
446    }
447
448    /// A law between two synchronous runs of slope 1 / R (a knife that matches the web): its slopes at the ends are the
449    /// neighbours', and with 3-4-5 the slope at mid-span is v + 1.875 (ds / dm - v).
450    #[test]
451    fn a_law_between_two_runs_keeps_their_slope_and_no_acceleration_at_its_ends() {
452        let v = 10.0;
453        let cam = Cam::from_segments(&[
454            Segment { master: 0.01, slave: 0.1, law: Law::Linear },
455            Segment { master: 0.5, slave: 6.0, law: Law::Poly345 },
456            Segment { master: 0.01, slave: 0.1, law: Law::Linear },
457        ])
458        .unwrap();
459        for m in [0.01 + 1e-12, 0.51 - 1e-12] {
460            let s = cam.at(m);
461            assert!((s[1] - v).abs() < 1e-6 && s[2].abs() < 1e-3, "{s:?}");
462        }
463        let mid = cam.at(0.26);
464        assert!((mid[1] - (v + 1.875 * (6.0 / 0.5 - v))).abs() < 1e-9, "{mid:?}");
465        assert!((cam.period - 0.52).abs() < 1e-12 && (cam.advance - 6.2).abs() < 1e-12);
466        // The next period goes on 6.2 higher.
467        assert!((cam.at(0.52 + 0.26)[0] - cam.at(0.26)[0] - 6.2).abs() < 1e-12);
468    }
469
470    #[test]
471    fn segments_that_cannot_join_are_refused_by_their_index() {
472        let lin = |master: f64, slave: f64| Segment { master, slave, law: Law::Linear };
473        assert_eq!(Cam::from_segments(&[lin(1.0, 1.0), lin(1.0, 2.0)]).unwrap_err(), 1);
474        assert_eq!(
475            Cam::from_segments(&[lin(1.0, 1.0), Segment { master: 1.0, slave: 0.5, law: Law::Dwell }]).unwrap_err(),
476            1
477        );
478        assert_eq!(Cam::from_segments(&[lin(0.0, 1.0)]).unwrap_err(), 0);
479    }
480
481    /// A table of a sine with its slopes runs through the sine; without slopes the periodic spline is near it too.
482    #[test]
483    fn a_table_imported_from_csv_runs_through_its_points() {
484        let text: String = std::iter::once("master,slave,slope\n# a sine over one turn\n".to_string())
485            .chain((0..=36).map(|i| {
486                let m = i as f64 * 10f64.to_radians();
487                format!("{m}, {}, {}\n", m.sin(), m.cos())
488            }))
489            .collect();
490        let rows = parse_table(&text).unwrap();
491        assert_eq!(rows.len(), 37);
492        let with = Cam::from_table(&rows).unwrap();
493        let without = Cam::from_table(&rows.iter().map(|r| (r.0, r.1, None)).collect::<Vec<_>>()).unwrap();
494        for m in [0.3, 1.0, 2.5, 4.0, 6.0] {
495            assert!((with.at(m)[0] - m.sin()).abs() < 1e-5 && (with.at(m)[1] - m.cos()).abs() < 1e-3, "{m}");
496            assert!((without.at(m)[0] - m.sin()).abs() < 1e-4 && (without.at(m)[2] + m.sin()).abs() < 2e-2, "{m}");
497        }
498        assert!(with.advance.abs() < 1e-12 && (with.period - std::f64::consts::TAU).abs() < 1e-12);
499        assert_eq!(parse_table("0, 1\n1, x\n"), Err(2));
500        assert_eq!(Cam::from_table(&[(0.0, 0.0, None), (1.0, 1.0, Some(1.0)), (2.0, 2.0, None)]).unwrap_err(), 0);
501    }
502
503    /// A new master speed while the cam runs, from 2 to 4 m/s over a ramp of 0.5 s: the speed (V0 + V1) / 2 = 3 m/s at
504    /// mid-ramp, with the ramp's highest acceleration (V1 - V0) pi / (2 ramp) = 2 pi m/s2 there; 4 m/s at its end,
505    /// having gone (V0 + V1) ramp / 2 = 1.5 m; at no point a step in speed or acceleration (0 at both ends). 0.25 s later
506    /// it has gone 1.5 + 4 * 0.25 = 2.5 m. Asked to stop at 1 s, it runs down from 4 m/s over 0.5 s: 1 m more.
507    #[test]
508    fn a_new_master_speed_ramps_from_the_old_one() {
509        use std::f64::consts::PI;
510        let (v0, v1, ramp) = (2.0, 4.0, 0.5);
511        assert_eq!(master_change(v0, v1, ramp, 0.0, None), [0.0, 2.0, 0.0]);
512        let mid = master_change(v0, v1, ramp, 0.25, None);
513        assert!((mid[1] - 3.0).abs() < 1e-12 && (mid[2] - (v1 - v0) * PI / (2.0 * ramp)).abs() < 1e-12, "{mid:?}");
514        let end = master_change(v0, v1, ramp, ramp, None);
515        assert!((end[0] - 1.5).abs() < 1e-12 && (end[1] - 4.0).abs() < 1e-12 && end[2].abs() < 1e-12, "{end:?}");
516        assert!((master_change(v0, v1, ramp, 0.75, None)[0] - 2.5).abs() < 1e-12);
517        let stopped = master_change(v0, v1, ramp, 3.0, Some(1.0));
518        assert!((stopped[0] - (1.5 + 4.0 * 0.5 + 1.0)).abs() < 1e-12 && stopped[1].abs() < 1e-12, "{stopped:?}");
519        let h = 1e-6;
520        for t in [0.1, 0.3, 0.49, 0.6, 1.2] {
521            let (a, b) = (master_change(v0, v1, ramp, t - h, Some(1.0)), master_change(v0, v1, ramp, t + h, Some(1.0)));
522            let at = master_change(v0, v1, ramp, t, Some(1.0));
523            assert!(
524                ((b[0] - a[0]) / (2.0 * h) - at[1]).abs() < 1e-6 && ((b[1] - a[1]) / (2.0 * h) - at[2]).abs() < 1e-5
525            );
526        }
527    }
528
529    /// The master's sin^2 ramp: up to speed in `ramp` seconds having gone ramp V / 2, down again over the same.
530    #[test]
531    fn the_master_runs_up_and_down_by_its_ramp() {
532        let (v, ramp) = (2.0, 0.5);
533        assert_eq!(master_at(v, ramp, 0.0, None), [0.0, 0.0, 0.0]);
534        let up = master_at(v, ramp, ramp, None);
535        assert!((up[0] - 0.5).abs() < 1e-12 && (up[1] - v).abs() < 1e-12);
536        let half = master_at(v, ramp, ramp / 2.0, None);
537        // Peak acceleration V pi / (2 ramp) at mid-ramp.
538        assert!((half[1] - 1.0).abs() < 1e-12 && (half[2] - v * std::f64::consts::PI / (2.0 * ramp)).abs() < 1e-12);
539        let stop = 2.0;
540        let end = master_at(v, ramp, stop + ramp + 1.0, Some(stop));
541        // 0.5 m up, 1.5 s steady at 2 m/s, 0.5 m down.
542        assert!((end[0] - (0.5 + 3.0 + 0.5)).abs() < 1e-12 && end[1].abs() < 1e-12, "{end:?}");
543        let h = 1e-6;
544        for t in [0.1, 0.3, 1.0, 2.1, 2.3] {
545            let (a, b) = (master_at(v, ramp, t - h, Some(stop)), master_at(v, ramp, t + h, Some(stop)));
546            let mid = master_at(v, ramp, t, Some(stop));
547            assert!(
548                ((b[0] - a[0]) / (2.0 * h) - mid[1]).abs() < 1e-6 && ((b[1] - a[1]) / (2.0 * h) - mid[2]).abs() < 1e-5
549            );
550        }
551    }
552}