"""Q-4: Type a small table and plot it -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q04-small-table/
Data:     https://apopt.com/data/tutorials/q04-small-table/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### A paper sheet becomes a table
#
# In the step test of Section 2.11, a partner writes on paper: the stage, the metronome's step
# rate, and the number of beats counted in 15 seconds after each stage and at each minute of
# recovery. Here is Sam's sheet. Sam is a made-up student; the numbers are the book's
# **synthetic** step test, made by a script so that the true answers are known.
#
# Type the sheet into Python as a **table** (a pandas DataFrame): one row per count, one column
# per thing written down. Typing it is the raw record; nothing is computed yet.

# %%
# Type the sheet
import pandas as pd

sheet = pd.DataFrame({
    "label":    ["stage 1", "stage 2", "stage 3", "recovery 1 min", "recovery 2 min",
                 "recovery 3 min", "recovery 4 min", "recovery 5 min"],
    "rate_cpm": [15, 20, 25, 0, 0, 0, 0, 0],          # step cycles a minute
    "count15":  [24, 27, 31, 22, 21, 19, 19, 20],     # beats counted in 15 s
    "t_mid_s":  [309.5, 509.5, 709.5, 767.5, 827.5, 887.5, 947.5, 1007.5],  # middle of the count
})
print(sheet.shape)
print(sheet.to_string(index=False))

# %% [markdown]
# ### Add the columns you compute, and check what you typed
#
# Two columns come from arithmetic. A 15-second count times four is beats a minute. The power
# spent lifting the body is m g h times cycles a second: Sam weighs 70 kg and the bench is
# 0.30 m. Then compare your table with the book's file of the same sheet. A typing error shows up
# here, not three weeks later in a chart.

# %%
# Compute two columns and check against the file
sheet["hr_bpm"] = sheet["count15"] * 4
sheet["power_W"] = (70 * 9.81 * 0.30 * sheet["rate_cpm"] / 60).round(1)
book = pd.read_csv("raw/steptest_counts.csv")
for col in ["count15", "hr_bpm", "power_W", "t_mid_s"]:
    assert (sheet[col].values == book[col].values).all(), f"{col} differs from the file"
print("typed table matches the file in every checked column")
import os
os.makedirs("clean", exist_ok=True)
sheet.to_csv("clean/step_test_sheet.csv", index=False)
print(sheet[["label", "power_W", "hr_bpm"]].to_string(index=False))

# %% [markdown]
# Every value matches. Change one count above (type 32 for stage 3, say) and run both cells
# again: the `assert` stops with the name of the column that differs.
#
# ### One chart

# %%
# Heart rate through the test
import matplotlib.pyplot as plt

work = sheet["rate_cpm"] > 0
fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.plot(sheet.loc[work, "t_mid_s"] / 60, sheet.loc[work, "hr_bpm"], "o-", ms=8, label="after each stage")
ax.plot(sheet.loc[~work, "t_mid_s"] / 60, sheet.loc[~work, "hr_bpm"], "s--", mfc="none", ms=8, label="recovery")
ax.set(xlabel="time from the start (min)", ylabel="heart rate (beats/min)")
ax.legend()
plt.tight_layout()
print(f"highest {sheet['hr_bpm'].max()} bpm; first recovery count {sheet.loc[~work, 'hr_bpm'].iloc[0]} bpm")

# %% [markdown]
# Heart rate climbs with each stage and falls quickly once Sam stops: 124 after stage 3, 88 one
# minute later. Every value is a multiple of four, because a 15-second count can only move in
# steps of four beats a minute (Section 2.12).
#
# **For the athlete:** "Your heart rate rose evenly with each step rate and was back under 90
# within a minute of stopping; we'll repeat the same sheet in six weeks and compare."
