Source code for spm1d._results.lists

'''
Result lists: ``SPMList``, ``SPMiList``, ``SPMPostHocList`` and
``SPMPostHocListMV``.
'''

# Copyright (C) 2026  Todd Pataky

import numpy as np
from .. util._serial import AttrDictSerial
from .. _attr import AttrHints
from . _base import _SPMListBase, INFERRED_HINT


[docs] class SPMList(_SPMListBase): ''' List of SPM objects (one per effect). Accessible by index or name (e.g., "Main A"). '''
[docs] def inference(self, alpha=0.05, method=None, **kwargs): ''' Inference on all effects. :Parameters: - Arguments of ``inference`` (see **SPM1D** and **SPM0D**) :Returns: - **SPMiList** object :Example: >>> import spm1d >>> y, A, B = spm1d.rng.anova2( nlevels=(2, 3), nsubj=5, Q=101, fwhm=20, seed=0 ) >>> spmi = spm1d.stats.anova2( y, A, B ).inference( 0.05 ) >>> print( spmi.get_h0reject_values() ) (False, False, False) ''' from . _base import perm_args from .. prob._methods import check_method, check_alpha, check_kwargs if method is None: method = 'param' if (self.dim == 0) else 'rft' check_method( method, self.dim ) check_alpha( alpha ) if self.dim == 1: # The list validates as a single SPM1D does. The members validate # again harmlessly. shared = { k: kwargs.pop(k) for k in ('roi',) if k in kwargs } # validated by the members kwargs = check_kwargs( method, kwargs, STAT=self.STAT ) kwargs.update( shared ) else: from .. stats._argparsers import InferenceArgumentParser0D parser = InferenceArgumentParser0D( self.STAT, method ) parser.parse( alpha, **kwargs ) kwargs = parser.kwargs if method != 'perm': FFi = SPMiList( [f.inference(alpha=alpha, method=method, **kwargs) for f in self] ) else: z = np.array([f.z for f in self]) # None means the smaller of 10000 and the number of unique # permutations. nperm = kwargs.get( 'nperm' ) roi = kwargs.get( 'roi' ) _roi = self[0]._resolve_roi( roi ) if (self.dim == 1 and roi is not None) else None # prob._perm is the subpackage. from .. prob._perm import perm as _perm self._check_perm_applicable() results = _perm(self.STAT, z, alpha=alpha, testname=self._testname, args=perm_args(self), nperm=nperm, dim=self.dim, roi=_roi) ikwargs = dict( method='perm', nperm=nperm ) if _roi is not None: ikwargs['roi'] = _roi FFi = SPMiList( [f._as_spmi(res, ikwargs) for f,res in zip(self, results)] ) if _roi is not None: # A masked z and the region-local smoothness, as # SPM1D.inference leaves them. for f,fi in zip( self, FFi ): fi._teststat.z, fi._sm = f._roi_view( _roi ) fi.roi = _roi return FFi
[docs] class SPMiList(_SPMListBase): ''' List of SPM inference objects (one per effect). ''' #: List type as printed. name = 'SPM inference list' _attr_hints = { 'inference': INFERRED_HINT }
[docs] def delete_perms(self): ''' Remove permutation distributions ``Z`` and ``Z2`` from all effects. :Returns: - None :Example: >>> import spm1d >>> y, A, B = spm1d.rng.anova2( nlevels=(2, 3), nsubj=5, Q=101, fwhm=20, seed=0 ) >>> spmi = spm1d.stats.anova2( y, A, B, cov_model='iid' ).inference( 0.05, method='perm', nperm=200 ) >>> spmi.delete_perms() ''' for f in self: f.delete_perms()
[docs] def get_h0reject_values(self): ''' Null hypothesis rejection decisions of all effects. :Returns: - Tuple of booleans in list order :Example: >>> import spm1d >>> y, A, B = spm1d.rng.anova2( nlevels=(2, 3), nsubj=5, Q=101, fwhm=20, seed=0 ) >>> spmi = spm1d.stats.anova2( y, A, B ).inference( 0.05 ) >>> print( spmi.get_h0reject_values() ) (False, False, False) ''' return tuple( [f.h0reject for f in self] )
[docs] def get_p_values(self): ''' P values of all effects. :Returns: - Tuple in list order (cluster-level p values for 1D data) :Example: >>> import spm1d >>> y, A, B = spm1d.rng.anova2( nlevels=(2, 3), nsubj=5, Q=101, fwhm=20, seed=0 ) >>> spmi = spm1d.stats.anova2( y, A, B ).inference( 0.05 ) >>> print( spmi.get_p_values() ) (None, None, None) ''' return tuple( [f.p_cluster if (self.dim == 1) else f.p for f in self] )
[docs] def get_zc_values(self): ''' Critical thresholds of all effects. :Returns: - Tuple of ``zc`` values in list order :Example: >>> import spm1d >>> y, A, B = spm1d.rng.anova2( nlevels=(2, 3), nsubj=5, Q=101, fwhm=20, seed=0 ) >>> spmi = spm1d.stats.anova2( y, A, B, cov_model='iid' ).inference( 0.05 ) >>> print( [round( zc, 3 ) for zc in spmi.get_zc_values()] ) [9.934, 6.996, 6.996] ''' return tuple( [f.zc for f in self] )
[docs] def get_zstar_values(self): # legacy name ("zc" was "zstar" before spm1d 0.5) ''' Deprecated v0.4 name of :meth:`get_zc_values`. :Returns: - As :meth:`get_zc_values` with a ``SPM1DDeprecationWarning`` ''' import warnings from .. exceptions import SPM1DDeprecationWarning from .. _settings import _user_stacklevel msg = 'Use of "get_zstar_values" is deprecated. Use "get_zc_values" to avoid this warning.' warnings.warn( msg , SPM1DDeprecationWarning , stacklevel=_user_stacklevel() ) return self.get_zc_values()
@property def h0reject(self): ''' True if the null hypothesis is rejected for at least one effect. ''' for f in self: if f.h0reject: return True return False
[docs] def posthoc(self, *args, **kwargs): ''' Pairwise comparisons of the levels of one factor. Subject and nested factors cannot be compared. :Parameters: - *factor* --- factor name (e.g., ``'A'``, ``'B'``) - *correction* --- (**Univariate results only**) ``'bonf'`` (default) or ``'scheffe'`` :Returns: - **SPMPostHocList** (or **SPMPostHocListMV**) of inferred comparisons :Example: >>> import spm1d >>> y, A, B = spm1d.rng.anova2( nlevels=(2, 3), nsubj=8, Q=1, mu=[[0, 0, 3], [0, 0, 3]], seed=0 ) >>> spmi = spm1d.stats.anova2( y, A, B, cov_model='iid' ).inference( 0.05 ) >>> phi = spmi.posthoc( 'B' ) >>> print( len( phi ), phi[0].name ) 3 B0 - B1 ''' from .. exceptions import SPM1DPostHocError first = self[0] first._posthoc_check_result( where='list' ) mv = bool( getattr( self.design, 'ismultivariate', False ) ) factor, correction = first._posthoc_parse_call( args, kwargs, mv, 'list' ) if not any( bool( getattr( item, 'h0reject', False ) ) for item in self ): raise SPM1DPostHocError( 'No effect of the "%s" design reached significance. Post hoc tests are therefore disabled.' % self._testname ) f = first._posthoc_resolve_factor( factor, 'list' ) label = 'Main %s' % f.name if label not in self.effect_labels: raise SPM1DPostHocError( 'posthoc() cannot find the main effect of factor "%s" among the "%s" ' 'design\'s effects (%s).' % ( f.name, self._testname, ', '.join( self.effect_labels ) ) ) item = self[ label ] item._posthoc_check_permitted() if mv: return item._posthoc_mv_run( f ) return item._posthoc_run( f, 'bonf' if (correction is None) else correction )
[docs] def print_table(self): ''' (**0D results only**) Print a classical ANOVA table. :Returns: - None :Example: >>> import spm1d >>> y, A, B = spm1d.rng.anova2( nlevels=(2, 3), nsubj=5, Q=1, seed=0 ) >>> spmi = spm1d.stats.anova2( y, A, B, cov_model='iid' ).inference( 0.05 ) >>> spmi.print_table() Source DF SS MS F P A 1.000 0.387 0.387 0.625 0.437 B 2.000 3.988 1.994 3.223 0.058 A:B 2.000 0.422 0.211 0.341 0.714 Error ... ''' if any( getattr(f, 'dim', 1) == 1 or np.ndim(f.z) > 0 for f in self ): from .. exceptions import SPM1DError raise SPM1DError( 'print_table is available for 0D results only. For 1D results ' 'use print_summary(), or print the list.' ) colnames = [f._name_s for f in self] + ['Source', 'Error'] n = 1 + max( [len(s) for s in colnames] ) fmt0 = '{:<%d} {:>6} {:>8} {:>8} {:>8} {:>8}' %n fmt = '{:<%d} {:6.3f} {:8.3f} {:8.3f} {:8.3f} {:8.3f}' %n fmte = '{:<%d} {:6.3f} {:8.3f} {:8.3f}' %n print( fmt0.format('Source', 'DF', 'SS', 'MS', 'F', 'P') ) for f in self: print( fmt.format(f._name_s, f.df[0], f.ss, f.ms, f.z, f.p) ) print( fmte.format('Error', self.dfe, self.sse, self.mse) )
[docs] class SPMPostHocList(AttrHints, list, AttrDictSerial): ''' SPM.posthoc() result with one SPM per pairwise comparison. The list is read-only. ''' #: List type as printed. name = 'SPM post hoc list' _attr_hints = { 'inference': INFERRED_HINT } def __init__(self, spms, labels, factor=None, alpha_omnibus=None, omnibus=None, correction=None): # list.__init__ bypasses the blocked methods below. list.__init__( self, spms ) self._labels = tuple( labels ) self._factor = factor self._alpha_omnibus = alpha_omnibus self._omnibus = omnibus # the factor's omnibus F SPM on the same fit self._correction = correction # None, 'bonf' or 'scheffe' once inferred def __getitem__(self, i): from .. exceptions import SPM1DError, SPM1DKeyError if isinstance(i, slice): raise SPM1DError( f'Slicing is not supported for {self.__class__.__name__}; index one comparison by position or by label.' ) if isinstance(i, str): if i not in self._labels: raise SPM1DKeyError( 'No comparison %r. This list holds: %s.' % (i, ', '.join(self._labels)) ) return list.__getitem__( self, self._labels.index(i) ) return list.__getitem__( self, i ) def __repr__(self): s = '%s\n' % self.name s += ' factor : %s\n' % self.factor s += ' ncomparisons : %d\n' % self.ncomparisons s += ' comparisons : [list of %d comparisons]\n' % self.ncomparisons if self._correction is not None: s += ' correction : %s\n' % self._correction s += '\n' return s def __setattr__(self, name, value): if name.startswith('_'): return object.__setattr__( self, name, value ) from .. exceptions import SPM1DAttributeError raise SPM1DAttributeError( "can't set attribute %r: SPM post hoc list is read-only." % (name,), name=name, obj=self ) def _immutable(self, *args, **kwargs): ''' Not available (read-only list). Raises ``SPM1DTypeError``. ''' from .. exceptions import SPM1DTypeError raise SPM1DTypeError( 'SPM post hoc list is read-only. Build a plain list instead such as ' '[ph[i] for i in (0, 2)].' ) def _infer(self, alpha, correction='bonf', inherited=None): ''' Run inference on every comparison using the omnibus alpha and inference settings. - ``correction='bonf'`` tests each comparison at alpha / ncomparisons. - ``correction='scheffe'`` thresholds each field at sqrt(dfn * u) where u is the omnibus critical value and dfn is its numerator degrees of freedom. Requires ``cov_model='iid'``. ''' from .. exceptions import SPM1DError kwargs = dict( inherited or {} ) if correction == 'bonf': spms = [s.inference(self.bonferroni(alpha), **kwargs) for s in self] elif correction == 'scheffe': if (self._omnibus is None) or (getattr(self._omnibus, 'STAT', None) != 'F'): raise SPM1DError( 'correction="scheffe" needs the omnibus F for factor %r on ' 'this fit, and this list does not carry one.' % self._factor ) # t**2 <= dfn * F holds for an ordinary least-squares fit only. if getattr( self._omnibus._model, 'QQ', None ) is not None: raise SPM1DError( 'correction="scheffe" is defined for an ordinary least-' 'squares fit only. Fit ' 'the ANOVA with cov_model="iid" to use it.' ) omni = self._omnibus omni_i = omni if getattr( omni, 'isinference', False ) else omni.inference( alpha, **kwargs ) dfn = float( omni.df[0] ) zc = float( np.sqrt( dfn * float(omni_i.zc) ) ) spms = [s.inference(alpha, dirn=0, _zc=zc, **kwargs) for s in self] else: raise SPM1DError( 'Unknown correction %r. Use "bonf" or "scheffe".' % (correction,) ) return SPMPostHocList( spms, self._labels, self._factor, self._alpha_omnibus, omnibus=self._omnibus, correction=correction ) def _pc_adj_str(self, ti): from .. util._str import p2str_pcadj return '%8s' % p2str_pcadj( self._pc_adj( ti ) ) def _table_col0(self): return 'comparison' def _table_head(self): head = '%s: factor %s' % (self.name, self._factor) if self._correction is not None: head += ', correction %s' % self._correction return head def _to_dict(self): ''' Dictionary form of this list with one dictionary per comparison. ''' d = AttrDictSerial._to_dict( self ) d['comparisons'] = [ spm._to_dict() for spm in self ] return d @property def alpha_omnibus(self): ''' Omnibus test Type I error rate. ''' return self._alpha_omnibus
[docs] def bonferroni(self, alpha=0.05): ''' Bonferroni-corrected alpha for this many comparisons. :Parameters: - *alpha* --- Type I error rate (default 0.05) :Returns: - alpha / ncomparisons :Example: >>> import spm1d >>> y, A = spm1d.rng.anova1( nlevels=3, nsubj=8, Q=101, fwhm=20, mu=[0, 0, 2], seed=0 ) >>> phi = spm1d.stats.anova1( y, A ).inference( 0.05 ).posthoc() >>> print( round( phi.bonferroni(), 4 ) ) 0.0167 ''' return float(alpha) / self.ncomparisons
@property def correction(self): ''' Threshold correction: ``bonf`` or ``scheffe`` (``omnibus`` for multivariate lists). ''' return self._correction @property def factor(self): '''Factor whose levels are compared.''' return self._factor @property def labels(self): '''Tuple of comparison labels in list order.''' return self._labels @property def ncomparisons(self): '''Number of pairwise comparisons (list length).''' return len( self ) @property def omnibus(self): '''Omnibus F SPM of the compared factor.''' return self._omnibus def _pc_adj(self, ti): ''' Adjusted critical p value of one comparison under this list's correction. ''' if self._correction in (None, 'bonf'): return float( ti.alpha ) return _critical_p( ti )
[docs] def plot_cluster_bars(self, **kwdargs): ''' One row of cluster bars per comparison (see :func:`spm1d.plot.plot_cluster_bars`). :Parameters: - Keyword arguments of :func:`spm1d.plot.plot_cluster_bars` :Returns: - Axes :Example: >>> import spm1d >>> y, A = spm1d.rng.anova1( nlevels=3, nsubj=8, Q=101, fwhm=20, mu=[0, 0, 2], seed=0 ) >>> phi = spm1d.stats.anova1( y, A ).inference( 0.05 ).posthoc() >>> ax = phi.plot_cluster_bars() ''' from .. plot import plot_cluster_bars return plot_cluster_bars(self, **kwdargs)
[docs] def plot_cluster_bars_colorsplit(self, **kwdargs): ''' One row of cluster bars per comparison (see :func:`spm1d.plot.plot_cluster_bars_colorsplit`). :Parameters: - Keyword arguments of :func:`spm1d.plot.plot_cluster_bars_colorsplit` :Returns: - Axes :Example: >>> import spm1d >>> y, A = spm1d.rng.anova1( nlevels=3, nsubj=8, Q=101, fwhm=20, mu=[0, 0, 2], seed=0 ) >>> phi = spm1d.stats.anova1( y, A ).inference( 0.05 ).posthoc() >>> ax = phi.plot_cluster_bars_colorsplit() ''' from .. plot import plot_cluster_bars_colorsplit return plot_cluster_bars_colorsplit(self, **kwdargs)
[docs] def plot_cluster_patches(self, **kwdargs): ''' One color of cluster bands per comparison (see :func:`spm1d.plot.plot_cluster_patches`). :Parameters: - Keyword arguments of :func:`spm1d.plot.plot_cluster_patches` :Returns: - Return value of :func:`spm1d.plot.plot_cluster_patches` :Example: >>> import spm1d >>> y, A = spm1d.rng.anova1( nlevels=3, nsubj=8, Q=101, fwhm=20, mu=[0, 0, 2], seed=0 ) >>> phi = spm1d.stats.anova1( y, A ).inference( 0.05 ).posthoc() >>> h = phi.plot_cluster_patches() ''' from .. plot import plot_cluster_patches return plot_cluster_patches(self, **kwdargs)
[docs] def print_summary(self): ''' Print the list header and one line per comparison. :Returns: - None :Example: >>> import spm1d >>> y, A = spm1d.rng.anova1( nlevels=3, nsubj=8, Q=101, fwhm=20, mu=[0, 0, 2], seed=0 ) >>> phi = spm1d.stats.anova1( y, A ).inference( 0.05 ).posthoc() >>> phi.print_summary() SPM post hoc list (factor A, correction bonf) df = (1, 20.395) FWHM = 20.7814 zc = 3.7574 Comparisons (T): A0 - A1 zmax=1.279 h0reject=False A0 - A2 zmax=-5.561 h0reject=True A1 - A2 zmax=-5.683 h0reject=True ''' print( self._summary_str() )
def _summary_str(self): from .. util._str import dflist2str if len(self) == 0: return '%s: no comparisons' % self.name s0 = self[0] isinf = getattr( s0, 'isinference', False ) head = '%s (%s %s' % (self.name, self._summary_factor_word, self.factor) if self._correction is not None: head += ', correction %s' % self._correction lines = [head + ')'] lines.append( ' df = %s' % dflist2str( s0.df ) ) if s0.dim == 1: lines.append( ' FWHM = %.4f' % float( s0.fwhm ) ) if isinf: zc = self.zc if hasattr( type(self), 'zc' ) else s0.zc lines.append( ' zc = %.4f' % float( zc ) ) lines.append( 'Comparisons (%s):' % s0.STAT ) w = max( len(lab) for lab in self._labels ) for lab, spm in zip( self._labels, self ): z = np.asarray( spm.z, dtype=float ) zmax = float( z[ np.nanargmax( np.abs(z) ) ] ) if (spm.dim == 1) else float( z ) line = ' %-*s zmax=%.3f' % (w, lab, zmax) if isinf: line += ' h0reject=%s' % spm.h0reject lines.append( line ) return '\n'.join( lines ) + '\n' _summary_factor_word = 'factor'
[docs] def print_table(self): ''' Print comparisons as a table. :Returns: - None :Example: >>> import spm1d >>> y, A = spm1d.rng.anova1( nlevels=3, nsubj=8, Q=101, fwhm=20, mu=[0, 0, 2], seed=0 ) >>> phi = spm1d.stats.anova1( y, A ).inference( 0.05 ).posthoc() >>> phi.print_table() SPM post hoc list: factor A, correction bonf comparison zc t max p_zmax pc-adj clusters h0reject A0 - A1 3.757 1.279 1.0000 0.0167 0 False A0 - A2 3.757 -5.561 <0.001 0.0167 2 True A1 - A2 3.757 -5.683 <0.001 0.0167 2 True pc-adj = adjusted critical p-value ''' print( self.table() + '\n' )
[docs] def table(self): ''' Text table with one row per comparison. ``p`` is the uncorrected p value and ``pc-adj`` is the adjusted critical p value. :Returns: - Table as a string :Example: >>> import spm1d >>> y, A = spm1d.rng.anova1( nlevels=3, nsubj=8, Q=101, fwhm=20, mu=[0, 0, 2], seed=0 ) >>> phi = spm1d.stats.anova1( y, A ).inference( 0.05 ).posthoc() >>> print( phi.table().splitlines()[0] ) SPM post hoc list: factor A, correction bonf ''' from .. util._str import p2string if len(self) == 0: return '%s: no comparisons' % self.name w = max( 10, max( len(lab) for lab in self._labels ) ) s0 = self[0] dim = s0.dim isinf = getattr( s0, 'isinference', False ) stat = 't' if (s0.STAT == 'T') else s0.STAT col0 = self._table_col0() rows = [self._table_head()] if isinf and dim == 0: rows.append( '%-*s %9s %8s %8s %s' % (w, col0, stat, 'p', 'pc-adj', 'h0reject') ) for lab, ti in zip( self._labels, self ): rows.append( '%-*s %9.3f %8s %8s %s' % (w, lab, float(ti.z), p2string(float(ti.p), fmt='%.4f'), self._pc_adj_str(ti), ti.h0reject) ) rows.append( 'pc-adj = adjusted critical p-value' ) elif isinf: rows.append( '%-*s %8s %9s %8s %8s %9s %s' % (w, col0, 'zc', stat + ' max', 'p_zmax', 'pc-adj', 'clusters', 'h0reject') ) for lab, ti in zip( self._labels, self ): z = np.asarray( ti.z, dtype=float ) zext = float( z[ np.nanargmax( np.abs(z) ) ] ) rows.append( '%-*s %8.3f %9.3f %8s %8s %9d %s' % (w, lab, float(ti.zc), zext, p2string(float(ti.p_zmax), fmt='%.4f'), self._pc_adj_str(ti), ti.nclusters, ti.h0reject) ) rows.append( 'pc-adj = adjusted critical p-value' ) elif dim == 0: rows.append( '%-*s %9s' % (w, col0, stat) ) for lab, t in zip( self._labels, self ): rows.append( '%-*s %9.3f' % (w, lab, float(t.z)) ) else: rows.append( '%-*s %9s %9s' % (w, col0, stat + ' min', stat + ' max') ) for lab, t in zip( self._labels, self ): z = np.asarray( t.z, dtype=float ) rows.append( '%-*s %9.3f %9.3f' % (w, lab, float(np.nanmin(z)), float(np.nanmax(z))) ) return '\n'.join( rows )
append = extend = insert = remove = pop = clear = _immutable sort = reverse = _immutable __setitem__ = __delitem__ = __iadd__ = __imul__ = _immutable
def _critical_p(ti): ''' P value of an inferred SPM's critical height. ''' import rft1d method = getattr( ti, 'method', None ) STAT = ti.STAT zc = float( ti.zc ) two = 2 if (STAT == 'T') else 1 if method == 'param': if STAT == 'T': v = ti.df[1] if isinstance( ti.df, (list, tuple, np.ndarray) ) else ti.df return float( 2 * rft1d.t.sf0d( zc, v ) ) if STAT == 'T2': return float( rft1d.T2.sf0d( zc, ti.df ) ) return None if method == 'rft': z = ti.z nNodes = z.count() if np.ma.is_masked( z ) else np.asarray( z ).size calc = rft1d.prob.RFTCalculatorResels( STAT=STAT, df=ti.df, resels=ti._sm.resels, withBonf=True, nNodes=nNodes ) return float( two * calc.sf( zc ) ) return None
[docs] class SPMPostHocListMV(SPMPostHocList): ''' SPM.posthoc() result for multivariate inference results. Items are component t tests or pairwise Hotelling's T2 tests. ''' #: List type as printed. name = 'SPM multivariate post hoc list' _summary_factor_word = 'items' def __init__(self, spms, labels, factor=None, omnibus=None, zc=None): SPMPostHocList.__init__( self, spms, labels, factor=factor, omnibus=omnibus, correction=( 'omnibus' if (zc is not None) else None ) ) self._zc = zc # the post hoc threshold on the T2 scale def __repr__(self): s = '%s\n' % self.name s += ' items : %s\n' % self.factor s += ' nitems : %d\n' % self.ncomparisons s += ' comparisons : [list of %d comparisons]\n' % self.ncomparisons if self._zc is not None: s += ' zc : %.5g (post hoc threshold on the T2 scale, from the omnibus %s critical value)\n' % (self._zc, self._omnibus.STAT) return s def _infer(self, inherited=None): ''' Threshold every item at the post hoc threshold derived from the omnibus critical value. ''' kwargs = dict( inherited or {} ) omni_i = self._omnibus alpha = float( omni_i.alpha ) u = self._posthoc_threshold( omni_i ) spms = [] for s in self: if s.STAT == 'T': spms.append( s.inference( alpha, dirn=0, _zc=float(np.sqrt(u)), **kwargs ) ) else: spms.append( s.inference( alpha, _zc=float(u), **kwargs ) ) return SPMPostHocListMV( spms, self._labels, self._factor, omnibus=omni_i, zc=u ) def _table_col0(self): return str( self._factor ) def _table_head(self): head = '%s: %s' % (self.name, self._factor) if self._zc is not None: head += ', thresholds derived from the omnibus %s critical value' % self._omnibus.STAT return head
[docs] def bonferroni(self, alpha=0.05): ''' Not available for multivariate post hoc lists. :Parameters: - *alpha* --- ignored :Returns: - Nothing. Raises ``SPM1DPostHocError`` ''' from .. exceptions import SPM1DPostHocError raise SPM1DPostHocError( 'A Bonferroni correction is not offered for the multivariate post ' 'hoc lists. For a Bonferroni threshold run each item\'s inference at ' 'alpha / %d yourself.' % len(self) )
@property def loadings(self): ''' Unit-length direction of maximal omnibus separation. Not available for pairwise MANOVA lists (use phi[k].posthoc().loadings). ''' from .. exceptions import SPM1DPostHocError fit = getattr( self._omnibus, 'fit', None ) a = getattr( fit, 'discriminant', None ) if a is None: raise SPM1DPostHocError( 'This post hoc list has no loadings. The omnibus contrast of ' 'a "%s" result has more than one row. Each pair has its own: ' 'phi[k].posthoc().loadings.' % getattr( self._omnibus, '_testname', 'manova1' ) ) return a def _pc_adj(self, ti): ''' Adjusted critical p value of one item. ''' return _critical_p( ti ) @staticmethod def _posthoc_threshold(omni_i): ''' Post hoc threshold on the T2 scale derived from the omnibus critical value. ''' zc = float( omni_i.zc ) if omni_i.STAT == 'T2': return zc if omni_i.STAT == 'F': from .. stats._mv._engine import MVGLM r = omni_i.fit._r dfe = float( r['df_e'] ) df1, df2, s = MVGLM.rao_df( r['c'], r['I'], dfe ) lam_a = ( df2 / (df2 + df1 * zc) ) ** s return dfe * ( 1.0 / lam_a - 1.0 ) from .. exceptions import SPM1DError raise SPM1DError( 'no post hoc threshold for an omnibus with STAT=%r' % omni_i.STAT ) @property def zc(self): ''' Post hoc threshold on the T2 scale (component t tests use its square root). ''' return self._zc