# Copyright (C) 2026 Todd Pataky
import numpy as np
from .. _dec import docdims, checkargs
def _assemble_spm_objects(design, model, fit, teststats, roi=None, _fwhm_method='taylor2007'):
if fit.dvdim==0:
from ... _results import SPM0D
spm = [SPM0D(design, model, fit, s) for s in teststats]
else:
from ... _results import SPM1D
spm = [SPM1D(design, model, fit, s, roi, _fwhm_method=_fwhm_method) for s in teststats]
if len(spm)==1:
spm = spm[0]
else:
from ... _results import SPMList
# Each member knows which of the design's contrasts it is. A t
# contrast carries no index.
for k, s in enumerate( spm ):
if getattr( s._teststat, 'ind', None ) is None:
s._teststat.ind = k
spm = SPMList( spm )
return spm
# Subject count at or below which a requested non-sphericity correction is
# reported because the corrected test is conservative at such small samples.
NSUBJ_WARN_MAX = 5
def _nsubj(design):
"""Number of subjects if present, otherwise None."""
for f in getattr(design, 'factors', []) or []:
if getattr(f, 'name', None) == 'SUBJ':
return int( f.nlevels )
return None
def _check_nonsphericity(design, cov_model, spm):
"""
Warn if a repeated-measures design with a covariance model has few
subjects.
"""
import numpy as np
from ... exceptions import SPM1DNonSphericityWarning
from ... _settings import settings, _user_stacklevel
if not settings.warnings_on:
return
if not getattr(design, 'isrm', False):
return
if isinstance(cov_model, str) and cov_model == 'iid':
return
n = _nsubj( design )
if (n is None) or (n > NSUBJ_WARN_MAX):
return
spms = spm if hasattr(spm, '__len__') else [spm]
df0s = getattr(design, 'df0list', None) or [ getattr(design, 'df0', None) ]
worst = None
for s, df0 in zip(spms, df0s):
if df0 is None:
continue
df1n = float( df0[0] )
if df1n < 1:
continue
df1 = float( np.ravel( s.df )[0] )
eps = df1 / df1n
# At the clamp the rate is nominal. A small tolerance keeps floating
# point from turning "at the bound" into "just above it".
if eps <= (1.0 / df1n) + 1e-9:
continue
if (worst is None) or (eps < worst):
worst = eps
if worst is None:
return
msg = (
f'Non-sphericity correction applied with {n} subjects (estimated epsilon '
f'{worst:.2f}). Corrections have known limitations for small samples '
f'with high non-sphericity. Pass cov_model="iid" to assume sphericity '
f'instead. Refer to the non-sphericity page in the documentation.'
)
settings._warn_once( msg, SPM1DNonSphericityWarning, stacklevel=_user_stacklevel() + 1 )
def _glm_via_design(y, design, cov_model='unstructured', roi=None, _Xeff=None, _use_reml_sc=False, _fwhm_method='taylor2007', _whiten=False):
'''
Fit a design object (internal glm interface).
'''
from . models import GeneralLinearModel
y = design.validate( y ) # returns the coerced array
if isinstance(cov_model, str):
QQ = design.get_variance_model( cov_model )
else:
QQ = cov_model # an explicit list of covariance components
E = design.get_error_terms()
if (QQ is not None) and any( e is not None for e in E ):
# A non-residual error term and a ReML covariance model cannot be
# combined.
from ... exceptions import SPM1DError
raise SPM1DError(
f'In "{design._testname}" at least one effect is tested against another effect '
'rather than against the residual, and no covariance '
'correction is defined for that combination. Pass '
'cov_model="iid".' )
model = GeneralLinearModel(design.X, design.df0, QQ)
fit = model.fit( y )
C = design.get_contrast_matrices()
# roi is a property of the inference and is applied by SPM1D.inference().
# _assemble_spm_objects stores it for the deprecation shim.
teststats = fit.calculate_teststats(C, _Xeff=_Xeff, _use_reml_sc=_use_reml_sc, _whiten=_whiten, E=E)
spm = _assemble_spm_objects(design, model, fit, teststats, roi=roi, _fwhm_method=_fwhm_method)
_check_nonsphericity( design, cov_model, spm )
return spm
[docs]
@checkargs
@docdims('univariate')
def glm(y, X, C, QQ=None, roi=None, _Xeff=None, _fwhm_method='taylor2007', _whiten=False):
'''
General Linear Model with an explicit design matrix and contrast(s).
::
spm = spm1d.stats.glm( y, X, c ) # one contrast
FF = spm1d.stats.glm( y, X, [c0, c1, C2] ) # several contrasts
1D and 2D contrast arrays correspond to t and F contrasts, respectively.
One SPM object is returned for each contrast.
:Parameters:
- *y* --- (J,) array for 0D data or (J,Q) array for 1D data
- *X* --- (J,n) design matrix
- *C* --- Contrast or contrast list
- *QQ* --- list of (J,J) covariance component matrices (default iid)
- *roi* --- DEPRECATED (use ``inference``)
:Returns:
- SPM or SPMList object
:Example:
Two-sample t test using spm1d.stats.glm:
>>> import numpy as np
>>> import spm1d
>>> rng = np.random.default_rng( 0 )
>>> y = rng.standard_normal( 20 )
>>> X = np.zeros( (20, 2) )
>>> X[:10, 0] = 1
>>> X[10:, 1] = 1
>>> spm = spm1d.stats.glm( y, X, [1, -1] )
>>> print( spm )
SPM{t} (0D)
fn_name : glm
STAT : T
name : contrast 0
z : 1.40714
df : (1, 18)
'''
from . design.designs import GLM
design = GLM(X, C)
return _glm_via_design(y, design, QQ, roi, _Xeff=_Xeff, _fwhm_method=_fwhm_method, _whiten=_whiten)
def _glm_formula_mv(formula, data, y, subject=None, cov_model=None, roi=None, _fwhm_method='taylor2007'):
'''
Multivariate general fixed-effects design built from a formula.
'''
from ... exceptions import SPM1DError
from . design.designs_mv import MVFORMULA
from .. _mv._mvfit import run_glm_list
from .. _mv.manova import _cov_model_iid
from . cov import UNSET
if subject is not None:
raise SPM1DError(
'A multivariate formula model is fitted on independent observations '
'only. Remove subject=, or use hotellings_paired for two conditions.' )
_cov_model_iid( 'formula', UNSET if (cov_model is None) else cov_model, UNSET )
if y.ndim == 1:
raise SPM1DError( '"y" is a 1D array. multivariate=True requires "y" with shape (J,I) for 0D data '
'and (J,Q,I) for 1D data, where J, Q, and I are the numbers of observations, '
'domain points, and vector components, respectively, and where I>1.' )
design = MVFORMULA( formula, data )
y = design.validate( y )
# Fit-time note as for manova1. One two-level factor alone is a two-sample
# Hotelling's T2 test in disguise.
if (len( design.factors ) == 1) and (not getattr( design, 'covariates', None )):
from .. _argchecks import warn_two_levels
warn_two_levels( 'manova1', design.factors[0].A )
# the multivariate smoothness estimator that the named procedures use
fwhm = 'taylor2008' if (_fwhm_method == 'taylor2007') else _fwhm_method
return run_glm_list( design, y, roi=roi, _fwhm_method=fwhm )