Source code for spm1d.rng._generators

'''
Random dataset generators. Datasets are generated from the model:

.. math::

    y = \\mu(\\mathrm{cell}) + X\\beta + s + e

where :math:`\\mu` are the true cell means, :math:`X\\beta` is the covariate
contribution, :math:`s` is a subject random effect and :math:`e` is the error.
'''

# Copyright (C) 2026  Todd Pataky

from __future__ import annotations

import numpy as np
from . import _errors

from . import _cov, _design, _fields


[docs] class Dataset: ''' A generated dataset. :Attributes: - *Y* --- (J,Q) data array or (J,) data array for 0D data - *factors* --- list of (J,1) discrete factor level vectors - *SUBJ* --- (J,1) subject labels if present, otherwise ``None`` - *X* --- (J,ncov) covariate values if present, otherwise ``None`` - *design* --- **Design** used ''' def __init__(self, Y, factors, SUBJ=None, X=None, design=None): #: Data as a ``(J,Q)`` array for 1D data or a ``(J,)`` array for 0D #: data (``(J,Q,I)`` or ``(J,I)`` for multivariate data). self.Y = Y #: One ``(J,)`` integer level vector per factor. self.factors = list(factors) #: Subject labels as a ``(J,)`` integer array if present, otherwise #: None. self.SUBJ = SUBJ #: Covariate values as a ``(J, ncov)`` array if present, otherwise #: None. self.X = X #: :class:`spm1d.rng.Design` the dataset was drawn from. self.design = design def __repr__(self): s = f'Dataset(Y={self.Y.shape}, factors={len(self.factors)}' if self.X is not None: s += f', covariates={self.X.shape[1]}' if self.SUBJ is not None: s += f', subjects={np.unique(self.SUBJ).size}' return s + ')'
[docs] def astuple(self): ''' Data as a tuple ordered for the spm1d.stats call signatures. :Returns: - ``(Y, *factors, *covariates, SUBJ)`` with absent items omitted :Example: >>> import spm1d >>> g = spm1d.rng.ANOVA( (2, 3), rm='B', nsubj=8, Q=101, fwhm=20, seed=0 ) >>> y, A, B, SUBJ = g.random().astuple() >>> spmi = spm1d.stats.anova2onerm( y, A, B, SUBJ ).inference( 0.05 ) ''' out = [self.Y] + list(self.factors) if self.X is not None: out += [self.X[:, i] for i in range(self.X.shape[1])] if self.SUBJ is not None: out += [self.SUBJ] return tuple(out)
[docs] class ANOVA: ''' Random dataset generator for *n*-way ANOVA designs. :Parameters: - *nlevels* --- number of levels of each factor such as ``(2, 3)`` - *rm* --- repeated-measures factors as labels (``'AB'``) or indices. ``None`` (default) means all factors and ``''`` means none. - *nsubj* --- subjects per between-subject group or observations per cell (between-subject designs). A scalar gives a balanced design. A sequence gives unequal sample sizes. - *nrep* --- observations per subject per repeated-measures cell - *Q* --- number of continuum nodes. 1 (default) gives 0D data - *fwhm* / *lkc* --- 1D smoothness as full-width at half-maximum or Lipschitz-Killing curvature (specify exactly one) - *mu* --- true cell means as a scalar, an array shaped like *nlevels* or (for 1D data) an array shaped ``nlevels + (Q,)`` - *sd* --- error standard deviation as a scalar or as an array shaped like *nlevels* for unequal group variance - *cov* --- explicit covariance matrix over the repeated-measures cells - *cov_model* --- ``'iid'``, ``'cs'``, ``'ar1'`` or ``'epsilon'`` - *rho* --- correlation for ``'cs'`` and ``'ar1'`` - *eps* --- target Greenhouse-Geisser epsilon for ``'epsilon'`` - *ncomp* --- number of vector components (default 1) - *comp_cov_model* / *comp_rho* / *comp_eps* / *comp_cov* --- covariance between components (same values as *cov_model*) - *subject_sd* --- standard deviation of the subject random effect - *seed* --- seed for reproducible output :Example: >>> g = rng.ANOVA((2, 3), rm='B', nsubj=8, mu=[[0, 0, 1], [0, 0, 1]], sd=1) >>> data = g.random() >>> y, A, B, SUBJ = data.astuple() ''' def __init__(self, nlevels, rm=None, nsubj=10, nrep=1, Q=1, fwhm=None, lkc=None, mu=0.0, sd=1.0, cov=None, cov_model='iid', rho=None, eps=None, ncomp=1, comp_cov=None, comp_cov_model='iid', comp_rho=None, comp_eps=None, subject_sd=0.0, ncov=0, slopes=0.0, covariate_kind='normal', covariate_values=None, labels=None, seed=None): #: Design object (:class:`spm1d.rng.Design`). self.design = _design.Design(nlevels, rm=rm, nsubj=nsubj, nrep=nrep, labels=labels) #: Number of domain nodes (1 for 0D data). self.Q = int(Q) if self.Q < 1: raise _errors.SPM1DRngError(f'Q must be at least 1; the given value is {Q}.') #: Field smoothness as full width at half maximum (``fwhm``) and #: Lipschitz-Killing curvature (``lkc``). None for 0D data. self.fwhm, self.lkc = _fields.resolve_smoothness(self.Q, fwhm, lkc) #: True cell means as an ``(ncells, Q)`` array. self.mu = self._parse_mu(mu) #: Error standard deviation of each cell as an ``(ncells,)`` array. self.sd = self._parse_sd(sd) #: Standard deviation of the subject random effect. self.subject_sd = float(subject_sd) if self.subject_sd < 0: raise _errors.SPM1DRngError(f'subject_sd must be non-negative; the given value is {subject_sd}.') # "cov" carries its own variances. "sd" scales cov_within. Giving both # would apply the scale twice. if (cov is not None) and (np.asarray(sd, dtype=float) != 1.0).any(): raise _errors.SPM1DRngError('Specify either "cov" or a non-default "sd", not both. Fold the variances into "cov" or use a ' 'named cov_model with "sd".') #: Covariance over the repeated-measures cells as an ``(nrmcells, #: nrmcells)`` array. self.cov_within = _cov.build(self.design.nrmcells, model=cov_model, rho=rho, eps=eps, cov=cov) #: Number of vector components (1 for univariate data). self.I = int(ncomp) if self.I < 1: raise _errors.SPM1DRngError(f'ncomp must be at least 1; the given value is {ncomp}.') #: Covariance between vector components as an ``(I, I)`` array if #: present, otherwise None. self.cov_comp = None if self.I > 1: self.cov_comp = _cov.build(self.I, model=comp_cov_model, rho=comp_rho, eps=comp_eps, cov=comp_cov) self._chol_comp = _cov.cholesky( self.cov_comp ) elif (comp_cov is not None) or (comp_cov_model != 'iid'): raise _errors.SPM1DRngError('A component covariance needs more than one component. ' f'ncomp is {self.I}. Set ncomp to the number of vector ' 'components (e.g. 3 for a 3D marker trajectory).') #: Number of covariates (0 for an ANOVA design). self.ncov = int(ncov) #: True covariate slopes as an ``(ncov, Q)`` array. self.slopes = self._parse_slopes(slopes) #: Covariate value distribution (``"normal"``, ``"uniform"`` or #: ``"given"``). self.covariate_kind = covariate_kind #: Covariate values given at construction if present, otherwise None. self.covariate_input = covariate_values #: Random seed given at construction if present, otherwise None. self.seed = seed self._rng = np.random.default_rng(seed) #: Full covariance over observations as a ``(J, J)`` array. self.cov = self._build_covariance() self._chol = _cov.cholesky(self.cov) def __repr__(self): s = f'{self.__class__.__name__}({self.design!r}, Q={self.Q}' if self.fwhm is not None: s += f', fwhm={self.fwhm:.3f}, lkc={self.lkc:.3f}' if self.ncov: s += f', covariates={self.ncov}' return s + ')' def _broadcast_over_components(self, a): '''Add a (J,Q) mean or covariate term to a (J,Q,I) array.''' return a if (self.I == 1) else np.asarray(a)[:, :, None] def _build_covariance(self): ''' Covariance of the *J* observations. ''' d = self.design J = d.J sd = self.sd[d.cell] # per-observation standard deviation S = np.zeros((J, J)) rmcell = d.rmcell if d.is_rm: rep = d.replicate() for i in range(J): for j in range(J): if d.SUBJ[i] != d.SUBJ[j]: continue if rep[i] == rep[j]: # same replicate and therefore correlated across cells S[i, j] += sd[i] * sd[j] * self.cov_within[rmcell[i], rmcell[j]] S[i, j] += self.subject_sd ** 2 # subject random effect else: S[np.diag_indices(J)] = sd ** 2 if self.subject_sd: raise _errors.SPM1DRngError('"subject_sd" requires a repeated-measures design.') return S @property def _cellshape(self): return self.design.nlevels if self.design.nfactors else (1,) def _parse_mu(self, mu): '''True cell means as a (ncells,Q) array.''' ncells = self.design.ncells mu = np.asarray(mu, dtype=float) if mu.ndim == 0: return np.full((ncells, self.Q), float(mu)) if mu.shape == self._cellshape: # one mean per cell return np.repeat(mu.reshape(ncells, 1), self.Q, axis=1) if mu.shape == tuple(self._cellshape) + (self.Q,): # a continuum per cell return mu.reshape(ncells, self.Q) if (self.Q > 1) and (mu.shape == (self.Q,)): # one continuum for all cells return np.repeat(mu.reshape(1, self.Q), ncells, axis=0) raise _errors.SPM1DRngError(f'"mu" must be a scalar, or have shape {self._cellshape}' + (f', {self._cellshape + (self.Q,)} or ({self.Q},)' if self.Q > 1 else '') + f'; the given array has shape {mu.shape}.') def _parse_sd(self, sd): '''Error standard deviation as one value per cell.''' ncells = self.design.ncells sd = np.asarray(sd, dtype=float) if sd.ndim == 0: sd = np.full(ncells, float(sd)) elif sd.shape == self._cellshape: sd = sd.reshape(ncells) else: raise _errors.SPM1DRngError(f'"sd" must be a scalar or have shape {self._cellshape}; ' f'the given array has shape {sd.shape}.') if np.any(sd < 0): raise _errors.SPM1DRngError('"sd" must be non-negative.') return sd def _parse_slopes(self, slopes): '''Covariate slopes as an (ncov,Q) array.''' if not self.ncov: return None b = np.asarray(slopes, dtype=float) if b.ndim == 0: return np.full((self.ncov, self.Q), float(b)) if b.shape == (self.ncov,): return np.repeat(b.reshape(self.ncov, 1), self.Q, axis=1) if b.shape == (self.ncov, self.Q): return b if (self.Q > 1) and (b.shape == (self.Q,)) and (self.ncov == 1): return b.reshape(1, self.Q) raise _errors.SPM1DRngError(f'"slopes" must be a scalar or have shape ({self.ncov},) ' f'or ({self.ncov}, {self.Q}); the given array has shape {b.shape}.') @property def epsilon(self): '''Greenhouse-Geisser epsilon of the within-subject covariance.''' return _cov.epsilon(self.cov_within) if self.design.nrmcells > 1 else 1.0
[docs] def random(self): ''' Generate one random dataset. :Returns: - A **Dataset** instance :Example: >>> import spm1d >>> g = spm1d.rng.ANOVA( (2, 3), rm='B', nsubj=8, Q=101, fwhm=20, seed=0 ) >>> y, A, B, SUBJ = g.random().astuple() >>> print( y.shape ) (48, 101) ''' d = self.design if self.I == 1: Z = _fields.white_noise(d.J, self.Q, fwhm=self.fwhm, rng=self._rng) Y = self._chol @ Z # impose the covariance across observations else: # One independent smooth field per component is mixed along the # component axis by chol(W). The total covariance is Sigma_obs (x) # W with the same W at every node. Neither mixing changes the FWHM # (see the W(q) note in the module docstring). Z = np.dstack([_fields.white_noise(d.J, self.Q, fwhm=self.fwhm, rng=self._rng) for _ in range(self.I)]) Y = np.einsum('jk,kqi->jqi', self._chol, Z) Y = Y @ self._chol_comp.T Y = Y + self._broadcast_over_components( self.mu[d.cell] ) # true cell means X = None if self.ncov: X = _design.covariate_values(d.J, self.ncov, kind=self.covariate_kind, rng=self._rng, values=self.covariate_input) Y = Y + self._broadcast_over_components( X @ self.slopes ) # Shapes follow spm1d.stats. Univariate data are (J,) or (J,Q) and # multivariate data (J,I) or (J,Q,I). if self.Q == 1: Y = Y.reshape(d.J, self.I) if (self.I > 1) else Y.flatten() return Dataset(Y, d.factors, SUBJ=d.SUBJ, X=X, design=d)
[docs] def random_many(self, n): ''' Generate *n* datasets. :Parameters: - *n* --- number of datasets :Returns: - List of *n* **Dataset** instances :Example: >>> import spm1d >>> g = spm1d.rng.ANOVA( (2, 3), rm='B', nsubj=8, Q=101, fwhm=20, seed=0 ) >>> datasets = g.random_many( 10 ) >>> print( len( datasets ) ) 10 ''' return [self.random() for _ in range(int(n))]
[docs] class ANCOVA(ANOVA): ''' Random dataset generator for ANCOVA designs. :Parameters: In addition to the **ANOVA** parameters: - *ncov* --- number of continuous covariates (default 1) - *slopes* --- true slope of each covariate as a scalar, an (ncov,) array or an (ncov,Q) array for 1D data - *covariate_kind* --- ``'normal'`` or ``'uniform'`` - *covariate_values* --- explicit (J,ncov) covariate values :Example: >>> g = rng.ANCOVA((2,), nsubj=12, rm='', ncov=1, slopes=0.5, mu=[0, 1]) >>> y, A, x = g.random().astuple() ''' def __init__(self, nlevels, ncov=1, slopes=1.0, **kwargs): if int(ncov) < 1: raise _errors.SPM1DRngError('ANCOVA requires at least one covariate. Use ANOVA instead.') kwargs.setdefault('rm', '') if np.ndim(nlevels) == 0: nlevels = (int(nlevels),) # one factor super().__init__(nlevels, ncov=ncov, slopes=slopes, **kwargs)
[docs] class Regression(ANOVA): ''' Random dataset generator for regression with continuous predictors only. :Parameters: - *J* --- number of observations - *ncov* --- number of predictors (default 1) - *slopes* --- true slope of each predictor - **ANOVA** parameters controlling data type, smoothness and error :Example: >>> g = rng.Regression(J=20, slopes=0.8, Q=101, fwhm=20) >>> y, x = g.random().astuple() ''' def __init__(self, J=20, ncov=1, slopes=1.0, **kwargs): if int(ncov) < 1: raise _errors.SPM1DRngError('Regression requires at least one predictor.') kwargs.pop('rm', None) kwargs.pop('nsubj', None) super().__init__((), rm='', nsubj=J, ncov=ncov, slopes=slopes, **kwargs)