'''
1D smoothness estimates (LKC and FWHM).
References:
Barnes GR, Ridgway GR, Flandin G, Woolrich M, Friston K (2013). Set-level
threshold-free tests on the intrinsic volumes of SPMs. NeuroImage 68:133-40.
https://doi.org/10.1016/j.neuroimage.2012.11.046
Taylor JE, Worsley KJ (2007). Detecting sparse signals in random fields, with
an application to brain mapping. Journal of the American Statistical
Association 102(479):913-28. https://doi.org/10.1198/016214507000000815
'''
# Copyright (C) 2026 Todd Pataky
from math import log
import numpy as np
from . _label import bwlabel
eps = np.finfo(float).eps
_4log2 = 4 * log(2)
class SmoothnessEstimates(object):
'''
Smoothness of a residual field (optionally restricted to a search region).
'''
def __init__(self, e, method='taylor2007', roi=None):
self.method = method
self.e = e
self.roi = None
self.rpn = None # resels per interval as a (Q-1,) array if the method provides them, otherwise None
self.fwhm = None
self.lkc = None
self.resels = None
if method != 'spm1d-v04':
self.rpn = resels_per_interval( e, method=method )
self.set_roi( roi )
def __repr__(self):
from .. util._rpr import DisplayParams
dp = DisplayParams( self )
dp.add_header( self.__class__.__name__ )
dp.add( 'J' )
dp.add( 'Q' )
dp.add( 'e', dp.fmt['array2shortstr'] )
if self.roi is not None:
dp.add( 'roi', dp.fmt['array2shortstr'] )
dp.add( 'fwhm', fmt='%.3f' )
dp.add( 'lkc', fmt='%.3f' )
dp.add( 'resels', fmt=dp.fmt['resels2str'] )
return dp.asstr()
def _estimate(self, roi):
if self.rpn is None: # legacy v0.4 behavior uses the whole-field FWHM with a region-masked node count
_mv = self.e.ndim == 3
_fwhm = estimate_fwhm_mv if _mv else estimate_fwhm
_counts = resel_counts_mv if _mv else resel_counts
self.fwhm = _fwhm(self.e, method=self.method)
if not np.isfinite( self.fwhm ):
_raise_infinite_smoothness( self.e, roi )
self.lkc = fwhm2lkc(self.fwhm, self.Q)
self.resels = _counts(self.e, self.fwhm, roi=roi)
return
b = self._validity_mask( roi )
ib = np.logical_and( b[:-1], b[1:] ) # intervals with both endpoints in the region
nintervals = int( ib.sum() ) # == nNodes - nClusters
nclusters = int( bwlabel(b)[1] )
resels = float( self.rpn[ib].sum() )
if not (resels > 0):
_raise_infinite_smoothness( self.e, roi )
self.resels = nclusters, resels
self.fwhm = nintervals / resels
self.lkc = resels2lkc( resels )
def _validity_mask(self, roi):
'''
Nodes usable by the smoothness estimate.
'''
isnan = np.isnan( self.e )
if isnan.ndim == 3:
# A node is unusable if any component is NaN.
isnan = np.any( isnan, axis=2 )
if roi is None:
return np.any( np.logical_not(isnan), axis=0 )
b = np.logical_not( np.any(isnan, axis=0) )
return np.logical_and( b, np.asarray(roi, dtype=bool) )
def as_roi(self, roi):
'''Copy restricted to ``roi``.'''
from copy import copy
sm = copy( self )
sm.set_roi( roi )
return sm
@property
def J(self):
return self.e.shape[0]
@property
def Q(self):
return self.e.shape[1]
def set_roi(self, roi):
self.roi = roi
self._estimate( roi )
# CONVERSION FUNCTIONS
[docs]
def fwhm2lkc(fwhm, Q):
'''
Lipschitz-Killing curvature (LKC) of a 1D field of a given smoothness.
:Parameters:
- *fwhm* --- field smoothness in nodes
- *Q* --- number of field nodes
:Returns:
- Field LKC
:Example:
>>> import spm1d
>>> print( round( spm1d.geom.fwhm2lkc( 20, 101 ), 3 ) )
8.326
'''
resels = (Q - 1) / fwhm # (Q-1) for point-based sampling, Q for element-based sampling
return resels2lkc( resels )
def _SPM1DError(msg):
from .. exceptions import SPM1DError
return SPM1DError( msg )
def nodes_str(flags):
'''
Location of flagged nodes for messages (e.g., "at node 41" or "at nodes 40
to 44").
'''
flags = np.asarray( flags, dtype=bool )
if flags.size == 1:
return 'in the data'
idx = np.argwhere( flags ).ravel().tolist()
if len(idx) == 1:
return 'at node %d' % idx[0]
if idx == list( range(idx[0], idx[-1]+1) ):
return 'at nodes %d to %d' % (idx[0], idx[-1])
return 'at nodes %s' % (idx if len(idx) <= 12 else '%s ... (%d nodes)' % (idx[:12], len(idx)))
def _flat_intervals(e):
'''
Boolean (Q-1,) array: True for intervals with constant residuals.
'''
e = np.asarray( e, dtype=float )
d = np.abs( np.diff( e, axis=1 ) )
tol = 64 * eps * ( np.abs( e ).max() if e.size else 0.0 )
return ( d <= tol ).all( axis=tuple(i for i in range(d.ndim) if i != 1) ) # one flag per interval
def _raise_infinite_smoothness(e, roi=None):
from .. exceptions import SPM1DInfiniteSmoothnessError
# Nodes where every residual is flat along the domain, i.e. both
# neighboring intervals carry no change.
flat = _flat_intervals( e )
const = np.zeros( e.shape[1], dtype=bool )
const[:-1] |= flat
const[1:] |= flat
if roi is not None:
inside = np.asarray( np.ma.getmaskarray(roi) if np.ma.isMaskedArray(roi) else ~np.asarray(roi, dtype=bool) )
const = np.logical_and( const, ~inside )
where = nodes_str( const ) if const.any() else 'along the domain'
raise SPM1DInfiniteSmoothnessError(
f'The residuals are constant {where}. The smoothness is therefore infinite and a 1D '
'(random field theory) threshold cannot be computed. Convert the data to 0D '
'(one value per observation such as "y[:, 0]") and use the 0D form of the procedure.' )
[docs]
def lkc2resels(lkc, d=1):
'''
Resel count of a field from its Lipschitz-Killing curvature (LKC).
Barnes et al. (2013) Eqn. 9: resels = (4 ln 2)^(-d/2) LKC.
:Parameters:
- *lkc* --- field LKC
- *d* --- field dimensionality (default 1)
:Returns:
- Field resel count
:Example:
>>> import spm1d
>>> print( round( spm1d.geom.lkc2resels( 8.0 ), 3 ) )
4.804
'''
return _4log2 **(-d/2) * lkc
[docs]
def lkc2fwhm(lkc, Q):
'''
Smoothness of a 1D field from its Lipschitz-Killing curvature (LKC).
:Parameters:
- *lkc* --- field LKC
- *Q* --- number of field nodes
:Returns:
- Field FWHM in nodes
:Example:
>>> import spm1d
>>> print( round( spm1d.geom.lkc2fwhm( 5, 101 ), 3 ) )
33.302
'''
resels = lkc2resels(lkc)
return (Q - 1) / resels # (Q-1) for point-based sampling, Q for element-based sampling
[docs]
def resels2lkc(resels, d=1):
'''
Lipschitz-Killing curvature (LKC) of a field from its resel count.
Inverse of :func:`lkc2resels`.
:Parameters:
- *resels* --- field resel count
- *d* --- field dimensionality (default 1)
:Returns:
- Field LKC
:Example:
>>> import spm1d
>>> print( round( spm1d.geom.resels2lkc( 5.0 ), 3 ) )
8.326
'''
return resels / ( _4log2 **(-d/2) )
# SMOOTHNESS ESTIMATION FUNCTIONS
def _estimate_fwhm_spm1d_v04(r, roi=None):
'''
Biased FWHM estimator from spm1d v0.4 (retained only for reproducing v0.4
results).
'''
if _flat_intervals( r ).all():
return np.inf # flat residuals give infinite smoothness. The caller refuses that
ssq = (r**2).sum(axis=0)
dy,dx = np.gradient(r) # gradient estimation (Method 2 from rft1d.geom)
v = (dx**2).sum(axis=0)
v /= (ssq + eps)
# ignore zero-variance nodes
i = np.isnan(v)
v = v[np.logical_not(i)]
rpn = np.sqrt( v / _4log2 ) # resels per node
m = rpn.mean()
fwhm = np.inf if (m == 0) else 1 / m # flat residuals give infinite smoothness. The caller refuses that
return fwhm
def _estimate_fwhm_kiebel1999(r, df=None):
'''
FWHM estimator of Kiebel et al. (1999) retained for comparison with the
default estimator.
r : (J,Q) array of residuals
df : error degrees of freedom (default J - 1)
'''
r = np.asarray( r, dtype=float )
J, Q = r.shape
nu = (J - 1) if (df is None) else float( df )
if nu <= 2:
raise _SPM1DError( f'The Kiebel et al. (1999) estimator needs more than two error degrees of freedom; the given residuals have {nu}.' )
if _flat_intervals( r ).all():
return np.inf
S = _unit_columns( r ) # eqn.13
dS = 0.5 * ( S[:, 2:] - S[:, :-2] ) # eqn.15, central differences at the interior nodes
lam = ( dS**2 ).sum( axis=0 ).mean() * (nu - 2) / (nu - 1) # eqn.16
return np.inf if (lam == 0) else float( np.sqrt( _4log2 / lam ) )
def _unit_columns(e):
"""
Residuals at each node divided by their norm. Constant nodes are set to
zero.
"""
d = (e**2).sum(axis=0)**0.5
return np.divide( e, d, out=np.zeros_like(e, dtype=float), where=(d > 0) )
def _lkc_per_interval_barnes2013(r):
"""Per-interval LKC contributions (Barnes et al. 2013 Eqns. 4-8)."""
u = _unit_columns( r ) # eqn.4
dR = np.diff(u, axis=1) # eqn.7
v = (dR**2).sum(axis=0)**0.5 # eqn.8
v[ _flat_intervals( r ) ] = 0 # constant to within rounding and so no change
return v
def _lkc_per_interval_taylor2007(e):
"""Per-interval LKC contributions (Taylor and Worsley 2007 Eqn. 6)."""
u = _unit_columns( e ) # eqn.5
d = np.diff(u, axis=1)
v = (d**2).sum(axis=0)**0.5
v[ _flat_intervals( e ) ] = 0 # constant to within rounding and so no change
return v
def _estimate_lkc_barnes2013(r):
'''
Lipschitz-Killing curvature (Barnes et al. 2013 Eqn. 9). Same result as
Taylor and Worsley (2007). Implemented as a check.
'''
return _lkc_per_interval_barnes2013( r ).sum() # eqn.9
def _estimate_lkc_taylor2007(e):
'''
Lipschitz-Killing curvature (Taylor and Worsley 2007 Eqn. 6).
'''
return _lkc_per_interval_taylor2007( e ).sum() # eqn.6
def _lkc_per_interval_mv_taylor2008(e):
"""
Per-interval LKC contributions for multivariate residuals (Taylor and
Worsley 2008 Eqn. 18).
"""
def _norm(a):
return (a**2).sum(axis=0)**0.5
n = e.shape[2] # number of vector components
v = np.zeros( e.shape[1] - 1 )
for i in range(n):
# All-zero residuals have no direction to normalize and contribute
# nothing. Degenerate nodes inside the search region are refused at
# inference.
d = _norm( e[:,:,i] )
u = np.divide( e[:,:,i], d, out=np.zeros_like(e[:,:,i]),
where=(d > 0) ) # normalized residuals
v = v + _norm( np.diff(u, axis=1) ) # this component's contribution
v[ _flat_intervals( e ) ] = 0 # constant to within rounding and so no change
return v / n
def _estimate_lkc_mv_taylor2008(e):
'''
Lipschitz-Killing curvature for multivariate residuals (Taylor and Worsley
2008 Eqn. 18).
Thank you to Fabian Telschow for helpful advice re: LKC estimates for
multivariate residuals.
'''
return _lkc_per_interval_mv_taylor2008( e ).sum() # eqn.18
def resels_per_interval(r, method='taylor2007'):
'''
Resels in each of the (Q-1) intervals between adjacent nodes.
r : (J,Q) array of residuals
'''
r = np.asarray(r)
if r.ndim == 3:
# Taylor & Worsley (2008) is the only multivariate estimator.
if method != 'taylor2008':
raise _SPM1DError( f'Multivariate residuals (J,Q,I) have only one per-interval estimator, "taylor2008"; the given method is "{method}".' )
return lkc2resels( _lkc_per_interval_mv_taylor2008(r) )
if method == 'taylor2007':
v = _lkc_per_interval_taylor2007(r)
elif method == 'barnes2013':
v = _lkc_per_interval_barnes2013(r)
elif method == 'taylor2008':
raise _SPM1DError( '"taylor2008" is the multivariate estimator and needs (J,Q,I) residuals. The given array is 2D. Use "taylor2007".' )
else:
raise _SPM1DError( f'No per-interval form for method "{method}" ("kiebel1999" and "spm1d-v04" are whole-field estimators, available through estimate_fwhm only). "method" must be one of: ["taylor2007", "barnes2013"] for univariate residuals, or "taylor2008" for multivariate ones.' )
return lkc2resels( v )
[docs]
def estimate_fwhm(r, method='taylor2007', roi=None, df=None):
'''
Estimate the FWHM (smoothness) of univariate residuals.
Methods:
- ``"taylor2007"`` (default): Lipschitz-Killing curvature estimator of
Taylor and Worsley (2007).
- ``"barnes2013"``: same estimator in the notation of Barnes et al. (2013).
- ``"kiebel1999"``: standardized-residual estimator of Kiebel et al. (1999)
Eqn. 16.
- ``"spm1d-v04"``: v0.4 estimator for reproducing v0.4 results.
:Parameters:
- *r* --- (J,Q) array of residuals with J observations and Q nodes
- *method* --- ``"taylor2007"`` (default), ``"barnes2013"``,
``"kiebel1999"`` or ``"spm1d-v04"``
- *roi* --- (**"spm1d-v04" only**) (Q,) boolean search region array
(default None: whole domain)
- *df* --- (**"kiebel1999" only**) error degrees of freedom (default None:
J - 1)
:Returns:
- FWHM in nodes (float)
:Example:
Smoothness of the residuals of a one-sample t test on ten simulated
responses from Pataky et al. (2015).
>>> import spm1d
>>> import jikudata as jd
>>> y = jd.SimulatedPataky2015b().y # (10,101) array
>>> t = spm1d.stats.ttest( y, 0 )
>>> print( round( spm1d.geom.estimate_fwhm( t.residuals ), 3 ) )
26.915
The example datasets require the jiku-data package:
``pip install "spm1d[data]"``.
:Note:
- Taylor JE, Worsley KJ (2007). Detecting sparse signals in random fields,
with an application to brain mapping. Journal of the American Statistical
Association 102:913-928.
- Barnes GR, Ridgway GR, Flandin G, Woolrich M, Friston K (2013). Set-level
threshold-free tests on the intrinsic volumes of SPMs. NeuroImage
68:133-140.
- Kiebel SJ, Poline JB, Friston KJ, Holmes AP, Worsley KJ (1999). Robust
smoothness estimation in statistical parametric maps using standardized
residuals from the general linear model. NeuroImage 10:756-766.
https://doi.org/10.1006/nimg.1999.0508
'''
if method=='spm1d-v04':
fwhm = _estimate_fwhm_spm1d_v04(r, roi=roi)
elif method == 'barnes2013':
lkc = _estimate_lkc_barnes2013(r)
fwhm = lkc2fwhm( lkc, r.shape[1] )
elif method == 'taylor2007':
lkc = _estimate_lkc_taylor2007(r)
fwhm = lkc2fwhm( lkc, r.shape[1] )
elif method == 'kiebel1999':
fwhm = _estimate_fwhm_kiebel1999(r, df=df)
else:
raise _SPM1DError( f'Unknown method: "{method}". "method" must be one of: ["taylor2007", "barnes2013", "kiebel1999", "spm1d-v04"]')
return fwhm
[docs]
def estimate_fwhm_mv(r, method='taylor2008'):
'''
Estimate the FWHM (smoothness) of multivariate residuals.
:Parameters:
- *r* --- (J,Q,I) residual array
- *method* --- ``"taylor2008"`` (default) or ``"spm1d-v04"``
:Returns:
- FWHM in nodes (float)
:Example:
Smoothness of the residuals of a one-sample Hotelling's T2 test on the
Dorn et al. (2012) dataset.
>>> import spm1d
>>> import jikudata as jd
>>> y = jd.Dorn2012().y # (8,100,3) array
>>> h = spm1d.stats.hotellings( y )
>>> print( round( spm1d.geom.estimate_fwhm_mv( h.residuals ), 3 ) )
13.599
The example datasets require the jiku-data package:
``pip install "spm1d[data]"``.
'''
if method == 'taylor2008':
lkc = _estimate_lkc_mv_taylor2008(r)
fwhm = lkc2fwhm( lkc, r.shape[1] )
elif method == 'spm1d-v04': # the v0.4 estimator, kept for comparison
fwhm = np.mean( [estimate_fwhm(r[:,:,i], method='spm1d-v04') for i in range(r.shape[2])] )
else:
raise _SPM1DError( f'Unknown method: "{method}". "method" must be one of: ["taylor2008", "spm1d-v04"]')
return fwhm
def _resel_counts(R, fwhm=1, element_based=False):
'''
Resel counts for continuous unbroken fields (modified from
rft1d.geom.resel_counts).
'''
if R.ndim==2:
b = np.any( np.logical_not(np.isnan(R)), axis=0)
else:
b = np.asarray(np.logical_not(R), dtype=bool)
nNodes = b.sum()
nClusters = bwlabel(b)[1]
if element_based:
resels = nClusters, float(nNodes)/fwhm
else:
resels = nClusters, float(nNodes-nClusters)/fwhm
return resels
[docs]
def resel_counts(r, fwhm=1, element_based=False, roi=None):
'''
Resolution element (resel) counts of a search domain.
:Parameters:
- *r* --- (J,Q) residual array (NaN: nodes without observations) or (Q,)
boolean mask (True: excluded nodes)
- *fwhm* --- residual smoothness in nodes (default 1)
- *element_based* --- if True, count inter-node elements instead of nodes
(default False)
- *roi* --- (Q,) boolean search region array (default None: whole domain)
:Returns:
- *resels0* --- search domain Euler characteristic
- *resels1* --- search domain length in FWHM units
:Example:
Resel counts of the residuals of a one-sample t test on ten simulated
responses from Pataky et al. (2015) for the whole domain and for a
region of interest.
>>> import numpy as np
>>> import spm1d
>>> import jikudata as jd
>>> y = jd.SimulatedPataky2015b().y # (10,101) array
>>> t = spm1d.stats.ttest( y, 0 )
>>> r0, r1 = spm1d.geom.resel_counts( t.residuals, fwhm=t.fwhm )
>>> print( r0, round( r1, 3 ) )
1 3.715
>>> roi = np.zeros( 101, dtype=bool )
>>> roi[20:60] = True
>>> r0, r1 = spm1d.geom.resel_counts( t.residuals, fwhm=t.fwhm, roi=roi )
>>> print( r0, round( r1, 3 ) )
1 1.449
The example datasets require the jiku-data package:
``pip install "spm1d[data]"``.
'''
# binary search area, False meaning masked
if roi is None: # continuous unbroken case
resels = _resel_counts(r, fwhm, element_based)
else:
b = np.any( np.isnan(r), axis=0) # node is True if nan
b = np.logical_and(np.logical_not(b), roi) # node is True if (in roi) and (not nan)
mask = np.logical_not(b) # True for masked-out regions
resels = resel_counts(mask, fwhm, element_based)
return resels
[docs]
def resel_counts_mv(r, fwhm=1, element_based=False, roi=None):
'''
Resolution element (resel) counts of a search domain from multivariate
residuals.
:Parameters:
- *r* --- (J,Q,I) residual array (nodes with all-zero residuals are
excluded)
- *fwhm* --- residual smoothness in nodes (default 1)
- *element_based* --- if True, count inter-node elements instead of nodes
(default False)
- *roi* --- (Q,) boolean search region array (default None: whole domain)
:Returns:
- *resels0* --- search domain Euler characteristic
- *resels1* --- search domain length in FWHM units
:Example:
Resel counts of the residuals of a one-sample Hotelling's T2 test on
the Dorn et al. (2012) dataset.
>>> import spm1d
>>> import jikudata as jd
>>> y = jd.Dorn2012().y # (8,100,3) array
>>> h = spm1d.stats.hotellings( y )
>>> r0, r1 = spm1d.geom.resel_counts_mv( h.residuals, fwhm=h.fwhm )
>>> print( r0, round( r1, 3 ) )
1 7.28
The example datasets require the jiku-data package:
``pip install "spm1d[data]"``.
'''
b = np.any(np.any(np.abs(r)>0, axis=0), axis=1) # False indicates no observations at that node
if roi is not None:
b = np.logical_and(b, roi) # node is True if in the ROI and not NaN
mask = np.logical_not(b) # True for masked-out regions
resels = resel_counts(mask, fwhm, element_based)
return resels