1use serde::{Deserialize, Serialize};
5
6#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
8pub struct CurveSample {
9 pub t_ms: f64,
10 pub value: f64,
11}
12
13#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
15pub struct CurveTrace {
16 pub component: String,
17 pub property: String,
18 pub samples: Vec<CurveSample>,
19}
20
21impl CurveTrace {
22 pub fn new(component: impl Into<String>, property: impl Into<String>) -> Self {
23 Self {
24 component: component.into(),
25 property: property.into(),
26 samples: Vec::new(),
27 }
28 }
29
30 pub fn push(&mut self, t_ms: f64, value: f64) {
31 self.samples.push(CurveSample { t_ms, value });
32 }
33
34 pub fn sample_at(&self, t_ms: f64) -> Option<f64> {
36 if self.samples.is_empty() {
37 return None;
38 }
39 if t_ms <= self.samples[0].t_ms || self.samples.len() == 1 {
40 return Some(self.samples[0].value);
41 }
42 for w in self.samples.windows(2) {
43 if t_ms <= w[1].t_ms {
44 let dt = (w[1].t_ms - w[0].t_ms).max(1e-9);
45 let frac = ((t_ms - w[0].t_ms) / dt).clamp(0.0, 1.0);
46 return Some(w[0].value + (w[1].value - w[0].value) * frac);
47 }
48 }
49 self.samples.last().map(|s| s.value)
50 }
51
52 pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
53 serde_json::to_string_pretty(self)
54 }
55}
56
57pub fn max_curve_error_pct(actual: &CurveTrace, expected: &CurveTrace) -> f64 {
62 if expected.samples.is_empty() || actual.samples.is_empty() {
63 return 100.0;
64 }
65 let min_v = expected
66 .samples
67 .iter()
68 .map(|s| s.value)
69 .fold(f64::INFINITY, f64::min);
70 let max_v = expected
71 .samples
72 .iter()
73 .map(|s| s.value)
74 .fold(f64::NEG_INFINITY, f64::max);
75 let span = (max_v - min_v).abs().max(1.0);
76
77 let mut max_err = 0.0_f64;
78 for ref_sample in &expected.samples {
79 if let Some(actual_val) = actual.sample_at(ref_sample.t_ms) {
80 let err_pct = ((actual_val - ref_sample.value).abs() / span) * 100.0;
81 max_err = max_err.max(err_pct);
82 }
83 }
84 max_err
85}
86
87#[cfg(test)]
88mod tests {
89 use super::*;
90
91 #[test]
92 fn curve_error_comparator_reports_normalized_percentage() {
93 let mut expected = CurveTrace::new("switch", "thumb_x");
94 let mut actual = CurveTrace::new("switch", "thumb_x");
95 for i in 0..=10 {
96 let t = i as f64 * 16.0;
97 let v = i as f64 * 1.8; expected.push(t, v);
99 actual.push(t, v + 0.36); }
101 let err = max_curve_error_pct(&actual, &expected);
102 assert!((err - 2.0).abs() < 1e-6);
103 assert!(err < 5.0);
104 }
105}