"""
One-way repeated-measures ANOVA
===============================

A one-way repeated-measures ANOVA assesses whether three or more conditions
differ when all measurements can be paired across condition pairs. Usually
these are multiple measurements from the same subjects.

**spm1d** v0.4 assumed sphericity for this design. Version 0.5 corrects for
non-sphericity by default. Refer to :doc:`/theory/nonsphericity` for more
details.

The example below uses vertical ground reaction forces from `Pataky et al. (2008) <https://doi.org/10.1016/j.jbiomech.2008.03.034>`_
that were measured on ten subjects walking at three speeds.
"""

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

dataset  = jd.SpeedGRFcategoricalRM()   # 1D dataset:  ten subjects, three walking speeds
y        = dataset.y                    # (30,101) array of observations
A, SUBJ  = dataset.x.T                  # speed and subject labels
Fi       = spm1d.stats.anova1rm( y, A, SUBJ ).inference( 0.05 )
print( f'df = ({Fi.df[0]:.2f}, {Fi.df[1]:.2f})' )

# %%
#  |
#  |
#
#  The figure below depicts the mean force at each walking speed.
plt.figure( figsize=(6.4, 4.5), tight_layout=True )
ax = plt.gca()
for a, label, color in zip( np.unique( A ), ('Slow', 'Normal', 'Fast'), ('#2eb0ce', 'k', '#0e6e84') ):
    ax.plot( y[A == a].mean( axis=0 ), lw=3, color=color, label=label )
ax.set_ylim( 0, 2.9 )                             # room for the legend above the curves
ax.legend( fontsize=18, ncol=3, loc='upper center', handlelength=1, columnspacing=0.8 )

# %%
#  |
#  |
#
#  The figure below depicts the F statistic and the critical threshold.
plt.figure( figsize=(8, 4.5), tight_layout=True )
ax = plt.gca()
Fi.plot( ax=ax )
ax.yaxis.label.set_size( 20 )
h0, h1 = ax.lines[0], ax.lines[2]                 # the test statistic and the critical threshold
ax.legend( [h0, h1], ['Test statistic', 'Critical threshold'], fontsize=20, ncol=2, loc='lower center', bbox_to_anchor=(0.5, 1) )   # above the axes
