"""
Regions of interest
===================

**spm1d** 0.5 supports ROI specification at the
inference stage via ``inference( alpha, roi=roi )``. ROI analysis is
available for all ``spm1d.stats`` procedures including multivariate tests.

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

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

dataset = jd.PlantarArchAngle()     # 1D dataset:  two conditions, ten participants
y, A    = dataset.y, dataset.x
y0, y1  = y[A == 0], y[A == 1]
roi     = np.arange( 101 ) >= 70    # region of interest:  the final 30% of the domain
t       = spm1d.stats.ttest_paired( y1, y0 )
ti      = t.inference( 0.05 )
tiroi   = t.inference( 0.05, roi=roi )
print( f'whole domain:        zc = {ti.zc:.3f}' )
print( f'region of interest:  zc = {tiroi.zc:.3f}' )

# %%
#  |
#  |
#
#  The figure below depicts inference restricted to an ROI (shaded). The
#  critical threshold is lower than for the whole domain because a smaller
#  part of the domain is searched. No inference is conducted outside the
#  ROI, so conclusions must pertain only to the ROI.
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.set_ylim( (-t.z).min() - 0.5, 1.12 * (-t.z).max() )
plot_roi( roi, ax=ax, facecolor='0.88' )
ax.plot( -t.z, color='0.6', lw=3 )                        # sign flipped:  the effect is negative
ax.plot( np.where( roi, -t.z, np.nan ), 'k', lw=3 )
ax.axhline( 0, color='0.6', ls=':' )
ax.axhline( ti.zc, color='0.5', ls='--', lw=2 )
ax.axhline( tiroi.zc, color='r', ls='--', lw=2 )
ax.text( 68, ti.zc + 0.1, 'Whole domain threshold  ', ha='right', va='bottom', fontsize=26, color='0.4' )
ax.text( 68, tiroi.zc - 0.1, 'ROI threshold  ', ha='right', va='top', fontsize=26, color='r' )
ax.set_xlim( 0, 100 )
ax.set_yticks( [] )
ax.tick_params( labelsize=14 )
for side in ('left', 'right', 'top'):
    ax.spines[side].set_visible( False )

# %%
#  |
#  |
#
#  The ``plot_roi`` function can be used to overlay ROIs
#  as dark vertical patches on arbitrary axes.
plt.figure( figsize=(8, 4.5), tight_layout=True )
ax = plt.gca()
tiroi.plot( ax=ax )
plot_roi( roi, ax=ax, facecolor='0.85' )
ax.set_title( f'zc = {tiroi.zc:.2f} in the region  (vs {ti.zc:.2f} over the whole domain)' )
