"""Q-32: Split by athlete, not by row -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q32-split-by-athlete/
Data:     https://apopt.com/data/tutorials/q32-split-by-athlete/ (keep raw/ next to this file)
"""

# %% [markdown]
# The file holds about 2,600 left-foot steps from an instrumented treadmill. Each runner
# contributes many steps, and neighboring steps of one runner are nearly copies of
# each other. A model tested on steps from runners it has already seen will look far better
# than it will be for a new runner. The fix is to split by **athlete**: every step of a runner
# goes to the same side.
#
# ### Open the file and label the runners
#
# The file names no runner. Each runner ran a ladder of rising speeds, so a speed the ladder
# has already used starts a new runner (the same inference as CS-13).

# %%
# Steps, trials and inferred runners
import numpy as np
import pandas as pd

df = pd.read_csv("raw/biomechanics.txt").replace(-9999, np.nan).dropna()
df = df[(df["lgt"] > 0) & df["lkneeswing"].between(0, 150)].copy()
df["trial"] = (df["speed"] != df["speed"].shift()).cumsum()   # a run of one speed
runner, seen, ids = 0, set(), {}
for t, speed in df.groupby("trial")["speed"].first().items():
    if not seen or speed in seen:          # a repeated speed starts a new ladder
        runner, seen = runner + 1, set()
    seen.add(speed)
    ids[t] = runner
df["runner"] = df["trial"].map(ids)
print(f"{len(df)} steps, {df['trial'].nunique()} trials, {df['runner'].nunique()} runners")
print("median steps per runner:", int(df.groupby("runner").size().median()))

# %% [markdown]
# ### Two splits, one model
#
# The model is five nearest neighbors on the nine gait measures, scaled inside a pipeline.
# The row split shuffles the steps into five folds. The athlete split makes the fold from the
# runner number: runner 1, 6, 11 and 16 in one fold, and so on (`runner % 5`). Fixed folds
# give the same answer in every version of scikit-learn; `GroupKFold` does the same job, but
# how it assigns runners to folds has changed between versions.

# %%
# Shuffled rows against whole runners held out
from sklearn.model_selection import KFold, PredefinedSplit, cross_val_predict
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score

FEATURES = ["lgt", "sr", "sl", "lkneeswing", "lhipflex", "lhipext", "lcmvert", "lkneesep", "lcmtoe"]
X, y = df[FEATURES], df["lpeakforce"]
model = make_pipeline(StandardScaler(), KNeighborsRegressor(5))
splits = {"by row": KFold(5, shuffle=True, random_state=0),
          "by runner": PredefinedSplit(df["runner"] % 5)}      # fold = runner number mod 5
pred = {name: cross_val_predict(model, X, y, cv=cv) for name, cv in splits.items()}
for name, p in pred.items():
    print(f"split {name:10s} R² {r2_score(y, p):.2f}")
print("runners in fold 1:", sorted(int(r) for r in df.loc[df["runner"] % 5 == 1, "runner"].unique()))

# %% [markdown]
# ### Where the difference comes from
#
# Compare the error for each runner under the two splits.

# %%
# Error for each runner, two ways
import matplotlib.pyplot as plt

err = pd.DataFrame({name: (p - y).abs() for name, p in pred.items()}).groupby(df["runner"]).mean()
print(err.mean().round(2).to_string())
print("runners whose error grew more than threefold:", int((err["by runner"] > 3 * err["by row"]).sum()))
fig, ax = plt.subplots(figsize=(6.4, 3.0))
ax.plot(err.index, err["by row"], "o", mfc="white", mec="black", label="split by row")
ax.plot(err.index, err["by runner"], "s", color="black", label="runner held out")
ax.set(xlabel="runner", ylabel="mean error (body weights)", xticks=err.index,
       title="Held out, most runners are predicted far worse")
ax.legend()
plt.tight_layout()

# %% [markdown]
# With a row split, every runner's own steps sat in the training folds, a few rows away, and
# the nearest neighbors found them. Held out, the model has to predict a runner it never saw,
# which is the job a coach would give it. Report the second number.
#
# **For the athlete:** "A model like this one would get your peak force wrong by about a
# fifth of your body weight on an average step, so we use it to rank gait measures, not to
# tell you your force."
