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