Source code for spm1d._results.ci


'''
Confidence intervals.
'''

# Copyright (C) 2026  Todd Pataky


import warnings
import numpy as np
from .. exceptions import SPM1DDeprecationWarning
from .. _settings import _user_stacklevel
from .. plot import plot_ci_0d, plot_ci_multisample_0d, plot_ci, plot_ci_multisample
from .. util._str import dflist2str
from .. util._serial import AttrDictSerial


from .. _attr import AttrHints


class _CI(AttrHints, AttrDictSerial):
    _dict_exclude    = ('zstar', 'hstar')   # the v0.4 names of zc and hc (deprecated aliases below)
    # summary attributes
    #: Interval type as printed: ``"0D Confidence Interval"`` or ``"1D
    #: Confidence Interval"``.
    name             = None

    #: Data dimensionality (0 or 1).
    dim              = None

    _kind            = None    # one-, paired- or two-sample

    # means, datum and criteria
    _criterion_type  = None    # criterion type (string)

    _criterion_value = None    # float or 1D array

    _criterion       = None    # tuple: (criterion_type, criterion_value)

    _datum_ci        = None    # primary ci ("ci" or "ciA")

    _datum_type      = None    # datum type (string)

    _datum_value     = None    # float or 1D array

    _datum           = None    # tuple: (datum_type, datum_value)

    _nMeans          = None    # number of means (1 or 2)

    #: Hypothesized value or criterion (``mu``) if present, otherwise None.
    mu               = None

    # probability
    #: Type I error rate.
    alpha            = None

    #: t statistic degrees of freedom as ``(1, df)``.
    df               = None

    #: Critical t value for the interval height (RFT-corrected for 1D data).
    zc               = None

    # confidence interval
    #: Interval half-height: float (0D) or ``(Q,)`` array (1D).
    hc               = None

    #: True if the criterion lies outside the interval (None if there is no
    #: criterion).
    h0reject         = None

    # booleans
    _ismultimean     = None    # is a multi-mean CI

    #: Always True (parametric intervals).
    isparametric     = True

    _isscalarmu      = None    # is mu a scalar

    _istest          = None    # is a hypothesis test

    def __init__(self, spmi):
        self.alpha           = spmi.alpha
        self.df              = spmi.df
        self.zc              = spmi.zc
        self.h0reject        = spmi.h0reject

    @property
    def dfs(self):
        '''Degrees of freedom ``df`` as a string such as ``"(1, 21)"``.'''
        from .. util._str import dflist2str
        return dflist2str( self.df )

    def __repr__(self):
        s            = self._get_repr_header()
        s           += self._get_repr_prob()
        s           += self._get_repr_ci()
        return s


    def _assemble_datum_criterion_pairs(self):
        self._datum      = self._datum_type, self._datum_value
        self._criterion  = self._criterion_type, self._criterion_value

    def _format_ci(self, ci, asstr=False, with_brackets=False):
        x      = ci
        #  With criterion "meanB" there is no second interval.
        if x is None:
            return None
        if asstr:
            if self.dim==0:
                x  = '(%.5f, %.5f)' %x
            else:
                x  = self._get_field_str(2, with_brackets)
        return x

    def _get_repr_ci(self):
        s        = ''
        s       += '   Confidence interval\n'
        s       += '      hc         :  %s\n'              %self._get_hc(asstr=True)
        if self._datum_type == 'mean':
            s   += '      ci         :  %s\n'              %self._get_ci(asstr=True)
        elif self._criterion_type == 'meanB':
            s   += '      ciA        :  %s\n'              %self.get_ciA(asstr=True)
        elif self._criterion_type == 'tailB':
            s   += '      ciA        :  %s\n'              %self.get_ciA(asstr=True)
            s   += '      ciB        :  %s\n'              %self.get_ciB(asstr=True)
        if self._istest:
            s   += '      h0reject   :  %s (%s)\n'         %(self.h0reject, self._get_h0rejection_decision_reason())
        return s

    def _get_repr_header(self):
        s        = ''
        s       += '%s (%s)\n'                             %(self.name, self._get_percent(asstr=True))
        s       += '   kind          :  %s\n'              %self._kind
        s       += '   datum         :  %s  %s\n'          %(self._datum_type, self._get_datum_value(asstr=True, with_brackets=True))
        if self._istest:
            s   += '   criterion     :  %s  %s\n'          %(self._criterion_type, self._get_criterion_value(asstr=True, with_brackets=True))
        return s

    def _get_repr_prob(self):
        s            = ''
        s           += '   Probability\n'
        s           += '      alpha      :  %.3f\n'            %self.alpha
        if self.isparametric:
            s       += '      df         :  %s\n'              %dflist2str(self.df)
            if self.dim == 1:
                s   += '      fwhm       :  %.5f\n'            %self.fwhm
                s   += '      resels     :  %s\n'              %dflist2str(self.resels)
        s           += '      zc         :  %.5f\n'            %self.zc
        return s

    def _get_value(self, x, asstr=False, with_brackets=False):
        if isinstance(x, str):
            if with_brackets:
                x      = '(%s)' %x
        else:
            if asstr:
                if (self.dim==0) or (np.size(x)==1):
                    x  = '(%.5f)'%x if with_brackets else '%.5f'%x
                else:
                    x  = self._get_field_str(1, with_brackets)
        return x


    def _get_ci(self, asstr=False, with_brackets=False):
        return self._format_ci(self.ci, asstr, with_brackets)

    def _get_criterion_value(self, asstr=False, with_brackets=False):
        return self._get_value(self._criterion_value, asstr, with_brackets)

    def _get_datum_value(self, asstr=False, with_brackets=False):
        return self._get_value(self._datum_value, asstr, with_brackets)

    def _get_h0rejection_decision_reason(self):
        reason = 'outside' if self.h0reject else 'inside'
        return '%s %s %s' %(self._criterion_type, reason, self._datum_ci)

    def _get_hc(self, asstr=False, with_brackets=False):
        return self._get_value(self.hc, asstr, with_brackets)

    def _get_hstar(self, asstr=False, with_brackets=False):   # legacy name ("hc" was "hstar" before spm1d 0.5)
        msg = 'Use of "get_hstar" is deprecated. Use "get_hc" to avoid this warning.'
        warnings.warn( msg , SPM1DDeprecationWarning , stacklevel=_user_stacklevel() )
        return self._get_hc(asstr, with_brackets)

    def _get_percent(self, asstr=False):
        x       = 100 * (1-self.alpha)
        if asstr:
            x   = '%.1f%s' %(x, '%')
        return x

    @property
    def hstar(self):   # legacy name ("hc" was "hstar" before spm1d 0.5)
        '''Deprecated name of ``hc``.'''
        msg = 'Use of "hstar" is deprecated. Use "hc" to avoid this warning.'
        warnings.warn( msg , SPM1DDeprecationWarning , stacklevel=_user_stacklevel() )
        return self.hc

    @property
    def zstar(self):   # legacy name ("zc" was "zstar" before spm1d 0.5)
        '''Deprecated name of ``zc``.'''
        msg = 'Use of "zstar" is deprecated. Use "zc" to avoid this warning.'
        warnings.warn( msg , SPM1DDeprecationWarning , stacklevel=_user_stacklevel() )
        return self.zc


class _CI0D(_CI):
    name             = '0D Confidence Interval'
    dim              = 0
    def plot(self, ax=None):
        '''
        Plot the 0D interval as the mean with an error bar (see
        :func:`spm1d.plot.plot_ci_0d`).

        :Parameters:

        - *ax* --- axes [default: matplotlib.pyplot.gca()]

        :Returns:

        - None

        :Example:

            >>> import spm1d
            >>> y0, y1 = spm1d.rng.ttest2( nsubj=8, seed=0 )
            >>> ci = spm1d.stats.ci_onesample( y0 )
            >>> ci.plot()
        '''
        plot_ci_0d(self, ax)


class _CI1D(_CI):
    name             = '1D Confidence Interval'
    dim              = 1
    #: Number of domain nodes.
    Q                = None
    #: Estimated residual smoothness (full width at half maximum).
    fwhm             = None
    #: Resolution element counts ``(resels0, resels1)``.
    resels           = None

    def __init__(self, spmi):
        super(_CI1D, self).__init__(spmi)
        self.Q            = spmi.z.size
        self.fwhm         = spmi.fwhm
        self.resels       = spmi.resels

    def _get_field_str(self, n=1, with_brackets=False):
        x            = '(%dx%d) field'  %(n, self.Q)
        if with_brackets:
            x        = '[%s]' %x
        return x

    def plot(self, ax=None, x=None, linecolor=None, facecolor=None, edgecolor=None, alpha=0.5, autoset_ylim=True):
        '''
        Plot the 1D interval (see :func:`spm1d.plot.plot_ci`).

        :Parameters:

        - *ax* --- axes [default: matplotlib.pyplot.gca()]
        - *x* --- (Q,) array of domain positions [default: 0, 1, ..., Q-1]
        - *linecolor* --- mean continuum color [default: text color]
        - *facecolor* --- band fill color [default: faint gray]
        - *edgecolor* --- band edge color [default: faint gray]
        - *alpha* --- band transparency [default: 0.5]
        - *autoset_ylim* --- if True (default), set y limits to show all
          plotted elements

        :Returns:

        - None

        :Example:

            >>> import spm1d
            >>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
            >>> ci = spm1d.stats.ci_onesample( y0 )
            >>> ci.plot( facecolor='r' )
        '''
        plot_ci(self, ax=ax, x=x, linecolor=linecolor, facecolor=facecolor, edgecolor=edgecolor, alpha=alpha, autoset_ylim=autoset_ylim)


def _asfloat(x):
    '''
    Convert a 0D value to a Python float.
    '''
    a = np.asarray(x, dtype=float).ravel()
    return float( a[0] )


class _CISingleMean(_CI):
    _kind            = 'One sample'
    _nMeans          = 1
    _ismultimean     = False
    #: Sample mean or mean difference: float (0D) or ``(Q,)`` array (1D).
    mean             = None
    #: Interval ``(mean - hc, mean + hc)``. Two-tuple (0D) or ``(2,Q)`` array
    #: (1D).
    ci               = None
    _datum_ci        = 'ci'
    _datum_type      = 'mean'
    _criterion_type  = 'mu'

    def __init__(self, spmi, mean, hc, mu=None):
        super(_CISingleMean, self).__init__(spmi)
        # main parameters
        self.mean            = mean if self.dim==1 else _asfloat(mean)
        self.mu              = mu
        # confidence interval
        self.hc              = hc if self.dim==1 else _asfloat(hc)
        self.ci              = self.mean - self.hc, self.mean + self.hc
        if self.dim == 1:
            self.ci          = np.asarray(self.ci)
        # derived attributes
        self._isscalarmu     = isinstance(mu, (int,float))
        self._istest         = mu is not None
        self._datum_value    = self.mean
        self._criterion_value = self.mu
        self._assemble_datum_criterion_pairs()


class _CIDifference(_CISingleMean):
    _kind            = 'Difference'


class _CIMultiMean(_CI):
    _nMeans          = 2
    _ismultimean     = True
    #: First sample mean (interval center).
    meanA            = None
    #: Second sample mean (criterion).
    meanB            = None
    #: Interval about ``meanA``. Two-tuple (0D) or ``(2,Q)`` array (1D).
    ciA              = None
    #: Interval about ``meanB`` (``mu='tailB'`` only, otherwise None).
    ciB              = None
    _datum_ci        = 'ciA'
    _datum_type      = 'meanA'

    def __init__(self, spmi, meanA, meanB, hc, criterion='meanB'):
        super(_CIMultiMean, self).__init__(spmi)
        # main parameters
        self.meanA           = meanA if self.dim==1 else _asfloat(meanA)
        self.meanB           = meanB if self.dim==1 else _asfloat(meanB)
        # confidence interval
        self.hc              = hc if self.dim==1 else _asfloat(hc)
        if criterion == 'meanB':
            self.ciA         = self.meanA - self.hc, self.meanA + self.hc
            if self.dim == 1:
                self.ciA     = np.asarray(self.ciA)
        elif criterion == 'tailB':
            self.ciA         = self.meanA - 0.5*self.hc, self.meanA + 0.5*self.hc
            self.ciB         = self.meanB - 0.5*self.hc, self.meanB + 0.5*self.hc
            if self.dim == 1:
                self.ciA     = np.asarray(self.ciA)
                self.ciB     = np.asarray(self.ciB)
        # derived attributes
        self._isscalarmu     = isinstance(self.meanA, (int,float))
        self._istest         = True
        self._datum_value    = self.meanA
        self._criterion_type = criterion
        if criterion == 'meanB':
            self._criterion_value = self.meanB
        else:
            if self.dim == 0:
                self._criterion_value = self.ciB[0] if (self.meanA<self.meanB) else self.ciB[1]
            else:
                self._criterion_value = 'CI divergence'
        self._assemble_datum_criterion_pairs()


    def _get_ci(self, asstr=False, with_brackets=False):
        return self.get_ciA(asstr, with_brackets)
    def get_ciA(self, asstr=False, with_brackets=False):
        '''
        Interval about ``meanA``.

        :Parameters:

        - *asstr* --- if True, return a formatted string (default False)
        - *with_brackets* --- if True, enclose the string in brackets (default
          False)

        :Returns:

        - ``ciA`` as an array (string if *asstr* is True)

        :Example:

            >>> import spm1d
            >>> y0, y1 = spm1d.rng.ttest2( nsubj=8, seed=0 )
            >>> ci = spm1d.stats.ci_twosample( y0, y1, datum='meanA' )
            >>> print( ci.get_ciA( asstr=True ) )
            (-0.36473, 1.06872)
        '''
        return self._format_ci(self.ciA, asstr, with_brackets)
    def get_ciB(self, asstr=False, with_brackets=False):
        '''
        Interval about ``meanB`` if present, otherwise None.

        :Parameters:

        - *asstr* --- if True, return a formatted string (default False)
        - *with_brackets* --- if True, enclose the string in brackets (default
          False)

        :Returns:

        - ``ciB`` as an array (string if *asstr* is True) or None

        :Example:

            >>> import spm1d
            >>> y0, y1 = spm1d.rng.ttest2( nsubj=8, seed=0 )
            >>> ci = spm1d.stats.ci_twosample( y0, y1, datum='meanA', mu='tailB' )
            >>> print( ci.get_ciB( asstr=True ) )
            (-1.24250, -0.52578)
        '''
        return self._format_ci(self.ciB, asstr, with_brackets)
    def plot(self, ax=None):
        '''
        Plot both 0D means with the interval(s) (see
        :func:`spm1d.plot.plot_ci_multisample_0d`).

        :Parameters:

        - *ax* --- axes [default: matplotlib.pyplot.gca()]

        :Returns:

        - None

        :Example:

            >>> import spm1d
            >>> y0, y1 = spm1d.rng.ttest2( nsubj=8, seed=0 )
            >>> ci = spm1d.stats.ci_twosample( y0, y1, datum='meanA' )
            >>> ci.plot()
        '''
        plot_ci_multisample_0d(self, ax)


class _CIMultiMean1D(_CIMultiMean):
    def plot(self, ax=None, x=None, linecolor=None, facecolor=None, edgecolor=None, alpha=0.5, autoset_ylim=True):
        '''
        Plot both mean continua with their confidence intervals (see
        :func:`spm1d.plot.plot_ci`).
        '''
        plot_ci(self, ax=ax, x=x, linecolor=linecolor, facecolor=facecolor, edgecolor=edgecolor, alpha=alpha, autoset_ylim=autoset_ylim)
class _CIMultiMean1DPlotter(object):
    def plot(self, ax=None, x=None, linecolors=('k','r'), facecolors=('0.8','r'), edgecolors=('0.4','r'), color_criterion='r', alphas=(0.5,0.5), autoset_ylim=True):
        '''
        Plot both 1D mean continua with the interval(s) (see
        :func:`spm1d.plot.plot_ci_multisample`).

        :Parameters:

        - *ax* --- axes [default: matplotlib.pyplot.gca()]
        - *x* --- (Q,) array of domain positions [default: 0, 1, ..., Q-1]
        - *linecolors* --- mean continuum colors [default: ('k', 'r')]
        - *facecolors* --- band fill colors [default: ('0.8', 'r')]
        - *edgecolors* --- band edge colors [default: ('0.4', 'r')]
        - *color_criterion* --- criterion line color [default: 'r']
        - *alphas* --- band transparencies [default: (0.5, 0.5)]
        - *autoset_ylim* --- if True (default), set y limits to show all
          plotted elements

        :Returns:

        - None

        :Example:

            >>> import spm1d
            >>> y0, y1 = spm1d.rng.ttest2( nsubj=8, Q=101, fwhm=20, seed=0 )
            >>> ci = spm1d.stats.ci_twosample( y0, y1, datum='meanA' )
            >>> ci.plot()
        '''
        plot_ci_multisample(self, ax=ax, x=x, linecolors=linecolors, facecolors=facecolors, edgecolors=edgecolors, color_criterion=color_criterion, alphas=alphas, autoset_ylim=autoset_ylim)


class _CIPairedSample(_CIMultiMean):
    _kind            = 'Paired sample'
class _CITwoSample(_CIMultiMean):
    _kind            = 'Two sample'
class _CIPairedDifference(_CIDifference):
    _kind            = 'Paired difference'
class _CITwoSampleDifference(_CIDifference):
    _kind            = 'Two-sample difference'


[docs] class CIOneSample0D(_CISingleMean, _CI0D): ''' 0D one-sample confidence interval. ''' pass
[docs] class CIPairedSample0D(_CIPairedSample, _CI0D): ''' 0D paired-sample confidence interval (``datum="meanA"``). ''' pass
[docs] class CITwoSample0D(_CITwoSample, _CI0D): ''' 0D two-sample confidence interval (``datum="meanA"``). ''' pass
[docs] class CIPairedDifference0D(_CIPairedDifference, _CI0D): ''' 0D paired-difference confidence interval. ''' pass
[docs] class CITwoSampleDifference0D(_CITwoSampleDifference, _CI0D): ''' 0D two-sample difference confidence interval. ''' pass
[docs] class CIOneSample1D(_CISingleMean, _CI1D): ''' 1D one-sample confidence interval. ''' pass
[docs] class CIPairedSample1D(_CIMultiMean1DPlotter, _CIPairedSample, _CI1D): ''' 1D paired-sample confidence interval (``datum="meanA"``). ''' pass
[docs] class CITwoSample1D(_CIMultiMean1DPlotter, _CITwoSample, _CI1D): ''' 1D two-sample confidence interval (``datum="meanA"``). ''' pass
[docs] class CIPairedDifference1D(_CIPairedDifference, _CI1D): ''' 1D paired-difference confidence interval. ''' pass
[docs] class CITwoSampleDifference1D(_CITwoSampleDifference, _CI1D): ''' 1D two-sample difference confidence interval. ''' pass