Skip to main content

reserving_kernels/
ldf.rs

1//! Age-to-age development factors and CDF construction.
2//!
3//! This module is the Section 2 bridge:
4//!
5//! ```text
6//! cumulative triangle -> selected age-to-age LDFs -> CDFs -> maturity %
7//! ```
8//!
9//! Three layers, all in this file:
10//!
11//! * **L0 columnar kernels** — operate on flat row-major slices and
12//!   caller-provided output buffers (e.g. [`volume_weighted_ldfs`],
13//!   [`cdfs_from_ldfs`]). Used by the WASM hot path and the columnar Mack /
14//!   Brosius engines.
15//! * **L1 view convenience** — take a [`TriangleView`] and return owned
16//!   `Vec<f64>` (e.g. [`volume_weighted`], [`simple_average`],
17//!   [`cdf_from_ldf`]). Used by tests, the unchecked WASM path, and the
18//!   internal raw projection helpers.
19//! * **L2 service / engine** — validated entry points returning a typed
20//!   [`DevelopmentFactors`] result (see [`DevelopmentFactorEngine`]).
21//!
22//! Input is a row-major cumulative triangle; unobserved cells are `NaN`.
23//! Each LDF vector has length `n − 1`; the trailing tail factor (dev `n − 1`
24//! → ultimate) is supplied by the caller.
25
26use crate::triangle::age_to_age;
27use crate::types::TriangleView;
28use crate::validate::{
29    MonotonicityPolicy, ValidationError, validate_monotone_cumulative,
30    validate_positive_finite_slice, validate_triangle,
31};
32
33// ===========================================================================
34// Types
35// ===========================================================================
36
37/// Selected development factor family.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
39pub enum LdfSelectionMethod {
40    /// Volume-weighted link ratios.
41    VolumeWeighted,
42    /// Simple average link ratios.
43    SimpleAverage,
44    /// Median link ratios.
45    Median,
46    /// Exclude the single highest and lowest individual ratio when possible.
47    ExHiLo,
48    /// Volume-weighted link ratios restricted to the most recent `last_n` origins.
49    LastNVolumeWeighted {
50        /// Number of most recent origins to include.
51        last_n: usize,
52    },
53    /// Simple-average link ratios restricted to the most recent `last_n` origins.
54    LastNSimpleAverage {
55        /// Number of most recent origins to include.
56        last_n: usize,
57    },
58    /// Caller-selected link ratios.
59    Selected,
60}
61
62/// Selected age-to-age factors and cumulative development factors.
63#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
64pub struct DevelopmentFactors {
65    /// Selected age-to-age LDFs, length `n_dev - 1`.
66    pub ldfs: Vec<f64>,
67    /// CDFs by development age, length `n_dev`.
68    pub cdfs: Vec<f64>,
69    /// Tail factor from the final development age to ultimate.
70    pub tail: f64,
71}
72
73impl DevelopmentFactors {
74    /// Percent mature/reported at each development age, `1 / cdf[j]`.
75    pub fn maturity_percentages(&self) -> Vec<f64> {
76        self.cdfs
77            .iter()
78            .map(|&cdf| if cdf > 0.0 { 1.0 / cdf } else { f64::NAN })
79            .collect()
80    }
81}
82
83/// Numerator/denominator trail for one selected link ratio.
84#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
85pub struct LinkRatioDiagnostic {
86    /// Development age `j` for the `j -> j + 1` link.
87    pub dev: usize,
88    /// Sum of observed `C[i, j + 1]`.
89    pub numerator: f64,
90    /// Sum of observed `C[i, j]`.
91    pub denominator: f64,
92    /// Selected LDF, `numerator / denominator`.
93    pub selected_ldf: f64,
94    /// Number of origin rows included in the link.
95    pub included_rows: usize,
96}
97
98// ===========================================================================
99// L0 — columnar kernels (flat slices + output buffers)
100// ===========================================================================
101
102/// Return whether cell `(i, j)` is observed under right-triangle geometry.
103#[inline]
104pub const fn is_observed_right_triangle(i: usize, j: usize, n_dev: usize) -> bool {
105    i + j < n_dev
106}
107
108/// Volume-weighted age-to-age LDF for one development age.
109///
110/// Only origin rows where both `dev` and `dev + 1` are observed are included.
111#[inline]
112pub fn volume_weighted_ldf(cum: &[f64], n_origin: usize, n_dev: usize, dev: usize) -> f64 {
113    volume_weighted_link_diagnostic(cum, n_origin, n_dev, dev).selected_ldf
114}
115
116/// Diagnostic numerator/denominator trail for one volume-weighted LDF.
117pub fn volume_weighted_link_diagnostic(
118    cum: &[f64],
119    n_origin: usize,
120    n_dev: usize,
121    dev: usize,
122) -> LinkRatioDiagnostic {
123    debug_assert_eq!(cum.len(), n_origin * n_dev);
124    debug_assert!(dev + 1 < n_dev);
125
126    let mut numerator = 0.0;
127    let mut denominator = 0.0;
128    let mut included_rows = 0;
129
130    for i in 0..n_origin {
131        if is_observed_right_triangle(i, dev + 1, n_dev) {
132            denominator += cum[i * n_dev + dev];
133            numerator += cum[i * n_dev + dev + 1];
134            included_rows += 1;
135        }
136    }
137
138    let selected_ldf = if denominator > 0.0 {
139        numerator / denominator
140    } else {
141        f64::NAN
142    };
143
144    LinkRatioDiagnostic {
145        dev,
146        numerator,
147        denominator,
148        selected_ldf,
149        included_rows,
150    }
151}
152
153/// Volume-weighted LDFs for all development links (row-major cache-friendly accumulation).
154pub fn volume_weighted_ldfs(cum: &[f64], n_origin: usize, n_dev: usize, out: &mut [f64]) {
155    debug_assert_eq!(cum.len(), n_origin * n_dev);
156    let m = n_dev.saturating_sub(1);
157    debug_assert_eq!(out.len(), m);
158    if m == 0 || n_origin == 0 {
159        return;
160    }
161
162    // Use a stack buffer for common triangle sizes (<= 64 links) to avoid heap allocation.
163    let mut stack_den = [0.0_f64; 64];
164    let mut heap_den;
165    let den: &mut [f64] = if m <= stack_den.len() {
166        &mut stack_den[..m]
167    } else {
168        heap_den = vec![0.0_f64; m];
169        &mut heap_den[..]
170    };
171    out.fill(0.0);
172
173    let max_rows = n_origin.min(m);
174    for i in 0..max_rows {
175        let upper = m - i;
176        let row = &cum[(i * n_dev)..=(i * n_dev + upper)];
177        for dev in 0..upper {
178            den[dev] += row[dev];
179            out[dev] += row[dev + 1];
180        }
181    }
182
183    for dev in 0..m {
184        out[dev] = if den[dev] > 0.0 {
185            out[dev] / den[dev]
186        } else {
187            f64::NAN
188        };
189    }
190}
191
192/// Volume-weighted age-to-age LDF for arbitrary observed row widths.
193///
194/// `observed_counts[i]` is the number of observed development periods in row `i`.
195pub fn volume_weighted_ldf_observed_counts(
196    cum: &[f64],
197    n_origin: usize,
198    n_dev: usize,
199    observed_counts: &[usize],
200    dev: usize,
201) -> f64 {
202    volume_weighted_link_diagnostic_observed_counts(cum, n_origin, n_dev, observed_counts, dev)
203        .selected_ldf
204}
205
206/// Diagnostic numerator/denominator trail for arbitrary observed row widths.
207pub fn volume_weighted_link_diagnostic_observed_counts(
208    cum: &[f64],
209    n_origin: usize,
210    n_dev: usize,
211    observed_counts: &[usize],
212    dev: usize,
213) -> LinkRatioDiagnostic {
214    debug_assert_eq!(cum.len(), n_origin * n_dev);
215    debug_assert_eq!(observed_counts.len(), n_origin);
216    debug_assert!(dev + 1 < n_dev);
217
218    let mut numerator = 0.0;
219    let mut denominator = 0.0;
220    let mut included_rows = 0;
221
222    for i in 0..n_origin {
223        if observed_counts[i] > dev + 1 {
224            denominator += cum[i * n_dev + dev];
225            numerator += cum[i * n_dev + dev + 1];
226            included_rows += 1;
227        }
228    }
229
230    let selected_ldf = if denominator > 0.0 {
231        numerator / denominator
232    } else {
233        f64::NAN
234    };
235
236    LinkRatioDiagnostic {
237        dev,
238        numerator,
239        denominator,
240        selected_ldf,
241        included_rows,
242    }
243}
244
245/// Volume-weighted LDFs for arbitrary observed row widths.
246pub fn volume_weighted_ldfs_observed_counts(
247    cum: &[f64],
248    n_origin: usize,
249    n_dev: usize,
250    observed_counts: &[usize],
251    out: &mut [f64],
252) {
253    debug_assert_eq!(cum.len(), n_origin * n_dev);
254    debug_assert_eq!(observed_counts.len(), n_origin);
255    debug_assert_eq!(out.len(), n_dev.saturating_sub(1));
256
257    for dev in 0..n_dev.saturating_sub(1) {
258        out[dev] = volume_weighted_ldf_observed_counts(cum, n_origin, n_dev, observed_counts, dev);
259    }
260}
261
262/// CDFs from selected LDFs using the convention:
263///
264/// ```text
265/// cdfs[last_dev] = tail
266/// cdfs[j] = ldfs[j] * cdfs[j + 1]
267/// ```
268pub fn cdfs_from_ldfs(ldfs: &[f64], tail: f64, out: &mut [f64]) {
269    debug_assert_eq!(out.len(), ldfs.len() + 1);
270    if out.is_empty() {
271        return;
272    }
273
274    let last = out.len() - 1;
275    out[last] = tail;
276    for j in (0..ldfs.len()).rev() {
277        out[j] = ldfs[j] * out[j + 1];
278    }
279}
280
281/// Latest maturity percentage by origin under right-triangle geometry.
282pub fn latest_maturity_percentages(n_origin: usize, n_dev: usize, cdfs: &[f64], out: &mut [f64]) {
283    debug_assert_eq!(cdfs.len(), n_dev);
284    debug_assert_eq!(out.len(), n_origin);
285
286    for i in 0..n_origin {
287        if i >= n_dev {
288            out[i] = f64::NAN;
289            continue;
290        }
291        let latest_dev = n_dev - 1 - i;
292        let cdf = cdfs[latest_dev];
293        out[i] = if cdf > 0.0 { 1.0 / cdf } else { f64::NAN };
294    }
295}
296
297// ===========================================================================
298// L1 — view-based selection methods (returns Vec<f64>)
299// ===========================================================================
300
301/// Volume-weighted all-year LDF: `f_j = Σ_i C_{i, j+1} / Σ_i C_{i, j}`
302/// summing over origins where both cells are observed (`i ≤ n − j − 2`).
303///
304/// This is the classical chain-ladder factor. Returns a vector of length
305/// `n − 1`. Cells where the denominator is zero emit `NaN`.
306pub fn volume_weighted(t: &TriangleView<'_>) -> Vec<f64> {
307    let n = t.n_origins.min(t.n_devs);
308    if n < 2 {
309        return Vec::new();
310    }
311    let m = n - 1;
312    let mut out = vec![0.0; m];
313    let mut stack_den = [0.0_f64; 64];
314    let mut heap_den;
315    let den: &mut [f64] = if m <= stack_den.len() {
316        &mut stack_den[..m]
317    } else {
318        heap_den = vec![0.0_f64; m];
319        &mut heap_den[..]
320    };
321    for i in 0..m {
322        let upper = m - i;
323        let row = &t.data[(i * t.n_devs)..=(i * t.n_devs + upper)];
324        for j in 0..upper {
325            den[j] += row[j];
326            out[j] += row[j + 1];
327        }
328    }
329    for j in 0..m {
330        out[j] = if den[j] > 0.0 {
331            out[j] / den[j]
332        } else {
333            f64::NAN
334        };
335    }
336    out
337}
338
339/// Simple (straight) average of individual age-to-age ratios:
340/// `f_j = mean_i( C_{i, j+1} / C_{i, j} )`. Each origin contributes equal
341/// weight regardless of loss size. Returns a vector of length `n − 1`.
342pub fn simple_average(t: &TriangleView<'_>) -> Vec<f64> {
343    let n = t.n_origins.min(t.n_devs);
344    if n < 2 {
345        return Vec::new();
346    }
347    let mut out = vec![0.0; n - 1];
348    for j in 0..n - 1 {
349        let mut sum = 0.0;
350        let mut count = 0;
351        for i in 0..n - j - 1 {
352            let r = age_to_age(t, i, j);
353            if r.is_finite() {
354                sum += r;
355                count += 1;
356            }
357        }
358        out[j] = if count > 0 {
359            sum / f64::from(count)
360        } else {
361            f64::NAN
362        };
363    }
364    out
365}
366
367/// Median of individual age-to-age ratios for each development link.
368pub fn median(t: &TriangleView<'_>) -> Vec<f64> {
369    let n = t.n_origins.min(t.n_devs);
370    if n < 2 {
371        return Vec::new();
372    }
373    let mut out = vec![0.0; n - 1];
374    let mut scratch: Vec<f64> = Vec::with_capacity(n);
375    for j in 0..n - 1 {
376        scratch.clear();
377        for i in 0..n - j - 1 {
378            let r = age_to_age(t, i, j);
379            if r.is_finite() {
380                scratch.push(r);
381            }
382        }
383        scratch.sort_by(f64::total_cmp);
384        let k = scratch.len();
385        out[j] = if k == 0 {
386            f64::NAN
387        } else if k % 2 == 1 {
388            scratch[k / 2]
389        } else {
390            f64::midpoint(scratch[k / 2 - 1], scratch[k / 2])
391        };
392    }
393    out
394}
395
396/// Ex-hi / ex-lo (trimmed mean) of individual age-to-age ratios:
397/// `f_j = mean of the individual ratios after dropping the single max and
398/// single min`. When fewer than 3 ratios are available for a link, falls
399/// back to [`simple_average`] on that link.
400pub fn ex_hi_lo(t: &TriangleView<'_>) -> Vec<f64> {
401    let n = t.n_origins.min(t.n_devs);
402    if n < 2 {
403        return Vec::new();
404    }
405    let mut out = vec![0.0; n - 1];
406    let mut scratch: Vec<f64> = Vec::with_capacity(n);
407    for j in 0..n - 1 {
408        scratch.clear();
409        for i in 0..n - j - 1 {
410            let r = age_to_age(t, i, j);
411            if r.is_finite() {
412                scratch.push(r);
413            }
414        }
415        let k = scratch.len();
416        out[j] = if k >= 3 {
417            let mut min_idx = 0usize;
418            let mut max_idx = 0usize;
419            for (idx, &v) in scratch.iter().enumerate().skip(1) {
420                if v < scratch[min_idx] {
421                    min_idx = idx;
422                }
423                if v > scratch[max_idx] {
424                    max_idx = idx;
425                }
426            }
427            if min_idx == max_idx {
428                max_idx = 1;
429            }
430            let mut sum = 0.0;
431            for (idx, &v) in scratch.iter().enumerate() {
432                if idx != min_idx && idx != max_idx {
433                    sum += v;
434                }
435            }
436            sum / ((k - 2) as f64)
437        } else if k > 0 {
438            scratch.iter().sum::<f64>() / (k as f64)
439        } else {
440            f64::NAN
441        };
442    }
443    out
444}
445
446/// Volume-weighted average restricted to the last `last_n` origin years.
447///
448/// `f_j = Σ C_{i, j+1} / Σ C_{i, j}` where `i` runs over the most-recent
449/// `last_n` observed origins at development `j`. If `last_n == 0` or the
450/// link has fewer observations, falls back to all available origins.
451pub fn volume_weighted_last_n(t: &TriangleView<'_>, last_n: usize) -> Vec<f64> {
452    let n = t.n_origins.min(t.n_devs);
453    if n < 2 {
454        return Vec::new();
455    }
456    let mut out = vec![0.0; n - 1];
457    for j in 0..n - 1 {
458        let available = n - j - 1;
459        let use_k = if last_n == 0 {
460            available
461        } else {
462            available.min(last_n)
463        };
464        // Most-recent origins are the largest `i` in `0..available`.
465        let start = available - use_k;
466        let mut num = 0.0;
467        let mut den = 0.0;
468        for i in start..available {
469            num += t.get(i, j + 1);
470            den += t.get(i, j);
471        }
472        out[j] = if den > 0.0 { num / den } else { f64::NAN };
473    }
474    out
475}
476
477/// Simple-average LDF restricted to the last `last_n` origin years.
478pub fn simple_average_last_n(t: &TriangleView<'_>, last_n: usize) -> Vec<f64> {
479    let n = t.n_origins.min(t.n_devs);
480    if n < 2 {
481        return Vec::new();
482    }
483    let mut out = vec![0.0; n - 1];
484    for j in 0..n - 1 {
485        let available = n - j - 1;
486        let use_k = if last_n == 0 {
487            available
488        } else {
489            available.min(last_n)
490        };
491        let start = available - use_k;
492        let mut sum = 0.0;
493        let mut count = 0;
494        for i in start..available {
495            let r = age_to_age(t, i, j);
496            if r.is_finite() {
497                sum += r;
498                count += 1;
499            }
500        }
501        out[j] = if count > 0 {
502            sum / f64::from(count)
503        } else {
504            f64::NAN
505        };
506    }
507    out
508}
509
510/// Convert age-to-age LDFs into cumulative development factors (CDFs).
511///
512/// `cdf[j] = f[j] × f[j+1] × … × f[n−2] × tail`. CDF at the last development
513/// age (`j = n − 1`) is simply `tail`. The returned vector has length
514/// `ldf.len() + 1 == n`.
515pub fn cdf_from_ldf(ldf: &[f64], tail: f64) -> Vec<f64> {
516    let m = ldf.len();
517    let mut out = vec![0.0; m + 1];
518    out[m] = tail;
519    let mut acc = tail;
520    for j in (0..m).rev() {
521        acc *= ldf[j];
522        out[j] = acc;
523    }
524    out
525}
526
527/// Percent-reported vector from CDFs: `pct[j] = 1 / cdf[j]`. Length matches
528/// `cdf`. Emits `NaN` where `cdf[j]` is non-positive.
529pub fn pct_reported(cdf: &[f64]) -> Vec<f64> {
530    cdf.iter()
531        .map(|&x| if x > 0.0 { 1.0 / x } else { f64::NAN })
532        .collect()
533}
534
535/// Geometric average of positive observed individual link ratios at each
536/// development period. Emits `1.0` if no positive links exist.
537pub fn geometric_average(t: &TriangleView<'_>) -> Vec<f64> {
538    let m = t.n_devs.saturating_sub(1);
539    let mut out = vec![1.0; m];
540    for j in 0..m {
541        let mut log_sum = 0.0;
542        let mut count = 0usize;
543        for i in 0..t.n_origins {
544            let a = t.get(i, j);
545            let b = t.get(i, j + 1);
546            if a.is_finite() && b.is_finite() && a > 0.0 && b > 0.0 {
547                log_sum += (b / a).ln();
548                count += 1;
549            }
550        }
551        if count > 0 {
552            out[j] = (log_sum / count as f64).exp();
553        }
554    }
555    out
556}
557
558/// Volume-weighted LDFs with an explicit row-major cell weight/exclusion mask
559/// of length `n_origins * n_devs`. Setting `weights[i * n_devs + j] = 0.0`
560/// excludes origin `i` from development link `j -> j + 1`.
561pub fn weighted_volume_ldfs(
562    t: &TriangleView<'_>,
563    weights: &[f64],
564) -> Result<Vec<f64>, ValidationError> {
565    if weights.len() != t.n_origins * t.n_devs {
566        return Err(ValidationError::ShapeMismatch);
567    }
568    if weights.iter().any(|&w| !w.is_finite() || w < 0.0) {
569        return Err(ValidationError::Negative);
570    }
571    let m = t.n_devs.saturating_sub(1);
572    let mut out = vec![1.0; m];
573    for j in 0..m {
574        let mut num = 0.0;
575        let mut den = 0.0;
576        for i in 0..t.n_origins {
577            let w = weights[i * t.n_devs + j];
578            if w <= 0.0 {
579                continue;
580            }
581            let a = t.get(i, j);
582            let b = t.get(i, j + 1);
583            if a.is_finite() && b.is_finite() && a > 0.0 {
584                num += w * b;
585                den += w * a;
586            }
587        }
588        if den <= 0.0 {
589            return Err(ValidationError::DivideByZero(
590                "weighted development denominator",
591            ));
592        }
593        out[j] = num / den;
594    }
595    Ok(out)
596}
597
598// ===========================================================================
599// L2 — validated engine
600// ===========================================================================
601
602/// Section 2 development-factor service.
603#[derive(Debug, Clone, Copy, Default)]
604pub struct DevelopmentFactorEngine;
605
606impl DevelopmentFactorEngine {
607    fn factors_from_validated_ldfs(
608        n_devs: usize,
609        tail: f64,
610        ldfs: Vec<f64>,
611    ) -> Result<DevelopmentFactors, ValidationError> {
612        validate_positive_finite_slice(&ldfs, "development denominator")?;
613
614        let mut cdfs = vec![0.0; n_devs];
615        cdfs_from_ldfs(&ldfs, tail, &mut cdfs);
616        if cdfs.iter().any(|cdf| !cdf.is_finite()) {
617            return Err(ValidationError::NotFinite);
618        }
619
620        Ok(DevelopmentFactors { ldfs, cdfs, tail })
621    }
622
623    /// Select volume-weighted factors and CDFs from a validated cumulative triangle.
624    pub fn volume_weighted(
625        tri: &TriangleView<'_>,
626        tail: f64,
627    ) -> Result<DevelopmentFactors, ValidationError> {
628        Self::volume_weighted_with_policy(tri, tail, MonotonicityPolicy::Strict)
629    }
630
631    /// Select volume-weighted factors and CDFs under an explicit [`MonotonicityPolicy`].
632    pub fn volume_weighted_with_policy(
633        tri: &TriangleView<'_>,
634        tail: f64,
635        policy: MonotonicityPolicy,
636    ) -> Result<DevelopmentFactors, ValidationError> {
637        validate_development_inputs_with_policy(tri, tail, policy)?;
638        let mut ldfs = vec![0.0; tri.n_devs - 1];
639        volume_weighted_ldfs(tri.data, tri.n_origins, tri.n_devs, &mut ldfs);
640        Self::factors_from_validated_ldfs(tri.n_devs, tail, ldfs)
641    }
642
643    /// Select simple-average factors and CDFs from a validated cumulative triangle.
644    pub fn simple_average(
645        tri: &TriangleView<'_>,
646        tail: f64,
647    ) -> Result<DevelopmentFactors, ValidationError> {
648        validate_development_inputs(tri, tail)?;
649        Self::factors_from_validated_ldfs(tri.n_devs, tail, simple_average(tri))
650    }
651
652    /// Select median factors and CDFs from a validated cumulative triangle.
653    pub fn median(
654        tri: &TriangleView<'_>,
655        tail: f64,
656    ) -> Result<DevelopmentFactors, ValidationError> {
657        validate_development_inputs(tri, tail)?;
658        Self::factors_from_validated_ldfs(tri.n_devs, tail, median(tri))
659    }
660
661    /// Select ex-hi-lo factors and CDFs from a validated cumulative triangle.
662    pub fn ex_hi_lo(
663        tri: &TriangleView<'_>,
664        tail: f64,
665    ) -> Result<DevelopmentFactors, ValidationError> {
666        validate_development_inputs(tri, tail)?;
667        Self::factors_from_validated_ldfs(tri.n_devs, tail, ex_hi_lo(tri))
668    }
669
670    /// Select volume-weighted last-N factors and CDFs from a validated cumulative triangle.
671    pub fn volume_weighted_last_n(
672        tri: &TriangleView<'_>,
673        tail: f64,
674        last_n: usize,
675    ) -> Result<DevelopmentFactors, ValidationError> {
676        validate_development_inputs(tri, tail)?;
677        Self::factors_from_validated_ldfs(tri.n_devs, tail, volume_weighted_last_n(tri, last_n))
678    }
679
680    /// Select simple-average last-N factors and CDFs from a validated cumulative triangle.
681    pub fn simple_average_last_n(
682        tri: &TriangleView<'_>,
683        tail: f64,
684        last_n: usize,
685    ) -> Result<DevelopmentFactors, ValidationError> {
686        validate_development_inputs(tri, tail)?;
687        Self::factors_from_validated_ldfs(tri.n_devs, tail, simple_average_last_n(tri, last_n))
688    }
689
690    /// Select geometric-average factors and CDFs from a validated cumulative triangle.
691    pub fn geometric_average(
692        tri: &TriangleView<'_>,
693        tail: f64,
694    ) -> Result<DevelopmentFactors, ValidationError> {
695        validate_development_inputs(tri, tail)?;
696        Self::factors_from_validated_ldfs(tri.n_devs, tail, geometric_average(tri))
697    }
698
699    /// Select volume-weighted factors with a per-cell weight / outlier-exclusion
700    /// mask (`weights[i * n_devs + j] == 0.0` excludes the link `j -> j+1` for
701    /// origin `i`).
702    pub fn volume_weighted_masked(
703        tri: &TriangleView<'_>,
704        weights: &[f64],
705        tail: f64,
706        policy: MonotonicityPolicy,
707    ) -> Result<DevelopmentFactors, ValidationError> {
708        validate_development_inputs_with_policy(tri, tail, policy)?;
709        let ldfs = weighted_volume_ldfs(tri, weights)?;
710        Self::factors_from_validated_ldfs(tri.n_devs, tail, ldfs)
711    }
712
713    /// Diagnostics for volume-weighted link selections.
714    pub fn volume_weighted_diagnostics(
715        tri: &TriangleView<'_>,
716        tail: f64,
717    ) -> Result<Vec<LinkRatioDiagnostic>, ValidationError> {
718        validate_development_inputs(tri, tail)?;
719
720        let mut diagnostics = Vec::with_capacity(tri.n_devs - 1);
721        for dev in 0..tri.n_devs - 1 {
722            let diagnostic =
723                volume_weighted_link_diagnostic(tri.data, tri.n_origins, tri.n_devs, dev);
724            if !diagnostic.selected_ldf.is_finite() {
725                return Err(ValidationError::DivideByZero("development denominator"));
726            }
727            diagnostics.push(diagnostic);
728        }
729        Ok(diagnostics)
730    }
731}
732
733fn validate_development_inputs(tri: &TriangleView<'_>, tail: f64) -> Result<(), ValidationError> {
734    validate_development_inputs_with_policy(tri, tail, MonotonicityPolicy::Strict)
735}
736
737fn validate_development_inputs_with_policy(
738    tri: &TriangleView<'_>,
739    tail: f64,
740    policy: MonotonicityPolicy,
741) -> Result<(), ValidationError> {
742    validate_triangle(tri)?;
743    if tri.n_devs < 2 {
744        return Err(ValidationError::ShapeMismatch);
745    }
746    if !tail.is_finite() {
747        return Err(ValidationError::NotFinite);
748    }
749    if tail < 1.0 {
750        return Err(ValidationError::InvalidTail { tail });
751    }
752    if policy == MonotonicityPolicy::Strict {
753        validate_monotone_cumulative(tri)?;
754    }
755    Ok(())
756}
757
758#[cfg(test)]
759mod tests {
760    use super::*;
761    use crate::types::Triangle;
762
763    fn triangle_3x3() -> Triangle {
764        #[rustfmt::skip]
765        let data = vec![
766            100.0, 150.0, 180.0,
767            120.0, 180.0, f64::NAN,
768            140.0, f64::NAN, f64::NAN,
769        ];
770        Triangle::new(3, 3, data)
771    }
772
773    fn triangle_5x5() -> Triangle {
774        #[rustfmt::skip]
775        let data = vec![
776            100.0, 150.0, 180.0, 198.0, 207.9,
777            120.0, 180.0, 216.0, 237.6, f64::NAN,
778            140.0, 210.0, 252.0, f64::NAN, f64::NAN,
779            160.0, 240.0, f64::NAN, f64::NAN, f64::NAN,
780            180.0, f64::NAN, f64::NAN, f64::NAN, f64::NAN,
781        ];
782        Triangle::new(5, 5, data)
783    }
784
785    fn close(a: f64, b: f64) -> bool {
786        (a - b).abs() <= 1e-12 * (1.0 + b.abs())
787    }
788
789    #[test]
790    fn volume_weighted_single_ldf_uses_only_observed_pairs() {
791        let tri = triangle_3x3();
792
793        let f0 = volume_weighted_ldf(&tri.data, 3, 3, 0);
794        let f1 = volume_weighted_ldf(&tri.data, 3, 3, 1);
795
796        assert!(close(f0, (150.0 + 180.0) / (100.0 + 120.0)));
797        assert!(close(f1, 180.0 / 150.0));
798    }
799
800    #[test]
801    fn volume_weighted_all_ldfs_3x3() {
802        let tri = triangle_3x3();
803        let mut out = [0.0; 2];
804
805        volume_weighted_ldfs(&tri.data, 3, 3, &mut out);
806
807        assert!(close(out[0], 1.5));
808        assert!(close(out[1], 1.2));
809    }
810
811    #[test]
812    fn volume_weighted_all_ldfs_5x5() {
813        let tri = triangle_5x5();
814        let mut out = [0.0; 4];
815
816        volume_weighted_ldfs(&tri.data, 5, 5, &mut out);
817
818        assert!(close(out[0], 1.5));
819        assert!(close(out[1], 1.2));
820        assert!(close(out[2], 1.1));
821        assert!(close(out[3], 1.05));
822    }
823
824    #[test]
825    fn observed_counts_ldfs_handle_semiannual_rectangle() {
826        #[rustfmt::skip]
827        let cum = [
828            100.0, 150.0, 180.0, 198.0,
829            120.0, 180.0, f64::NAN, f64::NAN,
830            140.0, f64::NAN, f64::NAN, f64::NAN,
831        ];
832        let observed_counts = [4, 2, 1];
833        let mut out = [0.0; 3];
834
835        volume_weighted_ldfs_observed_counts(&cum, 3, 4, &observed_counts, &mut out);
836
837        assert!(close(out[0], (150.0 + 180.0) / (100.0 + 120.0)));
838        assert!(close(out[1], 180.0 / 150.0));
839        assert!(close(out[2], 198.0 / 180.0));
840    }
841
842    #[test]
843    fn cdf_kernel_uses_tail_convention() {
844        let ldfs = [1.5, 1.2, 1.1];
845        let mut cdfs = [0.0; 4];
846
847        cdfs_from_ldfs(&ldfs, 1.0, &mut cdfs);
848
849        assert!(close(cdfs[0], 1.98));
850        assert!(close(cdfs[1], 1.32));
851        assert!(close(cdfs[2], 1.10));
852        assert!(close(cdfs[3], 1.00));
853    }
854
855    #[test]
856    fn engine_returns_factors_cdfs_and_maturity() {
857        let tri = triangle_5x5();
858        let factors = DevelopmentFactorEngine::volume_weighted(&tri.view(), 1.0).expect("factors");
859
860        assert_eq!(factors.ldfs.len(), 4);
861        assert_eq!(factors.cdfs.len(), 5);
862        assert!(close(factors.cdfs[4], 1.0));
863
864        let maturity = factors.maturity_percentages();
865        assert!(close(maturity[4], 1.0));
866        assert!(maturity[0] < maturity[1]);
867    }
868
869    #[test]
870    fn engine_supports_non_volume_weighted_selection_methods() {
871        let tri = triangle_5x5();
872
873        let simple =
874            DevelopmentFactorEngine::simple_average(&tri.view(), 1.0).expect("simple average");
875        assert_eq!(simple.ldfs, simple_average(&tri.view()));
876
877        let median_factors =
878            DevelopmentFactorEngine::median(&tri.view(), 1.0).expect("median factors");
879        assert_eq!(median_factors.ldfs, median(&tri.view()));
880
881        let ex_hi_lo_factors =
882            DevelopmentFactorEngine::ex_hi_lo(&tri.view(), 1.0).expect("ex-hi-lo factors");
883        assert_eq!(ex_hi_lo_factors.ldfs, ex_hi_lo(&tri.view()));
884
885        let last_n = DevelopmentFactorEngine::volume_weighted_last_n(&tri.view(), 1.0, 2)
886            .expect("last-n volume weighted factors");
887        assert_eq!(last_n.ldfs, volume_weighted_last_n(&tri.view(), 2));
888
889        let last_n_simple = DevelopmentFactorEngine::simple_average_last_n(&tri.view(), 1.0, 2)
890            .expect("last-n simple average factors");
891        assert_eq!(last_n_simple.ldfs, simple_average_last_n(&tri.view(), 2));
892    }
893
894    #[test]
895    fn latest_maturity_percentages_follow_latest_diagonal_age() {
896        let cdfs = [1.98, 1.32, 1.10, 1.0];
897        let mut out = [0.0; 4];
898
899        latest_maturity_percentages(4, 4, &cdfs, &mut out);
900
901        assert!(close(out[0], 1.0));
902        assert!(close(out[1], 1.0 / 1.10));
903        assert!(close(out[2], 1.0 / 1.32));
904        assert!(close(out[3], 1.0 / 1.98));
905    }
906
907    #[test]
908    fn diagnostics_include_numerator_denominator_and_rows() {
909        let tri = triangle_3x3();
910        let diagnostics = DevelopmentFactorEngine::volume_weighted_diagnostics(&tri.view(), 1.0)
911            .expect("diagnostics");
912
913        assert_eq!(diagnostics.len(), 2);
914        assert_eq!(diagnostics[0].dev, 0);
915        assert!(close(diagnostics[0].numerator, 330.0));
916        assert!(close(diagnostics[0].denominator, 220.0));
917        assert_eq!(diagnostics[0].included_rows, 2);
918        assert!(close(diagnostics[0].selected_ldf, 1.5));
919    }
920
921    #[test]
922    fn engine_rejects_tail_below_one() {
923        let tri = triangle_3x3();
924
925        assert_eq!(
926            DevelopmentFactorEngine::volume_weighted(&tri.view(), 0.99),
927            Err(ValidationError::InvalidTail { tail: 0.99 })
928        );
929    }
930
931    #[test]
932    fn engine_rejects_non_cumulative_rows() {
933        #[rustfmt::skip]
934        let tri = Triangle::new(3, 3, vec![
935            100.0, 90.0, 180.0,
936            120.0, 180.0, f64::NAN,
937            140.0, f64::NAN, f64::NAN,
938        ]);
939
940        assert_eq!(
941            DevelopmentFactorEngine::volume_weighted(&tri.view(), 1.0),
942            Err(ValidationError::NonMonotoneCumulative {
943                origin: 0,
944                dev: 1,
945                previous: 100.0,
946                value: 90.0,
947            })
948        );
949    }
950}