Skip to main content

reserving_kernels/preprocessing/
ragged.rs

1//! Factor selection for rectangular cumulative triangles.
2//!
3//! Inputs are row-major losses in consistent units; counts identify each row
4//! observed prefix at the caller's valuation date. No calendar assumptions are
5//! introduced here. Unselectable links produce NaN; callers validate results.
6
7/// Counts-aware simple average. `last_n=Some(k)` restricts to the `k` most
8/// recent eligible origins per link (origins are ordered with oldest first).
9pub fn simple_average_observed_counts(
10    cum: &[f64],
11    n_o: usize,
12    n_d: usize,
13    counts: &[usize],
14    last_n: Option<usize>,
15    out: &mut [f64],
16) {
17    debug_assert_eq!(cum.len(), n_o * n_d);
18    debug_assert_eq!(counts.len(), n_o);
19    let n_links = n_d.saturating_sub(1);
20    debug_assert_eq!(out.len(), n_links);
21
22    for j in 0..n_links {
23        let limit = last_n.unwrap_or(usize::MAX);
24        let mut seen_eligible = 0_usize;
25        let mut sum = 0.0_f64;
26        let mut count = 0_usize;
27        for i in (0..n_o).rev() {
28            if counts[i] <= j + 1 {
29                continue;
30            }
31            if seen_eligible >= limit {
32                break;
33            }
34            seen_eligible += 1;
35            let x = cum[i * n_d + j];
36            let y = cum[i * n_d + j + 1];
37            if x > 0.0 && x.is_finite() && y.is_finite() {
38                sum += y / x;
39                count += 1;
40            }
41        }
42        out[j] = if count > 0 {
43            sum / count as f64
44        } else {
45            f64::NAN
46        };
47    }
48}
49
50/// Counts-aware ex-hi/lo (drop largest and smallest ratio per link;
51/// fall back to simple average when fewer than 3 pairs).
52///
53/// Uses a two-pass index-tracking scan (zero heap allocations and free of
54/// catastrophic cancellation on extreme outlier ratios).
55pub fn ex_hi_lo_observed_counts(
56    cum: &[f64],
57    n_o: usize,
58    n_d: usize,
59    counts: &[usize],
60    out: &mut [f64],
61) {
62    debug_assert_eq!(cum.len(), n_o * n_d);
63    debug_assert_eq!(counts.len(), n_o);
64    let n_links = n_d.saturating_sub(1);
65    debug_assert_eq!(out.len(), n_links);
66
67    for j in 0..n_links {
68        let mut valid_count = 0_usize;
69        let mut min_val = f64::INFINITY;
70        let mut max_val = f64::NEG_INFINITY;
71        let mut min_idx = 0_usize;
72        let mut max_idx = 0_usize;
73
74        for i in 0..n_o {
75            if counts[i] <= j + 1 {
76                continue;
77            }
78            let x = cum[i * n_d + j];
79            let y = cum[i * n_d + j + 1];
80            if x > 0.0 && x.is_finite() && y.is_finite() {
81                let r = y / x;
82                if valid_count == 0 || r < min_val {
83                    min_val = r;
84                    min_idx = i;
85                }
86                if valid_count == 0 || r > max_val {
87                    max_val = r;
88                    max_idx = i;
89                }
90                valid_count += 1;
91            }
92        }
93
94        if valid_count == 0 {
95            out[j] = f64::NAN;
96            continue;
97        }
98
99        // If all valid ratios are equal, min_idx == max_idx; pick any distinct
100        // second index when trimming >= 3 elements.
101        let trim = valid_count >= 3;
102        if trim && min_idx == max_idx {
103            for i in 0..n_o {
104                if i == min_idx || counts[i] <= j + 1 {
105                    continue;
106                }
107                let x = cum[i * n_d + j];
108                let y = cum[i * n_d + j + 1];
109                if x > 0.0 && x.is_finite() && y.is_finite() {
110                    max_idx = i;
111                    break;
112                }
113            }
114        }
115
116        let mut sum = 0.0_f64;
117        let mut kept = 0_usize;
118        for i in 0..n_o {
119            if counts[i] <= j + 1 {
120                continue;
121            }
122            if trim && (i == min_idx || i == max_idx) {
123                continue;
124            }
125            let x = cum[i * n_d + j];
126            let y = cum[i * n_d + j + 1];
127            if x > 0.0 && x.is_finite() && y.is_finite() {
128                sum += y / x;
129                kept += 1;
130            }
131        }
132        out[j] = if kept > 0 {
133            sum / kept as f64
134        } else {
135            f64::NAN
136        };
137    }
138}
139
140/// Counts-aware volume-weighted, restricted to the `last_n` most recent eligible
141/// origins (largest index = most recent in the right-triangle convention).
142pub fn volume_weighted_last_n_observed_counts(
143    cum: &[f64],
144    n_o: usize,
145    n_d: usize,
146    counts: &[usize],
147    last_n: usize,
148    out: &mut [f64],
149) {
150    debug_assert_eq!(cum.len(), n_o * n_d);
151    debug_assert_eq!(counts.len(), n_o);
152    let n_links = n_d.saturating_sub(1);
153    debug_assert_eq!(out.len(), n_links);
154
155    for j in 0..n_links {
156        let mut seen = 0_usize;
157        let mut num = 0.0_f64;
158        let mut den = 0.0_f64;
159        for i in (0..n_o).rev() {
160            if counts[i] <= j + 1 {
161                continue;
162            }
163            if seen >= last_n {
164                break;
165            }
166            seen += 1;
167            num += cum[i * n_d + j + 1];
168            den += cum[i * n_d + j];
169        }
170        out[j] = if den > 0.0 { num / den } else { f64::NAN };
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn observed_count_selectors_match_manual_ratios() {
180        #[rustfmt::skip]
181        let cum = [
182            100.0, 150.0, 180.0,
183            100.0, 200.0, 240.0,
184            100.0, 160.0, f64::NAN,
185            100.0, f64::NAN, f64::NAN,
186        ];
187        let counts = [3, 3, 2, 1];
188        let mut out = [0.0; 2];
189
190        simple_average_observed_counts(&cum, 4, 3, &counts, None, &mut out);
191        assert!((out[0] - (1.5 + 2.0 + 1.6) / 3.0).abs() < 1e-12);
192        assert!((out[1] - 1.2).abs() < 1e-12);
193
194        simple_average_observed_counts(&cum, 4, 3, &counts, Some(2), &mut out);
195        assert!((out[0] - f64::midpoint(2.0, 1.6)).abs() < 1e-12);
196
197        ex_hi_lo_observed_counts(&cum, 4, 3, &counts, &mut out);
198        assert!((out[0] - 1.6).abs() < 1e-12);
199
200        volume_weighted_last_n_observed_counts(&cum, 4, 3, &counts, 2, &mut out);
201        assert!((out[0] - (200.0 + 160.0) / 200.0).abs() < 1e-12);
202    }
203}