"""
Multivariate data smoothness estimates
======================================

**spm1d** 0.5 uses an improved smoothness measure for multivariate data.
Version 0.4 simply averaged smoothness estimates across components but
this neglects the smoothness of local *vector* changes. **spm1d** 0.5
uses the multivariate Lipschitz–Killing curvature (LKC) estimator of Taylor &
Worsley (2008).

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

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

# %%
#  |
#  |
#
#  The example below generates two bivariate random fields with known
#  smoothness and compares the true FWHM with the v0.5 and v0.4 estimates.
fwhms  = (10, 30)                                                               # true FWHM:  rough, smooth
fields = [ spm1d.rng.hotellings( nsubj=10, Q=101, fwhm=w, ncomp=2, seed=s )[0]  for w, s in zip( fwhms, (4, 1) ) ]   # (10,101,2) arrays
T2s    = [ spm1d.stats.hotellings( y, 0 )  for y in fields ]
ests   = [ T2.fwhm  for T2 in T2s ]                                             # 0.5:  multivariate LKC estimate
ests04 = [ spm1d.geom.estimate_fwhm_mv( T2.residuals, method='spm1d-v04' )  for T2 in T2s ]   # 0.4:  mean of component-wise estimates
for w, est, est04 in zip( fwhms, ests, ests04 ):
    print( f'true FWHM = {w:2d},  estimated FWHM = {est:.1f} (v0.5),  estimated FWHM = {est04:.1f} (v0.4)' )

#  each field is drawn as vectors standing on the domain:  component 1 points
#  into the page (drawn obliquely), component 2 points up
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) )
axs      = [ fig.add_axes( [0.02, 0.50, 0.96, 0.50] ), fig.add_axes( [0.02, 0.04, 0.96, 0.50] ) ]   # overlapping:  the vectors fill the figure
q        = np.arange( 0, 101, 2 )                                               # every second node
e1, e2   = np.array( [0.55, 0.3] ), np.array( [0.0, 1.0] )                      # screen directions of the two components
for ax, y, est in zip( axs, fields, ests ):
    u, v  = y[0, q, 0], y[0, q, 1]                                              # one observation:  the vector at each node
    rms   = np.sqrt( np.mean( u**2 + v**2 ) )
    u, v  = 7 * u / rms, 7 * v / rms                                            # scaled for display
    dx    = u * e1[0] + v * e2[0]                                               # the vectors on screen
    dy    = u * e1[1] + v * e2[1]
    angle = ( np.arctan2( v, u ) + np.pi ) / (2 * np.pi)                        # vector direction, for color
    ax.quiver( q, np.zeros_like( q ), dx, dy, color=plt.cm.hsv( angle ),
               angles='xy', scale_units='xy', scale=1, width=0.004, headwidth=4, headlength=5, clip_on=False )
    ax.plot( q + dx, dy, '-', color='0.3', lw=1, clip_on=False )                 # the path traced by the vector tips
    ax.plot( [0, 100], [0, 0], color='0.4', lw=1.2 )                            # the domain
    ax.set_xlim( -2, 108 );  ax.set_ylim( -10, 10 )
    ax.set_yticks( [] )
    ax.patch.set_alpha( 0 )                                                     # transparent, so the axes may overlap
    for side in ('left', 'right', 'top'):
        ax.spines[side].set_visible( False )
    ax.text( -1, dy[ q < 58 ].max() + 0.8, f'Estimated FWHM = {est:.1f}', ha='left', va='bottom', fontsize=26 )   # just above the vectors beneath it
axs[0].set_xticks( [] )
axs[0].spines['bottom'].set_visible( False )
axs[1].set_xticks( [0, 25, 50, 75, 100] )
axs[1].tick_params( labelsize=14 )

# %%
#  |
#  |
#
#  The example below uses a real bivariate dataset. The figure depicts the
#  critical thresholds implied by the v0.5 and v0.4 smoothness estimates.
dataset = jd.Pataky2014cop()    # 1D bivariate dataset (paired)
y, A    = dataset.y, dataset.x
T2      = spm1d.stats.hotellings_paired( y[A == 1], y[A == 0] )
fwhm04  = spm1d.geom.estimate_fwhm_mv( T2.residuals, method='spm1d-v04' )
T2i     = T2.inference( 0.05 )                                                  # 0.5 estimate
zc04    = rft1d.T2.isf( 0.05, T2.df, T2.Q, fwhm04 )                             # threshold at the 0.4 estimate
print( f'FWHM = {T2.fwhm:.3f} (v0.5),  {fwhm04:.3f} (v0.4);  critical T2 = {T2i.zc:.2f} (v0.5),  {zc04:.2f} (v0.4)' )

plt.figure( figsize=(8, 4.5), tight_layout=True )
ax = plt.gca()
T2i.plot( ax=ax )
ax.axhline( T2i.zc, color='k', ls='--', lw=2, label=f'v0.5 estimate  (FWHM = {T2.fwhm:.1f},  zc = {T2i.zc:.1f})' )
ax.axhline( zc04, color='r', ls='--', lw=2, label=f'v0.4 estimate  (FWHM = {fwhm04:.1f},  zc = {zc04:.1f})' )
ax.legend( loc='upper left', fontsize=11 )
ax.set_title( "Paired Hotelling's T2:  the smoothness estimate sets the threshold" )
