"""CS-16: Forecast next week, and beat "same as last week" -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/cs16-forecast-load/
Data:     https://apopt.com/data/tutorials/cs16-forecast-load/ (keep raw/ next to this file)
"""

# %% [markdown]
# A coach planning next week's training wants a number for the load the athlete is likely to
# carry, with a range. Any forecast has to beat the simplest one there is: **same as last week**,
# the **persistence baseline** (Section 11.8.1). If it cannot, use persistence and say so.
#
# The data are two and a half years of activity summaries from one GPS watch with a wrist heart
# sensor, worn by an adult male athlete in his mid-40s who mostly runs, and also swims, uses an
# elliptical, rides and hikes. Load here is the case file's **training load**: moving minutes
# times (average heart rate / HRmax) squared, summed over every activity in a week, in arbitrary
# units (AU). A 50-minute run at 80% of HRmax adds 50 × 0.8² = 32 AU. This is training
# information, not medical advice.
#
# ### Step 1 · Gather
#
# The file is the watch's own FIT session summary, one row per activity, in the watch's units:
# times in seconds, distances in meters, and the start time in UTC with a separate offset to the
# local clock.

# %%
# Step 1 · Open the export and put the start on the local clock
import numpy as np
import pandas as pd

raw = pd.read_csv("raw/sessions_fit.csv")
utc = pd.to_datetime(raw["start_time"]).dt.tz_localize(None)
act = pd.DataFrame({
    "start": utc + pd.to_timedelta(raw["utc_offset_h"], unit="h"),   # local clock
    "sport": raw["sport"],
    "minutes": raw["total_timer_time"] / 60,                         # s -> min, pauses excluded
    "km": raw["total_distance"] / 1000,                              # m -> km
    "avg_hr": raw["avg_heart_rate"], "max_hr": raw["max_heart_rate"]})
print(act["sport"].value_counts().to_string())
span = act["start"].max() - act["start"].min()
print("from", act["start"].min().date(), "to", act["start"].max().date(), f"({span.days / 7:.0f} weeks)")
print("hours from UTC:", raw["utc_offset_h"].value_counts().to_dict())

# %% [markdown]
# Most activities are on a clock six or seven hours behind UTC (summer and winter time); the
# others are travel. Using the offset the watch stored keeps a 6 a.m. run in the right day.
#
# ### Step 2 · Statistics
#
# Profile the activities before summing anything. Look at the shortest ones, the heart rates the
# load depends on, and the day of the week.

# %%
# Step 2 · Profile activities and heart rate
print(act.groupby("sport")[["minutes", "avg_hr"]].median().round(0).to_string())
print("activities without average heart rate:", act["avg_hr"].isna().sum())
print(act.nsmallest(5, "minutes")[["start", "sport", "minutes", "km"]].round(2).to_string(index=False))
runs = act[act["sport"] == "running"]
HRMAX = float(np.percentile(runs["max_hr"].dropna(), 99, method="lower"))
print(f"run max HR: highest {runs['max_hr'].max():.0f}, 99th percentile {HRMAX:.0f} bpm")
print("runs by weekday:", runs["start"].dt.day_name().str[:3].value_counts().to_dict())

# %% [markdown]
# Four activities last under a minute: aborted starts, one of them a 0.2-minute run with no
# distance. Six have no average heart rate, so their load cannot be computed as recorded. The
# highest wrist reading on a run, 209 bpm, is probably the sensor locking onto cadence; the case
# file uses the 99th percentile, 202 bpm, as a stand-in for HRmax (not a tested maximum). The
# athlete ran on a Sunday once in two and a half years, so a Monday-to-Sunday week is a natural
# unit, and the last week of the export, which ends on a Saturday, is complete.
#
# ### Step 3 · Visualize
#
# Compute each activity's load, sum it by week starting on Monday, and keep every week between
# the first and the last, including weeks with nothing recorded.

# %%
# Step 3 · Weekly training load, raw
import matplotlib.dates
import matplotlib.pyplot as plt

act["load"] = act["minutes"] * (act["avg_hr"] / HRMAX) ** 2
monday = act["start"].dt.normalize() - pd.to_timedelta(act["start"].dt.day_of_week, unit="D")
raw_week = act.groupby(monday)["load"].sum()                      # missing HR counts as 0 here
weeks = pd.date_range(raw_week.index.min(), raw_week.index.max(), freq="7D")
raw_week = raw_week.reindex(weeks, fill_value=0)                  # empty weeks stay in, as 0
fig, ax = plt.subplots(figsize=(6.6, 3.0))
ax.plot(raw_week.index, raw_week, "o-", ms=2.5, color="black", lw=0.8)
ax.set(xlabel="week (starting Monday)", ylabel="training load per week (AU)",
       title="Raw weekly load: breaks each December and a few big weeks")
ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))
plt.tight_layout()
print(f"{len(raw_week)} weeks, {(raw_week == 0).sum()} with nothing recorded; "
      f"median {raw_week.median():.0f} AU, largest {raw_week.max():.0f} AU")

# %% [markdown]
# All five empty weeks fall over the December holidays; shorter dips come at other times. The
# watch recorded everything the athlete did, swims and hikes included, for two and a half years,
# so a week with nothing on it is most likely a week without training, and it stays in the series
# as **zero**. That is an assumption, and you should name it: if the watch had been left at home,
# those zeros would teach the model a rest that never happened. The largest week, in July 2024,
# holds an eight-hour hike. It is real load and stays.
#
# ### Step 4 · Cleanse
#
# Rules, written before the forecast is fitted, with a change log:
#
# 1. Drop activities shorter than one minute (aborted starts).
# 2. Fill a missing average heart rate with the median of the same sport, so a 37-minute run
#    does not count as zero load.
# 3. Drop the first week: the export starts on a Friday, so that week is partial.

# %%
# Step 4 · Rules, a change log and the clean weekly series
import os

log = []
short = act["minutes"] < 1
log.append({"rule": "shorter than 1 min", "changed": int(short.sum()), "left": int((~short).sum())})
keep = act[~short].copy()
gap = keep["avg_hr"].isna()
keep["avg_hr"] = keep["avg_hr"].fillna(keep.groupby("sport")["avg_hr"].transform("median"))
log.append({"rule": "average HR filled by sport", "changed": int(gap.sum()), "left": len(keep)})
keep["load"] = keep["minutes"] * (keep["avg_hr"] / HRMAX) ** 2
week = keep.groupby(monday[keep.index])["load"].sum().reindex(weeks, fill_value=0)
week = week.iloc[1:]                                              # first week is partial
log.append({"rule": "partial first week dropped", "changed": 1, "left": len(week)})
os.makedirs("clean", exist_ok=True)
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
week.round(1).rename("load_au").to_csv("clean/weekly_load.csv", index_label="week_start")
print(pd.DataFrame(log).to_string(index=False))
print(f"{len(week)} weeks, {(week == 0).sum()} at zero; median {week.median():.0f} AU, largest {week.max():.0f} AU")

# %% [markdown]
# ### Step 5 · Features from the past only
#
# Three features, each built only from weeks before the one being forecast:
#
# * `lag1`, last week's load, and `lag2`, the week before;
# * `mean4`, the mean of the four weeks before, **shifted by one week before averaging**, so the
#   week being forecast is never inside its own feature.
#
# The first four weeks lack a full history and cannot be used.

# %%
# Step 5 · Lag features and a trailing mean
f = pd.DataFrame({"y": week, "lag1": week.shift(1), "lag2": week.shift(2),
                  "mean4": week.shift(1).rolling(4).mean()})
usable = f.dropna()
print(f"{len(week)} weeks; {len(usable)} have all three features")
print(usable.head(3).round(0).to_string())
print("correlation of each feature with the week's load:",
      usable.corr()["y"].drop("y").round(2).to_dict())

# %% [markdown]
# Last week goes with this week (correlation 0.64): this athlete's training comes in blocks, so a
# big week tends to follow a big week. That is exactly the pattern persistence uses, which makes
# it a hard baseline to beat.
#
# ### Step 8 · Split by time and compare with persistence
#
# The test set is the last 52 usable weeks, one full year from December 2025; the model learns
# only from the 70 weeks before them. A random split would let it learn from weeks after the one
# it predicts. Every method is scored by its mean absolute error (MAE) on the same test weeks.
#
# A small gain in MAE can be luck. To check, take the gain week by week (persistence's miss minus
# the model's), then **bootstrap** it: draw 52 test weeks at random with replacement, average,
# and repeat 2000 times. If the middle 90% of those averages includes zero, the test year cannot
# tell the two methods apart.

# %%
# Step 8 · Five forecasts on the same 52 test weeks
from sklearn.linear_model import LinearRegression

X = ["lag1", "lag2", "mean4"]
train, test = usable.iloc[:-52], usable.iloc[-52:]          # chronological split
lin = LinearRegression().fit(train[X], train["y"])
pred = {"persistence (last week)": test["lag1"], "mean of last 4 weeks": test["mean4"],
        "training-weeks mean": pd.Series(train["y"].mean(), index=test.index),
        "linear on lags": pd.Series(lin.predict(test[X]), index=test.index)}
centered = week.rolling(5, center=True, min_periods=3).mean()           # uses the future!
pred["centered 5-week mean (leaks)"] = centered.loc[test.index]
print(f"train {len(train)} weeks ({train.index[0].date()} to {train.index[-1].date()}), test {len(test)}")
for name, p in pred.items():
    print(f"{name:30s} MAE {(test['y'] - p).abs().mean():5.1f} AU")
gain = (test["y"] - test["lag1"]).abs() - (test["y"] - pred["linear on lags"]).abs()
rng = np.random.default_rng(0)                              # resample test weeks: is the gain real?
boot = [rng.choice(gain, len(gain)).mean() for _ in range(2000)]
print(f"linear closer than persistence in {(gain > 0).sum()} of {len(test)} test weeks; mean gain "
      f"{gain.mean():.1f} AU, 90% bootstrap interval {np.percentile(boot, 5):.1f} to {np.percentile(boot, 95):.1f}")
print("coefficients:", {k: round(float(v), 2) for k, v in zip(X, lin.coef_)}, "intercept", round(float(lin.intercept_), 1))

# %% [markdown]
# The regression beats persistence by 2.0 AU a week (36.4 against 38.4), and it was closer in 28
# of the 52 weeks. That is not much. The bootstrap interval for the gain runs from -2.3 to +6.0 AU
# and includes zero, so the test year cannot tell the regression from "same as last week". Look
# at what it learned: most of its weight is on last week (0.62) plus a constant, so it is
# persistence pulled part of the way toward the usual week. The training mean and the 4-week
# mean, which ignore last week or dilute it, do clearly worse. The centered mean scores best of
# all and is useless: it uses the two weeks *after* the week it "predicts".
#
# ### Step 3 again · The forecast against the weeks it predicted

# %%
# Step 3 again · Test weeks, persistence and the regression
fig, ax = plt.subplots(figsize=(6.6, 3.2))
ax.plot(test.index, test["y"], "o", color="black", ms=4, label="recorded")
ax.plot(test.index, pred["persistence (last week)"], "--", color="0.35", drawstyle="steps-mid", label="same as last week")
ax.plot(test.index, pred["linear on lags"], "-", color="0.55", lw=2, label="linear on lags")
ax.set(xlabel="week (starting Monday)", ylabel="training load per week (AU)",
       title="The regression is persistence, pulled toward the middle", ylim=(0, 300))
ax.legend(fontsize=8, loc="upper center", ncol=3)
fig.autofmt_xdate()
plt.tight_layout()

# %% [markdown]
# Both forecasts are one week late at every turn: neither sees the December break or the dips in
# May and September coming, and both forecast a low week right after each one ends. In between,
# the regression follows persistence but sags below it in the big weeks of late 2026, because it
# pulls toward the usual week of the training period, which was lighter. A model that only knows
# past totals cannot know about a holiday or a planned taper; the coach can, and should overrule
# the number in those weeks.
#
# ### Step 8 again · Next week, with a range
#
# Persistence was not clearly beaten, so use it, and say so: it is simpler, and anyone can check
# it. The range comes from persistence's own test-week errors: the middle 80% of them, added to
# the forecast.

# %%
# Step 8 again · Next week's load and an 80% range
err = test["y"] - test["lag1"]
lo, hi = np.percentile(err, [10, 90])
fc = week.iloc[-1]                                          # persistence: same as last week
final = LinearRegression().fit(usable[X], usable["y"])
nxt = pd.DataFrame({"lag1": [week.iloc[-1]], "lag2": [week.iloc[-2]], "mean4": [week.iloc[-4:].mean()]})
print(f"last four weeks: {week.iloc[-4:].round(0).tolist()} AU")
print(f"week starting {(week.index[-1] + pd.Timedelta(days=7)).date()}: forecast {fc:.0f} AU, "
      f"80% range {fc + lo:.0f} to {fc + hi:.0f} AU")
print(f"the regression would say {final.predict(nxt)[0]:.0f} AU")

# %% [markdown]
# The range is wide, about 60 AU on each side, because one athlete's weeks are variable and 52
# test weeks are a short history of errors. The regression gives a lower number, 191 AU, because
# it pulls a big week back toward the usual week; on the test year that habit was worth too
# little to trust. The number is a planning guide for the coach, not a target: it says what this
# athlete is likely to do next, not what he should do.
