Source code for spm1d.stats._var

'''
Tests for variance.
'''

# Copyright (C) 2026  Todd Pataky

import numpy as np

from .. geom import estimate_fwhm
from . _dec import docdims


class _EqVarSPM1D(object):
    '''
    Variance ratio field before inference.
    '''

    STAT = 'F'
    dim  = 1

    def __init__(self, z, df, fwhm, alt, Q):
        self.z      = z         # (Q,) the variance-ratio field
        self.df     = df        # (J0-1, J1-1)
        self.fwhm   = fwhm      # smoothness of the pooled residuals
        self.alt    = alt       # "unequal" or "greater"
        self.Q      = Q

    def __repr__(self):
        from .. util._rpr import DisplayParams
        dp = DisplayParams( self )
        dp.add_header( 'SPM{F} (1D, equal variance)' )
        dp.add( 'alt' )
        dp.add( 'z', fmt=dp.fmt['array2shortstr'] )
        dp.add( 'df', fmt=dp.fmt['dflist2str'] )
        dp.add_header( 'Smoothness estimates:' )
        dp.add( 'fwhm', fmt='%.3f' )
        return dp.asstr()

    @property
    def _istwosided(self):
        return self.alt.upper() == 'UNEQUAL'

    def inference(self, alpha=0.05, withBonf=True):
        '''
        Random field theory height-level inference on the variance ratio field.

        :Parameters:

        - *alpha* --- Type I error rate (default 0.05)
        - *withBonf* --- if True (default), cap the RFT probabilities at their
          Bonferroni values

        :Returns:

        - **InferenceResults1D** object
        '''
        import rft1d
        from .. geom import assemble_clusters
        from .. prob._results import InferenceResults1D
        #  Two-sided through alpha/2 on a one-sided F threshold as v0.4 does.
        k        = 2.0 if self._istwosided else 1.0
        zc       = rft1d.f.isf(alpha / k, self.df, self.Q, self.fwhm,
                               withBonf=withBonf)
        sf       = lambda u: min(1.0, k * float(
                       rft1d.f.sf(u, self.df, self.Q, self.fwhm,
                                  withBonf=withBonf) ))
        clusters = assemble_clusters( self.z, zc, dirn=1, circular=False )
        for i, c in enumerate(clusters):
            #  "c.max" is the cluster's peak. "c.height" on a pre-inference cluster
            #  is the threshold it was cut at.
            clusters[i] = c._as_inference_cluster( c.extent / self.fwhm,
                                                  sf(abs(c.max)),
                                                  metric_type='height' )
        zz      = np.asarray(self.z, dtype=float)
        p_point = np.array([sf(v)  for v in np.ravel(zz)]).reshape(zz.shape)
        return InferenceResults1D('rft', 'F', self.z, alpha, self.df, 1, zc,
                                  None, clusters, p_point, isparametric=True)


[docs] @docdims('univariate') def eqvartest(y0, y1, alt="unequal"): ''' F test for equal variance. Adapted from the MATLAB script in the supplementary material of Kowalski et al. (2021). :Parameters: - *y0* --- One group as a (J0,Q) array of 1D data - *y1* --- Other group as a (J1,Q) array of 1D data - *alt* --- alternative hypothesis: ``unequal`` (default) or ``greater`` ( var(y0) > var(y1) ) :Returns: - Variance-ratio field object (not an **SPM1D** object) :Example: The 1D example uses two simulated groups of six responses. >>> import spm1d >>> import jikudata as jd >>> dataset = jd.SimulatedTwoLocalMax() >>> y, A = dataset.y, dataset.x # (12,101) array and (12,) array >>> y0, y1 = y[ A == 0 ], y[ A == 1 ] >>> results = spm1d.stats.eqvartest( y0, y1 ).inference( 0.05 ) >>> print( results.h0reject ) False The example datasets require the jiku-data package: ``pip install "spm1d[data]"``. :Note: - Height-level inference only. - 1D data only. ``alt='unequal'`` requires equal sample sizes. ''' from .. exceptions import SPM1DNotImplementedError, SPM1DError y0, y1 = np.asarray(y0, dtype=float), np.asarray(y1, dtype=float) if (y0.ndim != 2) or (y1.ndim != 2): raise SPM1DNotImplementedError( 'Only implemented for 1D data.' ) if str(alt).upper() not in ('UNEQUAL', 'GREATER'): raise SPM1DError( f'"alt" must be "unequal" or "greater", not {alt!r}.' ) J0, J1 = y0.shape[0], y1.shape[0] if (J0 != J1) and (alt.upper() == 'UNEQUAL'): raise SPM1DNotImplementedError( 'Unequal alternative implemented only for ' 'equal sample sizes. Set alt="greater" to ' 'conduct this test.' ) s0, s1 = y0.var(axis=0, ddof=1), y1.var(axis=0, ddof=1) if alt.upper() == 'UNEQUAL': ss = np.vstack([s0, s1]) z = ss.max(axis=0) / ss.min(axis=0) else: z = s0 / s1 r0, r1 = y0 - y0.mean(axis=0), y1 - y1.mean(axis=0) fwhm = estimate_fwhm( np.vstack([r0, r1]) ) return _EqVarSPM1D( z, (J0 - 1, J1 - 1), fwhm, alt, y0.shape[1] )