Multivariate distributions and further tests
| Problem | Model the amplitude of a noisy signal (Rice) and random vectors and matrices (multivariate normal and t, Dirichlet, Wishart, multinomial); test goodness of fit and differences between groups without normality (Cramér-von Mises, Brunner-Munzel); compare every pair of means at once (Tukey’s HSD); and measure effects in contingency tables (odds ratio, relative risk, Cramér’s V) |
| Devised by | Stephen Rice (1944), the Rice distribution; John Wishart (1928); Harald Cramér (1928) and Richard von Mises (1931), Theodore Anderson and Donald Darling (1952), Theodore Anderson (1962); Edgar Brunner and Ullrich Munzel (2000); John Tukey (1953), Clyde Kramer (1956), Paul Games and John Howell (1976); Jerome Cornfield (1956) and Barnet Woolf (1955), odds ratios; Harald Cramér (1946), association |
| Accuracy | Agrees with scipy.stats to or better throughout; the Rice tail probabilities are more accurate than SciPy’s |
| Cost | Densities: once for a factorisation, then per point; Cramér-von Mises: , exact two-sample p-values by dynamic programming over lattice paths; studentized range: a double integral of a few hundred thousand evaluations of |
| Read first | Probability distributions, More hypothesis tests |
| API | Rice; multivariate (MultivariateNormal, MultivariateT, Dirichlet, Wishart, InvWishart, Multinomial); goodness_of_fit (cramervonmises, cramervonmises_2samp); brunnermunzel, monte_carlo_test; posthoc (StudentizedRange, tukey_hsd); contingency (odds_ratio, relative_risk, association) |
Overview
This entry fills the gaps between the earlier statistics entries and scipy.stats:
- The Rice distribution of the magnitude of a constant signal plus Gaussian noise. It is the envelope distribution in radio, radar and MRI. With no signal it reduces to the Rayleigh distribution.
- Multivariate distributions. The multivariate normal and t model random vectors. The Dirichlet distribution models random probability vectors, for example the posterior of multinomial proportions. The Wishart and inverse Wishart distributions model random covariance matrices, and the multinomial models counts in several categories.
- Goodness of fit. The Cramér-von Mises statistic integrates the squared distance between distribution functions, . It is often more powerful than Kolmogorov-Smirnov’s maximum distance.
- Brunner-Munzel, a rank test for whether one group tends to have larger values than another, valid even when the groups have different spreads or shapes. The Mann-Whitney test assumes that they do not.
- Tukey’s honestly significant difference (HSD), which compares all pairs of group means with a family-wise error rate held at .
- Effect sizes for contingency tables: the odds ratio (conditional and sample), the relative risk, and Cramér’s V and its relatives.
- Monte Carlo tests, which take the null distribution of any statistic from simulations of the null hypothesis.
Where it is used
Many measurements are vectors, not numbers.
- Signal amplitude. The Rice distribution models the magnitude of a signal plus noise, as in radar, MRI and fading channels.
- Multivariate normal. Models correlated errors in navigation, calibration and finance; the Wishart distribution describes the sample covariance matrix.
- Compositional and proportion data. The Dirichlet distribution for fractions that sum to one, as in topic models and mixture compositions.
History
Stephen Rice (1944) derived the distribution of the envelope of a sinusoid in Gaussian noise in his study of random noise at Bell Laboratories. John Wishart (1928) found the distribution of the sample covariance matrix of normal data, and Maurice Bartlett (1933) gave the triangular decomposition used to simulate it.
Harald Cramér (1928) and Richard von Mises (1931) proposed the integrated squared distance between distribution functions. Theodore Anderson and Donald Darling (1952) found its limiting distribution as a series of Bessel functions, Anderson (1962) extended the test to two samples, and Sándor Csörgő and Julian Faraway (1996) gave the finite-sample correction that SciPy uses.
John Tukey’s (1953) “honestly significant difference” used the distribution of the range of normal means, studentized by an independent estimate of spread. Clyde Kramer (1956) extended it to unequal group sizes, and Paul Games and John Howell (1976) to unequal variances. Edgar Brunner and Ullrich Munzel (2000) solved the nonparametric Behrens-Fisher problem: testing without assuming equal distributions under the null hypothesis.
For contingency tables, Barnet Woolf (1955) gave the log-odds confidence interval, and Jerome Cornfield (1956) the exact conditional one. Harald Cramér (1946) normalised the χ² statistic to a measure of association between 0 and 1.
The idea
The Rice distribution
If with and , then
The product overflows for strong signals, although the density is a modest number. Writing it with the scaled Bessel function gives , which never overflows.
is non-central χ² with 2 degrees of freedom and non-centrality . That makes the distribution function a Poisson mixture of central χ² ones,
where is the regularised incomplete gamma function. Using instead gives the survival function. Both are sums of positive terms, so each is accurate to rounding in its own tail. The library sums outwards from the Poisson mode until the terms no longer matter.
The moments follow from Laguerre functions, which can be written with Bessel functions of argument , . For example, , and follows by a contiguous relation of the confluent hypergeometric function.
Multivariate distributions
All the densities need a log-determinant and a quadratic form. Both come from the Cholesky factor : , and . Sampling uses the same factor, . The multivariate t is a normal divided by an independent . A Dirichlet vector is a normalised vector of independent gamma deviates. A Wishart matrix is by Bartlett’s decomposition, where is lower triangular with and standard normal entries below the diagonal.
The Cramér-von Mises tests
For a sample and a hypothesised distribution function :
Its limiting distribution is Anderson and Darling’s Bessel series
and Csörgő and Faraway’s correction, a second Bessel series divided by , makes it accurate for small samples. The two-sample statistic uses the ranks of each sample in the pooled one. For small samples its exact distribution is a sum over all ways of interleaving the samples. Xiao, Gordon and Yakovlev count those efficiently: a dynamic programme over lattice paths, where a step adds to the statistic, keeps for each path end the number of paths reaching each value. Because the counts are exact integers, the p-value is exact.
The Brunner-Munzel test
Mann-Whitney tests . Brunner and Munzel test only . With pooled ranks and within-sample ranks , the “placements” estimate how many of the other sample lie below each observation. Their variances , give
which is referred to a distribution with Satterthwaite’s degrees of freedom.
Tukey’s honestly significant difference
If groups have equal means, the largest difference between sample means, divided by its standard error, follows the studentized range distribution:
Here is the distribution of the range of standard normals, and the density of . Comparing every pair with the point of this distribution keeps the probability of any false difference at , because the largest difference is below it with probability . The library evaluates both integrals by composite 16-point Gauss-Legendre quadrature. The inner range is . The outer one covers the part of that holds all but of its mass.
Effect sizes for contingency tables
For a 2 × 2 table , the sample odds ratio is , with Woolf’s interval . The conditional odds ratio conditions on all margins. Then alone is random, with Fisher’s noncentral hypergeometric distribution . The estimate solves , and the exact confidence limits solve and . This is the interval that matches Fisher’s exact test. The relative risk has Katz’s log-scale interval. Cramér’s V, , puts the strength of association of an table on a scale from 0 (independence) to 1.
Algorithm
Exact two-sample Cramér-von Mises p-value (sample sizes , ; , ):
- Keep, for each , a table from accumulated values to path counts. Start with at .
- For , sweep : merge the table for into a running table, add to every key, and store it as the new table for .
- The p-value is the count of paths whose value is at least the observed (rescaled) statistic, divided by .
Studentized range quantile: bracket the quantile by doubling, then use regula falsi with the Illinois modification to a relative tolerance of .
Implementation
/// The Rice distribution of the length of a two-dimensional normal vector with mean length `ν`
/// and standard deviation `σ` per component (SciPy's `rice(b = ν/σ, scale = σ)`):
/// `f(x) = x/σ² exp(−(x² + ν²)/(2σ²)) I₀(xν/σ²)`. With `ν = 0` it is the Rayleigh distribution;
/// for `ν ≫ σ` it approaches `N(ν, σ²)`. `X²/σ²` is non-central χ² with 2 degrees of freedom and
/// non-centrality `(ν/σ)²`, which gives the distribution function as a Poisson mixture of
/// regularised incomplete gamma functions.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rice {
pub nu: f64,
pub sigma: f64,
}
impl Rice {
pub fn new(nu: f64, sigma: f64) -> Result<Self, ErrorsJSL> {
if !(nu >= 0.0) || !nu.is_finite() {
return Err(ErrorsJSL::InvalidInputRange("ν must be non-negative"));
}
Ok(Rice { nu, sigma: positive(sigma, "σ must be positive")? })
}
/// `Σ_j Pois(j; λ/2) G(1 + j, y/2)` for `G` the lower (`upper = false`) or upper regularised
/// incomplete gamma function, `λ = (ν/σ)²`, `y = (x/σ)²`, summed outwards from the Poisson
/// mode until the terms no longer matter. Both tails are sums of positive terms, so both
/// are accurate to rounding.
fn mixture(&self, x: f64, upper: bool) -> f64 {
let half_lambda = 0.5 * (self.nu / self.sigma).powi(2);
let half_y = 0.5 * (x / self.sigma).powi(2);
let weight = |j: f64| (-half_lambda + j * half_lambda.ln() - ln_gamma(j + 1.0)).exp();
let term = |j: f64| {
let w = if half_lambda == 0.0 { if j == 0.0 { 1.0 } else { 0.0 } } else { weight(j) };
if w == 0.0 { 0.0 } else { w * if upper { incomplete_gamma_upper(1.0 + j, half_y) } else { incomplete_gamma(1.0 + j, half_y) } }
};
let mode = half_lambda.floor();
let mut sum = term(mode);
let mut j = mode + 1.0;
loop {
let t = term(j);
sum += t;
if (t <= 1e-17 * sum && j > half_lambda + 1.0) || j > mode + 10_000.0 {
break;
}
j += 1.0;
}
let mut j = mode - 1.0;
while j >= 0.0 {
let t = term(j);
sum += t;
if t <= 1e-17 * sum && j < half_lambda - 1.0 {
break;
}
j -= 1.0;
}
sum
}
/// The raw moments `E[X], E[X²], E[X³], E[X⁴]`, from the Laguerre functions
/// `L_{1/2}(−t)` and `L_{3/2}(−t)`, `t = ν²/(2σ²)`, written with scaled Bessel functions.
fn raw_moments(&self) -> [f64; 4] {
let (nu, s) = (self.nu, self.sigma);
let t = nu * nu / (2.0 * s * s);
let (i0, i1) = (bessel_i_scaled(0.0, t / 2.0), bessel_i_scaled(1.0, t / 2.0));
let l_half = (1.0 + t) * i0 + t * i1; // M(−1/2; 1; −t)
let l_three_halves = ((2.0 + t) * l_half - 0.5 * i0) / 1.5; // M(−3/2; 1; −t)
let c = (PI / 2.0).sqrt();
[c * s * l_half, 2.0 * s * s + nu * nu, 3.0 * c * s.powi(3) * l_three_halves, 8.0 * s.powi(4) + 8.0 * s * s * nu * nu + nu.powi(4)]
}
}
impl ContinuousDistribution for Rice {
fn pdf(&self, x: f64) -> f64 {
if x <= 0.0 { 0.0 } else { self.logpdf(x).exp() }
}
fn logpdf(&self, x: f64) -> f64 {
if x <= 0.0 {
return f64::NEG_INFINITY;
}
let s2 = self.sigma * self.sigma;
let z = x * self.nu / s2;
// exp(−(x² + ν²)/2σ²) I₀(z) = exp(−(x − ν)²/2σ²) I₀(z) e^{−z}.
(x / s2).ln() - (x - self.nu).powi(2) / (2.0 * s2) + bessel_i_scaled(0.0, z).ln()
}
fn cdf(&self, x: f64) -> f64 {
if x <= 0.0 { 0.0 } else { self.mixture(x, false).min(1.0) }
}
fn sf(&self, x: f64) -> f64 {
if x <= 0.0 { 1.0 } else { self.mixture(x, true).min(1.0) }
}
fn support(&self) -> (f64, f64) {
(0.0, f64::INFINITY)
}
fn mean(&self) -> f64 {
self.raw_moments()[0]
}
fn variance(&self) -> f64 {
let m = self.raw_moments();
m[1] - m[0] * m[0]
}
fn skewness(&self) -> f64 {
let m = self.raw_moments();
let v = m[1] - m[0] * m[0];
(m[2] - 3.0 * m[0] * m[1] + 2.0 * m[0].powi(3)) / v.powf(1.5)
}
fn excess_kurtosis(&self) -> f64 {
let m = self.raw_moments();
let v = m[1] - m[0] * m[0];
(m[3] - 4.0 * m[0] * m[2] + 6.0 * m[0] * m[0] * m[1] - 3.0 * m[0].powi(4)) / (v * v) - 3.0
}
}
impl Fit for Rice {
/// Maximum likelihood over `(ν, σ)` by Nelder-Mead, from the moment estimates
/// `ν² ≈ √(2 m₂² − m₄)`, `σ² ≈ (m₂ − ν²)/2` (the location is fixed at 0).
fn fit(data: &[f64]) -> Result<Self, ErrorsJSL> {
check_data(data, 2)?;
if data.iter().any(|&x| x <= 0.0) {
return Err(ErrorsJSL::InvalidInputRange("Rice data must be positive"));
}
let n = data.len() as f64;
let m2 = data.iter().map(|x| x * x).sum::<f64>() / n;
let m4 = data.iter().map(|x| x.powi(4)).sum::<f64>() / n;
let nu2 = (2.0 * m2 * m2 - m4).max(0.0).sqrt();
let s2 = ((m2 - nu2) / 2.0).max(1e-3 * m2);
let nll = |p: &[f64]| -> f64 {
let r = Rice { nu: p[0].abs(), sigma: p[1].exp() };
let ll = r.log_likelihood(data);
if ll.is_finite() { -ll } else { f64::INFINITY }
};
let p = nelder_mead(nll, &[nu2.sqrt().max(1e-3), 0.5 * s2.ln()]);
Rice::new(p[0].abs(), p[1].exp())
}
}
/// The Wishart distribution of `X = Σ_k z_k z_kᵀ`, `z_k ~ N(0, S)`, with `ν > p − 1` degrees of
/// freedom (SciPy's `wishart(df, scale)`): `log f(X) = ((ν − p − 1)/2) log|X| − tr(S⁻¹X)/2 −
/// (νp/2) log 2 − (ν/2) log|S| − log Γ_p(ν/2)`. Sampling uses Bartlett's decomposition
/// `X = L A Aᵀ Lᵀ`, `A` lower triangular with `A_ii = √χ²_{ν−i}` and standard normal entries
/// below the diagonal.
#[derive(Clone, Debug)]
pub struct Wishart {
pub df: f64,
pub scale: Matrix,
chol: Matrix,
log_det: f64,
}
impl Wishart {
pub fn new(df: f64, scale: Matrix) -> Result<Self, ErrorsJSL> {
let p = scale.len() as f64;
if !(df > p - 1.0) {
return Err(ErrorsJSL::InvalidInputRange("the degrees of freedom must exceed p − 1"));
}
let chol = cholesky(&scale)?;
let log_det = log_det_from_cholesky(&chol);
Ok(Wishart { df, scale, chol, log_det })
}
pub fn logpdf(&self, x: &Matrix) -> Result<f64, ErrorsJSL> {
let p = self.scale.len();
let lx = cholesky(x)?;
let inv_s = inverse_from_cholesky(&self.chol);
let trace: f64 = (0..p).map(|i| (0..p).map(|j| inv_s[i][j] * x[j][i]).sum::<f64>()).sum();
let (nu, pf) = (self.df, p as f64);
Ok(0.5 * (nu - pf - 1.0) * log_det_from_cholesky(&lx) - 0.5 * trace - 0.5 * nu * pf * 2f64.ln() - 0.5 * nu * self.log_det - multigammaln(nu / 2.0, p as u32))
}
pub fn pdf(&self, x: &Matrix) -> Result<f64, ErrorsJSL> {
Ok(self.logpdf(x)?.exp())
}
/// `ν S`.
pub fn mean(&self) -> Matrix {
self.scale.iter().map(|r| r.iter().map(|v| v * self.df).collect()).collect()
}
/// The variances of the entries, `ν (S_ij² + S_ii S_jj)`.
pub fn var(&self) -> Matrix {
let s = &self.scale;
(0..s.len()).map(|i| (0..s.len()).map(|j| self.df * (s[i][j] * s[i][j] + s[i][i] * s[j][j])).collect()).collect()
}
/// `(ν − p − 1) S`, for `ν ≥ p + 1`.
pub fn mode(&self) -> Option<Matrix> {
let p = self.scale.len() as f64;
(self.df >= p + 1.0).then(|| self.scale.iter().map(|r| r.iter().map(|v| v * (self.df - p - 1.0)).collect()).collect())
}
/// `((p + 1)/2) log|S| + (p(p + 1)/2) log 2 + log Γ_p(ν/2) − ((ν − p − 1)/2) ψ_p(ν/2) + νp/2`.
pub fn entropy(&self) -> f64 {
let p = self.scale.len();
let (nu, pf) = (self.df, p as f64);
let psi_p: f64 = (0..p).map(|i| digamma((nu - i as f64) / 2.0)).sum();
0.5 * (pf + 1.0) * self.log_det + 0.5 * pf * (pf + 1.0) * 2f64.ln() + multigammaln(nu / 2.0, p as u32) - 0.5 * (nu - pf - 1.0) * psi_p + 0.5 * nu * pf
}
pub fn sample<U: UniformGenerator>(&self, rng: &mut U) -> Matrix {
let p = self.scale.len();
let mut a = vec![vec![0.0; p]; p];
for (i, row) in a.iter_mut().enumerate() {
row[i] = (2.0 * standard_gamma((self.df - i as f64) / 2.0, rng)).sqrt();
for v in row.iter_mut().take(i) {
*v = standard_normal(rng);
}
}
// B = L A, X = B Bᵀ.
let b: Matrix = (0..p).map(|i| (0..p).map(|j| (0..p).map(|k| self.chol[i][k] * a[k][j]).sum()).collect()).collect();
(0..p).map(|i| (0..p).map(|j| (0..p).map(|k| b[i][k] * b[j][k]).sum()).collect()).collect()
}
}
/// The two-sample Cramér-von Mises test (SciPy's `cramervonmises_2samp`), from the average
/// ranks: `U = n_x Σ (r_i − i)² + n_y Σ (s_j − j)²` and `T = U/(n_x n_y N) − (4 n_x n_y − 1)/(6N)`,
/// with an exact p-value (lattice-path counting) or the asymptotic one after standardising `T`.
pub fn cramervonmises_2samp(x: &[f64], y: &[f64], method: CvmMethod) -> Result<TestResult, ErrorsJSL> {
let (nx, ny) = (x.len(), y.len());
if nx < 2 || ny < 2 || x.iter().chain(y).any(|v| !v.is_finite()) {
return Err(ErrorsJSL::InvalidInputRange("cramervonmises_2samp: need at least two finite observations per sample"));
}
let exact = match method {
CvmMethod::Exact => true,
CvmMethod::Asymptotic => false,
CvmMethod::Auto => nx.max(ny) <= 20,
};
let mut xs = x.to_vec();
let mut ys = y.to_vec();
xs.sort_by(f64::total_cmp);
ys.sort_by(f64::total_cmp);
let z: Vec<f64> = xs.iter().chain(&ys).copied().collect();
let r = rank(&z);
let (nxf, nyf) = (nx as f64, ny as f64);
let u = nxf * (0..nx).map(|i| (r[i] - (i + 1) as f64).powi(2)).sum::<f64>() + nyf * (0..ny).map(|j| (r[nx + j] - (j + 1) as f64).powi(2)).sum::<f64>();
let (k, n) = (nxf * nyf, nxf + nyf);
let t = u / (k * n) - (4.0 * k - 1.0) / (6.0 * n);
let p = if exact {
cvm_2samp_exact(u, nx, ny)
} else {
let et = (1.0 + 1.0 / n) / 6.0;
let vt = (n + 1.0) * (4.0 * k * n - 3.0 * (nxf * nxf + nyf * nyf) - 2.0 * k) / (45.0 * n * n * 4.0 * k);
let tn = 1.0 / 6.0 + (t - et) / (45.0 * vt).sqrt();
if tn >= 0.003 { (1.0 - cramer_von_mises_cdf_limit(tn)).max(0.0) } else { 1.0 }
};
Ok(TestResult::new(t, p, f64::NAN))
}
/// The Brunner-Munzel test of `P(X < Y) + ½ P(X = Y) = ½` (SciPy's `brunnermunzel`): unlike the
/// Mann-Whitney test it does not assume equal variances or shapes. With ranks `R` in the pooled
/// sample and `R⁽ˣ⁾` within each sample, the placement variances are
/// `S_x² = Σ (R_i − R_i⁽ˣ⁾ − R̄ + R̄⁽ˣ⁾)² / (n_x − 1)` (likewise for `y`), and
/// `W = n_x n_y (R̄_y − R̄_x) / ((n_x + n_y) √(n_x S_x² + n_y S_y²))`.
pub fn brunnermunzel(x: &[f64], y: &[f64], alternative: Alternative, distribution: BrunnerMunzelDistribution) -> Result<TestResult, ErrorsJSL> {
let (nx, ny) = (x.len(), y.len());
if nx < 2 || ny < 2 || x.iter().chain(y).any(|v| !v.is_finite()) {
return Err(ErrorsJSL::InvalidInputRange("brunnermunzel: need at least two finite observations per sample"));
}
let pooled: Vec<f64> = x.iter().chain(y).copied().collect();
let rc = rank(&pooled);
let (rcx, rcy) = rc.split_at(nx);
let (rx, ry) = (rank(x), rank(y));
let mean = |v: &[f64]| v.iter().sum::<f64>() / v.len() as f64;
let (mcx, mcy, mx, my) = (mean(rcx), mean(rcy), mean(&rx), mean(&ry));
let sx = rcx.iter().zip(&rx).map(|(a, b)| (a - b - mcx + mx).powi(2)).sum::<f64>() / (nx - 1) as f64;
let sy = rcy.iter().zip(&ry).map(|(a, b)| (a - b - mcy + my).powi(2)).sum::<f64>() / (ny - 1) as f64;
let (nxf, nyf) = (nx as f64, ny as f64);
let w = nxf * nyf * (mcy - mcx) / ((nxf + nyf) * (nxf * sx + nyf * sy).sqrt());
let (cdf, df): (Box<dyn Fn(f64) -> f64>, f64) = match distribution {
BrunnerMunzelDistribution::T => {
let df = (nxf * sx + nyf * sy).powi(2) / ((nxf * sx).powi(2) / (nxf - 1.0) + (nyf * sy).powi(2) / (nyf - 1.0));
(Box::new(move |t| lib_jsl_special_functions::student_t_cdf(t, df)), df)
}
BrunnerMunzelDistribution::Normal => (Box::new(|t| normal_cdf(t, 0.0, 1.0)), f64::INFINITY),
};
// SciPy evaluates the tails at −W.
let p = match alternative {
Alternative::Less => cdf(-w),
Alternative::Greater => cdf(w),
Alternative::TwoSided => (2.0 * cdf(-w.abs())).min(1.0),
};
Ok(TestResult { statistic: w, p_value: p, degrees_of_freedom: df })
}
/// Tukey's honestly significant difference test of all pairwise differences of means (SciPy's
/// `tukey_hsd`): `|x̄_i − x̄_j| / se_ij` against the studentized range with `k` treatments, where
/// `se_ij = √(MSE (1/n_i + 1/n_j) / 2)` with the pooled variance and `N − k` degrees of freedom
/// (the Tukey-Kramer form), or, with `equal_var = false`, the Games-Howell form
/// `se_ij = √((s_i²/n_i + s_j²/n_j)/2)` with Welch's degrees of freedom.
pub fn tukey_hsd(groups: &[Vec<f64>], equal_var: bool) -> Result<TukeyHsdResult, ErrorsJSL> {
let k = groups.len();
if k < 2 || groups.iter().any(|g| g.len() < 2 || g.iter().any(|v| !v.is_finite())) {
return Err(ErrorsJSL::InvalidInputRange("tukey_hsd: need at least two groups of at least two finite values"));
}
let n: Vec<f64> = groups.iter().map(|g| g.len() as f64).collect();
let means: Vec<f64> = groups.iter().map(|g| g.iter().sum::<f64>() / g.len() as f64).collect();
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();
let nobs: f64 = n.iter().sum();
let mut std_err = vec![vec![0.0; k]; k];
let mut df = vec![vec![0.0; k]; k];
if equal_var {
let mse = vars.iter().zip(&n).map(|(v, ni)| v * (ni - 1.0)).sum::<f64>() / (nobs - k as f64);
for i in 0..k {
for j in 0..k {
std_err[i][j] = ((1.0 / n[i] + 1.0 / n[j]) * mse / 2.0).sqrt();
df[i][j] = nobs - k as f64;
}
}
} else {
for i in 0..k {
for j in 0..k {
let (a, b) = (vars[i] / n[i], vars[j] / n[j]);
std_err[i][j] = (a + b).sqrt() / 2f64.sqrt();
df[i][j] = (a + b).powi(2) / (a * a / (n[i] - 1.0) + b * b / (n[j] - 1.0));
}
}
}
let statistic: Vec<Vec<f64>> = (0..k).map(|i| (0..k).map(|j| means[i] - means[j]).collect()).collect();
let mut p_values = vec![vec![1.0; k]; k];
for i in 0..k {
for j in i + 1..k {
let t = statistic[i][j].abs() / std_err[i][j];
let p = 1.0 - StudentizedRange::new(k as f64, df[i][j])?.cdf(t);
p_values[i][j] = p;
p_values[j][i] = p;
}
}
Ok(TukeyHsdResult { statistic, p_values, std_err, df, ntreatments: k })
}
/// The odds ratio of a 2 × 2 table `[[a, b], [c, d]]` (SciPy's `odds_ratio`). The conditional
/// estimate solves `E_ω[X] = a` for the odds ratio `ω` of Fisher's noncentral hypergeometric
/// distribution of `X = table[0][0]` given all margins; its confidence limits invert that
/// distribution's tails (the exact interval that matches Fisher's exact test). The sample odds
/// ratio is `ad/(bc)`, with Woolf's interval `exp(log OR ± z √(1/a + 1/b + 1/c + 1/d))`.
pub fn odds_ratio(table: [[u64; 2]; 2], kind: OddsRatioKind) -> OddsRatioResult {
let [[a, b], [c, d]] = table;
let statistic = if a + b == 0 || c + d == 0 || a + c == 0 || b + d == 0 {
f64::NAN
} else {
match kind {
OddsRatioKind::Sample => sample_odds_ratio(&table),
OddsRatioKind::Conditional => {
let h = FisherNcHypergeom::new(a + b + c + d, a + b, a + c);
if a == h.lo {
0.0
} else if a == h.hi {
f64::INFINITY
} else {
solve_positive(|nc| h.mean(nc) - a as f64)
}
}
}
};
OddsRatioResult { statistic, kind, table }
}
- The Cramér-von Mises series are summed exactly as SciPy sums them, stopping after the first term below , so the p-values agree to rounding. That threshold limits their absolute accuracy to about .
tukey_hsdreturns the full matrices, as SciPy does. Itsconfidence_intervalevaluates the studentized range quantile once for each distinct number of degrees of freedom.monte_carlo_testtakes the null distribution as a closurervs(sample index, size, rng)and the library’s random generators, so its results are reproducible for a given seed. They are not SciPy’s for the same seed.- Dunnett’s test, which compares treatments with a control, is not implemented. SciPy computes its p-values with a randomised quasi-Monte Carlo integration of the multivariate t distribution.
In practice
The references are from SciPy 1.17.1, written by book/generator/data/make_stats27_refs.py:
Table 10.12. The Rice and multivariate distributions against `scipy.stats`.
| distribution and quantities | largest relative difference from SciPy |
|---|---|
Rice: pdf, cdf, sf (ν/σ = 0, 1.7, 6) | 1e-13 |
Rice: sf at x = 6 (10⁻⁵ to 10⁻⁹) against direct integration of the density (SciPy: 2e-7) | 9e-15 |
Rice: ppf; mean, variance, skewness, kurtosis | 1e-9 |
Rice, ν/σ = 40: cdf and sf in the tails (SciPy’s moments are NaN here) | 4e-11 |
Rice::fit (location 0): log-likelihood 5e-9 above SciPy’s, whose optimiser stops earlier | 1e-5 |
Rice, ν/σ = 40: mean against the limit ν + σ²/(2ν) | 5e-8 |
MultivariateNormal: logpdf, entropy | 3e-16 |
MultivariateT: logpdf, entropy | 3e-16 |
Dirichlet: logpdf, mean, variance, entropy | 1e-15 |
Wishart: logpdf, variance, entropy | 1e-16 |
InvWishart: logpdf, mean, mode | 1e-16 |
Multinomial: logpmf, covariance | 1e-15 |
The densities, moments and entropies agree with SciPy to rounding. In the far upper tail of the Rice distribution, near , SciPy’s survival function is off by up to relative, while the library’s agrees with direct integration of the density to . At , SciPy’s moment formula overflows to NaN. The library’s moments, from scaled Bessel functions, are finite, and the mean approaches the normal limit . The fitted parameters differ from SciPy’s in the fifth digit. The library’s estimate has the higher likelihood, because SciPy’s optimiser stops earlier.
Table 10.13. Tests and effect sizes against `scipy.stats`.
| test or estimate | largest relative difference from SciPy |
|---|---|
cramervonmises (n = 10, 50) | 2e-14 |
cramervonmises_2samp: exact (7 and 9, with ties), asymptotic (7 and 9; 25 and 30) | 2e-14 |
brunnermunzel (three alternatives; t and normal) | 9e-16 |
StudentizedRange: cdf, pdf, 95 % point (k = 2–10, ν = 5–∞) | 3e-13 |
tukey_hsd (4 groups, unequal sizes; Tukey-Kramer and Games-Howell): differences, intervals | 3e-14 |
tukey_hsd: p-values (absolute difference) | 3e-15 |
odds_ratio, conditional and sample, with intervals for three alternatives (one table with a zero) | 4e-15 |
relative_risk with Katz’s interval | 8e-16 |
association: Cramér’s V, Tschuprow’s T, Pearson’s C (3 × 4 table) | 2e-16 |
Strengths
- The Rice distribution is accurate in both tails and for strong signals, where SciPy loses digits or returns NaN.
- The tests reproduce SciPy’s statistics and p-values to rounding, including the exact two-sample Cramér-von Mises p-values and the exact conditional odds ratio intervals.
- Tukey’s HSD comes with simultaneous confidence intervals, in the Tukey-Kramer (unequal sizes) and Games-Howell (unequal variances) forms.
Weaknesses
- The studentized range costs a double integral per evaluation, about 30 ms, and its quantile about ten evaluations (0.3 s).
- The multivariate normal needs a positive definite covariance (SciPy’s
allow_singularis not supported), and there is no multivariate normal distribution function. - No Dunnett test, and no
stats.samplinggenerators.
Exercises
- Show that the Rice distribution with is the Rayleigh distribution, and that is non-central χ² with 2 degrees of freedom.
- Show that is for the empirical distribution function .
- With three groups of four observations and pooled standard deviation 1, how large must a difference of means be to be significant at the 5 % level by Tukey’s HSD? (Use .)
- Find the conditional and sample odds ratios of , and explain why the exact interval is so wide.
- Show that a vector of independent Gamma() variables, divided by its sum, is Dirichlet().
Hints and answers
- leaves . is the sum of the squares of two independent normals with means , and unit variance: non-central χ² with non-centrality .
- Between order statistics, is constant at . Integrate over and sum, which gives the same expression after rearranging.
- . Here .
- Both are 1. With so few counts, the conditional distribution of has support , and almost any is compatible with it: the 95 % interval is .
- Change variables to and . The Jacobian is , and the joint density factorises into a Gamma() density in and the Dirichlet density in .
Further reading
- S. O. Rice, “Mathematical analysis of random noise”, Bell System Technical Journal 23 (1944) 282–332 and 24 (1945) 46–156.
- J. Wishart, “The generalised product moment distribution in samples from a normal multivariate population”, Biometrika 20A (1928) 32–52.
- T. W. Anderson and D. A. Darling, “Asymptotic theory of certain ‘goodness of fit’ criteria based on stochastic processes”, Annals of Mathematical Statistics 23 (1952) 193–212.
- T. W. Anderson, “On the distribution of the two-sample Cramér-von Mises criterion”, Annals of Mathematical Statistics 33 (1962) 1148–1159.
- S. Csörgő and J. J. Faraway, “The exact and asymptotic distributions of Cramér-von Mises statistics”, Journal of the Royal Statistical Society B 58 (1996) 221–234.
- Y. Xiao, A. Gordon and A. Yakovlev, “A C++ program for the Cramér-von Mises two-sample test”, Journal of Statistical Software 17 (2006) 1–15.
- E. Brunner and U. Munzel, “The nonparametric Behrens-Fisher problem: asymptotic theory and a small-sample approximation”, Biometrical Journal 42 (2000) 17–25.
- C. Y. Kramer, “Extension of multiple range tests to group means with unequal numbers of replications”, Biometrics 12 (1956) 307–310.
- P. A. Games and J. F. Howell, “Pairwise multiple comparison procedures with unequal n’s and/or variances”, Journal of Educational Statistics 1 (1976) 113–125.
- B. Woolf, “On estimating the relation between blood group and disease”, Annals of Human Genetics 19 (1955) 251–253.
- J. Cornfield, “A statistical problem arising from retrospective studies”, Proceedings of the Third Berkeley Symposium 4 (1956) 135–148.
- G. Marsaglia and W. W. Tsang, “A simple method for generating gamma variables”, ACM Transactions on Mathematical Software 26 (2000) 363–372.