"""
Paired t test
=============

A paired t test assesses whether the mean of paired within-subject
differences is different from zero.

The example below uses knee flexion data from `Fukuchi et al. (2017) <https://doi.org/10.6084/m9.figshare.4543435>`_
that were measured on 31 subjects at two running 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.Fukuchi2017running()        # 1D dataset:  three components, two conditions, 31 subjects
y, A    = dataset.y[:, :, 1], dataset.x  # (62,101) array of observations (knee flexion), (62,) array of condition labels
y0, y1  = y[A == 0], y[A == 1]           # two conditions
ti      = spm1d.stats.ttest_paired( y1, y0 ).inference( 0.05 )   # test statistic for  y1 - y0

# %%
#  |
#  |
#
#  The figure below depicts each subject's within-subject difference and
#  the mean difference.
plt.figure( figsize=(6.4, 4.5), tight_layout=True )
ax = plt.gca()
h0 = ax.plot( (y1 - y0).T, color='0.6', lw=0.8 )[0]
h1 = ax.plot( (y1 - y0).mean( axis=0 ), color='#2eb0ce', lw=5 )[0]
ax.axhline( 0, color='0.6', ls=':' )
ax.legend( [h0, h1], ['Paired differences', 'Mean'], fontsize=20 )

# %%
#  |
#  |
#
#  The figure below depicts the test statistic and the critical thresholds.
plt.figure( figsize=(8, 4.5), tight_layout=True )
ax = plt.gca()
ti.plot( ax=ax )
ax.yaxis.label.set_size( 20 )
h0, h1 = ax.lines[0], ax.lines[2]                 # the test statistic and the (upper) 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
