"""
One-sample Hotelling's T²
=========================

Hotelling's T² test is the multivariate generalization of the t test. **spm1d**
requires that data are arranged as ``(J, Q, I)`` arrays for 1D data and
``(J, I)`` arrays for 0D data, where:

- ``J``: number of observations
- ``Q``: number of domain points
- ``I``: number of vector components

The example below uses center of pressure trajectories from `Pataky et al.
(2014) <https://doi.org/10.1016/j.gaitpost.2014.01.023>`_. The data contain two
components for ten subjects in two conditions. The one-sample test is applied
to the within-subject differences between the two conditions. This is
equivalent to a paired Hotelling's T² test (``hotellings_paired``).
"""

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.Pataky2014cop()         # 1D dataset:  two components, two conditions, ten subjects
y, A    = dataset.y, dataset.x       # (20,101,2) array of observations, (20,) array of condition labels
d       = y[A == 1] - y[A == 0]      # (10,101,2) array of within-subject differences
T2i     = spm1d.stats.hotellings( d, 0 ).inference( 0.05 )   # null hypothesis:  mean difference = 0

# %%
#  |
#  |
#
#  The figure below depicts mean within-subject differences for each
#  component.
plt.figure( figsize=(6.4, 4.5), tight_layout=True )
ax = plt.gca()
for i in range( 2 ):
    ax.plot( d[:, :, i].mean( axis=0 ), lw=3, color=('#08343f', '#2eb0ce')[i], label=f'Component {i}' )
ax.axhline( 0, color='0.6', ls=':' )
ax.set_ylabel( 'Mean difference', fontsize=20 )
ax.set_ylim( -1.5, 9 )                            # room for the legend above the curves
ax.legend( fontsize=20, loc='upper left' )

# %%
#  |
#  |
#
#  The figure below depicts the T² statistic and the critical threshold.
plt.figure( figsize=(8, 4.5), tight_layout=True )
ax = plt.gca()
T2i.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
