"""Q-31: Scale two features, the right way and the wrong way -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q31-scale-right/
Data:     https://apopt.com/data/tutorials/q31-scale-right/ (keep raw/ next to this file)
"""

# %% [markdown]
# A nearest-neighbor model finds the past runs most like a new one by measuring a distance
# between them. If one feature is in steps per minute (about 165) and the other in meters
# (about 1.4), the distance is almost all step rate. **Scaling** puts both on one footing:
# subtract a mean and divide by a standard deviation, so each feature has mean 0 and spread 1.
#
# The question here is *whose* mean and standard deviation. The data are the first 30 runs an
# adult male athlete in his mid-40s recorded on a new watch, in the summer of 2024. The model
# learns from the first 20 and is tested on the last 10, in time order, the way a personal
# model is used: on runs it has not seen yet (Chapter 11, splitting by day).
#
# ### Open the file and convert the units

# %%
# Thirty runs, two features in different units
import pandas as pd

raw = pd.read_csv("raw/sessions_fit.csv")
# outdoor runs only: a blank sub_sport (treadmill and track runs have one)
runs = raw[(raw["sport"] == "running") & raw["sub_sport"].isna()]
runs = runs.sort_values("start_time").copy()
runs["km"] = runs["total_distance"] / 1000
runs["pace_s_km"] = runs["total_timer_time"] / runs["km"]  # pauses excluded
runs["cadence_spm"] = 2 * runs["avg_running_cadence"]      # one foot -> both feet
runs["step_m"] = runs["avg_step_length"] / 1000            # the watch stores mm
ok = (runs["km"] > 2) & (runs["cadence_spm"] > 100) & runs["step_m"].between(0.5, 3)
data = runs[ok].head(30).reset_index(drop=True)
X, y = ["cadence_spm", "step_m"], "pace_s_km"
train, test = data[:20], data[20:]
print(data[X + [y]].describe().loc[["mean", "std", "min", "max"]].round(2).to_string())

# %% [markdown]
# Step rate spreads by about 21 steps per minute and step length by about 0.13 m: a ratio
# of more than a hundred. Unscaled, a difference of one step per minute counts as much as a
# difference of a whole meter of step length. The low step rates (106 at the bottom) come from
# runs with walking in them, which also have the slowest paces.
#
# ### The right way: fit the scaler on the training runs only
#
# A **pipeline** joins the scaler and the model, so the scaler learns its mean and standard
# deviation inside `fit`, from the 20 training runs alone. The test runs are then scaled with
# those numbers, as a run next week would be.

# %%
# No scaling, then scaling done right
from sklearn.neighbors import KNeighborsRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import mean_absolute_error

def test_error(model, Xtr, Xte):
    model.fit(Xtr, train[y])
    return mean_absolute_error(test[y], model.predict(Xte))

mae = {"no scaling": test_error(KNeighborsRegressor(3), train[X], test[X]),
       "scaler fitted on training runs": test_error(
           make_pipeline(StandardScaler(), KNeighborsRegressor(3)), train[X], test[X])}
for k, v in mae.items():
    print(f"{k:32s} mean error {v:.1f} s/km")

# %% [markdown]
# ### The wrong way: fit the scaler on all 30 runs first
#
# The common shortcut scales the whole table and then splits it. The scaler has then seen
# the 10 test runs, which in real use would not exist yet. With only 30 runs, ten of them move
# the scaler's numbers a lot.

# %%
# The leak, measured
import matplotlib.pyplot as plt

leaky = StandardScaler().fit(data[X])                 # has seen the test runs
right = StandardScaler().fit(train[X])
mae["scaler fitted on all 30 runs"] = test_error(
    KNeighborsRegressor(3), leaky.transform(train[X]), leaky.transform(test[X]))
print("scaler mean, all runs:  ", leaky.mean_.round(2), " SD", leaky.scale_.round(3))
print("scaler mean, train only:", right.mean_.round(2), " SD", right.scale_.round(3))
print(f"leaky mean error {mae['scaler fitted on all 30 runs']:.1f} s/km")

order = ["no scaling", "scaler fitted on all 30 runs", "scaler fitted on training runs"]
fig, ax = plt.subplots(figsize=(6.4, 2.6))
ax.barh(["no scaling", "all 30 runs (leaks)", "training runs only"], [mae[k] for k in order],
        color=["0.75", "0.45", "0.15"], edgecolor="black")
ax.set(xlabel="mean error on the 10 test runs (s/km)", title="Scaling matters; the leak flatters")
plt.tight_layout()

# %% [markdown]
# Scaling cut the error by about a quarter, from 36.0 to 27.3 s/km. The leaky scaler looks
# better again, at 24.9 s/km, but that gain is not real: it came from knowing the spread of runs that had not happened yet.
# With thousands of rows the two scalers would be almost the same (CS-13 shows that); with 30
# they are not. The rule does not depend on size: anything that learns from data, a scaler
# included, is fitted on the training rows only.
#
# **For the athlete:** "The pace model was checked only on runs it had never seen, so its
# error of about 27 seconds per kilometer is the one you can expect next week."
