"""CS-15: Is the change real? One test, twelve weeks -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/cs15-is-change-real/
Data:     https://apopt.com/data/tutorials/cs15-is-change-real/ (keep raw/ next to this file)
"""

# %% [markdown]
# ## Part 1: a simulated twelve-week record
#
# The athlete record (Appendix J) holds one number per row: every jump, every resting pulse,
# with the device, the protocol and the conditions beside it. This record is **simulated**. No
# student has a full term of weekly tests yet, so the course made one with a program, and
# planted in it the things that happen to real records: a learning effect in the first weeks,
# a bad Monday, a real training gain, and a new phone. Because the truth is known, you can check
# at the end how close each method came. Part 2 repeats the method on a real record: an
# athlete's runs from 2024 to 2026.
#
# ### Step 1 · Gather
#
# Open the record and list what changed from week to week before looking at any jump height.

# %%
# Step 1 · Open the record and list the changes
import numpy as np
import pandas as pd

rec = pd.read_csv("raw/athlete-record-simulated.csv")
print(rec.shape)
print(rec.groupby(["test", "metric"]).size().to_string())
jump = rec[rec["metric"] == "jump_height_cm"].copy()
jump["week"] = pd.factorize(jump["date"])[0] + 1        # Monday sessions in date order
setup = jump.groupby("week").agg(date=("date", "first"), device=("device", lambda s: " + ".join(sorted(set(s)))),
                                 conditions=("conditions", "first"))
print(setup.to_string())
print(jump.loc[jump["note"].notna(), ["week", "device", "trial", "value", "note"]].to_string(index=False))

# %% [markdown]
# Fifty-one rows, not 48: in week 12 the same three jumps were filmed by two phones. The
# record says three things before any number is read. Week 4 followed a short night. From week
# 11 a new phone filmed at 60 frames per second from knee height (`protocol_version` v2), where
# the old one filmed at 120 from waist height. And one jump in week 6 has no height, because
# the app could not find the takeoff.
#
# ### Step 2 · Statistics
#
# Profile each session: how many jumps, their mean and their spread.

# %%
# Step 2 · A profile of every session
sess = (jump.dropna(subset=["value"]).groupby(["week", "device"])["value"]
        .agg(["count", "mean", "std"]))
print(sess.round(2).to_string())
dof = sess["count"] - 1
within = np.sqrt((sess["std"] ** 2 * dof).sum() / dof.sum())   # pooled over sessions
print(f"jump-to-jump SD within a morning: {within:.2f} cm")

# %% [markdown]
# Jumps on one morning agree to about half a centimeter. Keep that number; Step 2 again
# compares it with how much a whole morning moves from week to week.
#
# ### Step 3 · Visualize
#
# Plot every jump, not only the means, and mark the device change before reading a trend.

# %%
# Step 3 · Every jump, by device
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6.6, 3.4))
for dev, mk in [("phone-120fps", "o"), ("phone-60fps", "^")]:
    d = jump[jump["device"] == dev]
    ax.plot(d["week"], d["value"], mk, color="0.55", mfc="white", ms=5, label=f"each jump, {dev}")
    m = d.groupby("week")["value"].mean()
    ax.plot(m.index, m.values, "-" if dev == "phone-120fps" else ":", marker=mk, color="black", ms=4)
ax.axvline(10.5, color="0.4", ls="--", lw=1)
ax.text(10.6, ax.get_ylim()[0] + 0.3, "new phone", fontsize=8)
ax.set(xlabel="week", ylabel="jump height (cm)", xticks=range(1, 13),
       title="Raw record: the last two weeks jump up with the new phone")
ax.legend(fontsize=8, loc="upper left")
plt.tight_layout()

# %% [markdown]
# Three things to notice. Week 1 is low. Week 4 dips and week 5 comes straight back. And the
# new phone reads more than a centimeter above the old one on the very same jumps of week 12.
#
# ### Step 4 · Cleanse
#
# The rules are written before the analysis, and none of them changes a number in the record:
#
# 1. A row with no value is dropped from the analysis and logged.
# 2. Weeks 1 and 2 are practice. They stay in the record but not in the baseline.
# 3. The **baseline** is weeks 3 to 6, the four Mondays before the jump-training block began in week 7.
# 4. A session's value is the mean of its jumps. A different device or protocol starts a new
#    segment, which is compared with the old one only through a **bridge**: the same jumps
#    filmed by both.

# %%
# Step 4 · Rules, a change log and a clean record
import os

log = [{"rule": "no value", "rows_removed": int(rec["value"].isna().sum())}]
clean = rec.dropna(subset=["value"])
os.makedirs("clean", exist_ok=True)
clean.to_csv("clean/athlete-record.csv", index=False)       # same columns as the record
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
ok = jump.dropna(subset=["value"])
old = ok[ok["device"] == "phone-120fps"].groupby("week")["value"].mean()
new = ok[ok["device"] == "phone-60fps"].groupby("week")["value"].mean()
base = old.loc[3:6]
print(pd.DataFrame(log).to_string(index=False))
print("old phone, weekly means:", old.round(2).to_dict())
print("new phone, weekly means:", new.round(2).to_dict())

# %% [markdown]
# The clean record keeps the record's columns, so any tool that reads the record format can
# read it. The chart below draws it.

# %% [markdown]
# ### Step 2 again · Typical error and the smallest worthwhile change
#
# Chapter 11 measures the wobble of a test with a **test–retest** study. With one athlete, the
# baseline Mondays are the retests: nothing was meant to change across weeks 3 to 6, so the
# standard deviation of their four means is the **typical error of one session** (the rule of
# build step B-11). The **smallest worthwhile change** (SWC) comes from the sport, not the
# measurement; this athlete and coach agreed before the term to use the book's 0.65 cm
# (Section 11.1.2: a fifth of the spread between teammates).

# %%
# Step 2 again · Two kinds of wobble
te_session = base.std()                  # SD of four baseline Monday means
swc = 0.65                               # agreed before the term, cm
print(f"baseline (weeks 3-6): mean {base.mean():.2f} cm, typical error of a session {te_session:.2f} cm")
print(f"expected from jump-to-jump scatter alone: {within / np.sqrt(3):.2f} cm")
print(f"SWC {swc} cm; noise of one session against the 4-week mean: {te_session * np.sqrt(1 + 1/4):.2f} cm")
from scipy.stats import chi2
nu = len(base) - 1                       # four weeks give three degrees of freedom
print(f"90% interval for the typical error: {te_session * np.sqrt(nu / chi2.ppf(0.95, nu)):.2f} "
      f"to {te_session * np.sqrt(nu / chi2.ppf(0.05, nu)):.2f} cm")

# %% [markdown]
# A whole morning moves more than three times as much as three jumps averaged together would
# suggest. The jumps of one morning share that morning: its sleep, its warm-up, its mood. So
# filming more jumps on one day does not remove the day-to-day wobble; only more days do. And
# the noise of one session is larger than the SWC, so a single Monday can never settle the
# question.
#
# ### Step 3 again · A trend, a band and a run rule
#
# Draw the weekly means against the baseline band (mean ± one typical error) and the SWC, with
# a three-week rolling mean. Then apply a **run rule**, written before looking: a change is
# flagged when three Mondays in a row sit above the top of the band. One high Monday is not
# enough. Weeks 11 and 12 are left out until Step 4 again deals with the new phone.

# %%
# Step 3 again · Band, SWC, rolling mean and run rule
weeks = old.loc[:10]
roll = weeks.rolling(3).mean()
top = base.mean() + te_session
above = weeks > top
run = above & above.shift(1, fill_value=False) & above.shift(2, fill_value=False)
print("above the band:", list(weeks.index[above]))
print("run rule fires in week:", list(weeks.index[run]) or "none yet")

fig, ax = plt.subplots(figsize=(6.6, 3.4))
ax.axhspan(base.mean() - te_session, top, color="0.88", lw=0, label="baseline ± typical error")
for s, lab in ((-swc, None), (swc, "baseline ± SWC")):
    ax.axhline(base.mean() + s, color="0.3", ls="--", lw=0.8, label=lab)
ax.plot(weeks.index, weeks, "o-", color="black", label="weekly mean (old phone)")
ax.plot(roll.index, roll, "-", color="0.5", lw=2.5, alpha=0.7, label="3-week rolling mean")
ax.axvspan(0.5, 2.5, color="0.95", lw=0)
ax.text(1.5, 0.95, "practice", fontsize=8, ha="center", transform=ax.get_xaxis_transform())
ax.set(xlabel="week", ylabel="jump height (cm)", xticks=range(1, 11),
       title="The block lifts the jump, slowly; one Monday never decides")
ax.legend(fontsize=8, loc="lower right")
plt.tight_layout()

# %% [markdown]
# The rolling mean climbs through the block, but only week 10 clears the top of the band, so by
# week 10 the run rule has not fired. The dashed lines show why one Monday
# never settles it: the band is wider than the SWC.
#
# ### Step 2 again · The decision rule of Section 11.1.3
#
# For a change Δ with noise σ, the chances that the true change is a worthwhile gain, trivial
# or a loss follow from the normal curve, and each chance gets a word (Table 11.2). The chances
# then give one of three statuses: **improved** when a worthwhile gain is at least likely (75% or
# more), **no clear change** when both a gain and a loss are unlikely (under 25%), and
# **retest** when the answer is "possibly". (A likely loss would read **declined**.)

# %%
# Step 2 again · Chances, a word and a status
from scipy.stats import norm

WORDS = [(0.005, "most unlikely"), (0.05, "very unlikely"), (0.25, "unlikely"), (0.75, "possibly"),
         (0.95, "likely"), (0.995, "very likely"), (1.01, "most likely")]

def verdict(delta, noise, swc=swc, unit="cm"):
    gain = 1 - norm.cdf((swc - delta) / noise)
    loss = norm.cdf((-swc - delta) / noise)
    word = next(w for cut, w in WORDS if gain < cut)
    status = ("improved" if gain >= 0.75 else "declined" if loss >= 0.75
              else "no clear change" if max(gain, loss) < 0.25 else "retest")
    return (f"change {delta:+.2f} {unit}, noise {noise:.2f}: gain {gain:.0%} ({word}), "
            f"trivial {1 - gain - loss:.0%}, loss {loss:.0%} -> {status}")

print("week 5 vs week 4:       ", verdict(old[5] - old[4], te_session * np.sqrt(2)))
print("week 5 vs baseline:     ", verdict(old[5] - base.mean(), te_session * np.sqrt(1 + 1/4)))
print("weeks 9-10 vs baseline: ", verdict(old.loc[9:10].mean() - base.mean(), te_session * np.sqrt(1/2 + 1/4)))
print("weeks 9-10 vs weeks 1-4:", verdict(old.loc[9:10].mean() - old.loc[1:4].mean(), te_session * np.sqrt(1/2 + 1/4)))

# %% [markdown]
# Read the four lines in order.
#
# * **Week 5 against week 4** says "improved". That is **regression to the mean**: week 4 was a
#   bad morning, and the next measurement after an unusually low one is usually closer to the
#   athlete's normal, with or without training. Against the whole baseline, week 5 is ordinary.
# * **Weeks 9–10 against the baseline**, the honest comparison at the end of the block, says
#   "possibly": retest.
# * **Against weeks 1–4** the same weeks look like a clearer gain. Weeks 1 and 2 were low
#   because the athlete was still learning the test, a **learning effect**, not lost fitness.
#   A baseline that includes them flatters any later change.
#
# ### Step 4 again · A step that is not training
#
# Week 11 is the first Monday with the new phone. Its mean is far above everything before it.
# Is that the block finally showing? The bridge in week 12 answers it: the same three jumps,
# filmed by both phones.

# %%
# Step 4 again · The new phone, measured with a bridge
w11 = new[11]
print("week 11 (new phone) vs baseline:", verdict(w11 - base.mean(), te_session * np.sqrt(1 + 1/4)))
pair = ok[ok["week"] == 12].pivot(index="trial", columns="device", values="value")
diff = pair["phone-60fps"] - pair["phone-120fps"]
print(pair.assign(difference=diff).to_string())
offset = diff.mean()
print(f"bridge: the new phone reads {offset:+.2f} cm (SD of the three differences {diff.std():.2f})")
series = old.loc[:10].copy()
series[11] = w11 - offset                       # week 11 on the old phone's scale
series[12] = old[12]                            # week 12 from the old phone itself
late = series.loc[9:12]
print("corrected weekly means, weeks 9-12:", late.round(2).to_dict())
print("weeks 9-12 vs baseline:", verdict(late.mean() - base.mean(), te_session * np.sqrt(1/4 + 1/4)))
hi3 = series > base.mean() + te_session
print("run rule on the corrected series fires in week:",
      list(series.index[hi3 & hi3.shift(1, fill_value=False) & hi3.shift(2, fill_value=False)]))

# %% [markdown]
# Uncorrected, week 11 would have been reported as a very likely gain of more than three
# centimeters. About a centimeter of that is the phone. On the old phone's scale the last four
# weeks give a likely worthwhile gain, and in week 12 the run rule fires as well: three Mondays
# in a row above the band. "Improved" is the status to report. Without the bridge the
# step could not have been measured at all; a device change in a record needs one, or a fresh
# baseline.
#
# ### Check against the truth
#
# The simulation's planted values are in `raw/simulation-truth.csv`. Compare each with what the
# record let you estimate.

# %%
# What was planted, and what was found
truth = pd.read_csv("raw/simulation-truth.csv").set_index("week")
true_gain = (truth["true_ability_cm"] - 33.0).loc[9:12].mean()
print(f"training gain, weeks 9-12: planted {true_gain:.2f} cm, estimated {late.mean() - base.mean():.2f}")
print(f"learning effect, week 1: planted {truth.loc[1, 'learning_cm']:.1f} cm, "
      f"seen {old[1] - base.mean():+.2f} (includes that morning's day effect)")
print(f"new phone: planted {truth.loc[12, 'device_bias_cm']:.1f} cm, bridge {offset:.2f}")
print("day effects in the baseline weeks:", truth.loc[3:6, "day_effect_cm"].tolist())

# %% [markdown]
# Every estimate landed within half a centimeter of the truth, and each miss has a cause you
# can name. The baseline weeks happened to include the bad Monday of week 4, which pulls the
# baseline mean down and the estimated gain up. Three jumps make a short bridge.
#
# ### How good is the run rule? Autocorrelation
#
# Mondays are not independent: a good week tends to follow a good week, because sleep, a cold
# or a heavy training week last longer than a day. In the simulation each week's day effect
# keeps half of the last one (a lag-1 autocorrelation of 0.5). That makes runs above the band
# more common by chance. Simulate many unchanged athletes and count false alarms.

# %%
# False alarms of the run rule, with and without memory
rng = np.random.default_rng(0)

def false_alarms(phi, n=20000, weeks=10):
    e = np.zeros((n, weeks))
    for t in range(1, weeks):
        e[:, t] = phi * e[:, t - 1] + rng.normal(0, np.sqrt(1 - phi**2), n)
    b = e[:, :4]                                      # four baseline weeks, unit noise
    hi = (e[:, 4:] > (b.mean(1) + b.std(1, ddof=1))[:, None])
    three = hi[:, 2:] & hi[:, 1:-1] & hi[:, :-2]
    return three.any(axis=1).mean()

for phi in (0.0, 0.5):
    print(f"lag-1 autocorrelation {phi}: run rule fires by chance in {false_alarms(phi):.0%} of unchanged records")

# %% [markdown]
# Even with no memory the rule fires by chance in about one unchanged record in eleven,
# because four baseline weeks give a rough mean and a rough band. With the planted memory it
# fires in one in five. Read a run of
# three as "look harder", and confirm it with the decision rule and a retest.
#
# ## Part 2: a real record, 2024 to 2026
#
# There is no real weekly jump record yet. There is a real long record: the activity history of
# an adult male athlete in his mid-40s, 693 activities from one watch, of which 475 are outdoor
# runs. Which number in it can be tracked like a test?
#
# * Pace is there for every run, but a 3 km jog and a 15 km long run are different tests. So
#   keep runs of **6 to 12 km**, the athlete's usual steady run, and take the **median pace of
#   each month**, which a single race or a walk-jog cannot move much. Months with fewer than
#   five such runs are left out. Treadmill runs and the one track session are left out too: a
#   treadmill sets its own pace, and the watch measures its distance from the wrist.
# * Heart rate is there on almost every run, from the watch's optical sensor. So you can also
#   track **meters per heartbeat**: distance divided by the number of beats it took. A fitter
#   heart moves you further on each beat.
#
# The file stores time in seconds and distance in meters. Its clock is UTC, with the local offset
# in its own column, so the local month comes from `start_time` plus `utc_offset_h`. It is still
# not a controlled test: route, weather, hills and intent change from run to run. That is the
# lesson of Part 2.

# %%
# Step 1 and Step 4 · Monthly median pace of 6-12 km runs
raw = pd.read_csv("raw/sessions_fit.csv")
runs = raw[(raw["sport"] == "running") & ~raw["sub_sport"].isin(["indoor_running", "track"])].copy()
runs["start"] = (pd.to_datetime(raw["start_time"].str.rstrip("Z"))
                 + pd.to_timedelta(raw["utc_offset_h"], unit="h"))       # UTC + offset = local
runs["km"] = runs["total_distance"] / 1000
runs["pace_s_km"] = runs["total_timer_time"] / runs["km"]               # pauses excluded
runs["climb_m_km"] = runs["total_ascent"] / runs["km"]
runs["spm"] = 2 * runs["avg_running_cadence"]                           # the file counts one foot
runs["m_per_beat"] = runs["total_distance"] / (runs["total_timer_time"] / 60 * runs["avg_heart_rate"])
steady = runs[runs["km"].between(6, 12)]
month = steady.groupby(steady["start"].dt.to_period("M")).agg(
    runs=("pace_s_km", "size"), pace=("pace_s_km", "median"), climb=("climb_m_km", "median"),
    hr=("avg_heart_rate", "median"), spm=("spm", "median"), m_per_beat=("m_per_beat", "median"))
month = month[month["runs"] >= 5]
month = month.reindex(pd.period_range(month.index.min(), month.index.max(), freq="M"))  # gaps stay missing
month.round(3).to_csv("clean/monthly_pace.csv")
print(f"{len(runs)} outdoor runs, {len(steady)} of 6-12 km; {month['pace'].notna().sum()} months with "
      f"5 or more, {month['pace'].isna().sum()} months missing")
print(month.drop(columns="m_per_beat").dropna().round(1).to_string())

# %% [markdown]
# Read the table before any statistics. The first three months, July to September 2024, are
# about a minute per kilometer slower than everything after, with a lower step rate and a
# lower heart rate. Walk breaks show up as a lower step rate. The file cannot say why; it can
# say these runs were not the same test. Like the practice weeks of Part 1, they stay in the
# record but not in the baseline. Two months (December 2024 and September 2026) had fewer than
# five steady runs. They are missing, not slow and not zero, and they stay missing. The slowest
# later months, June 2025 and August and October 2026, also have the lowest heart rates (150 to
# 151 bpm): easier runs, which is intent, not lost fitness. And the climb per kilometer falls
# by half over the two years: the routes changed too.

# %%
# Step 2 and Step 3 · Band, autocorrelation and the decision rule, on real data
first6 = month["pace"].dropna().iloc[:6]                   # naive: the first six months
base_p = month.loc["2024-10":, "pace"].dropna().iloc[:6]   # after the start-up: Oct 2024 - Apr 2025
last = month["pace"].dropna().iloc[-5:]                    # Jun - Nov 2026
te_p, swc_p = base_p.std(), 0.01 * base_p.mean()           # SWC: 1% of pace, agreed in advance
r1 = month.loc["2024-10":, "pace"].autocorr(1)
n_eff = len(last) * (1 - r1) / (1 + r1)
print(f"baseline {base_p.mean():.1f} s/km, typical error of a month {te_p:.1f}, SWC {swc_p:.1f}")
print(f"lag-1 autocorrelation from Oct 2024 {r1:.2f}; 5 months carry about {n_eff:.1f} months' information")
print("last 5 vs first 6 months:", verdict(first6.mean() - last.mean(),      # faster = positive
      first6.std() * np.sqrt(1 / 5 + 1 / 6), 0.01 * first6.mean(), "s/km"))
print("last 5 months vs baseline:", verdict(base_p.mean() - last.mean(),
      te_p * np.sqrt(1 / len(last) + 1 / len(base_p)), swc_p, "s/km"))
import matplotlib.dates
fig, ax = plt.subplots(figsize=(6.6, 3.2))
ax.axhspan(base_p.mean() - te_p, base_p.mean() + te_p, color="0.88", lw=0, label="baseline ± typical error")
ax.plot(month.index.to_timestamp(), month["pace"], "o-", color="black", mfc="white", ms=4, label="monthly median")
ax.plot(last.index.to_timestamp(), last, "o", color="black", ms=5, label="last five months")
ax.invert_yaxis()                                          # faster is up
ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator(bymonth=[1, 7]))
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%b %Y"))
ax.set(xlabel="month", ylabel="pace (s/km), faster up", title="After the start-up, steady-run pace barely moves")
ax.legend(fontsize=8, loc="lower right")
plt.tight_layout()

# %% [markdown]
# The two baselines give opposite answers. Against the first six months, start-up included, the
# last five months are more than 40 s/km faster: "likely improved". That is the learning effect
# of Part 1 again; a baseline that holds the start-up flatters everything after it. Against the
# honest baseline, the last five months are about 2 s/km (under 1%) *slower*, which is possibly
# a small loss and possibly nothing, so the status is "retest". Once the start-up is left out,
# the months carry little memory from one to the next. With the start-up in, a long climb makes
# neighboring months look alike, and a run rule would fire on the trend.
#
# Pace leaves out how hard the athlete worked. Heart rate puts that back.

# %%
# Step 2 again · Meters per heartbeat
mpb = month["m_per_beat"]
base_e, last_e = mpb.loc[base_p.index], mpb.loc[last.index]   # the same months as for pace
pct = lambda v: 100 * v / base_e.mean()                       # work in % of the baseline
te_e = pct(base_e.std())
r1_e = mpb.loc["2024-10":].autocorr(1)
print(f"baseline {base_e.mean():.3f} m/beat, typical error {te_e:.1f}%; last 5 months {last_e.mean():.3f} m/beat")
print("baseline months:", dict(zip(base_e.index.astype(str), base_e.round(3))))
print(f"lag-1 autocorrelation from Oct 2024 {r1_e:.2f}; 5 months carry about "
      f"{len(last_e) * (1 - r1_e) / (1 + r1_e):.1f} months' information")
print("last 5 months vs baseline:", verdict(pct(last_e.mean()) - 100,          # SWC: 1% again
      te_e * np.sqrt(1 / len(last_e) + 1 / len(base_e)), 1.0, "%"))

# %% [markdown]
# At about the same pace, the heart now beats less often. The last five months cover 3.8% more
# ground per beat than the baseline, a likely worthwhile gain (92%). Read the baseline months
# before you believe it. The rise happened *inside* the baseline, from 1.172 m/beat in October
# 2024 to 1.249 in March 2025, and the last five months average 1.238: the number rose in the
# first winter and has held since. A baseline that is still climbing is not a steady baseline.
# The memory from month to month is also larger here (0.43), so five months carry about two
# months' information. And heat, hills, easy days and a wrist sensor all move heart rate. The
# summer months sit in the last five and not in the baseline, and heat raises heart rate, so
# heat did not make this gain. The honest reading: the steady run got cheaper for the heart
# during the first winter and has stayed cheaper; pace has not changed. To track fitness rather
# than routes, use a fixed test, the same course or a treadmill at a fixed speed with heart rate,
# recorded the same way each time. That is exactly what the weekly record of Part 1 was
# designed to be.
