Source code for spm1d.stats._glm.ui

# 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)
[docs] @checkargs @docdims('multivariate') def formula(formula, data, subject=None, cov_model=None, roi=None, multivariate=None, _fwhm_method='taylor2007'): ''' Formula-based model specification. :: spm = spm1d.stats.formula( 'y ~ A * B + x', data ) FF = spm1d.stats.formula( 'y ~ A * B', data, subject='SUBJ' ) The response (left of ``~``) must be a variable in ``data`` (dict). Integer-, boolean- and string-valued variables are factors. Float-valued variables are covariates. ``C(name)`` forces a factor. Integer-valued covariates must be converted using x.astype(float). Formulas describing named designs build those designs with factors named after the formula variables (e.g., ``Main supp``, ``Interaction supp:dose``, ``supp0 - supp1``). Other formulas fit fixed effects on independent observations with one adjusted F test per term. See :doc:`/api/formulas`. Single-term formulas return an SPM object. Multi-term formulas return an **SPMList**. **Multivariate formula**:: FF = spm1d.stats.formula( 'Y ~ A * B + x', data ) # Y: (J, Q, I) FF = spm1d.stats.formula( 'Y ~ A + x', data, multivariate=True ) # Y: (J, I), 0D Responses with an extra dimension (e.g., (J, Q, I) for 1D data) are tested with Wilks' lambda (as Rao's F) with one pooled covariance (MANOVA, MANCOVA or multivariate regression). ``subject`` is not supported for vector responses. A (J, I) response is read as 1D univariate data unless ``multivariate=True``. :Parameters: - *formula* --- Model formula such as ``'y ~ A * B + x'`` - *data* --- mapping from variable names to per-observation arrays - *subject* --- Subject variable name in ``data`` (repeated-measures formulas) - *cov_model* --- ``'iid'`` or ``'unstructured'``. Default None uses the named design default (otherwise ``'unstructured'`` with factors and ``'iid'`` without). - *roi* --- DEPRECATED (use ``inference``) - *multivariate* --- True to read a (J,I) response as 0D multivariate data :Returns: - An SPM (one term) or an **SPMList** (several terms) :Example: A formula on the R "ToothGrowth" dataset (2 x 3 design): >>> import spm1d >>> import jikudata as jd >>> dataset = jd.R_ToothGrowth() >>> A, B = dataset.x.T # (60,) arrays of factor labels >>> data = dict( y=dataset.y, supp=A, dose=B ) >>> spmi = spm1d.stats.formula( 'y ~ supp * dose', data, cov_model='iid' ).inference( 0.05 ) # one pooled variance as in the classical ANOVA >>> print( spmi ) SPMiList STAT : F fn_name : formula formula : y ~ supp * dose nfactors : 2 neffects : 3 Effects supp z=15.572 df=(1, 54) p=<0.001 dose z=92.000 df=(2, 54) p=<0.001 supp:dose z=4.107 df=(2, 54) p=0.02186 The example datasets require the jiku-data package: ``pip install "spm1d[data]"``. ''' from . design.formula import from_formula, response as _response from . design.designs import FORMULA from . cov import resolve_cov_model, UNSET from ... exceptions import SPM1DError from .. _argchecks import warn_two_levels y = _response( formula, data ) if y is None: raise SPM1DError( f'The formula "{formula}" has no response variable. Write "y ~ ..." with "y" a variable in data.' ) y = np.asarray( y ) if multivariate is None: multivariate = (y.ndim == 3) if multivariate: spm = _glm_formula_mv( formula, data, y, subject=subject, cov_model=cov_model, roi=roi, _fwhm_method=_fwhm_method ) else: design = from_formula( formula, data, subject ) if design._testname in ('anova1', 'anova1rm'): warn_two_levels( design._testname, design.factors[0].A ) # The default is the named procedure's. Independent-groups designs get # a per-group variance. The one-way repeated-measures design gets the # within-subject covariance. Designs that test against subject strata # get one pooled residual. A general formula gets one variance per # cell or one pooled residual without factors. if isinstance( design, FORMULA ): default = 'unstructured' if design.factors else 'iid' else: default = 'unstructured' if design._testname in ('anova1', 'anova2', 'anova3', 'ancova', 'ttest2', 'anova1rm') else 'iid' cm = resolve_cov_model( UNSET if (cov_model is None) else cov_model, default=default ) spm = _glm_via_design( y, design, cm, roi, _fwhm_method=_fwhm_method ) spm._set_fn_name( 'formula', formula ) return spm
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 )