"""Q-13: Find the beats in ten seconds of ECG -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q13-ecg-beats/
Data:     https://apopt.com/data/tutorials/q13-ecg-beats/ (keep raw/ next to this file)
"""

# %% [markdown]
# A chest strap that streams its raw ECG lets you find the heartbeats yourself. The file is
# three minutes of the instructor at rest, recorded with a Polar H10 strap: one row per ECG
# sample, with the strap's own beat-to-beat interval (`rr`, in milliseconds) on a few rows.
# You will look at ten seconds of it, find every R peak (the tall spike of each beat), and
# check your count against the strap.
#
# ### Open the file and read its clock

# %%
# Open the ECG and measure the sample rate
import numpy as np
import pandas as pd

ecg = pd.read_csv("raw/2026-06-26_2141_day_excerpt.csv")
t = (ecg["time"] - ecg["time"].iloc[0]) / 1e9        # nanoseconds -> seconds from the start
fs = 1 / t.diff().median()                           # samples per second, from the clock itself
pad = (t >= 59) & (t < 71)            # one spare second each side: filters misbehave at edges
x, tt = ecg["ecg"][pad].to_numpy(), t[pad].to_numpy()
print(f"{len(ecg)} samples in {t.iloc[-1]:.1f} s: {fs:.2f} samples/s, one sample = {1000 / fs:.2f} ms")
ten = (tt >= 60) & (tt < 70)                         # the ten seconds we count in
print(f"ten-second window: {ten.sum()} samples, ECG from {x[ten].min():.2f} to {x[ten].max():.2f} mV")

# %% [markdown]
# About 130 samples a second, so an R peak can only be placed to within one sample, 7.7 ms.
# The code keeps one spare second on each side of the window. A filter has nothing to work
# with beyond the last sample, so near an edge it goes wrong; without the spare second, a beat
# that peaked just before 60 s is "found" on the first sample of the window.
#
# ### Find the R peaks
#
# The recipe is the one in Section 5.4 of the book, after Pan and Tompkins: keep the
# frequencies where the QRS complex lives (5 to 15 Hz), take the slope, square it so every beat
# is a positive hump, average over 150 ms, and accept a hump as a beat only if it is tall enough
# and at least 200 ms after the last one. Then move each beat to the tallest ECG sample nearby.

# %%
# Band-pass, slope, square, average, peaks
from scipy.signal import butter, filtfilt, find_peaks

b, a = butter(2, [5, 15], btype="band", fs=fs)
slope = np.gradient(filtfilt(b, a, x))
w = int(0.150 * fs)                                   # 150 ms, about one QRS complex
hump = np.convolve(slope ** 2, np.ones(w) / w, mode="same")
pk, _ = find_peaks(hump, height=0.3 * hump.max(), distance=int(0.2 * fs))  # 200 ms refractory
r = np.array([max(p - w, 0) + np.argmax(x[max(p - w, 0):p + w]) for p in pk])  # tallest ECG sample
r = r[(tt[r] >= 60) & (tt[r] < 70)]                  # keep the beats inside the ten seconds
rr = np.diff(tt[r]) * 1000
print(f"{len(r)} beats, {len(rr)} intervals: {np.round(rr).astype(int).tolist()} ms")
print(f"mean interval {rr.mean():.1f} ms -> {60000 / rr.mean():.1f} beats/min")

# %% [markdown]
# Ten beats and nine intervals between them, 60.5 beats a minute in this stretch. Every
# interval is a whole number of samples, so the values come in steps of 7.7 ms (970, 978, 985:
# one sample apart).
#
# ### Look, and check against the strap

# %%
# The beats on the trace, and the strap's own intervals
import matplotlib.pyplot as plt

strap = ecg.loc[(t >= 60) & (t < 70) & ecg["rr"].notna(), "rr"]
print(f"strap: {len(strap)} intervals reported in the same ten seconds, mean {strap.mean():.1f} ms")
print(f"difference in mean interval: {rr.mean() - strap.mean():+.1f} ms")

fig, ax = plt.subplots(figsize=(9, 3))
ax.plot(tt[ten], x[ten], lw=0.8, label="ECG")
ax.plot(tt[r], x[r], "o", mfc="none", ms=9, label="detected R peak")
ax.set(xlabel="time from start of file (s)", ylabel="ECG (mV)", title=f"{len(r)} beats in 10 s")
ax.legend(loc="lower right")
plt.tight_layout()

# %% [markdown]
# The strap reports each interval in a packet a little after the beat, so its rows in a
# ten-second window are not exactly the same beats as yours: it reported 10 intervals here,
# you measured 9, and the means differ by 6.3 ms, less than one sample and under half a beat a
# minute. Your detector and the strap agree on the rhythm.
#
# **For the athlete:** "Your strap is reading your heartbeat cleanly: we found each beat in the
# raw signal ourselves, and the rhythm matches what the strap reported."
