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