Skip to main content

lib_jsl_statistics/
comparisons.rs

1//! More tests comparing samples, following `scipy.stats`: equal variances (Levene, Bartlett,
2//! Fligner-Killeen), rank tests (Kruskal-Wallis, Friedman, Wilcoxon signed-rank), exact tests
3//! (Fisher's exact test for 2 × 2 tables, the binomial test), permutation tests, and the
4//! adjustment of p-values for multiple comparisons (Benjamini-Hochberg, Benjamini-Yekutieli,
5//! Holm, Bonferroni).
6//!
7//! See the book entry [More hypothesis tests](https://jwkunz.github.io/lib_jsl/book/statistics/more-tests.html).
8
9use crate::correlation::rank;
10use crate::distributions::{DiscreteDistribution, Hypergeometric, Binomial};
11use crate::hypothesis_tests::{Alternative, TestResult};
12use lib_jsl_core::ErrorsJSL;
13use lib_jsl_random::uniform_generator::UniformGenerator;
14use lib_jsl_random::xoshiro256plusplus::Xoshiro256PlusPlus;
15use lib_jsl_special_functions::{chi_square_survival, f_cdf, normal_cdf, normal_quantile};
16
17fn mean(x: &[f64]) -> f64 {
18    x.iter().sum::<f64>() / x.len() as f64
19}
20
21fn median(x: &[f64]) -> f64 {
22    let mut s = x.to_vec();
23    s.sort_by(f64::total_cmp);
24    let n = s.len();
25    if n % 2 == 1 { s[n / 2] } else { 0.5 * (s[n / 2 - 1] + s[n / 2]) }
26}
27
28fn var(x: &[f64]) -> f64 {
29    let m = mean(x);
30    x.iter().map(|v| (v - m).powi(2)).sum::<f64>() / (x.len() as f64 - 1.0)
31}
32
33fn check_groups(groups: &[Vec<f64>]) -> Result<(), ErrorsJSL> {
34    if groups.len() < 2 || groups.iter().any(|g| g.len() < 2) {
35        return Err(ErrorsJSL::InvalidInputRange("need at least two groups of at least two values"));
36    }
37    Ok(())
38}
39
40/// `Σ (t³ − t)` over the groups of tied values.
41fn tie_sum(values: &[f64]) -> f64 {
42    let mut s = values.to_vec();
43    s.sort_by(f64::total_cmp);
44    let mut total = 0.0;
45    let mut i = 0;
46    while i < s.len() {
47        let mut j = i;
48        while j + 1 < s.len() && s[j + 1] == s[i] {
49            j += 1;
50        }
51        let t = (j - i + 1) as f64;
52        total += t * t * t - t;
53        i = j + 1;
54    }
55    total
56}
57
58// ------------------------------------------------------------------------------ equal variances
59
60// ANCHOR: levene
61/// Levene's test of equal variances with Brown and Forsythe's median centring (SciPy's `levene`
62/// with `center='median'`): one-way ANOVA on the absolute deviations from each group's median,
63/// referred to the F distribution with `k − 1` and `N − k` degrees of freedom.
64pub fn levene(groups: &[Vec<f64>]) -> Result<TestResult, ErrorsJSL> {
65    check_groups(groups)?;
66    let z: Vec<Vec<f64>> = groups.iter().map(|g| {
67        let m = median(g);
68        g.iter().map(|v| (v - m).abs()).collect()
69    }).collect();
70    let k = groups.len() as f64;
71    let n_total: f64 = z.iter().map(|g| g.len() as f64).sum();
72    let grand = z.iter().flatten().sum::<f64>() / n_total;
73    let between: f64 = z.iter().map(|g| g.len() as f64 * (mean(g) - grand).powi(2)).sum();
74    let within: f64 = z.iter().map(|g| {
75        let m = mean(g);
76        g.iter().map(|v| (v - m).powi(2)).sum::<f64>()
77    }).sum();
78    let w = (n_total - k) / (k - 1.0) * between / within;
79    Ok(TestResult { statistic: w, p_value: 1.0 - f_cdf(w, k - 1.0, n_total - k), degrees_of_freedom: k - 1.0 })
80}
81// ANCHOR_END: levene
82
83/// Bartlett's test of equal variances for normal samples (SciPy's `bartlett`), χ² with `k − 1`
84/// degrees of freedom.
85pub fn bartlett(groups: &[Vec<f64>]) -> Result<TestResult, ErrorsJSL> {
86    check_groups(groups)?;
87    let k = groups.len() as f64;
88    let ni: Vec<f64> = groups.iter().map(|g| g.len() as f64).collect();
89    let vi: Vec<f64> = groups.iter().map(|g| var(g)).collect();
90    let n_total: f64 = ni.iter().sum();
91    let sp2 = ni.iter().zip(&vi).map(|(n, v)| (n - 1.0) * v).sum::<f64>() / (n_total - k);
92    let num = (n_total - k) * sp2.ln() - ni.iter().zip(&vi).map(|(n, v)| (n - 1.0) * v.ln()).sum::<f64>();
93    let denom = 1.0 + (ni.iter().map(|n| 1.0 / (n - 1.0)).sum::<f64>() - 1.0 / (n_total - k)) / (3.0 * (k - 1.0));
94    let t = num / denom;
95    Ok(TestResult { statistic: t, p_value: chi_square_survival(t, k - 1.0), degrees_of_freedom: k - 1.0 })
96}
97
98/// The Fligner-Killeen test of equal variances (SciPy's `fligner`, median centring): normal
99/// scores of the ranks of the absolute deviations, compared across groups; robust to
100/// non-normality.
101pub fn fligner(groups: &[Vec<f64>]) -> Result<TestResult, ErrorsJSL> {
102    check_groups(groups)?;
103    let k = groups.len() as f64;
104    let dev: Vec<f64> = groups.iter().flat_map(|g| {
105        let m = median(g);
106        g.iter().map(move |v| (v - m).abs()).collect::<Vec<_>>()
107    }).collect();
108    let n_total = dev.len() as f64;
109    let ranks = rank(&dev);
110    let a: Vec<f64> = ranks.iter().map(|r| normal_quantile(r / (2.0 * (n_total + 1.0)) + 0.5, 0.0, 1.0)).collect();
111    let abar = mean(&a);
112    let varsq = var(&a);
113    let mut start = 0;
114    let mut stat = 0.0;
115    for g in groups {
116        let seg = &a[start..start + g.len()];
117        stat += g.len() as f64 * (mean(seg) - abar).powi(2);
118        start += g.len();
119    }
120    let stat = stat / varsq;
121    Ok(TestResult { statistic: stat, p_value: chi_square_survival(stat, k - 1.0), degrees_of_freedom: k - 1.0 })
122}
123
124// ----------------------------------------------------------------------------------- rank tests
125
126/// The Kruskal-Wallis H test that `k` samples come from the same distribution (SciPy's `kruskal`),
127/// with the tie correction, χ² with `k − 1` degrees of freedom.
128pub fn kruskal(groups: &[Vec<f64>]) -> Result<TestResult, ErrorsJSL> {
129    if groups.len() < 2 || groups.iter().any(|g| g.is_empty()) {
130        return Err(ErrorsJSL::InvalidInputRange("need at least two non-empty groups"));
131    }
132    let all: Vec<f64> = groups.iter().flatten().copied().collect();
133    let n = all.len() as f64;
134    let ranks = rank(&all);
135    let mut start = 0;
136    let mut h = 0.0;
137    for g in groups {
138        let r: f64 = ranks[start..start + g.len()].iter().sum();
139        h += r * r / g.len() as f64;
140        start += g.len();
141    }
142    h = 12.0 / (n * (n + 1.0)) * h - 3.0 * (n + 1.0);
143    let correction = 1.0 - tie_sum(&all) / (n * n * n - n);
144    let h = h / correction;
145    let df = groups.len() as f64 - 1.0;
146    Ok(TestResult { statistic: h, p_value: chi_square_survival(h, df), degrees_of_freedom: df })
147}
148
149/// Friedman's test for `k` treatments measured on the same `n` blocks (SciPy's
150/// `friedmanchisquare`): `treatments[j][i]` is treatment `j` on block `i`. Ranks within each
151/// block, with the tie correction, χ² with `k − 1` degrees of freedom.
152pub fn friedman(treatments: &[Vec<f64>]) -> Result<TestResult, ErrorsJSL> {
153    let k = treatments.len();
154    if k < 3 {
155        return Err(ErrorsJSL::InvalidInputRange("Friedman's test needs at least three treatments"));
156    }
157    let n = treatments[0].len();
158    if treatments.iter().any(|t| t.len() != n) || n < 2 {
159        return Err(ErrorsJSL::InvalidInputRange("every treatment needs the same blocks"));
160    }
161    let mut rank_sums = vec![0.0; k];
162    let mut ties = 0.0;
163    for i in 0..n {
164        let block: Vec<f64> = treatments.iter().map(|t| t[i]).collect();
165        let r = rank(&block);
166        for j in 0..k {
167            rank_sums[j] += r[j];
168        }
169        ties += tie_sum(&block);
170    }
171    let (nf, kf) = (n as f64, k as f64);
172    let c = 1.0 - ties / (nf * kf * (kf * kf - 1.0));
173    let ssbn: f64 = rank_sums.iter().map(|r| r * r).sum();
174    let chi2 = (12.0 / (nf * kf * (kf + 1.0)) * ssbn - 3.0 * nf * (kf + 1.0)) / c;
175    Ok(TestResult { statistic: chi2, p_value: chi_square_survival(chi2, kf - 1.0), degrees_of_freedom: kf - 1.0 })
176}
177
178// ANCHOR: wilcoxon
179/// The Wilcoxon signed-rank test that the differences `d` (or `x − y`) are symmetric about zero
180/// (SciPy's `wilcoxon` with its defaults: zeros dropped, no continuity correction). Without ties
181/// or zeros the p-value is exact, from the distribution of `W⁺` computed by dynamic programming
182/// over the ranks; with ties, by enumerating all sign changes when `n ≤ 13`, and otherwise from the
183/// normal approximation with the tie correction. For the two-sided test the statistic is
184/// `min(W⁺, W⁻)`, otherwise `W⁺`.
185pub fn wilcoxon(d: &[f64], alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
186    let n_all = d.len();
187    let nonzero: Vec<f64> = d.iter().copied().filter(|v| *v != 0.0).collect();
188    let n = nonzero.len();
189    if n == 0 {
190        return Err(ErrorsJSL::InvalidInputRange("all differences are zero"));
191    }
192    let abs: Vec<f64> = nonzero.iter().map(|v| v.abs()).collect();
193    let r = rank(&abs);
194    let r_plus: f64 = nonzero.iter().zip(&r).filter(|(v, _)| **v > 0.0).map(|(_, r)| r).sum();
195    let r_minus: f64 = nonzero.iter().zip(&r).filter(|(v, _)| **v < 0.0).map(|(_, r)| r).sum();
196    let has_ties = tie_sum(&abs) > 0.0;
197    let has_zeros = n < n_all;
198    let p = if !has_ties && !has_zeros {
199        // Exact distribution of W⁺ = Σ of a random subset of 1..n.
200        let max = n * (n + 1) / 2;
201        let mut counts = vec![0.0f64; max + 1];
202        counts[0] = 1.0;
203        for k in 1..=n {
204            for s in (k..=max).rev() {
205                counts[s] += counts[s - k];
206            }
207        }
208        let total = 2f64.powi(n as i32);
209        let cdf = |w: usize| counts[..=w.min(max)].iter().sum::<f64>() / total;
210        let sf = |w: usize| if w == 0 { 1.0 } else { 1.0 - cdf(w - 1) };
211        let (lo, hi) = (r_plus.ceil() as usize, r_plus.floor() as usize);
212        match alternative {
213            Alternative::Less => cdf(lo),
214            Alternative::Greater => sf(hi),
215            Alternative::TwoSided => (2.0 * sf(hi).min(cdf(lo))).min(1.0),
216        }
217    } else if n_all <= 13 {
218        // Permutation: every assignment of signs to the non-zero ranks.
219        let eps = (100.0 * f64::EPSILON * r_plus).abs();
220        let (mut le, mut ge) = (0usize, 0usize);
221        for mask in 0..(1usize << n) {
222            let w: f64 = (0..n).filter(|&i| mask >> i & 1 == 1).map(|i| r[i]).sum();
223            if w <= r_plus + eps {
224                le += 1;
225            }
226            if w >= r_plus - eps {
227                ge += 1;
228            }
229        }
230        let total = (1usize << n) as f64;
231        let (pl, pg) = (le as f64 / total, ge as f64 / total);
232        match alternative {
233            Alternative::Less => pl,
234            Alternative::Greater => pg,
235            Alternative::TwoSided => (2.0 * pl.min(pg)).min(1.0),
236        }
237    } else {
238        let nf = n as f64;
239        let mn = nf * (nf + 1.0) * 0.25;
240        let se = ((nf * (nf + 1.0) * (2.0 * nf + 1.0) - tie_sum(&abs) / 2.0) / 24.0).sqrt();
241        let z = (r_plus - mn) / se;
242        match alternative {
243            Alternative::Less => normal_cdf(z, 0.0, 1.0),
244            Alternative::Greater => normal_cdf(-z, 0.0, 1.0),
245            Alternative::TwoSided => 2.0 * normal_cdf(-z.abs(), 0.0, 1.0),
246        }
247    };
248    let statistic = if alternative == Alternative::TwoSided { r_plus.min(r_minus) } else { r_plus };
249    Ok(TestResult { statistic, p_value: p, degrees_of_freedom: f64::NAN })
250}
251// ANCHOR_END: wilcoxon
252
253// ---------------------------------------------------------------------------------- exact tests
254
255/// Fisher's exact test for a 2 × 2 table `[[a, b], [c, d]]` (SciPy's `fisher_exact`): the
256/// statistic is the sample odds ratio `ad / bc`, and the p-value comes from the hypergeometric
257/// distribution of `a` with the margins fixed; the two-sided p-value sums the probabilities of all
258/// tables no more likely than the observed one.
259pub fn fisher_exact(table: [[u64; 2]; 2], alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
260    let [[a, b], [c, d]] = table;
261    let odds = if b == 0 || c == 0 {
262        if a == 0 || d == 0 { f64::NAN } else { f64::INFINITY }
263    } else {
264        (a * d) as f64 / (b * c) as f64
265    };
266    let total = a + b + c + d;
267    if a + b == 0 || c + d == 0 || a + c == 0 || b + d == 0 {
268        return Ok(TestResult { statistic: f64::NAN, p_value: 1.0, degrees_of_freedom: f64::NAN });
269    }
270    let h = Hypergeometric::new(total, a + b, a + c)?;
271    let k = a as i64;
272    let p = match alternative {
273        Alternative::Less => h.cdf(k),
274        Alternative::Greater => h.sf(k - 1),
275        Alternative::TwoSided => {
276            let p0 = h.pmf(k) * (1.0 + 1e-7);
277            let (lo, hi) = h.support();
278            (lo..=hi).map(|j| h.pmf(j)).filter(|&p| p <= p0).sum::<f64>().min(1.0)
279        }
280    };
281    Ok(TestResult { statistic: odds, p_value: p, degrees_of_freedom: f64::NAN })
282}
283
284/// The exact binomial test of `k` successes in `n` trials against success probability `p`
285/// (SciPy's `binomtest`); the two-sided p-value sums the probabilities of all outcomes no more
286/// likely than `k`. The statistic is `k / n`.
287pub fn binomtest(k: u64, n: u64, p: f64, alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
288    if k > n {
289        return Err(ErrorsJSL::InvalidInputRange("k cannot exceed n"));
290    }
291    let b = Binomial::new(n, p)?;
292    let ki = k as i64;
293    let pv = match alternative {
294        Alternative::Less => b.cdf(ki),
295        Alternative::Greater => b.sf(ki - 1),
296        Alternative::TwoSided => {
297            let d = b.pmf(ki) * (1.0 + 1e-7);
298            if (k as f64 - n as f64 * p).abs() < 1e-12 { 1.0 } else { (0..=n as i64).map(|j| b.pmf(j)).filter(|&q| q <= d).sum::<f64>().min(1.0) }
299        }
300    };
301    Ok(TestResult { statistic: k as f64 / n as f64, p_value: pv, degrees_of_freedom: f64::NAN })
302}
303
304// --------------------------------------------------------------------------- permutation tests
305
306/// The result of [`permutation_test`].
307#[derive(Clone, Debug)]
308#[non_exhaustive]
309pub struct PermutationResult {
310    pub statistic: f64,
311    pub p_value: f64,
312    /// The statistic for each permutation examined.
313    pub null_distribution: Vec<f64>,
314    /// `true` when every partition was enumerated.
315    pub exact: bool,
316}
317
318// ANCHOR: permutation
319/// A two-sample permutation test (SciPy's `permutation_test` with `permutation_type='independent'`):
320/// the statistic `f(x, y)` is recomputed for every way of splitting the pooled observations into
321/// groups of the original sizes when there are at most `n_resamples` of them (exact), and otherwise
322/// for `n_resamples` random splits, for which the p-value counts the observed split as well.
323pub fn permutation_test(x: &[f64], y: &[f64], statistic: impl Fn(&[f64], &[f64]) -> f64, alternative: Alternative, n_resamples: usize, seed: u64) -> Result<PermutationResult, ErrorsJSL> {
324    if x.is_empty() || y.is_empty() {
325        return Err(ErrorsJSL::InvalidInputRange("both samples must be non-empty"));
326    }
327    let observed = statistic(x, y);
328    let pooled: Vec<f64> = x.iter().chain(y).copied().collect();
329    let (nx, n) = (x.len(), pooled.len());
330    // C(n, nx), saturating.
331    let mut combos = 1f64;
332    for i in 0..nx {
333        combos = combos * (n - i) as f64 / (i + 1) as f64;
334    }
335    let exact = combos <= n_resamples as f64;
336    let mut null = Vec::new();
337    if exact {
338        // Enumerate the nx-subsets in lexicographic order.
339        let mut idx: Vec<usize> = (0..nx).collect();
340        loop {
341            let mut in_x = vec![false; n];
342            idx.iter().for_each(|&i| in_x[i] = true);
343            let xs: Vec<f64> = (0..n).filter(|&i| in_x[i]).map(|i| pooled[i]).collect();
344            let ys: Vec<f64> = (0..n).filter(|&i| !in_x[i]).map(|i| pooled[i]).collect();
345            null.push(statistic(&xs, &ys));
346            let mut i = nx;
347            while i > 0 && idx[i - 1] == n - nx + i - 1 {
348                i -= 1;
349            }
350            if i == 0 {
351                break;
352            }
353            idx[i - 1] += 1;
354            for j in i..nx {
355                idx[j] = idx[j - 1] + 1;
356            }
357        }
358    } else {
359        let mut rng = Xoshiro256PlusPlus::from_seed(seed);
360        let mut perm = pooled.clone();
361        for _ in 0..n_resamples {
362            for i in (1..n).rev() {
363                let j = (rng.next_f64() * (i + 1) as f64) as usize;
364                perm.swap(i, j.min(i));
365            }
366            null.push(statistic(&perm[..nx], &perm[nx..]));
367        }
368    }
369    let gamma = (100.0 * f64::EPSILON * observed).abs();
370    let le = null.iter().filter(|&&v| v <= observed + gamma).count() as f64;
371    let ge = null.iter().filter(|&&v| v >= observed - gamma).count() as f64;
372    let (pl, pg) = if exact { (le / null.len() as f64, ge / null.len() as f64) } else { ((le + 1.0) / (null.len() as f64 + 1.0), (ge + 1.0) / (null.len() as f64 + 1.0)) };
373    let p = match alternative {
374        Alternative::Less => pl,
375        Alternative::Greater => pg,
376        Alternative::TwoSided => (2.0 * pl.min(pg)).min(1.0),
377    };
378    Ok(PermutationResult { statistic: observed, p_value: p, null_distribution: null, exact })
379}
380// ANCHOR_END: permutation
381
382/// The reference distribution of the Brunner-Munzel statistic.
383#[derive(Clone, Copy, Debug, PartialEq, Eq)]
384#[non_exhaustive]
385pub enum BrunnerMunzelDistribution {
386    /// Student's t with Satterthwaite's degrees of freedom (SciPy's default).
387    T,
388    /// The standard normal, for large samples.
389    Normal,
390}
391
392// ANCHOR: brunnermunzel
393/// The Brunner-Munzel test of `P(X < Y) + ½ P(X = Y) = ½` (SciPy's `brunnermunzel`): unlike the
394/// Mann-Whitney test it does not assume equal variances or shapes. With ranks `R` in the pooled
395/// sample and `R⁽ˣ⁾` within each sample, the placement variances are
396/// `S_x² = Σ (R_i − R_i⁽ˣ⁾ − R̄ + R̄⁽ˣ⁾)² / (n_x − 1)` (likewise for `y`), and
397/// `W = n_x n_y (R̄_y − R̄_x) / ((n_x + n_y) √(n_x S_x² + n_y S_y²))`.
398pub fn brunnermunzel(x: &[f64], y: &[f64], alternative: Alternative, distribution: BrunnerMunzelDistribution) -> Result<TestResult, ErrorsJSL> {
399    let (nx, ny) = (x.len(), y.len());
400    if nx < 2 || ny < 2 || x.iter().chain(y).any(|v| !v.is_finite()) {
401        return Err(ErrorsJSL::InvalidInputRange("brunnermunzel: need at least two finite observations per sample"));
402    }
403    let pooled: Vec<f64> = x.iter().chain(y).copied().collect();
404    let rc = rank(&pooled);
405    let (rcx, rcy) = rc.split_at(nx);
406    let (rx, ry) = (rank(x), rank(y));
407    let mean = |v: &[f64]| v.iter().sum::<f64>() / v.len() as f64;
408    let (mcx, mcy, mx, my) = (mean(rcx), mean(rcy), mean(&rx), mean(&ry));
409    let sx = rcx.iter().zip(&rx).map(|(a, b)| (a - b - mcx + mx).powi(2)).sum::<f64>() / (nx - 1) as f64;
410    let sy = rcy.iter().zip(&ry).map(|(a, b)| (a - b - mcy + my).powi(2)).sum::<f64>() / (ny - 1) as f64;
411    let (nxf, nyf) = (nx as f64, ny as f64);
412    let w = nxf * nyf * (mcy - mcx) / ((nxf + nyf) * (nxf * sx + nyf * sy).sqrt());
413    let (cdf, df): (Box<dyn Fn(f64) -> f64>, f64) = match distribution {
414        BrunnerMunzelDistribution::T => {
415            let df = (nxf * sx + nyf * sy).powi(2) / ((nxf * sx).powi(2) / (nxf - 1.0) + (nyf * sy).powi(2) / (nyf - 1.0));
416            (Box::new(move |t| lib_jsl_special_functions::student_t_cdf(t, df)), df)
417        }
418        BrunnerMunzelDistribution::Normal => (Box::new(|t| normal_cdf(t, 0.0, 1.0)), f64::INFINITY),
419    };
420    // SciPy evaluates the tails at −W.
421    let p = match alternative {
422        Alternative::Less => cdf(-w),
423        Alternative::Greater => cdf(w),
424        Alternative::TwoSided => (2.0 * cdf(-w.abs())).min(1.0),
425    };
426    Ok(TestResult { statistic: w, p_value: p, degrees_of_freedom: df })
427}
428// ANCHOR_END: brunnermunzel
429
430/// The result of [`monte_carlo_test`].
431#[derive(Clone, Debug)]
432#[non_exhaustive]
433pub struct MonteCarloResult {
434    pub statistic: f64,
435    pub p_value: f64,
436    pub null_distribution: Vec<f64>,
437}
438
439// ANCHOR: monte_carlo_test
440/// A Monte Carlo hypothesis test (SciPy's `monte_carlo_test`): the statistic of the observed
441/// samples is compared with its values on `n_resamples` sets of samples of the same sizes drawn
442/// from the null distribution by `rvs(sample index, size, rng)`. The p-value counts the observed
443/// value among the resamples, `(#{T* ≥ T} + 1)/(n + 1)`, so it is never zero, and two-sided
444/// p-values double the smaller tail.
445pub fn monte_carlo_test<U: UniformGenerator>(
446    data: &[Vec<f64>],
447    mut rvs: impl FnMut(usize, usize, &mut U) -> Vec<f64>,
448    statistic: impl Fn(&[Vec<f64>]) -> f64,
449    alternative: Alternative,
450    n_resamples: usize,
451    rng: &mut U,
452) -> Result<MonteCarloResult, ErrorsJSL> {
453    if data.is_empty() || n_resamples == 0 {
454        return Err(ErrorsJSL::InvalidInputRange("monte_carlo_test: need data and at least one resample"));
455    }
456    let observed = statistic(data);
457    let null: Vec<f64> = (0..n_resamples)
458        .map(|_| {
459            let samples: Vec<Vec<f64>> = data.iter().enumerate().map(|(i, d)| rvs(i, d.len(), rng)).collect();
460            statistic(&samples)
461        })
462        .collect();
463    let gamma = (100.0 * f64::EPSILON * observed).abs();
464    let n = n_resamples as f64;
465    let pl = (null.iter().filter(|&&v| v <= observed + gamma).count() as f64 + 1.0) / (n + 1.0);
466    let pg = (null.iter().filter(|&&v| v >= observed - gamma).count() as f64 + 1.0) / (n + 1.0);
467    let p = match alternative {
468        Alternative::Less => pl,
469        Alternative::Greater => pg,
470        Alternative::TwoSided => (2.0 * pl.min(pg)).min(1.0),
471    };
472    Ok(MonteCarloResult { statistic: observed, p_value: p, null_distribution: null })
473}
474// ANCHOR_END: monte_carlo_test
475
476// ------------------------------------------------------------------------ multiple comparisons
477
478/// How [`adjust_p_values`] controls the error rate across many tests.
479#[derive(Clone, Copy, Debug, PartialEq, Eq)]
480pub enum Adjustment {
481    /// Family-wise error rate: `min(1, m p)`.
482    Bonferroni,
483    /// Family-wise error rate, step-down: Holm (1979).
484    Holm,
485    /// False discovery rate for independent or positively dependent tests: Benjamini and
486    /// Hochberg (1995) (SciPy's `false_discovery_control(method='bh')`).
487    BenjaminiHochberg,
488    /// False discovery rate under any dependence: Benjamini and Yekutieli (2001) (`method='by'`).
489    BenjaminiYekutieli,
490}
491
492// ANCHOR: adjust
493/// Adjusted p-values: reject the hypotheses whose adjusted p-value is at most the target rate.
494pub fn adjust_p_values(p: &[f64], method: Adjustment) -> Result<Vec<f64>, ErrorsJSL> {
495    if p.iter().any(|v| !(0.0..=1.0).contains(v)) {
496        return Err(ErrorsJSL::InvalidInputRange("p-values must lie in [0, 1]"));
497    }
498    let m = p.len();
499    let mf = m as f64;
500    let mut order: Vec<usize> = (0..m).collect();
501    order.sort_by(|&a, &b| p[a].total_cmp(&p[b]));
502    let mut adj = vec![0.0; m];
503    match method {
504        Adjustment::Bonferroni => {
505            for i in 0..m {
506                adj[i] = (mf * p[i]).min(1.0);
507            }
508        }
509        Adjustment::Holm => {
510            let mut running: f64 = 0.0;
511            for (rank, &i) in order.iter().enumerate() {
512                running = running.max((mf - rank as f64) * p[i]);
513                adj[i] = running.min(1.0);
514            }
515        }
516        Adjustment::BenjaminiHochberg | Adjustment::BenjaminiYekutieli => {
517            let c = if method == Adjustment::BenjaminiYekutieli { (1..=m).map(|i| 1.0 / i as f64).sum::<f64>() } else { 1.0 };
518            let mut running: f64 = 1.0;
519            for (rank, &i) in order.iter().enumerate().rev() {
520                running = running.min(p[i] * mf * c / (rank + 1) as f64);
521                adj[i] = running.min(1.0);
522            }
523        }
524    }
525    Ok(adj)
526}
527// ANCHOR_END: adjust
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532
533    #[test]
534    fn wilcoxon_exact_matches_a_hand_count() {
535        // n = 5, all positive: W⁺ = 15, P(W⁺ ≥ 15) = 1/32; two-sided statistic min(15, 0) = 0.
536        let r = wilcoxon(&[1.0, 2.0, 3.0, 4.0, 5.0], Alternative::Greater).unwrap();
537        assert!((r.p_value - 1.0 / 32.0).abs() < 1e-15);
538        let r = wilcoxon(&[1.0, 2.0, 3.0, 4.0, 5.0], Alternative::TwoSided).unwrap();
539        assert_eq!(r.statistic, 0.0);
540        assert!((r.p_value - 1.0 / 16.0).abs() < 1e-15);
541    }
542
543    #[test]
544    fn fisher_and_binomial_known_values() {
545        let r = fisher_exact([[8, 2], [1, 5]], Alternative::TwoSided).unwrap();
546        assert!((r.statistic - 20.0).abs() < 1e-12);
547        assert!((r.p_value - 0.034965034965034975).abs() < 1e-12, "{}", r.p_value);
548        let r = binomtest(7, 20, 0.5, Alternative::TwoSided).unwrap();
549        assert!((r.p_value - 0.26317596435546875).abs() < 1e-12, "{}", r.p_value);
550    }
551
552    #[test]
553    fn fdr_adjustment_is_monotone() {
554        let p = [0.01, 0.04, 0.03, 0.005, 0.2];
555        let a = adjust_p_values(&p, Adjustment::BenjaminiHochberg).unwrap();
556        // Sorted p: 0.005, 0.01, 0.03, 0.04, 0.2 → 0.025, 0.025, 0.05, 0.05, 0.2.
557        let want = [0.025, 0.05, 0.05, 0.025, 0.2];
558        for (g, w) in a.iter().zip(want) {
559            assert!((g - w).abs() < 1e-15, "{a:?}");
560        }
561    }
562
563    #[test]
564    fn brunner_munzel_and_monte_carlo() {
565        // Swapping the samples changes the sign of the statistic and keeps the two-sided p-value.
566        let x = [1.0, 2.0, 1.0, 3.0, 2.0, 5.0];
567        let y = [3.0, 4.0, 2.0, 6.0, 5.0, 7.0, 4.0];
568        let a = brunnermunzel(&x, &y, Alternative::TwoSided, BrunnerMunzelDistribution::T).unwrap();
569        let b = brunnermunzel(&y, &x, Alternative::TwoSided, BrunnerMunzelDistribution::T).unwrap();
570        assert!((a.statistic + b.statistic).abs() < 1e-14 && (a.p_value - b.p_value).abs() < 1e-14);
571        assert!(a.statistic > 0.0 && a.p_value < 0.05);
572        // A Monte Carlo test of the mean of normal data: an extreme mean gets the smallest p.
573        let mut rng = Xoshiro256PlusPlus::from_seed(9);
574        let normal = |_: usize, n: usize, r: &mut Xoshiro256PlusPlus| (0..n).map(|_| crate::multivariate::standard_normal(r)).collect::<Vec<f64>>();
575        let mean = |d: &[Vec<f64>]| d[0].iter().sum::<f64>() / d[0].len() as f64;
576        let far = monte_carlo_test(&[vec![3.0; 10]], normal, mean, Alternative::Greater, 499, &mut rng).unwrap();
577        assert!((far.p_value - 1.0 / 500.0).abs() < 1e-15);
578        let near = monte_carlo_test(&[vec![0.0; 10]], normal, mean, Alternative::TwoSided, 999, &mut rng).unwrap();
579        assert!(near.p_value > 0.5 && near.null_distribution.len() == 999);
580    }
581}