Source code for spm1d.prob._results


'''
Inference result classes.
'''

# Copyright (C) 2026  Todd Pataky

import numpy as np


from .. util._serial import DictSerial


def _extra_fmt(results, key):
    '''
    Format an extra value for printing.
    '''
    if key == 'nperm':
        n = results.extras.get( 'nuperm' )
        return lambda v: ( f'all ({n})' if (n is not None and n < 1e6) else 'all' ) if (int(v) == -1 or (n is not None and int(v) == int(n))) else str( int(v) )
    if key == 'nuperm':
        return lambda v: str( int(v) ) if (v < 1e6) else f'{float(v):.3E}'
    if key in ('Z', 'Z2'):
        return lambda v: 'None' if (v is None) else f'{np.shape(v)} array'
    return None


class ExtraParameters(dict, DictSerial):
    

    @staticmethod
    def from_h5group(group):
        keys     = list( group.attrs.keys() )
        values   = []
        for k in keys:
            if k in ['nperm', 'nuperm']:
                v = int( group.attrs[k] )
            elif k in ['Z', 'Z2']:
                v = group.attrs[k]
                v = None if (isinstance(v, str) and v == 'None') else np.asarray( v )
            else:
                try:
                    v = group.attrs[k].item()
                except (AttributeError, ValueError):
                    v = group.attrs[k]
            values.append( v )
        extras   = dict( zip(keys,values) )
        if '_nprandstate' in group:
            from . _perm.nprandstate import NumpyRandomState
            state = NumpyRandomState.from_h5group(  group['_nprandstate']  )
            extras.update( _nprandstate=state )
        return ExtraParameters( extras )

    @property
    def isempty(self):
        return len(self)==0

    def write_to_h5group(self, group):
        for k,v in self.items():
            if k=='_nprandstate':
                v.write_to_h5group( group.create_group('_nprandstate') )
            elif (k == 'nuperm') and (v > 2**62):
                group.attrs[k] = float( v )          # beyond int64, stored as a float
            elif v is None:
                group.attrs[k] = 'None'
            else:
                group.attrs[k] = v


def _parse_df(df):
    if isinstance(df, np.ndarray):
        df = tuple( map(float, df) )
    else:
        df = None if (df=='None') else df
    return df
    
    
def _replace_none_str(x, dtype=None):
    if isinstance(x, str) and (x=='None'):
        x = None
    else:
        if dtype is not None:
            x = dtype(x)
    return x


from .. _attr import AttrHints


class _InferenceResults(AttrHints, DictSerial):
    
    dim = 0

    def __init__(self, method, STAT, z, alpha, df, dirn, zc, isparametric=True, extras={}):
        self._dp          = None   # DisplayParams
        self._dpe         = None   # DisplayParams for extras
        self.method       = method
        self.isparametric = isparametric
        self.STAT         = STAT
        self.z            = z
        self.alpha        = alpha
        from .. stats._glm.teststats import clean_df
        self.df           = clean_df( df )
        self.dirn         = dirn
        self.zc           = zc   # positive magnitude, applied at -zc when dirn == -1 (see zcs)
        self.extras       = ExtraParameters(extras)
        self._init_extras()
        self._init_dp()

    def __eq__(self, other):
        return self.isequal(other, verbose=False)


    def __repr__(self):
        return self._dp.asstr()
        
    def _init_extras(self):
        for key,value in self.extras.items():
            if not key.startswith('_'):
                setattr( self, key, value )

    def _perms_equal(self, other, verbose=False):
        '''
        Compare permutation distributions if present in both results.
        '''
        from .. util._eq import _equal
        for key in ('Z', 'Z2'):
            x0, x1 = self.extras.get( key ), other.extras.get( key )
            if (x0 is None) or (x1 is None):
                continue
            if not _equal( x0, x1, approx=True ):
                if verbose:
                    print( f'unequal {key} values' )
                return False
        return True

    def delete_perms(self):
        '''
        Remove permutation distributions ``Z`` and ``Z2``.

        :Returns:

        - None

        :Example:

            >>> import spm1d
            >>> y0, y1  = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
            >>> t       = spm1d.stats.ttest2( y0, y1 )
            >>> results = spm1d.prob.rft( 'T', t.z, t.df, t.fwhm, t.resels )
            >>> results.delete_perms()
        '''
        for key in ('Z', 'Z2'):
            if key in self.extras:
                del self.extras[key]
                delattr( self, key )
        self._init_dp()


    @staticmethod
    def from_h5group(group):
        '''
        Read results from an open HDF5 group.

        :Parameters:

        - *group* --- open ``h5py`` group

        :Returns:

        - **InferenceResults0D** or **InferenceResults1D** object

        :Example:

            >>> import h5py
            >>> import spm1d
            >>> from spm1d.prob._results import InferenceResults1D
            >>> y0, y1  = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
            >>> t       = spm1d.stats.ttest2( y0, y1 )
            >>> results = spm1d.prob.rft( 'T', t.z, t.df, t.fwhm, t.resels )
            >>> with h5py.File( 'results.h5', 'w' ) as f:
            ...     results.write_to_h5group( f.create_group( 'results' ) )
            >>> with h5py.File( 'results.h5', 'r' ) as f:
            ...     loaded = InferenceResults1D.from_h5group( f['results'] )
            >>> print( results.isequal( loaded ) )
            True
        '''
        dim          = int( group.attrs['dim'] )
        method       = group.attrs['method']
        isparametric = group.attrs['isparametric']
        STAT         = group.attrs['STAT']
        z            = group.attrs['z']
        alpha        = float( group.attrs['alpha'] )
        df           = _parse_df( group.attrs['df'] )
        dirn         = _replace_none_str( group.attrs['dirn'], int )
        zc           = _replace_none_str( group.attrs['zc'], float )
        extras       = ExtraParameters.from_h5group( group['extras'] )
        if dim == 0:
            p        = float( group.attrs['p'] )
            iresults = InferenceResults0D(method, STAT, z, alpha, df, dirn, zc, p, isparametric, extras)
        else:
            from .. geom._clusters import ClusterList
            p_set    = _replace_none_str( group.attrs['p_set'], float )
            clusters = ClusterList._from_h5group( group['clusters'] )
            p_point  = _replace_none_str( group.attrs['p_point'], np.asarray )
            p_zmax   = _replace_none_str( group.attrs['p_zmax'], float ) if ('p_zmax' in group.attrs) else None
            iresults = InferenceResults1D(method, STAT, z, alpha, df, dirn, zc, p_set, clusters, p_point, isparametric, extras, p_zmax=p_zmax)
        return iresults
        
    def write_to_h5group(self, group):
        '''
        Write results to an open HDF5 group.

        :Parameters:

        - *group* --- open ``h5py`` group

        :Returns:

        - None

        :Example:

            >>> import h5py
            >>> import spm1d
            >>> y0, y1  = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
            >>> t       = spm1d.stats.ttest2( y0, y1 )
            >>> results = spm1d.prob.rft( 'T', t.z, t.df, t.fwhm, t.resels )
            >>> with h5py.File( 'results.h5', 'w' ) as f:
            ...     results.write_to_h5group( f.create_group( 'results' ) )
        '''
        group.attrs['dim']          = self.dim
        group.attrs['method']       = self.method
        group.attrs['isparametric'] = self.isparametric
        group.attrs['STAT']         = self.STAT
        group.attrs['z']            = self.z
        group.attrs['alpha']        = self.alpha
        group.attrs['df']           = 'None' if (self.df is None) else self.df
        group.attrs['dirn']         = 'None' if (self.dirn is None) else self.dirn
        group.attrs['zc']           = 'None' if (self.zc is None) else self.zc
        if self.dim == 0:
            group.attrs['p']        = self.p
        else:
            group.attrs['p_set']    = 'None' if (self.p_set is None) else self.p_set
            group.attrs['p_point']  = 'None' if (self.p_point is None) else self.p_point
            group.attrs['p_zmax']   = 'None' if (self._p_zmax is None) else self._p_zmax
            self.clusters._write_to_h5group( group.create_group('clusters') )
        self.extras.write_to_h5group(  group.create_group('extras')  )

    @property
    def zcs(self):
        '''
        Signed critical threshold: ``-zc`` if ``dirn`` is ``-1``, otherwise
        ``zc``.
        '''
        return -self.zc if (self.dirn==-1) else self.zc


[docs] class InferenceResults0D(_InferenceResults): ''' Inference results for a 0D test statistic. **Attributes** ``method`` inference method: ``'param'`` or ``'perm'`` ``isparametric`` ``True`` for parametric methods and ``False`` otherwise ``STAT`` test statistic type: ``'T'``, ``'F'``, ``'T2'`` or ``'X2'`` ``z`` test statistic value ``df`` degrees of freedom (``None`` for permutation inference) ``alpha`` Type I error rate ``dirn`` inference direction: ``0`` (two-tailed), ``1`` or ``-1`` (one-tailed) ``zc`` critical threshold as a positive value ``zcs`` signed critical threshold ``h0reject`` ``True`` if ``z`` exceeds ``zc`` in the tested direction ``p`` probability value ``extras`` method-specific parameters (e.g., ``nperm``) ``Z`` (**Permutation inference only**) permutation distribution of the test statistic ''' def __init__(self, method, STAT, z, alpha, df, dirn, zc, p, isparametric=True, extras={}): self.p = p super().__init__(method, STAT, z, alpha, df, dirn, zc, isparametric, extras) def _init_dp(self): from .. util._rpr import DisplayParams dp = DisplayParams( self ) dp.add_header( 'Inference results:' ) dp.add( 'method' ) dp.add( 'isparametric' ) dp.add( 'alpha' ) if self.STAT == 'T': dp.add( 'dirn' ) dp.add( 'zc', dp.fmt['float2string_none'] ) dp.add( 'h0reject' ) dp.add( 'p', dp.fmt['p2string5'] ) # extras if not self.extras.isempty: for key in self.extras.keys(): if not key.startswith('_'): dp.add( key, fmt=_extra_fmt(self, key) ) self._dp = dp @property def h0reject(self): ''' True if ``z`` exceeds ``zc`` in the tested direction. ''' zc = self.zc # critical test statistic value if zc is None: return False if self.dirn in (None,1): h = self.z > zc elif self.dirn==0: h = (self.z < -zc) or (self.z > zc) elif self.dirn==-1: h = self.z < -zc # Plain bool: numpy's bool is not a subclass of Python's. return bool( h )
[docs] def isequal(self, other, verbose=False): ''' Equality with another inference result. :Parameters: - *other* --- other inference result - *verbose* --- if True, print the first unequal attribute name (default False) :Returns: - True if *other* holds identical inference results, otherwise False :Example: >>> import spm1d >>> y0, y1 = spm1d.rng.ttest2( nsubj=8, seed=0 ) >>> t = spm1d.stats.ttest2( y0, y1 ) >>> results = spm1d.prob.param( 'T', t.z, t.df ) >>> other = spm1d.prob.param( 'T', t.z, t.df ) >>> print( results.isequal( other ) ) True ''' from .. util import isequal as util_isequal attrs = ['method', 'STAT', 'alpha', 'dirn'] attrs_approx = ['df', 'z', 'zc'] return util_isequal(self, other, attrs, attrs_approx, verbose) and self._perms_equal(other, verbose)
[docs] class InferenceResults1D(_InferenceResults): ''' Inference results for a 1D test statistic field. **Attributes** ``method`` inference method: ``'rft'``, ``'perm'``, ``'fdr'``, ``'bonf'`` or ``'uncorr'`` ``isparametric`` ``True`` for parametric methods and ``False`` otherwise ``STAT`` test statistic type: ``'T'``, ``'F'``, ``'T2'`` or ``'X2'`` ``z`` (Q,) test statistic field ``df`` degrees of freedom (``None`` for permutation inference) ``alpha`` Type I error rate ``dirn`` inference direction: ``0`` (two-tailed), ``1`` or ``-1`` (one-tailed) ``zc`` critical threshold as a positive value ``zcs`` signed critical threshold ``h0reject`` ``True`` if ``zmax`` exceeds ``zc`` ``p_set`` set-level probability (``None`` for ``'fdr'``, ``'bonf'`` and ``'uncorr'``) ``p_cluster`` cluster-level probabilities if present, otherwise ``None`` ``p_point`` point-level probabilities (``None`` for ``'rft'``) ``clusters`` list of suprathreshold clusters (see :ref:`Clusters <api-classes-clusters>`) ``nclusters`` number of suprathreshold clusters ``hasclusters`` ``True`` if there is at least one suprathreshold cluster ``hasiclusters`` ``True`` if the clusters have cluster-level probabilities ``extras`` method-specific parameters (e.g., ``nperm``) ``Z`` (**Permutation inference only**) permutation distribution of the test statistic ``Z2`` (**Permutation inference only**) permutation distribution of the cluster metric ''' dim = 1 def __init__(self, method, STAT, z, alpha, df, dirn, zc, p_set, clusters, p_point, isparametric=True, extras={}, p_zmax=None): self.p_set = p_set self.clusters = clusters self.p_point = p_point # None for RFT, where SPMi1D.p_point computes it on request (see p_zmax) self._p_zmax = p_zmax # used only when p_point is None super().__init__(method, STAT, z, alpha, df, dirn, zc, isparametric, extras) def _init_dp(self): from .. util._rpr import DisplayParams dp = DisplayParams( self ) dp.add_header( 'Inference results:' ) dp.add( 'method' ) dp.add( 'isparametric' ) dp.add( 'alpha' ) if self.STAT == 'T': dp.add( 'dirn' ) dp.add( 'zc', dp.fmt['float2string_none'] ) dp.add( 'zmax', dp.fmt['float2string'] ) dp.add( 'h0reject' ) dp.add( 'p_zmax', dp.fmt['p2string_none'] ) dp.add( 'p_set', dp.fmt['p2string_none'] ) dp.add( 'p_cluster', dp.fmt['pcluster2string'] ) dp.add( 'p_point', dp.fmt['array2shortstr'] ) # extras if len(self.extras) > 0: for key in self.extras.keys(): if not key.startswith('_'): dp.add( key, fmt=_extra_fmt(self, key) ) self._dp = dp @property def h0reject(self): ''' True if ``zmax`` exceeds ``zc`` in the tested direction. ''' zc = self.zc if zc is None: return False if self.dirn in (None,1): h = self.z.max() > zc elif self.dirn==0: h = (self.z.min() < -zc) or (self.z.max() > zc) elif self.dirn==-1: h = self.z.min() < -zc return bool( h ) # see the 0D property above @property def hasclusters(self): ''' True if there is at least one suprathreshold cluster. ''' return (self.clusters is not None) and (len(self.clusters)>0) @property def hasiclusters(self): ''' True if clusters have cluster-level probabilities. ''' return self.hasclusters and hasattr(self.clusters[0], 'p')
[docs] def isequal(self, other, verbose=False): ''' Equality with another inference result. :Parameters: - *other* --- other inference result - *verbose* --- if True, print the first unequal attribute name (default False) :Returns: - True if *other* holds identical inference results, otherwise False :Example: >>> import spm1d >>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 ) >>> t = spm1d.stats.ttest2( y0, y1 ) >>> results = spm1d.prob.rft( 'T', t.z, t.df, t.fwhm, t.resels ) >>> other = spm1d.prob.rft( 'T', t.z, t.df, t.fwhm, t.resels ) >>> print( results.isequal( other ) ) True ''' from .. util import isequal as util_isequal attrs = ['method', 'STAT', 'alpha', 'dirn', 'clusters'] attrs_approx = ['z', 'zc', 'p_set', 'p_point', 'p_zmax'] return util_isequal(self, other, attrs, attrs_approx, verbose) and self._perms_equal(other, verbose)
@property def nclusters(self): ''' Number of suprathreshold clusters. ''' return 0 if (self.clusters is None) else len(self.clusters) @property def p_cluster(self): ''' Cluster-level probabilities if present, otherwise None. ''' if self.hasiclusters: return [c.p for c in self.clusters] else: return None @property def p_zmax(self): ''' P value of the test statistic extreme (zmax). ''' return self._p_zmax if (self.p_point is None) else self.p_point.min() @property def zmax(self): ''' Test statistic field extreme in the tested direction. ''' if self.dirn==0: return np.abs(self.z).max() elif self.dirn==1: return self.z.max() elif self.dirn==-1: return -self.z.min()