'''
Covariance models for the errors: iid, unequal group variance, compound
symmetry, AR(1), a target Greenhouse-Geisser epsilon and explicit matrices.
'''
# Copyright (C) 2026 Todd Pataky
from __future__ import annotations
import numpy as np
from . import _errors
def contrast_basis(k):
'''
Orthonormal (normalized Helmert) contrast basis for *k* repeated levels.
:Parameters:
- *k* --- number of levels
:Returns:
- A ((k-1) x k) array whose rows are orthonormal and orthogonal to the
constant vector
'''
k = int(k)
C = np.zeros((k - 1, k))
for i in range(1, k):
C[i - 1, :i] = 1.0
C[i - 1, i] = -float(i)
C[i - 1] /= np.sqrt(i * (i + 1.0))
return C
[docs]
def epsilon(S):
'''
Greenhouse-Geisser epsilon of a covariance matrix.
:Parameters:
- *S* --- (k,k) covariance matrix
:Returns:
- Epsilon (float).
:Example:
>>> import spm1d
>>> S = spm1d.rng.ar1( 4, 0.8 )
>>> print( round( spm1d.rng.epsilon( S ), 3 ) )
0.724
'''
S = np.asarray(S, dtype=float)
k = S.shape[0]
if k < 2:
return 1.0
C = contrast_basis(k)
T = C @ S @ C.T
m = k - 1
return float(np.trace(T) ** 2 / (m * np.trace(T @ T)))
def iid(k):
'''Identity covariance for *k* levels (independent, unit variance).'''
return np.eye(int(k))
[docs]
def compound_symmetry(k, rho):
'''
Compound-symmetric covariance with unit variances and constant correlation
*rho*.
:Parameters:
- *k* --- number of levels
- *rho* --- common correlation in (-1 / (k - 1), 1)
:Returns:
- (k,k) covariance matrix
:Example:
>>> import spm1d
>>> S = spm1d.rng.compound_symmetry( 3, 0.5 )
>>> print( S )
[[1. 0.5 0.5]
[0.5 1. 0.5]
[0.5 0.5 1. ]]
>>> print( spm1d.rng.epsilon( S ) )
1.0
:Note:
- Use :func:`ar1` or :func:`from_epsilon` for non-spherical covariance.
'''
k = int(k)
if k < 2:
raise _errors.SPM1DRngError(f'Compound symmetry needs at least two repeated-measures cells; this '
f'design has {k}. Use cov_model="iid" and model unequal group variance with "sd".')
if not (-1.0 / (k - 1) < rho < 1.0):
raise _errors.SPM1DRngError(f'rho must lie in (-1/(k-1), 1) = ({-1.0 / (k - 1)}, 1); the given value is {rho}.')
return (1.0 - rho) * np.eye(k) + rho * np.ones((k, k))
[docs]
def ar1(k, rho):
'''
First-order autoregressive covariance ``S[i,j] = rho ** |i - j|``.
:Parameters:
- *k* --- number of levels
- *rho* --- autocorrelation in (-1, 1)
:Returns:
- (k,k) covariance matrix
:Example:
>>> import spm1d
>>> S = spm1d.rng.ar1( 3, 0.5 )
>>> print( S )
[[1. 0.5 0.25]
[0.5 1. 0.5 ]
[0.25 0.5 1. ]]
>>> print( round( spm1d.rng.epsilon( S ), 3 ) )
0.925
'''
k = int(k)
if not (-1.0 < rho < 1.0):
raise _errors.SPM1DRngError(f'rho must lie in (-1, 1); the given value is {rho}.')
i = np.arange(k)
return np.asarray(float(rho)) ** np.abs(i[:, None] - i[None, :])
[docs]
def from_epsilon(k, eps):
'''
Covariance with a specified Greenhouse-Geisser epsilon.
Variances are normalized to average 1.
:Parameters:
- *k* --- number of levels
- *eps* --- target epsilon in ``[1/(k-1), 1]``
:Returns:
- (k,k) covariance matrix
:Example:
>>> import spm1d
>>> S = spm1d.rng.from_epsilon( 3, 0.7 )
>>> print( round( spm1d.rng.epsilon( S ), 3 ) )
0.7
>>> y, A, SUBJ = spm1d.rng.anova1rm( nlevels=3, nsubj=8, cov=S, seed=0 ) # 0D data with that covariance
'''
k = int(k)
m = k - 1
if k < 2:
raise _errors.SPM1DRngError(f'A target epsilon needs at least two repeated-measures cells; this '
f'design has {k}. Use cov_model="iid" and model unequal group variance with "sd".')
if k == 2:
if not np.isclose(eps, 1.0):
raise _errors.SPM1DRngError('With two levels epsilon is always 1. Sphericity cannot be violated.')
return np.eye(2)
lo = 1.0 / m
if not (lo - 1e-12 <= eps <= 1.0 + 1e-12):
raise _errors.SPM1DRngError(f'epsilon must lie in [1/(k-1), 1] = [{lo}, 1]; the given value is {eps}.')
eps = float(np.clip(eps, lo, 1.0))
a, b, c = eps * m - 1.0, 2.0 * m * (eps - 1.0), m ** 2 * (eps - 1.0)
if abs(a) < 1e-12:
# eps == 1/(k-1) is the lower bound, approached as delta grows
d = 1e8
else:
disc = max(b * b - 4 * a * c, 0.0)
roots = [(-b + s * np.sqrt(disc)) / (2 * a) for s in (1, -1)]
pos = [r for r in roots if r >= -1e-9]
d = max(pos) if pos else 0.0
lam = np.ones(m)
lam[0] = 1.0 + max(d, 0.0)
C = contrast_basis(k)
S = C.T @ np.diag(lam) @ C + np.ones((k, k)) / k # contrast part + mean direction
return S / np.mean(np.diag(S)) # normalize to average unit variance
def build(k, model='iid', rho=None, eps=None, cov=None):
'''
Build a within-subject covariance matrix from a model name.
:Parameters:
- *k* --- number of repeated levels
- *model* --- ``'iid'``, ``'cs'``, ``'ar1'``, ``'epsilon'`` or
``'explicit'`` (``'explicit'`` is implied when *cov* is given)
- *rho* --- correlation for ``'cs'`` and ``'ar1'``
- *eps* --- target Greenhouse-Geisser epsilon for ``'epsilon'``
- *cov* --- an explicit (k,k) covariance matrix
:Returns:
- A (k,k) covariance matrix with average unit variance.
'''
if cov is not None:
return validate(cov, k)
model = str(model).lower()
if model == 'explicit':
# "explicit" means the cov argument itself.
raise _errors.SPM1DRngError('cov_model="explicit" requires an explicit matrix. Pass it as "cov".')
if model == 'iid':
return iid(k)
if model in ('cs', 'compound_symmetry'):
if rho is None:
raise _errors.SPM1DRngError("Compound symmetry requires 'rho'.")
return compound_symmetry(k, rho)
if model == 'ar1':
if rho is None:
raise _errors.SPM1DRngError("AR(1) requires 'rho'.")
return ar1(k, rho)
if model in ('epsilon', 'eps'):
if eps is None:
raise _errors.SPM1DRngError("The 'epsilon' model requires 'eps'.")
return from_epsilon(k, eps)
raise _errors.SPM1DRngError(f"Unknown covariance model {model!r}; expected one of "
"'iid', 'cs', 'ar1', 'epsilon', 'explicit'.")
def validate(S, k=None, tol=1e-8):
'''Check that *S* is a square symmetric positive semi-definite matrix.'''
S = np.asarray(S, dtype=float)
if S.ndim != 2 or S.shape[0] != S.shape[1]:
raise _errors.SPM1DRngError(f'Covariance must be a square matrix; the given matrix has shape {S.shape}.')
if (k is not None) and (S.shape[0] != k):
raise _errors.SPM1DRngError(f'Covariance must be ({k} x {k}); the given matrix has shape {S.shape}.')
if not np.allclose(S, S.T, atol=tol):
raise _errors.SPM1DRngError('Covariance matrix must be symmetric.')
w = np.linalg.eigvalsh(S)
if w.min() < -tol * max(1.0, abs(w.max())):
raise _errors.SPM1DRngError(f'Covariance matrix must be positive semi-definite '
f'(smallest eigenvalue {w.min():.3g}).')
return S
def cholesky(S, tol=1e-10):
'''
Lower-triangular factor *L* with ``L @ L.T == S``. Eigendecomposition is
used when *S* is not positive definite.
'''
S = np.asarray(S, dtype=float)
try:
return np.linalg.cholesky(S)
except np.linalg.LinAlgError:
w, V = np.linalg.eigh(S)
w = np.clip(w, 0.0, None)
return V @ np.diag(np.sqrt(w)) * (np.abs(w).max() > tol)