reserving-kernels 0.3.0

Pure Rust numeric kernels for P&C actuarial reserving and reserve-risk capital modeling.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Prevalidated columnar triangle inputs.
//!
//! A loss-development triangle is an `n_origins × n_devs` grid of cumulative
//! amounts (paid or incurred). Cell `(i, j)` is observed iff `i + j ≤ n - 1`
//! for a square triangle. Unobserved cells are represented as `NaN` so the
//! compute kernels stay branch-light — null-handling lives at the ingress
//! boundary (see [`crate::validate`]).

use std::fmt;

use crate::benktander::{BenktanderEngine, BenktanderProjection};
use crate::bf::{BornhuetterFergusonEngine, BornhuetterFergusonProjection};
use crate::bootstrap_odp::{
    OdpBootstrapOptions, OdpBootstrapResult, OdpFit, bootstrap_odp, fit_odp,
};
use crate::brosius::{self, Brosius};
use crate::cape_cod::{CapeCodEngine, CapeCodProjection};
use crate::chain_ladder::{ChainLadderEngine, ChainLadderProjection};
use crate::clark_mle::{self, ClarkMleResult, ClarkOptions};
use crate::diagnostics::triangle_diagnostics::{self, TriangleDiagnostics};
use crate::exhibit::{ExhibitBundle, build_exhibit_bundle};
use crate::generalized_cape_cod::{GeneralizedCapeCodEngine, GeneralizedCapeCodProjection};
use crate::glm_reserving::{self, GlmOptions, GlmReservingResult};
use crate::ldf::{DevelopmentFactorEngine, DevelopmentFactors};
use crate::mack::{self, Mack};
use crate::merz_wuthrich::{self, MerzWuthrichResult};
use crate::ptf_regression::{self, PtfOptions, PtfResult};
use crate::triangle::{cumulative_to_incremental, latest_diagonal};
use crate::validate::{MonotonicityPolicy, ValidationError, validate_triangle};

/// Deserialize a `Vec<f64>` where JSON `null` values map back to `f64::NAN`,
/// enabling lossless `serde_json` round-trips for triangles containing `NaN`
/// sentinels in unobserved cells.
fn deserialize_vec_f64_null_as_nan<'de, D>(deserializer: D) -> Result<Vec<f64>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;
    let opts: Vec<Option<f64>> = Vec::deserialize(deserializer)?;
    Ok(opts.into_iter().map(|v| v.unwrap_or(f64::NAN)).collect())
}

#[derive(serde::Deserialize)]
struct RawTriangle {
    n_origins: usize,
    n_devs: usize,
    #[serde(deserialize_with = "deserialize_vec_f64_null_as_nan")]
    data: Vec<f64>,
}

impl TryFrom<RawTriangle> for Triangle {
    type Error = ValidationError;

    fn try_from(raw: RawTriangle) -> Result<Self, Self::Error> {
        Self::try_new(raw.n_origins, raw.n_devs, raw.data)
    }
}

/// An `n_origins × n_devs` cumulative loss triangle in row-major layout.
///
/// `data[i * n_devs + j]` is the cumulative loss for origin `i` at
/// development age `j`. Unobserved cells are `NaN`. The kernels assume the
/// triangle is *square* (`n_origins == n_devs`) and that cell `(i, j)` is
/// observed for `i + j ≤ n - 1`.
///
/// Equality (`PartialEq`) treats two `NaN` cells at the same position as equal
/// so `tri == tri.clone()` holds for triangles with unobserved cells.
/// Deserialization maps JSON `null` to `NaN` and validates via [`Self::try_new`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "RawTriangle")]
pub struct Triangle {
    n_origins: usize,
    n_devs: usize,
    data: Vec<f64>,
}

impl PartialEq for Triangle {
    fn eq(&self, other: &Self) -> bool {
        self.view() == other.view()
    }
}

impl Triangle {
    /// Construct a triangle from a row-major slice without validation.
    ///
    /// Callers must ensure `data.len() == n_origins * n_devs`. Use
    /// [`Self::try_new`] at external ingress boundaries when full validation
    /// (square, finite, non-negative observed cells) is required.
    #[inline]
    pub fn new(n_origins: usize, n_devs: usize, data: Vec<f64>) -> Self {
        debug_assert_eq!(data.len(), n_origins * n_devs);
        Self {
            n_origins,
            n_devs,
            data,
        }
    }

    /// Construct and validate a square cumulative triangle.
    ///
    /// This enforces the same shape, finiteness, and non-negative observed-cell
    /// contract used by the checked reserving engines. Row monotonicity is
    /// still method-specific and is validated by those engines.
    pub fn try_new(
        n_origins: usize,
        n_devs: usize,
        data: Vec<f64>,
    ) -> Result<Self, ValidationError> {
        let triangle = Self {
            n_origins,
            n_devs,
            data,
        };
        validate_triangle(&triangle.view())?;
        Ok(triangle)
    }

    /// Construct and validate a square cumulative triangle directly from
    /// ragged upper-triangle rows (no manual `f64::NAN` padding required).
    ///
    /// Row `i` must have length `n - i` where `n = rows.len() > 0`.
    /// For owned `Vec<Vec<f64>>` inputs, see [`Self::try_from_rows`].
    ///
    /// # Example
    /// ```rust
    /// use reserving_kernels::Triangle;
    ///
    /// let tri = Triangle::try_from_upper_rows(&[
    ///     &[100.0, 160.0, 195.0],
    ///     &[120.0, 190.0],
    ///     &[135.0],
    /// ])?;
    /// assert_eq!(tri.n(), 3);
    /// assert_eq!(tri.latest_diagonal(), vec![195.0, 190.0, 135.0]);
    /// # Ok::<(), reserving_kernels::validate::ValidationError>(())
    /// ```
    pub fn try_from_upper_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
        Self::try_from_rows(rows)
    }

    /// Generic variant of [`Self::try_from_upper_rows`] accepting any slice of
    /// row buffers (`&[Vec<f64>]`, `&[&[f64]]`, etc.).
    pub fn try_from_rows<R: AsRef<[f64]>>(rows: &[R]) -> Result<Self, ValidationError> {
        let n = rows.len();
        if n == 0 {
            return Err(ValidationError::ShapeMismatch);
        }
        let mut data = vec![f64::NAN; n * n];
        for (i, row) in rows.iter().enumerate() {
            let row = row.as_ref();
            if row.len() != n - i {
                return Err(ValidationError::ShapeMismatch);
            }
            data[i * n..i * n + row.len()].copy_from_slice(row);
        }
        Self::try_new(n, n, data)
    }

    /// Construct and validate a square cumulative triangle by cumulating
    /// incremental upper-triangle rows along each origin period.
    ///
    /// Row `i` must have length `n - i` where `n = rows.len() > 0`.
    pub fn try_from_incremental_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
        let n = rows.len();
        if n == 0 {
            return Err(ValidationError::ShapeMismatch);
        }
        let mut data = vec![f64::NAN; n * n];
        for (i, row) in rows.iter().enumerate() {
            if row.len() != n - i {
                return Err(ValidationError::ShapeMismatch);
            }
            let mut acc = 0.0;
            for (j, &inc) in row.iter().enumerate() {
                if !inc.is_finite() {
                    return Err(ValidationError::NotFinite);
                }
                acc += inc;
                data[i * n + j] = acc;
            }
        }
        Self::try_new(n, n, data)
    }

    /// Cumulative value at origin `i`, development `j`. `NaN` if unobserved.
    #[inline]
    pub fn get(&self, i: usize, j: usize) -> f64 {
        self.data[i * self.n_devs + j]
    }

    /// Observed cumulative slice for origin `i` (length `n - i`, excluding trailing `NaN`s).
    #[inline]
    pub fn origin_row(&self, i: usize) -> &[f64] {
        let n = self.n();
        let len = n.saturating_sub(i);
        let start = i * self.n_devs;
        &self.data[start..start + len]
    }

    /// Number of origin (accident / policy) periods.
    #[inline]
    pub fn n_origins(&self) -> usize {
        self.n_origins
    }

    /// Number of development periods.
    #[inline]
    pub fn n_devs(&self) -> usize {
        self.n_devs
    }

    /// Borrow the underlying row-major slice of length `n_origins * n_devs`.
    #[inline]
    pub fn data(&self) -> &[f64] {
        &self.data
    }

    /// Square triangle dimension `min(n_origins, n_devs)`.
    #[inline]
    pub fn n(&self) -> usize {
        self.n_origins.min(self.n_devs)
    }

    /// `true` iff the triangle has zero origins or zero development periods.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.n_origins == 0 || self.n_devs == 0
    }

    /// Borrow as a [`TriangleView`].
    #[inline]
    pub fn view(&self) -> TriangleView<'_> {
        TriangleView {
            n_origins: self.n_origins,
            n_devs: self.n_devs,
            data: &self.data,
        }
    }

    /// Extract the latest-observed cumulative anti-diagonal.
    pub fn latest_diagonal(&self) -> Vec<f64> {
        latest_diagonal(&self.view())
    }

    /// Convert this cumulative triangle to an incremental [`Triangle`].
    pub fn to_incremental(&self) -> Self {
        let n = self.n();
        Self::new(n, n, cumulative_to_incremental(&self.view()))
    }

    /// Volume-weighted development factors and CDFs (`tail = 1.0` for fully developed).
    pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
        self.view().ldfs(tail)
    }

    /// Volume-weighted Chain-Ladder projection (`tail = 1.0` for fully developed).
    pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
        self.view().chain_ladder(tail)
    }

    /// Mack (1993) distribution-free chain-ladder reserve & standard error analysis.
    pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
        self.view().mack(tail)
    }

    /// Mack (1993) analysis under an explicit [`MonotonicityPolicy`].
    pub fn mack_with_policy(
        &self,
        tail: f64,
        policy: MonotonicityPolicy,
    ) -> Result<Mack, ValidationError> {
        self.view().mack_with_policy(tail, policy)
    }

    /// Merz & Wüthrich (2008) 1-year Solvency II Claims Development Result (CDR) MSEP.
    pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
        self.view().merz_wuthrich()
    }

    /// Merz & Wüthrich (2008) 1-year CDR MSEP under an explicit [`MonotonicityPolicy`].
    pub fn merz_wuthrich_with_policy(
        &self,
        policy: MonotonicityPolicy,
    ) -> Result<MerzWuthrichResult, ValidationError> {
        self.view().merz_wuthrich_with_policy(policy)
    }

    /// Bornhuetter–Ferguson projection using volume-weighted LDFs.
    pub fn bf(
        &self,
        expected_ultimate: &[f64],
        tail: f64,
    ) -> Result<BornhuetterFergusonProjection, ValidationError> {
        self.view().bf(expected_ultimate, tail)
    }

    /// Cape Cod projection using volume-weighted LDFs.
    pub fn cape_cod(
        &self,
        premium: &[f64],
        tail: f64,
    ) -> Result<CapeCodProjection, ValidationError> {
        self.view().cape_cod(premium, tail)
    }

    /// Run England & Verrall / Shapland ODP bootstrap reserve simulation.
    pub fn bootstrap_odp(
        &self,
        tail: f64,
        options: OdpBootstrapOptions,
    ) -> Result<OdpBootstrapResult, ValidationError> {
        self.view().bootstrap_odp(tail, options)
    }

    /// Build a complete JSON-serializable reserving exhibit bundle.
    pub fn exhibit(
        &self,
        premium: Option<&[f64]>,
        expected_ultimate: Option<&[f64]>,
        tail: f64,
    ) -> Result<ExhibitBundle, ValidationError> {
        self.view().exhibit(premium, expected_ultimate, tail)
    }

    /// Benktander (1976) / Hovinen credibility projection using volume-weighted LDFs.
    pub fn benktander(
        &self,
        expected_ultimate: &[f64],
        iterations: usize,
        tail: f64,
    ) -> Result<BenktanderProjection, ValidationError> {
        self.view().benktander(expected_ultimate, iterations, tail)
    }

    /// Generalized Cape Cod (Gluck 1997) decay-weighted projection.
    pub fn generalized_cape_cod(
        &self,
        premium: &[f64],
        decay: f64,
        tail: f64,
    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
        self.view().generalized_cape_cod(premium, decay, tail)
    }

    /// Brosius (1993) OLS credibility development projection.
    pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
        self.view().brosius(tail)
    }

    /// Fit the Over-Dispersed Poisson GLM (`fit_odp`) with strict monotonicity.
    pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
        self.view().fit_odp(tail)
    }

    /// Fit a reserving GLM (`Odp`, `Gamma`, `Tweedie`, or `LogNormal`) via Householder QR IRLS.
    pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
        self.view().glm(options)
    }

    /// Fit Clark (2003) LDF parametric growth-curve MLE.
    pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
        self.view().clark_ldf(options)
    }

    /// Fit Clark (2003) Cape Cod parametric growth-curve MLE.
    pub fn clark_cape_cod(
        &self,
        premium: &[f64],
        options: &ClarkOptions,
    ) -> Result<ClarkMleResult, ValidationError> {
        self.view().clark_cape_cod(premium, options)
    }

    /// Fit Barnett & Zehnwirth (2000) Probabilistic Trend Family log-linear regression.
    pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
        self.view().ptf(options)
    }

    /// Structural triangle diagnostics (observed/missing counts, monotonicity, zero latest).
    pub fn diagnostics(&self) -> TriangleDiagnostics {
        self.view().diagnostics()
    }
}

impl fmt::Display for Triangle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.view().fmt(f)
    }
}

/// A non-owning view over a triangle's row-major buffer.
#[derive(Debug, Clone, Copy)]
pub struct TriangleView<'a> {
    /// Number of origin periods.
    pub n_origins: usize,
    /// Number of development periods.
    pub n_devs: usize,
    /// Row-major buffer.
    pub data: &'a [f64],
}

impl PartialEq for TriangleView<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.n_origins == other.n_origins
            && self.n_devs == other.n_devs
            && self.data.len() == other.data.len()
            && self
                .data
                .iter()
                .zip(other.data.iter())
                .all(|(&a, &b)| (a.is_nan() && b.is_nan()) || a == b)
    }
}

impl fmt::Display for TriangleView<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for i in 0..self.n_origins {
            if i > 0 {
                writeln!(f)?;
            }
            for j in 0..self.n_devs {
                if j > 0 {
                    write!(f, "\t")?;
                }
                let v = self.data[i * self.n_devs + j];
                if v.is_finite() {
                    write!(f, "{v:.2}")?;
                } else {
                    write!(f, "-")?;
                }
            }
        }
        Ok(())
    }
}

impl TriangleView<'_> {
    /// Cumulative value at origin `i`, development `j`. `NaN` if unobserved.
    #[inline]
    pub fn get(&self, i: usize, j: usize) -> f64 {
        self.data[i * self.n_devs + j]
    }

    /// `true` iff cell `(i, j)` is scheduled to be observed under the
    /// upper-triangular square-triangle convention (`i + j < n`).
    #[inline]
    pub fn is_scheduled_observed(&self, i: usize, j: usize) -> bool {
        let n = self.n_origins.min(self.n_devs);
        i < n && j < n && i + j < n
    }

    /// `true` iff cell `(i, j)` is scheduled observed and holds a finite value.
    #[inline]
    pub fn is_valid_observed(&self, i: usize, j: usize) -> bool {
        self.is_scheduled_observed(i, j) && self.get(i, j).is_finite()
    }

    /// `true` iff cell `(i, j)` is scheduled observed and holds a finite value.
    ///
    /// This preserves the original hot-path predicate. Use
    /// [`Self::is_scheduled_observed`] when validation needs to distinguish
    /// triangle geometry from numeric validity.
    #[inline]
    pub fn is_observed(&self, i: usize, j: usize) -> bool {
        self.is_valid_observed(i, j)
    }

    /// Volume-weighted development factors and CDFs (`tail = 1.0` for fully developed).
    pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
        DevelopmentFactorEngine::volume_weighted(self, tail)
    }

    /// Volume-weighted Chain-Ladder projection (`tail = 1.0` for fully developed).
    pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
        ChainLadderEngine::project(self, &factors)
    }

    /// Mack (1993) distribution-free chain-ladder reserve & standard error analysis.
    pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
        mack::analyze(self, tail)
    }

    /// Mack (1993) analysis under an explicit [`MonotonicityPolicy`].
    pub fn mack_with_policy(
        &self,
        tail: f64,
        policy: MonotonicityPolicy,
    ) -> Result<Mack, ValidationError> {
        mack::analyze_with_policy(self, tail, policy)
    }

    /// Merz & Wüthrich (2008) 1-year Solvency II Claims Development Result (CDR) MSEP.
    pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
        merz_wuthrich::analyze(self)
    }

    /// Merz & Wüthrich (2008) 1-year CDR MSEP under an explicit [`MonotonicityPolicy`].
    pub fn merz_wuthrich_with_policy(
        &self,
        policy: MonotonicityPolicy,
    ) -> Result<MerzWuthrichResult, ValidationError> {
        merz_wuthrich::analyze_with_policy(self, policy)
    }

    /// Bornhuetter–Ferguson projection using volume-weighted LDFs.
    pub fn bf(
        &self,
        expected_ultimate: &[f64],
        tail: f64,
    ) -> Result<BornhuetterFergusonProjection, ValidationError> {
        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
        BornhuetterFergusonEngine::project_from_expected_ultimate(self, &factors, expected_ultimate)
    }

    /// Cape Cod projection using volume-weighted LDFs.
    pub fn cape_cod(
        &self,
        premium: &[f64],
        tail: f64,
    ) -> Result<CapeCodProjection, ValidationError> {
        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
        CapeCodEngine::project(self, &factors, premium)
    }

    /// Run England & Verrall / Shapland ODP bootstrap reserve simulation.
    pub fn bootstrap_odp(
        &self,
        tail: f64,
        options: OdpBootstrapOptions,
    ) -> Result<OdpBootstrapResult, ValidationError> {
        bootstrap_odp(self, tail, options)
    }

    /// Build a complete JSON-serializable reserving exhibit bundle.
    pub fn exhibit(
        &self,
        premium: Option<&[f64]>,
        expected_ultimate: Option<&[f64]>,
        tail: f64,
    ) -> Result<ExhibitBundle, ValidationError> {
        build_exhibit_bundle(self, premium, expected_ultimate, tail)
    }

    /// Benktander (1976) / Hovinen credibility projection using volume-weighted LDFs.
    pub fn benktander(
        &self,
        expected_ultimate: &[f64],
        iterations: usize,
        tail: f64,
    ) -> Result<BenktanderProjection, ValidationError> {
        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
        BenktanderEngine::project_from_expected_ultimate(
            self,
            &factors,
            expected_ultimate,
            iterations,
        )
    }

    /// Generalized Cape Cod (Gluck 1997) decay-weighted projection.
    pub fn generalized_cape_cod(
        &self,
        premium: &[f64],
        decay: f64,
        tail: f64,
    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
        GeneralizedCapeCodEngine::project(self, &factors, premium, decay)
    }

    /// Brosius (1993) OLS credibility development projection.
    pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
        brosius::project(self, tail)
    }

    /// Fit the Over-Dispersed Poisson GLM (`fit_odp`) with strict monotonicity.
    pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
        fit_odp(self, tail, MonotonicityPolicy::Strict)
    }

    /// Fit a reserving GLM (`Odp`, `Gamma`, `Tweedie`, or `LogNormal`) via Householder QR IRLS.
    pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
        glm_reserving::fit_glm(self, options)
    }

    /// Fit Clark (2003) LDF parametric growth-curve MLE.
    pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
        clark_mle::fit_clark_ldf(self, options)
    }

    /// Fit Clark (2003) Cape Cod parametric growth-curve MLE.
    pub fn clark_cape_cod(
        &self,
        premium: &[f64],
        options: &ClarkOptions,
    ) -> Result<ClarkMleResult, ValidationError> {
        clark_mle::fit_clark_cape_cod(self, premium, options)
    }

    /// Fit Barnett & Zehnwirth (2000) Probabilistic Trend Family log-linear regression.
    pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
        ptf_regression::fit_ptf(self, options)
    }

    /// Structural triangle diagnostics (observed/missing counts, monotonicity, zero latest).
    pub fn diagnostics(&self) -> TriangleDiagnostics {
        triangle_diagnostics::analyze(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::validate::ValidationError;

    #[test]
    fn try_new_rejects_shape_mismatch() {
        assert_eq!(
            Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0]),
            Err(ValidationError::ShapeMismatch)
        );
    }

    #[test]
    fn try_new_accepts_valid_square_triangle() {
        let triangle = Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0, f64::NAN]).expect("triangle");

        assert_eq!(triangle.n_origins, 2);
        assert_eq!(triangle.n_devs, 2);
        assert_eq!(triangle, triangle.clone());
        assert_eq!(triangle.view(), triangle.view());
    }

    #[test]
    fn triangle_serde_json_roundtrips_nan_and_validates() {
        let triangle =
            Triangle::try_from_upper_rows(&[&[100.0, 160.0, 195.0], &[120.0, 190.0], &[135.0]])
                .expect("triangle");
        let json = serde_json::to_string(&triangle).expect("serialize");
        let decoded: Triangle = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(triangle, decoded);

        let malformed = r#"{"n_origins":3,"n_devs":3,"data":[1.0]}"#;
        assert!(serde_json::from_str::<Triangle>(malformed).is_err());
    }
}