"""CS-9: A season of load: fitness, fatigue, and a taper -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/cs09-fitness-fatigue/
Data:     https://apopt.com/data/tutorials/cs09-fitness-fatigue/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### Step 1 · Gather
#
# The case file holds the activity history of an adult male athlete in his mid-40s: one watch,
# every activity from June 2024 to November 2026, one row per activity. The rows are the FIT
# file's session fields, in the watch's own names and units: times in seconds, distance in
# metres, start times in UTC with a separate offset to the local clock. Section 2.8 describes
# Banister's fitness–fatigue model, which turns a training history into predicted performance.
# The question here: fitted to this athlete's own history, can it say when to start a taper?

# %%
# Step 1 · Open the export and put each activity on its local day
import numpy as np
import pandas as pd

raw = pd.read_csv("raw/sessions_fit.csv")
local = pd.to_datetime(raw["start_time"]) + pd.to_timedelta(raw["utc_offset_h"], unit="h")
act = pd.DataFrame({"date": local.dt.tz_localize(None).dt.normalize(),
                    "sport": raw["sub_sport"].fillna(raw["sport"]).replace({"lap_swimming": "swimming"}),
                    "minutes": raw["total_timer_time"] / 60,        # timer time: pauses excluded
                    "km": raw["total_distance"].fillna(0) / 1000,
                    "hr": raw["avg_heart_rate"], "hr_max": raw["max_heart_rate"],
                    "steps_min": 2 * raw["avg_running_cadence"],   # the watch counts one foot
                    "effort_mps": raw["Effort Pace"]})
print(f"{len(act)} activities, {act['date'].min():%Y-%m-%d} to {act['date'].max():%Y-%m-%d}; "
      f"heart rate on {act['hr'].notna().sum()}")
print(act.groupby("sport").agg(n=("hr", "size"), with_hr=("hr", "count"),
                               median_hr=("hr", "median")).sort_values("n", ascending=False).to_string())

# %% [markdown]
# Heart rate is present on all but 6 activities, in every sport. Swims read low: a median of
# 123 beats/min against 157 on outdoor runs, below everything but hikes and walks. Part of that is real, since swimming is easier on
# the heart at the same effort, and part is the sensor: a wrist sensor under water reads poorly.
#
# ### Step 2 · Statistics

# %%
# Step 2 · Two periods, many sports
act["period"] = np.where(act["date"] < "2026-01-01", "2024-25", "2026")
prof = act.groupby("period").agg(first=("date", "min"), last=("date", "max"), activities=("km", "size"),
                                 hours=("minutes", lambda m: m.sum() / 60),
                                 run_share=("sport", lambda s: (s == "running").mean()))
print(prof.round(2).to_string())
print(act.groupby("sport")["minutes"].sum().div(60).round(0).sort_values(ascending=False).to_string())
gaps = act["date"].drop_duplicates().sort_values().diff().dt.days
print(f"longest gap between active days: {gaps.max():.0f} days")

# %% [markdown]
# Eighteen months before 2026 and eleven months in it, with no long break: the longest gap is
# 27 days. There is no natural seam, so the split for Step 8 is a calendar one: fit on 2024–25,
# test on 2026. About seven of every ten activities are outdoor runs; the rest are elliptical,
# swims, indoor runs, rides, hikes and walks, and they hold about a third of the hours.
#
# ### Step 3 · Visualize

# %%
# Step 3 · Every outdoor run, speed against step rate
import matplotlib.pyplot as plt

runs_all = act[act["sport"] == "running"].assign(speed_mps=raw["enhanced_avg_speed"])
fig, ax = plt.subplots(figsize=(7, 3.6))
for long, m, lab in [(True, "o", "5 km or more"), (False, "x", "under 5 km")]:
    sub = runs_all[(runs_all["km"] >= 5) == long]
    ax.plot(sub["steps_min"], sub["speed_mps"], m, mfc="none", ms=4, alpha=0.6, color="k", label=lab)
ax.axvline(160, ls="--", color="gray", lw=0.8)
ax.set(xlabel="step rate (steps/min, both feet)", ylabel="average speed (m/s)")
ax.legend()
plt.tight_layout()
slow = runs_all[(runs_all["km"] >= 5) & (runs_all["steps_min"] < 160)]
print(f"median step rate, runs of 5 km or more: {runs_all.loc[runs_all['km'] >= 5, 'steps_min'].median():.0f}/min")
print("runs of 5 km or more under 160 steps/min, by half-year:",
      (slow["date"].dt.year.astype(str) + np.where(slow["date"].dt.month <= 6, " Jan-Jun", " Jul-Dec")).value_counts().sort_index().to_dict())

# %% [markdown]
# Most runs sit in a tight cloud near 176 steps a minute. Below 160 (the dashed line) is a tail
# of slow runs, 19 of the 22 longer ones from July to December 2024: runs with walking breaks,
# which lower the average speed and step rate together. A few fragments of under a kilometre lie near zero. And
# one problem the plot cannot show: a wrist sensor can lock onto the arm swing and report the
# step rate as the heart rate.
#
# ### Step 4 · Cleanse
#
# Two products, two sets of rules, written down before any model is fitted.
#
# **Load** keeps every activity, because every session tires the athlete. The six without heart
# rate get the median intensity of their own sport.
#
# **Performance runs** must be steady outdoor runs whose heart rate can be trusted:
#
# 1. Outdoor runs only (no treadmill, whose distance comes from the wrist).
# 2. Runs of 5 to 12 km, long enough to settle, short enough to limit heart-rate drift.
# 3. Heart rate and the watch's hill-adjusted speed both present.
# 4. A step rate of 160 or more, so the run had no walking breaks.
# 5. Heart rate not within 2 beats/min of the step rate (a possible lock on the arm swing).

# %%
# Step 4 · Apply the rules with a change log
import os

perf_runs, log = act.copy(), []
for name, bad in [("1 not an outdoor run", lambda d: d["sport"] != "running"),
                  ("2 not 5-12 km", lambda d: ~d["km"].between(5, 12)),
                  ("3 no heart rate or effort pace", lambda d: d["hr"].isna() | d["effort_mps"].isna()),
                  ("4 under 160 steps/min", lambda d: d["steps_min"] < 160),
                  ("5 heart rate within 2 of step rate", lambda d: (d["hr"] - d["steps_min"]).abs() <= 2)]:
    b = bad(perf_runs)
    log.append({"rule": name, "removed": int(b.sum()), "left": int((~b).sum())})
    perf_runs = perf_runs[~b]
os.makedirs("clean", exist_ok=True)
perf_runs.to_csv("clean/performance_runs.csv", index=False)
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
print(pd.DataFrame(log).to_string(index=False))

# %% [markdown]
# ### Step 5 · Features: a load for every day, and a performance measure
#
# **Load.** The case file's rule: load = minutes × (average heart rate / HRmax)². The square
# makes a hard minute count more than an easy one, as the heart-rate load of Section 6.6 does.
# HRmax is a stand-in: the 99th percentile of the maximum heart rate over all runs, not a tested
# maximum. Every sport counts by the same rule, so an hour on the elliptical at the same heart
# rate counts as an hour of running. That is an assumption, not a fact: the legs take far less
# pounding on the elliptical or in the pool, and the wrist under-reads swims, so their load is
# likely too low. Loads are summed per day, with zeros on days off.
#
# **Performance.** The history has no test, so one has to be derived. The measure: metres per
# heartbeat, the watch's hill-adjusted speed ("Effort Pace", whose formula is not published)
# divided by heart rate, the median over the performance runs in each 14-day block. Why: a
# fitter runner covers more ground per beat at an easy pace, and the median does not depend on
# whether he chose to run hard. Why it is a proxy: heat, sleep, illness and the sensor move the
# heart rate too, and a fortnight with one or two runs gives a noisy median.

# %%
# Step 5 · Daily load and fortnightly performance
hr_ref = act.loc[act["sport"].isin(["running", "indoor_running"]), "hr_max"].quantile(0.99)
act["factor"] = (act["hr"] / hr_ref) ** 2
act["factor"] = act["factor"].fillna(act.groupby("sport")["factor"].transform("median"))
act["load"] = act["minutes"] * act["factor"]
days = pd.date_range(act["date"].min(), act["date"].max())
load = act.groupby("date")["load"].sum().reindex(days, fill_value=0.0).to_numpy()
cross = act.loc[act["sport"] != "running", "load"].sum() / act["load"].sum()

pr = perf_runs.assign(m_per_beat=perf_runs["effort_mps"] * 60 / perf_runs["hr"],
                      block=(perf_runs["date"] - days[0]).dt.days // 14)
perf = pr.groupby("block").agg(date=("date", "max"), runs=("date", "size"),
                               m_per_beat=("m_per_beat", "median")).reset_index(drop=True)
perf["day"] = (perf["date"] - days[0]).dt.days
perf["train"] = perf["date"] < "2026-01-01"
perf.to_csv("clean/performance.csv", index=False)
print(f"HRmax stand-in {hr_ref:.0f} beats/min; {len(days)} days, mean daily load {load.mean():.1f}; "
      f"share of load not from outdoor runs {cross:.0%}")
print(perf.groupby("train")["m_per_beat"].describe().round(3).to_string())

# %% [markdown]
# Sixty-one performance points, 37 in 2024–25 and 24 in 2026. In 2024–25 the measure climbs
# from under 1.1 metres per beat in the run-walk months of 2024 to about 1.3 by late 2025
# (standard deviation 0.079). In 2026 it is nearly flat (0.037). About a quarter of the load
# (26%) comes from sessions other than outdoor runs. The model must explain the rise and the
# small wobbles around it.
#
# ### Step 8 · Split: fit on 2024–25, test on 2026
#
# The model of Section 2.8 is p(t) = p₀ + k₁·fitness(t) − k₂·fatigue(t), where fitness and
# fatigue are the daily loads before day t, each fading with its own time constant, τ₁ and τ₂.
# For fixed time constants the model is a straight line in p₀, k₁ and k₂, so the fit is a loop:
# for every pair (τ₁, τ₂) on a grid, fit the three numbers by least squares (with k₁, k₂ ≥ 0) on
# 2024–25, and keep the training error and the error on 2026.

# %%
# Step 8 · Fit every pair of time constants
from scipy.signal import lfilter
from scipy.optimize import lsq_linear
def response(w, tau):                                   # sum of earlier days' load, fading with tau
    a = np.exp(-1 / tau)
    return lfilter([0, a], [1, -a], w)

def fit_grid(y, d, tr):                                 # every (tau1, tau2): fit on tr, score both sides
    rows = []
    for t1 in range(5, 91):
        for t2 in range(1, min(t1, 31)):
            X = np.c_[np.ones(len(y)), response(load, t1)[d], -response(load, t2)[d]]
            fit = lsq_linear(X[tr], y[tr], bounds=([-np.inf, 0, 0], np.inf))
            res = X @ fit.x - y
            rows.append({"tau1": t1, "tau2": t2, "train_rmse": np.sqrt(np.mean(res[tr] ** 2)),
                         "test_rmse": np.sqrt(np.mean(res[~tr] ** 2)), "p0": fit.x[0], "k1": fit.x[1], "k2": fit.x[2]})
    return pd.DataFrame(rows)
y, tr, d = perf["m_per_beat"].to_numpy(), perf["train"].to_numpy(), perf["day"].to_numpy()
grid = fit_grid(y, d, tr)
best = grid.loc[grid["train_rmse"].idxmin()]
print(f"{len(grid)} pairs; best fit:", best.round(5).to_dict())
print(f"2024-25 mean as the forecast: train {y[tr].std():.3f}, test {np.sqrt(np.mean((y[~tr] - y[tr].mean()) ** 2)):.3f} m/beat")
near = grid[grid["train_rmse"] <= best["train_rmse"] * 1.025]   # within 5% in squared error
print(f"{len(near)} pairs fit within 5% of the best: tau1 {near['tau1'].min()}-{near['tau1'].max()} d, "
      f"tau2 {near['tau2'].min()}-{near['tau2'].max()} d; test RMSE {near['test_rmse'].min():.3f}-{near['test_rmse'].max():.3f}")
print("dashboard pair (42, 7):", grid[(grid["tau1"] == 42) & (grid["tau2"] == 7)][["train_rmse", "test_rmse"]].round(3).to_dict("records"))

# %% [markdown]
# The best pair sits on the edge of the grid, τ₁ = 90 days and τ₂ = 30 days, with tiny gains.
# In training it beats the 2024–25 mean (0.052 against 0.078 metres per beat), because it can
# draw the slow climb of the build-up. On 2026 it does worse than that same mean (0.054 against
# 0.040): fitness keeps rising with the load in the model, while the measure stopped rising.
# And 599 of the 2229 pairs fit within 5% of the best: every τ₁ from 57 to 90 days, and every
# fatigue constant from 1 to 30 days. The data say only that fitness changes slowly; they say
# nothing about how fast fatigue fades. The pair the dashboard uses for its 42-day and 7-day
# averages (Section 6.6) fits worse (0.057) and forecasts about as badly (0.055).

# %%
# Step 8 · The error landscape, and the forecast
fig, ax = plt.subplots(1, 2, figsize=(10, 3.8))
pv = grid.pivot(index="tau2", columns="tau1", values="train_rmse")
cs = ax[0].contourf(pv.columns, pv.index, pv.values, levels=12, cmap="Greys")
ax[0].plot(best["tau1"], best["tau2"], "w*", ms=14, mec="k", clip_on=False, zorder=5)
ax[0].set(xlabel="fitness time constant τ1 (days)", ylabel="fatigue time constant τ2 (days)")
fig.colorbar(cs, ax=ax[0], label="training RMSE (m/beat)")
p = best["p0"] + best["k1"] * response(load, best["tau1"]) - best["k2"] * response(load, best["tau2"])
ax[1].plot(days, p, "-", lw=0.8, color="gray", label="model (fitted on 2024-25)")
ax[1].plot(perf["date"], perf["m_per_beat"], "o", mfc="none", color="k", label="fortnight median, steady runs")
ax[1].axvline(pd.Timestamp("2026-01-01"), ls="--", color="k", lw=0.8)
ax[1].set(ylabel="metres per heartbeat"); ax[1].legend(fontsize=8, loc="lower right")
fig.autofmt_xdate()
plt.tight_layout()

# %% [markdown]
# Try the same model on a plan you draw yourself. The viewer below runs Banister's model in the
# page: change the taper's length and load, the two time constants and the weight on fatigue,
# and watch how the best race day moves. Try a fatigue constant of 2 days and then 20: the data
# here could not tell those apart.

# %% [markdown]
# ### Step 5 · When to start a taper?
#
# A taper is a short reduction in load before a race, which lets fatigue fade while fitness
# stays (Section 2.8). Ask each of the near-equally good models the same question: on a plan of
# twelve weeks at this athlete's 2026 mean daily load, with the last N days at half the load,
# which N gives the best race day?

# %%
# Step 5 · The best taper, model by model
base = load[days >= "2026-01-01"].mean()                 # 2026 mean daily load
def taper_gain(row):
    out = []
    for n in range(29):
        plan = np.full(85, base); plan[84 - n:84] *= 0.5
        out.append(row["p0"] + row["k1"] * response(plan, row["tau1"])[84] - row["k2"] * response(plan, row["tau2"])[84])
    return int(np.argmax(out)), max(out) - out[0]

tap = pd.DataFrame([dict(zip(["days", "gain"], taper_gain(r)), tau1=r["tau1"], tau2=r["tau2"])
                    for _, r in near.iterrows()])
dash = taper_gain(grid[(grid["tau1"] == 42) & (grid["tau2"] == 7)].iloc[0])
print(f"base load {base:.1f} a day; {len(tap)} near-best models: best taper from {tap['days'].min()} to {tap['days'].max()} days "
      f"(median {tap['days'].median():.0f}), predicted gain up to {tap['gain'].max():.4f} m/beat")
print(tap["days"].value_counts().sort_index().to_dict())
print(f"dashboard pair (42, 7): best taper {dash[0]} days, gain {dash[1]:.4f} m/beat")

# %% [markdown]
# Almost every near-best model says the same thing: no taper at all (517 of 599), or one or two
# days, with a predicted gain of at most 0.0004 metres per beat, far too small to measure. The
# dashboard pair says 3 days, for 0.0013. That is not evidence that a taper does nothing. It
# says that this measure, the ground covered per beat on an easy run, follows the slow build of
# fitness and barely moves after a hard week, so the fit learns nothing about fatigue. A taper
# acts on fatigue. The performance measure decides what the model can learn.

# %%
# Step 5 · Same question, a different performance measure
fast = pr.loc[pr.groupby("block")["effort_mps"].idxmax()]
y2, d2 = fast["effort_mps"].to_numpy(), (fast["date"] - days[0]).dt.days.to_numpy()
tr2 = (fast["date"] < "2026-01-01").to_numpy()
grid2 = fit_grid(y2, d2, tr2)
best2 = grid2.loc[grid2["train_rmse"].idxmin()]
near2 = grid2[grid2["train_rmse"] <= best2["train_rmse"] * 1.025]
tap2 = pd.DataFrame([dict(zip(["days", "gain"], taper_gain(r))) for _, r in near2.iterrows()])
print(f"best (tau1, tau2) = ({best2['tau1']:.0f}, {best2['tau2']:.0f}); train {best2['train_rmse']:.3f}, "
      f"test {best2['test_rmse']:.3f} m/s; 2024-25 mean as forecast: train {y2[tr2].std():.3f}, test {np.sqrt(np.mean((y2[~tr2] - y2[tr2].mean()) ** 2)):.3f}")
print(f"{len(near2)} of {len(grid2)} pairs within 5%; best taper {tap2['days'].min()}-{tap2['days'].max()} days "
      f"(median {tap2['days'].median():.0f}), predicted gain up to {tap2['gain'].max():.3f} m/s")

# %% [markdown]
# With the fortnight's fastest run as the measure, the answer changes. This measure depends on
# whether the athlete chose to run hard, and it is noisy: the model again forecasts 2026 worse
# than the 2024–25 mean (0.249 against 0.224 m/s), and 1666 of the 2229 pairs fit within 5% of
# the best. Those models recommend tapers from 0 to 22 days (median 2), with gains up to
# 0.064 m/s. Two defensible proxies, two different answers, and neither forecasts better than
# a flat line. The history cannot set the taper.
#
# Evidence from many athletes is stronger than a fit to one: a meta-analysis of 27 studies
# found the largest performance effect for a taper of about two weeks, with training volume cut
# by 41 to 60% and intensity and frequency kept (Bosquet and colleagues, 2007). The same
# weakness of the fitted model is reported in elite swimmers, where the fitted time constants
# had wide intervals and some parameters were so correlated that their separate values meant
# little (Hellard and colleagues, 2006). Treat the model as a way to think, as Section 2.8 says,
# set the taper from the population evidence, and watch this athlete's response. This is
# training information, not medical advice.
