use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct CurveSample {
pub t_ms: f64,
pub value: f64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CurveTrace {
pub component: String,
pub property: String,
pub samples: Vec<CurveSample>,
}
impl CurveTrace {
pub fn new(component: impl Into<String>, property: impl Into<String>) -> Self {
Self {
component: component.into(),
property: property.into(),
samples: Vec::new(),
}
}
pub fn push(&mut self, t_ms: f64, value: f64) {
self.samples.push(CurveSample { t_ms, value });
}
pub fn sample_at(&self, t_ms: f64) -> Option<f64> {
if self.samples.is_empty() {
return None;
}
if t_ms <= self.samples[0].t_ms || self.samples.len() == 1 {
return Some(self.samples[0].value);
}
for w in self.samples.windows(2) {
if t_ms <= w[1].t_ms {
let dt = (w[1].t_ms - w[0].t_ms).max(1e-9);
let frac = ((t_ms - w[0].t_ms) / dt).clamp(0.0, 1.0);
return Some(w[0].value + (w[1].value - w[0].value) * frac);
}
}
self.samples.last().map(|s| s.value)
}
pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(self)
}
}
pub fn max_curve_error_pct(actual: &CurveTrace, expected: &CurveTrace) -> f64 {
if expected.samples.is_empty() || actual.samples.is_empty() {
return 100.0;
}
let min_v = expected
.samples
.iter()
.map(|s| s.value)
.fold(f64::INFINITY, f64::min);
let max_v = expected
.samples
.iter()
.map(|s| s.value)
.fold(f64::NEG_INFINITY, f64::max);
let span = (max_v - min_v).abs().max(1.0);
let mut max_err = 0.0_f64;
for ref_sample in &expected.samples {
if let Some(actual_val) = actual.sample_at(ref_sample.t_ms) {
let err_pct = ((actual_val - ref_sample.value).abs() / span) * 100.0;
max_err = max_err.max(err_pct);
}
}
max_err
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn curve_error_comparator_reports_normalized_percentage() {
let mut expected = CurveTrace::new("switch", "thumb_x");
let mut actual = CurveTrace::new("switch", "thumb_x");
for i in 0..=10 {
let t = i as f64 * 16.0;
let v = i as f64 * 1.8; expected.push(t, v);
actual.push(t, v + 0.36); }
let err = max_curve_error_pct(&actual, &expected);
assert!((err - 2.0).abs() < 1e-6);
assert!(err < 5.0);
}
}