"""Q-14: Heart rate from beat intervals -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q14-hr-from-rr/
Data:     https://apopt.com/data/tutorials/q14-hr-from-rr/ (keep raw/ next to this file)
"""

# %% [markdown]
# A chest strap reports two things: the time between beats (the RR interval, in milliseconds)
# and a heart rate for its display. They are not the same number. This file is eight minutes of
# the instructor wearing a Polar H10: quiet at first, then two short efforts, then rest. Every
# ECG sample is a row; the `rr` column is filled on the rows where the strap reported a beat
# interval, and the `hr` column on the rows where it reported its displayed heart rate.
#
# ### Separate the beats from the display

# %%
# Two outputs of one strap
import numpy as np
import pandas as pd

raw = pd.read_csv("raw/2026-06-27_1810_day.csv.gz")       # pandas reads the gzip directly
t = (raw["time"] - raw["time"].iloc[0]) / 1e9               # seconds from the start
beats = pd.DataFrame({"t": t[raw["rr"].notna()], "rr": raw["rr"].dropna()})
shown = pd.DataFrame({"t": t[raw["hr"].notna()], "hr": raw["hr"].dropna()})
print(f"{len(raw)} rows over {t.iloc[-1]:.1f} s ({t.iloc[-1] / 60:.1f} min)")
print(f"{len(beats)} beat intervals, {len(shown)} displayed heart rates")
print(f"RR from {beats['rr'].min():.0f} to {beats['rr'].max():.0f} ms; "
      f"intervals add up to {beats['rr'].sum() / 1000:.1f} s")

# %% [markdown]
# The intervals add up to within a second of the recording's length, as they should if no
# beat is missing. A missed beat would leave a gap of a whole interval.
#
# ### Heart rate, beat by beat
#
# One beat that lasts RR milliseconds is a heart rate of 60 000 / RR beats a minute. That gives
# a heart rate for every beat. Now average it over the session, two ways.

# %%
# A rate per beat, and two averages
beats["hr"] = 60000 / beats["rr"]
per_beat = beats["hr"].mean()                       # every beat counts once
per_time = 60000 / beats["rr"].mean()               # beats counted per minute of time
print(f"mean of the beat heart rates   {per_beat:.1f} beats/min")
print(f"60 000 / mean RR               {per_time:.1f} beats/min")
print(f"beats / minutes                {len(beats) / (beats['rr'].sum() / 60000):.1f} beats/min")
print(f"strap's displayed mean         {shown['hr'].mean():.1f} beats/min")

# %% [markdown]
# They differ by about 9 beats a minute. A fast beat is short, so a minute of hard work holds
# many more beats than a minute of rest, and averaging over beats lets the hard minutes count
# too often. The heart rate of a session is beats divided by minutes, which is 60 000 divided by
# the mean interval. The strap's display agrees with that one.
#
# ### Beat by beat against the display

# %%
# The two outputs over time, and the peak
import matplotlib.pyplot as plt

five = 60000 / beats.groupby(beats["t"] // 5)["rr"].mean()   # 5-second bins, beats per minute of time
print(f"highest single beat {beats['hr'].max():.1f} at {beats.loc[beats['hr'].idxmax(), 't'] / 60:.1f} min")
print(f"highest 5-second rate {five.max():.1f}; highest displayed {shown['hr'].max():.0f} beats/min")

fig, ax = plt.subplots(figsize=(9, 3.4))
ax.plot(beats["t"] / 60, beats["hr"], ".", ms=3, label="from each RR interval")
ax.plot(shown["t"] / 60, shown["hr"], "-", lw=1.5, color="k", label="strap's display")
ax.set(xlabel="time (min)", ylabel="heart rate (beats/min)")
ax.legend(loc="upper left")
plt.tight_layout()

# %% [markdown]
# The highest single beat, 142.5 beats a minute, sits alone, about 30 above the beats on either
# side of it. A heart does not jump that far for one beat during steady effort: a beat was
# mistimed, or a noise spike was counted. A few more such dots sit near minute 5.8. Averaged over
# five seconds, the peak is 133.4, and the strap's smoothed display, 134, agrees. Use the
# intervals for anything that changes within seconds, but never report one beat as a peak.
# Chapter 5 shows the rules that remove such beats; Q-15 uses one.
#
# **For the athlete:** "Your heart rate over this session averaged about 81 beats a minute, and
# your peak was about 134; one beat that read 142 was a glitch, not you."
