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 + 1];
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 + 1];
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 / (count as f64)
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            (scratch[k / 2 - 1] + scratch[k / 2]) / 2.0
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 / (count as f64)
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.
603pub struct DevelopmentFactorEngine;
604
605impl DevelopmentFactorEngine {
606    fn factors_from_validated_ldfs(
607        n_devs: usize,
608        tail: f64,
609        ldfs: Vec<f64>,
610    ) -> Result<DevelopmentFactors, ValidationError> {
611        validate_positive_finite_slice(&ldfs, "development denominator")?;
612
613        let mut cdfs = vec![0.0; n_devs];
614        cdfs_from_ldfs(&ldfs, tail, &mut cdfs);
615        if cdfs.iter().any(|cdf| !cdf.is_finite()) {
616            return Err(ValidationError::NotFinite);
617        }
618
619        Ok(DevelopmentFactors { ldfs, cdfs, tail })
620    }
621
622    /// Select volume-weighted factors and CDFs from a validated cumulative triangle.
623    pub fn volume_weighted(
624        tri: &TriangleView<'_>,
625        tail: f64,
626    ) -> Result<DevelopmentFactors, ValidationError> {
627        Self::volume_weighted_with_policy(tri, tail, MonotonicityPolicy::Strict)
628    }
629
630    /// Select volume-weighted factors and CDFs under an explicit [`MonotonicityPolicy`].
631    pub fn volume_weighted_with_policy(
632        tri: &TriangleView<'_>,
633        tail: f64,
634        policy: MonotonicityPolicy,
635    ) -> Result<DevelopmentFactors, ValidationError> {
636        validate_development_inputs_with_policy(tri, tail, policy)?;
637        let mut ldfs = vec![0.0; tri.n_devs - 1];
638        volume_weighted_ldfs(tri.data, tri.n_origins, tri.n_devs, &mut ldfs);
639        Self::factors_from_validated_ldfs(tri.n_devs, tail, ldfs)
640    }
641
642    /// Select simple-average factors and CDFs from a validated cumulative triangle.
643    pub fn simple_average(
644        tri: &TriangleView<'_>,
645        tail: f64,
646    ) -> Result<DevelopmentFactors, ValidationError> {
647        validate_development_inputs(tri, tail)?;
648        Self::factors_from_validated_ldfs(tri.n_devs, tail, simple_average(tri))
649    }
650
651    /// Select median factors and CDFs from a validated cumulative triangle.
652    pub fn median(
653        tri: &TriangleView<'_>,
654        tail: f64,
655    ) -> Result<DevelopmentFactors, ValidationError> {
656        validate_development_inputs(tri, tail)?;
657        Self::factors_from_validated_ldfs(tri.n_devs, tail, median(tri))
658    }
659
660    /// Select ex-hi-lo factors and CDFs from a validated cumulative triangle.
661    pub fn ex_hi_lo(
662        tri: &TriangleView<'_>,
663        tail: f64,
664    ) -> Result<DevelopmentFactors, ValidationError> {
665        validate_development_inputs(tri, tail)?;
666        Self::factors_from_validated_ldfs(tri.n_devs, tail, ex_hi_lo(tri))
667    }
668
669    /// Select volume-weighted last-N factors and CDFs from a validated cumulative triangle.
670    pub fn volume_weighted_last_n(
671        tri: &TriangleView<'_>,
672        tail: f64,
673        last_n: usize,
674    ) -> Result<DevelopmentFactors, ValidationError> {
675        validate_development_inputs(tri, tail)?;
676        Self::factors_from_validated_ldfs(tri.n_devs, tail, volume_weighted_last_n(tri, last_n))
677    }
678
679    /// Select simple-average last-N factors and CDFs from a validated cumulative triangle.
680    pub fn simple_average_last_n(
681        tri: &TriangleView<'_>,
682        tail: f64,
683        last_n: usize,
684    ) -> Result<DevelopmentFactors, ValidationError> {
685        validate_development_inputs(tri, tail)?;
686        Self::factors_from_validated_ldfs(tri.n_devs, tail, simple_average_last_n(tri, last_n))
687    }
688
689    /// Select geometric-average factors and CDFs from a validated cumulative triangle.
690    pub fn geometric_average(
691        tri: &TriangleView<'_>,
692        tail: f64,
693    ) -> Result<DevelopmentFactors, ValidationError> {
694        validate_development_inputs(tri, tail)?;
695        Self::factors_from_validated_ldfs(tri.n_devs, tail, geometric_average(tri))
696    }
697
698    /// Select volume-weighted factors with a per-cell weight / outlier-exclusion
699    /// mask (`weights[i * n_devs + j] == 0.0` excludes the link `j -> j+1` for
700    /// origin `i`).
701    pub fn volume_weighted_masked(
702        tri: &TriangleView<'_>,
703        weights: &[f64],
704        tail: f64,
705        policy: MonotonicityPolicy,
706    ) -> Result<DevelopmentFactors, ValidationError> {
707        validate_development_inputs_with_policy(tri, tail, policy)?;
708        let ldfs = weighted_volume_ldfs(tri, weights)?;
709        Self::factors_from_validated_ldfs(tri.n_devs, tail, ldfs)
710    }
711
712    /// Diagnostics for volume-weighted link selections.
713    pub fn volume_weighted_diagnostics(
714        tri: &TriangleView<'_>,
715        tail: f64,
716    ) -> Result<Vec<LinkRatioDiagnostic>, ValidationError> {
717        validate_development_inputs(tri, tail)?;
718
719        let mut diagnostics = Vec::with_capacity(tri.n_devs - 1);
720        for dev in 0..tri.n_devs - 1 {
721            let diagnostic =
722                volume_weighted_link_diagnostic(tri.data, tri.n_origins, tri.n_devs, dev);
723            if !diagnostic.selected_ldf.is_finite() {
724                return Err(ValidationError::DivideByZero("development denominator"));
725            }
726            diagnostics.push(diagnostic);
727        }
728        Ok(diagnostics)
729    }
730}
731
732fn validate_development_inputs(tri: &TriangleView<'_>, tail: f64) -> Result<(), ValidationError> {
733    validate_development_inputs_with_policy(tri, tail, MonotonicityPolicy::Strict)
734}
735
736fn validate_development_inputs_with_policy(
737    tri: &TriangleView<'_>,
738    tail: f64,
739    policy: MonotonicityPolicy,
740) -> Result<(), ValidationError> {
741    validate_triangle(tri)?;
742    if tri.n_devs < 2 {
743        return Err(ValidationError::ShapeMismatch);
744    }
745    if !tail.is_finite() {
746        return Err(ValidationError::NotFinite);
747    }
748    if tail < 1.0 {
749        return Err(ValidationError::InvalidTail { tail });
750    }
751    if policy == MonotonicityPolicy::Strict {
752        validate_monotone_cumulative(tri)?;
753    }
754    Ok(())
755}
756
757#[cfg(test)]
758mod tests {
759    use super::*;
760    use crate::types::Triangle;
761
762    fn triangle_3x3() -> Triangle {
763        #[rustfmt::skip]
764        let data = vec![
765            100.0, 150.0, 180.0,
766            120.0, 180.0, f64::NAN,
767            140.0, f64::NAN, f64::NAN,
768        ];
769        Triangle::new(3, 3, data)
770    }
771
772    fn triangle_5x5() -> Triangle {
773        #[rustfmt::skip]
774        let data = vec![
775            100.0, 150.0, 180.0, 198.0, 207.9,
776            120.0, 180.0, 216.0, 237.6, f64::NAN,
777            140.0, 210.0, 252.0, f64::NAN, f64::NAN,
778            160.0, 240.0, f64::NAN, f64::NAN, f64::NAN,
779            180.0, f64::NAN, f64::NAN, f64::NAN, f64::NAN,
780        ];
781        Triangle::new(5, 5, data)
782    }
783
784    fn close(a: f64, b: f64) -> bool {
785        (a - b).abs() <= 1e-12 * (1.0 + b.abs())
786    }
787
788    #[test]
789    fn volume_weighted_single_ldf_uses_only_observed_pairs() {
790        let tri = triangle_3x3();
791
792        let f0 = volume_weighted_ldf(&tri.data, 3, 3, 0);
793        let f1 = volume_weighted_ldf(&tri.data, 3, 3, 1);
794
795        assert!(close(f0, (150.0 + 180.0) / (100.0 + 120.0)));
796        assert!(close(f1, 180.0 / 150.0));
797    }
798
799    #[test]
800    fn volume_weighted_all_ldfs_3x3() {
801        let tri = triangle_3x3();
802        let mut out = [0.0; 2];
803
804        volume_weighted_ldfs(&tri.data, 3, 3, &mut out);
805
806        assert!(close(out[0], 1.5));
807        assert!(close(out[1], 1.2));
808    }
809
810    #[test]
811    fn volume_weighted_all_ldfs_5x5() {
812        let tri = triangle_5x5();
813        let mut out = [0.0; 4];
814
815        volume_weighted_ldfs(&tri.data, 5, 5, &mut out);
816
817        assert!(close(out[0], 1.5));
818        assert!(close(out[1], 1.2));
819        assert!(close(out[2], 1.1));
820        assert!(close(out[3], 1.05));
821    }
822
823    #[test]
824    fn observed_counts_ldfs_handle_semiannual_rectangle() {
825        #[rustfmt::skip]
826        let cum = [
827            100.0, 150.0, 180.0, 198.0,
828            120.0, 180.0, f64::NAN, f64::NAN,
829            140.0, f64::NAN, f64::NAN, f64::NAN,
830        ];
831        let observed_counts = [4, 2, 1];
832        let mut out = [0.0; 3];
833
834        volume_weighted_ldfs_observed_counts(&cum, 3, 4, &observed_counts, &mut out);
835
836        assert!(close(out[0], (150.0 + 180.0) / (100.0 + 120.0)));
837        assert!(close(out[1], 180.0 / 150.0));
838        assert!(close(out[2], 198.0 / 180.0));
839    }
840
841    #[test]
842    fn cdf_kernel_uses_tail_convention() {
843        let ldfs = [1.5, 1.2, 1.1];
844        let mut cdfs = [0.0; 4];
845
846        cdfs_from_ldfs(&ldfs, 1.0, &mut cdfs);
847
848        assert!(close(cdfs[0], 1.98));
849        assert!(close(cdfs[1], 1.32));
850        assert!(close(cdfs[2], 1.10));
851        assert!(close(cdfs[3], 1.00));
852    }
853
854    #[test]
855    fn engine_returns_factors_cdfs_and_maturity() {
856        let tri = triangle_5x5();
857        let factors = DevelopmentFactorEngine::volume_weighted(&tri.view(), 1.0).expect("factors");
858
859        assert_eq!(factors.ldfs.len(), 4);
860        assert_eq!(factors.cdfs.len(), 5);
861        assert!(close(factors.cdfs[4], 1.0));
862
863        let maturity = factors.maturity_percentages();
864        assert!(close(maturity[4], 1.0));
865        assert!(maturity[0] < maturity[1]);
866    }
867
868    #[test]
869    fn engine_supports_non_volume_weighted_selection_methods() {
870        let tri = triangle_5x5();
871
872        let simple =
873            DevelopmentFactorEngine::simple_average(&tri.view(), 1.0).expect("simple average");
874        assert_eq!(simple.ldfs, simple_average(&tri.view()));
875
876        let median_factors =
877            DevelopmentFactorEngine::median(&tri.view(), 1.0).expect("median factors");
878        assert_eq!(median_factors.ldfs, median(&tri.view()));
879
880        let ex_hi_lo_factors =
881            DevelopmentFactorEngine::ex_hi_lo(&tri.view(), 1.0).expect("ex-hi-lo factors");
882        assert_eq!(ex_hi_lo_factors.ldfs, ex_hi_lo(&tri.view()));
883
884        let last_n = DevelopmentFactorEngine::volume_weighted_last_n(&tri.view(), 1.0, 2)
885            .expect("last-n volume weighted factors");
886        assert_eq!(last_n.ldfs, volume_weighted_last_n(&tri.view(), 2));
887
888        let last_n_simple = DevelopmentFactorEngine::simple_average_last_n(&tri.view(), 1.0, 2)
889            .expect("last-n simple average factors");
890        assert_eq!(last_n_simple.ldfs, simple_average_last_n(&tri.view(), 2));
891    }
892
893    #[test]
894    fn latest_maturity_percentages_follow_latest_diagonal_age() {
895        let cdfs = [1.98, 1.32, 1.10, 1.0];
896        let mut out = [0.0; 4];
897
898        latest_maturity_percentages(4, 4, &cdfs, &mut out);
899
900        assert!(close(out[0], 1.0));
901        assert!(close(out[1], 1.0 / 1.10));
902        assert!(close(out[2], 1.0 / 1.32));
903        assert!(close(out[3], 1.0 / 1.98));
904    }
905
906    #[test]
907    fn diagnostics_include_numerator_denominator_and_rows() {
908        let tri = triangle_3x3();
909        let diagnostics = DevelopmentFactorEngine::volume_weighted_diagnostics(&tri.view(), 1.0)
910            .expect("diagnostics");
911
912        assert_eq!(diagnostics.len(), 2);
913        assert_eq!(diagnostics[0].dev, 0);
914        assert!(close(diagnostics[0].numerator, 330.0));
915        assert!(close(diagnostics[0].denominator, 220.0));
916        assert_eq!(diagnostics[0].included_rows, 2);
917        assert!(close(diagnostics[0].selected_ldf, 1.5));
918    }
919
920    #[test]
921    fn engine_rejects_tail_below_one() {
922        let tri = triangle_3x3();
923
924        assert_eq!(
925            DevelopmentFactorEngine::volume_weighted(&tri.view(), 0.99),
926            Err(ValidationError::InvalidTail { tail: 0.99 })
927        );
928    }
929
930    #[test]
931    fn engine_rejects_non_cumulative_rows() {
932        #[rustfmt::skip]
933        let tri = Triangle::new(3, 3, vec![
934            100.0, 90.0, 180.0,
935            120.0, 180.0, f64::NAN,
936            140.0, f64::NAN, f64::NAN,
937        ]);
938
939        assert_eq!(
940            DevelopmentFactorEngine::volume_weighted(&tri.view(), 1.0),
941            Err(ValidationError::NonMonotoneCumulative {
942                origin: 0,
943                dev: 1,
944                previous: 100.0,
945                value: 90.0,
946            })
947        );
948    }
949}