Skip to main content

reserving_kernels/
mack.rs

1//! Mack's distribution-free chain-ladder standard error.
2//!
3//! Implements:
4//!
5//! * Mack (1993), *Distribution-Free Calculation of the Standard Error of Chain
6//!   Ladder Reserve Estimates*, ASTIN Bulletin, Vol. 23, No. 2, pp. 213–225.
7//! * Mack (1999), *The Standard Error of Chain Ladder Reserve Estimates:
8//!   Recursive Calculation and Inclusion of a Tail Factor*, ASTIN Bulletin,
9//!   Vol. 29, No. 2, pp. 361–366.
10//!
11//! Notation (0-indexed, square triangle of size `n`):
12//!
13//! * `f_k = Σ_i C_{i, k+1} / Σ_i C_{i, k}` — volume-weighted LDF at link
14//!   `k`, summed over `i = 0..n−k−2`.
15//! * `σ²_k = 1/(n_k − 1) × Σ_i C_{i, k} × (C_{i, k+1}/C_{i, k} − f_k)²`
16//!   with `n_k = n − k − 1` (observed pairs at link `k`).
17//! * For the last link (`k = n − 2`, only one pair observed) `σ²` is
18//!   extrapolated via Mack's min-rule:
19//!   `σ²_{n−2} = min(σ⁴_{n−3}/σ²_{n−4}, σ²_{n−3}, σ²_{n−4})`.
20//! * `Ĉ_{i,k}` — projected cumulative for origin `i` at development `k`,
21//!   defined observationally for `k ≤ n − 1 − i` and by chain-ladder for
22//!   `k > n − 1 − i`.
23//! * `S_k = Σ_{i=0}^{n_k−1} C_{i,k}` — column sum entering the LDF.
24//!
25//! Per-origin MSE (Mack 1993, Theorem 3 / Eq. 7):
26//!
27//! `MSE(Û_i) = Û_i² × Σ_{k = n−1−i}^{n−2} σ²_k/f²_k × (1/Ĉ_{i,k} + 1/S_k)`.
28//!
29//! Total-reserve MSE (Mack 1993, Theorem 3 / Eq. 15):
30//!
31//! `MSE(ΣR) = Σ MSE(R_i) + 2 × Σ_{i<j} Û_i Û_j × Σ_{k=n−1−i}^{n−2}
32//!            σ²_k / (f²_k × S_k)`.
33//!
34//! With a stochastic tail factor `f_tail` carrying process variance
35//! `σ²_tail` and parameter standard error `se(f_tail)` (Mack 1999, Eq. 4):
36//!
37//! `MSE(Û_i) = f_tail² × MSE(Ĉ_{i,n−1}) + Ĉ_{i,n−1} × σ²_tail + Ĉ_{i,n−1}² × se(f_tail)²`,
38//!
39//! and every pair `0 ≤ i < j < n` gains cross-origin tail covariance
40//! `2 × Ĉ_{i,n−1} × Ĉ_{j,n−1} × se(f_tail)²`.
41
42use crate::ldf::volume_weighted_ldfs_observed_counts;
43use crate::triangle::latest_diagonal;
44use crate::types::TriangleView;
45use crate::validate::{
46    MonotonicityPolicy, ValidationError, validate_monotone_cumulative,
47    validate_observed_count_inputs, validate_tail, validate_triangle,
48};
49
50/// Tail-factor mean and variance parameters for Mack (1999) recursive standard errors.
51#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
52pub struct MackTailSpec {
53    /// Multiplicative tail factor `f_tail >= 1.0`.
54    pub tail_factor: f64,
55    /// Tail process variance parameter `sigma_tail^2 >= 0.0` (Mack 1999, Eq. 4).
56    pub tail_sigma_sq: f64,
57    /// Tail parameter estimation standard error `se(f_tail) >= 0.0` (Mack 1999, Eq. 4).
58    pub tail_se: f64,
59}
60
61impl MackTailSpec {
62    /// Fixed tail factor with zero modeled tail uncertainty.
63    #[inline]
64    pub const fn fixed(tail_factor: f64) -> Self {
65        Self {
66            tail_factor,
67            tail_sigma_sq: 0.0,
68            tail_se: 0.0,
69        }
70    }
71}
72
73/// Full Mack chain-ladder result: point estimates and standard errors.
74#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
75pub struct Mack {
76    /// Volume-weighted LDFs, length `n − 1`.
77    pub ldf: Vec<f64>,
78    /// Mack σ² per development link, length `n − 1`.
79    pub sigma_sq: Vec<f64>,
80    /// Chain-ladder ultimates per origin, length `n`.
81    pub ultimate: Vec<f64>,
82    /// Reserves per origin, length `n`.
83    pub reserve: Vec<f64>,
84    /// Standard error per origin, length `n`.
85    pub standard_error: Vec<f64>,
86    /// Coefficient of variation per origin (SE / reserve), length `n`.
87    pub cv: Vec<f64>,
88    /// Total reserve across origins.
89    pub total_reserve: f64,
90    /// Total MSE (sum of per-origin MSE plus covariance adjustment).
91    pub total_mse: f64,
92    /// Total standard error: `sqrt(total_mse)`.
93    pub total_standard_error: f64,
94    /// Total coefficient of variation: `total_se / total_reserve`.
95    pub total_cv: f64,
96}
97
98impl std::fmt::Display for Mack {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        write!(
101            f,
102            "Mack(reserve={:.2}, se={:.2}, cv={:.2}%)",
103            self.total_reserve,
104            self.total_standard_error,
105            self.total_cv * 100.0
106        )
107    }
108}
109
110fn sigma_sq_vec(t: &TriangleView<'_>, f: &[f64]) -> Vec<f64> {
111    let n = t.n_origins.min(t.n_devs);
112    if n < 2 {
113        return Vec::new();
114    }
115    let mut s: Vec<Option<f64>> = vec![None; n - 1];
116    // Links k = 0..n-2; observed pairs n_k = n - k - 1.
117    for k in 0..n - 1 {
118        let nk = n - k - 1;
119        let mut acc = 0.0;
120        let mut valid = 0usize;
121        let mut invalid_zero = false;
122        for i in 0..nk {
123            let c_k = t.get(i, k);
124            let c_kp1 = t.get(i, k + 1);
125            if c_k > 0.0 {
126                let ratio = c_kp1 / c_k;
127                acc += c_k * (ratio - f[k]).powi(2);
128                valid += 1;
129            } else if c_k == 0.0 && c_kp1 == 0.0 {
130                // Zero prior and zero next contributes 0 to variance and does not
131                // provide an independent ratio observation.
132            } else {
133                invalid_zero = true;
134                break;
135            }
136        }
137        if invalid_zero {
138            s[k] = Some(f64::NAN);
139        } else if valid >= 2 {
140            s[k] = Some(acc / (valid as f64 - 1.0));
141        }
142        // valid < 2 remains None for Mack's extrapolation below.
143    }
144    // Extrapolate missing links using Mack's min-rule.
145    let mut out = vec![0.0; n - 1];
146    for k in 0..n - 1 {
147        if let Some(val) = s[k] {
148            out[k] = val;
149        } else if k >= 2 {
150            let a = out[k - 1];
151            let b = out[k - 2];
152            out[k] = if a.is_finite() && b.is_finite() && a > 0.0 && b > 0.0 {
153                (a * a / b).min(a).min(b).max(0.0)
154            } else {
155                0.0
156            };
157        } else if k == 1 {
158            out[k] = if out[0].is_finite() {
159                out[0].max(0.0)
160            } else {
161                0.0
162            };
163        } else {
164            out[k] = 0.0;
165        }
166    }
167    out
168}
169
170fn sigma_sq_vec_observed_counts(
171    t: &TriangleView<'_>,
172    observed_counts: &[usize],
173    f: &[f64],
174) -> Vec<f64> {
175    let n_dev = t.n_devs;
176    if n_dev < 2 {
177        return Vec::new();
178    }
179    let mut s: Vec<Option<f64>> = vec![None; n_dev - 1];
180    for k in 0..n_dev - 1 {
181        let mut acc = 0.0;
182        let mut valid = 0usize;
183        let mut invalid_zero = false;
184        for (i, &count) in observed_counts.iter().enumerate() {
185            if count <= k + 1 {
186                continue;
187            }
188            let c_k = t.get(i, k);
189            let c_kp1 = t.get(i, k + 1);
190            if c_k > 0.0 {
191                let ratio = c_kp1 / c_k;
192                acc += c_k * (ratio - f[k]).powi(2);
193                valid += 1;
194            } else if c_k == 0.0 && c_kp1 == 0.0 {
195                // Zero prior and zero next contributes 0 to variance.
196            } else {
197                invalid_zero = true;
198                break;
199            }
200        }
201        if invalid_zero {
202            s[k] = Some(f64::NAN);
203        } else if valid >= 2 {
204            s[k] = Some(acc / (valid as f64 - 1.0));
205        }
206    }
207    extrapolate_missing_sigma(&s)
208}
209
210fn extrapolate_missing_sigma(sigma_sq: &[Option<f64>]) -> Vec<f64> {
211    let mut out = vec![0.0; sigma_sq.len()];
212    for k in 0..sigma_sq.len() {
213        if let Some(val) = sigma_sq[k] {
214            out[k] = val;
215            continue;
216        }
217        let mut last_two = [None, None];
218        for &value in &out[..k] {
219            if value.is_finite() && value >= 0.0 {
220                last_two[0] = last_two[1];
221                last_two[1] = Some(value);
222            }
223        }
224        out[k] = match last_two {
225            [Some(b), Some(a)] => {
226                if a > 0.0 && b > 0.0 {
227                    (a * a / b).min(a).min(b).max(0.0)
228                } else {
229                    0.0
230                }
231            }
232            [None, Some(a)] => a,
233            _ => 0.0,
234        };
235    }
236    out
237}
238
239/// Run the full Mack analysis without validation.
240///
241/// `tail` is the multiplicative tail factor (pass `1.0` for fully-developed).
242/// When a tail > 1 is applied, the reported standard errors capture only the
243/// chain-ladder development uncertainty — tail uncertainty is not modelled.
244/// Use [`analyze_with_tail_uncertainty`] to include Mack (1999) tail variance.
245///
246/// Prefer [`analyze`] at external ingress boundaries.
247pub fn analyze_unchecked(t: &TriangleView<'_>, tail: f64) -> Mack {
248    analyze_with_tail_spec_unchecked(t, MackTailSpec::fixed(tail))
249}
250
251/// Run the full Mack (1993 / 1999) analysis with an explicit [`MackTailSpec`]
252/// without validation.
253pub fn analyze_with_tail_spec_unchecked(t: &TriangleView<'_>, tail_spec: MackTailSpec) -> Mack {
254    let n = t.n_origins.min(t.n_devs);
255    let m = n.saturating_sub(1);
256    let tail = tail_spec.tail_factor;
257    let tail_se_sq = tail_spec.tail_se * tail_spec.tail_se;
258
259    // Fused row-major pass for column sums S_k and numerator sums -> LDFs.
260    let mut s_col = vec![0.0; m];
261    let mut num_col = vec![0.0; m];
262    let n_devs = t.n_devs;
263    for i in 0..m {
264        let row = &t.data[i * n_devs..i * n_devs + (n - i)];
265        let upper = n - 1 - i;
266        for k in 0..upper {
267            s_col[k] += row[k];
268            num_col[k] += row[k + 1];
269        }
270    }
271    let mut ldf = vec![0.0; m];
272    for k in 0..m {
273        ldf[k] = if s_col[k] > 0.0 {
274            num_col[k] / s_col[k]
275        } else {
276            f64::NAN
277        };
278    }
279
280    let sigma_sq = sigma_sq_vec(t, &ldf);
281
282    // Precompute per-link parameter & process multipliers once:
283    //   link_var[k] = sigma_k^2 / f_k^2
284    //   link_param[k] = sigma_k^2 / (f_k^2 * S_k)
285    let mut link_var = vec![0.0; m];
286    let mut link_param = vec![0.0; m];
287    for k in 0..m {
288        let fk = ldf[k];
289        let sk2 = sigma_sq[k];
290        let s = s_col[k];
291        if fk > 0.0 && s > 0.0 {
292            let lv = sk2 / (fk * fk);
293            link_var[k] = lv;
294            link_param[k] = lv / s;
295        }
296    }
297
298    // Suffix sums of link_param for O(1) covariance lookup:
299    //   cov_suffix[start] = sum_{k = start}^{m - 1} sigma_k^2 / (f_k^2 * S_k).
300    let mut cov_suffix = vec![0.0; n];
301    for k in (0..m).rev() {
302        cov_suffix[k] = cov_suffix[k + 1] + link_param[k];
303    }
304
305    // Compute ultimates, reserves, and per-origin MSE on-the-fly without an n × n matrix.
306    let mut ultimate = vec![0.0; n];
307    let mut reserve = vec![0.0; n];
308    let mut c_last_vec = vec![0.0; n];
309    let mut mse = vec![0.0; n];
310    let mut total_reserve = 0.0;
311    let mut total_mse = 0.0;
312
313    for i in 0..n {
314        let start = n - 1 - i;
315        let lat = t.get(i, start);
316        let mut c_hat = lat;
317        let mut acc = 0.0;
318        for k in start..m {
319            if c_hat > 0.0 {
320                acc += link_var[k] / c_hat + link_param[k];
321            }
322            c_hat *= ldf[k];
323        }
324        let c_last = c_hat;
325        c_last_vec[i] = c_last;
326        let ult = c_last * tail;
327        let res = ult - lat;
328        ultimate[i] = ult;
329        reserve[i] = res;
330        total_reserve += res;
331
332        let pre_tail_mse = if i >= 1 { c_last * c_last * acc } else { 0.0 };
333        let tail_process = if c_last > 0.0 {
334            c_last * tail_spec.tail_sigma_sq
335        } else {
336            0.0
337        };
338        let tail_param = c_last * c_last * tail_se_sq;
339        let mse_i = tail * tail * pre_tail_mse + tail_process + tail_param;
340        mse[i] = mse_i;
341        total_mse += mse_i;
342    }
343
344    let standard_error: Vec<f64> = mse
345        .iter()
346        .map(|&v| {
347            if v.is_finite() {
348                v.max(0.0).sqrt()
349            } else {
350                f64::NAN
351            }
352        })
353        .collect();
354    let cv: Vec<f64> = standard_error
355        .iter()
356        .zip(reserve.iter())
357        .map(|(s, r)| if *r > 0.0 { s / r } else { 0.0 })
358        .collect();
359
360    // O(n) cross-origin covariance using suffix sums of ultimate[j] and c_last[j]:
361    //   2 * sum_{i < j} [ U_i U_j cov_suffix[n - 1 - i] + C_{i,n-1} C_{j,n-1} se(f_tail)^2 ].
362    let mut ult_suffix = 0.0;
363    let mut c_last_suffix = 0.0;
364    for i in (0..n).rev() {
365        let start = n - 1 - i;
366        if i >= 1 {
367            total_mse += 2.0 * ultimate[i] * ult_suffix * cov_suffix[start];
368        }
369        if tail_se_sq > 0.0 {
370            total_mse += 2.0 * c_last_vec[i] * c_last_suffix * tail_se_sq;
371        }
372        ult_suffix += ultimate[i];
373        c_last_suffix += c_last_vec[i];
374    }
375
376    let total_standard_error = if total_mse.is_finite() {
377        total_mse.max(0.0).sqrt()
378    } else {
379        f64::NAN
380    };
381    let total_cv = if total_reserve > 0.0 {
382        total_standard_error / total_reserve
383    } else {
384        0.0
385    };
386
387    Mack {
388        ldf,
389        sigma_sq,
390        ultimate,
391        reserve,
392        standard_error,
393        cv,
394        total_reserve,
395        total_mse,
396        total_standard_error,
397        total_cv,
398    }
399}
400
401/// Run Mack analysis for rectangular/ragged triangles using observed row widths.
402///
403/// `observed_counts[i]` is the number of observed development periods in
404/// origin row `i`. The latest value is taken from `observed_counts[i] - 1`, and
405/// each development link uses rows where both adjacent cells are observed.
406pub fn analyze_observed_counts(
407    t: &TriangleView<'_>,
408    observed_counts: &[usize],
409    tail: f64,
410) -> Result<Mack, ValidationError> {
411    validate_observed_count_inputs(t, observed_counts, tail)?;
412
413    let n_origin = t.n_origins;
414    let n_dev = t.n_devs;
415    let mut ldf = vec![0.0; n_dev.saturating_sub(1)];
416    volume_weighted_ldfs_observed_counts(t.data, n_origin, n_dev, observed_counts, &mut ldf);
417    if ldf.iter().any(|value| !value.is_finite()) {
418        return Err(ValidationError::DivideByZero("development denominator"));
419    }
420
421    let sigma_sq = sigma_sq_vec_observed_counts(t, observed_counts, &ldf);
422    if sigma_sq.iter().any(|value| !value.is_finite()) {
423        return Err(ValidationError::NotFinite);
424    }
425
426    let mut s_col = vec![0.0; n_dev.saturating_sub(1)];
427    for k in 0..n_dev.saturating_sub(1) {
428        let mut acc = 0.0;
429        for (i, &count) in observed_counts.iter().enumerate() {
430            if count > k + 1 {
431                acc += t.get(i, k);
432            }
433        }
434        s_col[k] = acc;
435    }
436
437    let mut latest = vec![0.0; n_origin];
438    let mut latest_dev = vec![0; n_origin];
439    for i in 0..n_origin {
440        latest_dev[i] = observed_counts[i] - 1;
441        latest[i] = t.get(i, latest_dev[i]);
442    }
443
444    let mut proj = vec![0.0; n_origin * n_dev];
445    for i in 0..n_origin {
446        let start = latest_dev[i];
447        proj[i * n_dev + start] = latest[i];
448        for k in (start + 1)..n_dev {
449            proj[i * n_dev + k] = proj[i * n_dev + k - 1] * ldf[k - 1];
450        }
451    }
452
453    let mut ultimate = vec![0.0; n_origin];
454    let mut reserve = vec![0.0; n_origin];
455    for i in 0..n_origin {
456        ultimate[i] = proj[i * n_dev + (n_dev - 1)] * tail;
457        reserve[i] = ultimate[i] - latest[i];
458    }
459
460    let mut mse = vec![0.0; n_origin];
461    for i in 0..n_origin {
462        let start = latest_dev[i];
463        let mut acc = 0.0;
464        for k in start..n_dev.saturating_sub(1) {
465            let fk = ldf[k];
466            let sk2 = sigma_sq[k];
467            let c_hat = proj[i * n_dev + k];
468            let s = s_col[k];
469            if fk > 0.0 && c_hat > 0.0 && s > 0.0 {
470                acc += (sk2 / (fk * fk)) * (1.0 / c_hat + 1.0 / s);
471            }
472        }
473        let u = ultimate[i];
474        mse[i] = u * u * acc;
475    }
476
477    let standard_error: Vec<f64> = mse.iter().map(|value| value.sqrt()).collect();
478    let cv: Vec<f64> = standard_error
479        .iter()
480        .zip(reserve.iter())
481        .map(|(standard_error, reserve)| {
482            if *reserve > 0.0 {
483                standard_error / reserve
484            } else {
485                0.0
486            }
487        })
488        .collect();
489    let total_reserve: f64 = reserve.iter().sum();
490
491    let mut total_mse: f64 = mse.iter().sum();
492    for i in 0..n_origin {
493        for j in (i + 1)..n_origin {
494            let start = latest_dev[i].max(latest_dev[j]);
495            let mut cov_sum = 0.0;
496            for k in start..n_dev.saturating_sub(1) {
497                let fk = ldf[k];
498                let sk2 = sigma_sq[k];
499                let s = s_col[k];
500                if fk > 0.0 && s > 0.0 {
501                    cov_sum += sk2 / (fk * fk * s);
502                }
503            }
504            total_mse += 2.0 * ultimate[i] * ultimate[j] * cov_sum;
505        }
506    }
507
508    let total_standard_error = total_mse.max(0.0).sqrt();
509    let total_cv = if total_reserve > 0.0 {
510        total_standard_error / total_reserve
511    } else {
512        0.0
513    };
514
515    Ok(Mack {
516        ldf,
517        sigma_sq,
518        ultimate,
519        reserve,
520        standard_error,
521        cv,
522        total_reserve,
523        total_mse,
524        total_standard_error,
525        total_cv,
526    })
527}
528
529/// Run Mack analysis after validating square-triangle and development inputs.
530///
531/// `tail > 1` scales point estimates, but tail-factor uncertainty is not
532/// included in the Mack standard errors. Use [`analyze_with_tail_uncertainty`]
533/// to incorporate Mack (1999) tail variance, or [`analyze_with_policy`] when
534/// analyzing triangles with negative incremental development (e.g., incurred
535/// case-reserve releases or Mack's 1993 RAA dataset).
536pub fn analyze(t: &TriangleView<'_>, tail: f64) -> Result<Mack, ValidationError> {
537    analyze_with_policy(t, tail, MonotonicityPolicy::Strict)
538}
539
540/// Run Mack analysis under an explicit [`MonotonicityPolicy`].
541pub fn analyze_with_policy(
542    t: &TriangleView<'_>,
543    tail: f64,
544    policy: MonotonicityPolicy,
545) -> Result<Mack, ValidationError> {
546    analyze_with_tail_uncertainty_and_policy(t, MackTailSpec::fixed(tail), policy)
547}
548
549/// Run Mack (1999) recursive standard-error analysis including tail uncertainty.
550pub fn analyze_with_tail_uncertainty(
551    t: &TriangleView<'_>,
552    tail_spec: MackTailSpec,
553) -> Result<Mack, ValidationError> {
554    analyze_with_tail_uncertainty_and_policy(t, tail_spec, MonotonicityPolicy::Strict)
555}
556
557/// Run Mack (1999) recursive standard-error analysis with explicit tail
558/// uncertainty and [`MonotonicityPolicy`].
559pub fn analyze_with_tail_uncertainty_and_policy(
560    t: &TriangleView<'_>,
561    tail_spec: MackTailSpec,
562    policy: MonotonicityPolicy,
563) -> Result<Mack, ValidationError> {
564    validate_triangle(t)?;
565    if policy == MonotonicityPolicy::Strict {
566        validate_monotone_cumulative(t)?;
567    }
568    validate_tail_spec(tail_spec)?;
569    let n = t.n_origins;
570    let n_devs = t.n_devs;
571    for i in 0..n.saturating_sub(1) {
572        let row = &t.data[i * n_devs..i * n_devs + (n - i)];
573        for k in 0..(n - 1 - i) {
574            if row[k] == 0.0 && row[k + 1] != 0.0 {
575                return Err(ValidationError::DivideByZero("mack link denominator"));
576            }
577        }
578    }
579    let result = analyze_with_tail_spec_unchecked(t, tail_spec);
580    if result.ldf.iter().any(|&v| !v.is_finite() || v <= 0.0) {
581        return Err(ValidationError::DivideByZero("development denominator"));
582    }
583    Ok(result)
584}
585
586/// Configuration for generalized Mack chain-ladder analysis with custom
587/// weighting exponent `alpha` (Murphy 1994; `mages/ChainLadder`) and optional
588/// per-cell outlier/exclusion weights.
589#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
590pub struct MackOptions {
591    /// Tail factor and optional Mack (1999) tail variance specification.
592    pub tail_spec: MackTailSpec,
593    /// Variance weighting exponent $\alpha$:
594    /// - `1.0` (default): classical volume-weighted chain ladder (Mack 1993)
595    /// - `0.0`: OLS regression through the origin
596    /// - `2.0`: unweighted simple average of individual link ratios
597    pub alpha: f64,
598    /// Monotonicity validation policy for the cumulative input triangle.
599    pub policy: MonotonicityPolicy,
600    /// Optional row-major cell weight mask of length `n_origins * n_devs`
601    /// (`0.0` excludes a link from LDF and $\hat{\sigma}_k^2$ estimation;
602    /// positive values scale the cell's weight).
603    pub weights: Option<Vec<f64>>,
604}
605
606impl Default for MackOptions {
607    fn default() -> Self {
608        Self {
609            tail_spec: MackTailSpec::fixed(1.0),
610            alpha: 1.0,
611            policy: MonotonicityPolicy::Strict,
612            weights: None,
613        }
614    }
615}
616
617impl MackOptions {
618    /// Set the variance weighting exponent $\alpha$ (`0.0`, `1.0`, or `2.0`).
619    pub fn with_alpha(mut self, alpha: f64) -> Self {
620        self.alpha = alpha;
621        self
622    }
623
624    /// Set the tail specification.
625    pub fn with_tail_spec(mut self, tail_spec: MackTailSpec) -> Self {
626        self.tail_spec = tail_spec;
627        self
628    }
629
630    /// Set the monotonicity validation policy.
631    pub fn with_policy(mut self, policy: MonotonicityPolicy) -> Self {
632        self.policy = policy;
633        self
634    }
635
636    /// Set a row-major cell weight / outlier-exclusion mask.
637    pub fn with_weights(mut self, weights: Vec<f64>) -> Self {
638        self.weights = Some(weights);
639        self
640    }
641}
642
643/// Run generalized Mack (1993 / 1999) / Murphy (1994) analysis with explicit
644/// `alpha` weighting and optional cell weight/exclusion mask.
645pub fn analyze_with_options(
646    t: &TriangleView<'_>,
647    options: &MackOptions,
648) -> Result<Mack, ValidationError> {
649    if !options.alpha.is_finite() {
650        return Err(ValidationError::NotFinite);
651    }
652    if options.weights.is_none() && (options.alpha - 1.0).abs() <= 1e-12 {
653        return analyze_with_tail_uncertainty_and_policy(t, options.tail_spec, options.policy);
654    }
655
656    validate_triangle(t)?;
657    if options.policy == MonotonicityPolicy::Strict {
658        validate_monotone_cumulative(t)?;
659    }
660    validate_tail_spec(options.tail_spec)?;
661
662    let n = t.n_origins.min(t.n_devs);
663    if n < 2 {
664        return Err(ValidationError::ShapeMismatch);
665    }
666    if let Some(ref w) = options.weights {
667        if w.len() != t.n_origins * t.n_devs {
668            return Err(ValidationError::ShapeMismatch);
669        }
670        if w.iter().any(|&v| !v.is_finite() || v < 0.0) {
671            return Err(ValidationError::Negative);
672        }
673    }
674
675    let alpha = options.alpha;
676    let cell_w = |i: usize, k: usize| -> f64 {
677        options
678            .weights
679            .as_ref()
680            .map_or(1.0, |w| w[i * t.n_devs + k])
681    };
682
683    let n_steps = n - 1;
684    let mut ldf = vec![1.0; n_steps];
685    let mut s_col = vec![0.0; n_steps];
686    let mut sigma_sq = vec![0.0; n_steps];
687
688    for k in 0..n_steps {
689        let nk = n - 1 - k;
690        let mut num = 0.0;
691        let mut den = 0.0;
692        for i in 0..nk {
693            let w = cell_w(i, k);
694            if w <= 0.0 {
695                continue;
696            }
697            let c0 = t.get(i, k);
698            let c1 = t.get(i, k + 1);
699            if !c0.is_finite() || !c1.is_finite() || c0 <= 0.0 {
700                continue;
701            }
702            let c_pow = c0.powf(alpha);
703            num += w * c_pow * (c1 / c0);
704            den += w * c_pow;
705        }
706        if den <= 0.0 {
707            return Err(ValidationError::DivideByZero("mack weighted denominator"));
708        }
709        let fk = num / den;
710        ldf[k] = fk;
711        s_col[k] = den;
712
713        let mut active = 0usize;
714        let mut sse = 0.0;
715        for i in 0..nk {
716            let w = cell_w(i, k);
717            if w <= 0.0 {
718                continue;
719            }
720            let c0 = t.get(i, k);
721            let c1 = t.get(i, k + 1);
722            if !c0.is_finite() || !c1.is_finite() || c0 <= 0.0 {
723                continue;
724            }
725            active += 1;
726            let diff = (c1 / c0) - fk;
727            sse += w * c0.powf(alpha) * diff * diff;
728        }
729        if active >= 2 {
730            sigma_sq[k] = (sse / (active - 1) as f64).max(0.0);
731        }
732    }
733
734    // Mack (1993) extrapolation for the last column when fewer than 2 active links exist.
735    if n_steps >= 3 && sigma_sq[n_steps - 1] == 0.0 {
736        let s1 = sigma_sq[n_steps - 2];
737        let s2 = sigma_sq[n_steps - 3];
738        if s2 > 0.0 {
739            sigma_sq[n_steps - 1] = (s1 * s1 / s2).min(s1.min(s2)).max(0.0);
740        }
741    }
742
743    let tail = options.tail_spec.tail_factor;
744    let tail_se_sq = options.tail_spec.tail_se * options.tail_spec.tail_se;
745    let latest = latest_diagonal(t);
746
747    let mut proj = vec![0.0; n * n];
748    for i in 0..n {
749        let start = n - 1 - i;
750        proj[i * n + start] = latest[i];
751        for k in (start + 1)..n {
752            proj[i * n + k] = proj[i * n + k - 1] * ldf[k - 1];
753        }
754    }
755
756    let mut ultimate = vec![0.0; n];
757    let mut reserve = vec![0.0; n];
758    for i in 0..n {
759        ultimate[i] = proj[i * n + (n - 1)] * tail;
760        reserve[i] = ultimate[i] - latest[i];
761    }
762
763    let mut mse = vec![0.0; n];
764    for i in 0..n {
765        let c_last = proj[i * n + (n - 1)];
766        let mut pre_tail_mse = 0.0;
767        if i >= 1 {
768            let start = n - 1 - i;
769            let mut acc = 0.0;
770            for k in start..n_steps {
771                let fk = ldf[k];
772                let sk2 = sigma_sq[k];
773                let c_hat = proj[i * n + k];
774                let s = s_col[k];
775                if fk > 0.0 && c_hat > 0.0 && s > 0.0 {
776                    acc += (sk2 / (fk * fk)) * (1.0 / c_hat.powf(alpha) + 1.0 / s);
777                }
778            }
779            pre_tail_mse = c_last * c_last * acc;
780        }
781        let tail_process = if c_last > 0.0 {
782            c_last * options.tail_spec.tail_sigma_sq
783        } else {
784            0.0
785        };
786        let tail_param = c_last * c_last * tail_se_sq;
787        mse[i] = tail * tail * pre_tail_mse + tail_process + tail_param;
788    }
789
790    let standard_error: Vec<f64> = mse
791        .iter()
792        .map(|&m| {
793            if m.is_finite() {
794                m.max(0.0).sqrt()
795            } else {
796                f64::NAN
797            }
798        })
799        .collect();
800    let cv: Vec<f64> = standard_error
801        .iter()
802        .zip(reserve.iter())
803        .map(|(s, r)| if *r > 0.0 { s / r } else { 0.0 })
804        .collect();
805    let total_reserve: f64 = reserve.iter().sum();
806
807    let mut total_mse: f64 = mse.iter().sum();
808    for i in 0..n {
809        let c_last_i = proj[i * n + (n - 1)];
810        let start = n - 1 - i;
811        let mut cov_sum = 0.0;
812        if i >= 1 {
813            for k in start..n_steps {
814                let fk = ldf[k];
815                let sk2 = sigma_sq[k];
816                let s = s_col[k];
817                if fk > 0.0 && s > 0.0 {
818                    cov_sum += sk2 / (fk * fk * s);
819                }
820            }
821        }
822        for j in (i + 1)..n {
823            let c_last_j = proj[j * n + (n - 1)];
824            total_mse +=
825                2.0 * ultimate[i] * ultimate[j] * cov_sum + 2.0 * c_last_i * c_last_j * tail_se_sq;
826        }
827    }
828
829    let total_standard_error = if total_mse.is_finite() {
830        total_mse.max(0.0).sqrt()
831    } else {
832        f64::NAN
833    };
834    let total_cv = if total_reserve > 0.0 {
835        total_standard_error / total_reserve
836    } else {
837        0.0
838    };
839
840    Ok(Mack {
841        ldf,
842        sigma_sq,
843        ultimate,
844        reserve,
845        standard_error,
846        cv,
847        total_reserve,
848        total_mse,
849        total_standard_error,
850        total_cv,
851    })
852}
853
854fn validate_tail_spec(spec: MackTailSpec) -> Result<(), ValidationError> {
855    validate_tail(spec.tail_factor)?;
856    if !spec.tail_sigma_sq.is_finite() || !spec.tail_se.is_finite() {
857        return Err(ValidationError::NotFinite);
858    }
859    if spec.tail_sigma_sq < 0.0 || spec.tail_se < 0.0 {
860        return Err(ValidationError::Negative);
861    }
862    Ok(())
863}
864
865#[cfg(test)]
866mod observed_count_tests {
867    use super::*;
868
869    fn rectangular_data() -> Vec<f64> {
870        #[rustfmt::skip]
871        let data = vec![
872            100.0, 150.0, 180.0, 198.0,
873            120.0, 180.0, 216.0, f64::NAN,
874            140.0, 210.0, f64::NAN, f64::NAN,
875        ];
876        data
877    }
878
879    #[test]
880    fn analyze_observed_counts_projects_rectangular_triangle() {
881        let data = rectangular_data();
882        let view = TriangleView {
883            n_origins: 3,
884            n_devs: 4,
885            data: &data,
886        };
887
888        let result = analyze_observed_counts(&view, &[4, 3, 2], 1.0).expect("mack");
889
890        assert_eq!(result.ldf.len(), 3);
891        assert_eq!(result.reserve.len(), 3);
892        assert_eq!(result.standard_error.len(), 3);
893        assert!(result.total_reserve.is_finite());
894        assert!(result.total_standard_error.is_finite());
895        assert!(result.ultimate[0] >= 198.0);
896        assert!(result.ultimate[2] > 210.0);
897    }
898
899    #[test]
900    fn analyze_observed_counts_rejects_bad_count() {
901        let data = rectangular_data();
902        let view = TriangleView {
903            n_origins: 3,
904            n_devs: 4,
905            data: &data,
906        };
907
908        assert_eq!(
909            analyze_observed_counts(&view, &[4, 5, 2], 1.0).map(|_| ()),
910            Err(ValidationError::ShapeMismatch)
911        );
912    }
913}