Source code for spm1d.geom._clusters.cluster



'''
Cluster class.
'''

# Copyright (C) 2026  Todd Pataky


import numpy as np
from . _base import _Cluster, _WithInference


from ... util._serial import DictSerial


class Cluster( _Cluster, DictSerial ):
    '''
    Suprathreshold cluster of a 1D test statistic.
    '''

    iswrapped       = False

    def __init__(self, x, z, u, sign=1):
        self._InferenceClass = ClusterWithInference
        self._Q              = None          # domain size (defined during right-boundary interpolation)
        self._x              = list( x )     # post-interpolated
        self.z               = list( z )     # post-interpolated
        self._u              = u             # threshold
        self.sign            = sign
        self._endpoints      = x[0], x[-1]   # pre-interpolation

    def __eq__(self, other):
        if type(self)!=type(other):
            return False
        eq = True
        #  _InferenceClass and _endpoints derive from _x and are not state.
        for k,v in self.__dict__.items():
            if k not in ('_InferenceClass', '_endpoints'):
                v1 = getattr(other, k)
                if v is None:
                    eq = v1 is None
                elif isinstance(v, float) and np.isnan(v):
                    eq = np.isnan( v1 )
                elif isinstance(v, str):
                    eq = v==v1
                elif isinstance(v, (int,float,tuple,list)):
                    from ... util._eq import _equal
                    eq = _equal(v, v1, approx=True)   # interpolated endpoints and p-values are compared to floating-point tolerance
                else:
                    from ... exceptions import SPM1DInternalError
                    raise SPM1DInternalError( f'Unable to hash type: {type(v)}' )
                if not eq:
                    break
        return eq

    def __lt__(self, other):
        return self._x[0] < other._x[0]


    def _interp_left(self, zf):
        i,u        = self._x[0], self._u
        if (i==0) or np.ma.is_masked( zf[i-1] ):
            self._x = [i] + self._x
            self.z = [u] + self.z
        else:
            z0,z1  = zf[i-1], zf[i]
            dx     = (z1-u) / (z1-z0)
            self._x = [i-dx] + self._x
            self.z = [u] + self.z

    def _interp_right(self, zf):
        i,u,Q      = self._x[-1], self._u, zf.size
        if i==(Q-1) or np.ma.is_masked( zf[i+1] ):
            self._x += [i]
            self.z += [u]
        else:
            z0,z1   = zf[i], zf[i+1]
            dx      = (z0-u) / (z0-z1)
            self._x += [i+dx]
            self.z += [u]
        self._Q      = Q


    def _asarray(self):
        return np.array( [ self._x, self.z ] ).T

    @property
    def centroid(self):
        '''
        Cluster centroid ``(x, z)``.
        '''
        x,z = self._asarray().T
        xc  = (x*z).sum() / z.sum()
        zc  = z.mean()
        return xc, zc

    @property
    def endpoints(self):
        '''
        Interpolated cluster start and end positions ``(x0, x1)`` in domain
        nodes.
        '''
        return self._x[0], self._x[-1]

    @property
    def _endpoints_preinterp(self):
        return self._endpoints

    @property
    def extent(self):
        '''
        Cluster width ``x1 - x0`` in domain nodes (1 for single-node clusters).
        '''
        x0,x1  = self.endpoints
        w      = x1 - x0
        if w == 0:
            w  = 1   # a cluster that is not interpolated can be a single node, whose extent is one
        return w

    @staticmethod
    def _from_h5group(group):
        if ('iswrapped' in group.attrs) and bool( group.attrs['iswrapped'] ):
            from . wrapped import WrappedCluster
            return WrappedCluster._from_h5group( group )
        isinference  = bool( group.attrs['isinference'] )
        Q            = int( group.attrs['Q'] )
        x            = group.attrs['x']
        z            = group.attrs['z']
        u            = float( group.attrs['u'] )
        sign         = int( group.attrs['sign'] )
        if isinference:
            mtype    = _replace_none_str( group.attrs['metric_type'], str )
            metric   = _replace_none_str( group.attrs['metric'], float )
            p        = _replace_none_str( group.attrs['p'], float )
            cluster  = ClusterWithInference( x, z, u, sign=sign )
            cluster._set_inference_params(metric, p, metric_type=mtype)
        else:
            cluster  = Cluster( x, z, u, sign=sign )
        cluster._Q    = Q
        return cluster

    @property
    def height(self):
        '''
        Least extreme cluster value (threshold when interpolated). Same as
        ``min``.
        '''
        return self.min

    @property
    def integral(self):
        '''
        Area between the statistic and threshold.
        '''
        from .. _metrics import trapz
        return self.sign * trapz( np.asarray(self.z) - self._u )

    def _interp(self, zfull):
        # interpolate to threshold u using similar triangles method
        self._interp_left(zfull)
        self._interp_right(zfull)

    @property
    def _isLboundary(self):
        return self._endpoints[0] == 0

    @property
    def _isRboundary(self):
        return self._endpoints[1] == (self._Q-1)

    @property
    def max(self):
        '''
        Most extreme cluster statistic value (minimum for negative clusters).
        '''
        return max(self.z) if (self.sign==1) else min(self.z)

    @property
    def min(self):
        '''
        Least extreme cluster statistic value (threshold when interpolated).
        '''
        return min(self.z) if (self.sign==1) else max(self.z)

    @property
    def nnodes(self):
        '''
        Number of cluster nodes (excluding interpolated end points).
        '''
        return len(self._x) - 2  # interpolation adds two points (one to each end)

    def _write_to_h5group(self, group):
        group.attrs['isinference'] = self._isinference
        group.attrs['Q']           = self._Q
        group.attrs['x']           = self._x
        group.attrs['z']           = self.z
        group.attrs['u']           = self._u
        group.attrs['sign']        = self.sign


def _nonestr(x):
    return 'None' if (x is None) else x

def _replace_none_str(x, dtype=None):
    if x=='None':
        x = None
    else:
        if dtype is not None:
            x = dtype(x)
    return x


[docs] class ClusterWithInference(_WithInference, Cluster): ''' Suprathreshold cluster with inference results. ''' def _write_to_h5group(self, group): super()._write_to_h5group( group ) group.attrs['metric_type'] = _nonestr(self.metric_type) group.attrs['metric'] = _nonestr(self.metric) group.attrs['p'] = _nonestr(self.p)