reserving_kernels/diagnostics/
mack_tests.rs1use crate::dependence::spearman_correlation;
18use crate::severity::normal_cdf_exact;
19use crate::triangle::age_to_age;
20use crate::types::TriangleView;
21
22#[derive(Debug, Clone, Copy, PartialEq)]
24pub struct AdjacentLinkCorrelation {
25 pub link: usize,
27 pub n_pairs: usize,
29 pub spearman_t: f64,
31 pub weight: f64,
33}
34
35#[derive(Debug, Clone, PartialEq)]
37pub struct MackCorrelationTest {
38 pub by_link: Vec<AdjacentLinkCorrelation>,
40 pub statistic_t: f64,
42 pub null_variance: f64,
44 pub z_score: f64,
46 pub two_sided_p_value: f64,
48 pub bound_50_pct: f64,
50 pub bound_95_pct: f64,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct CalendarDiagonalTestRow {
57 pub calendar_diagonal: usize,
59 pub small_count: usize,
61 pub large_count: usize,
63 pub z_d: f64,
65 pub expected_z_d: f64,
67 pub variance_z_d: f64,
69}
70
71#[derive(Debug, Clone, PartialEq)]
73pub struct MackCalendarYearTest {
74 pub diagonals: Vec<CalendarDiagonalTestRow>,
76 pub statistic_z: f64,
78 pub expected_z: f64,
80 pub variance_z: f64,
82 pub z_score: f64,
85 pub lower_tail_p_value: f64,
87 pub two_sided_p_value: f64,
89}
90
91pub fn adjacent_factor_correlation_test(t: &TriangleView<'_>) -> MackCorrelationTest {
94 let n = t.n_origins.min(t.n_devs);
95 let mut by_link = Vec::new();
96 let mut weighted_sum = 0.0;
97 let mut total_weight = 0.0;
98
99 if n >= 4 {
100 for k in 0..(n - 3) {
101 let mut left = Vec::new();
102 let mut right = Vec::new();
103 for i in 0..(n - k - 2) {
104 let r1 = age_to_age(t, i, k);
105 let r2 = age_to_age(t, i, k + 1);
106 if r1.is_finite() && r2.is_finite() {
107 left.push(r1);
108 right.push(r2);
109 }
110 }
111 let m = left.len();
112 if m >= 2 {
113 let tk = spearman_correlation(&left, &right);
114 if tk.is_finite() {
115 let w = (m - 1) as f64;
116 weighted_sum += w * tk;
117 total_weight += w;
118 by_link.push(AdjacentLinkCorrelation {
119 link: k,
120 n_pairs: m,
121 spearman_t: tk,
122 weight: w,
123 });
124 }
125 }
126 }
127 }
128
129 if total_weight <= 0.0 {
130 return MackCorrelationTest {
131 by_link,
132 statistic_t: f64::NAN,
133 null_variance: f64::NAN,
134 z_score: f64::NAN,
135 two_sided_p_value: f64::NAN,
136 bound_50_pct: f64::NAN,
137 bound_95_pct: f64::NAN,
138 };
139 }
140
141 let statistic_t = weighted_sum / total_weight;
142 let null_variance = 1.0 / total_weight;
143 let sd = null_variance.sqrt();
144 let z_score = statistic_t / sd;
145 let two_sided_p_value = (2.0 * normal_cdf_exact(-z_score.abs())).clamp(0.0, 1.0);
146
147 MackCorrelationTest {
148 by_link,
149 statistic_t,
150 null_variance,
151 z_score,
152 two_sided_p_value,
153 bound_50_pct: 0.674_489_750_196_081_7 * sd,
154 bound_95_pct: 1.959_963_984_540_054 * sd,
155 }
156}
157
158fn exact_min_binomial_moments(n: usize) -> (f64, f64) {
161 if n <= 1 {
162 return (0.0, 0.0);
163 }
164 let nf = n as f64;
165 let m = (n - 1) / 2;
166 let log_comb = crate::bootstrap_odp::ln_gamma(nf)
168 - crate::bootstrap_odp::ln_gamma((m + 1) as f64)
169 - crate::bootstrap_odp::ln_gamma((n - m) as f64);
170 let comb_over_2n = (log_comb - nf * std::f64::consts::LN_2).exp();
171 let expected = 0.5 * nf - comb_over_2n * nf;
172 let variance = (0.25 * nf * (nf - 1.0) - comb_over_2n * nf * (nf - 1.0) + expected
173 - expected * expected)
174 .max(0.0);
175 (expected, variance)
176}
177
178pub fn calendar_year_effect_test(t: &TriangleView<'_>) -> MackCalendarYearTest {
180 let n = t.n_origins.min(t.n_devs);
181 if n < 3 {
182 return MackCalendarYearTest {
183 diagonals: Vec::new(),
184 statistic_z: f64::NAN,
185 expected_z: f64::NAN,
186 variance_z: f64::NAN,
187 z_score: f64::NAN,
188 lower_tail_p_value: f64::NAN,
189 two_sided_p_value: f64::NAN,
190 };
191 }
192
193 let mut small_by_diag = vec![0usize; n];
194 let mut large_by_diag = vec![0usize; n];
195
196 for k in 0..(n - 1) {
197 let mut pairs: Vec<(usize, f64)> = Vec::new();
198 for i in 0..(n - k - 1) {
199 let r = age_to_age(t, i, k);
200 if r.is_finite() {
201 pairs.push((i, r));
202 }
203 }
204 if pairs.len() < 2 {
205 continue;
206 }
207 let mut sorted_vals: Vec<f64> = pairs.iter().map(|&(_, r)| r).collect();
208 sorted_vals.sort_by(f64::total_cmp);
209 let len = sorted_vals.len();
210 let median = if len % 2 == 1 {
211 sorted_vals[len / 2]
212 } else {
213 0.5 * (sorted_vals[len / 2 - 1] + sorted_vals[len / 2])
214 };
215
216 for (i, r) in pairs {
217 let diag = i + k + 1;
218 if diag < n {
219 if r < median {
220 small_by_diag[diag] += 1;
221 } else if r > median {
222 large_by_diag[diag] += 1;
223 }
224 }
225 }
226 }
227
228 let mut diagonals = Vec::new();
229 let mut statistic_z = 0.0;
230 let mut expected_z = 0.0;
231 let mut variance_z = 0.0;
232
233 for diag in 1..n {
234 let s = small_by_diag[diag];
235 let l = large_by_diag[diag];
236 let nd = s + l;
237 if nd == 0 {
238 continue;
239 }
240 let z_d = s.min(l) as f64;
241 let (e_d, v_d) = exact_min_binomial_moments(nd);
242 statistic_z += z_d;
243 expected_z += e_d;
244 variance_z += v_d;
245 diagonals.push(CalendarDiagonalTestRow {
246 calendar_diagonal: diag,
247 small_count: s,
248 large_count: l,
249 z_d,
250 expected_z_d: e_d,
251 variance_z_d: v_d,
252 });
253 }
254
255 if !(variance_z > 0.0) {
256 return MackCalendarYearTest {
257 diagonals,
258 statistic_z,
259 expected_z,
260 variance_z,
261 z_score: f64::NAN,
262 lower_tail_p_value: f64::NAN,
263 two_sided_p_value: f64::NAN,
264 };
265 }
266
267 let z_score = (statistic_z - expected_z) / variance_z.sqrt();
268 let lower_tail_p_value = normal_cdf_exact(z_score).clamp(0.0, 1.0);
269 let two_sided_p_value = (2.0 * normal_cdf_exact(-z_score.abs())).clamp(0.0, 1.0);
270
271 MackCalendarYearTest {
272 diagonals,
273 statistic_z,
274 expected_z,
275 variance_z,
276 z_score,
277 lower_tail_p_value,
278 two_sided_p_value,
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use crate::types::Triangle;
286
287 #[test]
288 fn exact_min_binomial_moments_match_hand_calculations() {
289 assert_eq!(exact_min_binomial_moments(1), (0.0, 0.0));
290 let (e2, v2) = exact_min_binomial_moments(2);
291 assert!((e2 - 0.5).abs() < 1e-12 && (v2 - 0.25).abs() < 1e-12);
292 let (e3, v3) = exact_min_binomial_moments(3);
293 assert!((e3 - 0.75).abs() < 1e-12 && (v3 - 0.1875).abs() < 1e-12);
294 let (e4, v4) = exact_min_binomial_moments(4);
295 assert!((e4 - 1.25).abs() < 1e-12 && (v4 - 0.4375).abs() < 1e-12);
296 }
297
298 #[test]
299 fn calendar_test_detects_strong_calendar_year_inflation_shock() {
300 let n = 8usize;
303 let base_ldfs = [2.0, 1.5, 1.25, 1.15, 1.10, 1.05, 1.02];
304 let mut data = vec![f64::NAN; n * n];
305 for i in 0..n {
306 let mut c = 1000.0 + 50.0 * i as f64;
307 data[i * n] = c;
308 for j in 1..(n - i) {
309 let cal = i + j;
310 let shock = if cal >= n - 2 {
311 1.25
312 } else if cal <= 3 {
313 0.90
314 } else {
315 1.0
316 };
317 c *= base_ldfs[j - 1] * shock;
318 data[i * n + j] = c;
319 }
320 }
321 let tri = Triangle::new(n, n, data);
322 let cal_test = calendar_year_effect_test(&tri.view());
323 assert!(cal_test.z_score < -1.96, "z={}", cal_test.z_score);
324 assert!(cal_test.lower_tail_p_value < 0.025);
325 }
326
327 #[test]
328 fn correlation_test_computes_exact_null_variance() {
329 let n = 6usize;
330 let mut data = vec![f64::NAN; n * n];
331 for i in 0..n {
332 let mut c = 100.0 * (i + 1) as f64;
333 data[i * n] = c;
334 for j in 1..(n - i) {
335 let jitter = 1.0 + 0.02 * ((i * 3 + j) % 5) as f64;
336 c *= (1.4 - 0.05 * j as f64) * jitter;
337 data[i * n + j] = c;
338 }
339 }
340 let tri = Triangle::new(n, n, data);
341 let res = adjacent_factor_correlation_test(&tri.view());
342 assert!((res.null_variance - 1.0 / 6.0).abs() < 1e-12);
344 assert!(res.two_sided_p_value >= 0.0 && res.two_sided_p_value <= 1.0);
345 }
346}