# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# ## FPCA_FACE Demo
# ### <NAME> (<EMAIL>)

import numpy as np
import pandas as pd
from math import pi, sin, cos
import matplotlib.pyplot as plt
from fpca_face import FPCA_FACE

# ### Sample 1: Simulated Data

# +
# Generate Data
np.random.seed(123)
I = 50 
J = 3000 
t = [(j + 1) / J for j in range(J)] 
N = 4 
sigma = 2 
lambdaTrue = [1,0.5,0.5**2,0.5**3]
phi = np.sqrt(2) * pd.DataFrame({"phi1":[np.sin(2*pi*ti) for ti in t], \
              "phi2":[np.cos(2*pi*ti) for ti in t], \
              "phi3":[np.sin(4*pi*ti) for ti in t], \
              "phi4":[np.cos(4*pi*ti) for ti in t]})
xi = np.reshape(np.random.normal(size=I*N), (I,N))
xi = xi @ np.diag(np.sqrt(lambdaTrue))
X = xi @ (phi.values.T); # of size I by J
Y = X + sigma*np.reshape(np.random.normal(size=I*J), (I,J))

# Fit FPCA
mod = FPCA_FACE(Y=Y,argvals=t,npc=4,knots=35)
fit = mod.fit()

# Plot Estimates against truths (may be flipped over y-axis)
fig, ax_arr = plt.subplots(ncols=2, nrows=2, figsize=(12,6));

pd.DataFrame(fit.efunctions).plot(ax=ax_arr[0,0]);
phi.plot(ax=ax_arr[0,1]);

ax_arr[1,0].bar(list(range(len(fit.fve))), fit.fve);
ax_arr[1,1].bar(list(range(len(fit.fve))), lambdaTrue);

# -

# ### Sample 2: Real Data

# +
Y = pd.read_csv("dti.csv")
Y.T.plot(legend=False)
t = list(range(93))

# Fit FPCA
mod = FPCA_FACE(Y=Y,argvals=t,pve=0.8,knots=40,center=True)
fit = mod.fit()

# Plot Eigenfunctions
pd.DataFrame(fit.efunctions).plot();

StarcoderdataJupyterScriptsDedupFiltered