"""
Normality tests
==============================

**spm1d** introduces ``test_normality`` as a method of test
statistic objects. This method applies the D'Agostino–Pearson K² test to the
model's residuals for all univariate **spm1d.stats** tests. For 1D data the
K² field is thresholded using random field theory.

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

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

dataset = jd.PlantarArchAngle()     # 1D dataset:  two conditions, ten participants
y, A    = dataset.y, dataset.x
y0, y1  = y[A == 0], y[A == 1]
spm     = spm1d.stats.ttest_paired( y1, y0 )
ni      = spm.test_normality()      # normality test of the residuals
print( ni )

# %%
#  |
#  |
#
#  The figure below depicts the model's residuals (top) and the normality
#  K² field (bottom).
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) )
ax0 = fig.add_axes( [0.02, 0.50, 0.96, 0.48] )
ax1 = fig.add_axes( [0.02, 0.08, 0.96, 0.42] )
ax0.plot( spm.residuals.T, color='0.4', lw=1 )
ax0.axhline( 0, color='k', lw=1 )
ax0.text( 0.02, 0.95, 'Residuals', transform=ax0.transAxes, ha='left', va='top', fontsize=26 )
ax1.plot( ni.z, 'k', lw=3 )
ax1.axhline( ni.zc, color='r', ls='--', lw=2 )
ax1.text( 0.02, 0.95, 'Normality test', transform=ax1.transAxes, ha='left', va='top', fontsize=26 )
ax1.text( 100, ni.zc + 0.2, 'critical threshold', ha='right', va='bottom', fontsize=16, color='r' )
ax1.set_ylim( 0, 1.35 * ni.zc )
ax1.set_xlim( ax0.get_xlim() )
ax0.set_xticks( [] );  ax0.set_yticks( [] )
ax1.set_yticks( [] )
ax1.tick_params( labelsize=14 )
for ax in (ax0, ax1):
    for side in ('left', 'right', 'top'):
        ax.spines[side].set_visible( False )
ax0.spines['bottom'].set_visible( False )

# %%
#  |
#  |
#
#  The normality test is available for all designs. For example
#  after ANOVA the normality of the residuals can be tested as: 
dataset = jd.SpeedGRFcategorical()
F       = spm1d.stats.anova1( dataset.y, dataset.x )
print( F.test_normality() )
