"""
n-way MANOVA and MANCOVA
========================

In spm1d v0.4 only ``manova1`` (one-way MANOVA) was available.  Version 0.5 adds
``manova2``, ``manova3`` and ``mancova``. The 0.5 implementation of MANCOVA permits
one factor with any number of covariates. Wilks' Λ is used in all tests with test
statistic: Rao's F.

The data below are the Palmer penguins dataset. Factor A is species and Factor B
is sex.
"""

import numpy as np
from matplotlib import pyplot as plt
import spm1d
import jikudata as jd

dataset = jd.R_Penguins()   # 0D dataset:  bill length, bill depth, flipper length, body mass
y       = dataset.y         # (333,4) array of responses
A, B, _ = dataset.x.T       # species, sex and year

FFi     = spm1d.stats.manova2( y, A, B ).inference( 0.05 )
print( FFi )
print( "Wilks' lambda:", [ round( float(F.fit.wilks), 3 ) for F in FFi ] )

# %%
#  |
#  |
#  |
#
#  The figure below depicts two-way MANOVA for 0D multivariate data in which
#  factor A has three levels and factor B has two levels. Thick arrows represent
#  means and faint arrows represent individual observations.
plt.rc( 'font', family='sans-serif' )
plt.rc( 'font', **{'sans-serif': ['Helvetica Neue', 'Helvetica', 'Arial', 'Liberation Sans', 'DejaVu Sans']} )
fig    = plt.figure( figsize=(10, 6) )
ax     = fig.add_axes( [0.0, 0.0, 1, 1] )
yz     = ( y - y.mean( axis=0 ) ) / y.std( axis=0 )                            # standardized responses
colors = ('#5c6569', '#2eb0ce', '#0e6e84')
x      = 2.6 * np.arange( 6 )
for k, (a, b) in enumerate( [ (a, b)  for a in range(3)  for b in range(2) ] ):
    i      = (A == a) & (B == b)
    d      = 0.9 * yz[i][:, [0, 1]]                                             # (n,2) vectors:  bill length (horizontal), bill depth (vertical)
    ax.quiver( np.full( d.shape[0], x[k] ), np.zeros( d.shape[0] ), d[:, 0], d[:, 1], color=colors[a], alpha=0.25,
               angles='xy', scale_units='xy', scale=1, width=0.004, headwidth=4, headlength=5 )
    dm     = d.mean( axis=0 )
    ax.quiver( [x[k]], [0], [dm[0]], [dm[1]], color=colors[a], angles='xy', scale_units='xy', scale=1,
               width=0.007, headwidth=3.5, headlength=4, edgecolor='k', linewidth=1 )
    ax.plot( x[k], 0, 'o', ms=9, color='k' )
    ax.text( x[k], -2.6, f'B{b+1}', fontsize=22, ha='center', va='top' )
ax.plot( [-2.2, 16.4], [0, 0], color='0.4', lw=1.2 )
ax.set_xlim( -2.2, 16.4 );  ax.set_ylim( -3.4, 3.4 )
ax.axis( 'off' )
for a in range(3):
    ax.text( x[2*a:2*a+2].mean(), 3.2, f'A{a+1}', fontsize=24, color=colors[a], ha='center', va='top' )
plt.show()
