Skip to main content

lib_jsl_statistics/
mvn_cdf.rs

1//! Distribution functions of the multivariate normal and t distributions by Genz's
2//! quasi-Monte Carlo method (SciPy's `multivariate_normal.cdf` and `multivariate_t.cdf`), the
3//! exact bivariate normal distribution function (Drezner and Wesolowsky, as Genz's `bvnu`), and
4//! Dunnett's many-to-one comparisons (SciPy's `dunnett`).
5//!
6//! See the book entry [Multivariate distribution functions and quasi-Monte Carlo sampling](https://jwkunz.github.io/lib_jsl/book/statistics/mvn-cdf.html).
7
8// Lattice and Cholesky kernels read best as index loops.
9#![allow(clippy::needless_range_loop)]
10
11use crate::multivariate::{MultivariateNormal, MultivariateT};
12use lib_jsl_core::ErrorsJSL;
13use lib_jsl_random::uniform_generator::UniformGenerator;
14use lib_jsl_special_functions::{gammaincinv, normal_cdf, normal_quantile};
15use std::f64::consts::PI;
16
17fn phi(x: f64) -> f64 {
18    if x == f64::INFINITY {
19        1.0
20    } else if x == f64::NEG_INFINITY {
21        0.0
22    } else {
23        normal_cdf(x, 0.0, 1.0)
24    }
25}
26
27fn phinv(p: f64) -> f64 {
28    normal_quantile(p.clamp(1e-300, 1.0 - f64::EPSILON / 2.0), 0.0, 1.0)
29}
30
31// ------------------------------------------------------------------------- bivariate normal
32
33/// Gauss-Legendre nodes and weights on `[−1, 1]` (Newton's method on `P_n`).
34fn gauss_legendre(n: usize) -> (Vec<f64>, Vec<f64>) {
35    let mut x = vec![0.0; n];
36    let mut w = vec![0.0; n];
37    for i in 0..n.div_ceil(2) {
38        let mut z = (PI * (i as f64 + 0.75) / (n as f64 + 0.5)).cos();
39        for _ in 0..100 {
40            let (mut p0, mut p1) = (1.0, z);
41            for k in 2..=n {
42                let p2 = ((2 * k - 1) as f64 * z * p1 - (k - 1) as f64 * p0) / k as f64;
43                p0 = p1;
44                p1 = p2;
45            }
46            let dp = n as f64 * (z * p1 - p0) / (z * z - 1.0);
47            let dz = p1 / dp;
48            z -= dz;
49            if dz.abs() < 1e-16 {
50                let (mut q0, mut q1) = (1.0, z);
51                for k in 2..=n {
52                    let q2 = ((2 * k - 1) as f64 * z * q1 - (k - 1) as f64 * q0) / k as f64;
53                    q0 = q1;
54                    q1 = q2;
55                }
56                let dq = n as f64 * (z * q1 - q0) / (z * z - 1.0);
57                x[i] = z;
58                x[n - 1 - i] = -z;
59                w[i] = 2.0 / ((1.0 - z * z) * dq * dq);
60                w[n - 1 - i] = w[i];
61                break;
62            }
63        }
64    }
65    (x, w)
66}
67
68// ANCHOR: bvnu
69/// `P(X > h, Y > k)` for standard bivariate normal `(X, Y)` with correlation `r` (Genz's `bvnu`,
70/// after Drezner and Wesolowsky): for `|r| < 0.925` Plackett's integral over the correlation,
71/// `∫₀^{asin r} exp(−(h² + k² − 2hk sin θ)/(2 cos²θ)) dθ / 2π + Φ(−h)Φ(−k)`, by 6-, 12- or
72/// 20-point Gauss-Legendre rules; near `|r| = 1` an asymptotic expansion plus a correction
73/// integral. Accurate to about 10⁻¹⁵.
74pub fn bivariate_normal_upper(h: f64, k: f64, r: f64) -> f64 {
75    if h == f64::INFINITY || k == f64::INFINITY {
76        return 0.0;
77    }
78    if h == f64::NEG_INFINITY {
79        return if k == f64::NEG_INFINITY { 1.0 } else { phi(-k) };
80    }
81    if k == f64::NEG_INFINITY {
82        return phi(-h);
83    }
84    if r == 0.0 {
85        return phi(-h) * phi(-k);
86    }
87    let tp = 2.0 * PI;
88    let n = if r.abs() < 0.3 {
89        6
90    } else if r.abs() < 0.75 {
91        12
92    } else {
93        20
94    };
95    let (xs, ws) = gauss_legendre(n);
96    let (x, w): (Vec<f64>, Vec<f64>) = xs.iter().zip(&ws).filter(|(x, _)| **x < 0.0).map(|(a, b)| (*a, *b)).unzip();
97    let mut k = k;
98    let mut hk = h * k;
99    let mut bvn = 0.0;
100    if r.abs() < 0.925 {
101        let hs = (h * h + k * k) / 2.0;
102        let asr = r.asin();
103        for i in 0..x.len() {
104            let sn = (asr * (1.0 + x[i]) / 2.0).sin();
105            bvn += w[i] * ((sn * hk - hs) / (1.0 - sn * sn)).exp();
106            let sn = (asr * (1.0 - x[i]) / 2.0).sin();
107            bvn += w[i] * ((sn * hk - hs) / (1.0 - sn * sn)).exp();
108        }
109        return bvn * asr / (2.0 * tp) + phi(-h) * phi(-k);
110    }
111    if r < 0.0 {
112        k = -k;
113        hk = -hk;
114    }
115    if r.abs() < 1.0 {
116        let as_ = (1.0 - r) * (1.0 + r);
117        let mut a = as_.sqrt();
118        let bs = (h - k) * (h - k);
119        let c = (4.0 - hk) / 8.0;
120        let d = (12.0 - hk) / 16.0;
121        bvn = a * (-(bs / as_ + hk) / 2.0).exp() * (1.0 - c * (bs - as_) * (1.0 - d * bs / 5.0) / 3.0 + c * d * as_ * as_ / 5.0);
122        if hk > -160.0 {
123            let b = bs.sqrt();
124            bvn -= (-hk / 2.0).exp() * tp.sqrt() * phi(-b / a) * b * (1.0 - c * bs * (1.0 - d * bs / 5.0) / 3.0);
125        }
126        a /= 2.0;
127        for i in 0..x.len() {
128            for sgn in [-1.0, 1.0] {
129                let xs = (a * (sgn * x[i] + 1.0)).powi(2);
130                let rs = (1.0 - xs).sqrt();
131                bvn += a * w[i] * ((-bs / (2.0 * xs) - hk / (1.0 + rs)).exp() / rs - (-(bs / xs + hk) / 2.0).exp() * (1.0 + c * xs * (1.0 + d * xs)));
132            }
133        }
134        bvn = -bvn / tp;
135    }
136    if r > 0.0 {
137        bvn += phi(-h.max(k));
138    } else {
139        bvn = -bvn;
140        if k > h {
141            if h < 0.0 {
142                bvn += phi(k) - phi(h);
143            } else {
144                bvn += phi(-h) - phi(-k);
145            }
146        }
147    }
148    bvn.clamp(0.0, 1.0)
149}
150// ANCHOR_END: bvnu
151
152/// `P(a < X < b)` for a bivariate normal with covariance `cov` (SciPy's `_bvn`).
153fn bivariate_rectangle(a: &[f64], b: &[f64], cov: &[Vec<f64>]) -> f64 {
154    let (s1, s2) = (cov[0][0].sqrt(), cov[1][1].sqrt());
155    let r = cov[0][1] / (s1 * s2);
156    let (xl, xu, yl, yu) = (a[0] / s1, b[0] / s1, a[1] / s2, b[1] / s2);
157    let p = bivariate_normal_upper(xl, yl, r) - bivariate_normal_upper(xu, yl, r) - bivariate_normal_upper(xl, yu, r) + bivariate_normal_upper(xu, yu, r);
158    p.clamp(0.0, 1.0)
159}
160
161// ------------------------------------------------------------------- Genz's QMC integration
162
163fn primes_up_to(n: usize) -> Vec<usize> {
164    if n < 2 {
165        return Vec::new();
166    }
167    let mut sieve = vec![true; n + 1];
168    sieve[0] = false;
169    sieve[1] = false;
170    let mut i = 2;
171    while i * i <= n {
172        if sieve[i] {
173            for j in (i * i..=n).step_by(i) {
174                sieve[j] = false;
175            }
176        }
177        i += 1;
178    }
179    (0..=n).filter(|&k| sieve[k]).collect()
180}
181
182fn primitive_root(p: usize) -> usize {
183    let pm = p - 1;
184    let mut factors = Vec::new();
185    let mut m = pm;
186    let mut f = 2;
187    while f * f <= m {
188        if m.is_multiple_of(f) {
189            factors.push(f);
190            while m.is_multiple_of(f) {
191                m /= f;
192            }
193        }
194        f += 1;
195    }
196    if m > 1 {
197        factors.push(m);
198    }
199    let powmod = |mut b: u128, mut e: u128, md: u128| {
200        let mut r = 1u128;
201        b %= md;
202        while e > 0 {
203            if e & 1 == 1 {
204                r = r * b % md;
205            }
206            b = b * b % md;
207            e >>= 1;
208        }
209        r
210    };
211    (2..p).find(|&g| factors.iter().all(|&q| powmod(g as u128, (pm / q) as u128, p as u128) != 1)).unwrap_or(1)
212}
213
214/// A rank-1 lattice generating vector by Nuyens and Cools's fast component-by-component
215/// construction (SciPy's `_cbc_lattice`), for the largest prime number of points `≤ n`.
216fn cbc_lattice(n_dim: usize, n_qmc: usize) -> (Vec<f64>, usize) {
217    let p = *primes_up_to(n_qmc.max(2)).last().expect("a prime ≥ 2");
218    let mut z = vec![1usize; n_dim.max(1)];
219    if p < 5 || n_dim <= 1 {
220        return (z.iter().map(|&v| v as f64 / p as f64).collect(), p);
221    }
222    let m = (p - 1) / 2;
223    let g = primitive_root(p);
224    let mut perm = vec![1usize; m];
225    for j in 0..m - 1 {
226        perm[j + 1] = g * perm[j] % p;
227    }
228    let perm: Vec<usize> = perm.into_iter().map(|v| v.min(p - v)).collect();
229    let c: Vec<f64> = perm.iter().map(|&v| {
230        let pn = v as f64 / p as f64;
231        pn * pn - pn + 1.0 / 6.0
232    }).collect();
233    let mut q = vec![1.0f64; m];
234    let mut w = 0usize;
235    // Circular convolutions by FFTs of length m (SciPy's ifft(fft(c) · fft(q))).
236    use lib_jsl_ffts::{BestFft, FftDirection, FftEngine1D, FftOrdering, FftScaleFactor};
237    use num_complex::Complex;
238    let mut fwd = BestFft::new();
239    let mut inv = BestFft::new();
240    let planned = fwd.plan(m, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).is_ok() && inv.plan(m, FftScaleFactor::N, FftDirection::Inverse, FftOrdering::Standard).is_ok();
241    let fc: Vec<Complex<f64>> = if planned { fwd.execute(&c.iter().map(|&v| Complex::new(v, 0.0)).collect::<Vec<_>>()).unwrap_or_default() } else { Vec::new() };
242    for s in 1..n_dim {
243        // reordered = [c[..=w] reversed, c[w+1..] reversed]
244        let mut reordered: Vec<f64> = c[..=w].iter().rev().copied().collect();
245        reordered.extend(c[w + 1..].iter().rev());
246        let gm = if s == 1 { 1.0 } else { 0.8f64.powi(s as i32 - 2) };
247        for i in 0..m {
248            q[i] *= 1.0 + gm * reordered[i];
249        }
250        let conv: Vec<f64> = if planned && fc.len() == m {
251            let fq = fwd.execute(&q.iter().map(|&v| Complex::new(v, 0.0)).collect::<Vec<_>>()).expect("planned");
252            let prod: Vec<Complex<f64>> = fc.iter().zip(&fq).map(|(a, b)| a * b).collect();
253            inv.execute(&prod).expect("planned").iter().map(|v| v.re).collect()
254        } else {
255            (0..m).map(|t| (0..m).map(|i| c[i] * q[(t + m - i) % m]).sum()).collect()
256        };
257        w = conv.iter().enumerate().fold((f64::INFINITY, 0usize), |b, (t, &v)| if v < b.0 { (v, t) } else { b }).1;
258        z[s] = perm[w];
259    }
260    (z.iter().map(|&v| v as f64 / p as f64).collect(), p)
261}
262
263/// SciPy's `_permuted_cholesky`: Genz's variable reordering (the most constrained variable
264/// first) with the Cholesky factor of the correlation-scaled covariance, tolerating positive
265/// semidefinite matrices.
266fn permuted_cholesky(cov: &[Vec<f64>], low: &[f64], high: &[f64]) -> (Vec<Vec<f64>>, Vec<f64>, Vec<f64>) {
267    let n = cov.len();
268    let tol = 1e-10;
269    let dc: Vec<f64> = (0..n).map(|i| { let v = cov[i][i].max(0.0).sqrt(); if v == 0.0 { 1.0 } else { v } }).collect();
270    let mut lo: Vec<f64> = (0..n).map(|i| low[i] / dc[i]).collect();
271    let mut hi: Vec<f64> = (0..n).map(|i| high[i] / dc[i]).collect();
272    let mut cho: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|j| cov[i][j] / dc[i] / dc[j]).collect()).collect();
273    let mut y = vec![0.0; n];
274    let sqtp = (2.0 * PI).sqrt();
275    for k in 0..n {
276        let epk = (k + 1) as f64 * tol;
277        let (mut im, mut ck, mut dem, mut lo_m, mut hi_m) = (k, 0.0, 1.0, 0.0, 0.0);
278        for i in k..n {
279            if cho[i][i] > tol {
280                let ci = cho[i][i].sqrt();
281                let s: f64 = if i > 0 { (0..k).map(|t| cho[i][t] * y[t]).sum() } else { 0.0 };
282                let lo_i = (lo[i] - s) / ci;
283                let hi_i = (hi[i] - s) / ci;
284                let de = phi(hi_i) - phi(lo_i);
285                if de <= dem {
286                    ck = ci;
287                    dem = de;
288                    lo_m = lo_i;
289                    hi_m = hi_i;
290                    im = i;
291                }
292            }
293        }
294        if im > k {
295            cho[im][im] = cho[k][k];
296            for t in 0..k {
297                let tmp = cho[im][t];
298                cho[im][t] = cho[k][t];
299                cho[k][t] = tmp;
300            }
301            for row in cho.iter_mut().take(n).skip(im + 1) {
302                row.swap(im, k);
303            }
304            for t in k + 1..im {
305                let tmp = cho[t][k];
306                cho[t][k] = cho[im][t];
307                cho[im][t] = tmp;
308            }
309            lo.swap(k, im);
310            hi.swap(k, im);
311        }
312        if ck > epk {
313            cho[k][k] = ck;
314            for t in k + 1..n {
315                cho[k][t] = 0.0;
316            }
317            for i in k + 1..n {
318                cho[i][k] /= ck;
319                for t in k + 1..=i {
320                    cho[i][t] -= cho[i][k] * cho[t][k];
321                }
322            }
323            if dem.abs() > tol {
324                y[k] = ((-lo_m * lo_m / 2.0).exp() - (-hi_m * hi_m / 2.0).exp()) / (sqtp * dem);
325            } else {
326                y[k] = (lo_m + hi_m) / 2.0;
327                if lo_m < -10.0 {
328                    y[k] = hi_m;
329                } else if hi_m > 10.0 {
330                    y[k] = lo_m;
331                }
332            }
333            for t in 0..=k {
334                cho[k][t] /= ck;
335            }
336            lo[k] /= ck;
337            hi[k] /= ck;
338        } else {
339            for t in k..n {
340                cho[t][k] = 0.0;
341            }
342            y[k] = (lo[k] + hi[k]) / 2.0;
343        }
344    }
345    (cho, lo, hi)
346}
347
348/// One randomised-lattice estimate: Genz's separation-of-variables integrand averaged over
349/// `n_batches` random shifts of the lattice, with the tent periodisation. `chi` adds a leading
350/// χ-variable for the t distribution with `ν` degrees of freedom.
351fn qmc_estimate<U: UniformGenerator>(m: usize, cov: &[Vec<f64>], low: &[f64], high: &[f64], nu: Option<f64>, rng: &mut U) -> (f64, f64, usize) {
352    let n_batches = 10;
353    let n = cov.len();
354    let sn = nu.map_or(1.0, |v| v.sqrt().max(1.0));
355    let (lo_s, hi_s): (Vec<f64>, Vec<f64>) = (low.iter().map(|v| v / sn).collect(), high.iter().map(|v| v / sn).collect());
356    let (cho, lo, hi) = permuted_cholesky(cov, &lo_s, &hi_s);
357    let qdim = if nu.is_some() { n } else { n - 1 };
358    let (q, nq) = cbc_lattice(qdim.max(1), (m / n_batches).max(1));
359    let (mut prob, mut err_var) = (0.0, 0.0);
360    let mut y = vec![0.0; n];
361    for j in 0..n_batches {
362        // SciPy draws one row of `n` numbers per batch (`rng.random(size=(n_batches, n))`). The normal
363        // integrand uses columns 1 to n − 1 (column 0 is not used), the t integrand columns 0 to n − 1,
364        // so a seeded generator gives SciPy's shifts.
365        let drawn: Vec<f64> = (0..n).map(|_| rng.next_f64()).collect();
366        let shift = if nu.is_some() { &drawn[..] } else { &drawn[1..] };
367        let mut sum = 0.0;
368        for k in 0..nq {
369            let point = |d: usize| -> f64 {
370                let z = q[d] * (k + 1) as f64 + shift[d];
371                (2.0 * (z - z.floor()) - 1.0).abs()
372            };
373            // The scale of the limits: 1, or √(W/ν)·sn for the t distribution, W ~ χ²_ν.
374            let (scale, off) = match nu {
375                Some(v) => {
376                    let u = point(0).clamp(1e-300, 1.0 - 1e-16);
377                    let w = 2.0 * gammaincinv(v / 2.0, u);
378                    ((w / v).sqrt() * sn, 1)
379                }
380                None => (1.0, 0),
381            };
382            let ct = cho[0][0];
383            let mut c = phi(lo[0] * scale / ct);
384            let d0 = phi(hi[0] * scale / ct);
385            let mut dc = d0 - c;
386            let mut pv = dc;
387            for i in 1..n {
388                let x = point(i - 1 + off);
389                y[i - 1] = phinv(c + x * dc);
390                let s: f64 = (0..i).map(|t| cho[i][t] * y[t]).sum();
391                let ct = cho[i][i];
392                if ct == 0.0 {
393                    continue;
394                }
395                c = phi((lo[i] * scale - s) / ct);
396                let d = phi((hi[i] * scale - s) / ct);
397                dc = d - c;
398                pv *= dc;
399            }
400            sum += pv;
401        }
402        let mean = sum / nq as f64;
403        let d = (mean - prob) / (j + 1) as f64;
404        prob += d;
405        err_var = (j as f64 - 1.0) * err_var / (j + 1) as f64 + d * d;
406    }
407    (prob, 3.0 * err_var.sqrt(), nq * n_batches)
408}
409
410/// SciPy's `_qauto`: repeat the estimate with `√2` times more points until the error is below
411/// `abseps` or `maxpts` points are used, weighting the estimates by their errors.
412fn qauto<U: UniformGenerator>(cov: &[Vec<f64>], low: &[f64], high: &[f64], abseps: f64, maxpts: usize, rng: &mut U) -> (f64, f64) {
413    let n = cov.len();
414    if n == 1 {
415        let s = cov[0][0].sqrt();
416        return (phi(high[0] / s) - phi(low[0] / s), 1e-15);
417    }
418    if n == 2 {
419        return (bivariate_rectangle(low, high, cov), 1e-15);
420    }
421    let mut mi = maxpts.min(n * 1000) as f64;
422    let (mut prob, mut est_error, mut n_samples) = (0.0, 1.0, 0usize);
423    while est_error > abseps && n_samples < maxpts {
424        mi = (2f64.sqrt() * mi).round();
425        let (pi, ei, ni) = qmc_estimate(mi as usize, cov, low, high, None, rng);
426        n_samples += ni;
427        let wt = 1.0 / (1.0 + (ei / est_error).powi(2));
428        prob += wt * (pi - prob);
429        est_error = wt.sqrt() * ei;
430    }
431    (prob, est_error)
432}
433
434/// Options for the multivariate distribution functions (SciPy's defaults).
435#[derive(Clone, Copy, Debug)]
436pub struct MvCdfOptions {
437    /// The largest number of integrand evaluations; `None` for SciPy's `10⁶ d` (normal) or
438    /// `1000 d` (t).
439    pub maxpts: Option<usize>,
440    /// The target absolute error of the normal distribution function (SciPy's `abseps`).
441    pub abseps: f64,
442}
443
444impl Default for MvCdfOptions {
445    fn default() -> Self {
446        MvCdfOptions { maxpts: None, abseps: 1e-5 }
447    }
448}
449
450/// Swaps reversed limits and returns the sign of the result (as SciPy does).
451fn order_limits(lower: &[f64], upper: &[f64]) -> (Vec<f64>, Vec<f64>, f64) {
452    let (mut a, mut b) = (lower.to_vec(), upper.to_vec());
453    let mut sign = 1.0;
454    for i in 0..a.len() {
455        if b[i] < a[i] {
456            std::mem::swap(&mut a[i], &mut b[i]);
457            sign = -sign;
458        }
459    }
460    (a, b, sign)
461}
462
463// ANCHOR: mvn_cdf
464impl MultivariateNormal {
465    /// `P(lower < X ≤ upper)` (SciPy's `multivariate_normal.cdf(upper, lower_limit=lower)`;
466    /// `lower = None` for −∞), with the error estimate. One and two dimensions are exact; in
467    /// more, Genz's method: reorder the variables so the most constrained comes first, factor
468    /// `Σ = L Lᵀ`, and write the probability as an integral over the unit cube of a product of
469    /// one-dimensional normal probabilities whose limits depend on the earlier variables, then
470    /// integrate it with randomised rank-1 lattice rules until the error is below `abseps`.
471    pub fn cdf_between<U: UniformGenerator>(&self, lower: Option<&[f64]>, upper: &[f64], options: MvCdfOptions, rng: &mut U) -> Result<(f64, f64), ErrorsJSL> {
472        let d = self.dim();
473        if upper.len() != d || lower.is_some_and(|l| l.len() != d) {
474            return Err(ErrorsJSL::IncompatibleArraySizes((upper.len(), d)));
475        }
476        let low: Vec<f64> = match lower {
477            Some(l) => l.iter().zip(&self.mean).map(|(a, m)| a - m).collect(),
478            None => vec![f64::NEG_INFINITY; d],
479        };
480        let up: Vec<f64> = upper.iter().zip(&self.mean).map(|(a, m)| a - m).collect();
481        let (a, b, sign) = order_limits(&low, &up);
482        let (p, e) = qauto(&self.cov, &a, &b, options.abseps, options.maxpts.unwrap_or(1_000_000 * d), rng);
483        Ok((sign * p, e))
484    }
485
486    /// `P(X ≤ x)` (SciPy's `multivariate_normal.cdf`).
487    pub fn cdf<U: UniformGenerator>(&self, x: &[f64], rng: &mut U) -> Result<f64, ErrorsJSL> {
488        Ok(self.cdf_between(None, x, MvCdfOptions::default(), rng)?.0)
489    }
490}
491// ANCHOR_END: mvn_cdf
492
493impl MultivariateT {
494    /// `P(lower < X ≤ upper)` (SciPy's `multivariate_t.cdf`), by Genz's method with a leading
495    /// χ variable: `X = μ + Z/√(W/ν)`, so the probability is the normal one with limits scaled
496    /// by `√(W/ν)`, averaged over `W ~ χ²_ν` through its inverse distribution function. SciPy
497    /// uses one lattice estimate of `1000 d` points.
498    pub fn cdf_between<U: UniformGenerator>(&self, lower: Option<&[f64]>, upper: &[f64], options: MvCdfOptions, rng: &mut U) -> Result<(f64, f64), ErrorsJSL> {
499        let d = self.loc.len();
500        if upper.len() != d || lower.is_some_and(|l| l.len() != d) {
501            return Err(ErrorsJSL::IncompatibleArraySizes((upper.len(), d)));
502        }
503        let low: Vec<f64> = match lower {
504            Some(l) => l.iter().zip(&self.loc).map(|(a, m)| a - m).collect(),
505            None => vec![f64::NEG_INFINITY; d],
506        };
507        let up: Vec<f64> = upper.iter().zip(&self.loc).map(|(a, m)| a - m).collect();
508        let (a, b, sign) = order_limits(&low, &up);
509        let (p, e, _) = qmc_estimate(options.maxpts.unwrap_or(1000 * d), &self.shape, &a, &b, Some(self.df), rng);
510        Ok((sign * p, e))
511    }
512
513    /// `P(X ≤ x)` (SciPy's `multivariate_t.cdf`).
514    pub fn cdf<U: UniformGenerator>(&self, x: &[f64], rng: &mut U) -> Result<f64, ErrorsJSL> {
515        Ok(self.cdf_between(None, x, MvCdfOptions::default(), rng)?.0)
516    }
517}
518
519// ------------------------------------------------------------------------------------ Dunnett
520
521/// The result of [`dunnett`].
522#[derive(Clone, Debug)]
523#[non_exhaustive]
524pub struct DunnettResult {
525    /// The t statistic of each treatment against the control.
526    pub statistic: Vec<f64>,
527    /// The adjusted p-value of each comparison.
528    pub pvalue: Vec<f64>,
529    /// The pooled standard deviation and its degrees of freedom.
530    pub std: f64,
531    pub df: f64,
532}
533
534/// The alternative hypothesis of [`dunnett`].
535#[derive(Clone, Copy, Debug, PartialEq, Eq)]
536#[non_exhaustive]
537pub enum DunnettAlternative {
538    TwoSided,
539    /// The treatment means exceed the control's.
540    Greater,
541    Less,
542}
543
544// ANCHOR: dunnett
545/// Dunnett's test comparing each treatment group with a control (SciPy's `dunnett`):
546/// `tᵢ = (x̄ᵢ − x̄₀)/(s √(1/nᵢ + 1/n₀))` with the pooled standard deviation `s` on
547/// `N − k − 1` degrees of freedom. The statistics are jointly multivariate t with correlations
548/// `ρᵢⱼ = 1/√((1 + n₀/nᵢ)(1 + n₀/nⱼ))`, and each p-value is the probability that the largest
549/// (absolute) statistic exceeds `tᵢ`, from the multivariate t distribution function — so the
550/// p-values carry its quasi-Monte Carlo error (about 10⁻³ with SciPy's 1000 points per
551/// dimension).
552pub fn dunnett<U: UniformGenerator>(samples: &[&[f64]], control: &[f64], alternative: DunnettAlternative, rng: &mut U) -> Result<DunnettResult, ErrorsJSL> {
553    let k = samples.len();
554    if k == 0 || control.len() < 2 || samples.iter().any(|s| s.is_empty()) {
555        return Err(ErrorsJSL::InvalidInputRange("dunnett: need a control of two or more values and non-empty treatment groups"));
556    }
557    let n0 = control.len() as f64;
558    let ns: Vec<f64> = samples.iter().map(|s| s.len() as f64).collect();
559    let n_total = n0 + ns.iter().sum::<f64>();
560    let df = n_total - k as f64 - 1.0;
561    if df <= 0.0 {
562        return Err(ErrorsJSL::InvalidInputRange("dunnett: not enough observations for the degrees of freedom"));
563    }
564    let mean = |s: &[f64]| s.iter().sum::<f64>() / s.len() as f64;
565    let m0 = mean(control);
566    let ms: Vec<f64> = samples.iter().map(|s| mean(s)).collect();
567    let ss = |s: &[f64], m: f64| s.iter().map(|v| (v - m).powi(2)).sum::<f64>();
568    let s2 = (ss(control, m0) + samples.iter().zip(&ms).map(|(s, &m)| ss(s, m)).sum::<f64>()) / df;
569    let std = s2.sqrt();
570    let statistic: Vec<f64> = (0..k).map(|i| (ms[i] - m0) / (1.0 / ns[i] + 1.0 / n0).sqrt() / std).collect();
571    let r: Vec<f64> = ns.iter().map(|n| n0 / n + 1.0).collect();
572    let rho: Vec<Vec<f64>> = (0..k).map(|i| (0..k).map(|j| if i == j { 1.0 } else { 1.0 / (r[i] * r[j]).sqrt() }).collect()).collect();
573    let mvt = MultivariateT::new(vec![0.0; k], rho, df)?;
574    let opts = MvCdfOptions::default();
575    let mut pvalue = Vec::with_capacity(k);
576    for &t in &statistic {
577        let p = match alternative {
578            DunnettAlternative::TwoSided => {
579                let a = t.abs();
580                1.0 - mvt.cdf_between(Some(&vec![-a; k]), &vec![a; k], opts, rng)?.0
581            }
582            DunnettAlternative::Greater => 1.0 - mvt.cdf_between(None, &vec![t; k], opts, rng)?.0,
583            DunnettAlternative::Less => 1.0 - mvt.cdf_between(Some(&vec![t; k]), &vec![f64::INFINITY; k], opts, rng)?.0,
584        };
585        pvalue.push(p.clamp(0.0, 1.0));
586    }
587    Ok(DunnettResult { statistic, pvalue, std, df })
588}
589// ANCHOR_END: dunnett
590
591// ANCHOR: dunnett_ci
592/// Simultaneous confidence intervals for the differences of the treatment means and the control
593/// mean (SciPy's `DunnettResult.confidence_interval`): `x̄ᵢ − x̄₀ ± c s √(1/nᵢ + 1/n₀)` for the
594/// two-sided alternative, with `(−∞, … + …]` and `[… − …, ∞)` for the one-sided ones, where `c`
595/// is the critical value of Dunnett's test at the level `1 − confidence_level`: the `c` for which
596/// the probability that the largest (absolute) statistic exceeds it is `1 − confidence_level`.
597///
598/// `c` is found by bisection on that probability. The probability is a quasi-Monte Carlo
599/// estimate, noisy from one evaluation to the next, so every evaluation reuses one stream of random
600/// shifts (a seed drawn from `rng`), which makes it a smooth function of `c`. Returns, for each
601/// treatment, the interval `(low, high)`.
602pub fn dunnett_confidence_interval<U: UniformGenerator>(samples: &[&[f64]], control: &[f64], alternative: DunnettAlternative, confidence_level: f64, rng: &mut U) -> Result<Vec<(f64, f64)>, ErrorsJSL> {
603    if !(confidence_level > 0.0 && confidence_level < 1.0) {
604        return Err(ErrorsJSL::InvalidInputRange("dunnett: the confidence level must lie between 0 and 1"));
605    }
606    // The statistics, correlations and degrees of freedom come from the test itself.
607    let k = samples.len();
608    let result = dunnett(samples, control, alternative, rng)?;
609    let n0 = control.len() as f64;
610    let ns: Vec<f64> = samples.iter().map(|s| s.len() as f64).collect();
611    let r: Vec<f64> = ns.iter().map(|n| n0 / n + 1.0).collect();
612    let rho: Vec<Vec<f64>> = (0..k).map(|i| (0..k).map(|j| if i == j { 1.0 } else { 1.0 / (r[i] * r[j]).sqrt() }).collect()).collect();
613    let mvt = MultivariateT::new(vec![0.0; k], rho, result.df)?;
614    let seed = rng.next_u64();
615    let alpha = 1.0 - confidence_level;
616    let opts = MvCdfOptions::default();
617    // P(the largest statistic exceeds c), by symmetry the same for `Less` as for `Greater`.
618    let tail = |c: f64| -> Result<f64, ErrorsJSL> {
619        let mut fixed = lib_jsl_random::uniform_generator::UniformRNG::from_seed(seed);
620        let inside = match alternative {
621            DunnettAlternative::TwoSided => mvt.cdf_between(Some(&vec![-c; k]), &vec![c; k], opts, &mut fixed)?.0,
622            _ => mvt.cdf_between(None, &vec![c; k], opts, &mut fixed)?.0,
623        };
624        Ok(1.0 - inside)
625    };
626    // The tail decreases from 1 (or 1 − 2^-k) at c = 0: bracket the root, then bisect.
627    let (mut lo, mut hi) = (0.0f64, 1.0f64);
628    while tail(hi)? > alpha {
629        lo = hi;
630        hi *= 2.0;
631        if hi > 1e3 {
632            return Err(ErrorsJSL::RuntimeError("dunnett: no critical value found for this confidence level"));
633        }
634    }
635    for _ in 0..40 {
636        let mid = 0.5 * (lo + hi);
637        if tail(mid)? > alpha { lo = mid } else { hi = mid }
638    }
639    let critical = 0.5 * (lo + hi);
640    let mean = |s: &[f64]| s.iter().sum::<f64>() / s.len() as f64;
641    let m0 = mean(control);
642    Ok(samples
643        .iter()
644        .zip(&ns)
645        .map(|(s, &n)| {
646            let diff = mean(s) - m0;
647            let allowance = critical * result.std * (1.0 / n + 1.0 / n0).sqrt();
648            match alternative {
649                DunnettAlternative::TwoSided => (diff - allowance, diff + allowance),
650                DunnettAlternative::Greater => (diff - allowance, f64::INFINITY),
651                DunnettAlternative::Less => (f64::NEG_INFINITY, diff + allowance),
652            }
653        })
654        .collect())
655}
656// ANCHOR_END: dunnett_ci
657
658#[cfg(test)]
659mod tests {
660    use super::*;
661    use lib_jsl_random::uniform_generator::UniformRNG;
662
663    #[test]
664    fn bivariate_and_trivariate_against_known_values() {
665        // P(X > 0, Y > 0) = 1/4 + asin(r)/(2π).
666        for r in [-0.95f64, -0.5, 0.2, 0.8, 0.99] {
667            let want = 0.25 + r.asin() / (2.0 * PI);
668            assert!((bivariate_normal_upper(0.0, 0.0, r) - want).abs() < 1e-14, "{r}");
669        }
670        // An equicorrelated trivariate orthant: P(all < 0) = 1/8 + 3 asin(ρ)/(4π).
671        let rho = 0.5;
672        let cov = vec![vec![1.0, rho, rho], vec![rho, 1.0, rho], vec![rho, rho, 1.0]];
673        let mvn = MultivariateNormal::new(vec![0.0; 3], cov.clone()).unwrap();
674        let mut rng = UniformRNG::from_seed(7);
675        let (p, e) = mvn.cdf_between(None, &[0.0; 3], MvCdfOptions::default(), &mut rng).unwrap();
676        let want = 0.125 + 3.0 * rho.asin() / (4.0 * PI);
677        assert!((p - want).abs() < 2e-5 && e < 1e-4, "{p} vs {want} (±{e})");
678        // The t distribution's orthant probability is the same (elliptical symmetry).
679        let t = MultivariateT::new(vec![0.0; 3], cov, 5.0).unwrap();
680        let (pt, _) = t.cdf_between(None, &[0.0; 3], MvCdfOptions { maxpts: Some(100_000), ..Default::default() }, &mut rng).unwrap();
681        assert!((pt - want).abs() < 2e-4, "{pt}");
682    }
683
684    #[test]
685    fn dunnett_confidence_intervals_match_scipy_and_have_the_right_shape() {
686        let control = [7.40, 8.50, 7.20, 8.24, 9.84, 8.32];
687        let a = [9.76, 8.80, 7.68, 9.36];
688        let b = [12.80, 9.68, 12.16, 9.20, 10.55];
689        let mut rng = UniformRNG::from_seed(3);
690        // SciPy (rng = 1): two-sided 95 %: drug A (-1.2570545, 2.5570545), drug B (0.8390243, 4.4169757).
691        let ci = dunnett_confidence_interval(&[&a, &b], &control, DunnettAlternative::TwoSided, 0.95, &mut rng).unwrap();
692        for (got, want) in [ci[0].0, ci[0].1, ci[1].0, ci[1].1].iter().zip([-1.2570545, 2.5570545, 0.8390243, 4.4169757]) {
693            assert!((got - want).abs() < 6e-3, "{got} vs {want}");
694        }
695        let wide = dunnett_confidence_interval(&[&a, &b], &control, DunnettAlternative::TwoSided, 0.99, &mut rng).unwrap();
696        assert!(wide[0].0 < ci[0].0 && wide[0].1 > ci[0].1);
697        let up = dunnett_confidence_interval(&[&a, &b], &control, DunnettAlternative::Greater, 0.95, &mut rng).unwrap();
698        assert!(up[0].1 == f64::INFINITY && up[0].0.is_finite());
699        let down = dunnett_confidence_interval(&[&a, &b], &control, DunnettAlternative::Less, 0.95, &mut rng).unwrap();
700        assert!(down[1].0 == f64::NEG_INFINITY && down[1].1.is_finite());
701        assert!(dunnett_confidence_interval(&[&a], &control, DunnettAlternative::TwoSided, 1.5, &mut rng).is_err());
702    }
703
704    /// With NumPy's generator (`Pcg64::from_seed`) a single estimate is SciPy's to rounding:
705    /// `_qmvn(5657, ...)` with `default_rng(7)` gives 0.26992899873152054 in SciPy 1.17. (The full
706    /// `cdf` can differ from SciPy's in the sixth digit: the lattice vectors of some sizes are chosen
707    /// by an `argmin` over values that tie to rounding, and SciPy's FFT breaks the tie differently.)
708    #[test]
709    fn a_seeded_estimate_is_scipys() {
710        use lib_jsl_random::numpy::Pcg64;
711        let cov = vec![vec![2.0, 0.5, 0.3, 0.1], vec![0.5, 1.5, 0.4, 0.2], vec![0.3, 0.4, 1.0, 0.25], vec![0.1, 0.2, 0.25, 0.8]];
712        let mean = [0.1, -0.2, 0.3, 0.0];
713        let hi: Vec<f64> = [0.5, 0.2, 1.0, 0.4].iter().zip(&mean).map(|(a, b)| a - b).collect();
714        let lo = vec![f64::NEG_INFINITY; 4];
715        let mut rng = Pcg64::from_seed(7);
716        let (p, e, n) = qmc_estimate(5657, &cov, &lo, &hi, None, &mut rng);
717        assert!((p - 0.26992899873152054).abs() < 1e-13, "{p}");
718        assert!((e - 1.6337898722562712e-05).abs() < 1e-12 && n == 5630, "{e} {n}");
719    }
720}