use xtce_model::{Calibrator, PolynomialTerm, Spline};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CalibrationError {
OutsideSplineRange,
EmptySpline,
UnsupportedOrder(u8),
}
impl std::fmt::Display for CalibrationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::OutsideSplineRange => {
f.write_str("query point falls outside the spline points and extrapolate is false")
}
Self::EmptySpline => f.write_str("spline calibrator has no usable points"),
Self::UnsupportedOrder(order) => {
write!(f, "spline order {order} is not supported (only 0 and 1)")
}
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum CalibrationInput {
Integer(i128),
Float(f64),
}
impl CalibrationInput {
fn as_f64(self) -> f64 {
match self {
Self::Integer(value) => value as f64,
Self::Float(value) => value,
}
}
}
pub fn apply(calibrator: &Calibrator, input: CalibrationInput) -> Result<f64, CalibrationError> {
match calibrator {
Calibrator::Polynomial(terms) => Ok(polynomial(terms, input)),
Calibrator::Spline(spline) => interpolate(spline, input.as_f64()),
Calibrator::Unsupported { .. } => Ok(input.as_f64()),
}
}
#[must_use]
pub fn polynomial(terms: &[PolynomialTerm], input: CalibrationInput) -> f64 {
let mut sum = 0.0f64;
for term in terms {
sum += term.coefficient * power(input, term.exponent);
}
sum
}
fn power(input: CalibrationInput, exponent: i32) -> f64 {
match input {
CalibrationInput::Integer(base) if exponent >= 0 => {
match u32::try_from(exponent)
.ok()
.and_then(|exponent| base.checked_pow(exponent))
{
Some(exact) => exact as f64,
None => (base as f64).powi(exponent),
}
}
CalibrationInput::Integer(base) => (base as f64).powi(exponent),
CalibrationInput::Float(base) => base.powi(exponent),
}
}
pub fn interpolate(spline: &Spline, query: f64) -> Result<f64, CalibrationError> {
let points = spline.points.as_slice();
let (Some(first), Some(last)) = (points.first(), points.last()) else {
return Err(CalibrationError::EmptySpline);
};
if query < first.raw {
if !spline.extrapolate {
return Err(CalibrationError::OutsideSplineRange);
}
return match spline.order {
0 => Ok(first.calibrated),
1 => match points.get(1) {
Some(second) => Ok(line(
query,
first.raw,
second.raw,
first.calibrated,
second.calibrated,
)),
None => Ok(first.calibrated),
},
other => Err(CalibrationError::UnsupportedOrder(other)),
};
}
if query > last.raw {
if !spline.extrapolate {
return Err(CalibrationError::OutsideSplineRange);
}
return match spline.order {
0 => Ok(last.calibrated),
1 => match points.len().checked_sub(2).and_then(|i| points.get(i)) {
Some(prev) => Ok(line(
query,
prev.raw,
last.raw,
prev.calibrated,
last.calibrated,
)),
None => Ok(last.calibrated),
},
other => Err(CalibrationError::UnsupportedOrder(other)),
};
}
let hi = points.partition_point(|point| point.raw <= query).max(1);
match spline.order {
0 => Ok(points
.get(hi - 1)
.map_or(first.calibrated, |point| point.calibrated)),
1 => {
if points.len() < 2 {
return Ok(first.calibrated);
}
let upper = hi.min(points.len() - 1);
let (Some(lower_point), Some(upper_point)) = (points.get(upper - 1), points.get(upper))
else {
return Ok(first.calibrated);
};
Ok(line(
query,
lower_point.raw,
upper_point.raw,
lower_point.calibrated,
upper_point.calibrated,
))
}
other => Err(CalibrationError::UnsupportedOrder(other)),
}
}
fn line(x: f64, x0: f64, x1: f64, y0: f64, y1: f64) -> f64 {
if (x1 - x0) == 0.0 {
return y0;
}
let slope = (y1 - y0) / (x1 - x0);
slope * (x - x0) + y0
}
#[cfg(test)]
mod tests {
use super::*;
use xtce_model::SplinePoint;
fn spline(order: u8, extrapolate: bool, points: &[(f64, f64)]) -> Spline {
Spline {
order,
points: points
.iter()
.map(|&(raw, calibrated)| SplinePoint { raw, calibrated })
.collect(),
extrapolate,
}
}
#[test]
fn polynomial_sums_in_document_order() {
let terms = [
PolynomialTerm {
coefficient: 1.0,
exponent: 0,
},
PolynomialTerm {
coefficient: 2.0,
exponent: 1,
},
PolynomialTerm {
coefficient: 3.0,
exponent: 2,
},
];
assert_eq!(polynomial(&terms, CalibrationInput::Integer(2)), 17.0);
assert_eq!(polynomial(&terms, CalibrationInput::Float(2.0)), 17.0);
assert_eq!(polynomial(&[], CalibrationInput::Integer(9)), 0.0);
}
#[test]
fn integer_powers_stay_exact_beyond_the_f64_mantissa() {
let base: i128 = (1 << 27) + 1;
let terms = [PolynomialTerm {
coefficient: 1.0,
exponent: 2,
}];
let exact = (base * base) as f64;
assert_eq!(polynomial(&terms, CalibrationInput::Integer(base)), exact);
}
#[test]
fn zero_order_spline_takes_the_nearest_lower_point() {
let spline = spline(0, false, &[(0.0, 10.0), (10.0, 20.0), (20.0, 30.0)]);
assert_eq!(interpolate(&spline, 0.0), Ok(10.0));
assert_eq!(interpolate(&spline, 9.9), Ok(10.0));
assert_eq!(interpolate(&spline, 10.0), Ok(20.0));
assert_eq!(interpolate(&spline, 19.0), Ok(20.0));
assert_eq!(interpolate(&spline, 20.0), Ok(30.0));
}
#[test]
fn first_order_spline_interpolates() {
let spline = spline(1, false, &[(0.0, 0.0), (10.0, 100.0)]);
assert_eq!(interpolate(&spline, 0.0), Ok(0.0));
assert_eq!(interpolate(&spline, 5.0), Ok(50.0));
assert_eq!(interpolate(&spline, 10.0), Ok(100.0));
}
#[test]
fn out_of_range_respects_extrapolate() {
let bounded = spline(1, false, &[(0.0, 0.0), (10.0, 100.0)]);
assert_eq!(
interpolate(&bounded, -1.0),
Err(CalibrationError::OutsideSplineRange)
);
assert_eq!(
interpolate(&bounded, 11.0),
Err(CalibrationError::OutsideSplineRange)
);
let unbounded = spline(1, true, &[(0.0, 0.0), (10.0, 100.0)]);
assert_eq!(interpolate(&unbounded, -1.0), Ok(-10.0));
assert_eq!(interpolate(&unbounded, 11.0), Ok(110.0));
let flat = spline(0, true, &[(0.0, 7.0), (10.0, 9.0)]);
assert_eq!(interpolate(&flat, -5.0), Ok(7.0));
assert_eq!(interpolate(&flat, 50.0), Ok(9.0));
}
#[test]
fn degenerate_splines_do_not_panic() {
assert_eq!(
interpolate(&spline(1, true, &[]), 1.0),
Err(CalibrationError::EmptySpline)
);
let single = spline(1, true, &[(5.0, 42.0)]);
assert_eq!(interpolate(&single, 5.0), Ok(42.0));
assert_eq!(interpolate(&single, 1.0), Ok(42.0));
assert_eq!(interpolate(&single, 9.0), Ok(42.0));
assert_eq!(
interpolate(&spline(2, true, &[(0.0, 0.0), (1.0, 1.0)]), 0.5),
Err(CalibrationError::UnsupportedOrder(2))
);
}
}