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