"""
Inference methods
=================

**spm1d** 0.5 offers five inference methods, three more than 0.4. 
The desired inference method can be selected using the ``method``
argument of ``inference``:

- ``'rft'`` --- random field theory (default)
- ``'perm'`` --- permutation
- ``'fdr'`` --- false discovery rate
- ``'bonf'`` --- Bonferroni correction
- ``'uncorr'`` --- uncorrected; equivalent to 0D inference ⚠️

.. dropdown:: ⚠️ ``uncorr``

   The ``'uncorr'`` method is **not** a valid procedure for 1D data; it is provided only as a baseline for comparison.

All methods use the same test statistic but yield different critical
thresholds.

Refer to :doc:`/theory/inference` for more details.
"""

# sphinx_gallery_thumbnail_path = '_static/thumbs/inference_methods.png'
import numpy as np
from matplotlib import pyplot as plt
import spm1d
import jikudata as jd

dataset = jd.PlantarArchAngle()     # 1D dataset:  two conditions, ten participants
y, A    = dataset.y, dataset.x
y0, y1  = y[A == 0], y[A == 1]
t       = spm1d.stats.ttest_paired( y1, y0 )

# %%
#  |
#  |
#
#  The figure below depicts the critical thresholds of all five methods for
#  a single test statistic.
#
#  The ``method='uncorr'`` is the (invalid) 0D threshold, and serves only as a baseline
#  to show how much the other (valid) 1D procedures raise the critical
#  threshold. Using ``method='uncorr'`` generates the
#  ``SPM1DUncorrWarning`` shown below as a reminder that the procedure is not
#  valid.
#
#  .. code-block:: text
#     :class: spm1d-warning
#
#     SPM1DUncorrWarning: method="uncorr" yields uncorrected probabilities
#     which ignore the domain-level multiple comparisons problem and which are
#     not valid for domain-level analysis. These uncorrected probabilities are
#     provided in spm1d as a baseline for comparison with the other methods.
#     To force-allow access to these probabilities without a warning use:
#
#     warnings.filterwarnings("ignore", category=spm1d.exceptions.SPM1DUncorrWarning).


# sphinx_gallery_start_ignore
import warnings
warnings.filterwarnings( 'ignore', category=spm1d.exceptions.SPM1DUncorrWarning )   # the warning is shown in the styled block above
# sphinx_gallery_end_ignore
np.random.seed( 0 )                                       # reproducible permutations
results = {}
for method in ('rft', 'perm', 'fdr', 'bonf', 'uncorr'):
    kwargs = dict( nperm=1000 ) if (method == 'perm') else {}
    results[method] = t.inference( 0.05, method=method, **kwargs )
# sphinx_gallery_start_ignore
warnings.filterwarnings( 'always', category=spm1d.exceptions.SPM1DUncorrWarning )   # spm1d's default filter
# sphinx_gallery_end_ignore

plt.rc( 'font', family='sans-serif' )
plt.rc( 'font', **{'sans-serif': ['Helvetica Neue', 'Helvetica', 'Arial', 'Liberation Sans', 'DejaVu Sans']} )
fig = plt.figure( figsize=(8, 6) )
ax  = fig.add_axes( [0.02, 0.08, 0.96, 0.90] )
ax.plot( -t.z, 'k', lw=3 )                                # sign flipped:  the effect is negative
ax.axhline( 0, color='0.6', ls=':' )
colors = dict( rft='C3', perm='C1', fdr='C2', bonf='C4', uncorr='C0' )
xpos   = dict( rft=50, perm=30, fdr=70, bonf=50, uncorr=50 )           # staggered, so that near-equal thresholds do not overlap
for method, ti in results.items():
    ax.axhline( ti.zc, color=colors[method], lw=2.5, ls='--' )
    ax.text( xpos[method], ti.zc, method, ha='center', va='center', fontsize=26, color=colors[method],
             bbox=dict( boxstyle='round,pad=0.25', facecolor='w', edgecolor='none', alpha=0.8 ) )
ax.set_xlim( 0, 100 )
ax.set_ylim( (-t.z).min() - 0.5, 1.1 * max( (-t.z).max(), max( ti.zc for ti in results.values() ) ) )
ax.set_yticks( [] )
ax.tick_params( labelsize=14 )
for side in ('left', 'right', 'top'):
    ax.spines[side].set_visible( False )

# %%
#  |
#  |
#
#  These five methods control different error rates so their critical thresholds
#  differ. The thresholds depicted above pertain only to this
#  dataset. The ordering and relative proximities of the various thresholds
#  will generally vary from dataset to dataset. The ``uncorr`` method is always
#  expected to yield the lowest threshold and ``bonf`` is generally expected to
#  yield the highest. The other thresholds may vary substantially between these
#  two extremes. Note that ``perm`` can yield a higher threshold than ``bonf``
#  in certain cases such as very small sample sizes.
