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                f64::NAN
162            };
163        } else {
164            out[k] = f64::NAN;
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            _ => f64::NAN,
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/// Defaults to [`MonotonicityPolicy::AllowNegativeIncrements`] because Mack's
532/// (1993) assumptions do not require monotonically increasing rows (allowing
533/// incurred case-reserve releases and canonical benchmarks such as Mack's RAA
534/// triangle). Use [`analyze_with_policy`] with [`MonotonicityPolicy::Strict`]
535/// to enforce monotone paid triangles, or [`analyze_with_tail_uncertainty`] to
536/// incorporate Mack (1999) tail variance.
537///
538/// # Example
539/// ```rust
540/// use reserving_kernels::{Triangle, mack};
541///
542/// let tri = Triangle::try_from_upper_rows(&[
543///     &[100.0, 160.0, 195.0, 205.0],
544///     &[120.0, 190.0, 232.0],
545///     &[135.0, 218.0],
546///     &[150.0],
547/// ])?;
548/// let res = mack::analyze(&tri.view(), 1.0)?;
549/// assert!(res.total_reserve > 0.0);
550/// assert!(res.total_standard_error > 0.0);
551/// # Ok::<(), reserving_kernels::validate::ValidationError>(())
552/// ```
553pub fn analyze(t: &TriangleView<'_>, tail: f64) -> Result<Mack, ValidationError> {
554    analyze_with_policy(t, tail, MonotonicityPolicy::AllowNegativeIncrements)
555}
556
557/// Run Mack analysis under an explicit [`MonotonicityPolicy`].
558pub fn analyze_with_policy(
559    t: &TriangleView<'_>,
560    tail: f64,
561    policy: MonotonicityPolicy,
562) -> Result<Mack, ValidationError> {
563    analyze_with_tail_uncertainty_and_policy(t, MackTailSpec::fixed(tail), policy)
564}
565
566/// Run Mack (1999) recursive standard-error analysis including tail uncertainty.
567pub fn analyze_with_tail_uncertainty(
568    t: &TriangleView<'_>,
569    tail_spec: MackTailSpec,
570) -> Result<Mack, ValidationError> {
571    analyze_with_tail_uncertainty_and_policy(
572        t,
573        tail_spec,
574        MonotonicityPolicy::AllowNegativeIncrements,
575    )
576}
577
578/// Run Mack (1999) recursive standard-error analysis with explicit tail
579/// uncertainty and [`MonotonicityPolicy`].
580pub fn analyze_with_tail_uncertainty_and_policy(
581    t: &TriangleView<'_>,
582    tail_spec: MackTailSpec,
583    policy: MonotonicityPolicy,
584) -> Result<Mack, ValidationError> {
585    validate_triangle(t)?;
586    if policy == MonotonicityPolicy::Strict {
587        validate_monotone_cumulative(t)?;
588    }
589    validate_tail_spec(tail_spec)?;
590    let n = t.n_origins;
591    if n < 3 {
592        return Err(ValidationError::InvalidParameter(
593            "Mack variance estimation requires at least a 3x3 triangle",
594        ));
595    }
596    let n_devs = t.n_devs;
597    for i in 0..n.saturating_sub(1) {
598        let row = &t.data[i * n_devs..i * n_devs + (n - i)];
599        for k in 0..(n - 1 - i) {
600            if row[k] == 0.0 && row[k + 1] != 0.0 {
601                return Err(ValidationError::DivideByZero("mack link denominator"));
602            }
603        }
604    }
605    let result = analyze_with_tail_spec_unchecked(t, tail_spec);
606    if result.ldf.iter().any(|&v| !v.is_finite() || v <= 0.0) {
607        return Err(ValidationError::DivideByZero("development denominator"));
608    }
609    Ok(result)
610}
611
612/// Configuration for generalized Mack chain-ladder analysis with custom
613/// weighting exponent `alpha` (Murphy 1994; `mages/ChainLadder`) and optional
614/// per-cell outlier/exclusion weights.
615#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
616pub struct MackOptions {
617    /// Tail factor and optional Mack (1999) tail variance specification.
618    pub tail_spec: MackTailSpec,
619    /// Variance weighting exponent $\alpha$:
620    /// - `1.0` (default): classical volume-weighted chain ladder (Mack 1993)
621    /// - `0.0`: OLS regression through the origin
622    /// - `2.0`: unweighted simple average of individual link ratios
623    pub alpha: f64,
624    /// Monotonicity validation policy for the cumulative input triangle.
625    pub policy: MonotonicityPolicy,
626    /// Optional row-major cell weight mask of length `n_origins * n_devs`
627    /// (`0.0` excludes a link from LDF and $\hat{\sigma}_k^2$ estimation;
628    /// positive values scale the cell's weight).
629    pub weights: Option<Vec<f64>>,
630}
631
632impl Default for MackOptions {
633    fn default() -> Self {
634        Self {
635            tail_spec: MackTailSpec::fixed(1.0),
636            alpha: 1.0,
637            policy: MonotonicityPolicy::AllowNegativeIncrements,
638            weights: None,
639        }
640    }
641}
642
643impl MackOptions {
644    /// Set the variance weighting exponent $\alpha$ (`0.0`, `1.0`, or `2.0`).
645    pub fn with_alpha(mut self, alpha: f64) -> Self {
646        self.alpha = alpha;
647        self
648    }
649
650    /// Set the tail specification.
651    pub fn with_tail_spec(mut self, tail_spec: MackTailSpec) -> Self {
652        self.tail_spec = tail_spec;
653        self
654    }
655
656    /// Set the monotonicity validation policy.
657    pub fn with_policy(mut self, policy: MonotonicityPolicy) -> Self {
658        self.policy = policy;
659        self
660    }
661
662    /// Set a row-major cell weight / outlier-exclusion mask.
663    pub fn with_weights(mut self, weights: Vec<f64>) -> Self {
664        self.weights = Some(weights);
665        self
666    }
667}
668
669/// Run generalized Mack (1993 / 1999) / Murphy (1994) analysis with explicit
670/// `alpha` weighting and optional cell weight/exclusion mask.
671pub fn analyze_with_options(
672    t: &TriangleView<'_>,
673    options: &MackOptions,
674) -> Result<Mack, ValidationError> {
675    if !options.alpha.is_finite() {
676        return Err(ValidationError::NotFinite);
677    }
678    if options.weights.is_none() && (options.alpha - 1.0).abs() <= 1e-12 {
679        return analyze_with_tail_uncertainty_and_policy(t, options.tail_spec, options.policy);
680    }
681
682    validate_triangle(t)?;
683    if options.policy == MonotonicityPolicy::Strict {
684        validate_monotone_cumulative(t)?;
685    }
686    validate_tail_spec(options.tail_spec)?;
687
688    let n = t.n_origins.min(t.n_devs);
689    if n < 3 {
690        return Err(ValidationError::InvalidParameter(
691            "Mack variance estimation requires at least a 3x3 triangle",
692        ));
693    }
694    if let Some(ref w) = options.weights {
695        if w.len() != t.n_origins * t.n_devs {
696            return Err(ValidationError::ShapeMismatch);
697        }
698        if w.iter().any(|&v| !v.is_finite() || v < 0.0) {
699            return Err(ValidationError::Negative);
700        }
701    }
702
703    let alpha = options.alpha;
704    let cell_w = |i: usize, k: usize| -> f64 {
705        options
706            .weights
707            .as_ref()
708            .map_or(1.0, |w| w[i * t.n_devs + k])
709    };
710
711    let n_steps = n - 1;
712    let mut ldf = vec![1.0; n_steps];
713    let mut s_col = vec![0.0; n_steps];
714    let mut sigma_sq = vec![0.0; n_steps];
715
716    for k in 0..n_steps {
717        let nk = n - 1 - k;
718        let mut num = 0.0;
719        let mut den = 0.0;
720        for i in 0..nk {
721            let w = cell_w(i, k);
722            if w <= 0.0 {
723                continue;
724            }
725            let c0 = t.get(i, k);
726            let c1 = t.get(i, k + 1);
727            if !c0.is_finite() || !c1.is_finite() || c0 <= 0.0 {
728                continue;
729            }
730            let c_pow = c0.powf(alpha);
731            num += w * c_pow * (c1 / c0);
732            den += w * c_pow;
733        }
734        if den <= 0.0 {
735            return Err(ValidationError::DivideByZero("mack weighted denominator"));
736        }
737        let fk = num / den;
738        ldf[k] = fk;
739        s_col[k] = den;
740
741        let mut active = 0usize;
742        let mut sse = 0.0;
743        for i in 0..nk {
744            let w = cell_w(i, k);
745            if w <= 0.0 {
746                continue;
747            }
748            let c0 = t.get(i, k);
749            let c1 = t.get(i, k + 1);
750            if !c0.is_finite() || !c1.is_finite() || c0 <= 0.0 {
751                continue;
752            }
753            active += 1;
754            let diff = (c1 / c0) - fk;
755            sse += w * c0.powf(alpha) * diff * diff;
756        }
757        if active >= 2 {
758            sigma_sq[k] = (sse / (active - 1) as f64).max(0.0);
759        }
760    }
761
762    // Mack (1993) extrapolation for the last column when fewer than 2 active links exist.
763    if n_steps >= 3 && sigma_sq[n_steps - 1] == 0.0 {
764        let s1 = sigma_sq[n_steps - 2];
765        let s2 = sigma_sq[n_steps - 3];
766        if s2 > 0.0 {
767            sigma_sq[n_steps - 1] = (s1 * s1 / s2).min(s1.min(s2)).max(0.0);
768        }
769    }
770
771    let tail = options.tail_spec.tail_factor;
772    let tail_se_sq = options.tail_spec.tail_se * options.tail_spec.tail_se;
773    let latest = latest_diagonal(t);
774
775    let mut proj = vec![0.0; n * n];
776    for i in 0..n {
777        let start = n - 1 - i;
778        proj[i * n + start] = latest[i];
779        for k in (start + 1)..n {
780            proj[i * n + k] = proj[i * n + k - 1] * ldf[k - 1];
781        }
782    }
783
784    let mut ultimate = vec![0.0; n];
785    let mut reserve = vec![0.0; n];
786    for i in 0..n {
787        ultimate[i] = proj[i * n + (n - 1)] * tail;
788        reserve[i] = ultimate[i] - latest[i];
789    }
790
791    let mut mse = vec![0.0; n];
792    for i in 0..n {
793        let c_last = proj[i * n + (n - 1)];
794        let mut pre_tail_mse = 0.0;
795        if i >= 1 {
796            let start = n - 1 - i;
797            let mut acc = 0.0;
798            for k in start..n_steps {
799                let fk = ldf[k];
800                let sk2 = sigma_sq[k];
801                let c_hat = proj[i * n + k];
802                let s = s_col[k];
803                if fk > 0.0 && c_hat > 0.0 && s > 0.0 {
804                    acc += (sk2 / (fk * fk)) * (1.0 / c_hat.powf(alpha) + 1.0 / s);
805                }
806            }
807            pre_tail_mse = c_last * c_last * acc;
808        }
809        let tail_process = if c_last > 0.0 {
810            c_last * options.tail_spec.tail_sigma_sq
811        } else {
812            0.0
813        };
814        let tail_param = c_last * c_last * tail_se_sq;
815        mse[i] = tail * tail * pre_tail_mse + tail_process + tail_param;
816    }
817
818    let standard_error: Vec<f64> = mse
819        .iter()
820        .map(|&m| {
821            if m.is_finite() {
822                m.max(0.0).sqrt()
823            } else {
824                f64::NAN
825            }
826        })
827        .collect();
828    let cv: Vec<f64> = standard_error
829        .iter()
830        .zip(reserve.iter())
831        .map(|(s, r)| if *r > 0.0 { s / r } else { 0.0 })
832        .collect();
833    let total_reserve: f64 = reserve.iter().sum();
834
835    let mut total_mse: f64 = mse.iter().sum();
836    for i in 0..n {
837        let c_last_i = proj[i * n + (n - 1)];
838        let start = n - 1 - i;
839        let mut cov_sum = 0.0;
840        if i >= 1 {
841            for k in start..n_steps {
842                let fk = ldf[k];
843                let sk2 = sigma_sq[k];
844                let s = s_col[k];
845                if fk > 0.0 && s > 0.0 {
846                    cov_sum += sk2 / (fk * fk * s);
847                }
848            }
849        }
850        for j in (i + 1)..n {
851            let c_last_j = proj[j * n + (n - 1)];
852            total_mse +=
853                2.0 * ultimate[i] * ultimate[j] * cov_sum + 2.0 * c_last_i * c_last_j * tail_se_sq;
854        }
855    }
856
857    let total_standard_error = if total_mse.is_finite() {
858        total_mse.max(0.0).sqrt()
859    } else {
860        f64::NAN
861    };
862    let total_cv = if total_reserve > 0.0 {
863        total_standard_error / total_reserve
864    } else {
865        0.0
866    };
867
868    Ok(Mack {
869        ldf,
870        sigma_sq,
871        ultimate,
872        reserve,
873        standard_error,
874        cv,
875        total_reserve,
876        total_mse,
877        total_standard_error,
878        total_cv,
879    })
880}
881
882fn validate_tail_spec(spec: MackTailSpec) -> Result<(), ValidationError> {
883    validate_tail(spec.tail_factor)?;
884    if !spec.tail_sigma_sq.is_finite() || !spec.tail_se.is_finite() {
885        return Err(ValidationError::NotFinite);
886    }
887    if spec.tail_sigma_sq < 0.0 || spec.tail_se < 0.0 {
888        return Err(ValidationError::Negative);
889    }
890    Ok(())
891}
892
893#[cfg(test)]
894mod observed_count_tests {
895    use super::*;
896
897    fn rectangular_data() -> Vec<f64> {
898        #[rustfmt::skip]
899        let data = vec![
900            100.0, 150.0, 180.0, 198.0,
901            120.0, 180.0, 216.0, f64::NAN,
902            140.0, 210.0, f64::NAN, f64::NAN,
903        ];
904        data
905    }
906
907    #[test]
908    fn analyze_observed_counts_projects_rectangular_triangle() {
909        let data = rectangular_data();
910        let view = TriangleView {
911            n_origins: 3,
912            n_devs: 4,
913            data: &data,
914        };
915
916        let result = analyze_observed_counts(&view, &[4, 3, 2], 1.0).expect("mack");
917
918        assert_eq!(result.ldf.len(), 3);
919        assert_eq!(result.reserve.len(), 3);
920        assert_eq!(result.standard_error.len(), 3);
921        assert!(result.total_reserve.is_finite());
922        assert!(result.total_standard_error.is_finite());
923        assert!(result.ultimate[0] >= 198.0);
924        assert!(result.ultimate[2] > 210.0);
925    }
926
927    #[test]
928    fn analyze_observed_counts_rejects_bad_count() {
929        let data = rectangular_data();
930        let view = TriangleView {
931            n_origins: 3,
932            n_devs: 4,
933            data: &data,
934        };
935
936        assert_eq!(
937            analyze_observed_counts(&view, &[4, 5, 2], 1.0).map(|_| ()),
938            Err(ValidationError::ShapeMismatch)
939        );
940    }
941}