1use xtce_model::{Calibrator, PolynomialTerm, Spline};
4
5#[derive(Clone, Debug, PartialEq, Eq)]
7pub enum CalibrationError {
8 OutsideSplineRange,
10 EmptySpline,
12 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#[derive(Clone, Copy, Debug)]
36pub enum CalibrationInput {
37 Integer(i128),
39 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
52pub 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 Calibrator::Unsupported { .. } => Ok(input.as_f64()),
65 }
66}
67
68#[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 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
105pub 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 let hi = points.partition_point(|point| point.raw <= query).max(1);
168
169 match spline.order {
170 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 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
198fn 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 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 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}