"""
Sphericity test
===============

**spm1d** version 0.5 introduces a ``test_sphericity`` method that conducts
Mauchly's sphericity test for repeated-measures designs.

The example below uses a 0D dataset.

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

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

dataset = jd.DatariumSelfesteem()   # 0D dataset:  ten subjects, three conditions
A, SUBJ = dataset.x.T               # condition and subject labels
x2i     = spm1d.stats.anova1rm( dataset.y, A, SUBJ ).test_sphericity()
print( x2i )

# %%
#  |
#  |
#
#  "Sphericity" means that the differences between conditions are equally
#  variable for all pairs of conditions. The figure below depicts simulated
#  non-spherical data from six subjects. The condition 1-2 differences are
#  nearly equal for all subjects but the condition 2-3 differences vary
#  widely.
rng  = np.random.default_rng( 0 )
y1   = np.linspace( 0, 2.5, 6 )
y2   = y1 + 1.5 + rng.normal( 0, 0.05, 6 )                    # nearly equal 1-2 differences
y3   = y2 + np.array( [3.5, -0.8, 1.7, -0.8, -0.3, -3.6] )    # widely varying 2-3 differences
ysim = np.vstack( [y1, y2, y3] )                              # (3,6) conditions by subjects

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.04, 0.10, 0.94, 0.88] )
for ys, color in zip( ysim.T, ('#08343f', '#0b5262', '#0e6e84', '#1e8fa9', '#2eb0ce', '#6fd3e8') ):
    ax.plot( [1, 2, 3], ys, 'o-', ms=14, lw=3, color=color )
ax.set_xticks( [1, 2, 3] )
ax.set_xticklabels( [ f'condition {a}' for a in (1, 2, 3) ], fontsize=18 )
ax.set_yticks( [] )
ax.set_xlim( 0.7, 3.3 )
ax.set_ylim( ysim.min() - 0.05 * np.ptp( ysim ), ysim.max() + 0.05 * np.ptp( ysim ) )
for side in ('left', 'right', 'top'):
    ax.spines[side].set_visible( False )

# %%
#  |
#  |
#
#  **spm1d** corrects for non-sphericity through the default covariance
#  model (``cov_model='unstructured'``). To force an assumption of
#  sphericity use ``cov_model='iid'``.
for cov_model in ('iid', 'unstructured'):
    Fi = spm1d.stats.anova1rm( dataset.y, A, SUBJ, cov_model=cov_model ).inference( 0.05 )
    print( f'{cov_model:13s} df = ({Fi.df[0]:.2f}, {Fi.df[1]:.2f}),  p = {Fi.p:.3f}' )
