lib_jsl_statistics/
goodness_of_fit.rs1use crate::correlation::rank;
8use crate::hypothesis_tests::TestResult;
9use lib_jsl_core::ErrorsJSL;
10use lib_jsl_special_functions::bessel_functions_fractional::bessel_k_fractional;
11use lib_jsl_special_functions::gamma::{gamma, ln_gamma};
12use std::collections::HashMap;
13use std::f64::consts::PI;
14
15pub fn cramer_von_mises_cdf_limit(x: f64) -> f64 {
20 if !(x > 0.0) {
21 return 0.0;
22 }
23 let mut total = 0.0;
24 let mut k = 0;
25 loop {
26 let u = (ln_gamma(k as f64 + 0.5) - ln_gamma(k as f64 + 1.0)).exp() / (PI.powf(1.5) * x.sqrt());
27 let y = 4.0 * k as f64 + 1.0;
28 let q = y * y / (16.0 * x);
29 let term = u * y.sqrt() * (-q).exp() * bessel_k_fractional(0.25, q);
30 total += term;
31 if term.abs() < 1e-7 || k > 1000 {
32 return total;
33 }
34 k += 1;
35 }
36}
37fn psi1_mod(x: f64) -> f64 {
41 let ed2 = |y: f64| {
42 let z = y * y / 4.0;
43 (-z).exp() * (y / 2.0).powf(1.5) * (bessel_k_fractional(0.25, z) + bessel_k_fractional(0.75, z)) / PI.sqrt()
44 };
45 let ed3 = |y: f64| {
46 let z = y * y / 4.0;
47 (-z).exp() / PI.sqrt() * (y / 2.0).powf(2.5) * (2.0 * bessel_k_fractional(0.25, z) + 3.0 * bessel_k_fractional(0.75, z) - bessel_k_fractional(1.25, z))
48 };
49 let ak = |k: f64| {
50 let m = 2.0 * k + 1.0;
51 let sx = 2.0 * x.sqrt();
52 let (y1, y2) = (x.powf(0.75), x.powf(1.25));
53 let (g1, g3) = (gamma(k + 0.5), gamma(k + 1.5));
54 m * g1 * ed2((4.0 * k + 3.0) / sx) / (9.0 * y1)
55 + g1 * ed3((4.0 * k + 1.0) / sx) / (72.0 * y2)
56 + 2.0 * (m + 2.0) * g3 * ed3((4.0 * k + 5.0) / sx) / (12.0 * y2)
57 + 7.0 * m * g1 * ed2((4.0 * k + 1.0) / sx) / (144.0 * y1)
58 + 7.0 * m * g1 * ed2((4.0 * k + 5.0) / sx) / (144.0 * y1)
59 };
60 let mut total = 0.0;
61 let mut k = 0.0;
62 loop {
63 let z = -ak(k) / (PI * gamma(k + 1.0));
64 total += z;
65 if z.abs() < 1e-7 || k > 1000.0 {
66 return total;
67 }
68 k += 1.0;
69 }
70}
71
72pub fn cramer_von_mises_cdf(x: f64, n: usize) -> f64 {
75 let n = n as f64;
76 if x >= n / 3.0 {
77 1.0
78 } else if x > 1.0 / (12.0 * n) {
79 cramer_von_mises_cdf_limit(x) * (1.0 + 1.0 / (12.0 * n)) + psi1_mod(x) / n
80 } else {
81 0.0
82 }
83}
84
85pub fn cramervonmises(x: &[f64], cdf: impl Fn(f64) -> f64) -> Result<TestResult, ErrorsJSL> {
90 let n = x.len();
91 if n < 2 || x.iter().any(|v| !v.is_finite()) {
92 return Err(ErrorsJSL::InvalidInputRange("cramervonmises: need at least two finite observations"));
93 }
94 let mut s = x.to_vec();
95 s.sort_by(f64::total_cmp);
96 let nf = n as f64;
97 let w = 1.0 / (12.0 * nf) + s.iter().enumerate().map(|(i, &v)| ((2 * i + 1) as f64 / (2.0 * nf) - cdf(v)).powi(2)).sum::<f64>();
98 let p = (1.0 - cramer_von_mises_cdf(w, n)).max(0.0);
99 Ok(TestResult::new(w, p, f64::NAN))
100}
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105#[non_exhaustive]
106pub enum CvmMethod {
107 Auto,
109 Exact,
110 Asymptotic,
111}
112
113fn cvm_2samp_exact(u: f64, m: usize, n: usize) -> f64 {
117 let gcd = |mut a: usize, mut b: usize| {
118 while b != 0 {
119 (a, b) = (b, a % b);
120 }
121 a
122 };
123 let lcm = m / gcd(m, n) * n;
124 let (a, b) = ((lcm / m) as i64, (lcm / n) as i64);
125 let mn = (m * n) as f64;
126 let zeta = ((lcm * lcm * (m + n)) as f64 * (6.0 * u - mn * (4.0 * mn - 1.0)) / (6.0 * mn * mn)).floor();
127 let mut gs: Vec<HashMap<u64, u64>> = vec![HashMap::new(); m + 1];
129 gs[0].insert(0, 1);
130 for w in 0..=n {
131 let mut next = Vec::with_capacity(m + 1);
132 let mut tmp: HashMap<u64, u64> = HashMap::new();
133 for (v, g) in gs.iter().enumerate() {
134 for (&k, &c) in g {
135 *tmp.entry(k).or_insert(0) += c;
136 }
137 let res = ((a * v as i64 - b * w as i64).pow(2)) as u64;
138 tmp = tmp.into_iter().map(|(k, c)| (k + res, c)).collect();
139 next.push(tmp.clone());
140 }
141 gs = next;
142 }
143 let total: f64 = (0..m).fold(1.0, |acc, i| acc * (n + m - i) as f64 / (i + 1) as f64).round();
144 let count: u64 = gs[m].iter().filter(|(k, _)| **k as f64 >= zeta).map(|(_, c)| *c).sum();
145 count as f64 / total
146}
147
148pub fn cramervonmises_2samp(x: &[f64], y: &[f64], method: CvmMethod) -> Result<TestResult, ErrorsJSL> {
153 let (nx, ny) = (x.len(), y.len());
154 if nx < 2 || ny < 2 || x.iter().chain(y).any(|v| !v.is_finite()) {
155 return Err(ErrorsJSL::InvalidInputRange("cramervonmises_2samp: need at least two finite observations per sample"));
156 }
157 let exact = match method {
158 CvmMethod::Exact => true,
159 CvmMethod::Asymptotic => false,
160 CvmMethod::Auto => nx.max(ny) <= 20,
161 };
162 let mut xs = x.to_vec();
163 let mut ys = y.to_vec();
164 xs.sort_by(f64::total_cmp);
165 ys.sort_by(f64::total_cmp);
166 let z: Vec<f64> = xs.iter().chain(&ys).copied().collect();
167 let r = rank(&z);
168 let (nxf, nyf) = (nx as f64, ny as f64);
169 let u = nxf * (0..nx).map(|i| (r[i] - (i + 1) as f64).powi(2)).sum::<f64>() + nyf * (0..ny).map(|j| (r[nx + j] - (j + 1) as f64).powi(2)).sum::<f64>();
170 let (k, n) = (nxf * nyf, nxf + nyf);
171 let t = u / (k * n) - (4.0 * k - 1.0) / (6.0 * n);
172 let p = if exact {
173 cvm_2samp_exact(u, nx, ny)
174 } else {
175 let et = (1.0 + 1.0 / n) / 6.0;
176 let vt = (n + 1.0) * (4.0 * k * n - 3.0 * (nxf * nxf + nyf * nyf) - 2.0 * k) / (45.0 * n * n * 4.0 * k);
177 let tn = 1.0 / 6.0 + (t - et) / (45.0 * vt).sqrt();
178 if tn >= 0.003 { (1.0 - cramer_von_mises_cdf_limit(tn)).max(0.0) } else { 1.0 }
179 };
180 Ok(TestResult::new(t, p, f64::NAN))
181}
182#[cfg(test)]
185mod tests {
186 use super::*;
187
188 #[test]
189 fn limiting_distribution_and_exact_two_sample_p_values() {
190 assert!((cramer_von_mises_cdf_limit(0.46136) - 0.95).abs() < 1e-4);
192 let (x, y) = ([0.3, 1.9, 2.5], [0.1, 1.1, 3.2, 4.0]);
194 let r = cramervonmises_2samp(&x, &y, CvmMethod::Exact).unwrap();
195 let pooled: Vec<f64> = x.iter().chain(&y).copied().collect();
196 let mut count = 0;
197 let mut total = 0;
198 for mask in 0u32..128 {
199 if mask.count_ones() != 3 {
200 continue;
201 }
202 let xs: Vec<f64> = (0..7).filter(|i| mask >> i & 1 == 1).map(|i| pooled[i]).collect();
203 let ys: Vec<f64> = (0..7).filter(|i| mask >> i & 1 == 0).map(|i| pooled[i]).collect();
204 let t = cramervonmises_2samp(&xs, &ys, CvmMethod::Asymptotic).unwrap().statistic;
205 total += 1;
206 if t >= r.statistic - 1e-12 {
207 count += 1;
208 }
209 }
210 assert!((r.p_value - count as f64 / total as f64).abs() < 1e-12, "{} vs {count}/{total}", r.p_value);
211 let u: Vec<f64> = (0..40).map(|i| (i as f64 + 0.5) / 40.0).collect();
213 assert!(cramervonmises(&u, |v| v.clamp(0.0, 1.0)).unwrap().p_value > 0.99);
214 }
215}