"""Q-5: Fit a straight line and read the slope's units -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### Heart rate against workload
#
# Over the middle of its range, heart rate rises almost in a straight line with how hard you
# work (Section 2.11). Sam's step test gives three points: the lifting power of each stage, in
# watts, and the heart rate counted after it. Sam is a made-up student and the data are the
# book's **synthetic** step test. Fit the straight line HR = a + b × P by least squares: the
# line that makes the squared vertical misses as small as possible.

# %%
# Fit the line
import numpy as np
import pandas as pd

counts = pd.read_csv("raw/steptest_counts.csv")
st = counts[counts["label"].str.startswith("stage")]
P, HR = st["power_W"].to_numpy(), st["hr_bpm"].to_numpy()
b, a = np.polyfit(P, HR, 1)                  # slope first, then intercept
print(st[["label", "rate_cpm", "power_W", "hr_bpm"]].to_string(index=False))
print(f"HR = {a:.1f} bpm + {b:.3f} bpm/W x P")

# %% [markdown]
# ### Read the slope with its units
#
# The slope is 0.816, and without units it means nothing. Heart rate is in beats a minute and
# power in watts, so the slope is **beats a minute per watt**. The same line can be written per
# step rate: one more step cycle a minute lifts 70 kg up 0.30 m once more a minute, which is
# 3.43 W. The intercept has units too, beats a minute, and it is the line's value at zero watts.

# %%
# The same slope in other units, and a prediction
W_PER_CPM = 70 * 9.81 * 0.30 / 60            # watts added by one more cycle a minute
print(f"one cycle a minute = {W_PER_CPM:.2f} W -> slope {b * W_PER_CPM:.2f} bpm per cycle/min")
print(f"10 W more -> {10 * b:.1f} bpm more")
p22 = 22 * W_PER_CPM
print(f"at 22 cycles/min ({p22:.1f} W) the line predicts {a + b * p22:.0f} bpm")
print(f"intercept {a:.1f} bpm at 0 W; Sam's resting heart rate on the strap before the test: about 64 bpm")

# %% [markdown]
# Each watt adds about 0.8 beats a minute; each extra step cycle a minute adds about 2.8. A
# stage at 22 cycles a minute, between the second and third, should bring Sam to about 115.
# But the intercept, 53 at zero watts, is **below** Sam's resting heart rate of about 64. A
# line fitted between 51 and 86 W says nothing reliable outside that range; heart rate at rest
# is not on it. (The resting value comes from the strap's record of the same test, used in Q-6.)
#
# ### One chart

# %%
# The points, the line, and where the line stops being true
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.plot(P, HR, "o", ms=9, label="15 s counts after each stage")
x_in = np.linspace(P.min(), P.max(), 10)
x_out = np.linspace(0, P.min(), 10)
ax.plot(x_in, a + b * x_in, "k-", label=f"fit: slope {b:.2f} bpm/W")
ax.plot(x_out, a + b * x_out, "k:", label="the line extended, untested")
ax.axhline(64, color="0.5", ls="--", lw=1, label="resting heart rate")
ax.set(xlabel="lifting power (W)", ylabel="heart rate (beats/min)", xlim=(0, 95))
ax.legend(loc="upper left")
plt.tight_layout()
print("residuals (bpm):", (HR - (a + b * P)).round(1))

# %% [markdown]
# The line fits the three stages to within 1.4 beats a minute. That is less than the 4-beat steps
# a 15-second count can resolve, so do not read much into how well three points fit; CS-2 tests a
# line on a stage it has not seen.
#
# **For the athlete:** "In this test each step faster per minute raised your heart rate by about
# 3 beats; that holds between the slowest and fastest stages we tried, not outside them."
