"""CS-2: A step test and a first straight line -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/cs02-step-test-line/
Data:     https://apopt.com/data/tutorials/cs02-step-test-line/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### Step 1 · Gather: the partner's sheet
#
# Sam (a made-up student; every number here is **synthetic**, made by `prepare.py` from the same
# model as the book's step test in Section 2.11) stepped on a 0.30 m bench for five 3-minute
# stages, each faster than the last. Sam weighs 70 kg. After each stage a partner counted beats for
# 15 seconds, starting two seconds after Sam stopped, and asked Sam to read a short paragraph aloud:
# could Sam speak comfortably? (the talk test, Section 7.4.4). Before the test the partner also
# counted 30 seconds at rest. The file is the sheet as the partner wrote it.

# %%
# Step 1 · Open the sheet
import pandas as pd

sheet = pd.read_csv("raw/steptest_five_stages_synthetic.csv")
print(sheet.to_string(index=False))

# %% [markdown]
# Two things on the sheet are not yet the numbers you need. The metronome is set in **beats** a
# minute, four beats per step cycle (up, up, down, down), so 60 on the metronome is 15 cycles a
# minute. And the counts are not all the same length: 30 seconds at rest, 15 after each stage.
# Turn each into the quantity it stands for, with the unit in the column name, and keep the sheet
# untouched.

# %%
# Step 1 · Units first: cycles, watts, beats a minute
import os

MASS, G, BENCH = 70, 9.81, 0.30                        # kg, m/s², m
df = sheet.copy()
df["rate_cpm"] = df["metronome_bpm"] / 4               # step cycles a minute
df["power_W"] = (MASS * G * BENCH * df["rate_cpm"] / 60).round(1)   # lifting power
df["hr_bpm"] = df["beats"] * 60 / df["count_s"]        # beats in the count, per minute
os.makedirs("clean", exist_ok=True)
df.to_csv("clean/steptest_clean.csv", index=False)
print(df[["stage", "rate_cpm", "power_W", "hr_bpm", "talk"]].to_string(index=False))

# %% [markdown]
# ### Step 2 · Statistics: what can these counts resolve?
#
# A profile before any fit. How far does heart rate move across the test, and what is the smallest
# step a count can show?

# %%
# Step 2 · Range and resolution
st = df[df["stage"] != "rest"]
print(f"rest: {df.loc[df['stage'] == 'rest', 'hr_bpm'].iloc[0]:.0f} bpm (30 s count)")
print(f"stages: {st['hr_bpm'].min():.0f} to {st['hr_bpm'].max():.0f} bpm over "
      f"{st['power_W'].min()} to {st['power_W'].max()} W")
print("resolution of a 15 s count: 60/15 =", 60 // 15, "bpm; of the 30 s rest count:", 60 // 30, "bpm")
print("rise per stage (bpm):", st["hr_bpm"].diff().dropna().astype(int).tolist())

# %% [markdown]
# Heart rate rises by 40 beats a minute across the five stages, in steps of 8, 16, 8 and 8. Each
# count can only move in steps of 4, and a partner can miscount by a beat, so a single stage can be
# 4 beats a minute off either way. That is the size of error the fit must be judged against.
#
# ### Step 3 · Visualize

# %%
# Step 3 · Heart rate against lifting power, with the talk test
import matplotlib.pyplot as plt

marks = {"yes": "o", "yes but": "^", "no": "X"}
fig, ax = plt.subplots(figsize=(6.4, 3.8))
for answer, m in marks.items():
    s = st[st["talk"] == answer]
    ax.plot(s["power_W"], s["hr_bpm"], m, ms=10, color="k", mfc="white" if answer != "no" else "k",
            label=f"talk test: {answer}")
rest = df[df["stage"] == "rest"]
ax.plot(rest["power_W"], rest["hr_bpm"], "s", ms=9, color="0.5", label="rest (30 s count)")
ax.set(xlabel="lifting power (W)", ylabel="heart rate (beats/min)", xlim=(-5, 130))
ax.legend(loc="upper left")
plt.tight_layout()

# %% [markdown]
# The five stages lie close to a straight line. Rest, at 66, happens to sit near where that line
# would meet zero watts, but nothing guarantees it: in Q-5's three-stage test the line met zero
# watts 11 beats a minute below rest. A line is only tested over the range of its data. Sam
# could talk comfortably through the first three stages, only just at the fourth, not at the fifth.
#
# ### Step 8 · Split: fit the line, then test it on a stage it has not seen
#
# A line through five points always looks good on the points it was fitted to. The honest test is
# a point it has **not** seen. Hold out one stage, fit the line to the other four, predict the
# held-out stage, and repeat for each stage in turn. Compare with the **mean baseline**: ignore
# power and always guess the average heart rate of the four training stages. A line that cannot
# beat that has learned nothing (Section 2.11, the engineer's note "Your first straight-line fit").

# %%
# Step 8 · The line on all five stages, then one stage held out at a time
import numpy as np

P, HR = st["power_W"].to_numpy(), st["hr_bpm"].to_numpy()
b, a = np.polyfit(P, HR, 1)
r2 = 1 - ((HR - (a + b * P)) ** 2).sum() / ((HR - HR.mean()) ** 2).sum()
print(f"all five: HR = {a:.1f} bpm + {b:.3f} bpm/W x P   (R² {r2:.3f}); "
      f"{b * MASS * G * BENCH / 60:.2f} bpm per cycle/min")
rows = []
for i in range(len(P)):
    keep = np.arange(len(P)) != i
    bi, ai = np.polyfit(P[keep], HR[keep], 1)
    rows.append({"held out": st["stage"].iloc[i], "measured": HR[i],
                 "line": round(ai + bi * P[i], 1), "line miss": round(HR[i] - (ai + bi * P[i]), 1),
                 "baseline miss": round(HR[i] - HR[keep].mean(), 1)})
held = pd.DataFrame(rows)
print(held.to_string(index=False))
print(f"mean absolute miss: line {held['line miss'].abs().mean():.1f} bpm, "
      f"baseline {held['baseline miss'].abs().mean():.1f} bpm")

# %% [markdown]
# Fitted to all five stages, each watt adds 0.61 beats a minute, or 2.1 per extra step cycle a
# minute. On stages it had not seen, the line misses by 2.5 beats a minute on average, against 16.8
# for the mean baseline: it has learned something real. Its misses are about one count's
# resolution, 4 beats a minute, so the line is about as good as the counts allow, even at the fifth
# stage, where it had to extrapolate beyond the four it was fitted to. The baseline misses the two
# end stages by the most, 26 and 24 beats a minute, because they are farthest from the average.

# %%
# Step 8 · Misses on held-out stages
fig, ax = plt.subplots(figsize=(6.4, 3.4))
x = np.arange(len(held))
ax.axhspan(-4, 4, color="0.9", label="one count step (±4 bpm)")
ax.plot(x, held["line miss"], "o", ms=9, color="k", label="straight line")
ax.plot(x, held["baseline miss"], "s", ms=8, mfc="none", color="k", label="mean baseline")
ax.axhline(0, color="k", lw=0.8)
ax.set(xticks=x, xticklabels=held["held out"], ylabel="measured − predicted (bpm)")
ax.legend(loc="upper left")
plt.tight_layout()

# %% [markdown]
# ### A heart rate for an easy session
#
# The talk test gives the decision a boundary. Sam could still talk comfortably at the third stage
# and not quite at the fourth. Section 7.4.4 reports that the last comfortable stage of a talk test
# falls close to the first threshold, the top of the easy range. So read the line at the third
# stage's power, and use the held-out misses as the band.

# %%
# The heart rate at the last comfortable stage
easy = st[st["talk"] == "yes"].iloc[-1]
hr_easy = a + b * easy["power_W"]
band = held["line miss"].abs().max()
print(f"last 'yes' stage: {easy['stage']}, {easy['rate_cpm']:.0f} cycles/min, {easy['power_W']} W")
print(f"line: {hr_easy:.0f} bpm, held-out band ±{band:.0f} bpm -> easy up to about {hr_easy:.0f} bpm")
print(f"counts start 2 s after stopping, so a strap read while moving shows more (Section 2.12)")

# %% [markdown]
# The line puts the top of Sam's easy range at about 121 beats a minute, give or take 4. That
# number comes from counts taken after Sam stopped, and heart rate starts falling the moment work
# stops; Section 2.12 measured that effect at about 9 beats a minute for the book's version of this
# test. A strap read while moving will therefore show somewhat more at the same effort. Say so on
# the action card, and retest with the same bench, the same metronome and the same partner.
