use crate::dependence::spearman_correlation;
use crate::severity::normal_cdf_exact;
use crate::triangle::age_to_age;
use crate::types::TriangleView;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AdjacentLinkCorrelation {
pub link: usize,
pub n_pairs: usize,
pub spearman_t: f64,
pub weight: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MackCorrelationTest {
pub by_link: Vec<AdjacentLinkCorrelation>,
pub statistic_t: f64,
pub null_variance: f64,
pub z_score: f64,
pub two_sided_p_value: f64,
pub bound_50_pct: f64,
pub bound_95_pct: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CalendarDiagonalTestRow {
pub calendar_diagonal: usize,
pub small_count: usize,
pub large_count: usize,
pub z_d: f64,
pub expected_z_d: f64,
pub variance_z_d: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MackCalendarYearTest {
pub diagonals: Vec<CalendarDiagonalTestRow>,
pub statistic_z: f64,
pub expected_z: f64,
pub variance_z: f64,
pub z_score: f64,
pub lower_tail_p_value: f64,
pub two_sided_p_value: f64,
}
pub fn adjacent_factor_correlation_test(t: &TriangleView<'_>) -> MackCorrelationTest {
let n = t.n_origins.min(t.n_devs);
let mut by_link = Vec::new();
let mut weighted_sum = 0.0;
let mut total_weight = 0.0;
if n >= 4 {
for k in 0..(n - 3) {
let mut left = Vec::new();
let mut right = Vec::new();
for i in 0..(n - k - 2) {
let r1 = age_to_age(t, i, k);
let r2 = age_to_age(t, i, k + 1);
if r1.is_finite() && r2.is_finite() {
left.push(r1);
right.push(r2);
}
}
let m = left.len();
if m >= 2 {
let tk = spearman_correlation(&left, &right);
if tk.is_finite() {
let w = (m - 1) as f64;
weighted_sum += w * tk;
total_weight += w;
by_link.push(AdjacentLinkCorrelation {
link: k,
n_pairs: m,
spearman_t: tk,
weight: w,
});
}
}
}
}
if total_weight <= 0.0 {
return MackCorrelationTest {
by_link,
statistic_t: f64::NAN,
null_variance: f64::NAN,
z_score: f64::NAN,
two_sided_p_value: f64::NAN,
bound_50_pct: f64::NAN,
bound_95_pct: f64::NAN,
};
}
let statistic_t = weighted_sum / total_weight;
let null_variance = 1.0 / total_weight;
let sd = null_variance.sqrt();
let z_score = statistic_t / sd;
let two_sided_p_value = (2.0 * normal_cdf_exact(-z_score.abs())).clamp(0.0, 1.0);
MackCorrelationTest {
by_link,
statistic_t,
null_variance,
z_score,
two_sided_p_value,
bound_50_pct: 0.674_489_750_196_081_7 * sd,
bound_95_pct: 1.959_963_984_540_054 * sd,
}
}
fn exact_min_binomial_moments(n: usize) -> (f64, f64) {
if n <= 1 {
return (0.0, 0.0);
}
let nf = n as f64;
let m = (n - 1) / 2;
let log_comb = crate::bootstrap_odp::ln_gamma(nf)
- crate::bootstrap_odp::ln_gamma((m + 1) as f64)
- crate::bootstrap_odp::ln_gamma((n - m) as f64);
let comb_over_2n = (log_comb - nf * std::f64::consts::LN_2).exp();
let expected = 0.5 * nf - comb_over_2n * nf;
let variance = (0.25 * nf * (nf - 1.0) - comb_over_2n * nf * (nf - 1.0) + expected
- expected * expected)
.max(0.0);
(expected, variance)
}
pub fn calendar_year_effect_test(t: &TriangleView<'_>) -> MackCalendarYearTest {
let n = t.n_origins.min(t.n_devs);
if n < 3 {
return MackCalendarYearTest {
diagonals: Vec::new(),
statistic_z: f64::NAN,
expected_z: f64::NAN,
variance_z: f64::NAN,
z_score: f64::NAN,
lower_tail_p_value: f64::NAN,
two_sided_p_value: f64::NAN,
};
}
let mut small_by_diag = vec![0usize; n];
let mut large_by_diag = vec![0usize; n];
for k in 0..(n - 1) {
let mut pairs: Vec<(usize, f64)> = Vec::new();
for i in 0..(n - k - 1) {
let r = age_to_age(t, i, k);
if r.is_finite() {
pairs.push((i, r));
}
}
if pairs.len() < 2 {
continue;
}
let mut sorted_vals: Vec<f64> = pairs.iter().map(|&(_, r)| r).collect();
sorted_vals.sort_by(f64::total_cmp);
let len = sorted_vals.len();
let median = if len % 2 == 1 {
sorted_vals[len / 2]
} else {
0.5 * (sorted_vals[len / 2 - 1] + sorted_vals[len / 2])
};
for (i, r) in pairs {
let diag = i + k + 1;
if diag < n {
if r < median {
small_by_diag[diag] += 1;
} else if r > median {
large_by_diag[diag] += 1;
}
}
}
}
let mut diagonals = Vec::new();
let mut statistic_z = 0.0;
let mut expected_z = 0.0;
let mut variance_z = 0.0;
for diag in 1..n {
let s = small_by_diag[diag];
let l = large_by_diag[diag];
let nd = s + l;
if nd == 0 {
continue;
}
let z_d = s.min(l) as f64;
let (e_d, v_d) = exact_min_binomial_moments(nd);
statistic_z += z_d;
expected_z += e_d;
variance_z += v_d;
diagonals.push(CalendarDiagonalTestRow {
calendar_diagonal: diag,
small_count: s,
large_count: l,
z_d,
expected_z_d: e_d,
variance_z_d: v_d,
});
}
if !(variance_z > 0.0) {
return MackCalendarYearTest {
diagonals,
statistic_z,
expected_z,
variance_z,
z_score: f64::NAN,
lower_tail_p_value: f64::NAN,
two_sided_p_value: f64::NAN,
};
}
let z_score = (statistic_z - expected_z) / variance_z.sqrt();
let lower_tail_p_value = normal_cdf_exact(z_score).clamp(0.0, 1.0);
let two_sided_p_value = (2.0 * normal_cdf_exact(-z_score.abs())).clamp(0.0, 1.0);
MackCalendarYearTest {
diagonals,
statistic_z,
expected_z,
variance_z,
z_score,
lower_tail_p_value,
two_sided_p_value,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::Triangle;
#[test]
fn exact_min_binomial_moments_match_hand_calculations() {
assert_eq!(exact_min_binomial_moments(1), (0.0, 0.0));
let (e2, v2) = exact_min_binomial_moments(2);
assert!((e2 - 0.5).abs() < 1e-12 && (v2 - 0.25).abs() < 1e-12);
let (e3, v3) = exact_min_binomial_moments(3);
assert!((e3 - 0.75).abs() < 1e-12 && (v3 - 0.1875).abs() < 1e-12);
let (e4, v4) = exact_min_binomial_moments(4);
assert!((e4 - 1.25).abs() < 1e-12 && (v4 - 0.4375).abs() < 1e-12);
}
#[test]
fn calendar_test_detects_strong_calendar_year_inflation_shock() {
let n = 8usize;
let base_ldfs = [2.0, 1.5, 1.25, 1.15, 1.10, 1.05, 1.02];
let mut data = vec![f64::NAN; n * n];
for i in 0..n {
let mut c = 1000.0 + 50.0 * i as f64;
data[i * n] = c;
for j in 1..(n - i) {
let cal = i + j;
let shock = if cal >= n - 2 {
1.25
} else if cal <= 3 {
0.90
} else {
1.0
};
c *= base_ldfs[j - 1] * shock;
data[i * n + j] = c;
}
}
let tri = Triangle::new(n, n, data);
let cal_test = calendar_year_effect_test(&tri.view());
assert!(cal_test.z_score < -1.96, "z={}", cal_test.z_score);
assert!(cal_test.lower_tail_p_value < 0.025);
}
#[test]
fn correlation_test_computes_exact_null_variance() {
let n = 6usize;
let mut data = vec![f64::NAN; n * n];
for i in 0..n {
let mut c = 100.0 * (i + 1) as f64;
data[i * n] = c;
for j in 1..(n - i) {
let jitter = 1.0 + 0.02 * ((i * 3 + j) % 5) as f64;
c *= (1.4 - 0.05 * j as f64) * jitter;
data[i * n + j] = c;
}
}
let tri = Triangle::new(n, n, data);
let res = adjacent_factor_correlation_test(&tri.view());
assert!((res.null_variance - 1.0 / 6.0).abs() < 1e-12);
assert!(res.two_sided_p_value >= 0.0 && res.two_sided_p_value <= 1.0);
}
}