Skip to main content

sim_core/
testkit.rs

1//! The standard machine test suite. Every kinematics must pass it unchanged:
2//! transformation round trip, static hold, energy conservation, step-size convergence, determinism, and the
3//! energy balance with the losses the machine reports.
4
5use crate::{ENERGY_PARTS, LOSS_PREFIX, Machine, MachineEntry, Rk4, advance, advance_refined};
6
7pub const DT: f64 = 62.5e-6;
8pub const SUBSTEPS: u32 = 4;
9/// The suite's pulse: short enough to ring the belt, smooth enough to leave the gear mode alone.
10const PULSE_S: f64 = 0.02;
11const PULSE_ACC: f64 = 0.1;
12
13pub fn run_standard_suite(entry: &MachineEntry) {
14    let default = (entry.build)(&entry.config()).unwrap();
15    round_trip(default.as_ref());
16    frame_momentum_moves_its_first_moment(default.as_ref());
17    static_hold(default.as_ref());
18    determinism(default.as_ref());
19    loss_budget(default.as_ref());
20    let configs = (entry.suite_configs)();
21    assert!(!configs.is_empty(), "{}: no loss-free config for the suite", entry.id);
22    // A config to a thread: the six-axis arm's four took half a minute one after the other.
23    std::thread::scope(|scope| {
24        for config in &configs {
25            scope.spawn(move || {
26                let machine = (entry.build)(config).unwrap();
27                round_trip(machine.as_ref());
28                static_hold(machine.as_ref());
29                energy_conservation(machine.as_ref());
30                step_convergence(machine.as_ref());
31                determinism(machine.as_ref());
32                loss_budget(machine.as_ref());
33            });
34        }
35    });
36}
37
38/// Repeatable measurement noise from a linear congruential generator: for tests, and for the drives'
39/// sensor noise, which has to be the same in every run.
40#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
41pub struct Noise(pub u64);
42
43impl Noise {
44    /// Evenly spread from 0 up to, but not including, 1.
45    pub fn uniform(&mut self) -> f64 {
46        self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
47        (self.0 >> 11) as f64 / (1u64 << 53) as f64
48    }
49
50    /// Roughly normal with standard deviation 1: twelve uniform numbers summed.
51    #[allow(clippy::should_implement_trait)] // an endless source, not an iterator: every test calls it by this name
52    pub fn next(&mut self) -> f64 {
53        (0..12).map(|_| self.uniform()).sum::<f64>() - 6.0
54    }
55}
56
57pub fn mid_pose(m: &dyn Machine) -> Vec<f64> {
58    m.axes().iter().map(|a| 0.5 * (a.min + a.max)).collect()
59}
60
61/// Forward of inverse returns the starting pose within 1e-9, on a grid over the whole workspace: the box of the
62/// axis ranges, less the poses the machine reports it cannot go to (`Machine::unreachable`).
63pub fn round_trip(m: &dyn Machine) {
64    let axes = m.axes();
65    let (mut motors, mut back) = (vec![0.0; m.motors().len()], vec![0.0; axes.len()]);
66    let mut tried = 0;
67    for k in 0..5usize.pow(axes.len() as u32) {
68        let pose: Vec<f64> = axes
69            .iter()
70            .enumerate()
71            .map(|(i, a)| a.min + (a.max - a.min) * ((k / 5usize.pow(i as u32)) % 5) as f64 / 4.0)
72            .collect();
73        if m.unreachable(&pose, 0.0).is_some() {
74            continue;
75        }
76        tried += 1;
77        m.inverse(&pose, &mut motors);
78        m.forward(&motors, &mut back);
79        for (p, b) in pose.iter().zip(&back) {
80            assert!((p - b).abs() < 1e-9, "round trip at {pose:?} gave {back:?}");
81        }
82    }
83    assert!(2 * tried > 5usize.pow(axes.len() as u32) / 2, "only {tried} poses of the grid are in the workspace");
84}
85
86/// At the equilibrium state, under the holding torques, nothing moves for one second.
87pub fn static_hold(m: &dyn Machine) {
88    let n = m.axes().len();
89    let pose = mid_pose(m);
90    let (mut state, mut hold) = (Vec::new(), vec![0.0; m.motors().len()]);
91    m.equilibrium(&pose, &mut state, &mut hold);
92    assert_eq!(state.len(), m.state_len());
93    let mut rk = Rk4::new(state.len());
94    for _ in 0..(1.0 / DT) as usize {
95        advance(m, &mut rk, &mut state, &hold, DT, SUBSTEPS);
96    }
97    let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
98    m.tool_state(&state, &mut pos, &mut vel);
99    for i in 0..n {
100        assert!((pos[i] - pose[i]).abs() < 1e-7, "axis {i} moved from {} to {}", pose[i], pos[i]);
101        assert!(vel[i].abs() < 1e-6, "axis {i} has speed {}", vel[i]);
102    }
103}
104
105/// A run that starts at rest, gets one smooth torque pulse and then only the holding torques.
106pub struct PulseRun<'a> {
107    m: &'a dyn Machine,
108    rk: Rk4,
109    pub state: Vec<f64>,
110    pub hold: Vec<f64>,
111    /// The torques of the last step.
112    pub torque: Vec<f64>,
113    delta: Vec<f64>,
114    motor0: Vec<f64>,
115    step: usize,
116    dt: f64,
117    pulse_s: f64,
118    pub substeps: u32,
119}
120
121impl<'a> PulseRun<'a> {
122    /// The pulse is sin^2 shaped, `pulse_s` long, and asks for `acc_fraction` of each axis's
123    /// acceleration limit at its peak.
124    pub fn new(m: &'a dyn Machine, dt: f64, acc_fraction: f64, pulse_s: f64) -> Self {
125        let pose = mid_pose(m);
126        let motors = m.motors().len();
127        let (mut state, mut hold) = (Vec::new(), vec![0.0; motors]);
128        m.equilibrium(&pose, &mut state, &mut hold);
129        let acc: Vec<f64> = m.axes().iter().map(|a| acc_fraction * a.max_acc).collect();
130        let (mut with, mut without) = (vec![0.0; motors], vec![0.0; motors]);
131        m.feedforward_torque(&pose, &acc, &mut with);
132        m.feedforward_torque(&pose, &vec![0.0; acc.len()], &mut without);
133        let delta = with.iter().zip(&without).map(|(a, b)| a - b).collect();
134        let mut run = Self {
135            m,
136            rk: Rk4::new(state.len()),
137            torque: hold.clone(),
138            state,
139            hold,
140            delta,
141            motor0: vec![0.0; motors],
142            step: 0,
143            dt,
144            pulse_s,
145            substeps: SUBSTEPS,
146        };
147        run.motor0 = run.motor_pos();
148        run
149    }
150
151    fn motor_pos(&self) -> Vec<f64> {
152        let n = self.m.motors().len();
153        let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
154        self.m.motor_state(&self.state, &mut pos, &mut vel);
155        pos
156    }
157
158    pub fn tool_pos(&self) -> Vec<f64> {
159        let n = self.m.axes().len();
160        let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
161        self.m.tool_state(&self.state, &mut pos, &mut vel);
162        pos
163    }
164
165    pub fn run(&mut self, seconds: f64, mut each: impl FnMut(&Self)) {
166        for _ in 0..(seconds / self.dt).round() as usize {
167            let t = self.step as f64 * self.dt;
168            let pulse = if t < self.pulse_s { (std::f64::consts::PI * t / self.pulse_s).sin().powi(2) } else { 0.0 };
169            self.torque = self.hold.iter().zip(&self.delta).map(|(h, d)| h + d * pulse).collect();
170            advance_refined(self.m, &mut self.rk, &mut self.state, &self.torque, self.dt, self.substeps);
171            self.step += 1;
172            each(self);
173        }
174    }
175
176    /// Energy minus the work of the constant holding torques: constant once the pulse is over.
177    fn invariant(&self) -> f64 {
178        let work: f64 =
179            self.motor_pos().iter().zip(&self.motor0).zip(&self.hold).map(|((p, p0), h)| h * (p - p0)).sum();
180        self.m.energy(&self.state) - work
181    }
182}
183
184/// With friction and control off, total energy drifts less than 0.1 % over 10 s.
185/// The drift is measured against the energy the pulse put in, which is far stricter than
186/// measuring against the gravitational potential.
187pub fn energy_conservation(m: &dyn Machine) {
188    let (worst, injected) = energy_drift(m);
189    assert!(injected > 0.0, "the pulse put in no energy ({injected})");
190    assert!(worst < 1e-3 * injected, "energy drifted by {:.4} % of the {injected} J put in", 100.0 * worst / injected);
191}
192
193/// The run of `energy_conservation`: how far the energy drifted at most over the 10 s after the pulse, and what the
194/// pulse put in (J).
195pub fn energy_drift(m: &dyn Machine) -> (f64, f64) {
196    let mut run = PulseRun::new(m, DT, PULSE_ACC, PULSE_S);
197    let before = run.invariant();
198    run.run(PULSE_S, |_| {});
199    let after = run.invariant();
200    let mut worst = 0f64;
201    run.run(10.0, |r| worst = worst.max((r.invariant() - after).abs()));
202    (worst, after - before)
203}
204
205/// A run into a stop: at rest under the holding torques in the middle of the axes but axis `axis`, which stands 5 % of
206/// its range short of the end it is pushed towards, a constant push on top that asks for `acc` (signed) of its
207/// acceleration limit, for `seconds` in base steps `dt`, each cut as the machine
208/// asks (`advance_refined`), and no longer than `settle` after the first step cut (the contact and its bounce; a push
209/// held on can take a parallel machine through a singular pose). The energy less the work of the constant torques changes only by what the losses take.
210pub struct StopRun {
211    /// How far the energy less the torques' work drifted from its start at most (J).
212    pub drift: f64,
213    /// The most work the push did on the way (J).
214    pub push_work: f64,
215    /// Base steps cut finer, and all.
216    pub cut: u64,
217    pub steps: u64,
218    /// The run went to a state that is not finite (out of the kinematics), and stopped there.
219    pub broke: bool,
220}
221
222pub fn stop_run(m: &dyn Machine, axis: usize, acc: f64, dt: f64, seconds: f64, settle: f64) -> StopRun {
223    let mut pose = mid_pose(m);
224    let a = &m.axes()[axis];
225    pose[axis] = a.min + (0.5 + 0.45 * acc.signum()) * (a.max - a.min);
226    let motors = m.motors().len();
227    let (mut state, mut hold) = (Vec::new(), vec![0.0; motors]);
228    m.equilibrium(&pose, &mut state, &mut hold);
229    let mut wanted: Vec<f64> = vec![0.0; pose.len()];
230    wanted[axis] = acc * m.axes()[axis].max_acc;
231    let (mut with, mut without) = (vec![0.0; motors], vec![0.0; motors]);
232    m.feedforward_torque(&pose, &wanted, &mut with);
233    m.feedforward_torque(&pose, &vec![0.0; pose.len()], &mut without);
234    let push: Vec<f64> = with.iter().zip(&without).map(|(a, b)| a - b).collect();
235    let torque: Vec<f64> = hold.iter().zip(&push).map(|(h, p)| h + p).collect();
236    let angles = |state: &[f64]| {
237        let (mut pos, mut vel) = (vec![0.0; motors], vec![0.0; motors]);
238        m.motor_state(state, &mut pos, &mut vel);
239        pos
240    };
241    let (start, energy) = (angles(&state), m.energy(&state));
242    let work = |state: &[f64], torques: &[f64]| -> f64 {
243        angles(state).iter().zip(&start).zip(torques).map(|((a, s), t)| t * (a - s)).sum()
244    };
245    let mut rk = Rk4::new(state.len());
246    let mut out = StopRun { drift: 0.0, push_work: 0.0, cut: 0, steps: 0, broke: false };
247    let mut left = seconds;
248    while left > 0.5 * dt {
249        let cut = advance_refined(m, &mut rk, &mut state, &torque, dt, SUBSTEPS) > 1;
250        if cut && out.cut == 0 {
251            left = left.min(settle);
252        }
253        (out.cut, out.steps, left) = (out.cut + u64::from(cut), out.steps + 1, left - dt);
254        if !state.iter().all(|x| x.is_finite()) {
255            out.broke = true;
256            break;
257        }
258        out.push_work = out.push_work.max(work(&state, &push).abs());
259        out.drift = out.drift.max((m.energy(&state) - energy - work(&state, &torque)).abs());
260    }
261    out
262}
263
264/// Tolerance of `loss_budget`, as a share of the work the motor torques did either way.
265pub const LOSS_BUDGET_TOLERANCE: f64 = 1e-3;
266
267/// The energy balance with losses: over a run with a strong torque pulse, the work of the motor torques
268/// (sum of torque times rotor angle turned, exact for torques held over a step) equals the change of the
269/// machine's energy plus the time integral of every loss power it reports (signals starting with `LOSS_PREFIX`),
270/// to within `LOSS_BUDGET_TOLERANCE`. The run takes the integrator's own sub-steps (`DT / SUBSTEPS`, one each) as its
271/// steps; the powers are taken at the end of each and summed times the step, which is the trapezoid rule but for the
272/// two ends of the run. What is left is that rule's error on powers that change within a step (the bristles of a
273/// friction contact settle within microseconds when the speed reverses), and on a power that jumps, up to half of
274/// it times the step: a stop's damper takes c v^2 as soon as the axis touches it. On the linear delta, whose
275/// carriages the pulse takes into their upper stops, one touches at 0.533 m/s 1.7 us before the end of a step:
276/// 5000 N s/m * 0.533^2 = 1422 W, of which the trapezoid booked 0.5 * 1422 W * 62.5 us = 0.044 J where 0.002 J were
277/// lost, 0.042 J off against the 0.018 J allowed; on the 15.6 us sub-steps at most 0.011 J.
278/// The energy parts it reports (`energy.*`) add up to `Machine::energy`. A machine that reports no loss powers is
279/// not checked.
280pub fn loss_budget(m: &dyn Machine) {
281    let infos = m.signal_infos();
282    let pick = |prefix: &str| {
283        infos.iter().enumerate().filter(|(_, s)| s.id.starts_with(prefix)).map(|(i, _)| i).collect::<Vec<_>>()
284    };
285    let (losses, parts) = (pick(LOSS_PREFIX), pick("energy."));
286    if losses.is_empty() {
287        return;
288    }
289    assert_eq!(parts.len(), ENERGY_PARTS.len(), "the energy parts are not all reported");
290    let mut run = PulseRun::new(m, DT / SUBSTEPS as f64, 0.5, 0.1);
291    run.substeps = 1;
292    let start = m.energy(&run.state);
293    let (mut before, mut work, mut gross, mut lost, mut signals) = (run.motor_pos(), 0.0, 0.0, 0.0, Vec::new());
294    run.run(1.0, |r| {
295        let after = r.motor_pos();
296        let step: f64 = r.torque.iter().zip(after.iter().zip(&before)).map(|(t, (a, b))| t * (a - b)).sum();
297        (work, gross, before) = (work + step, gross + step.abs(), after);
298        signals.clear();
299        m.signals(&r.state, &r.torque, &mut signals);
300        lost += losses.iter().map(|&i| signals[i]).sum::<f64>() * r.dt;
301        let (energy, sum) = (m.energy(&r.state), parts.iter().map(|&i| signals[i]).sum::<f64>());
302        assert!((sum - energy).abs() <= 1e-9 * energy.abs().max(1.0), "energy parts add up to {sum}, not {energy}");
303    });
304    let stored = m.energy(&run.state) - start;
305    let off = work - stored - lost;
306    println!(
307        "loss budget: work {work:.6} J (gross {gross:.6}), stored {stored:.6} J, lost {lost:.6} J, off {off:.3e} J"
308    );
309    assert!(
310        off.abs() < LOSS_BUDGET_TOLERANCE * gross,
311        "work {work} J, stored {stored} J, lost {lost} J: off by {off} J of {gross} J"
312    );
313}
314
315/// Halving the time step changes the result by less than 1 %.
316pub fn step_convergence(m: &dyn Machine) {
317    let travel = |dt: f64| {
318        let mut run = PulseRun::new(m, dt, PULSE_ACC, PULSE_S);
319        let start = run.tool_pos();
320        run.run(1.0, |_| {});
321        run.tool_pos().iter().zip(&start).map(|(p, s)| p - s).collect::<Vec<f64>>()
322    };
323    let (coarse, fine) = (travel(DT), travel(DT / 2.0));
324    for (c, f) in coarse.iter().zip(&fine) {
325        assert!(f.abs() > 1e-6, "axis did not move, the check would be empty");
326        assert!((c - f).abs() < 0.01 * f.abs(), "step halving changed travel from {c} to {f}");
327    }
328}
329
330/// Where a machine tells its `frame_momentum`, the linear momentum is the rate of the first moment of what moves: at the
331/// middle of the axes, every axis moving at a tenth of its top speed, d/dt sum m r by central differences over +-1 us
332/// along the state's rate equals sum m v within 1e-6 of it (plus 1e-9 N s).
333pub fn frame_momentum_moves_its_first_moment(m: &dyn Machine) {
334    let pose = mid_pose(m);
335    let (mut state, mut torque) = (Vec::new(), vec![0.0; m.motors().len()]);
336    m.equilibrium(&pose, &mut state, &mut torque);
337    let Some(_) = m.frame_momentum(&state) else { return };
338    let vel: Vec<f64> = m.axes().iter().map(|a| 0.1 * a.max_vel).collect();
339    m.set_tool_velocity(&mut state, &vel);
340    let mut rate = vec![0.0; state.len()];
341    m.derivatives(&state, &torque, &mut rate);
342    let h = 1e-6;
343    let at = |s: f64| {
344        let moved: Vec<f64> = state.iter().zip(&rate).map(|(x, r)| x + s * r).collect();
345        m.frame_momentum(&moved).unwrap()
346    };
347    let (now, before, after) = (at(0.0), at(-h), at(h));
348    for k in 0..3 {
349        let moved = (after.first_moment[k] - before.first_moment[k]) / (2.0 * h);
350        assert!(
351            (moved - now.linear[k]).abs() <= 1e-6 * now.linear[k].abs() + 1e-9,
352            "{k}: the first moment moves at {moved} kg m/s, the momentum is {} N s",
353            now.linear[k]
354        );
355    }
356}
357
358/// Where a machine tells its `frame_momentum`, its weight sits at the first moment: at the middle of the axes, every
359/// axis moving at a tenth of its top speed, the potential energy (`energy.potential`) changes along the state's rate as
360/// -g . d/dt sum m r, by central differences over +-1 us, within 1e-6 of it (plus 1e-9 W). V + g . c is then the same
361/// along any motion, as it is for any body whose weight is m g at its centre of mass.
362pub fn weight_is_at_the_first_moment(m: &dyn Machine) {
363    weight_is_at_the_first_moment_at(m, &mid_pose(m));
364}
365
366/// `weight_is_at_the_first_moment` at `pose`: off the middle a part whose shape changes with the pose (a beam's mode
367/// under a carriage) moves its first moment with the pose too.
368pub fn weight_is_at_the_first_moment_at(m: &dyn Machine, pose: &[f64]) {
369    let pose = pose.to_vec();
370    let (mut state, mut torque) = (Vec::new(), vec![0.0; m.motors().len()]);
371    m.equilibrium(&pose, &mut state, &mut torque);
372    let Some(f) = m.frame_momentum(&state) else { return };
373    let potential = m.signal_infos().iter().position(|s| s.id == "energy.potential").expect("energy.potential");
374    let vel: Vec<f64> = m.axes().iter().map(|a| 0.1 * a.max_vel).collect();
375    m.set_tool_velocity(&mut state, &vel);
376    let mut rate = vec![0.0; state.len()];
377    m.derivatives(&state, &torque, &mut rate);
378    let h = 1e-6;
379    let at = |s: f64| {
380        let moved: Vec<f64> = state.iter().zip(&rate).map(|(x, r)| x + s * r).collect();
381        let mut out = Vec::new();
382        m.signals(&moved, &torque, &mut out);
383        let c = m.frame_momentum(&moved).unwrap().first_moment;
384        (out[potential], (0..3).map(|k| f.gravity[k] * c[k]).sum::<f64>())
385    };
386    let ((v0, c0), (v1, c1)) = (at(-h), at(h));
387    let (dv, dgc) = ((v1 - v0) / (2.0 * h), (c1 - c0) / (2.0 * h));
388    assert!(dgc.abs() > 1e-6, "the first moment did not move vertically, the check would be empty");
389    assert!(
390        (dv + dgc).abs() <= 1e-6 * dgc.abs() + 1e-9,
391        "the potential changes at {dv} W, the weight's -g.c at {}",
392        -dgc
393    );
394}
395
396/// The same config and the same commands give bit-identical traces.
397pub fn determinism(m: &dyn Machine) {
398    let trace = || {
399        let mut run = PulseRun::new(m, DT, PULSE_ACC, PULSE_S);
400        let mut bits = Vec::new();
401        run.run(0.1, |r| bits.extend(r.state.iter().map(|v| v.to_bits())));
402        bits
403    };
404    assert!(trace() == trace(), "two identical runs differ");
405}
406
407/// Appends one check against an outside number as a JSON line to the file `KS_VALIDATION_OUT` names, for the
408/// validation dashboard (tools/validation_dashboard.py); nothing when the variable is unset. It asserts nothing: the
409/// test's own assert stays the judge. `allowed` is the largest difference the test accepts, in the reference's unit
410/// (a relative tolerance times |reference|, or the absolute one). The test is the running thread's name, as libtest
411/// and nextest name it, and the source line is the caller's.
412#[track_caller]
413pub fn record_check(what: &str, reference: f64, simulated: f64, allowed: f64) {
414    let Some(path) = std::env::var_os("KS_VALIDATION_OUT") else { return };
415    let at = std::panic::Location::caller();
416    let thread = std::thread::current();
417    let number = |v: f64| if v.is_finite() { format!("{v:e}") } else { "null".into() };
418    let line = format!(
419        "{{\"test\":{},\"file\":{},\"line\":{},\"what\":{},\"reference\":{},\"simulated\":{},\"allowed\":{}}}\n",
420        json_string(thread.name().unwrap_or("")),
421        json_string(&at.file().replace('\\', "/")),
422        at.line(),
423        json_string(what),
424        number(reference),
425        number(simulated),
426        number(allowed),
427    );
428    // One write per line in append mode: the tests of a run write to the same file at once.
429    use std::io::Write;
430    let file = std::fs::OpenOptions::new().create(true).append(true).open(&path);
431    if let Err(e) = file.and_then(|mut f| f.write_all(line.as_bytes())) {
432        panic!("KS_VALIDATION_OUT={}: {e}", path.to_string_lossy());
433    }
434}
435
436fn json_string(s: &str) -> String {
437    let mut out = String::from("\"");
438    for c in s.chars() {
439        match c {
440            '"' => out.push_str("\\\""),
441            '\\' => out.push_str("\\\\"),
442            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
443            c => out.push(c),
444        }
445    }
446    out + "\""
447}
448
449#[cfg(test)]
450mod record_tests {
451    #[test]
452    fn a_string_is_escaped_as_json() {
453        assert_eq!(super::json_string("a\"b\\c\nd ü"), r#""a\"b\\c\u000ad ü""#);
454    }
455}