"""Q-33: A rolling mean and a band -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q33-rolling-band/
Data:     https://apopt.com/data/tutorials/q33-rolling-band/ (keep raw/ next to this file)
"""

# %% [markdown]
# One morning's heart rate says little: it moves by a few beats a minute from day to day with
# no change in you. Two tools from Chapter 11 make a daily series readable. A **band** is your
# usual range, the mean plus or minus one standard deviation of a baseline period. A
# **rolling mean** is the mean of the last seven days, recomputed each day; it smooths the
# day-to-day noise and reacts a little late.
#
# The file is the book's **simulated** six weeks of morning heart rate (Section 11.8). In the
# simulation the true level rises by 4 beats a minute after day 35, so you know what the tools
# should find.
#
# ### A baseline band from the first four weeks

# %%
# Open the series and set the band
import pandas as pd

hr = pd.read_csv("raw/morning_hr_simulated.csv", index_col="day")["hr"]
base = hr.loc[1:28]                                   # four weeks before anything changed
lo, hi = base.mean() - base.std(), base.mean() + base.std()
print(f"{len(hr)} mornings; baseline mean {base.mean():.1f} bpm, band {lo:.1f} to {hi:.1f}")
print(f"baseline mornings outside the band: {int(((base < lo) | (base > hi)).sum())} of 28")

# %% [markdown]
# Twelve of 28 ordinary mornings fall outside a band of one standard deviation. For normal
# scatter you expect about a third outside; with day-to-day memory in the series (a high
# morning tends to follow a high morning) runs outside are common. One morning above the band
# is not news.
#
# ### A trailing seven-day mean

# %%
# Rolling mean, looking back only
roll = hr.rolling(7).mean()                           # days d-6 to d: past only
check = pd.read_csv("raw/morning_hr_simulated.csv", index_col="day")["roll7"]
print(f"largest difference from the book's column: {(roll - check).abs().max():.3f} bpm")
print(f"7-day mean on day 35 {roll[35]:.1f}, on day 42 {roll[42]:.1f}")
print(f"mornings above the band in the last week: {int((hr.loc[36:] > hi).sum())} of 7")
print(f"7-day mean above the band from day {int(roll[roll > hi].index.min())}")

# %% [markdown]
# Only three of the seven high mornings clear the band. The rolling mean climbs every day of
# the week, from 49.9 to 53.5, and ends above the band on day 42: the band says "watch", the
# rolling mean says "the week as a whole has moved". Use `rolling(7)` (the last seven days), not `rolling(7, center=True)`: a
# centered window uses days that have not happened yet, which a tracker cannot do and a
# forecast must not do (Section 11.8.1).
#
# ### The chart

# %%
# Each morning, the rolling mean and the band
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6.4, 3.2))
ax.axhspan(lo, hi, color="0.88", lw=0, label="usual range (days 1-28)")
ax.plot(hr.index, hr, "o", mfc="white", mec="0.35", ms=4, label="each morning")
ax.plot(roll.index, roll, "-", color="black", lw=1.8, label="7-day rolling mean")
ax.axvline(35.5, color="0.4", ls="--", lw=1)
ax.set(xlabel="day", ylabel="morning heart rate (bpm)",
       title="The weekly mean shows the rise that single mornings blur")
ax.legend(loc="upper left", fontsize=8)
plt.tight_layout()

# %% [markdown]
# **For the athlete:** "Your morning heart rate this week averaged about 2 beats a minute above
# your usual level; that is training information, not a diagnosis, so tell us how you are
# sleeping and we will look again next week."
