Skip to main content

cal_model/
conversion.rs

1//! The COMPU_METHOD conversion model: raw ↔ physical, in both directions.
2//!
3//! An A2L `COMPU_METHOD` is a pure function of the raw value stored in ECU
4//! memory. `a2l_parse` retains the *declaration* (conversion type,
5//! coefficients, `COMPU_TAB_REF`); this module turns that declaration into
6//! an evaluator ([`CompuMethod::apply`]) and — the part every calibration
7//! tool actually needs — an inverter ([`CompuMethod::invert`]).
8//!
9//! # Inversion is where the interesting failures live
10//!
11//! `to_raw` is not simply "undo the arithmetic". A physical value is only
12//! writable if the raw value that produces it exists inside the deposit's
13//! datatype range, so [`CompuMethod::invert`] takes the raw bounds
14//! (`value_min`, `value_max`) and reports [`CalError::OutOfBounds`] when the
15//! target is not bracketed by them. That is the check that stops a
16//! calibration engineer from writing a value the ECU would latch as
17//! something else entirely.
18//!
19//! # TABLE conversions
20//!
21//! `a2l_parse` retains the `COMPU_TAB_REF` *name* but not the `COMPU_TAB`
22//! points (the ASAP2 format stores them in a separate block, which the L1
23//! parser skips as an unknown sub-block). [`CompuMethod::Table`] therefore
24//! carries an empty point list until the points are registered on the
25//! project ([`CalibrationProject::register_table`](crate::CalibrationProject::register_table))
26//! or set directly. [`CompuMethod::apply`] stays **total** on an empty
27//! table (it falls back to the identity function); it is
28//! [`CalibrationProject`](crate::CalibrationProject) — the layer that knows
29//! the project — that refuses to resolve a table with no points, so an
30//! unresolvable conversion is a typed error rather than a silently wrong
31//! number.
32
33use crate::CalError;
34use std::collections::BTreeMap;
35
36/// Bisection steps used to invert a rational conversion. 128 halvings of a
37/// 32-bit raw range land far below the 1e-9 tolerance the rest of the stack
38/// works to.
39const BISECTION_STEPS: usize = 128;
40
41/// A raw ↔ physical conversion, driven by an A2L `COMPU_METHOD`.
42#[derive(Debug, Clone, PartialEq)]
43pub enum CompuMethod {
44    /// `IDENTITY` (also spelled `IDENTICAL`): `f(x) = x`.
45    Identity,
46    /// `LINEAR` — `f(x) = slope · x + intercept`.
47    Linear {
48        /// Multiplicative term (`COEFFS_LINEAR` `a`).
49        slope: f64,
50        /// Additive term (`COEFFS_LINEAR` `b`).
51        intercept: f64,
52    },
53    /// `RAT_FUNC` — `f(x) = (a·x² + b·x + c) / (d·x² + e·x + f)`, the six
54    /// `COEFFS` in the spec's own notation. Reducible-linear forms (the
55    /// common case, `d = e = a = 0`) are evaluated as written, which is
56    /// both faster and free of any reduction's rounding.
57    RatFunc {
58        /// `COEFFS a b c d e f`.
59        coeffs: [f64; 6],
60    },
61    /// `TABLE` — a conversion through tabulated points. `points` are
62    /// `(raw, physical)` pairs ascending by raw; `interpolate` is `true` for
63    /// `TAB_INTP` (piecewise-linear, the ASAP2 default) and `false` for
64    /// `TAB_NOINTP`/`TAB_VERB` (step lookup, nearest point wins).
65    Table {
66        /// The `COMPU_TAB_REF` name, when the declaration carried one.
67        tab_ref: Option<String>,
68        /// `(raw, physical)` points, ascending by raw.
69        points: Vec<(f64, f64)>,
70        /// `TAB_INTP` interpolation (`true`) or step lookup (`false`).
71        interpolate: bool,
72    },
73}
74
75impl CompuMethod {
76    /// `IDENTITY` — the passthrough conversion.
77    #[must_use]
78    pub const fn identity() -> Self {
79        Self::Identity
80    }
81
82    /// `LINEAR` — `f(x) = slope · x + intercept`.
83    #[must_use]
84    pub const fn linear(slope: f64, intercept: f64) -> Self {
85        Self::Linear { slope, intercept }
86    }
87
88    /// `RAT_FUNC` — `f(x) = (a·x² + b·x + c) / (d·x² + e·x + f)`.
89    #[must_use]
90    pub const fn rat_func(coeffs: [f64; 6]) -> Self {
91        Self::RatFunc { coeffs }
92    }
93
94    /// `TAB_INTP` — an interpolated table conversion.
95    #[must_use]
96    pub fn tab_intp(points: Vec<(f64, f64)>) -> Self {
97        Self::Table {
98            tab_ref: None,
99            points,
100            interpolate: true,
101        }
102    }
103
104    /// `TAB_NOINTP`/`TAB_VERB` — a stepped table conversion.
105    #[must_use]
106    pub fn tab_no_intp(points: Vec<(f64, f64)>) -> Self {
107        Self::Table {
108            tab_ref: None,
109            points,
110            interpolate: false,
111        }
112    }
113
114    /// Build the conversion carried by an [`a2l_parse::CompuMethod`].
115    ///
116    /// A `TABLE` declaration arrives with its `COMPU_TAB_REF` name and an
117    /// empty point list; the points are registered on the project.
118    #[must_use]
119    pub fn from_a2l(method: &a2l_parse::CompuMethod) -> Self {
120        match method.conversion_type {
121            a2l_parse::ConversionType::Identity => Self::Identity,
122            a2l_parse::ConversionType::Linear => match method.coeffs {
123                a2l_parse::Coeffs::Linear([slope, intercept]) => Self::Linear { slope, intercept },
124                // A LINEAR method without COEFFS_LINEAR: the format requires
125                // the keyword, but a sloppy generator omits it. a2l_parse
126                // models that as Coeffs::None; identity is the only reading
127                // that cannot invent a wrong scale.
128                _ => Self::Identity,
129            },
130            a2l_parse::ConversionType::RatFunc => match method.coeffs {
131                a2l_parse::Coeffs::RatFunc(coeffs) => Self::RatFunc { coeffs },
132                _ => Self::Identity,
133            },
134            a2l_parse::ConversionType::Table => Self::Table {
135                tab_ref: method.tab_ref.clone(),
136                points: Vec::new(),
137                interpolate: true,
138            },
139        }
140    }
141
142    /// The A2L conversion-type keyword this method came from
143    /// (`LINEAR`, `RAT_FUNC`, `TABLE`, `IDENTITY`).
144    #[must_use]
145    pub const fn keyword(&self) -> &'static str {
146        match self {
147            Self::Identity => "IDENTITY",
148            Self::Linear { .. } => "LINEAR",
149            Self::RatFunc { .. } => "RAT_FUNC",
150            Self::Table { .. } => "TABLE",
151        }
152    }
153
154    /// The tabulated points, empty for every non-`TABLE` method.
155    #[must_use]
156    pub fn points(&self) -> &[(f64, f64)] {
157        match self {
158            Self::Table { points, .. } => points,
159            _ => &[],
160        }
161    }
162
163    /// The `COMPU_TAB_REF` name, when the declaration carried one.
164    #[must_use]
165    pub fn tab_ref(&self) -> Option<&str> {
166        match self {
167            Self::Table { tab_ref, .. } => tab_ref.as_deref(),
168            _ => None,
169        }
170    }
171
172    /// `true` for the passthrough conversion.
173    #[must_use]
174    pub const fn is_identity(&self) -> bool {
175        matches!(self, Self::Identity)
176    }
177
178    /// Replace the point list of a `TABLE` method (a no-op otherwise).
179    pub fn set_points(&mut self, points: Vec<(f64, f64)>) {
180        if let Self::Table { points: slot, .. } = self {
181            *slot = points;
182        }
183    }
184
185    /// Fill in the points of a `TABLE` method from the project's table
186    /// registry when it carries none of its own.
187    ///
188    /// # Errors
189    ///
190    /// [`CalError::Unsupported`] when a `TABLE` conversion cannot be
191    /// resolved: no points of its own and no registered `COMPU_TAB_REF`.
192    pub fn resolved(&self, tables: &BTreeMap<String, Vec<(f64, f64)>>) -> Result<Self, CalError> {
193        let Self::Table {
194            tab_ref,
195            points,
196            interpolate,
197        } = self
198        else {
199            return Ok(self.clone());
200        };
201        if !points.is_empty() {
202            return Ok(self.clone());
203        }
204        let Some(name) = tab_ref else {
205            return Err(CalError::Unsupported {
206                subject: "TABLE conversion".to_string(),
207                reason: "no points and no COMPU_TAB_REF to resolve them from".to_string(),
208            });
209        };
210        let Some(found) = tables.get(name.as_str()) else {
211            return Err(CalError::Unsupported {
212                subject: format!("COMPU_TAB_REF `{name}`"),
213                reason: "no table registered under that name".to_string(),
214            });
215        };
216        if found.is_empty() {
217            return Err(CalError::Unsupported {
218                subject: format!("COMPU_TAB_REF `{name}`"),
219                reason: "the registered table has no points".to_string(),
220            });
221        }
222        Ok(Self::Table {
223            tab_ref: tab_ref.clone(),
224            points: found.clone(),
225            interpolate: *interpolate,
226        })
227    }
228
229    /// Evaluate the conversion: raw value in, physical value out.
230    ///
231    /// Total — no input panics and every variant is a plain evaluation. A
232    /// `TABLE` with no points evaluates as the identity; use
233    /// [`CompuMethod::resolved`] first when completeness matters.
234    #[must_use]
235    pub fn apply(&self, raw: f64) -> f64 {
236        match self {
237            Self::Identity => raw,
238            Self::Linear { slope, intercept } => slope * raw + intercept,
239            Self::RatFunc { coeffs } => {
240                let [a, b, c, d, e, f] = *coeffs;
241                // f64 division by zero is infinity/NaN, never a panic: a
242                // degenerate denominator yields a non-finite physical value,
243                // which every caller rejects through its limit check.
244                let x = raw;
245                (a * x * x + b * x + c) / (d * x * x + e * x + f)
246            }
247            Self::Table {
248                points,
249                interpolate,
250                ..
251            } => table_apply(points, *interpolate, raw),
252        }
253    }
254
255    /// Invert the conversion: physical value in, raw value out, bracketed
256    /// by the deposit's raw bounds `value_min`/`value_max` (in physical
257    /// units, after sign extension).
258    ///
259    /// * `IDENTITY` and `LINEAR` are closed-form (a zero slope is not
260    ///   invertible and is reported as [`CalError::Unsupported`]).
261    /// * `RAT_FUNC` is inverted by bisection over `[value_min, value_max]`,
262    ///   which needs no derivative and is exact to well under one raw count
263    ///   across the whole 64-bit range.
264    /// * `TABLE` inverts segment-wise, linearly for `TAB_INTP` and by
265    ///   nearest point for a stepped table.
266    ///
267    /// `name` is the characteristic the inversion is for; it appears in the
268    /// error so a session log says which parameter failed.
269    ///
270    /// # Errors
271    ///
272    /// [`CalError::Unsupported`] when the conversion is not invertible (zero
273    /// slope, or a `TABLE` with no points), [`CalError::OutOfBounds`] when
274    /// the physical value is not produced anywhere inside
275    /// `[value_min, value_max]`.
276    pub fn invert(
277        &self,
278        name: &str,
279        physical: f64,
280        value_min: f64,
281        value_max: f64,
282    ) -> Result<f64, CalError> {
283        match self {
284            Self::Identity => in_range(name, physical, value_min, value_max),
285            Self::Linear { slope, intercept } => {
286                if *slope == 0.0 || !slope.is_finite() {
287                    return Err(CalError::Unsupported {
288                        subject: format!("`{name}`"),
289                        reason: format!("linear conversion with slope {slope} is not invertible"),
290                    });
291                }
292                in_range(name, (physical - intercept) / slope, value_min, value_max)
293            }
294            Self::RatFunc { .. } => bisect(self, name, physical, value_min, value_max),
295            Self::Table {
296                points,
297                interpolate,
298                ..
299            } => table_invert(points, *interpolate, name, physical, value_min, value_max),
300        }
301    }
302}
303
304/// Range-check a computed raw value against the deposit bounds.
305fn in_range(name: &str, raw: f64, value_min: f64, value_max: f64) -> Result<f64, CalError> {
306    if !raw.is_finite() || raw < value_min || raw > value_max {
307        return Err(CalError::OutOfBounds {
308            name: name.to_string(),
309            value: raw,
310            lower: value_min,
311            upper: value_max,
312        });
313    }
314    Ok(raw)
315}
316
317/// Bisection inversion of a conversion that is monotone on the bracket.
318fn bisect(
319    method: &CompuMethod,
320    name: &str,
321    physical: f64,
322    value_min: f64,
323    value_max: f64,
324) -> Result<f64, CalError> {
325    let mut lo = value_min;
326    let mut hi = value_max;
327    let y_lo = method.apply(lo);
328    let y_hi = method.apply(hi);
329    if !y_lo.is_finite() || !y_hi.is_finite() {
330        return Err(CalError::Unsupported {
331            subject: format!("`{name}`"),
332            reason: "rational conversion is not finite at the deposit bounds".to_string(),
333        });
334    }
335    // Bisection needs the target *between* the endpoint values, whichever
336    // way the conversion runs. A descending conversion is searched by
337    // comparing against the reversed endpoint, not by swapping the bracket:
338    // the raw axis stays ascending throughout.
339    let descending = y_lo > y_hi;
340    let low_physical = if descending { y_hi } else { y_lo };
341    let high_physical = if descending { y_lo } else { y_hi };
342    if physical < low_physical || physical > high_physical {
343        return Err(CalError::OutOfBounds {
344            name: name.to_string(),
345            value: physical,
346            lower: low_physical,
347            upper: high_physical,
348        });
349    }
350    for _ in 0..BISECTION_STEPS {
351        let mid = lo.midpoint(hi);
352        if hi - lo <= 1e-9 * mid.abs().max(1.0) {
353            break;
354        }
355        let below = if descending {
356            method.apply(mid) > physical
357        } else {
358            method.apply(mid) < physical
359        };
360        if below {
361            lo = mid;
362        } else {
363            hi = mid;
364        }
365    }
366    Ok(lo.midpoint(hi))
367}
368
369/// Piecewise evaluation of a tabulated conversion; identity when empty.
370fn table_apply(points: &[(f64, f64)], interpolate: bool, raw: f64) -> f64 {
371    let Some(&(first_x, first_y)) = points.first() else {
372        return raw;
373    };
374    if raw <= first_x {
375        return first_y;
376    }
377    let Some(&(last_x, last_y)) = points.last() else {
378        return raw;
379    };
380    if raw >= last_x {
381        return last_y;
382    }
383    // Points are ascending by raw (validated on registration), so the
384    // bracketing segment is found by a single linear scan. The upper end is
385    // half-open so a raw value sitting exactly on a breakpoint takes the
386    // *later* point — which is what a step lookup means, and what makes
387    // interpolation continuous across the breakpoint.
388    for pair in points.windows(2) {
389        let [first, second] = pair else { continue };
390        let (x0, y0) = *first;
391        let (x1, y1) = *second;
392        if raw >= x0 && raw < x1 {
393            if !interpolate {
394                // `TAB_NOINTP` holds the segment's *lower* tabulated value
395                // across the whole segment, switching to the next point at
396                // its own breakpoint — the step the name describes.
397                return y0;
398            }
399            let span = x1 - x0;
400            if span == 0.0 {
401                return y0;
402            }
403            return y0 + (y1 - y0) * (raw - x0) / span;
404        }
405    }
406    first_y
407}
408
409/// Segment-wise inversion of a tabulated conversion.
410fn table_invert(
411    points: &[(f64, f64)],
412    interpolate: bool,
413    name: &str,
414    physical: f64,
415    value_min: f64,
416    value_max: f64,
417) -> Result<f64, CalError> {
418    if points.is_empty() {
419        return Err(CalError::Unsupported {
420            subject: format!("`{name}`"),
421            reason: "TABLE conversion has no points to invert".to_string(),
422        });
423    }
424    let lowest = points
425        .iter()
426        .map(|&(_, phys)| phys)
427        .fold(f64::INFINITY, f64::min);
428    let highest = points
429        .iter()
430        .map(|&(_, phys)| phys)
431        .fold(f64::NEG_INFINITY, f64::max);
432    if !physical.is_finite() || physical < lowest || physical > highest {
433        return Err(CalError::OutOfBounds {
434            name: name.to_string(),
435            value: physical,
436            lower: lowest,
437            upper: highest,
438        });
439    }
440    if !interpolate {
441        // The inverse of a step function is the step's own lower breakpoint:
442        // the largest tabulated point whose value is still at or below the
443        // target (the mirror of `table_apply`'s `y0`). `points` is non-empty
444        // here — the early return above guarantees it.
445        let Some(&first) = points.first() else {
446            return Err(CalError::Unsupported {
447                subject: format!("`{name}`"),
448                reason: "TABLE conversion has no points to invert".to_string(),
449            });
450        };
451        let mut best = first;
452        for &point in points {
453            if point.1 <= physical {
454                best = point;
455            }
456        }
457        if physical < best.1 {
458            // Below the first step: clamp to the domain's first point.
459            best = first;
460        }
461        return in_range(name, best.0, value_min, value_max);
462    }
463    // Ascending tables invert segment-wise; a descending or non-monotone
464    // table still resolves, because every bracketing pair is examined and
465    // the one whose round trip is most accurate wins.
466    let mut best_raw: Option<f64> = None;
467    let mut best_error = f64::INFINITY;
468    for pair in points.windows(2) {
469        let [first, second] = pair else { continue };
470        let (x0, y0) = *first;
471        let (x1, y1) = *second;
472        let (low_y, high_y) = if y0 <= y1 { (y0, y1) } else { (y1, y0) };
473        if physical < low_y || physical > high_y {
474            continue;
475        }
476        let span = y1 - y0;
477        let raw = if span == 0.0 {
478            x0
479        } else {
480            x0 + (physical - y0) * (x1 - x0) / span
481        };
482        let error = (table_apply(points, interpolate, raw) - physical).abs();
483        if error < best_error {
484            best_error = error;
485            best_raw = Some(raw);
486        }
487    }
488    let Some(raw) = best_raw else {
489        return Err(CalError::OutOfBounds {
490            name: name.to_string(),
491            value: physical,
492            lower: lowest,
493            upper: highest,
494        });
495    };
496    in_range(name, raw, value_min, value_max)
497}