"""Q-15: One night's RMSSD -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# RMSSD, the root mean square of successive differences between beats, is the working measure
# of heart rate variability (Section 5.5): it follows the fast, vagal part of the beat-to-beat
# variation. Here you compute it for one whole night of the instructor's sleep, from the beat
# intervals his chest strap recorded, one row per beat.
#
# ### Open the night

# %%
# Six hours of beats
import numpy as np
import pandas as pd

night = pd.read_csv("raw/2026-06-28_2343_sleep_rr.csv")     # t_s, rr_ms, hr_bpm
rr = night["rr_ms"].to_numpy(float)
print(f"{len(rr)} beats over {night['t_s'].iloc[-1] / 3600:.2f} h")
print(f"RR from {rr.min():.0f} to {rr.max():.0f} ms, median {np.median(rr):.0f} ms")
print(f"outside 300-2000 ms (treated as not physiological): {int(((rr < 300) | (rr > 2000)).sum())}")

# %% [markdown]
# ### An artifact rule, and the successive differences it allows
#
# The rule: keep a beat if its interval is between 300 and 2000 ms and within 20% of the
# **previous recorded** beat. Comparing with the previous recorded beat, not the last one kept,
# means one bad beat removes only its neighbours, not a long run of good beats after it. A
# successive difference is then used only when **both** of its beats were kept, so no difference
# reaches across a removed beat.

# %%
# Keep, pair, and RMSSD for the whole night
prev = np.r_[np.nan, rr[:-1]]
keep = (rr >= 300) & (rr <= 2000) & (np.abs(rr - prev) <= 0.2 * prev)
pair = keep & np.r_[False, keep[:-1]]                # this beat and the one before both kept
diff = np.r_[np.nan, np.diff(rr)]
night["keep"], night["pair"], night["diff"] = keep, pair, diff
print(f"kept {keep.sum()} of {len(rr)} beats ({keep.mean():.1%}); {pair.sum()} successive differences")
print(f"RMSSD over the whole night: {np.sqrt(np.mean(diff[pair] ** 2)):.1f} ms")

# %% [markdown]
# ### Five-minute windows, then the median
#
# One number for six hours mixes deep sleep, light sleep and waking. The usual way, and the
# Heart app's, is RMSSD in each five-minute window, then a summary of the windows. A window
# counts if it holds at least 120 kept beats and at least 80% of its beats were kept, the same
# test the Heart app applies.

# %%
# RMSSD per window, and the night's median
def window_stats(w):
    d = w["diff"][w["pair"]]
    return pd.Series({"beats": int(w["keep"].sum()), "kept": w["keep"].mean(),
                      "rmssd": np.sqrt(np.mean(d ** 2)), "hr": 60000 / w["rr_ms"][w["keep"]].mean()})

win = night.groupby(night["t_s"] // 300).apply(window_stats)
win["valid"] = (win["beats"] >= 120) & (win["kept"] >= 0.8)
ok = win[win["valid"]]
q1, q3 = ok["rmssd"].quantile([0.25, 0.75])
print(f"{len(ok)} valid windows of {len(win)}, RMSSD from {ok['rmssd'].min():.1f} to {ok['rmssd'].max():.1f} ms")
print(f"median RMSSD {ok['rmssd'].median():.1f} ms (middle half {q1:.1f} to {q3:.1f}); "
      f"ln RMSSD {np.log(ok['rmssd'].median()):.2f}")
print(f"lowest 5-minute heart rate {ok['hr'].min():.1f} beats/min")

# %% [markdown]
# ### The night as a picture

# %%
# RMSSD and heart rate through the night
import matplotlib.pyplot as plt

hours = (win.index * 300 + 150) / 3600
fig, ax = plt.subplots(2, 1, figsize=(9, 4.4), sharex=True)
ax[0].plot(hours[win["valid"]], ok["rmssd"], "o-", ms=3)
ax[0].axhline(ok["rmssd"].median(), ls="--", color="k", lw=1, label="median of the windows")
ax[0].set(ylabel="RMSSD (ms)")
ax[0].legend(loc="upper right")
ax[1].plot(hours[win["valid"]], ok["hr"], "s-", ms=3, color="k")
ax[1].set(xlabel="hours since the recording started", ylabel="heart rate (beats/min)")
plt.tight_layout()

# %% [markdown]
# The median of the windows (58.7 ms) sits a little below the whole-night value (59.6 ms):
# the whole-night figure averages squared differences, which the most variable windows pull up.
# RMSSD swings about three-fold within the night, mostly opposite to heart rate: when the heart
# slows, the beat-to-beat variation grows. The one window near 68 beats a minute, probably a
# brief waking, has the lowest RMSSD. One five-minute window says little; the median
# over the night is the number to keep, and only beside other nights measured the same way.
# The case study CS-6 does that for two nights.
#
# **For the athlete:** "Last night your heart rate variability was about 59 ms (the middle of
# the night's five-minute readings); it means something only next to your other nights."
