Skip to main content

lib_jsl_statistics/
hypothesis_tests.rs

1//! Classical hypothesis tests.
2//!
3//! See the book entry [Hypothesis tests](https://jwkunz.github.io/lib_jsl/book/statistics/hypothesis-tests.html).
4
5use crate::correlation::rank;
6use crate::descriptive::{mean, variance};
7use lib_jsl_core::ErrorsJSL;
8use lib_jsl_special_functions::{chi_square_survival, incomplete_beta, normal_cdf, student_t_cdf};
9
10/// The alternative hypothesis.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum Alternative {
13    TwoSided,
14    /// The location of the first sample is less (than the reference or the second sample).
15    Less,
16    Greater,
17}
18
19/// A test statistic with its p-value.
20#[derive(Debug, Clone, Copy, PartialEq)]
21#[non_exhaustive]
22pub struct TestResult {
23    pub statistic: f64,
24    pub p_value: f64,
25    /// Degrees of freedom of the reference distribution (NaN where not applicable).
26    pub degrees_of_freedom: f64,
27}
28
29impl TestResult {
30    /// A result built outside the library, for example for a custom test (the struct is
31    /// `#[non_exhaustive]`, so it cannot be written as a literal in other crates).
32    pub fn new(statistic: f64, p_value: f64, degrees_of_freedom: f64) -> TestResult {
33        TestResult { statistic, p_value, degrees_of_freedom }
34    }
35}
36
37fn tail(cdf: impl Fn(f64) -> f64, statistic: f64, alternative: Alternative) -> f64 {
38    // Symmetric reference distributions: use the lower tail to avoid cancellation.
39    match alternative {
40        Alternative::TwoSided => (2.0 * cdf(-statistic.abs())).min(1.0),
41        Alternative::Less => cdf(statistic),
42        Alternative::Greater => cdf(-statistic),
43    }
44}
45
46/// One-sample Student t-test of the mean against `mu`.
47pub fn t_test_one_sample(x: &[f64], mu: f64, alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
48    let n = x.len() as f64;
49    let t = (mean(x)? - mu) / (variance(x, 1)? / n).sqrt();
50    let df = n - 1.0;
51    Ok(TestResult { statistic: t, p_value: tail(|v| student_t_cdf(v, df), t, alternative), degrees_of_freedom: df })
52}
53
54// ANCHOR: t_two_sample
55/// Two-sample t-test of equal means: Student's pooled-variance test with `equal_variance`,
56/// otherwise Welch's test with the Welch-Satterthwaite degrees of freedom.
57pub fn t_test_two_sample(x: &[f64], y: &[f64], equal_variance: bool, alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
58    let (nx, ny) = (x.len() as f64, y.len() as f64);
59    let (vx, vy) = (variance(x, 1)?, variance(y, 1)?);
60    let difference = mean(x)? - mean(y)?;
61    let (t, df) = if equal_variance {
62        let pooled = ((nx - 1.0) * vx + (ny - 1.0) * vy) / (nx + ny - 2.0);
63        (difference / (pooled * (1.0 / nx + 1.0 / ny)).sqrt(), nx + ny - 2.0)
64    } else {
65        let (a, b) = (vx / nx, vy / ny);
66        (difference / (a + b).sqrt(), (a + b).powi(2) / (a * a / (nx - 1.0) + b * b / (ny - 1.0)))
67    };
68    Ok(TestResult { statistic: t, p_value: tail(|v| student_t_cdf(v, df), t, alternative), degrees_of_freedom: df })
69}
70// ANCHOR_END: t_two_sample
71
72/// Paired t-test: the one-sample test on the differences `x − y`.
73pub fn t_test_paired(x: &[f64], y: &[f64], alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
74    if x.len() != y.len() {
75        return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), y.len())));
76    }
77    let d: Vec<f64> = x.iter().zip(y).map(|(a, b)| a - b).collect();
78    t_test_one_sample(&d, 0.0, alternative)
79}
80
81/// Pearson's chi-square goodness-of-fit test of observed counts against expected frequencies
82/// (uniform when `None`; rescaled to the observed total), on `k − 1` degrees of freedom.
83pub fn chi_square_goodness_of_fit(observed: &[f64], expected: Option<&[f64]>) -> Result<TestResult, ErrorsJSL> {
84    let k = observed.len();
85    if k < 2 {
86        return Err(ErrorsJSL::InvalidInputRange("Need at least two categories."));
87    }
88    let total: f64 = observed.iter().sum();
89    let expected: Vec<f64> = match expected {
90        Some(e) if e.len() != k => return Err(ErrorsJSL::IncompatibleArraySizes((e.len(), k))),
91        Some(e) => {
92            let s: f64 = e.iter().sum();
93            e.iter().map(|v| v * total / s).collect()
94        }
95        None => vec![total / k as f64; k],
96    };
97    if expected.iter().any(|e| !(*e > 0.0)) {
98        return Err(ErrorsJSL::InvalidInputRange("Expected frequencies must be positive."));
99    }
100    let statistic: f64 = observed.iter().zip(&expected).map(|(o, e)| (o - e) * (o - e) / e).sum();
101    let df = (k - 1) as f64;
102    Ok(TestResult { statistic, p_value: chi_square_survival(statistic, df), degrees_of_freedom: df })
103}
104
105/// Pearson's chi-square test of independence for an `r × c` contingency table (no continuity
106/// correction), on `(r − 1)(c − 1)` degrees of freedom.
107pub fn chi_square_independence(table: &[Vec<f64>]) -> Result<TestResult, ErrorsJSL> {
108    let r = table.len();
109    let c = table.first().map_or(0, |row| row.len());
110    if r < 2 || c < 2 || table.iter().any(|row| row.len() != c) {
111        return Err(ErrorsJSL::InvalidInputRange("Need a rectangular table of at least 2 × 2."));
112    }
113    let rows: Vec<f64> = table.iter().map(|row| row.iter().sum()).collect();
114    let columns: Vec<f64> = (0..c).map(|j| table.iter().map(|row| row[j]).sum()).collect();
115    let total: f64 = rows.iter().sum();
116    let mut statistic = 0.0;
117    for i in 0..r {
118        for j in 0..c {
119            let e = rows[i] * columns[j] / total;
120            if !(e > 0.0) {
121                return Err(ErrorsJSL::InvalidInputRange("A row or column of the table is empty."));
122            }
123            statistic += (table[i][j] - e).powi(2) / e;
124        }
125    }
126    let df = ((r - 1) * (c - 1)) as f64;
127    Ok(TestResult { statistic, p_value: chi_square_survival(statistic, df), degrees_of_freedom: df })
128}
129
130/// One-way analysis of variance: the F test of equal group means, on `(k − 1, N − k)` degrees
131/// of freedom (reported as the between-groups value; the within-groups one is `N − k`).
132pub fn anova_one_way(groups: &[Vec<f64>]) -> Result<(TestResult, f64), ErrorsJSL> {
133    let k = groups.len();
134    let n: usize = groups.iter().map(|g| g.len()).sum();
135    if k < 2 || n <= k || groups.iter().any(|g| g.is_empty()) {
136        return Err(ErrorsJSL::InvalidInputRange("Need at least two non-empty groups and more observations than groups."));
137    }
138    let grand = groups.iter().flatten().sum::<f64>() / n as f64;
139    let mut between = 0.0;
140    let mut within = 0.0;
141    for g in groups {
142        let m = g.iter().sum::<f64>() / g.len() as f64;
143        between += g.len() as f64 * (m - grand).powi(2);
144        within += g.iter().map(|v| (v - m).powi(2)).sum::<f64>();
145    }
146    let (df1, df2) = ((k - 1) as f64, (n - k) as f64);
147    let f = (between / df1) / (within / df2);
148    // The upper tail P(F > f) = I_{d2/(d2 + d1 f)}(d2/2, d1/2) directly: 1 − CDF would lose every
149    // digit of a small p-value.
150    let p_value = if f.is_finite() { incomplete_beta(0.5 * df2, 0.5 * df1, df2 / (df2 + df1 * f)) } else { 0.0 };
151    Ok((TestResult { statistic: f, p_value, degrees_of_freedom: df1 }, df2))
152}
153
154/// The Kolmogorov distribution's survival function `Q(λ) = 2 Σ (−1)^{k−1} e^{−2k²λ²}`.
155pub fn kolmogorov_survival(lambda: f64) -> f64 {
156    if lambda < 0.2 {
157        return 1.0;
158    }
159    let mut sum = 0.0;
160    for k in 1..=100 {
161        let term = (-2.0 * (k * k) as f64 * lambda * lambda).exp();
162        sum += if k % 2 == 1 { term } else { -term };
163        if term < 1e-17 {
164            break;
165        }
166    }
167    (2.0 * sum).clamp(0.0, 1.0)
168}
169
170/// The one-sample Kolmogorov-Smirnov test of `x` against a continuous `cdf`:
171/// `D = sup |F_n − F|`, with the asymptotic p-value `Q((√n + 0.12 + 0.11/√n) D)` (Stephens).
172pub fn ks_test_one_sample<F: Fn(f64) -> f64>(x: &[f64], cdf: F) -> Result<TestResult, ErrorsJSL> {
173    if x.is_empty() || x.iter().any(|v| v.is_nan()) {
174        return Err(ErrorsJSL::InvalidInputRange("The sample must be non-empty and free of NaN."));
175    }
176    let mut s = x.to_vec();
177    s.sort_by(f64::total_cmp);
178    let n = s.len() as f64;
179    let d = s.iter().enumerate().map(|(i, &v)| { let f = cdf(v); (f - i as f64 / n).max((i + 1) as f64 / n - f) }).fold(0.0, f64::max);
180    let en = n.sqrt();
181    Ok(TestResult { statistic: d, p_value: kolmogorov_survival((en + 0.12 + 0.11 / en) * d), degrees_of_freedom: f64::NAN })
182}
183
184/// The two-sample Kolmogorov-Smirnov test. The p-value is the asymptotic
185/// `Q((√nₑ + 0.12 + 0.11/√nₑ) D)` with the effective size `nₑ = nm / (n + m)`, borrowing
186/// Stephens' one-sample correction; for small samples it can differ from the exact p-value by
187/// several per cent (7% for samples of 15 and 25).
188pub fn ks_test_two_sample(x: &[f64], y: &[f64]) -> Result<TestResult, ErrorsJSL> {
189    if x.is_empty() || y.is_empty() || x.iter().chain(y).any(|v| v.is_nan()) {
190        return Err(ErrorsJSL::InvalidInputRange("Both samples must be non-empty and free of NaN."));
191    }
192    let (mut a, mut b) = (x.to_vec(), y.to_vec());
193    a.sort_by(f64::total_cmp);
194    b.sort_by(f64::total_cmp);
195    let (n, m) = (a.len(), b.len());
196    let (mut i, mut j, mut d) = (0usize, 0usize, 0.0f64);
197    while i < n && j < m {
198        let v = a[i].min(b[j]);
199        while i < n && a[i] <= v {
200            i += 1;
201        }
202        while j < m && b[j] <= v {
203            j += 1;
204        }
205        d = d.max((i as f64 / n as f64 - j as f64 / m as f64).abs());
206    }
207    let en = ((n * m) as f64 / (n + m) as f64).sqrt();
208    Ok(TestResult { statistic: d, p_value: kolmogorov_survival((en + 0.12 + 0.11 / en) * d), degrees_of_freedom: f64::NAN })
209}
210
211// ANCHOR: mann_whitney
212/// The Mann-Whitney U test (Wilcoxon rank-sum) for a location shift between two samples. The
213/// statistic is `U` of the first sample; the p-value uses the normal approximation with tie and
214/// continuity corrections (adequate for samples above about 10 each).
215pub fn mann_whitney_u(x: &[f64], y: &[f64], alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
216    if x.is_empty() || y.is_empty() {
217        return Err(ErrorsJSL::InvalidInputRange("Both samples must be non-empty."));
218    }
219    let (n1, n2) = (x.len() as f64, y.len() as f64);
220    let combined: Vec<f64> = x.iter().chain(y).copied().collect();
221    let ranks = rank(&combined);
222    let r1: f64 = ranks[..x.len()].iter().sum();
223    let u = r1 - n1 * (n1 + 1.0) / 2.0;
224    let n = n1 + n2;
225    // Tie correction Σ(t³ − t).
226    let mut sorted = combined.clone();
227    sorted.sort_by(f64::total_cmp);
228    let mut ties = 0.0;
229    let mut i = 0;
230    while i < sorted.len() {
231        let mut j = i;
232        while j + 1 < sorted.len() && sorted[j + 1] == sorted[i] {
233            j += 1;
234        }
235        let t = (j - i + 1) as f64;
236        ties += t * t * t - t;
237        i = j + 1;
238    }
239    let mu = n1 * n2 / 2.0;
240    let sigma = (n1 * n2 / 12.0 * ((n + 1.0) - ties / (n * (n - 1.0)))).sqrt();
241    let z = |shift: f64| (u - mu + shift) / sigma;
242    let p = match alternative {
243        Alternative::TwoSided => (2.0 * normal_cdf(-((u - mu).abs() - 0.5).max(0.0) / sigma, 0.0, 1.0)).min(1.0),
244        Alternative::Less => normal_cdf(z(0.5), 0.0, 1.0),
245        Alternative::Greater => normal_cdf(-z(-0.5), 0.0, 1.0),
246    };
247    Ok(TestResult { statistic: u, p_value: p, degrees_of_freedom: f64::NAN })
248}
249// ANCHOR_END: mann_whitney
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use lib_jsl_special_functions::f_cdf;
255
256    #[test]
257    fn t_tests_reach_textbook_critical_values() {
258        // x = 2.228 + e with e = −5..5: mean offset 2.228 and standard error exactly 1, so
259        // t = 2.228, the two-sided 5% critical value for 10 degrees of freedom.
260        let x: Vec<f64> = (-5..=5).map(|e| 2.228 + e as f64).collect();
261        let r = t_test_one_sample(&x, 0.0, Alternative::TwoSided).unwrap();
262        assert!((r.statistic - 2.228).abs() < 1e-12 && r.degrees_of_freedom == 10.0);
263        assert!((r.p_value - 0.05).abs() < 2e-4, "{}", r.p_value);
264        let greater = t_test_one_sample(&x, 0.0, Alternative::Greater).unwrap().p_value;
265        assert!((greater - r.p_value / 2.0).abs() < 1e-12 && (t_test_one_sample(&x, 0.0, Alternative::Less).unwrap().p_value - (1.0 - greater)).abs() < 1e-12);
266        // Two samples: pooled versus Welch.
267        let a = [19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0];
268        let b = [28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7, 23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2];
269        let student = t_test_two_sample(&a, &b, true, Alternative::TwoSided).unwrap();
270        let welch = t_test_two_sample(&a, &b, false, Alternative::TwoSided).unwrap();
271        let (va, vb) = (variance(&a, 1).unwrap() / 10.0, variance(&b, 1).unwrap() / 20.0);
272        assert!((welch.degrees_of_freedom - (va + vb).powi(2) / (va * va / 9.0 + vb * vb / 19.0)).abs() < 1e-9);
273        let difference = mean(&a).unwrap() - mean(&b).unwrap();
274        assert!((welch.statistic - difference / (va + vb).sqrt()).abs() < 1e-12);
275        assert!(student.degrees_of_freedom == 28.0 && student.statistic < 0.0 && (0.0..1.0).contains(&welch.p_value));
276        let paired = t_test_paired(&[1.0, 2.0, 3.0, 4.0], &[1.5, 2.5, 3.0, 5.0], Alternative::TwoSided).unwrap();
277        assert!(paired.statistic < 0.0 && paired.degrees_of_freedom == 3.0);
278    }
279
280    #[test]
281    fn chi_square_and_anova() {
282        // 60/40 against 50/50: χ² = 4, p = 0.0455.
283        let g = chi_square_goodness_of_fit(&[60.0, 40.0], None).unwrap();
284        assert!((g.statistic - 4.0).abs() < 1e-12 && (g.p_value - 0.045_500_26).abs() < 1e-7, "{}", g.p_value);
285        let weighted = chi_square_goodness_of_fit(&[30.0, 70.0], Some(&[1.0, 3.0])).unwrap();
286        assert!((weighted.statistic - (25.0 / 25.0 + 25.0 / 75.0)).abs() < 1e-12);
287        // 2 × 2 table with expected 15 in every cell: χ² = 20/3, p = 0.00982.
288        let ind = chi_square_independence(&[vec![10.0, 20.0], vec![20.0, 10.0]]).unwrap();
289        assert!((ind.statistic - 20.0 / 3.0).abs() < 1e-12 && (ind.p_value - 0.009_823).abs() < 1e-5, "{}", ind.p_value);
290        // ANOVA: F = MS_between / MS_within computed by hand.
291        let groups = vec![vec![1.0, 2.0, 3.0, 4.0, 5.0], vec![3.0, 4.0, 5.0, 6.0, 7.0], vec![5.0, 6.0, 7.0, 8.0, 9.0]];
292        let (f, df2) = anova_one_way(&groups).unwrap();
293        assert!((f.statistic - (40.0 / 2.0) / (30.0 / 12.0)).abs() < 1e-12 && df2 == 12.0);
294        // F(2, 12) = 3.885 is the 5% critical value.
295        let critical: Vec<Vec<f64>> = vec![vec![0.0, 1.0], vec![0.0, 1.0]];
296        assert!(anova_one_way(&critical).unwrap().0.p_value > 0.99);
297        assert!((1.0 - f_cdf(3.885, 2.0, 12.0) - 0.05).abs() < 1e-3);
298        assert!(f.p_value < 0.01);
299        // Small p-values keep their relative precision: here F = 20 000 on (2, 12), and
300        // p = (1 + 2F/12)^{−6} is about 7e-22, which 1 − CDF would round to zero.
301        let separated = vec![vec![0.0, 0.1, 0.2, 0.3, 0.4], vec![10.0, 10.1, 10.2, 10.3, 10.4], vec![20.0, 20.1, 20.2, 20.3, 20.4]];
302        let (far, _) = anova_one_way(&separated).unwrap();
303        let exact = (1.0 + 2.0 * far.statistic / 12.0).powi(-6);
304        assert!((far.p_value / exact - 1.0).abs() < 1e-10, "{} vs {exact}", far.p_value);
305        assert!(chi_square_goodness_of_fit(&[1.0], None).is_err() && chi_square_independence(&[vec![1.0, 2.0]]).is_err());
306    }
307
308    #[test]
309    fn rank_and_distribution_tests() {
310        assert!((kolmogorov_survival(1.358) - 0.05).abs() < 2e-4);
311        // A perfectly spaced uniform sample is accepted; a shifted one rejected.
312        let u: Vec<f64> = (0..200).map(|i| (i as f64 + 0.5) / 200.0).collect();
313        let accept = ks_test_one_sample(&u, |v| v.clamp(0.0, 1.0)).unwrap();
314        assert!((accept.statistic - 0.0025).abs() < 1e-12 && accept.p_value > 0.99);
315        let shifted: Vec<f64> = u.iter().map(|v| v * 0.8).collect();
316        assert!(ks_test_one_sample(&shifted, |v| v.clamp(0.0, 1.0)).unwrap().p_value < 1e-6);
317        let two = ks_test_two_sample(&[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0, 7.0]).unwrap();
318        assert_eq!(two.statistic, 1.0);
319        assert_eq!(ks_test_two_sample(&u, &u).unwrap().statistic, 0.0);
320        // Mann-Whitney: complete separation of two samples of 10 gives U = 0 and z = −49.5/13.23.
321        let x: Vec<f64> = (0..10).map(|v| v as f64).collect();
322        let y: Vec<f64> = (10..20).map(|v| v as f64).collect();
323        let mw = mann_whitney_u(&x, &y, Alternative::TwoSided).unwrap();
324        let z = 49.5 / (100.0f64 * 21.0 / 12.0).sqrt();
325        assert!(mw.statistic == 0.0 && (mw.p_value - 2.0 * normal_cdf(-z, 0.0, 1.0)).abs() < 1e-12);
326        assert!(mann_whitney_u(&x, &y, Alternative::Less).unwrap().p_value < 1e-3 && mann_whitney_u(&x, &y, Alternative::Greater).unwrap().p_value > 0.99);
327    }
328}