"""CS-7: Critical speed from a watch archive -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/cs07-critical-speed/
Data:     https://apopt.com/data/tutorials/cs07-critical-speed/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### Step 1 · Gather
#
# The archive is the instructor's 19 runs from April and May 2026, as his watch recorded them:
# one table of runs, one table of laps, and one file per run with a record every second
# (positions removed). No run in it was planned as a test. The question is whether a season of
# ordinary training holds enough hard running to estimate a critical speed, and so a pace for
# threshold sessions.

# %%
# Step 1 · Nineteen runs, one record a second
import numpy as np
import pandas as pd

runs = pd.read_csv("raw/activities.csv")
rec = {a: pd.read_csv(f"raw/{f}", parse_dates=["time"]) for a, f in zip(runs["activity_id"], runs["records_file"])}
print(f"{len(runs)} runs from {runs['date'].min()} to {runs['date'].max()}, "
      f"{runs['distance_km'].sum():.0f} km in {runs['moving_time_min'].sum() / 60:.1f} h")
print(f"{sum(len(r) for r in rec.values())} one-second records; columns: {list(rec[runs['activity_id'][0]].columns)}")
print(runs[["date", "distance_km", "moving_time_min", "pace_min_per_km", "avg_hr_bpm", "laps"]].to_string(index=False))

# %% [markdown]
# Pace in the run table is minutes per kilometre: all 19 runs average between 4.6 and 6.0
# minutes per km, steady running. A hard effort would hide inside a run, so the records are
# what to search.
#
# ### Step 2 · Statistics

# %%
# Step 2 · Profile the records: pauses and one-second steps
rows = []
for a, r in rec.items():
    gap = r["time"].diff().dt.total_seconds()
    step = r["distance_m"].diff()[gap == 1]
    rows.append({"run": a[:15], "records": len(r), "pauses": int((gap > 1).sum()),
                 "max_1s_step_m": step.max(), "steps_over_8m": int((step > 8).sum()),
                 "max_hr": r["heart_rate_bpm"].max()})
prof = pd.DataFrame(rows)
print(prof.to_string(index=False))
print(f"highest heart rate in the archive: {prof['max_hr'].max():.0f} beats/min")

# %% [markdown]
# Most runs have pauses (traffic, a drink, the watch stopped between repeats), and several have
# one-second distance steps of 14 to 26 m: 14 to 26 m/s, faster than any runner. A picture of one
# shows what they are.
#
# ### Step 3 · Visualize

# %%
# Step 3 · A one-second step of 17.5 m
import matplotlib.pyplot as plt

r = rec["2026-05-15_1509_running"]
w = r[(r["time"] >= "2026-05-15 22:11:55+00:00") & (r["time"] < "2026-05-15 22:12:25+00:00")]
s = (w["time"] - w["time"].iloc[0]).dt.total_seconds()
from_speed = w["distance_m"].iloc[0] + w["speed_mps"].fillna(0).cumsum().shift(fill_value=0)
print(w[["time", "distance_m", "speed_mps"]].iloc[8:16].to_string(index=False))
fig, ax = plt.subplots(figsize=(8, 3.2))
ax.step(s, w["distance_m"], where="post", color="k", label="distance field (raw)")
ax.plot(s, from_speed, "o--", ms=3, label="sum of the speed field")
ax.set(xlabel="time (s)", ylabel="distance (m)", title="2026-05-15: start of a fast repeat")
ax.legend(loc="upper left")
plt.tight_layout()

# %% [markdown]
# The runner was standing, then started a fast repeat. The watch's speed field rises at once,
# but its distance field stays put for twelve seconds and then catches up in two steps of
# 17.5 m, ending about 15 m above the summed speed. Which of the two is right second by second
# the file cannot say; over whole runs they differ by a percent or two. What matters here is
# narrower: a best effort whose window starts just before such a jump gains metres that were not
# run inside the window.
#
# ### Step 4 · Cleanse
#
# The rules, written before any best effort is computed:
#
# 1. A pause (a gap over 1 s between records) ends a stretch; no effort may span a pause.
# 2. An effort may not contain a one-second distance step over 8 m, faster than anything this
#    runner does; such a window is skipped, not repaired.
# 3. Only durations from 2 to 15 minutes are used, the range in which the critical-speed model
#    is normally fitted (Jones and Vanhatalo, 2017).

# %%
# Step 4 · Best efforts under the three rules
import os

DURATIONS = [120, 180, 240, 300, 420, 600, 720, 900]          # seconds, rule 3

def best_efforts(a, r):
    gap = r["time"].diff().dt.total_seconds()
    jump = ((r["distance_m"].diff() > 8) & (gap == 1)).to_numpy()
    out = []
    for _, g in r.groupby((gap != 1).cumsum()):                 # rule 1: stretches without pauses
        d, j, hr = g["distance_m"].to_numpy(), np.cumsum(jump[g.index]), g["heart_rate_bpm"].to_numpy()
        for T in [T for T in DURATIONS if len(d) > T]:
            gain = np.where(j[T:] - j[:-T] > 0, -1, d[T:] - d[:-T])  # rule 2: skip windows with a jump
            i = int(np.argmax(gain))
            if gain[i] > 0:
                out.append({"t_s": T, "d_m": gain[i], "run": a[:10], "start": g["time"].iloc[i],
                            "hr": np.nanmean(hr[i:i + T])})
    return out

eff = pd.DataFrame([e for a, r in rec.items() for e in best_efforts(a, r)])
best = eff.loc[eff.groupby("t_s")["d_m"].idxmax()].reset_index(drop=True)
best["v_mps"] = best["d_m"] / best["t_s"]
best["hr_pct"] = 100 * best["hr"] / prof["max_hr"].max()
os.makedirs("clean", exist_ok=True); best.to_csv("clean/best_efforts.csv", index=False)
print(f"{len(eff)} candidate efforts; the best at each duration:")
print(best[["t_s", "d_m", "v_mps", "run", "hr", "hr_pct"]].round(2).to_string(index=False))

# %% [markdown]
# Every best effort from 2 to 10 minutes comes from one run, 18 May, and the 12- and 15-minute
# bests from another, 11 April. The run table explains it: both runs held hard miles in the
# middle (on 18 May two miles in 343 and 321 s, on 11 April three in 369, 359 and 347 s), and
# no other run did. The heart rate says neither was all-out: 86 to 90% of the highest heart rate
# in the archive on 18 May, about 82% on 11 April.
#
# ### Step 5 · Features: the speed–duration line
#
# Section 6.5: plot each best effort as distance against time and fit a straight line,
# d = CS·t + D′. The slope is the critical speed; the intercept D′ is the distance that can be
# run above it.

# %%
# Step 5 · Critical speed and D′ from all eight efforts
cs, dprime = np.polyfit(best["t_s"], best["d_m"], 1)
best["resid_m"] = best["d_m"] - (cs * best["t_s"] + dprime)
pace = lambda v: f"{int(1000 / v // 60)}:{1000 / v % 60:04.1f} per km"
print(f"CS = {cs:.2f} m/s ({pace(cs)}), D' = {dprime:.0f} m")
print("residuals (m):", best["resid_m"].round(0).tolist())
print(f"R² = {1 - (best['resid_m'] ** 2).sum() / ((best['d_m'] - best['d_m'].mean()) ** 2).sum():.4f}")

# %% [markdown]
# A critical speed of 4.37 m/s and a D′ of 192 m are plausible numbers for a trained runner, and
# R² is 0.996, as high as a fit of distance against time always is (Section 6.5). The residuals are
# not plausible: they run from −72 m up to +129 m and back down to −68 m, a curve, not
# scatter. The 18 May points rise above the line and the 11 April points fall below it. A line
# through efforts from two different days, neither run to exhaustion, mostly measures how hard
# each day was.
#
# ### Step 8 · Split: hold out an effort, then hold out a run
#
# Hold out one effort, fit the other seven, and predict the one left out. Then do it the way
# CS-13 taught: the efforts of one run are not independent (the 2-minute best sits inside the
# 10-minute best), so hold out a whole run.

# %%
# Step 8 · How well does the line predict what it has not seen?
def fit(sub):
    return np.polyfit(sub["t_s"], sub["d_m"], 1)

loo = [best.loc[i, "d_m"] - np.polyval(fit(best.drop(i)), best.loc[i, "t_s"]) for i in best.index]
print("leave one effort out, prediction errors (m):", np.round(loo).astype(int).tolist())
for run in best["run"].unique():
    c, d0 = fit(best[best["run"] != run])
    print(f"fitted without {run}: CS {c:.2f} m/s ({pace(c)}), D' {d0:.0f} m")

fig, ax = plt.subplots(1, 2, figsize=(9, 3.6))
for run, m in zip(best["run"].unique(), ["o", "s"]):
    sub = best[best["run"] == run]
    ax[0].plot(sub["t_s"], sub["d_m"], m, mfc="none", color="k", label=run)
    ax[1].plot(sub["t_s"], sub["resid_m"], m, mfc="none", color="k", label=run)
tt = np.array([0, 960])
ax[0].plot(tt, cs * tt + dprime, "-", label="all efforts")
for run, ls in zip(best["run"].unique(), ["--", ":"]):
    ax[0].plot(tt, np.polyval(fit(best[best["run"] == run]), tt), ls, label=f"{run} only")
ax[0].set(xlabel="duration (s)", ylabel="best distance (m)"); ax[0].legend(fontsize=8)
ax[1].axhline(0, color="gray", lw=1)
ax[1].set(xlabel="duration (s)", ylabel="residual from all-efforts line (m)")
plt.tight_layout()

# %% [markdown]
# Holding out one effort at a time, the line misses by as much as 156 m. Holding out a run, the
# answer depends on which run is left: the 11 April efforts alone give 4.32 m/s, the 18 May
# efforts alone 4.79 m/s, 3:51 against 3:29 per kilometre. The archive brackets the
# critical speed; it does not measure it.
#
# That is the finding. Smyth and Muniz-Pumares (2020) estimated critical speed from the
# training logs of thousands of marathon runners and noted that raw training data cannot verify
# that an effort was maximal. Here the heart rate shows that it was not. For setting a threshold
# pace, the safe choice is the lowest estimate: threshold work sits just under critical speed
# (Section 6.5), and 4.32 m/s is the speed the athlete has already held for 15 minutes.
