Skip to main content

sim_components/
trace.rs

1//! Drive traces: what a drive's scope exports, read from CSV and replayed through the simulator.
2
3use crate::control::Command;
4use crate::sim::Sim;
5use sim_core::{Config, ConfigError, MachineEntry, MotorInfo};
6
7/// A trace that cannot be read or replayed; `key` is a translation key, `detail` its argument.
8#[derive(Debug, Clone, PartialEq)]
9pub struct TraceError {
10    pub key: &'static str,
11    pub detail: String,
12}
13
14impl From<ConfigError> for TraceError {
15    fn from(e: ConfigError) -> Self {
16        Self { key: e.key(), detail: e.detail().into() }
17    }
18}
19
20/// Whether the motors turn by the same angle per travel of each axis everywhere: at 40 % and at 60 % of every range,
21/// 1 mm along each axis, to 1e-9. The fit per axis (`identify::fit_rigid`) takes the motor angles per axis travel as
22/// constant, so it refuses a machine whose transformation is not linear (the delta's arms, a SCARA), which gave numbers
23/// without meaning; those are fitted in the motors' own coordinates (`identify::fit_joints`). Replay works for both.
24pub fn linear_transformation(machine: &dyn sim_core::Machine) -> bool {
25    let (axes, motors) = (machine.axes(), machine.motors().len());
26    let turned = |pose: &[f64], axis: usize| {
27        let (mut a, mut b) = (vec![0.0; motors], vec![0.0; motors]);
28        let ahead: Vec<f64> = pose.iter().enumerate().map(|(i, p)| if i == axis { p + 1e-3 } else { *p }).collect();
29        machine.inverse(pose, &mut a);
30        machine.inverse(&ahead, &mut b);
31        b.iter().zip(&a).map(|(b, a)| b - a).collect::<Vec<f64>>()
32    };
33    let at = |share: f64| axes.iter().map(|a| a.min + share * (a.max - a.min)).collect::<Vec<f64>>();
34    (0..axes.len()).all(|axis| {
35        turned(&at(0.4), axis)
36            .iter()
37            .zip(turned(&at(0.6), axis))
38            .all(|(a, b)| (a - b).abs() <= 1e-9 * a.abs().max(1e-6))
39    })
40}
41
42/// Whether the fit per axis (`identify::fit_rigid`) applies: a linear transformation, and a rigid model whose torques
43/// per unit of each axis's acceleration are the same at 10 %, 20 % ... 90 % of every range (a SCARA's inertia, even in its
44/// elbow angle, agrees at poses symmetric about the middle; a cam's dwells hold two probes alike), to `PER_AXIS_SPREAD` of
45/// the largest. A SCARA's tool pose is its joints, linear, but the inertia an arm turns changes with the pose.
46pub fn per_axis_fit(machine: &dyn sim_core::Machine) -> bool {
47    let (axes, motors) = (machine.axes(), machine.motors().len());
48    let at = |share: f64| axes.iter().map(|a| a.min + share * (a.max - a.min)).collect::<Vec<f64>>();
49    let inertia = |pose: &[f64], axis: usize| {
50        let (mut a, mut b) = (vec![0.0; motors], vec![0.0; motors]);
51        let acc: Vec<f64> = (0..axes.len()).map(|i| if i == axis { 1.0 } else { 0.0 }).collect();
52        machine.feedforward_torque(pose, &vec![0.0; axes.len()], &mut a);
53        machine.feedforward_torque(pose, &acc, &mut b);
54        b.iter().zip(&a).map(|(b, a)| b - a).collect::<Vec<f64>>()
55    };
56    // Nine poses across the range, 10 % to 90 %: two of them can both fall in a dwell of a cam (the Geneva drive's and the
57    // indexer's reflected inertia varies 5 to 7 times, yet agreed at 35 % and 60 %).
58    let same = |axis: usize| {
59        let low = inertia(&at(0.1), axis);
60        let largest = low.iter().fold(0.0, |m: f64, v| m.max(v.abs()));
61        (2..=9).all(|k| {
62            let high = inertia(&at(k as f64 / 10.0), axis);
63            low.iter().zip(&high).all(|(a, b)| (a - b).abs() <= PER_AXIS_SPREAD * largest)
64        })
65    };
66    linear_transformation(machine) && (0..axes.len()).all(same)
67}
68
69/// How far the torques per unit of an axis's acceleration may differ across the range for the fit per axis
70/// (`per_axis_fit`), of the largest: the fitted mass is then their mean over the trace, and how far the inertia strays
71/// from it over the trace's poses is in the mass's error (`AxisFit::mass_spread`), so this only chooses which of the two
72/// fits answers, and both answer honestly on either side of it (the disc cam per axis without its payload and in its
73/// motor's coordinates with it, `a_mass_that_varies_over_the_poses_carries_its_spread_in_its_error`). The T-shaped belt gantry's belt (its runs on the vertical posts and its share in the
74/// Z axis's moves) changes its torques by up to 3.9 % over the range (4.5 % without the payload); the other machines
75/// fitted per axis by 0; the disc cam by 6.2 % (4.1 % without the payload, so its config without one is fitted per
76/// axis); the slider-crank, the SCARA, the indexers' cams and the arm by 40 % and more.
77pub const PER_AXIS_SPREAD: f64 = 0.05;
78
79/// One motor's columns of a trace, all at the motor shaft: position setpoint, position, speed, torque.
80#[derive(Debug, Clone, Default, PartialEq)]
81pub struct MotorTrace {
82    pub setpoint: Vec<f64>,
83    pub angle: Vec<f64>,
84    pub speed: Vec<f64>,
85    pub torque: Vec<f64>,
86}
87
88impl MotorTrace {
89    pub fn following_error(&self) -> Vec<f64> {
90        self.setpoint.iter().zip(&self.angle).map(|(s, a)| s - a).collect()
91    }
92}
93
94#[derive(Debug, Clone, Default, PartialEq)]
95pub struct Trace {
96    pub time: Vec<f64>,
97    pub motors: Vec<MotorTrace>,
98    /// Per axis the tool's speed and acceleration setpoints row by row, where the trace carries them (a file written by
99    /// a run: `axis.<id>.velocity_setpoint`, `.acceleration_setpoint`); empty for a drive's trace, whose rates `replay`
100    /// derives from the rows.
101    pub tool_rates: Vec<[Vec<f64>; 2]>,
102}
103
104/// The named columns of a CSV table with a header line. A unit in brackets after a column's name is
105/// dropped; columns that are not asked for are ignored.
106pub fn columns(text: &str, names: &[String]) -> Result<Vec<Vec<f64>>, TraceError> {
107    let mut lines = text.lines().filter(|l| !l.trim().is_empty());
108    let header: Vec<&str> =
109        lines.next().unwrap_or("").split(',').map(|h| h.split('[').next().unwrap_or("").trim()).collect();
110    let mut at = Vec::new();
111    for name in names {
112        at.push(
113            header
114                .iter()
115                .position(|h| h == name)
116                .ok_or_else(|| TraceError { key: "error-trace-column", detail: name.clone() })?,
117        );
118    }
119    let mut out = vec![Vec::new(); names.len()];
120    for line in lines {
121        let fields: Vec<&str> = line.split(',').collect();
122        for (column, &i) in out.iter_mut().zip(&at) {
123            let value = fields.get(i).and_then(|f| f.trim().parse::<f64>().ok()).filter(|v| v.is_finite());
124            column.push(value.ok_or_else(|| TraceError { key: "error-trace-row", detail: line.into() })?);
125        }
126    }
127    Ok(out)
128}
129
130/// Refuses times that do not rise, naming the first data row (1 = the row under the header) that does not.
131pub fn rising(time: &[f64]) -> Result<(), TraceError> {
132    match time.windows(2).position(|p| !(p[1] > p[0])) {
133        Some(i) => Err(TraceError {
134            key: "error-import-time",
135            detail: format!("row {}: {} s after {} s", i + 2, time[i + 1], time[i]),
136        }),
137        None => Ok(()),
138    }
139}
140
141impl Trace {
142    /// Reads a trace whose columns are named like the simulator's signals: `time` and per motor
143    /// `motor.<id>.angle_setpoint`, `.angle`, `.speed` and `.torque`. So a file written by a run is a trace.
144    pub fn parse(text: &str, motors: &[MotorInfo]) -> Result<Self, TraceError> {
145        let mut names = vec!["time".to_string()];
146        for motor in motors {
147            names.extend(["angle_setpoint", "angle", "speed", "torque"].map(|n| format!("motor.{}.{n}", motor.id)));
148        }
149        let mut found = columns(text, &names)?.into_iter();
150        let time = found.next().unwrap_or_default();
151        rising(&time)?;
152        let mut next = || found.next().unwrap_or_default();
153        let motors = motors
154            .iter()
155            .map(|_| MotorTrace { setpoint: next(), angle: next(), speed: next(), torque: next() })
156            .collect();
157        // The axes' speed and acceleration setpoints, where every axis named in the header has both.
158        let header: Vec<&str> = text
159            .lines()
160            .find(|l| !l.trim().is_empty())
161            .unwrap_or("")
162            .split(',')
163            .map(|h| h.split('[').next().unwrap_or("").trim())
164            .collect();
165        let axes: Vec<&str> =
166            header.iter().filter_map(|h| h.strip_prefix("axis.")?.strip_suffix(".position")).collect();
167        let names: Vec<String> = axes
168            .iter()
169            .flat_map(|a| ["velocity_setpoint", "acceleration_setpoint"].map(|n| format!("axis.{a}.{n}")))
170            .collect();
171        let tool_rates = match columns(text, &names) {
172            Ok(found) if !axes.is_empty() => found.chunks(2).map(|c| [c[0].clone(), c[1].clone()]).collect(),
173            _ => Vec::new(),
174        };
175        Ok(Self { time, motors, tool_rates })
176    }
177
178    /// Adds the present state of a simulation as one row, with the values a run writes to CSV.
179    pub fn record(&mut self, sim: &Sim) {
180        let n = sim.control.drives.len();
181        let (mut angle, mut speed) = (vec![0.0; n], vec![0.0; n]);
182        sim.machine.motor_state(&sim.state, &mut angle, &mut speed);
183        self.motors.resize(n, MotorTrace::default());
184        self.time.push(sim.time());
185        for (k, motor) in self.motors.iter_mut().enumerate() {
186            let drive = &sim.control.drives[k];
187            motor.setpoint.push(drive.pos_set);
188            motor.angle.push(angle[k]);
189            motor.speed.push(speed[k]);
190            motor.torque.push(drive.torque);
191        }
192    }
193}
194
195/// The shortest run-up of a replay (`replay`), s: long enough for the loops' integrators and the friction to settle
196/// at the trace's first speed before its first row.
197pub const RUN_UP_S: f64 = 0.25;
198
199/// Plays the position setpoints of a trace through the simulator and returns what the simulated drives
200/// did at the times of the trace's rows. The replay starts from the trace's own state, whatever the config's start pose:
201/// at rest at a pose before it, it runs up to the first row's position setpoint at the first row's measured speed, so a
202/// recording cut out of a longer motion replays without the jolt of a start from rest. The run-up is a smootherstep of
203/// the speed (rest to that speed, zero acceleration at both ends, `RUN_UP_S` or more, so that its acceleration stays
204/// within a quarter of each axis's limit), the way covered half the speed times its time; the pose it starts at has to
205/// be within the axes' ranges; the run-up starts where the machine's setpoint stands at rest there (its motors, a sag
206/// away from the tool) and takes that difference up on the way. A trace that starts at rest where the config's own
207/// machine stands at rest (a trace written by a run of the config) is replayed from that state with no run-up, the
208/// first row the machine at rest, as before the run-up existed: it replays onto itself to rounding.
209///
210/// The setpoints become tool poses (the machine's forward transformation) and run with their speeds and accelerations
211/// as `Command::RatedTrajectory`, so the simulator's own controller makes the speed and torque feedforward from them, as
212/// it does for any path. With a row per profile cycle the position setpoints are reproduced exactly. Where the trace
213/// carries the tool's speed and acceleration setpoints (`Trace::tool_rates`, a file written by a run), those are the
214/// rates; a drive's trace has none, and they are derived from the rows (`slopes`: the quartic through the five rows
215/// around each that do not straddle a step of the jerk), which gives a planned motion's own. Slopes between rows were
216/// off by up to jerk x row, which moved what the fit finds on a run's own trace by up to 0.63 % (11 of its standard
217/// errors on the six-strut platform). Behind the last row the motion carries on (below): the trace's end is not forced to rest.
218pub fn replay(entry: &MachineEntry, cfg: &Config, trace: &Trace) -> Result<Trace, TraceError> {
219    // The rows are a stream, interpolated between neighbours as a drive does (the Hermite cubic, whatever the config's
220    // `profile.trajectory_spline`): the C2 spline, clamped at rest at the end of the run-out below, rang back over
221    // the rows before it, the last ones off by 4 N m of torque on a belt axis and 800 N m on a linear motor.
222    let mut cfg = cfg.clone();
223    cfg.set_text("profile.trajectory_spline = \"hermite\"")?;
224    let rows = trace.time.len();
225    // The first row is the start, and carrying on behind the last one (below) takes three more.
226    if rows < 4 {
227        return Err(TraceError { key: "error-trace-short", detail: String::new() });
228    }
229    let machine = (entry.build)(&crate::catalog::resolve(entry, &cfg)?)?;
230    let pose_of = |angles: &[f64]| {
231        let mut pose = vec![0.0; machine.axes().len()];
232        machine.forward(angles, &mut pose);
233        pose
234    };
235    // The trace's state at its first row: the position setpoint's pose, and the measured speed in tool units (the pose
236    // 1 ms ahead at that speed).
237    let first: Vec<f64> = trace.motors.iter().map(|m| m.setpoint[0]).collect();
238    let start = pose_of(&first);
239    let ahead = pose_of(&trace.motors.iter().map(|m| m.setpoint[0] + 1e-3 * m.speed[0]).collect::<Vec<f64>>());
240    let speed: Vec<f64> = ahead.iter().zip(&start).map(|(a, s)| (a - s) / 1e-3).collect();
241    let step = trace.time[1] - trace.time[0];
242    // A trace that starts at rest where the config's own machine stands at rest (its drives' setpoints those of the
243    // first row: a trace written by a run of this config) is replayed from that very state, with no run-up: so it
244    // replays onto itself to rounding, where the gear mesh sticks at rest too (an arm, a machine on cables).
245    let at_rest = trace.motors.iter().all(|m| m.speed[0].abs() <= 1e-9);
246    let own = Sim::new(entry, &cfg)?;
247    let same_start =
248        own.control.drives.iter().zip(&first).all(|(d, s)| (d.pos_set - s).abs() <= 1e-9 * s.abs().max(1.0));
249    // Peak acceleration of the smootherstep: 15/8 of speed over time.
250    let long =
251        machine.axes().iter().zip(&speed).map(|(a, v)| 1.875 * v.abs() / (0.25 * a.max_acc)).fold(RUN_UP_S, f64::max);
252    let run_up = if at_rest && same_start { 0 } else { (long / step).ceil() as usize + 1 };
253    let span = run_up.saturating_sub(1) as f64 * step;
254    let from: Vec<f64> = start.iter().zip(&speed).map(|(p, v)| p - 0.5 * v * span).collect();
255    let mut sim = if run_up == 0 {
256        own
257    } else {
258        cfg.set("start.pose", toml::Value::Array(from.iter().map(|p| toml::Value::Float(*p)).collect()))?;
259        Sim::new(entry, &cfg)?
260    };
261    // The setpoint of a machine at rest is where its motors stand, some hundredths of a millimetre from the tool where
262    // gravity twists its gears or stretches its belts or cables (`Controller::command`): the run-up starts there and
263    // takes the difference up along a smoothstep, so the setpoint does not step.
264    let rest = sim.control.planned_pos().to_vec();
265    // Smootherstep of the speed, integrated: s(u) = 2.5 u^4 - 3 u^5 + u^6, 1/2 at u = 1; with its speed and acceleration
266    // (`rates`, for a trace that carries its own).
267    let (mut points, mut rates): (Vec<(f64, Vec<f64>)>, Vec<[Vec<f64>; 2]>) = (0..run_up)
268        .map(|k| {
269            let u = k as f64 / (run_up - 1) as f64;
270            let way = [
271                span * (2.5 * u.powi(4) - 3.0 * u.powi(5) + u.powi(6)),
272                10.0 * u.powi(3) - 15.0 * u.powi(4) + 6.0 * u.powi(5),
273                (30.0 * u * u - 60.0 * u.powi(3) + 30.0 * u.powi(4)) / span,
274            ];
275            let blend = [
276                1.0 - u * u * u * (10.0 - 15.0 * u + 6.0 * u * u),
277                -(30.0 * u * u - 60.0 * u.powi(3) + 30.0 * u.powi(4)) / span,
278                -(60.0 * u - 180.0 * u * u + 120.0 * u.powi(3)) / (span * span),
279            ];
280            let at = |d: usize| (0..from.len()).map(|i| speed[i] * way[d] + (rest[i] - from[i]) * blend[d]).collect();
281            let pose: Vec<f64> =
282                (0..from.len()).map(|i| from[i] + speed[i] * way[0] + (rest[i] - from[i]) * blend[0]).collect();
283            ((k as f64 * step, pose), [at(1), at(2)])
284        })
285        .unzip();
286    // A row holds the setpoint the drive worked with up to the row's time (a run writes a row before it
287    // computes the step at that time). So each row is commanded one row earlier: the first row, the start, ends the
288    // run-up, and row i follows at the run-up's end plus the time from row 1 to row i + 1. Without a run-up, row 1 is
289    // commanded at once and row 0 is the machine at rest.
290    let offset = if run_up == 0 { 0.0 } else { span + step };
291    points.extend((1..rows).map(|i| {
292        let setpoint: Vec<f64> = trace.motors.iter().map(|m| m.setpoint[i]).collect();
293        (offset + trace.time[i] - trace.time[1], pose_of(&setpoint))
294    }));
295    let rated = trace.tool_rates.len() == from.len() && trace.tool_rates.iter().all(|r| r[0].len() == rows);
296    let rate = |d: usize, i: usize| trace.tool_rates.iter().map(|r| r[d][i]).collect::<Vec<f64>>();
297    rates.extend((1..rows).map(|i| if rated { [rate(0, i), rate(1, i)] } else { Default::default() }));
298    // A trajectory ends at rest, a trace may end in motion. Two more points, carrying on with the last
299    // rows' speed and acceleration, put the stop and the piece of curve that bends towards it behind
300    // the last row.
301    for _ in 0..2 {
302        let [a, b, c] = [1, 2, 3].map(|back| &points[points.len() - back]);
303        let (time, gap) = (2.0 * a.0 - b.0, a.0 - b.0);
304        points.push((time, (0..a.1.len()).map(|i| 3.0 * a.1[i] - 3.0 * b.1[i] + c.1[i]).collect()));
305        let [v, acc] = rates[rates.len() - 1].clone();
306        rates.push([v.iter().zip(&acc).map(|(v, a)| v + a * gap).collect(), acc]);
307    }
308    // A drive's trace has no rate columns: its rows' speeds and accelerations come from the rows around them (`slopes`),
309    // so it runs as a run's trace does, a quintic through them, not a cubic whose acceleration steps at every row.
310    if !rated {
311        for k in run_up..points.len() {
312            rates[k] = slopes(&points, k);
313        }
314    }
315    let (speeds, accelerations) = rates.into_iter().map(|[v, a]| (v, a)).unzip();
316    let command = Command::RatedTrajectory(points, speeds, accelerations);
317    sim.command(command).map_err(|e| TraceError { key: e.key, detail: String::new() })?;
318    let mut out = Trace::default();
319    for time in &trace.time {
320        while sim.step < ((time - trace.time[0] + offset) / sim.dt).round() as u64 {
321            sim.step();
322        }
323        out.record(&sim);
324    }
325    out.time.clone_from(&trace.time);
326    Ok(out)
327}
328
329/// Speed and acceleration at point `k` of a curve given by its points (at least five), per axis from the quartic through
330/// five neighbouring points that hold `k`: of the five such windows the most central one whose fourth divided difference
331/// is within `SMOOTHEST` of the smallest. A planned motion is a piecewise cubic in time (the jerk steps), so a window
332/// that does not straddle a step gives the plan's own speed and acceleration, where the central one, straddling it, was
333/// off by about jerk step x row interval in the acceleration and moved a fit by 5 of its standard errors. Where the rows
334/// carry noise (setpoints in encoder counts) the windows' differences are all of its size, and the central window,
335/// which amplifies it least (a fifth of what a window at the end does), is kept: always taking the smallest put the
336/// synthetic belt axis's replay at 0.00397 N m RMS, 0.00348 with the cubic before, 0.00311 now (datasets/RESULTS.md; 0.00307 on the trace regenerated on 17 November 2026).
337fn slopes(points: &[(f64, Vec<f64>)], k: usize) -> [Vec<f64>; 2] {
338    /// How much smoother than the central window another has to be to be taken.
339    const SMOOTHEST: f64 = 10.0;
340    let n = points.len();
341    let t = |i: usize| points[i].0;
342    let starts = || {
343        let mut s: Vec<usize> = (k.saturating_sub(4)..=k.min(n - 5)).collect();
344        s.sort_by_key(|&s| (2 * s + 4).abs_diff(2 * k));
345        s
346    };
347    let axes = points[k].1.len();
348    let (mut speed, mut acc) = (vec![0.0; axes], vec![0.0; axes]);
349    for a in 0..axes {
350        let fourth = |s: usize| {
351            (s..s + 5)
352                .map(|j| points[j].1[a] / (s..s + 5).filter(|&i| i != j).map(|i| t(j) - t(i)).product::<f64>())
353                .sum::<f64>()
354                .abs()
355        };
356        let smallest = starts().into_iter().map(fourth).fold(f64::INFINITY, f64::min);
357        let s = starts().into_iter().find(|&s| fourth(s) <= SMOOTHEST * smallest).unwrap_or(0);
358        let times: Vec<f64> = (s..s + 5).map(t).collect();
359        let w = fornberg(t(k), &times);
360        speed[a] = (0..5).map(|j| w[j][1] * points[s + j].1[a]).sum();
361        acc[a] = (0..5).map(|j| w[j][2] * points[s + j].1[a]).sum();
362    }
363    [speed, acc]
364}
365
366/// Weights of the values at `x` for the value, first and second derivative at `z` of the polynomial through them
367/// (Fornberg 1988, Math. Comp. 51, 699): `w[j][m]`.
368fn fornberg(z: f64, x: &[f64]) -> Vec<[f64; 3]> {
369    let mut c = vec![[0.0; 3]; x.len()];
370    c[0][0] = 1.0;
371    let (mut c1, mut c4) = (1.0, x[0] - z);
372    for i in 1..x.len() {
373        let (mut c2, c5) = (1.0, c4);
374        c4 = x[i] - z;
375        for j in 0..i {
376            let c3 = x[i] - x[j];
377            c2 *= c3;
378            if j == i - 1 {
379                for m in (1..3).rev() {
380                    c[i][m] = c1 * (m as f64 * c[i - 1][m - 1] - c5 * c[i - 1][m]) / c2;
381                }
382                c[i][0] = -c1 * c5 * c[i - 1][0] / c2;
383            }
384            for m in (1..3).rev() {
385                c[j][m] = (c4 * c[j][m] - m as f64 * c[j][m - 1]) / c3;
386            }
387            c[j][0] = c4 * c[j][0] / c3;
388        }
389        c1 = c2;
390    }
391    c
392}
393
394/// Per motor how far a replay is from its trace: RMS and peak of the difference of the torques, then of the
395/// following errors.
396pub fn differences(measured: &Trace, simulated: &Trace) -> Vec<[f64; 4]> {
397    let apart = |(m, s): (&MotorTrace, &MotorTrace)| {
398        let (torque, error) =
399            (difference(&m.torque, &s.torque), difference(&m.following_error(), &s.following_error()));
400        [torque.0, torque.1, error.0, error.1]
401    };
402    measured.motors.iter().zip(&simulated.motors).map(apart).collect()
403}
404
405/// Measured and simulated torque, speed and following error side by side, per motor named in `ids`, one line
406/// per row of the trace, as CSV with a header.
407pub fn overlay_csv(ids: &[&str], measured: &Trace, simulated: &Trace) -> String {
408    let names = ["torque", "speed", "following_error"];
409    let header: Vec<String> =
410        ids.iter().flat_map(|id| names.map(|n| format!("motor.{id}.{n}_measured,motor.{id}.{n}_simulated"))).collect();
411    let mut out = format!("time,{}\n", header.join(","));
412    let pairs = || measured.motors.iter().zip(&simulated.motors);
413    let errors: Vec<(Vec<f64>, Vec<f64>)> = pairs().map(|(m, s)| (m.following_error(), s.following_error())).collect();
414    for (row, time) in measured.time.iter().enumerate() {
415        let values: Vec<String> = pairs()
416            .zip(&errors)
417            .flat_map(|((m, s), (m_error, s_error))| {
418                [m.torque[row], s.torque[row], m.speed[row], s.speed[row], m_error[row], s_error[row]]
419            })
420            .map(|v| format!("{v:.9e}"))
421            .collect();
422        out += &format!("{time:.9e},{}\n", values.join(","));
423    }
424    out
425}
426
427/// RMS and peak of the difference between two columns.
428pub fn difference(a: &[f64], b: &[f64]) -> (f64, f64) {
429    let squares: f64 = a.iter().zip(b).map(|(a, b)| (a - b).powi(2)).sum();
430    ((squares / a.len().max(1) as f64).sqrt(), a.iter().zip(b).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max))
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436
437    /// A jerk-limited start, a row every millisecond: jerk 1000 m/s³ for 13.5 ms, then none (the step lies between rows
438    /// 13 and 14). Every row's speed and acceleration are the curve's own: a = j min(t, T), v = j t² / 2 up to T and
439    /// j T (t - T / 2) after it.
440    #[test]
441    fn the_rates_of_a_row_are_those_of_the_piecewise_cubic_through_it() {
442        let (j, big_t) = (1000.0, 0.0135);
443        let x = |t: f64| {
444            if t <= big_t {
445                j * t.powi(3) / 6.0
446            } else {
447                j * big_t.powi(3) / 6.0 + j * big_t * big_t / 2.0 * (t - big_t) + j * big_t / 2.0 * (t - big_t).powi(2)
448            }
449        };
450        let points: Vec<(f64, Vec<f64>)> = (0..30).map(|i| (i as f64 * 1e-3, vec![x(i as f64 * 1e-3)])).collect();
451        for k in 0..points.len() {
452            let t = points[k].0;
453            let (v, a) = if t <= big_t { (j * t * t / 2.0, j * t) } else { (j * big_t * (t - big_t / 2.0), j * big_t) };
454            let [speed, acc] = slopes(&points, k);
455            assert!((speed[0] - v).abs() < 1e-9 && (acc[0] - a).abs() < 1e-6, "row {k}: {speed:?} {acc:?}, {v} {a}");
456        }
457    }
458}