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::benktander::{BenktanderEngine, BenktanderProjection};
12use crate::bf::{BornhuetterFergusonEngine, BornhuetterFergusonProjection};
13use crate::bootstrap_odp::{
14    OdpBootstrapOptions, OdpBootstrapResult, OdpFit, bootstrap_odp, fit_odp,
15};
16use crate::brosius::{self, Brosius};
17use crate::cape_cod::{CapeCodEngine, CapeCodProjection};
18use crate::chain_ladder::{ChainLadderEngine, ChainLadderProjection};
19use crate::clark_mle::{self, ClarkMleResult, ClarkOptions};
20use crate::diagnostics::triangle_diagnostics::{self, TriangleDiagnostics};
21use crate::exhibit::{ExhibitBundle, build_exhibit_bundle};
22use crate::generalized_cape_cod::{GeneralizedCapeCodEngine, GeneralizedCapeCodProjection};
23use crate::glm_reserving::{self, GlmOptions, GlmReservingResult};
24use crate::ldf::{DevelopmentFactorEngine, DevelopmentFactors};
25use crate::mack::{self, Mack};
26use crate::merz_wuthrich::{self, MerzWuthrichResult};
27use crate::ptf_regression::{self, PtfOptions, PtfResult};
28use crate::triangle::{cumulative_to_incremental, latest_diagonal};
29use crate::validate::{MonotonicityPolicy, ValidationError, validate_triangle};
30
31/// An `n_origins × n_devs` cumulative loss triangle in row-major layout.
32///
33/// `data[i * n_devs + j]` is the cumulative loss for origin `i` at
34/// development age `j`. Unobserved cells are `NaN`. The kernels assume the
35/// triangle is *square* (`n_origins == n_devs`) and that cell `(i, j)` is
36/// observed for `i + j ≤ n - 1`.
37#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
38pub struct Triangle {
39    /// Number of origin (accident / policy) periods.
40    pub n_origins: usize,
41    /// Number of development periods.
42    pub n_devs: usize,
43    /// Row-major buffer of length `n_origins * n_devs`.
44    pub data: Vec<f64>,
45}
46
47impl Triangle {
48    /// Construct a triangle from a row-major slice without validation.
49    ///
50    /// Callers must ensure `data.len() == n_origins * n_devs`. Use
51    /// [`Self::try_new`] at external ingress boundaries when full validation
52    /// (square, finite, non-negative observed cells) is required.
53    #[inline]
54    pub fn new(n_origins: usize, n_devs: usize, data: Vec<f64>) -> Self {
55        debug_assert_eq!(data.len(), n_origins * n_devs);
56        Self {
57            n_origins,
58            n_devs,
59            data,
60        }
61    }
62
63    /// Construct and validate a square cumulative triangle.
64    ///
65    /// This enforces the same shape, finiteness, and non-negative observed-cell
66    /// contract used by the checked reserving engines. Row monotonicity is
67    /// still method-specific and is validated by those engines.
68    pub fn try_new(
69        n_origins: usize,
70        n_devs: usize,
71        data: Vec<f64>,
72    ) -> Result<Self, ValidationError> {
73        let triangle = Self {
74            n_origins,
75            n_devs,
76            data,
77        };
78        validate_triangle(&triangle.view())?;
79        Ok(triangle)
80    }
81
82    /// Construct and validate a square cumulative triangle directly from
83    /// ragged upper-triangle rows (no manual `f64::NAN` padding required).
84    ///
85    /// Row `i` must have length `n - i` where `n = rows.len() > 0`.
86    /// For owned `Vec<Vec<f64>>` inputs, see [`Self::try_from_rows`].
87    ///
88    /// # Example
89    /// ```rust
90    /// use reserving_kernels::Triangle;
91    ///
92    /// let tri = Triangle::try_from_upper_rows(&[
93    ///     &[100.0, 160.0, 195.0],
94    ///     &[120.0, 190.0],
95    ///     &[135.0],
96    /// ])?;
97    /// assert_eq!(tri.n(), 3);
98    /// assert_eq!(tri.latest_diagonal(), vec![195.0, 190.0, 135.0]);
99    /// # Ok::<(), reserving_kernels::validate::ValidationError>(())
100    /// ```
101    pub fn try_from_upper_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
102        Self::try_from_rows(rows)
103    }
104
105    /// Generic variant of [`Self::try_from_upper_rows`] accepting any slice of
106    /// row buffers (`&[Vec<f64>]`, `&[&[f64]]`, etc.).
107    pub fn try_from_rows<R: AsRef<[f64]>>(rows: &[R]) -> Result<Self, ValidationError> {
108        let n = rows.len();
109        if n == 0 {
110            return Err(ValidationError::ShapeMismatch);
111        }
112        let mut data = vec![f64::NAN; n * n];
113        for (i, row) in rows.iter().enumerate() {
114            let row = row.as_ref();
115            if row.len() != n - i {
116                return Err(ValidationError::ShapeMismatch);
117            }
118            data[i * n..i * n + row.len()].copy_from_slice(row);
119        }
120        Self::try_new(n, n, data)
121    }
122
123    /// Construct and validate a square cumulative triangle by cumulating
124    /// incremental upper-triangle rows along each origin period.
125    ///
126    /// Row `i` must have length `n - i` where `n = rows.len() > 0`.
127    pub fn try_from_incremental_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
128        let n = rows.len();
129        if n == 0 {
130            return Err(ValidationError::ShapeMismatch);
131        }
132        let mut data = vec![f64::NAN; n * n];
133        for (i, row) in rows.iter().enumerate() {
134            if row.len() != n - i {
135                return Err(ValidationError::ShapeMismatch);
136            }
137            let mut acc = 0.0;
138            for (j, &inc) in row.iter().enumerate() {
139                if !inc.is_finite() {
140                    return Err(ValidationError::NotFinite);
141                }
142                acc += inc;
143                data[i * n + j] = acc;
144            }
145        }
146        Self::try_new(n, n, data)
147    }
148
149    /// Cumulative value at origin `i`, development `j`. `NaN` if unobserved.
150    #[inline]
151    pub fn get(&self, i: usize, j: usize) -> f64 {
152        self.data[i * self.n_devs + j]
153    }
154
155    /// Observed cumulative slice for origin `i` (length `n - i`, excluding trailing `NaN`s).
156    #[inline]
157    pub fn origin_row(&self, i: usize) -> &[f64] {
158        let n = self.n();
159        let len = n.saturating_sub(i);
160        let start = i * self.n_devs;
161        &self.data[start..start + len]
162    }
163
164    /// Square triangle dimension `min(n_origins, n_devs)`.
165    #[inline]
166    pub fn n(&self) -> usize {
167        self.n_origins.min(self.n_devs)
168    }
169
170    /// `true` iff the triangle has zero origins or zero development periods.
171    #[inline]
172    pub fn is_empty(&self) -> bool {
173        self.n_origins == 0 || self.n_devs == 0
174    }
175
176    /// Borrow as a [`TriangleView`].
177    #[inline]
178    pub fn view(&self) -> TriangleView<'_> {
179        TriangleView {
180            n_origins: self.n_origins,
181            n_devs: self.n_devs,
182            data: &self.data,
183        }
184    }
185
186    /// Extract the latest-observed cumulative anti-diagonal.
187    pub fn latest_diagonal(&self) -> Vec<f64> {
188        latest_diagonal(&self.view())
189    }
190
191    /// Convert this cumulative triangle to an incremental [`Triangle`].
192    pub fn to_incremental(&self) -> Self {
193        let n = self.n();
194        Self::new(n, n, cumulative_to_incremental(&self.view()))
195    }
196
197    /// Volume-weighted development factors and CDFs (`tail = 1.0` for fully developed).
198    pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
199        self.view().ldfs(tail)
200    }
201
202    /// Volume-weighted Chain-Ladder projection (`tail = 1.0` for fully developed).
203    pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
204        self.view().chain_ladder(tail)
205    }
206
207    /// Mack (1993) distribution-free chain-ladder reserve & standard error analysis.
208    pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
209        self.view().mack(tail)
210    }
211
212    /// Mack (1993) analysis under an explicit [`MonotonicityPolicy`].
213    pub fn mack_with_policy(
214        &self,
215        tail: f64,
216        policy: MonotonicityPolicy,
217    ) -> Result<Mack, ValidationError> {
218        self.view().mack_with_policy(tail, policy)
219    }
220
221    /// Merz & Wüthrich (2008) 1-year Solvency II Claims Development Result (CDR) MSEP.
222    pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
223        self.view().merz_wuthrich()
224    }
225
226    /// Bornhuetter–Ferguson projection using volume-weighted LDFs.
227    pub fn bf(
228        &self,
229        expected_ultimate: &[f64],
230        tail: f64,
231    ) -> Result<BornhuetterFergusonProjection, ValidationError> {
232        self.view().bf(expected_ultimate, tail)
233    }
234
235    /// Cape Cod projection using volume-weighted LDFs.
236    pub fn cape_cod(
237        &self,
238        premium: &[f64],
239        tail: f64,
240    ) -> Result<CapeCodProjection, ValidationError> {
241        self.view().cape_cod(premium, tail)
242    }
243
244    /// Run England & Verrall / Shapland ODP bootstrap reserve simulation.
245    pub fn bootstrap_odp(
246        &self,
247        tail: f64,
248        options: OdpBootstrapOptions,
249    ) -> Result<OdpBootstrapResult, ValidationError> {
250        self.view().bootstrap_odp(tail, options)
251    }
252
253    /// Build a complete JSON-serializable reserving exhibit bundle.
254    pub fn exhibit(
255        &self,
256        premium: Option<&[f64]>,
257        expected_ultimate: Option<&[f64]>,
258        tail: f64,
259    ) -> Result<ExhibitBundle, ValidationError> {
260        self.view().exhibit(premium, expected_ultimate, tail)
261    }
262
263    /// Benktander (1976) / Hovinen credibility projection using volume-weighted LDFs.
264    pub fn benktander(
265        &self,
266        expected_ultimate: &[f64],
267        iterations: usize,
268        tail: f64,
269    ) -> Result<BenktanderProjection, ValidationError> {
270        self.view().benktander(expected_ultimate, iterations, tail)
271    }
272
273    /// Generalized Cape Cod (Gluck 1997) decay-weighted projection.
274    pub fn generalized_cape_cod(
275        &self,
276        premium: &[f64],
277        decay: f64,
278        tail: f64,
279    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
280        self.view().generalized_cape_cod(premium, decay, tail)
281    }
282
283    /// Brosius (1993) OLS credibility development projection.
284    pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
285        self.view().brosius(tail)
286    }
287
288    /// Fit the Over-Dispersed Poisson GLM (`fit_odp`) with strict monotonicity.
289    pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
290        self.view().fit_odp(tail)
291    }
292
293    /// Fit a reserving GLM (`Odp`, `Gamma`, `Tweedie`, or `LogNormal`) via Householder QR IRLS.
294    pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
295        self.view().glm(options)
296    }
297
298    /// Fit Clark (2003) LDF parametric growth-curve MLE.
299    pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
300        self.view().clark_ldf(options)
301    }
302
303    /// Fit Clark (2003) Cape Cod parametric growth-curve MLE.
304    pub fn clark_cape_cod(
305        &self,
306        premium: &[f64],
307        options: &ClarkOptions,
308    ) -> Result<ClarkMleResult, ValidationError> {
309        self.view().clark_cape_cod(premium, options)
310    }
311
312    /// Fit Barnett & Zehnwirth (2000) Probabilistic Trend Family log-linear regression.
313    pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
314        self.view().ptf(options)
315    }
316
317    /// Structural triangle diagnostics (observed/missing counts, monotonicity, zero latest).
318    pub fn diagnostics(&self) -> TriangleDiagnostics {
319        self.view().diagnostics()
320    }
321}
322
323impl fmt::Display for Triangle {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        for i in 0..self.n_origins {
326            if i > 0 {
327                writeln!(f)?;
328            }
329            for j in 0..self.n_devs {
330                if j > 0 {
331                    write!(f, "\t")?;
332                }
333                let v = self.data[i * self.n_devs + j];
334                if v.is_finite() {
335                    write!(f, "{v:.2}")?;
336                } else {
337                    write!(f, "-")?;
338                }
339            }
340        }
341        Ok(())
342    }
343}
344
345/// A non-owning view over a triangle's row-major buffer.
346#[derive(Debug, Clone, Copy)]
347pub struct TriangleView<'a> {
348    /// Number of origin periods.
349    pub n_origins: usize,
350    /// Number of development periods.
351    pub n_devs: usize,
352    /// Row-major buffer.
353    pub data: &'a [f64],
354}
355
356impl<'a> TriangleView<'a> {
357    /// Cumulative value at origin `i`, development `j`. `NaN` if unobserved.
358    #[inline]
359    pub fn get(&self, i: usize, j: usize) -> f64 {
360        self.data[i * self.n_devs + j]
361    }
362
363    /// `true` iff cell `(i, j)` is scheduled to be observed under the
364    /// upper-triangular square-triangle convention (`i + j < n`).
365    #[inline]
366    pub fn is_scheduled_observed(&self, i: usize, j: usize) -> bool {
367        let n = self.n_origins.min(self.n_devs);
368        i < n && j < n && i + j < n
369    }
370
371    /// `true` iff cell `(i, j)` is scheduled observed and holds a finite value.
372    #[inline]
373    pub fn is_valid_observed(&self, i: usize, j: usize) -> bool {
374        self.is_scheduled_observed(i, j) && self.get(i, j).is_finite()
375    }
376
377    /// `true` iff cell `(i, j)` is scheduled observed and holds a finite value.
378    ///
379    /// This preserves the original hot-path predicate. Use
380    /// [`Self::is_scheduled_observed`] when validation needs to distinguish
381    /// triangle geometry from numeric validity.
382    #[inline]
383    pub fn is_observed(&self, i: usize, j: usize) -> bool {
384        self.is_valid_observed(i, j)
385    }
386
387    /// Volume-weighted development factors and CDFs (`tail = 1.0` for fully developed).
388    pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
389        DevelopmentFactorEngine::volume_weighted(self, tail)
390    }
391
392    /// Volume-weighted Chain-Ladder projection (`tail = 1.0` for fully developed).
393    pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
394        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
395        ChainLadderEngine::project(self, &factors)
396    }
397
398    /// Mack (1993) distribution-free chain-ladder reserve & standard error analysis.
399    pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
400        mack::analyze(self, tail)
401    }
402
403    /// Mack (1993) analysis under an explicit [`MonotonicityPolicy`].
404    pub fn mack_with_policy(
405        &self,
406        tail: f64,
407        policy: MonotonicityPolicy,
408    ) -> Result<Mack, ValidationError> {
409        mack::analyze_with_policy(self, tail, policy)
410    }
411
412    /// Merz & Wüthrich (2008) 1-year Solvency II Claims Development Result (CDR) MSEP.
413    pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
414        merz_wuthrich::analyze(self)
415    }
416
417    /// Bornhuetter–Ferguson projection using volume-weighted LDFs.
418    pub fn bf(
419        &self,
420        expected_ultimate: &[f64],
421        tail: f64,
422    ) -> Result<BornhuetterFergusonProjection, ValidationError> {
423        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
424        BornhuetterFergusonEngine::project_from_expected_ultimate(self, &factors, expected_ultimate)
425    }
426
427    /// Cape Cod projection using volume-weighted LDFs.
428    pub fn cape_cod(
429        &self,
430        premium: &[f64],
431        tail: f64,
432    ) -> Result<CapeCodProjection, ValidationError> {
433        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
434        CapeCodEngine::project(self, &factors, premium)
435    }
436
437    /// Run England & Verrall / Shapland ODP bootstrap reserve simulation.
438    pub fn bootstrap_odp(
439        &self,
440        tail: f64,
441        options: OdpBootstrapOptions,
442    ) -> Result<OdpBootstrapResult, ValidationError> {
443        bootstrap_odp(self, tail, options)
444    }
445
446    /// Build a complete JSON-serializable reserving exhibit bundle.
447    pub fn exhibit(
448        &self,
449        premium: Option<&[f64]>,
450        expected_ultimate: Option<&[f64]>,
451        tail: f64,
452    ) -> Result<ExhibitBundle, ValidationError> {
453        build_exhibit_bundle(self, premium, expected_ultimate, tail)
454    }
455
456    /// Benktander (1976) / Hovinen credibility projection using volume-weighted LDFs.
457    pub fn benktander(
458        &self,
459        expected_ultimate: &[f64],
460        iterations: usize,
461        tail: f64,
462    ) -> Result<BenktanderProjection, ValidationError> {
463        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
464        BenktanderEngine::project_from_expected_ultimate(
465            self,
466            &factors,
467            expected_ultimate,
468            iterations,
469        )
470    }
471
472    /// Generalized Cape Cod (Gluck 1997) decay-weighted projection.
473    pub fn generalized_cape_cod(
474        &self,
475        premium: &[f64],
476        decay: f64,
477        tail: f64,
478    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
479        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
480        GeneralizedCapeCodEngine::project(self, &factors, premium, decay)
481    }
482
483    /// Brosius (1993) OLS credibility development projection.
484    pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
485        brosius::project(self, tail)
486    }
487
488    /// Fit the Over-Dispersed Poisson GLM (`fit_odp`) with strict monotonicity.
489    pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
490        fit_odp(self, tail, MonotonicityPolicy::Strict)
491    }
492
493    /// Fit a reserving GLM (`Odp`, `Gamma`, `Tweedie`, or `LogNormal`) via Householder QR IRLS.
494    pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
495        glm_reserving::fit_glm(self, options)
496    }
497
498    /// Fit Clark (2003) LDF parametric growth-curve MLE.
499    pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
500        clark_mle::fit_clark_ldf(self, options)
501    }
502
503    /// Fit Clark (2003) Cape Cod parametric growth-curve MLE.
504    pub fn clark_cape_cod(
505        &self,
506        premium: &[f64],
507        options: &ClarkOptions,
508    ) -> Result<ClarkMleResult, ValidationError> {
509        clark_mle::fit_clark_cape_cod(self, premium, options)
510    }
511
512    /// Fit Barnett & Zehnwirth (2000) Probabilistic Trend Family log-linear regression.
513    pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
514        ptf_regression::fit_ptf(self, options)
515    }
516
517    /// Structural triangle diagnostics (observed/missing counts, monotonicity, zero latest).
518    pub fn diagnostics(&self) -> TriangleDiagnostics {
519        triangle_diagnostics::analyze(self)
520    }
521}
522
523#[cfg(test)]
524mod tests {
525    use super::*;
526    use crate::validate::ValidationError;
527
528    #[test]
529    fn try_new_rejects_shape_mismatch() {
530        assert_eq!(
531            Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0]),
532            Err(ValidationError::ShapeMismatch)
533        );
534    }
535
536    #[test]
537    fn try_new_accepts_valid_square_triangle() {
538        let triangle = Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0, f64::NAN]).expect("triangle");
539
540        assert_eq!(triangle.n_origins, 2);
541        assert_eq!(triangle.n_devs, 2);
542    }
543}