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

The two-sample Hotelling's T² test is the multivariate generalization of the
two-sample t test. It assesses whether the mean vectors (or vector fields)
of two independent groups differ.

The example below uses joint angles during walking from `Fukuchi et al. (2018)
<https://doi.org/10.6084/m9.figshare.5722711>`_. The data contain hip, knee and
ankle angles for two groups of 24 and 27 subjects.
"""

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.Fukuchi2018walking()   # 1D dataset:  three components, two groups
y, A    = dataset.y, dataset.x      # (51,101,3) array of observations, (51,) array of group labels
y0, y1  = y[A == 0], y[A == 1]      # the two groups
T2i     = spm1d.stats.hotellings2( y1, y0 ).inference( 0.05 )

# %%
#  |
#  |
#
#  The figure below depicts the two groups' mean angles for the three joints.
plt.figure( figsize=(8, 6), tight_layout=True )
ax = plt.gca()
for i, (joint, xy, ls) in enumerate( zip( ('Hip', 'Knee', 'Ankle'), ((10, 40), (73, 48), (30, -12)), ('-', '--', ':') ) ):
    ax.plot( y0[:, :, i].mean( axis=0 ), 'k', lw=3, ls=ls )
    ax.plot( y1[:, :, i].mean( axis=0 ), color='#2eb0ce', lw=3, ls=ls )
    ax.text( *xy, joint, fontsize=24, ha='center', va='center' )
h0, h1 = ax.lines[0], ax.lines[1]                 # the two groups' hip curves
ax.set_xlabel( 'Time  (%)', fontsize=20 )
ax.set_ylabel( 'Angle  (deg)', fontsize=20 )
ax.legend( [h0, h1], ['Group 0', 'Group 1'], fontsize=20, ncol=2, loc='lower center', bbox_to_anchor=(0.5, 1) )   # above the axes

# %%
#  |
#  |
#
#  The figure below depicts the T² statistic and the critical threshold. See also:
#  :doc:`post hoc analysis options </theory/posthoc>`.
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
