"""
Random effects analysis
=======================

Random effects analysis models subjects as randomly drawn from a larger population,
and tests whether subject effects generalize to the population level. **spm1d**
does not offer an explicit interface to random effects analysis, but it does
support random effects modeling and analysis through a two-step hierarchical
procedure:

**Level 1**: Fit a model to each subject's data.

**Level 2**: Conduct random effects analysis on the subjects' fitted
parameter values.

The example below demonstrates how this can be implemented in **spm1d**.
The dataset comes from `Pataky et al. (2008)
<https://doi.org/10.1016/j.jbiomech.2008.03.034>`_ and consists of
ten subjects who each walked 60 times at a range of speeds.
The Level 1 model employs linear regression to estimate the slope
between walking speed and ground reaction force (GRF). The Level 2
model analyzes those slopes with a one-sample t test. If there were no
true slope effect, this approach would yield significance in 100α% of
experiments.

Refer to :doc:`/theory/random_effects` for more details.
"""

import numpy as np
from matplotlib import pyplot as plt
import spm1d
plt.rc( 'font', size=18 )             # minimum font size for all figure text

data = np.load( 'data/speed_grf_rfx.npz' )
y, x = data['y'], data['x']           # (10,60,101) GRF array (subjects, trials, time) and (10,60) walking speeds

beta = np.array( [spm1d.stats.regress( yy, xx ).fit.b[0]   for yy, xx in zip( y, x )] )   # level 1:  (10,101) slopes
ti   = spm1d.stats.ttest( beta ).inference( 0.05 )                                        # level 2:  null hypothesis slope = 0

# %%
#  |
#  |
#
#  The random effects results below suggest that the mean subject slope
#  is significantly different from zero.
plt.figure(figsize=(8, 5.6))
ax = plt.axes([0.17,0.1,0.82,0.89])
ax.plot( beta.T, color='0.5', lw=1 )
ax.plot( beta.mean( axis=0 ), color='k', lw=3 )
ax.axhline( 0, color='k', ls=':' )
ax.set_ylabel( 'Per-subject slopes', size=24 )
ti.plot_cluster_patches( ax=ax, color='#6fd3e8', alpha=0.3 ) 
ax.set_xticks( [0, 50, 100] )
plt.show()