'''
Inference results: ``SPMi0D`` and ``SPMi1D``.
'''
# Copyright (C) 2026 Todd Pataky
import numpy as np
from . _base import _SPMi, _SPM0DBase, _SPM1DBase
from . spm import SPM0D, SPM1D
[docs]
class SPMi0D(_SPMi, _SPM0DBase):
'''
SPM inference object.
**Inference attributes** (in addition to all ``SPM0D`` attributes except
``inference``)
``method``
inference method: ``'param'`` or ``'perm'``
``isparametric``
``True`` for parametric methods and ``False`` otherwise
``alpha``
Type I error rate
``dirn``
inference direction: ``0`` (two-tailed), ``1`` or ``-1`` (one-tailed)
``zc``
critical threshold
``h0reject``
``True`` if ``z`` exceeds ``zc`` (in the tested direction)
``p``
probability value
``Z``
(**Permutation inference only**) permutation distribution of the test
statistic
'''
def _repr_summ(self, n=5):
from .. util._str import dflist2str, p2string
return ('{:<%d} z={:<8} df={:<15} p={}\n' % n).format(self._name_s, self._repr_teststat_short(), dflist2str(self.df), p2string(self.p,fmt='%.5f'))
@staticmethod
def _from_h5group(group):
from .. stats._args import InputArguments
from .. prob._results import _InferenceResults
spm = SPM0D._from_h5group(group)
iresults = _InferenceResults.from_h5group( group['iresults'] )
_iargs = InputArguments.from_h5group( group['_iargs'] )
spmi = spm._as_spmi(iresults, _iargs.kwargs)
return spmi
[docs]
def write_to_h5group(self, group, with_args=False):
'''
Write to an open HDF5 group including inference results.
:Parameters:
- *group* --- open ``h5py`` group
- *with_args* --- write input arguments if True (default False)
:Returns:
- None (read with ``SPMi0D._from_h5group``)
:Example:
>>> import h5py
>>> import spm1d
>>> y0, y1 = spm1d.rng.ttest2( nsubj=8, seed=0 )
>>> spmi = spm1d.stats.ttest2( y0, y1 ).inference( 0.05 )
>>> with h5py.File( 'ttest2.h5', 'w' ) as f:
... spmi.write_to_h5group( f.create_group( 'spmi' ) )
'''
super().write_to_h5group( group, with_args=with_args )
self._iargs.write_to_h5group( group.create_group('_iargs') )
self._iresults.write_to_h5group( group.create_group('iresults') )
group.attrs['isinference'] = True
group.attrs['isparametric'] = self._iresults.isparametric
[docs]
class SPMi1D(_SPMi, _SPM1DBase):
'''
SPM inference object.
**Inference attributes** (in addition to all ``SPM1D`` attributes except
``inference``)
``method``
inference method: ``'rft'``, ``'perm'``, ``'fdr'``, ``'bonf'`` or
``'uncorr'``
``isparametric``
``True`` for parametric methods and ``False`` otherwise
``alpha``
Type I error rate
``dirn``
inference direction: ``0`` (two-tailed), ``1`` or ``-1`` (one-tailed)
``zc``
critical threshold
``zmax``
test statistic continuum maximum in the tested direction
``h0reject``
``True`` if ``zmax`` exceeds ``zc``
``p_zmax``
continuum-level probability
``p_set``
(**Random field theory only**) set-level probability
``p_cluster``
cluster-level probabilities if present, otherwise ``None``
``p_point``
point-level probabilities
``clusters``
list of suprathreshold clusters
``nclusters``
number of suprathreshold clusters
``Z``
(**Permutation inference only**) permutation distribution of the test
statistic
``Z2``
(**Permutation inference only**) permutation distribution of the
cluster metric
'''
def _repr_summ(self, n=5):
from .. util._str import dflist2str
return ('{:<%d} z={:<18} df={:<16} h0reject={}\n' % n).format(self._name_s, self._repr_teststat_short(), dflist2str(self.df), self.h0reject)
@property
def clusters(self):
'''
List of suprathreshold
:class:`~spm1d.geom._clusters.cluster.ClusterWithInference` objects in
domain order (see :ref:`Clusters <api-classes-clusters>`).
'''
return self._iresults.clusters
@staticmethod
def _from_h5group(group):
from .. stats._args import InputArguments
from .. prob._results import _InferenceResults
spm = SPM1D._from_h5group(group)
iresults = _InferenceResults.from_h5group( group['iresults'] )
_iargs = InputArguments.from_h5group( group['_iargs'] )
spmi = spm._as_spmi(iresults, _iargs.kwargs)
# Smoothness over the search region when there was one.
roi = getattr( spm, 'roi', None )
if roi is not None:
spmi._sm = spm._sm.as_roi( roi )
# The file holds plain arrays, so the region's mask is restored.
mask = np.logical_not( np.asarray( roi, dtype=bool ) )
spmi._teststat.z = np.ma.masked_array( np.ma.getdata( spmi.z ), mask )
spmi._iresults.z = np.ma.masked_array( np.ma.getdata( spmi._iresults.z ), mask )
if isinstance( spmi._iresults.p_point, np.ndarray ):
spmi._iresults.p_point = np.ma.masked_array( np.ma.getdata( spmi._iresults.p_point ), mask )
return spmi
@property
def nclusters(self):
'''Number of suprathreshold clusters.'''
return len( self._iresults.clusters )
@property
def p(self):
'''
Deprecated name of ``p_cluster``.
'''
import warnings
from .. exceptions import SPM1DDeprecationWarning
from .. _settings import _user_stacklevel
msg = 'Use of "p" is deprecated. Use "p_cluster" to avoid this warning.'
warnings.warn( msg , SPM1DDeprecationWarning , stacklevel=_user_stacklevel() )
return self.p_cluster
@property
def p_cluster(self):
'''
Cluster-level p values in ``clusters`` order.
'''
return self._iresults.p_cluster
@property
def p_set(self):
'''
(**RFT inference only**) Set-level p value.
'''
return self._iresults.p_set
@property
def p_zmax(self):
'''
Field maximum (``zmax``) p value.
'''
return self._iresults.p_zmax
@property
def p_point(self):
'''
Point-level p values.
RFT point-level p values are accurate only for small p values (see the
"Reporting p values" theory page).
'''
p = self._iresults.p_point
if (p is not None) or (self.method != 'rft'):
return p
import rft1d
from .. exceptions import SPM1DUserWarning
from .. _settings import settings
from .. prob._general import p_corrected_dirn, z_corrected_dirn, p_point_in_region
settings._warn_once(
'Random field theory point-level p-values (p_point) are accurate only when small '
'(p < 0.2), approximately accurate when moderate (p < 0.5) but increasingly '
'approximate for large p-values (p > 0.5). You may validly use p-values for '
'reporting, but please be cautious about how large p-values are interpreted, and '
'please never use p-values as likelihoods in further analyses. See the '
'"Reporting p values" documentation page for more details.',
SPM1DUserWarning )
z = self.z
if getattr( self, '_isnormality', False ):
# the K2 field has its own EC density (see stats._diag.ec)
from .. stats._diag.ec import sf
p = np.array( [ sf( float(v), self.design.J, self.resels ) for v in np.ravel( np.ma.getdata(z) ) ] )
return p_point_in_region( p.reshape( z.shape ), z )
nNodes = int( z.count() ) if np.ma.is_masked( z ) else z.size
withBonf = bool( self._iargs.kwargs.get( 'withBonf', True ) )
calc = rft1d.prob.RFTCalculatorResels( STAT=self.STAT, df=self.df, resels=self.resels,
withBonf=withBonf, nNodes=nNodes )
dirn = self.dirn if (self.STAT == 'T') else 1
_z = z_corrected_dirn( z, dirn )
p = np.asarray( calc.sf( np.ma.getdata(_z) ), dtype=float )
p = p_corrected_dirn( p, dirn )
return p_point_in_region( p, z )
[docs]
def plot(self, **kwdargs):
'''
Plot the statistic, critical threshold and clusters (see
:func:`spm1d.plot.plot_spmi`).
:Parameters:
- Keyword arguments of :func:`spm1d.plot.plot_spmi`
:Returns:
- Return value of :func:`spm1d.plot.plot_spmi`
:Example:
>>> import spm1d
>>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
>>> spmi = spm1d.stats.ttest2( y0, y1 ).inference( 0.05 )
>>> h = spmi.plot()
'''
from .. plot import plot_spmi
return plot_spmi(self, **kwdargs)
[docs]
def plot_barh(self, **kwdargs):
'''
Attach a cluster bar strip to an axes (see
:func:`spm1d.plot.plot_cluster_barh`).
:Parameters:
- Keyword arguments of :func:`spm1d.plot.plot_cluster_barh`
:Returns:
- Return value of :func:`spm1d.plot.plot_cluster_barh`
:Example:
>>> import spm1d
>>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
>>> spmi = spm1d.stats.ttest2( y0, y1 ).inference( 0.05 )
>>> h = spmi.plot_barh()
'''
from .. plot import plot_cluster_barh
return plot_cluster_barh(self, **kwdargs)
[docs]
def plot_cluster_bars(self, **kwdargs):
'''
Plot clusters as bars (see
:func:`spm1d.plot.plot_cluster_bars`).
:Parameters:
- Keyword arguments of :func:`spm1d.plot.plot_cluster_bars`
:Returns:
- Axes
:Example:
>>> import spm1d
>>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
>>> spmi = spm1d.stats.ttest2( y0, y1 ).inference( 0.05 )
>>> ax = spmi.plot_cluster_bars()
'''
from .. plot import plot_cluster_bars
return plot_cluster_bars(self, **kwdargs)
[docs]
def plot_cluster_patches(self, **kwdargs):
'''
Plot clusters as vertical bands (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
>>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
>>> spmi = spm1d.stats.ttest2( y0, y1 ).inference( 0.05 )
>>> h = spmi.plot_cluster_patches()
'''
from .. plot import plot_cluster_patches
return plot_cluster_patches(self, **kwdargs)
[docs]
def plot_p_values(self, **kwdargs):
'''
Write cluster p values (see
:func:`spm1d.plot.plot_spmi_p_values`).
:Parameters:
- Keyword arguments of :func:`spm1d.plot.plot_spmi_p_values`
:Returns:
- Return value of :func:`spm1d.plot.plot_spmi_p_values`
:Example:
>>> import spm1d
>>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
>>> spmi = spm1d.stats.ttest2( y0, y1 ).inference( 0.05 )
>>> h = spmi.plot()
>>> h = spmi.plot_p_values()
'''
from .. plot import plot_spmi_p_values
return plot_spmi_p_values(self, **kwdargs)
[docs]
def plot_threshold_label(self, **kwdargs):
'''
Write the critical threshold and alpha beside the threshold line (see
:func:`spm1d.plot.plot_spmi_threshold_label`).
:Parameters:
- Keyword arguments of :func:`spm1d.plot.plot_spmi_threshold_label`
:Returns:
- Return value of :func:`spm1d.plot.plot_spmi_threshold_label`
:Example:
>>> import spm1d
>>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
>>> spmi = spm1d.stats.ttest2( y0, y1 ).inference( 0.05 )
>>> h = spmi.plot()
>>> h = spmi.plot_threshold_label()
'''
from .. plot import plot_spmi_threshold_label
return plot_spmi_threshold_label(self, **kwdargs)
[docs]
def write_to_h5group(self, group, with_args=False):
'''
Write to an open HDF5 group including inference results.
:Parameters:
- *group* --- open ``h5py`` group
- *with_args* --- write input arguments if True (default False)
:Returns:
- None (read with ``SPMi1D._from_h5group``)
:Example:
>>> import h5py
>>> import spm1d
>>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
>>> spmi = spm1d.stats.ttest2( y0, y1 ).inference( 0.05 )
>>> with h5py.File( 'ttest2.h5', 'w' ) as f:
... spmi.write_to_h5group( f.create_group( 'spmi' ) )
'''
super().write_to_h5group(group, with_args=with_args)
self._iargs.write_to_h5group( group.create_group('_iargs') )
self._iresults.write_to_h5group( group.create_group('iresults') )
group.attrs['isinference'] = True
group.attrs['isparametric'] = self._iresults.isparametric
@property
def zmax(self):
'''
Field extreme in the tested direction.
'''
return self._iresults.zmax