Skip to main content

xtce_decode/
calibrate.rs

1//! Calibrators: raw encoded value to engineering value.
2
3use xtce_model::{Calibrator, PolynomialTerm, Spline};
4
5/// Why a calibrator could not produce a value.
6#[derive(Clone, Debug, PartialEq, Eq)]
7pub enum CalibrationError {
8    /// The query point is outside the spline's range and extrapolation is off.
9    OutsideSplineRange,
10    /// The spline has too few points to interpolate.
11    EmptySpline,
12    /// The spline order is above 1.
13    UnsupportedOrder(u8),
14}
15
16impl std::fmt::Display for CalibrationError {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        match self {
19            Self::OutsideSplineRange => {
20                f.write_str("query point falls outside the spline points and extrapolate is false")
21            }
22            Self::EmptySpline => f.write_str("spline calibrator has no usable points"),
23            Self::UnsupportedOrder(order) => {
24                write!(f, "spline order {order} is not supported (only 0 and 1)")
25            }
26        }
27    }
28}
29
30/// The raw value handed to a calibrator.
31///
32/// Integers are kept as integers rather than widened to `f64` on the way in, because
33/// `coefficient * x.pow(n)` is evaluated exactly for integral `x` where it can be — see
34/// [`polynomial`].
35#[derive(Clone, Copy, Debug)]
36pub enum CalibrationInput {
37    /// An integer-encoded raw value.
38    Integer(i128),
39    /// A float-encoded raw value.
40    Float(f64),
41}
42
43impl CalibrationInput {
44    fn as_f64(self) -> f64 {
45        match self {
46            Self::Integer(value) => value as f64,
47            Self::Float(value) => value,
48        }
49    }
50}
51
52/// Applies a calibrator.
53///
54/// # Errors
55///
56/// Returns [`CalibrationError`] for a spline query that cannot be answered. Polynomials
57/// never fail.
58pub fn apply(calibrator: &Calibrator, input: CalibrationInput) -> Result<f64, CalibrationError> {
59    match calibrator {
60        Calibrator::Polynomial(terms) => Ok(polynomial(terms, input)),
61        Calibrator::Spline(spline) => interpolate(spline, input.as_f64()),
62        // Reaching an unsupported calibrator is a caller error; it is filtered out before
63        // this point so that the failure carries the parameter's name.
64        Calibrator::Unsupported { .. } => Ok(input.as_f64()),
65    }
66}
67
68/// Evaluates a polynomial calibrator.
69///
70/// Terms are summed in document order, not Horner's method and not sorted by exponent.
71/// Floating-point addition is neither associative nor commutative, so any reordering shifts
72/// the low bits of the result — and correctness here is defined by bit-for-bit agreement
73/// with a reference implementation that sums in document order.
74///
75/// For an integral raw value and a non-negative exponent the power is computed in `i128` and
76/// converted once, which is exactly what the Python reference does with its arbitrary-
77/// precision integers. Repeated `f64` multiplication would round at every step and drift for
78/// large values.
79#[must_use]
80pub fn polynomial(terms: &[PolynomialTerm], input: CalibrationInput) -> f64 {
81    let mut sum = 0.0f64;
82    for term in terms {
83        sum += term.coefficient * power(input, term.exponent);
84    }
85    sum
86}
87
88fn power(input: CalibrationInput, exponent: i32) -> f64 {
89    match input {
90        CalibrationInput::Integer(base) if exponent >= 0 => {
91            match u32::try_from(exponent)
92                .ok()
93                .and_then(|exponent| base.checked_pow(exponent))
94            {
95                Some(exact) => exact as f64,
96                // Overflowed `i128`; no exact route left, so fall back to floating point.
97                None => (base as f64).powi(exponent),
98            }
99        }
100        CalibrationInput::Integer(base) => (base as f64).powi(exponent),
101        CalibrationInput::Float(base) => base.powi(exponent),
102    }
103}
104
105/// Evaluates a spline calibrator at `query`.
106///
107/// # Errors
108///
109/// Returns [`CalibrationError`] when the query is out of range with extrapolation disabled,
110/// when the spline has no usable points, or for orders above 1.
111pub fn interpolate(spline: &Spline, query: f64) -> Result<f64, CalibrationError> {
112    let points = spline.points.as_slice();
113    let (Some(first), Some(last)) = (points.first(), points.last()) else {
114        return Err(CalibrationError::EmptySpline);
115    };
116
117    if query < first.raw {
118        if !spline.extrapolate {
119            return Err(CalibrationError::OutsideSplineRange);
120        }
121        return match spline.order {
122            0 => Ok(first.calibrated),
123            1 => match points.get(1) {
124                Some(second) => Ok(line(
125                    query,
126                    first.raw,
127                    second.raw,
128                    first.calibrated,
129                    second.calibrated,
130                )),
131                None => Ok(first.calibrated),
132            },
133            other => Err(CalibrationError::UnsupportedOrder(other)),
134        };
135    }
136
137    if query > last.raw {
138        if !spline.extrapolate {
139            return Err(CalibrationError::OutsideSplineRange);
140        }
141        return match spline.order {
142            0 => Ok(last.calibrated),
143            1 => match points.len().checked_sub(2).and_then(|i| points.get(i)) {
144                Some(prev) => Ok(line(
145                    query,
146                    prev.raw,
147                    last.raw,
148                    prev.calibrated,
149                    last.calibrated,
150                )),
151                None => Ok(last.calibrated),
152            },
153            other => Err(CalibrationError::UnsupportedOrder(other)),
154        };
155    }
156
157    // In range. `partition_point` gives the index of the first point strictly above the
158    // query, so the enclosing segment is `[index - 1, index]`.
159    //
160    // The reference implementation raises here when the query equals the largest raw value,
161    // because its `list.index(True)` finds no element greater than the query. That is a bug,
162    // not a specification: XTCE says the range is inclusive. This clamps to the final
163    // segment instead, which is recorded as a deliberate divergence in `SUPPORTED.md`.
164    // `hi` is the index of the first point strictly above the query. It is at least 1
165    // because `query >= first.raw` was established above — except for a NaN query, where
166    // every comparison is false, so it is floored explicitly.
167    let hi = points.partition_point(|point| point.raw <= query).max(1);
168
169    match spline.order {
170        // Nearest lower point: the last point at or below the query, which for a query
171        // sitting exactly on a point is that point itself.
172        0 => Ok(points
173            .get(hi - 1)
174            .map_or(first.calibrated, |point| point.calibrated)),
175        1 => {
176            if points.len() < 2 {
177                return Ok(first.calibrated);
178            }
179            // A query equal to the last raw value has no point above it; interpolating over
180            // the final segment evaluates to exactly that point's calibrated value.
181            let upper = hi.min(points.len() - 1);
182            let (Some(lower_point), Some(upper_point)) = (points.get(upper - 1), points.get(upper))
183            else {
184                return Ok(first.calibrated);
185            };
186            Ok(line(
187                query,
188                lower_point.raw,
189                upper_point.raw,
190                lower_point.calibrated,
191                upper_point.calibrated,
192            ))
193        }
194        other => Err(CalibrationError::UnsupportedOrder(other)),
195    }
196}
197
198/// The line through `(x0, y0)` and `(x1, y1)`, evaluated at `x`.
199fn line(x: f64, x0: f64, x1: f64, y0: f64, y1: f64) -> f64 {
200    if (x1 - x0) == 0.0 {
201        return y0;
202    }
203    let slope = (y1 - y0) / (x1 - x0);
204    slope * (x - x0) + y0
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use xtce_model::SplinePoint;
211
212    fn spline(order: u8, extrapolate: bool, points: &[(f64, f64)]) -> Spline {
213        Spline {
214            order,
215            points: points
216                .iter()
217                .map(|&(raw, calibrated)| SplinePoint { raw, calibrated })
218                .collect(),
219            extrapolate,
220        }
221    }
222
223    #[test]
224    fn polynomial_sums_in_document_order() {
225        let terms = [
226            PolynomialTerm {
227                coefficient: 1.0,
228                exponent: 0,
229            },
230            PolynomialTerm {
231                coefficient: 2.0,
232                exponent: 1,
233            },
234            PolynomialTerm {
235                coefficient: 3.0,
236                exponent: 2,
237            },
238        ];
239        assert_eq!(polynomial(&terms, CalibrationInput::Integer(2)), 17.0);
240        assert_eq!(polynomial(&terms, CalibrationInput::Float(2.0)), 17.0);
241        assert_eq!(polynomial(&[], CalibrationInput::Integer(9)), 0.0);
242    }
243
244    #[test]
245    fn integer_powers_stay_exact_beyond_the_f64_mantissa() {
246        // 2^27 squared is 2^54, one bit past the exact-integer range of f64. Computing it
247        // exactly and rounding once gives a different answer from rounding twice would.
248        let base: i128 = (1 << 27) + 1;
249        let terms = [PolynomialTerm {
250            coefficient: 1.0,
251            exponent: 2,
252        }];
253        let exact = (base * base) as f64;
254        assert_eq!(polynomial(&terms, CalibrationInput::Integer(base)), exact);
255    }
256
257    #[test]
258    fn zero_order_spline_takes_the_nearest_lower_point() {
259        let spline = spline(0, false, &[(0.0, 10.0), (10.0, 20.0), (20.0, 30.0)]);
260        assert_eq!(interpolate(&spline, 0.0), Ok(10.0));
261        assert_eq!(interpolate(&spline, 9.9), Ok(10.0));
262        assert_eq!(interpolate(&spline, 10.0), Ok(20.0));
263        assert_eq!(interpolate(&spline, 19.0), Ok(20.0));
264        // Upper bound is inclusive here, where the reference raises.
265        assert_eq!(interpolate(&spline, 20.0), Ok(30.0));
266    }
267
268    #[test]
269    fn first_order_spline_interpolates() {
270        let spline = spline(1, false, &[(0.0, 0.0), (10.0, 100.0)]);
271        assert_eq!(interpolate(&spline, 0.0), Ok(0.0));
272        assert_eq!(interpolate(&spline, 5.0), Ok(50.0));
273        assert_eq!(interpolate(&spline, 10.0), Ok(100.0));
274    }
275
276    #[test]
277    fn out_of_range_respects_extrapolate() {
278        let bounded = spline(1, false, &[(0.0, 0.0), (10.0, 100.0)]);
279        assert_eq!(
280            interpolate(&bounded, -1.0),
281            Err(CalibrationError::OutsideSplineRange)
282        );
283        assert_eq!(
284            interpolate(&bounded, 11.0),
285            Err(CalibrationError::OutsideSplineRange)
286        );
287
288        let unbounded = spline(1, true, &[(0.0, 0.0), (10.0, 100.0)]);
289        assert_eq!(interpolate(&unbounded, -1.0), Ok(-10.0));
290        assert_eq!(interpolate(&unbounded, 11.0), Ok(110.0));
291
292        let flat = spline(0, true, &[(0.0, 7.0), (10.0, 9.0)]);
293        assert_eq!(interpolate(&flat, -5.0), Ok(7.0));
294        assert_eq!(interpolate(&flat, 50.0), Ok(9.0));
295    }
296
297    #[test]
298    fn degenerate_splines_do_not_panic() {
299        assert_eq!(
300            interpolate(&spline(1, true, &[]), 1.0),
301            Err(CalibrationError::EmptySpline)
302        );
303        let single = spline(1, true, &[(5.0, 42.0)]);
304        assert_eq!(interpolate(&single, 5.0), Ok(42.0));
305        assert_eq!(interpolate(&single, 1.0), Ok(42.0));
306        assert_eq!(interpolate(&single, 9.0), Ok(42.0));
307        assert_eq!(
308            interpolate(&spline(2, true, &[(0.0, 0.0), (1.0, 1.0)]), 0.5),
309            Err(CalibrationError::UnsupportedOrder(2))
310        );
311    }
312}