1use crate::control::Command;
4use crate::sim::Sim;
5use sim_core::{Config, ConfigError, MachineEntry, MotorInfo};
6
7#[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
20pub 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
42pub 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 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
69pub const PER_AXIS_SPREAD: f64 = 0.05;
78
79#[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 pub tool_rates: Vec<[Vec<f64>; 2]>,
102}
103
104pub 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
130pub 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 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 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 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
195pub const RUN_UP_S: f64 = 0.25;
198
199pub fn replay(entry: &MachineEntry, cfg: &Config, trace: &Trace) -> Result<Trace, TraceError> {
219 let mut cfg = cfg.clone();
223 cfg.set_text("profile.trajectory_spline = \"hermite\"")?;
224 let rows = trace.time.len();
225 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 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 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 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 let rest = sim.control.planned_pos().to_vec();
265 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 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 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 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
329fn slopes(points: &[(f64, Vec<f64>)], k: usize) -> [Vec<f64>; 2] {
338 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), ×);
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
366fn 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
394pub 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
405pub 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
427pub 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 #[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}