Source code for spm1d._results.effectsize


'''
Effect size.
'''

# Copyright (C) 2026  Todd Pataky


import numpy as np
from .. util._serial import AttrDictSerial


def _hedges_J(v):
    """
    Hedges' small-sample correction factor J = gamma(v/2) / ( sqrt(v/2) *
    gamma((v-1)/2) ).
    """
    from scipy.special import gammaln
    v = float(v)
    if not (v > 1.0):
        return np.nan
    return float( np.exp( gammaln(v / 2.0) - gammaln((v - 1.0) / 2.0) )
                  / np.sqrt(v / 2.0) )


[docs] class EffectSize(AttrDictSerial): ''' Effect size object. :Attributes: - *z* --- primary effect size measure: scalar (0D) or field (1D) - *name* --- name of the ``z`` measure - *standardizer* --- ``classical`` or ``model`` (see SPM.effect_size) - *d*, *g* --- Cohen's d and Hedges' g (t contrasts only) - *eta2p*, *eta2*, *omega2* --- partial eta squared, eta squared and omega squared (F contrasts only) - *D* --- Mahalanobis distance (Hotelling's T2 only) - *wilks* --- Wilks' lambda (MANOVA, MANCOVA and CCA only) - *df* --- degrees of freedom of the contrast - *dim* --- data dimensionality (0 or 1) ''' #: Cohen's d (t contrasts only). d = None #: Hedges' g (t contrasts only). g = None #: Partial eta squared (F contrasts only). eta2p = None #: Eta squared (ANOVA F contrasts only). eta2 = None #: Omega squared (ANOVA F contrasts only). omega2 = None #: Mahalanobis distance (Hotelling's T2 only). D = None #: Wilks' lambda (MANOVA, MANCOVA and CCA effects only). wilks = None def __init__(self, z, name, standardizer, df, dim, **extra): #: Effect size: float (0D) or ``(Q,)`` array (1D). Measure name: #: ``name``. self.z = z #: Name of the ``z`` measure (e.g., "Cohen's d"). self.name = name #: Standardizer: ``"classical"`` (pooled sample SD) or ``"model"`` #: (fitted model error variance). self.standardizer = standardizer #: Contrast degrees of freedom as ``(df1, df2)``. self.df = df #: Data dimensionality (0 or 1). self.dim = dim for k in ('d', 'g', 'eta2p', 'eta2', 'omega2', 'D', 'wilks'): setattr(self, k, extra.get(k)) @property def dfs(self): '''Degrees of freedom ``df`` as a string such as ``"(1, 21)"``.''' from .. util._str import dflist2str return dflist2str( self.df ) def __repr__(self): s = 'Effect size (%dD)\n' % self.dim s += ' measure : %s\n' % self.name s += ' standardizer : %s\n' % self.standardizer from .. util._str import dflist2str s += ' df : %s\n' % dflist2str( self.df ) for k in ('z', 'd', 'g', 'D', 'eta2p', 'eta2', 'omega2', 'wilks'): v = getattr(self, k) if v is None: continue if np.ndim(v) == 0: s += ' %-12s : %.5f\n' % (k, float(v)) else: s += ' %-12s : (%d,) array\n' % (k, np.size(v)) return s
[docs] def plot(self, ax=None, **kwargs): ''' Plot the 1D effect size field ``z`` (see :func:`spm1d.plot.plot_effectsize`). :Parameters: - *ax* --- axes [default: matplotlib.pyplot.gca()] - Keyword arguments of :func:`spm1d.plot.plot_effectsize` :Returns: - Axes :Example: >>> import spm1d >>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 ) >>> es = spm1d.stats.ttest2( y0, y1 ).effect_size() >>> ax = es.plot() ''' from .. plot import plot_effectsize return plot_effectsize(self, ax=ax, **kwargs)
def _effect_size_mv(spm, from_model): ''' Effect size of a multivariate contrast. Hotelling's T2: Mahalanobis distance D. Wilks' lambda: partial eta squared. ''' from .. exceptions import SPM1DError from .. stats._glm.design.designs_mv import rao_df ts, fit, dim, df = spm._teststat, spm.fit, spm.dim, spm.df r = fit._r if not r: raise SPM1DError( 'effect_size() needs the multivariate fit\'s engine result. This SPM does not carry it.' ) f0 = (lambda x: float(x) if dim == 0 else np.asarray(x, dtype=float)) dfe = float( r['df_e'] ) if ts.STAT == 'T2': X = np.asarray( fit.design.X, dtype=float ) c = np.asarray( r['C'], dtype=float ).ravel() v = float( c @ np.linalg.pinv( X.T @ X ) @ c ) # c'(X'X)^-c T2 = np.asarray( ts.z, dtype=float ) with np.errstate( invalid='ignore' ): D = np.sqrt( T2 * v ) eta2p = T2 / (T2 + dfe) return EffectSize( f0(D), 'Mahalanobis D', 'classical', df, dim, D=f0(D), eta2p=f0(eta2p) ) if ts.STAT == 'F': lam = np.asarray( r['wilks'], dtype=float ) _, _, s = rao_df( r['c'], r['I'], dfe ) eta2p = 1.0 - lam ** (1.0 / s) return EffectSize( f0(eta2p), 'multivariate partial eta squared', 'classical', df, dim, eta2p=f0(eta2p), wilks=f0(lam) ) raise SPM1DError( 'effect_size() is not defined for a multivariate SPM carrying "%s".' % ts.STAT ) def _contrast_variance(fit, c): """c'(X'X)^- c computed from the pseudo-inverse.""" cXi = np.asarray(fit.Xi, dtype=float).T @ np.asarray(c, dtype=float) return float( cXi @ cXi ) def effect_size(spm, from_model=False, **kwargs): ''' Effect size of this SPM's contrast. ''' from .. exceptions import SPM1DError, SPM1DKeywordError if kwargs: raise SPM1DKeywordError( f'effect_size() has no keyword argument "{next(iter(kwargs))}". It takes "from_model" only.' ) ts = spm._teststat stat = getattr(ts, 'STAT', None) dim = getattr(spm, 'dim', 0) df = getattr(spm, 'df', None) if getattr( spm, 'ismultivariate', False ): return _effect_size_mv( spm, from_model ) if stat not in ('T', 'F'): raise SPM1DError( 'effect_size() is defined for T and F contrasts. This SPM carries "%s".' % stat ) std = 'model' if from_model else 'classical' if stat == 'T': t = np.asarray( ts.z, dtype=float ) v = _contrast_variance( spm.fit, ts.c ) # from_model: t*sqrt(c'(X'X)^-c) divides by the SD the test used and # inherits the covariance correction. Otherwise the classical pooled # SD sqrt(sse/dfe0) is used. if from_model: d = t * np.sqrt( v ) else: est = np.asarray(ts.c, dtype=float) @ np.asarray(spm.fit.b, dtype=float) sse = np.asarray( spm.fit.sse, dtype=float ) s2 = sse / float( spm.fit.dfe0 ) with np.errstate(divide='ignore', invalid='ignore'): d = np.ravel(est) / np.sqrt( np.ravel(s2) ) d = d if (dim == 1) else float( d[0] ) d = np.asarray(d, dtype=float) if (dim == 1) else d nu = float( np.atleast_1d(df)[-1] ) if (df is not None) else np.nan J = _hedges_J( nu ) g = d * J e = (t ** 2) / (t ** 2 + nu) z = float(d) if dim == 0 else d return EffectSize(z, "Cohen's d", std, df, dim, d=z, g=(float(g) if dim == 0 else g), eta2p=(float(e) if dim == 0 else e)) # Partial eta squared is a function of F and its df alone, so it holds for # any contrast in any design. f = np.asarray( ts.z, dtype=float ) v0, v1 = [float(x) for x in np.atleast_1d(df)[:2]] eta2p = (v0 * f) / (v0 * f + v1) eta2 = omega2 = None ss = getattr(ts, 'ss', None) sse = getattr(ts, 'sse', None) mse = getattr(ts, 'mse', None) if (ss is not None) and (sse is not None): ss, sse = np.asarray(ss, dtype=float), np.asarray(sse, dtype=float) tot = ss + sse with np.errstate(divide='ignore', invalid='ignore'): eta2 = np.where(tot > 0, ss / tot, np.nan) if mse is not None: m = np.asarray(mse, dtype=float) omega2 = np.where((tot + m) > 0, (ss - v0 * m) / (tot + m), np.nan) f0 = (lambda x: None if x is None else (float(x) if dim == 0 else x)) return EffectSize(f0(eta2p), 'partial eta squared', std, df, dim, eta2p=f0(eta2p), eta2=f0(eta2), omega2=f0(omega2))