"""
ANCOVA
======

ANCOVA was unavailable in **spm1d** version 0.4 but appears in 0.5 as:
``spm1d.stats.ancova( y, A, x )`` where the group effect ``A`` is
adjusted according to the continuous covariate ``x``.

The examples below use the `exam-score data from statology.org <https://www.statology.org/ancova-python/>`_
where the group factor is "study technique" and the covariate is "current grade",
with "exam score" as the dependent variable. For illustrative purposes the
first example uses fictional "current grade" values that are strongly
correlated with "exam score". The second example uses the original
dataset's "current grade" values.

These two examples demonstrate the various ways in which a covariate
can affect conclusions.
"""

# sphinx_gallery_thumbnail_path = '_static/thumbs/ancova.png'
import numpy as np
from matplotlib import pyplot as plt
import spm1d

A = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2])              # study technique
y = np.array([77, 89, 72, 74, 69, 78, 88, 93, 94, 90, 85, 81, 83, 88, 79])  # exam score

# %%
#  |
#  |
#
#  **Example 1**: This example uses constructed covariate values ``xc`` that
#  are highly correlated with ``y`` (r = 0.98). One-way ANOVA (without a 
#  covariance correction) detects a significant group effect. After adjusting
#  for the covariate the group effect is no longer significant because the
#  groups' differences in ``y`` are largely explained by their differences in
#  the covariate.
xc  = np.array([67, 80, 61, 62, 58, 68, 81, 81, 85, 77, 77, 73, 75, 79, 69])  # constructed covariate

Fi1 = spm1d.stats.anova1( y, A, cov_model='iid' ).inference( 0.05 )
Fic = spm1d.stats.ancova( y, A, xc, cov_model='iid' ).inference( 0.05 )
print( f'ANOVA  (no covariate):           F = {Fi1.z:.3f},  p = {Fi1.p:.3f},  h0reject = {Fi1.h0reject}' )
print( f'ANCOVA (constructed covariate):  F = {Fic.z:.3f},  p = {Fic.p:.3f},  h0reject = {Fic.h0reject}' )

# %%
#  |
#  |
#
#  The figure below depicts the data plotted against the constructed covariate.
#  The parallel lines depict the overall correlation between ``xc`` and ``y``
#  recentered at each group's mean. The covariate-adjusted group means
#  (i.e., the straight lines) differ only slightly and non-significantly.
plt.rc( 'font', family='sans-serif' )
plt.rc( 'font', **{'sans-serif': ['Helvetica Neue', 'Helvetica', 'Arial', 'Liberation Sans', 'DejaVu Sans']} )
bc  = Fic.fit.b                                                                 # model coefficients;  the covariate's is last
fig = plt.figure( figsize=(8, 6) )
ax  = fig.add_axes( [0.10, 0.12, 0.88, 0.86] )
xx  = np.linspace( xc.min() - 2, xc.max() + 2, 2 )
for a, color in zip( range(3), ('#08343f', 'C3', '#2eb0ce') ):
    ax.plot( xc[A == a], y[A == a], 'o', ms=12, color=color, label=f'Group {a + 1}' )
    ax.plot( xx, y[A == a].mean() + bc[-1] * (xx - xc[A == a].mean()), '-', color=color, lw=3 )
ax.legend( loc='upper left', fontsize=22, frameon=False )
ax.set_xlabel( 'Covariate', fontsize=26 )
ax.set_ylabel( 'Dependent variable', fontsize=26 )
ax.set_xticks( [] );  ax.set_yticks( [] )
ax.set_ylim( y.min() - 3, y.max() + 18 )
for side in ('right', 'top'):
    ax.spines[side].set_visible( False )

# %%
#  |
#  |
#
#  **Example 2**: This example uses the original covariate. The reported group
#  effect for it at `statology.org <https://www.statology.org/ancova-python/>`_
#  is F = 4.810 (p = 0.032), which ``spm1d.stats.ancova`` reproduces.

x = np.array([67, 88, 75, 77, 85, 92, 69, 77, 74, 88, 96, 91, 88, 82, 80])  # current grade

Fi = spm1d.stats.ancova( y, A, x, cov_model='iid' ).inference( 0.05 )
print( Fi )

# %%
#  |
#  |
#
#  With the covariate the group effect is slightly weaker but still
#  significant. This implies that variability that is attributable
#  to the covariate does not affect the conclusions regarding the
#  main group effect.
Fi1 = spm1d.stats.anova1( y, A, cov_model='iid' ).inference( 0.05 )
print( f'ANOVA  (no covariate):  F = {Fi1.z:.3f},  p = {Fi1.p:.3f}' )
print( f'ANCOVA (covariate):     F = {Fi.z:.3f},  p = {Fi.p:.3f}' )

# %%
#  |
#
b   = Fi.fit.b                                                                  # model coefficients;  the covariate's is last
fig = plt.figure( figsize=(8, 6) )
ax  = fig.add_axes( [0.10, 0.12, 0.88, 0.86] )
xx  = np.linspace( x.min() - 2, x.max() + 2, 2 )
for a, color in zip( range(3), ('#08343f', 'C3', '#2eb0ce') ):
    ax.plot( x[A == a], y[A == a], 'o', ms=12, color=color, label=f'Group {a + 1}' )
    ax.plot( xx, y[A == a].mean() + b[-1] * (xx - x[A == a].mean()), '-', color=color, lw=3 )
ax.legend( loc='upper left', fontsize=22, frameon=False )
ax.set_xlabel( 'Covariate', fontsize=26 )
ax.set_ylabel( 'Dependent variable', fontsize=26 )
ax.set_xticks( [] );  ax.set_yticks( [] )
ax.set_ylim( y.min() - 3, y.max() + 18 )
for side in ('right', 'top'):
    ax.spines[side].set_visible( False )


