Multivariate distribution functions and quasi-Monte Carlo sampling
| Problem | Compute probabilities of boxes under multivariate normal and t distributions; handle normal distributions with singular covariance matrices; compare several treatments with one control (Dunnett’s test); and draw low-discrepancy normal samples and evenly spread random points |
| Devised by | Zvi Drezner and George Wesolowsky (1990), bivariate normal probabilities; Alan Genz (1992) and Frank Bretz (2002), the multivariate normal and t integrals; Dirk Nuyens and Ronald Cools (2006), fast lattice construction; Charles Dunnett (1955); Robert Bridson (2007), Poisson-disk sampling |
| Accuracy | Bivariate normal exact to ; higher dimensions to the requested error ( by default, typically ); t probabilities to about with SciPy’s default of points |
| Cost | Normal: up to integrand evaluations of each; t: ; Poisson disk: with a background grid |
| Read first | Multivariate distributions and further tests, Quasi-random sequences |
| API | MultivariateNormal::cdf_between, MultivariateNormal::new_allow_singular, MultivariateT::cdf_between, MvCdfOptions, bivariate_normal_upper, dunnett, dunnett_confidence_interval; MultivariateNormalQmc; PoissonDisk |
Overview
The multivariate normal distribution has no closed-form distribution function beyond two dimensions, yet its box probabilities are needed throughout statistics:
- multiple-comparison procedures;
- probit models with correlated choices;
- reliability with correlated failure modes;
- the multivariate t distribution behind simultaneous confidence intervals.
SciPy computes them with Alan Genz’s quasi-Monte Carlo method, and so does the library.
This entry adds:
- Distribution functions of the multivariate normal (exact in one and two dimensions) and t distributions.
- Singular covariances for the normal distribution (SciPy’s
allow_singular=True), whose density lives on a lower-dimensional subspace. - Dunnett’s test, which compares each of several treatment groups with a control while holding the family-wise error rate.
MultivariateNormalQmc, low-discrepancy normal samples from a Sobol sequence.PoissonDisk, random points no two of which are closer than a given radius: blue-noise sampling for graphics and space-filling designs.
Where it is used
Probabilities of regions under a multivariate normal distribution are hard to compute.
- Reliability and tolerance analysis. The probability that several correlated quantities all lie within specification at once.
- Statistics. Simultaneous confidence regions and the p-values of multiple comparisons.
- Finance and insurance. Joint default or loss probabilities.
- Method. Quasi-Monte Carlo with a clever variable transformation (Genz’s method) turns a hard integral into a fast and accurate one.
History
Zvi Drezner and George Wesolowsky (1990) gave the Gauss-Legendre evaluation of Plackett’s integral for bivariate normal probabilities that Genz refined into bvnu. Alan Genz (1992) transformed the multivariate normal integral into an integral over the unit cube that is smooth enough for quasi-Monte Carlo rules. With Frank Bretz (2002) he extended it to the t distribution. The randomised rank-1 lattice rules with Nuyens and Cools’s (2006) fast component-by-component construction are what SciPy’s _qmvnt uses. Charles Dunnett (1955) introduced the many-to-one comparisons, and Robert Bridson (2007) the linear-time Poisson-disk algorithm.
The idea
Genz’s transformation
Write with lower triangular, so with standard normal. The constraint becomes The limits of each variable depend only on the earlier ones. Substituting , where are the limits mapped through , turns the probability into The integrand is smooth and bounded by 1. The first variable is integrated exactly, which removes one dimension. Reordering the variables so that the most constrained come first reduces its variance further.
Lattice rules
A rank-1 lattice rule averages the integrand over the points , , for a prime and a generating vector . The vector is chosen component by component to minimise a worst-case error, with fast Fourier transforms. Ten random shifts of the lattice give independent estimates, and their spread gives the error estimate.
The “tent” transform makes the integrand periodic, which lattice rules need for their fast convergence. For smooth integrands the error falls almost like , against for Monte Carlo.
The t distribution
with . The t probability is therefore the normal one with limits scaled by , averaged over . That adds one dimension, the χ variable, through the inverse χ² distribution function.
Singular covariances
If has rank , lies in . With the eigendecomposition restricted to the eigenvalues above , the density on that affine subspace is the -dimensional normal density. It uses the pseudo-inverse and the pseudo-determinant , and is zero off the subspace.
Dunnett’s test
With group means , control mean and pooled standard deviation on degrees of freedom, the statistics are jointly multivariate t. They share , so they are correlated with . The adjusted p-value of comparison is , one minus a multivariate t box probability.
Confidence intervals. The same distribution gives simultaneous confidence intervals for the differences : , where the critical value is the one for which (one-sided: , and the interval is open at one end). dunnett_confidence_interval finds by bisection. The probability is a quasi-Monte Carlo estimate, so it is noisy from one evaluation to the next; every evaluation reuses one stream of random lattice shifts, which makes it a smooth function of that bisection can follow. SciPy minimises with Brent’s method on the noisy function, to a tolerance of .
Quasi-Monte Carlo normal samples
MultivariateNormalQmc maps the points of a Sobol sequence to normal samples. The default is the inverse transform: each coordinate goes through . The alternative is the Box-Muller transform, which uses pairs of coordinates and needs one extra Sobol dimension when is odd. Either way the result is multiplied by a factor with and shifted by the mean. The factor is a Cholesky factor, or an eigenvalue factor when is singular. Averages over the samples inherit the faster convergence of the Sobol points.
Poisson-disk sampling
Bridson’s algorithm keeps a background grid with cells of side , each of which can hold at most one point. Starting from a random point, it repeatedly takes an active point and draws 30 candidates around it. A candidate is kept if no point within already exists, which only the neighbouring cells need checking for. A point with no successful candidate is retired, and the process ends when none remain active, with the box filled.
Implementation
impl MultivariateNormal {
/// `P(lower < X ≤ upper)` (SciPy's `multivariate_normal.cdf(upper, lower_limit=lower)`;
/// `lower = None` for −∞), with the error estimate. One and two dimensions are exact; in
/// more, Genz's method: reorder the variables so the most constrained comes first, factor
/// `Σ = L Lᵀ`, and write the probability as an integral over the unit cube of a product of
/// one-dimensional normal probabilities whose limits depend on the earlier variables, then
/// integrate it with randomised rank-1 lattice rules until the error is below `abseps`.
pub fn cdf_between<U: UniformGenerator>(&self, lower: Option<&[f64]>, upper: &[f64], options: MvCdfOptions, rng: &mut U) -> Result<(f64, f64), ErrorsJSL> {
let d = self.dim();
if upper.len() != d || lower.is_some_and(|l| l.len() != d) {
return Err(ErrorsJSL::IncompatibleArraySizes((upper.len(), d)));
}
let low: Vec<f64> = match lower {
Some(l) => l.iter().zip(&self.mean).map(|(a, m)| a - m).collect(),
None => vec![f64::NEG_INFINITY; d],
};
let up: Vec<f64> = upper.iter().zip(&self.mean).map(|(a, m)| a - m).collect();
let (a, b, sign) = order_limits(&low, &up);
let (p, e) = qauto(&self.cov, &a, &b, options.abseps, options.maxpts.unwrap_or(1_000_000 * d), rng);
Ok((sign * p, e))
}
/// `P(X ≤ x)` (SciPy's `multivariate_normal.cdf`).
pub fn cdf<U: UniformGenerator>(&self, x: &[f64], rng: &mut U) -> Result<f64, ErrorsJSL> {
Ok(self.cdf_between(None, x, MvCdfOptions::default(), rng)?.0)
}
}
/// `P(X > h, Y > k)` for standard bivariate normal `(X, Y)` with correlation `r` (Genz's `bvnu`,
/// after Drezner and Wesolowsky): for `|r| < 0.925` Plackett's integral over the correlation,
/// `∫₀^{asin r} exp(−(h² + k² − 2hk sin θ)/(2 cos²θ)) dθ / 2π + Φ(−h)Φ(−k)`, by 6-, 12- or
/// 20-point Gauss-Legendre rules; near `|r| = 1` an asymptotic expansion plus a correction
/// integral. Accurate to about 10⁻¹⁵.
pub fn bivariate_normal_upper(h: f64, k: f64, r: f64) -> f64 {
if h == f64::INFINITY || k == f64::INFINITY {
return 0.0;
}
if h == f64::NEG_INFINITY {
return if k == f64::NEG_INFINITY { 1.0 } else { phi(-k) };
}
if k == f64::NEG_INFINITY {
return phi(-h);
}
if r == 0.0 {
return phi(-h) * phi(-k);
}
let tp = 2.0 * PI;
let n = if r.abs() < 0.3 {
6
} else if r.abs() < 0.75 {
12
} else {
20
};
let (xs, ws) = gauss_legendre(n);
let (x, w): (Vec<f64>, Vec<f64>) = xs.iter().zip(&ws).filter(|(x, _)| **x < 0.0).map(|(a, b)| (*a, *b)).unzip();
let mut k = k;
let mut hk = h * k;
let mut bvn = 0.0;
if r.abs() < 0.925 {
let hs = (h * h + k * k) / 2.0;
let asr = r.asin();
for i in 0..x.len() {
let sn = (asr * (1.0 + x[i]) / 2.0).sin();
bvn += w[i] * ((sn * hk - hs) / (1.0 - sn * sn)).exp();
let sn = (asr * (1.0 - x[i]) / 2.0).sin();
bvn += w[i] * ((sn * hk - hs) / (1.0 - sn * sn)).exp();
}
return bvn * asr / (2.0 * tp) + phi(-h) * phi(-k);
}
if r < 0.0 {
k = -k;
hk = -hk;
}
if r.abs() < 1.0 {
let as_ = (1.0 - r) * (1.0 + r);
let mut a = as_.sqrt();
let bs = (h - k) * (h - k);
let c = (4.0 - hk) / 8.0;
let d = (12.0 - hk) / 16.0;
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);
if hk > -160.0 {
let b = bs.sqrt();
bvn -= (-hk / 2.0).exp() * tp.sqrt() * phi(-b / a) * b * (1.0 - c * bs * (1.0 - d * bs / 5.0) / 3.0);
}
a /= 2.0;
for i in 0..x.len() {
for sgn in [-1.0, 1.0] {
let xs = (a * (sgn * x[i] + 1.0)).powi(2);
let rs = (1.0 - xs).sqrt();
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)));
}
}
bvn = -bvn / tp;
}
if r > 0.0 {
bvn += phi(-h.max(k));
} else {
bvn = -bvn;
if k > h {
if h < 0.0 {
bvn += phi(k) - phi(h);
} else {
bvn += phi(-h) - phi(-k);
}
}
}
bvn.clamp(0.0, 1.0)
}
/// Dunnett's test comparing each treatment group with a control (SciPy's `dunnett`):
/// `tᵢ = (x̄ᵢ − x̄₀)/(s √(1/nᵢ + 1/n₀))` with the pooled standard deviation `s` on
/// `N − k − 1` degrees of freedom. The statistics are jointly multivariate t with correlations
/// `ρᵢⱼ = 1/√((1 + n₀/nᵢ)(1 + n₀/nⱼ))`, and each p-value is the probability that the largest
/// (absolute) statistic exceeds `tᵢ`, from the multivariate t distribution function — so the
/// p-values carry its quasi-Monte Carlo error (about 10⁻³ with SciPy's 1000 points per
/// dimension).
pub fn dunnett<U: UniformGenerator>(samples: &[&[f64]], control: &[f64], alternative: DunnettAlternative, rng: &mut U) -> Result<DunnettResult, ErrorsJSL> {
let k = samples.len();
if k == 0 || control.len() < 2 || samples.iter().any(|s| s.is_empty()) {
return Err(ErrorsJSL::InvalidInputRange("dunnett: need a control of two or more values and non-empty treatment groups"));
}
let n0 = control.len() as f64;
let ns: Vec<f64> = samples.iter().map(|s| s.len() as f64).collect();
let n_total = n0 + ns.iter().sum::<f64>();
let df = n_total - k as f64 - 1.0;
if df <= 0.0 {
return Err(ErrorsJSL::InvalidInputRange("dunnett: not enough observations for the degrees of freedom"));
}
let mean = |s: &[f64]| s.iter().sum::<f64>() / s.len() as f64;
let m0 = mean(control);
let ms: Vec<f64> = samples.iter().map(|s| mean(s)).collect();
let ss = |s: &[f64], m: f64| s.iter().map(|v| (v - m).powi(2)).sum::<f64>();
let s2 = (ss(control, m0) + samples.iter().zip(&ms).map(|(s, &m)| ss(s, m)).sum::<f64>()) / df;
let std = s2.sqrt();
let statistic: Vec<f64> = (0..k).map(|i| (ms[i] - m0) / (1.0 / ns[i] + 1.0 / n0).sqrt() / std).collect();
let r: Vec<f64> = ns.iter().map(|n| n0 / n + 1.0).collect();
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();
let mvt = MultivariateT::new(vec![0.0; k], rho, df)?;
let opts = MvCdfOptions::default();
let mut pvalue = Vec::with_capacity(k);
for &t in &statistic {
let p = match alternative {
DunnettAlternative::TwoSided => {
let a = t.abs();
1.0 - mvt.cdf_between(Some(&vec![-a; k]), &vec![a; k], opts, rng)?.0
}
DunnettAlternative::Greater => 1.0 - mvt.cdf_between(None, &vec![t; k], opts, rng)?.0,
DunnettAlternative::Less => 1.0 - mvt.cdf_between(Some(&vec![t; k]), &vec![f64::INFINITY; k], opts, rng)?.0,
};
pvalue.push(p.clamp(0.0, 1.0));
}
Ok(DunnettResult { statistic, pvalue, std, df })
}
/// Simultaneous confidence intervals for the differences of the treatment means and the control
/// mean (SciPy's `DunnettResult.confidence_interval`): `x̄ᵢ − x̄₀ ± c s √(1/nᵢ + 1/n₀)` for the
/// two-sided alternative, with `(−∞, … + …]` and `[… − …, ∞)` for the one-sided ones, where `c`
/// is the critical value of Dunnett's test at the level `1 − confidence_level`: the `c` for which
/// the probability that the largest (absolute) statistic exceeds it is `1 − confidence_level`.
///
/// `c` is found by bisection on that probability. The probability is a quasi-Monte Carlo
/// estimate, noisy from one evaluation to the next, so every evaluation reuses one stream of random
/// shifts (a seed drawn from `rng`), which makes it a smooth function of `c`. Returns, for each
/// treatment, the interval `(low, high)`.
pub fn dunnett_confidence_interval<U: UniformGenerator>(samples: &[&[f64]], control: &[f64], alternative: DunnettAlternative, confidence_level: f64, rng: &mut U) -> Result<Vec<(f64, f64)>, ErrorsJSL> {
if !(confidence_level > 0.0 && confidence_level < 1.0) {
return Err(ErrorsJSL::InvalidInputRange("dunnett: the confidence level must lie between 0 and 1"));
}
// The statistics, correlations and degrees of freedom come from the test itself.
let k = samples.len();
let result = dunnett(samples, control, alternative, rng)?;
let n0 = control.len() as f64;
let ns: Vec<f64> = samples.iter().map(|s| s.len() as f64).collect();
let r: Vec<f64> = ns.iter().map(|n| n0 / n + 1.0).collect();
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();
let mvt = MultivariateT::new(vec![0.0; k], rho, result.df)?;
let seed = rng.next_u64();
let alpha = 1.0 - confidence_level;
let opts = MvCdfOptions::default();
// P(the largest statistic exceeds c), by symmetry the same for `Less` as for `Greater`.
let tail = |c: f64| -> Result<f64, ErrorsJSL> {
let mut fixed = lib_jsl_random::uniform_generator::UniformRNG::from_seed(seed);
let inside = match alternative {
DunnettAlternative::TwoSided => mvt.cdf_between(Some(&vec![-c; k]), &vec![c; k], opts, &mut fixed)?.0,
_ => mvt.cdf_between(None, &vec![c; k], opts, &mut fixed)?.0,
};
Ok(1.0 - inside)
};
// The tail decreases from 1 (or 1 − 2^-k) at c = 0: bracket the root, then bisect.
let (mut lo, mut hi) = (0.0f64, 1.0f64);
while tail(hi)? > alpha {
lo = hi;
hi *= 2.0;
if hi > 1e3 {
return Err(ErrorsJSL::RuntimeError("dunnett: no critical value found for this confidence level"));
}
}
for _ in 0..40 {
let mid = 0.5 * (lo + hi);
if tail(mid)? > alpha { lo = mid } else { hi = mid }
}
let critical = 0.5 * (lo + hi);
let mean = |s: &[f64]| s.iter().sum::<f64>() / s.len() as f64;
let m0 = mean(control);
Ok(samples
.iter()
.zip(&ns)
.map(|(s, &n)| {
let diff = mean(s) - m0;
let allowance = critical * result.std * (1.0 / n + 1.0 / n0).sqrt();
match alternative {
DunnettAlternative::TwoSided => (diff - allowance, diff + allowance),
DunnettAlternative::Greater => (diff - allowance, f64::INFINITY),
DunnettAlternative::Less => (f64::NEG_INFINITY, diff + allowance),
}
})
.collect())
}
/// A normal distribution whose covariance may be singular (SciPy's
/// `multivariate_normal(mean, cov, allow_singular=True)`). The covariance's eigenvalues
/// above `ε = 10⁶ ε_mach max|λ|` define its rank `r` and range; the density is the `r`-
/// dimensional one on the affine support `μ + range(Σ)`, with the pseudo-determinant and
/// pseudo-inverse, and zero off it.
pub fn new_allow_singular(mean: Vec<f64>, cov: Matrix) -> Result<Self, ErrorsJSL> {
let d = mean.len();
if cov.len() != d || d == 0 || cov.iter().any(|r| r.len() != d) {
return Err(ErrorsJSL::InvalidInputRange("the mean and covariance must have one dimension"));
}
if let Ok(chol) = cholesky(&cov) {
let log_det = log_det_from_cholesky(&chol);
return Ok(MultivariateNormal { mean, cov, chol, log_det, psd: None });
}
let (lam, v) = symmetric_eigen(&cov);
let eps = 1e6 * f64::EPSILON * lam.iter().fold(0.0f64, |m, x| m.max(x.abs()));
if lam.iter().any(|&l| l < -eps) {
return Err(ErrorsJSL::InvalidInputRange("the covariance must be positive semidefinite"));
}
let keep: Vec<usize> = (0..d).filter(|&i| lam[i] > eps).collect();
let drop: Vec<usize> = (0..d).filter(|&i| lam[i] <= eps).collect();
let col = |cols: &[usize], f: &dyn Fn(f64) -> f64| -> Matrix { (0..d).map(|i| cols.iter().map(|&j| v[i][j] * f(lam[j])).collect()).collect() };
let psd = Psd {
root: col(&keep, &|l| l.sqrt()),
pinv_root: col(&keep, &|l| 1.0 / l.sqrt()),
null: col(&drop, &|_| 1.0),
rank: keep.len(),
eps,
};
let log_det = keep.iter().map(|&j| lam[j].ln()).sum();
Ok(MultivariateNormal { mean, cov, chol: Vec::new(), log_det, psd: Some(psd) })
}
impl MultivariateNormalQmc {
/// Samples from `N(mean, cov)` driven by `engine`, a Sobol sequence of dimension `d` (or
/// `2⌈d/2⌉` with `inv_transform = false`), plain or scrambled. With `inv_transform`, each
/// coordinate is `Φ⁻¹(½ + (1 − 10⁻¹⁰)(u − ½))` (SciPy's default); otherwise pairs of
/// coordinates go through the Box-Muller transform. The covariance's square root is its
/// Cholesky factor, or `V √Λ` from its eigendecomposition when it is only semidefinite.
pub fn new(mean: Vec<f64>, cov: &[Vec<f64>], inv_transform: bool, engine: SobolSequence) -> Result<Self, ErrorsJSL> {
let d = mean.len();
if d == 0 || cov.len() != d || cov.iter().any(|r| r.len() != d) {
return Err(ErrorsJSL::InvalidInputRange("MultivariateNormalQmc: the mean and covariance must have one dimension"));
}
let need = if inv_transform { d } else { 2 * d.div_ceil(2) };
if engine.dimension() != need {
return Err(ErrorsJSL::InvalidInputRange("MultivariateNormalQmc: the engine's dimension must be d (or 2⌈d/2⌉ without the inverse transform)"));
}
let root = match cholesky(cov) {
Some(l) => l,
None => {
let (lam, v) = crate::multivariate::symmetric_eigen_pub(cov);
if lam.iter().any(|&l| l < -1e-8) {
return Err(ErrorsJSL::InvalidInputRange("MultivariateNormalQmc: the covariance is not positive semidefinite"));
}
(0..d).map(|i| (0..d).map(|j| v[i][j] * lam[j].max(0.0).sqrt()).collect()).collect()
}
};
Ok(MultivariateNormalQmc { mean, root, inv_transform, engine })
}
/// The next `n` samples.
pub fn random(&mut self, n: usize) -> Vec<Vec<f64>> {
let d = self.mean.len();
(0..n)
.map(|_| {
let u = self.engine.next_point();
let z: Vec<f64> = if self.inv_transform {
u.iter().map(|&v| normal_quantile(0.5 + (1.0 - 1e-10) * (v - 0.5), 0.0, 1.0)).collect()
} else {
let mut z = Vec::with_capacity(u.len());
for p in u.chunks(2) {
let r = (-2.0 * p[0].ln()).sqrt();
let t = 2.0 * std::f64::consts::PI * p[1];
z.push(r * t.cos());
z.push(r * t.sin());
}
z.truncate(d);
z
};
(0..d).map(|i| self.mean[i] + (0..d).map(|k| self.root[i][k] * z[k]).sum::<f64>()).collect()
})
.collect()
}
}
/// Up to `n` new points (fewer when the box is full).
pub fn random<G: UniformGenerator>(&mut self, n: usize, rng: &mut G) -> Vec<Vec<f64>> {
let mut out = Vec::new();
if n == 0 {
return out;
}
if self.points.is_empty() {
let p: Vec<f64> = (0..self.d).map(|k| self.lower[k] + rng.next_f64() * (self.upper[k] - self.lower[k])).collect();
self.add(p, &mut out);
}
while !self.pool.is_empty() && out.len() < n {
let at = (rng.next_u64() % self.pool.len() as u64) as usize;
let centre = self.points[self.pool.swap_remove(at)].clone();
for _ in 0..self.ncandidates {
let dir: Vec<f64> = (0..self.d).map(|_| Self::normal(rng)).collect();
let norm = dir.iter().map(|v| v * v).sum::<f64>().sqrt().max(f64::MIN_POSITIVE);
let r = match self.hypersphere {
Hypersphere::Volume => 2.0 * self.radius * rng.next_f64().powf(1.0 / self.d as f64),
Hypersphere::Surface => 1.001 * self.radius,
};
let cand: Vec<f64> = centre.iter().zip(&dir).map(|(c, v)| c + r * v / norm).collect();
if cand.iter().enumerate().any(|(k, &v)| v < self.lower[k] || v > self.upper[k]) || self.too_close(&cand) {
continue;
}
self.add(cand, &mut out);
if out.len() >= n {
break;
}
}
}
out
}
- The quasi-Monte Carlo functions take a random generator for the lattice shifts, so results are reproducible for a seed. With
lib_jsl_random::numpy::Pcg64::from_seed(seed), which reproduces NumPy’sdefault_rng(seed)bit for bit, the shifts are SciPy’s: a single estimate (_qmvnfor a given number of points) equals SciPy’s to rounding. The fullcdfcan still differ from SciPy’s in about the sixth digit: SciPy chooses the lattice vector of some sizes by anargminover values that tie to rounding, and its FFT breaks the tie differently from the library’s. The difference is within the error estimate. - The normal distribution function repeats the estimate with times more points until the error estimate is below
abseps(SciPy’s_qauto). The t distribution function makes a single estimate of points, as SciPy does. - The random generator is an argument of every quasi-Monte Carlo function, so a seeded
UniformRNGmakes the results repeatable.dunnett_confidence_intervaldraws one seed from the generator you pass and reuses it throughout its root finding. MultivariateNormalQmctakes anySobolSequence. With an unscrambled one it reproduces SciPy’s samples exactly.
In practice
The references are from SciPy 1.17.1, written by book/generator/data/make_mv214_refs.py. For the quasi-Monte Carlo results, the reference is SciPy run with many more points ( for the normal, four runs of for the t), and both the library’s and SciPy’s default runs are compared with it:
Table 10.14. Multivariate normal and t box probabilities: the library's estimate, and the errors of the library's and SciPy's default runs against a high-accuracy reference.
| Distribution function | Library (error estimate) | Library vs reference | SciPy vs reference |
|---|---|---|---|
| Bivariate normal (exact), 6 cases with r from −0.97 to 0.999 | — | 2e-16 | both exact |
| Normal, d = 3, a box | 0.1912648 (±1e-6) | 2e-7 | 2e-7 |
| Normal, d = 5, a box | 0.0052471 (±2e-7) | 8e-8 | 5e-8 |
| Normal, d = 8, a box | 0.0013965 (±9e-7) | 1e-7 | 4e-7 |
| t, d = 2, ν = 4, 1000 d points | 0.3527379 (±9e-5) | 7e-6 | 6e-5 |
| t, d = 3, ν = 3, 1000 d points | 0.6571449 (±2e-4) | 9e-5 | 7e-5 |
| t, d = 5, ν = 10, 1000 d points | 0.4752262 (±5e-4) | 9e-5 | 8e-5 |
Both reach the accuracy their error estimates promise. Neither is systematically better: the differences come from the random shifts.
Table 10.15. Singular normal densities, Dunnett's test, quasi-Monte Carlo normal samples and Poisson-disk sampling against SciPy.
| Function | Difference from SciPy |
|---|---|
| Singular normal (rank 2 in 4-D): logpdf, entropy; a point off the support | 4e-16 / 0; −∞ in both |
dunnett, two-sided: statistics; p-values (QMC) | 0; 2e-4 (p = 0.6201, 0.0060) |
dunnett, greater: statistics; p-values (QMC) | 0; 2e-5 (p = 0.3250, 0.0029) |
dunnett, less: statistics; p-values (QMC) | 0; 1e-5 (p = 0.9168, 0.9998) |
MultivariateNormalQmc, unscrambled Sobol, 16 samples: inverse transform; Box-Muller | 2e-15; 2e-16 |
PoissonDisk, r = 0.05, fill_space: points (mean of 5 seeds), volume; surface | 250 vs 250; 346 vs 347 |
Dunnett’s statistics are identical. The p-values differ by at most , within the error of the multivariate t integration SciPy and the library both use.
The confidence intervals, for the same data, against SciPy’s confidence_interval:
Table 10.16. Columns: Alternative and level, Library: intervals for drug A and drug B, Library vs SciPy (seed 1), SciPy seed 2 vs seed 1.
| Alternative and level | Library: intervals for drug A and drug B | Library vs SciPy (seed 1) | SciPy seed 2 vs seed 1 |
|---|---|---|---|
| two-sided, 95% confidence | [-1.256, 2.556] and [0.840, 4.416] | 7e-4 | 9e-4 |
| two-sided, 90% confidence | [-0.957, 2.257] and [1.120, 4.136] | 8e-4 | 1e-3 |
| greater, 95% confidence | [-0.959, inf] and [1.119, inf] | 5e-4 | 1e-3 |
| greater, 90% confidence | [-0.643, inf] and [1.415, inf] | 8e-4 | 1e-3 |
| less, 95% confidence | [-inf, 2.259] and [-inf, 4.137] | 5e-4 | 1e-3 |
| less, 90% confidence | [-inf, 1.943] and [-inf, 3.841] | 1e-4 | 8e-5 |
The library’s intervals differ from SciPy’s by at most , which is the difference between two runs of SciPy with different seeds (): SciPy’s own critical value is only good to its noise.
Figure 10.6. A Poisson-disk sample with radius 0.05 filling the unit square (left), and the same number of independent uniform points (right). The independent points clump and leave gaps; the Poisson-disk points are evenly spread but not regular.
Figure 10.7. The error of a 5-D normal box probability () against the number of points. Genz's transformation alone reduces the variance enormously, and the lattice rules converge faster than . At 1000 points the method is already about a hundred times more accurate than Monte Carlo with points.
Strengths
- Exact bivariate probabilities, and error-controlled ones in higher dimensions.
- Normal distributions with singular covariances, for degenerate models and constraints.
- Dunnett’s test with exact statistics, multivariate-t p-values and simultaneous confidence intervals.
Weaknesses
- The results depend on random lattice shifts, so they agree with SciPy only to their error estimates.
- The cost grows with dimension: beyond 20 or so dimensions, many more points are needed.
- No Poisson-disk
optimization(SciPy’srandom-cdandlloyd).
Exercises
- Show that for a standard bivariate normal with correlation .
- Why does integrating the first variable exactly reduce the dimension of the Genz integral to ?
- Show that the correlation of the Dunnett statistics and is .
- Why must the background grid’s cells have side at most ?
Hints and answers
- Write . The region is a wedge in the plane of angle , and the standard normal is rotationally symmetric.
- Its limits do not depend on any other variable, so its contribution is the constant factor .
- , and the variances are .
- The cell diagonal is then at most , so no two points with distance at least can share a cell.
Further reading
- A. Genz, “Numerical computation of multivariate normal probabilities”, Journal of Computational and Graphical Statistics 1 (1992) 141–149.
- A. Genz and F. Bretz, “Comparison of methods for the computation of multivariate t probabilities”, Journal of Computational and Graphical Statistics 11 (2002) 950–971.
- Z. Drezner and G. O. Wesolowsky, “On the computation of the bivariate normal integral”, Journal of Statistical Computation and Simulation 35 (1990) 101–107.
- D. Nuyens and R. Cools, “Fast algorithms for component-by-component construction of rank-1 lattice rules in shift-invariant reproducing kernel Hilbert spaces”, Mathematics of Computation 75 (2006) 903–920.
- C. W. Dunnett, “A multiple comparison procedure for comparing several treatments with a control”, Journal of the American Statistical Association 50 (1955) 1096–1121.
- R. Bridson, “Fast Poisson disk sampling in arbitrary dimensions”, SIGGRAPH Sketches (2007).