"""
2D data
=======

Permutation inference can be applied to registered 2D data by flattening each
image into a 1D array. The critical threshold ``zc`` is valid for 2D data
because it depends only on the distribution of the image maximum, and not
on the spatial structure of the domain. Cluster p-values can not be calculated
using **spm1d** because 2D cluster assessment requires 2D data processing
procedures that are excluded from **spm1d**.

The example below uses plantar pressure images from `Pataky (2012)
<https://www.sciencedirect.com/science/article/pii/S0021929012003193>`_. One subject stood ten times
leaning backward and ten times leaning forward.

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

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

Y    = np.load( 'data/pressure2d.npy' )   # (20,60,32) array:  ten backward-leaning then ten forward-leaning images
y    = Y.reshape( 20, -1 )                # (20,1920) flattened images
eps  = np.finfo( float ).eps
i    = (y[:10].std( axis=0 ) > eps) & (y[10:].std( axis=0 ) > eps)   # pixels with non-zero variance in both tasks
np.random.seed( 0 )
ti   = spm1d.stats.ttest2( y[:10, i], y[10:, i] ).inference( 0.05, method='perm', nperm=10000 )

# %%
#  |
#  |
#
#  The figure below depicts the t-value image (left) and the same image
#  thresholded at ``zc`` (right). Here red and blue values indicate higher
#  and lower pressures in backward vs. forward leaning, respectively. 
z       = np.zeros( y.shape[1] )
z[i]    = ti.z
Z       = z.reshape( Y.shape[1:] )
Zi      = np.where( np.abs( Z ) > ti.zc, Z, 0 )
r,c     = np.nonzero( Z )
fig,axs = plt.subplots( 1, 2, figsize=(5.7, 4), tight_layout=True )   # thumbnail aspect 400:280
for ax, zz in zip( axs, [Z, Zi] ):
    ax.imshow( np.ma.masked_array( zz, zz == 0 ), origin='lower', cmap='RdBu_r', vmin=-15, vmax=15 )
    ax.set_xlim( c.min() - 1, c.max() + 1 )
    ax.set_ylim( r.min() - 1, r.max() + 1 )
    ax.set_axis_off()
axs[0].set_title( 't-value' )
axs[1].set_title( '|t| > zc' )
plt.show()
