"""
Permutation inference
=====================

Permutation inference is a nonparametric method that does not assume normality
and which uses observation label permutation to calculate critical thresholds
and other probabilistic quantities **numerically** (and thus
slowly) directly from the data. It iteratively relabels the observations in ways
that are equivalent under the null hypothesis, recalculates the test statistic
for each relabeling, stores the maximum test statistic (z-max) for each relabeling
and then calculates the critical threshold from the resulting z-max distribution
simply as a distribution percentile. This procedure is equivalent to the "Fmax"
procedure from the functional data literature.

In **spm1d** v0.4 permutation inference was conducted through the
``spm1d.stats.nonparam`` module. In version 0.5 it is integrated with the
inference method as ``inference( alpha, method='perm' )``.

The example below uses plantar arch angles from `Caravaggi et al. (2010) <https://doi.org/10.1111/j.1469-7580.2010.01261.x>`_
that were measured on ten participants during normal-speed and fast walking and
compares the RFT and permutation thresholds for a paired t test.

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

import numpy as np
from matplotlib import pyplot as plt
import spm1d
import jikudata as jd
plt.rc( 'font', size=18 )             # minimum font size for all figure text

dataset = jd.PlantarArchAngle()      # 1D dataset:  two conditions, ten participants
y, A    = dataset.y, dataset.x       # (20,101) array of observations, (20,) array of condition labels
t       = spm1d.stats.ttest_paired( y[A == 1], y[A == 0] )   # test statistic
ti      = t.inference( 0.05 )                                # RFT inference
tp      = t.inference( 0.05, method='perm', nperm=-1 )       # permutation inference, using all possible permutations
print( f'RFT threshold:          {ti.zc:.3f}' )
print( f'permutation threshold:  {tp.zc:.3f}' )

# %%
#  |
#  |
#
#  The figure below depicts the test statistic (black) and both sets of
#  critical thresholds. The test statistic is identical for both methods. Only the
#  critical threshold differs.
plt.figure( figsize=(6.4, 4.5), tight_layout=True )
ax = plt.gca()
ax.plot( t.z, color='k', lw=3 )
ax.axhline( 0, color='0.6', ls=':' )
for zc, color, label in [(ti.zc, '#08343f', 'RFT'), (tp.zc, '#2eb0ce', 'Permutation')]:
    ax.axhline(  zc, color=color, lw=2.5, ls='--', label=label )
    ax.axhline( -zc, color=color, lw=2.5, ls='--' )
ax.legend( fontsize=20, ncol=2, loc='lower center', bbox_to_anchor=(0.5, 1) )   # critical thresholds;  above the axes
ax.set_ylabel( 't-value', fontsize=20 )
