Skip to main content

lib_jsl_statistics/
posthoc.rs

1//! The studentized range distribution and Tukey's honestly significant difference test (SciPy's
2//! `studentized_range` and `tukey_hsd`).
3//!
4//! See the book entry [Multivariate distributions and further tests](https://jwkunz.github.io/lib_jsl/book/statistics/multivariate-tests.html#tukeys-honestly-significant-difference).
5
6use crate::distributions::ContinuousDistribution;
7use lib_jsl_core::ErrorsJSL;
8use lib_jsl_special_functions::gamma::ln_gamma;
9use lib_jsl_special_functions::error_function::erfc;
10
11/// The standard normal density.
12fn normal_pdf(z: f64) -> f64 {
13    (-0.5 * z * z).exp() / (2.0 * std::f64::consts::PI).sqrt()
14}
15
16/// The standard normal distribution function, `½ erfc(−z/√2)`, accurate in both tails.
17fn normal_cdf(z: f64) -> f64 {
18    0.5 * erfc(-z / std::f64::consts::SQRT_2)
19}
20
21/// 16-point Gauss-Legendre nodes and weights on [−1, 1] (positive half).
22const GL_X: [f64; 8] = [
23    0.095_012_509_837_637_44,
24    0.281_603_550_779_258_9,
25    0.458_016_777_657_227_4,
26    0.617_876_244_402_643_7,
27    0.755_404_408_355_003,
28    0.865_631_202_387_831_8,
29    0.944_575_023_073_232_6,
30    0.989_400_934_991_649_9,
31];
32const GL_W: [f64; 8] = [
33    0.189_450_610_455_068_5,
34    0.182_603_415_044_923_6,
35    0.169_156_519_395_002_5,
36    0.149_595_988_816_576_7,
37    0.124_628_971_255_533_9,
38    0.095_158_511_682_492_78,
39    0.062_253_523_938_647_89,
40    0.027_152_459_411_754_09,
41];
42
43/// `∫_a^b f` by the 16-point Gauss-Legendre rule on `panels` equal panels.
44fn integrate(f: &dyn Fn(f64) -> f64, a: f64, b: f64, panels: usize) -> f64 {
45    let h = (b - a) / panels as f64;
46    let mut total = 0.0;
47    for p in 0..panels {
48        let (c, r) = (a + (p as f64 + 0.5) * h, 0.5 * h);
49        for (x, w) in GL_X.iter().zip(&GL_W) {
50            total += w * (f(c - r * x) + f(c + r * x));
51        }
52    }
53    total * 0.5 * h
54}
55
56// ANCHOR: studentized_range
57/// The distribution of `Q = (max − min)/S` for `k` independent standard normal deviates and an
58/// independent `S = √(χ²_ν / ν)` (SciPy's `studentized_range(k, df)`):
59/// `F(q) = ∫₀^∞ f_S(s) W(qs) ds`, with the distribution of the range
60/// `W(w) = k ∫ φ(z) (Φ(z) − Φ(z − w))^{k−1} dz` and
61/// `f_S(s) = ν^{ν/2} s^{ν−1} e^{−νs²/2} / (Γ(ν/2) 2^{ν/2−1})`. Both integrals are evaluated by
62/// composite Gauss-Legendre quadrature (the inner over `|z| ≤ 8.5`, the outer over the part of
63/// `s` holding all but 10⁻¹⁷ of its mass); `df = ∞` gives the range of standard normals itself.
64#[derive(Clone, Copy, Debug, PartialEq)]
65pub struct StudentizedRange {
66    pub k: f64,
67    pub df: f64,
68}
69
70impl StudentizedRange {
71    pub fn new(k: f64, df: f64) -> Result<Self, ErrorsJSL> {
72        if !(k > 1.0) || !(df > 0.0) {
73            return Err(ErrorsJSL::InvalidInputRange("need k > 1 and df > 0"));
74        }
75        Ok(StudentizedRange { k, df })
76    }
77
78    /// `P(range of k standard normals ≤ w)`.
79    fn range_cdf(&self, w: f64) -> f64 {
80        if w <= 0.0 {
81            return 0.0;
82        }
83        let k = self.k;
84        let f = |z: f64| normal_pdf(z) * (normal_cdf(z) - normal_cdf(z - w)).max(0.0).powf(k - 1.0);
85        (k * integrate(&f, -8.5, 8.5, 12)).min(1.0)
86    }
87
88    /// The density of the range, `k(k−1) ∫ φ(z) φ(z − w) (Φ(z) − Φ(z − w))^{k−2} dz`.
89    fn range_pdf(&self, w: f64) -> f64 {
90        if w <= 0.0 {
91            return 0.0;
92        }
93        let k = self.k;
94        let f = |z: f64| normal_pdf(z) * normal_pdf(z - w) * (normal_cdf(z) - normal_cdf(z - w)).max(0.0).powf(k - 2.0);
95        k * (k - 1.0) * integrate(&f, -8.5, 8.5 + w, 12 + w as usize)
96    }
97
98    /// The integration range of `s` and the log of `f_S`'s normalising constant.
99    fn scale_range(&self) -> (f64, f64, f64) {
100        let nu = self.df;
101        let log_c = 0.5 * nu * nu.ln() - ln_gamma(0.5 * nu) - (0.5 * nu - 1.0) * 2f64.ln();
102        let hi = ((nu + 12.0 * (2.0 * nu).sqrt() + 45.0) / nu).sqrt();
103        let lo = if nu > 50.0 { (1.0 - 12.0 / (2.0 * nu).sqrt()).max(0.0) } else { 0.0 };
104        (lo, hi, log_c)
105    }
106
107    fn mix(&self, inner: &dyn Fn(f64) -> f64, weight_s: bool) -> f64 {
108        let (lo, hi, log_c) = self.scale_range();
109        let nu = self.df;
110        let f = |s: f64| {
111            if s <= 0.0 {
112                return 0.0;
113            }
114            let dens = (log_c + (nu - 1.0) * s.ln() - 0.5 * nu * s * s).exp();
115            dens * if weight_s { s } else { 1.0 } * inner(s)
116        };
117        integrate(&f, lo, hi, 24)
118    }
119}
120
121impl ContinuousDistribution for StudentizedRange {
122    fn pdf(&self, q: f64) -> f64 {
123        if q <= 0.0 {
124            return 0.0;
125        }
126        if self.df.is_infinite() {
127            return self.range_pdf(q);
128        }
129        self.mix(&|s| self.range_pdf(q * s), true)
130    }
131    fn cdf(&self, q: f64) -> f64 {
132        if q <= 0.0 {
133            return 0.0;
134        }
135        if self.df.is_infinite() {
136            return self.range_cdf(q);
137        }
138        self.mix(&|s| self.range_cdf(q * s), false).clamp(0.0, 1.0)
139    }
140    /// By bisection on the distribution function (the default would need the moments, which are
141    /// themselves integrals).
142    fn ppf(&self, p: f64) -> f64 {
143        if !(0.0..=1.0).contains(&p) {
144            return f64::NAN;
145        }
146        if p == 0.0 {
147            return 0.0;
148        }
149        if p == 1.0 {
150            return f64::INFINITY;
151        }
152        // Bracket, then regula falsi with the Illinois modification (superlinear, and safe).
153        let (mut lo, mut hi) = (0.0, 4.0);
154        let mut fhi = self.cdf(hi) - p;
155        while fhi < 0.0 {
156            lo = hi;
157            hi *= 2.0;
158            fhi = self.cdf(hi) - p;
159        }
160        let mut flo = self.cdf(lo) - p;
161        let mut side = 0;
162        for _ in 0..100 {
163            let x = (lo * fhi - hi * flo) / (fhi - flo);
164            let fx = self.cdf(x) - p;
165            if fx == 0.0 || (hi - lo).abs() <= 1e-13 * hi {
166                return x;
167            }
168            if (fx < 0.0) == (flo < 0.0) {
169                lo = x;
170                flo = fx;
171                if side == -1 {
172                    fhi *= 0.5;
173                }
174                side = -1;
175            } else {
176                hi = x;
177                fhi = fx;
178                if side == 1 {
179                    flo *= 0.5;
180                }
181                side = 1;
182            }
183            if (hi - lo).abs() <= 1e-13 * hi.abs() {
184                break;
185            }
186        }
187        (lo * fhi - hi * flo) / (fhi - flo)
188    }
189    fn support(&self) -> (f64, f64) {
190        (0.0, f64::INFINITY)
191    }
192    /// `∫ sf`, numerically.
193    fn mean(&self) -> f64 {
194        self.raw_moment(1)
195    }
196    fn variance(&self) -> f64 {
197        let m1 = self.raw_moment(1);
198        self.raw_moment(2) - m1 * m1
199    }
200    fn skewness(&self) -> f64 {
201        let (m1, m2, m3) = (self.raw_moment(1), self.raw_moment(2), self.raw_moment(3));
202        let v = m2 - m1 * m1;
203        (m3 - 3.0 * m1 * m2 + 2.0 * m1.powi(3)) / v.powf(1.5)
204    }
205    fn excess_kurtosis(&self) -> f64 {
206        let (m1, m2, m3, m4) = (self.raw_moment(1), self.raw_moment(2), self.raw_moment(3), self.raw_moment(4));
207        let v = m2 - m1 * m1;
208        (m4 - 4.0 * m1 * m3 + 6.0 * m1 * m1 * m2 - 3.0 * m1.powi(4)) / (v * v) - 3.0
209    }
210}
211
212impl StudentizedRange {
213    /// `E[Qʲ] = ∫₀^∞ j q^{j−1} P(Q > q) dq` (infinite when `j ≥ df`).
214    fn raw_moment(&self, j: i32) -> f64 {
215        if self.df <= j as f64 {
216            return f64::INFINITY;
217        }
218        let upper = self.ppf(1.0 - 1e-12) * 1.5;
219        let f = |q: f64| j as f64 * q.powi(j - 1) * (1.0 - self.cdf(q));
220        integrate(&f, 0.0, upper, 24)
221    }
222}
223// ANCHOR_END: studentized_range
224
225/// Lower and upper limits, as `k × k` matrices.
226pub type IntervalMatrices = (Vec<Vec<f64>>, Vec<Vec<f64>>);
227
228/// The result of [`tukey_hsd`]: entry `(i, j)` compares treatment `i` with treatment `j`.
229#[derive(Clone, Debug)]
230#[non_exhaustive]
231pub struct TukeyHsdResult {
232    /// The differences of the means, `x̄_i − x̄_j`.
233    pub statistic: Vec<Vec<f64>>,
234    pub p_values: Vec<Vec<f64>>,
235    /// The standard errors of the differences (divided by √2, as SciPy).
236    pub std_err: Vec<Vec<f64>>,
237    /// The degrees of freedom of each comparison.
238    pub df: Vec<Vec<f64>>,
239    pub ntreatments: usize,
240}
241
242impl TukeyHsdResult {
243    /// Simultaneous confidence intervals `x̄_i − x̄_j ± q_{1−α}(k, ν) · se_ij`, as matrices of lower
244    /// and upper limits.
245    pub fn confidence_interval(&self, confidence_level: f64) -> Result<IntervalMatrices, ErrorsJSL> {
246        if !(confidence_level > 0.0 && confidence_level < 1.0) {
247            return Err(ErrorsJSL::InvalidInputRange("the confidence level must lie in (0, 1)"));
248        }
249        let k = self.ntreatments;
250        let mut lo = vec![vec![0.0; k]; k];
251        let mut hi = vec![vec![0.0; k]; k];
252        let mut cache: Vec<(f64, f64)> = Vec::new();
253        for i in 0..k {
254            for j in 0..k {
255                let df = self.df[i][j];
256                let q = match cache.iter().find(|c| c.0 == df) {
257                    Some(c) => c.1,
258                    None => {
259                        let q = StudentizedRange::new(k as f64, df)?.ppf(confidence_level);
260                        cache.push((df, q));
261                        q
262                    }
263                };
264                let r = q * self.std_err[i][j];
265                lo[i][j] = self.statistic[i][j] - r;
266                hi[i][j] = self.statistic[i][j] + r;
267            }
268        }
269        Ok((lo, hi))
270    }
271}
272
273// ANCHOR: tukey_hsd
274/// Tukey's honestly significant difference test of all pairwise differences of means (SciPy's
275/// `tukey_hsd`): `|x̄_i − x̄_j| / se_ij` against the studentized range with `k` treatments, where
276/// `se_ij = √(MSE (1/n_i + 1/n_j) / 2)` with the pooled variance and `N − k` degrees of freedom
277/// (the Tukey-Kramer form), or, with `equal_var = false`, the Games-Howell form
278/// `se_ij = √((s_i²/n_i + s_j²/n_j)/2)` with Welch's degrees of freedom.
279pub fn tukey_hsd(groups: &[Vec<f64>], equal_var: bool) -> Result<TukeyHsdResult, ErrorsJSL> {
280    let k = groups.len();
281    if k < 2 || groups.iter().any(|g| g.len() < 2 || g.iter().any(|v| !v.is_finite())) {
282        return Err(ErrorsJSL::InvalidInputRange("tukey_hsd: need at least two groups of at least two finite values"));
283    }
284    let n: Vec<f64> = groups.iter().map(|g| g.len() as f64).collect();
285    let means: Vec<f64> = groups.iter().map(|g| g.iter().sum::<f64>() / g.len() as f64).collect();
286    let vars: Vec<f64> = groups.iter().zip(&means).map(|(g, m)| g.iter().map(|v| (v - m).powi(2)).sum::<f64>() / (g.len() - 1) as f64).collect();
287    let nobs: f64 = n.iter().sum();
288    let mut std_err = vec![vec![0.0; k]; k];
289    let mut df = vec![vec![0.0; k]; k];
290    if equal_var {
291        let mse = vars.iter().zip(&n).map(|(v, ni)| v * (ni - 1.0)).sum::<f64>() / (nobs - k as f64);
292        for i in 0..k {
293            for j in 0..k {
294                std_err[i][j] = ((1.0 / n[i] + 1.0 / n[j]) * mse / 2.0).sqrt();
295                df[i][j] = nobs - k as f64;
296            }
297        }
298    } else {
299        for i in 0..k {
300            for j in 0..k {
301                let (a, b) = (vars[i] / n[i], vars[j] / n[j]);
302                std_err[i][j] = (a + b).sqrt() / 2f64.sqrt();
303                df[i][j] = (a + b).powi(2) / (a * a / (n[i] - 1.0) + b * b / (n[j] - 1.0));
304            }
305        }
306    }
307    let statistic: Vec<Vec<f64>> = (0..k).map(|i| (0..k).map(|j| means[i] - means[j]).collect()).collect();
308    let mut p_values = vec![vec![1.0; k]; k];
309    for i in 0..k {
310        for j in i + 1..k {
311            let t = statistic[i][j].abs() / std_err[i][j];
312            let p = 1.0 - StudentizedRange::new(k as f64, df[i][j])?.cdf(t);
313            p_values[i][j] = p;
314            p_values[j][i] = p;
315        }
316    }
317    Ok(TukeyHsdResult { statistic, p_values, std_err, df, ntreatments: k })
318}
319// ANCHOR_END: tukey_hsd
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    #[test]
326    fn studentized_range_and_tukey() {
327        // k = 2, ν = ∞: the range of two standard normals is |Z₁ − Z₂| ~ √2 |Z|.
328        let d = StudentizedRange::new(2.0, f64::INFINITY).unwrap();
329        for q in [0.5, 1.7, 3.0] {
330            let want = 2.0 * normal_cdf(q / std::f64::consts::SQRT_2) - 1.0;
331            assert!((d.cdf(q) - want).abs() < 1e-13, "{q}");
332        }
333        let d = StudentizedRange::new(4.0, 12.0).unwrap();
334        let q = d.ppf(0.95);
335        assert!((d.cdf(q) - 0.95).abs() < 1e-12);
336        // Tables give q(0.95; 4, 12) = 4.199.
337        assert!((q - 4.199).abs() < 1e-3, "{q}");
338        let groups = vec![vec![1.0, 2.0, 1.5, 1.8], vec![1.1, 2.1, 1.6, 1.7], vec![5.0, 5.5, 4.8, 5.2]];
339        let r = tukey_hsd(&groups, true).unwrap();
340        assert!(r.p_values[0][1] > 0.5 && r.p_values[0][2] < 1e-5 && r.p_values[2][0] == r.p_values[0][2]);
341        let (lo, hi) = r.confidence_interval(0.95).unwrap();
342        assert!(lo[0][1] < 0.0 && hi[0][1] > 0.0 && hi[0][2] < 0.0);
343    }
344}