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        self.view().fmt(f)
326    }
327}
328
329/// A non-owning view over a triangle's row-major buffer.
330#[derive(Debug, Clone, Copy, PartialEq)]
331pub struct TriangleView<'a> {
332    /// Number of origin periods.
333    pub n_origins: usize,
334    /// Number of development periods.
335    pub n_devs: usize,
336    /// Row-major buffer.
337    pub data: &'a [f64],
338}
339
340impl fmt::Display for TriangleView<'_> {
341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342        for i in 0..self.n_origins {
343            if i > 0 {
344                writeln!(f)?;
345            }
346            for j in 0..self.n_devs {
347                if j > 0 {
348                    write!(f, "\t")?;
349                }
350                let v = self.data[i * self.n_devs + j];
351                if v.is_finite() {
352                    write!(f, "{v:.2}")?;
353                } else {
354                    write!(f, "-")?;
355                }
356            }
357        }
358        Ok(())
359    }
360}
361
362impl TriangleView<'_> {
363    /// Cumulative value at origin `i`, development `j`. `NaN` if unobserved.
364    #[inline]
365    pub fn get(&self, i: usize, j: usize) -> f64 {
366        self.data[i * self.n_devs + j]
367    }
368
369    /// `true` iff cell `(i, j)` is scheduled to be observed under the
370    /// upper-triangular square-triangle convention (`i + j < n`).
371    #[inline]
372    pub fn is_scheduled_observed(&self, i: usize, j: usize) -> bool {
373        let n = self.n_origins.min(self.n_devs);
374        i < n && j < n && i + j < n
375    }
376
377    /// `true` iff cell `(i, j)` is scheduled observed and holds a finite value.
378    #[inline]
379    pub fn is_valid_observed(&self, i: usize, j: usize) -> bool {
380        self.is_scheduled_observed(i, j) && self.get(i, j).is_finite()
381    }
382
383    /// `true` iff cell `(i, j)` is scheduled observed and holds a finite value.
384    ///
385    /// This preserves the original hot-path predicate. Use
386    /// [`Self::is_scheduled_observed`] when validation needs to distinguish
387    /// triangle geometry from numeric validity.
388    #[inline]
389    pub fn is_observed(&self, i: usize, j: usize) -> bool {
390        self.is_valid_observed(i, j)
391    }
392
393    /// Volume-weighted development factors and CDFs (`tail = 1.0` for fully developed).
394    pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
395        DevelopmentFactorEngine::volume_weighted(self, tail)
396    }
397
398    /// Volume-weighted Chain-Ladder projection (`tail = 1.0` for fully developed).
399    pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
400        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
401        ChainLadderEngine::project(self, &factors)
402    }
403
404    /// Mack (1993) distribution-free chain-ladder reserve & standard error analysis.
405    pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
406        mack::analyze(self, tail)
407    }
408
409    /// Mack (1993) analysis under an explicit [`MonotonicityPolicy`].
410    pub fn mack_with_policy(
411        &self,
412        tail: f64,
413        policy: MonotonicityPolicy,
414    ) -> Result<Mack, ValidationError> {
415        mack::analyze_with_policy(self, tail, policy)
416    }
417
418    /// Merz & Wüthrich (2008) 1-year Solvency II Claims Development Result (CDR) MSEP.
419    pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
420        merz_wuthrich::analyze(self)
421    }
422
423    /// Bornhuetter–Ferguson projection using volume-weighted LDFs.
424    pub fn bf(
425        &self,
426        expected_ultimate: &[f64],
427        tail: f64,
428    ) -> Result<BornhuetterFergusonProjection, ValidationError> {
429        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
430        BornhuetterFergusonEngine::project_from_expected_ultimate(self, &factors, expected_ultimate)
431    }
432
433    /// Cape Cod projection using volume-weighted LDFs.
434    pub fn cape_cod(
435        &self,
436        premium: &[f64],
437        tail: f64,
438    ) -> Result<CapeCodProjection, ValidationError> {
439        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
440        CapeCodEngine::project(self, &factors, premium)
441    }
442
443    /// Run England & Verrall / Shapland ODP bootstrap reserve simulation.
444    pub fn bootstrap_odp(
445        &self,
446        tail: f64,
447        options: OdpBootstrapOptions,
448    ) -> Result<OdpBootstrapResult, ValidationError> {
449        bootstrap_odp(self, tail, options)
450    }
451
452    /// Build a complete JSON-serializable reserving exhibit bundle.
453    pub fn exhibit(
454        &self,
455        premium: Option<&[f64]>,
456        expected_ultimate: Option<&[f64]>,
457        tail: f64,
458    ) -> Result<ExhibitBundle, ValidationError> {
459        build_exhibit_bundle(self, premium, expected_ultimate, tail)
460    }
461
462    /// Benktander (1976) / Hovinen credibility projection using volume-weighted LDFs.
463    pub fn benktander(
464        &self,
465        expected_ultimate: &[f64],
466        iterations: usize,
467        tail: f64,
468    ) -> Result<BenktanderProjection, ValidationError> {
469        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
470        BenktanderEngine::project_from_expected_ultimate(
471            self,
472            &factors,
473            expected_ultimate,
474            iterations,
475        )
476    }
477
478    /// Generalized Cape Cod (Gluck 1997) decay-weighted projection.
479    pub fn generalized_cape_cod(
480        &self,
481        premium: &[f64],
482        decay: f64,
483        tail: f64,
484    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
485        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
486        GeneralizedCapeCodEngine::project(self, &factors, premium, decay)
487    }
488
489    /// Brosius (1993) OLS credibility development projection.
490    pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
491        brosius::project(self, tail)
492    }
493
494    /// Fit the Over-Dispersed Poisson GLM (`fit_odp`) with strict monotonicity.
495    pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
496        fit_odp(self, tail, MonotonicityPolicy::Strict)
497    }
498
499    /// Fit a reserving GLM (`Odp`, `Gamma`, `Tweedie`, or `LogNormal`) via Householder QR IRLS.
500    pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
501        glm_reserving::fit_glm(self, options)
502    }
503
504    /// Fit Clark (2003) LDF parametric growth-curve MLE.
505    pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
506        clark_mle::fit_clark_ldf(self, options)
507    }
508
509    /// Fit Clark (2003) Cape Cod parametric growth-curve MLE.
510    pub fn clark_cape_cod(
511        &self,
512        premium: &[f64],
513        options: &ClarkOptions,
514    ) -> Result<ClarkMleResult, ValidationError> {
515        clark_mle::fit_clark_cape_cod(self, premium, options)
516    }
517
518    /// Fit Barnett & Zehnwirth (2000) Probabilistic Trend Family log-linear regression.
519    pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
520        ptf_regression::fit_ptf(self, options)
521    }
522
523    /// Structural triangle diagnostics (observed/missing counts, monotonicity, zero latest).
524    pub fn diagnostics(&self) -> TriangleDiagnostics {
525        triangle_diagnostics::analyze(self)
526    }
527}
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532    use crate::validate::ValidationError;
533
534    #[test]
535    fn try_new_rejects_shape_mismatch() {
536        assert_eq!(
537            Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0]),
538            Err(ValidationError::ShapeMismatch)
539        );
540    }
541
542    #[test]
543    fn try_new_accepts_valid_square_triangle() {
544        let triangle = Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0, f64::NAN]).expect("triangle");
545
546        assert_eq!(triangle.n_origins, 2);
547        assert_eq!(triangle.n_devs, 2);
548    }
549}