"""CS-13: Predicting peak left-leg force -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/cs13-peak-force/
Data:     https://apopt.com/data/tutorials/cs13-peak-force/ (keep raw/ next to this file)
"""

# %% [markdown]
# ## Part 1 (Week 9): reproduce the course result
#
# The Data-Driven Engineering course fits this data set and reports an R² near 0.94. Part 1
# repeats that work step by step, the way it is usually done. Part 2 (Week 11) checks whether
# the score holds for a runner the model has never seen.
#
# ### Step 1 · Gather
#
# The file is one row per left-foot step on an instrumented treadmill. Open it and look at
# the first rows before doing anything else.

# %%
# Step 1 · Open the raw file
import pandas as pd

raw = pd.read_csv("raw/biomechanics.txt")
print(raw.shape)
print(raw.head(3).to_string())

# %% [markdown]
# ### Step 2 · Statistics
#
# A profile first: count, mean, smallest and largest value of every column. The smallest
# value is where bad data usually shows itself.

# %%
# Step 2 · Profile every column
profile = raw.describe().T[["count", "mean", "min", "max"]]
print(profile.round(3).to_string())
print("rows holding -9999:", int((raw == -9999).any(axis=1).sum()))

# %% [markdown]
# Every measure has a minimum of −9999. That is not a force or an angle: it is the code the
# recording software wrote when it had no value. A model fitted with those rows in it would
# treat −9999 as a real number.
#
# ### Step 3 · Visualize
#
# Plot the target in recorded order. A picture shows the missing-value codes and also how
# the data is arranged: runs of steps at one speed.

# %%
# Step 3 · Look before you clean
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
ax[0].plot(raw["lpeakforce"].values, ".", ms=2)
ax[0].set(title="Raw: the -9999 codes", xlabel="row", ylabel="peak force (BW)")
ok = raw["lpeakforce"] > -9999
ax[1].plot(raw.index[ok], raw["lpeakforce"][ok], ".", ms=2)
ax[1].set(title="Without them", xlabel="row", ylabel="peak force (BW)")
plt.tight_layout()

# %% [markdown]
# ### Step 4 · Cleanse
#
# Write the rules down before applying them, keep the raw file untouched, and log how many
# rows each rule removes. The two range rules are the ones the Data-Driven Engineering page
# uses: contact time must be positive and the knee angle at peak swing must lie between 0 and
# 150 degrees.
#
# Two columns are added while the rows are still in recorded order: `trial` (a run of steps
# at one speed) and `runner` (a ladder of rising speeds; a speed the ladder has already used
# starts a new runner). The file has no runner names, so this is an inference, and it matters
# in Part 2.

# %%
# Step 4 · Rules, a change log and a clean copy
import numpy as np
import os

df = raw.replace(-9999, np.nan)
df["trial"] = (df["speed"] != df["speed"].shift()).cumsum()
runner, seen, ids = 0, set(), {}
for t, g in df.groupby("trial"):
    s = g["speed"].iloc[0]
    if not seen or s in seen:
        runner, seen = runner + 1, set()
    seen.add(s)
    ids[t] = runner
df["runner"] = df["trial"].map(ids)

RULES = {
    "missing value (-9999)": lambda d: d.drop(columns=["trial", "runner"]).isna().any(axis=1),
    "contact time not positive": lambda d: ~(d["lgt"] > 0),
    "knee swing angle outside 0-150 deg": lambda d: ~d["lkneeswing"].between(0, 150),
}
log = []
for name, rule in RULES.items():
    bad = rule(df)
    log.append({"rule": name, "rows_removed": int(bad.sum()), "rows_left": int((~bad).sum())})
    df = df[~bad]
df = df.reset_index(drop=True)
os.makedirs("clean", exist_ok=True)
df.to_csv("clean/biomechanics_clean.csv", index=False)
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
print(pd.DataFrame(log).to_string(index=False))
print(f"{len(df)} steps, {df['trial'].nunique()} trials, {df['runner'].nunique()} runners")

# %% [markdown]
# ### Step 5 · Features, including one from physics
#
# Two kinds of feature. The nine measured gait features are already columns. The tenth comes
# from physics: over a whole step the vertical force must average one body weight, or the
# runner would rise or sink. The foot is down for only part of the step, so the force during
# contact is larger, and if it is shaped like half a sine wave its peak is π/2 times its mean:
#
# peak force / body weight ≈ (π/2) × step time / contact time, with step time = 1 / (2 × stride rate).
#
# This uses two columns and no fitting at all. How close does it get?

# %%
# Step 5 · Rank the measured features, then try the physics estimate
from sklearn.feature_selection import f_regression

FEATURES = ["lgt", "sr", "sl", "lkneeswing", "lhipflex", "lhipext", "lcmvert", "lkneesep", "lcmtoe"]
X, y = df[FEATURES], df["lpeakforce"]
F, _ = f_regression(X, y)
scores = pd.Series(F, index=FEATURES).sort_values()

df["physics"] = (np.pi / 2) / (2 * df["sr"] * df["lgt"])
err = df["physics"] - y
r2_phys = 1 - (err ** 2).sum() / ((y - y.mean()) ** 2).sum()
print("strongest features:", ", ".join(f"{k} {v:.0f}" for k, v in scores[::-1][:3].items()))
print(f"physics estimate: mean error {err.mean():+.2f} BW, R² {r2_phys:.2f}, "
      f"correlation {np.corrcoef(df['physics'], y)[0, 1]:.2f}")

fig, ax = plt.subplots(1, 2, figsize=(9, 3.4))
ax[0].barh(scores.index, scores.values)
ax[0].set(title="F-score with peak force", xlabel="F-score")
ax[1].plot(y, df["physics"], ".", ms=2, alpha=0.4)
ax[1].plot([2, 5], [2, 5], "k--", lw=1)
ax[1].set(title="Physics alone, no fitting", xlabel="measured (BW)", ylabel="estimate (BW)")
plt.tight_layout()

# %% [markdown]
# Contact time and stride length are the two strongest single features, well ahead of the
# rest. The physics estimate, built from
# contact time and stride rate with no fitting at all, rises and falls with the measured force
# (correlation 0.74), but it runs about 0.3 body weights low, because a real force curve is
# more peaked than half a sine wave. R² punishes that offset, so on its own the estimate scores
# below zero: worse than always guessing the average. Keep it anyway; Part 2 shows why.
#
# ### Steps 7 and 8 · Scale and split, the usual way
#
# Now the course recipe: shuffle the rows, scale every column to mean 0 and standard
# deviation 1, keep the first 80% for training and the last 20% for testing, and compare
# several regressors. Five are fitted here so you can see each one; the Data-Driven
# Engineering page uses a package that fits dozens.

# %%
# Steps 7–8 · Scale everything, split by row, compare five models
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor
from sklearn.svm import SVR
from sklearn.metrics import r2_score, mean_squared_error

MODELS = {
    "linear": lambda: LinearRegression(),
    "5 neighbors": lambda: KNeighborsRegressor(5),
    "random forest": lambda: RandomForestRegressor(100, random_state=0),
    "extra trees": lambda: ExtraTreesRegressor(100, random_state=0),
    "support vector": lambda: SVR(),
}
data = df[FEATURES + ["lpeakforce"]].sample(frac=1, random_state=0)
scaled = pd.DataFrame(StandardScaler().fit_transform(data), columns=data.columns)
n = int(0.8 * len(scaled))
Xtr, Xte = scaled[FEATURES][:n], scaled[FEATURES][n:]
ytr, yte = scaled["lpeakforce"][:n], scaled["lpeakforce"][n:]
row_split = {}
for name, make in MODELS.items():
    pred = make().fit(Xtr, ytr).predict(Xte)
    row_split[name] = r2_score(yte, pred)
    print(f"{name:15s} R² {row_split[name]:.2f}  RMSE {mean_squared_error(yte, pred) ** 0.5:.2f} (scaled units)")

# %% [markdown]
# The tree ensembles and the nearest-neighbor model score above 0.9, the linear model far
# lower. That matches the course page. Before believing it, notice two things the recipe did.
# The scaler learned the mean and spread of **all** rows, including the 20% it was about to
# test on. And the split was by row: steps from the same runner, often the step just before
# and just after, sit on both sides of it.
#
# ## Part 2 (Week 11): would it work on a new runner?
#
# ### Step 7 again · Fit the scaler on the training rows only
#
# A pipeline fits the scaler inside each training set, so the test rows never inform it. The
# split is still by row, to change one thing at a time.

# %%
# Step 7, done right · Scaling inside a pipeline
from sklearn.pipeline import make_pipeline

shuffled = df.sample(frac=1, random_state=0)
tr, te = shuffled[:n], shuffled[n:]
for name in ["5 neighbors", "extra trees"]:
    pipe = make_pipeline(StandardScaler(), MODELS[name]()).fit(tr[FEATURES], tr["lpeakforce"])
    print(f"{name:15s} R² {r2_score(te['lpeakforce'], pipe.predict(te[FEATURES])):.2f} "
          f"(was {row_split[name]:.2f})")

# %% [markdown]
# Almost no change. With 2,600 rows the scaler's mean and spread barely move when 20% are
# removed, so this leak is small here. It is still a leak, and in a small data set it is not
# small. Keep the habit: anything that learns from data is fitted on training rows only.
#
# ### Step 8 again · Hold out whole runners
#
# The question a coach asks is about a runner who was not in the data. So hold out whole
# runners: five folds made from the runner number (runner 1, 6, 11, 16 in fold 1, and so on), so no
# runner is ever on both sides. scikit-learn's `GroupKFold` does the same job, but how it assigns
# runners to folds has changed between versions; fixed folds give the same answer everywhere.

# %%
# Step 8, done right · Split by runner
from sklearn.model_selection import PredefinedSplit, cross_val_predict

cv = PredefinedSplit(df["runner"] % 5)        # fold number from the runner number
grouped = {}
for name, make in MODELS.items():
    pred = cross_val_predict(make_pipeline(StandardScaler(), make()), df[FEATURES], df["lpeakforce"], cv=cv)
    grouped[name] = r2_score(df["lpeakforce"], pred)
    if name == "extra trees":
        trees_pred = pred
print(pd.DataFrame({"row split": row_split, "runners held out": grouped}).round(2).to_string())

rows_pipe = make_pipeline(StandardScaler(), MODELS["extra trees"]()).fit(tr[FEATURES], tr["lpeakforce"])
fig, ax = plt.subplots(1, 2, figsize=(9, 3.6), sharex=True, sharey=True)
ax[0].plot(te["lpeakforce"], rows_pipe.predict(te[FEATURES]), ".", ms=3, alpha=0.5)
ax[0].set(title=f"Row split: R² {row_split['extra trees']:.2f}", xlabel="measured (BW)", ylabel="predicted (BW)")
ax[1].plot(df["lpeakforce"], trees_pred, ".", ms=2, alpha=0.3)
ax[1].set(title=f"Runners held out: R² {grouped['extra trees']:.2f}", xlabel="measured (BW)")
for a in ax:
    a.plot([2, 5], [2, 5], "k--", lw=1)
plt.tight_layout()

# %% [markdown]
# The score falls a long way. With a row split, the model had already seen steps from the same
# runner at the same speed, a few rows away, and nearest-neighbor and tree models are very good
# at finding them. That is memory, not prediction.
#
# ### Step 5 again · Does the physics feature help a new runner?
#
# Add the physics estimate as a tenth feature and compare four answers under the honest split:
# physics alone, the mean (always predict the average), and the linear and extra-trees models
# with and without the physics feature.

# %%
# Physics, regression, and both together
def held_out_r2(features, make):
    pred = cross_val_predict(make_pipeline(StandardScaler(), make()), df[features], df["lpeakforce"], cv=cv)
    return r2_score(df["lpeakforce"], pred)

print(f"always the mean          R² {0:.2f}")
print(f"physics alone            R² {r2_phys:.2f}")
print(f"physics, one fitted line R² {held_out_r2(['physics'], MODELS['linear']):.2f}")
for name in ["linear", "extra trees"]:
    print(f"{name:12s} 9 features R² {held_out_r2(FEATURES, MODELS[name]):.2f}   "
          f"+ physics R² {held_out_r2(FEATURES + ['physics'], MODELS[name]):.2f}")

# %% [markdown]
# Read the table from the top. Physics alone is biased. Give it one fitted straight line,
# learned from the other runners, and the bias is gone. That one-feature model, built from two
# numbers a phone can measure, comes within about 0.1 of the best of the five fitted models
# with all nine features, and beats the nine-feature linear model. Adding the physics feature
# to the models does not help them: they already have contact time and stride rate.
#
# That is the finding to carry to the coach. Most of what can be predicted about peak force
# for a new runner comes from step timing, the share of each step the foot spends on the
# ground, through a relation physics explains. The other measures add little that transfers
# from one runner to the next.
