Skip to main content

reserving_kernels/
types.rs

1//! Prevalidated columnar triangle inputs.
2//!
3//! A loss-development triangle is an `n_origins × n_devs` grid of cumulative
4//! amounts (paid or incurred). Cell `(i, j)` is observed iff `i + j ≤ n - 1`
5//! for a square triangle. Unobserved cells are represented as `NaN` so the
6//! compute kernels stay branch-light — null-handling lives at the ingress
7//! boundary (see [`crate::validate`]).
8
9use std::fmt;
10
11use crate::validate::{ValidationError, validate_triangle};
12
13/// Deserialize a `Vec<f64>` where JSON `null` values map back to `f64::NAN`,
14/// enabling lossless `serde_json` round-trips for triangles containing `NaN`
15/// sentinels in unobserved cells.
16fn deserialize_vec_f64_null_as_nan<'de, D>(deserializer: D) -> Result<Vec<f64>, D::Error>
17where
18    D: serde::Deserializer<'de>,
19{
20    use serde::Deserialize;
21    let opts: Vec<Option<f64>> = Vec::deserialize(deserializer)?;
22    Ok(opts.into_iter().map(|v| v.unwrap_or(f64::NAN)).collect())
23}
24
25#[derive(serde::Deserialize)]
26struct RawTriangle {
27    n_origins: usize,
28    n_devs: usize,
29    #[serde(deserialize_with = "deserialize_vec_f64_null_as_nan")]
30    data: Vec<f64>,
31}
32
33impl TryFrom<RawTriangle> for Triangle {
34    type Error = ValidationError;
35
36    fn try_from(raw: RawTriangle) -> Result<Self, Self::Error> {
37        Self::try_new(raw.n_origins, raw.n_devs, raw.data)
38    }
39}
40
41/// An `n_origins × n_devs` cumulative loss triangle in row-major layout.
42///
43/// `data[i * n_devs + j]` is the cumulative loss for origin `i` at
44/// development age `j`. Unobserved cells are `NaN`. The kernels assume the
45/// triangle is *square* (`n_origins == n_devs`) and that cell `(i, j)` is
46/// observed for `i + j ≤ n - 1`.
47///
48/// Equality (`PartialEq`) treats two `NaN` cells at the same position as equal
49/// so `tri == tri.clone()` holds for triangles with unobserved cells.
50/// Deserialization maps JSON `null` to `NaN` and validates via [`Self::try_new`].
51#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
52#[serde(try_from = "RawTriangle")]
53pub struct Triangle {
54    n_origins: usize,
55    n_devs: usize,
56    data: Vec<f64>,
57}
58
59impl PartialEq for Triangle {
60    fn eq(&self, other: &Self) -> bool {
61        self.view() == other.view()
62    }
63}
64
65impl Triangle {
66    /// Construct a triangle from a row-major slice without validation.
67    ///
68    /// Callers must ensure `data.len() == n_origins * n_devs`. Use
69    /// [`Self::try_new`] at external ingress boundaries when full validation
70    /// (square, finite, non-negative observed cells) is required.
71    #[inline]
72    pub fn new(n_origins: usize, n_devs: usize, data: Vec<f64>) -> Self {
73        debug_assert_eq!(data.len(), n_origins * n_devs);
74        Self {
75            n_origins,
76            n_devs,
77            data,
78        }
79    }
80
81    /// Construct and validate a square cumulative triangle.
82    ///
83    /// This enforces the same shape, finiteness, and non-negative observed-cell
84    /// contract used by the checked reserving engines. Row monotonicity is
85    /// still method-specific and is validated by those engines.
86    pub fn try_new(
87        n_origins: usize,
88        n_devs: usize,
89        data: Vec<f64>,
90    ) -> Result<Self, ValidationError> {
91        let triangle = Self {
92            n_origins,
93            n_devs,
94            data,
95        };
96        validate_triangle(&triangle.view())?;
97        Ok(triangle)
98    }
99
100    /// Construct and validate a square cumulative triangle directly from
101    /// ragged upper-triangle rows (no manual `f64::NAN` padding required).
102    ///
103    /// Row `i` must have length `n - i` where `n = rows.len() > 0`.
104    /// For owned `Vec<Vec<f64>>` inputs, see [`Self::try_from_rows`].
105    ///
106    /// # Example
107    /// ```rust
108    /// use reserving_kernels::Triangle;
109    ///
110    /// let tri = Triangle::try_from_upper_rows(&[
111    ///     &[100.0, 160.0, 195.0],
112    ///     &[120.0, 190.0],
113    ///     &[135.0],
114    /// ])?;
115    /// assert_eq!(tri.n(), 3);
116    /// assert_eq!(tri.latest_diagonal(), vec![195.0, 190.0, 135.0]);
117    /// # Ok::<(), reserving_kernels::validate::ValidationError>(())
118    /// ```
119    pub fn try_from_upper_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
120        Self::try_from_rows(rows)
121    }
122
123    /// Generic variant of [`Self::try_from_upper_rows`] accepting any slice of
124    /// row buffers (`&[Vec<f64>]`, `&[&[f64]]`, etc.).
125    pub fn try_from_rows<R: AsRef<[f64]>>(rows: &[R]) -> Result<Self, ValidationError> {
126        let n = rows.len();
127        if n == 0 {
128            return Err(ValidationError::ShapeMismatch);
129        }
130        let mut data = vec![f64::NAN; n * n];
131        for (i, row) in rows.iter().enumerate() {
132            let row = row.as_ref();
133            if row.len() != n - i {
134                return Err(ValidationError::ShapeMismatch);
135            }
136            data[i * n..i * n + row.len()].copy_from_slice(row);
137        }
138        Self::try_new(n, n, data)
139    }
140
141    /// Construct and validate a square cumulative triangle by cumulating
142    /// incremental upper-triangle rows along each origin period.
143    ///
144    /// Row `i` must have length `n - i` where `n = rows.len() > 0`.
145    pub fn try_from_incremental_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
146        let n = rows.len();
147        if n == 0 {
148            return Err(ValidationError::ShapeMismatch);
149        }
150        let mut data = vec![f64::NAN; n * n];
151        for (i, row) in rows.iter().enumerate() {
152            if row.len() != n - i {
153                return Err(ValidationError::ShapeMismatch);
154            }
155            let mut acc = 0.0;
156            for (j, &inc) in row.iter().enumerate() {
157                if !inc.is_finite() {
158                    return Err(ValidationError::NotFinite);
159                }
160                acc += inc;
161                data[i * n + j] = acc;
162            }
163        }
164        Self::try_new(n, n, data)
165    }
166
167    /// Cumulative value at origin `i`, development `j`. `NaN` if unobserved.
168    #[inline]
169    pub fn get(&self, i: usize, j: usize) -> f64 {
170        self.data[i * self.n_devs + j]
171    }
172
173    /// Observed cumulative slice for origin `i` (length `n - i`, excluding trailing `NaN`s).
174    #[inline]
175    pub fn origin_row(&self, i: usize) -> &[f64] {
176        let n = self.n();
177        let len = n.saturating_sub(i);
178        let start = i * self.n_devs;
179        &self.data[start..start + len]
180    }
181
182    /// Number of origin (accident / policy) periods.
183    #[inline]
184    pub fn n_origins(&self) -> usize {
185        self.n_origins
186    }
187
188    /// Number of development periods.
189    #[inline]
190    pub fn n_devs(&self) -> usize {
191        self.n_devs
192    }
193
194    /// Borrow the underlying row-major slice of length `n_origins * n_devs`.
195    #[inline]
196    pub fn data(&self) -> &[f64] {
197        &self.data
198    }
199
200    /// Square triangle dimension `min(n_origins, n_devs)`.
201    #[inline]
202    pub fn n(&self) -> usize {
203        self.n_origins.min(self.n_devs)
204    }
205
206    /// `true` iff the triangle has zero origins or zero development periods.
207    #[inline]
208    pub fn is_empty(&self) -> bool {
209        self.n_origins == 0 || self.n_devs == 0
210    }
211
212    /// Borrow as a [`TriangleView`].
213    #[inline]
214    pub fn view(&self) -> TriangleView<'_> {
215        TriangleView {
216            n_origins: self.n_origins,
217            n_devs: self.n_devs,
218            data: &self.data,
219        }
220    }
221}
222
223impl fmt::Display for Triangle {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        self.view().fmt(f)
226    }
227}
228
229/// A non-owning view over a triangle's row-major buffer.
230#[derive(Debug, Clone, Copy)]
231pub struct TriangleView<'a> {
232    /// Number of origin periods.
233    pub n_origins: usize,
234    /// Number of development periods.
235    pub n_devs: usize,
236    /// Row-major buffer.
237    pub data: &'a [f64],
238}
239
240impl PartialEq for TriangleView<'_> {
241    fn eq(&self, other: &Self) -> bool {
242        self.n_origins == other.n_origins
243            && self.n_devs == other.n_devs
244            && self.data.len() == other.data.len()
245            && self
246                .data
247                .iter()
248                .zip(other.data.iter())
249                .all(|(&a, &b)| (a.is_nan() && b.is_nan()) || a == b)
250    }
251}
252
253impl fmt::Display for TriangleView<'_> {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        for i in 0..self.n_origins {
256            if i > 0 {
257                writeln!(f)?;
258            }
259            for j in 0..self.n_devs {
260                if j > 0 {
261                    write!(f, "\t")?;
262                }
263                let v = self.data[i * self.n_devs + j];
264                if v.is_finite() {
265                    write!(f, "{v:.2}")?;
266                } else {
267                    write!(f, "-")?;
268                }
269            }
270        }
271        Ok(())
272    }
273}
274
275impl TriangleView<'_> {
276    /// Cumulative value at origin `i`, development `j`. `NaN` if unobserved.
277    #[inline]
278    pub fn get(&self, i: usize, j: usize) -> f64 {
279        self.data[i * self.n_devs + j]
280    }
281
282    /// `true` iff cell `(i, j)` is scheduled to be observed under the
283    /// upper-triangular square-triangle convention (`i + j < n`).
284    #[inline]
285    pub fn is_scheduled_observed(&self, i: usize, j: usize) -> bool {
286        let n = self.n_origins.min(self.n_devs);
287        i < n && j < n && i + j < n
288    }
289
290    /// `true` iff cell `(i, j)` is scheduled observed and holds a finite value.
291    #[inline]
292    pub fn is_valid_observed(&self, i: usize, j: usize) -> bool {
293        self.is_scheduled_observed(i, j) && self.get(i, j).is_finite()
294    }
295
296    /// `true` iff cell `(i, j)` is scheduled observed and holds a finite value.
297    ///
298    /// This preserves the original hot-path predicate. Use
299    /// [`Self::is_scheduled_observed`] when validation needs to distinguish
300    /// triangle geometry from numeric validity.
301    #[inline]
302    pub fn is_observed(&self, i: usize, j: usize) -> bool {
303        self.is_valid_observed(i, j)
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use crate::validate::ValidationError;
311
312    #[test]
313    fn try_new_rejects_shape_mismatch() {
314        assert_eq!(
315            Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0]),
316            Err(ValidationError::ShapeMismatch)
317        );
318    }
319
320    #[test]
321    fn try_new_accepts_valid_square_triangle() {
322        let triangle = Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0, f64::NAN]).expect("triangle");
323
324        assert_eq!(triangle.n_origins, 2);
325        assert_eq!(triangle.n_devs, 2);
326        assert_eq!(triangle, triangle.clone());
327        assert_eq!(triangle.view(), triangle.view());
328    }
329
330    #[test]
331    fn triangle_serde_json_roundtrips_nan_and_validates() {
332        let triangle =
333            Triangle::try_from_upper_rows(&[&[100.0, 160.0, 195.0], &[120.0, 190.0], &[135.0]])
334                .expect("triangle");
335        let json = serde_json::to_string(&triangle).expect("serialize");
336        let decoded: Triangle = serde_json::from_str(&json).expect("deserialize");
337        assert_eq!(triangle, decoded);
338
339        let malformed = r#"{"n_origins":3,"n_devs":3,"data":[1.0]}"#;
340        assert!(serde_json::from_str::<Triangle>(malformed).is_err());
341    }
342}