'''
False discovery rate (FDR) probabilities.
The corrected p values and the Benjamini/Yekutieli constant in "fdr" are
modified from statsmodels.stats.multitest.fdrcorrection:
https://github.com/statsmodels/statsmodels/blob/main/statsmodels/stats/multitest.py
Copyright (C) 2006, Jonathan E. Taylor
All rights reserved.
Copyright (c) 2006-2008 Scipy Developers.
All rights reserved.
Copyright (c) 2009-2018 statsmodels Developers.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
a. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
b. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
c. Neither the name of statsmodels nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL STATSMODELS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
'''
# Copyright (C) 2026 Todd Pataky
import numpy as np
from .. geom import assemble_clusters
from .. geom._clusters import ClusterList
from . _results import InferenceResults1D
from . _uncorr import p_uncorrected
[docs]
def fdr(STAT, z, df, alpha=0.05, dirn=0, circular=False, approach='bh'):
'''
False discovery rate (FDR) inference on a 1D test statistic field.
Corrected point-level p values follow
statsmodels.stats.multitest.fdrcorrection. Modified from fdr1d
(https://github.com/0todd0000/fdr1d).
:Parameters:
- *STAT* --- test statistic: ``'T'``, ``'F'``, ``'T2'`` or ``'X2'``
- *z* --- (Q,) test statistic field (optionally masked)
- *df* --- degrees of freedom as a two-element tuple
- *alpha* --- false discovery rate (default 0.05)
- *dirn* --- inference direction: 0 (two-tailed), +1 or -1 (one-tailed)
- *circular* --- True for circular domains
- *approach* --- ``'bh'`` (Benjamini-Hochberg, default) or ``'by'``
(Benjamini-Yekutieli)
:Returns:
- **InferenceResults1D** object
:Example:
FDR inference on the t field of a one-sample t test. No node passes the
criterion. The critical height is therefore infinite.
>>> import spm1d
>>> import jikudata as jd
>>> y = jd.SimulatedPataky2015b().y # (10,101) array
>>> t = spm1d.stats.ttest( y, 0 )
>>> results = spm1d.prob.fdr( 'T', t.z, t.df, alpha=0.05, dirn=1 )
>>> print( results.zc, results.h0reject, round( results.p_point.min(), 3 ) )
inf False 0.073
The example datasets require the jiku-data package:
``pip install "spm1d[data]"``.
'''
if isinstance(dirn, bool) or (dirn not in (-1, 0, 1)):
from .. exceptions import SPM1DError
raise SPM1DError( f'"dirn" must be -1, 0 or 1, not {dirn!r}.' )
if STAT != 'T':
dirn = 1
_stats = ["T", "F", "T2", "X2"]
if STAT not in _stats:
from .. exceptions import SPM1DError
raise SPM1DError( f'Unknown statistic: {STAT}. Must be one of: {_stats}' )
if approach not in ('bh', 'by'):
from .. exceptions import SPM1DError
raise SPM1DError( f'Unknown FDR approach {approach!r}; must be "bh" (Benjamini-Hochberg) or "by" (Benjamini-Yekutieli).' )
# A two-tailed T is ranked by |z| with two-tailed p-values.
twotailed = (STAT=='T') and (dirn==0)
_z = np.abs(z) if twotailed else z
a = alpha
# A masked z is a search region. Its nodes alone set Q, the ranks and the
# threshold. The corrected p-values are scattered back to full field length
# at the end.
inroi = np.logical_not( np.ma.getmaskarray(z) ) if np.ma.is_masked(z) else np.ones(z.size, dtype=bool)
_z = np.asarray( np.ma.getdata(_z) )[ inroi ]
Q = int( inroi.sum() )
pu = p_uncorrected(STAT, _z, df) # uncorrected p-values (upper tail)
pu = (1-pu) if (dirn==-1) else pu # lower tail
pu = np.minimum( 2*pu, 1 ) if twotailed else pu
ind = np.argsort(pu)
psorted = pu[ind]
# empirical CDF
ec = (np.arange(Q) + 1) / float(Q)
if approach=='bh': # Benjamini/Hochberg for independent or positively correlated tests
pass
elif approach=='by': # Benjamini/Yekutieli for general or negatively correlated tests (modified from statsmodels.stats.multitest.fdrcorrection)
cm = np.sum( 1. / np.arange(1, Q+1) )
ec = ec / cm
psortedth = a * ec # sorted p value threshold
b = psorted <= psortedth # Benjamini-Hochberg, p(k) <= k/Q * alpha
if np.any(b):
ii = np.argwhere(b).ravel()[-1]
# Just inside the least extreme rejected node, so that the clusters
# and h0reject agree. zc is a positive magnitude for every dirn, as
# for the other methods. It is applied at -zc when dirn is -1.
zc = abs( np.nextafter( _z[ind][ii], 0 ) )
else:
zc = np.inf # nothing rejected
# corrected p-values (modified from statsmodels.stats.multitest.fdrcorrection)
pc = psorted / ec
pc = np.minimum.accumulate( pc[::-1] )[::-1]
pc[pc>1] = 1
pc_ = np.empty_like(pc)
pc_[ind] = pc
if not inroi.all(): # back to full field length, masked outside the region
pc_full = np.ma.masked_all( inroi.size )
pc_full[ inroi ] = pc_
pc_ = pc_full
if not np.isfinite(zc):
clusters = ClusterList([])
else:
clusters = assemble_clusters(z, zc, dirn=dirn, circular=circular)
for i,c in enumerate( clusters ):
clusters[i] = c._as_inference_cluster(None, None)
p_set = None
p_point = pc_
extras = dict(approach=approach)
results = InferenceResults1D( 'fdr', STAT, z, alpha, df, dirn, zc, p_set, clusters, p_point, isparametric=True, extras=extras )
return results