"""CS-6: From a chest-strap recording to a recovery number -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### Step 1 · Gather
#
# The instructor slept in a Polar H10 chest strap on two nights in June 2026, 26 and 28 June.
# The strap wrote two things: its raw ECG, about 130 samples a second, and the interval
# between beats it timed itself (the RR interval). The whole-night ECG files are large, so this
# study uses the strap's beat files for the nights, one row per beat, and a three-minute ECG
# excerpt from the middle of the second night to check those beats against the raw signal.
# Everything here is training information about one healthy adult, not medical advice.

# %%
# Step 1 · Open the two nights
import numpy as np
import pandas as pd

FILES = {"2026-06-26": "raw/2026-06-26_2347_sleep_rr.csv", "2026-06-28": "raw/2026-06-28_2343_sleep_rr.csv"}
nights = {k: pd.read_csv(f) for k, f in FILES.items()}            # t_s, rr_ms, hr_bpm
for k, d in nights.items():
    print(f"{k}: {len(d)} beats over {d['t_s'].iloc[-1] / 3600:.2f} h; columns {list(d.columns)}")

# %% [markdown]
# Before trusting the strap's intervals for a whole night, check them against the ECG it
# recorded at the same time. Find the R peaks in the three-minute excerpt (the method of Q-13),
# then line up your intervals with the ones the strap wrote.

# %%
# Step 1 · Check the strap's intervals against its own ECG
from scipy.signal import butter, filtfilt, find_peaks

ecg = pd.read_csv("raw/2026-06-28_2343_sleep_excerpt.csv")
t, x = ((ecg["time"] - ecg["time"].iloc[0]) / 1e9).to_numpy(), ecg["ecg"].to_numpy()
fs = 1 / np.median(np.diff(t))
b, a = butter(2, [5, 15], btype="band", fs=fs)
w = int(0.150 * fs)
hump = np.convolve(np.gradient(filtfilt(b, a, x)) ** 2, np.ones(w) / w, mode="same")
pk, _ = find_peaks(hump, height=0.3 * np.percentile(hump, 99), distance=int(0.2 * fs))
r = np.array([max(p - w, 0) + np.argmax(x[max(p - w, 0):p + w]) for p in pk])
r = r[(t[r] > 1) & (t[r] < t[-1] - 1)]                      # skip the edges, where filters fail
mine, t_mine = np.diff(t[r]) * 1000, t[r][1:]
strap, t_strap = ecg["rr"].dropna().to_numpy(), t[ecg["rr"].notna().to_numpy()]

def mismatch(k):                                           # strap rows shifted k beats
    n = min(len(mine), len(strap) - k)
    return np.median(np.abs(mine[:n] - strap[k:k + n]))

k = min(range(11), key=mismatch)
n = min(len(mine), len(strap) - k)
print(f"{len(mine)} intervals from the ECG, {len(strap)} from the strap; best shift {k} rows")
print(f"strap rows written {np.median(t_strap[k:k + n] - t_mine[:n]):.1f} s after the beat")
print(f"difference: median {mismatch(k):.1f} ms, largest {np.abs(mine[:n] - strap[k:k + n]).max():.1f} ms")

# %% [markdown]
# Lined up, the two agree to within one ECG sample (7.7 ms) on every beat. The strap's intervals
# are written to the file a few seconds late, which does not matter for HRV but would matter if
# you joined them to another clock. From here on the study uses the strap's own intervals: they
# are the same beats, given to the millisecond.
#
# ### Step 2 · Statistics
#
# A profile of each night first: how many beats, how they are spread, and how many look wrong
# before any rule is applied.

# %%
# Step 2 · Profile each night
rows = []
for k, d in nights.items():
    rr = d["rr_ms"].to_numpy(float)
    jump = np.abs(np.diff(rr)) > 0.2 * rr[:-1]
    rows.append({"night": k, "beats": len(rr), "hours": d["t_s"].iloc[-1] / 3600,
                 "median_rr_ms": np.median(rr), "min_rr_ms": rr.min(), "max_rr_ms": rr.max(),
                 "outside_300_2000": int(((rr < 300) | (rr > 2000)).sum()), "jumps_over_20pct": int(jump.sum()),
                 "mean_hr_bpm": 60000 / rr.mean()})
print(pd.DataFrame(rows).round(1).to_string(index=False))

# %% [markdown]
# The first night has nearly four times as many suspect jumps and 110 intervals outside the
# range a resting heart produces, from 254 ms to over 11 seconds. A mean heart rate of 47 to 50
# beats a minute is what you would expect in sleep. The extremes need a picture before a rule.
#
# ### Step 3 · Visualize

# %%
# Step 3 · The first night, raw
import matplotlib.pyplot as plt

d = nights["2026-06-26"]
rr = d["rr_ms"].to_numpy(float)
prev = np.r_[np.nan, rr[:-1]]
suspect = ~((rr >= 300) & (rr <= 2000) & (np.abs(rr - prev) <= 0.2 * prev))
h = d["t_s"] / 3600
fig, ax = plt.subplots(2, 1, figsize=(9, 5))
ax[0].plot(h, rr, ".", ms=1)
ax[0].set(ylim=(0, 2500), xlabel="hours since the recording started", ylabel="RR (ms)", title="2026-06-26, every beat")
z = (h > 4.0) & (h < 4.35)
ax[1].plot(h[z], rr[z], ".", ms=3, label="beat")
ax[1].plot(h[z & suspect], rr[z & suspect], "x", ms=5, color="k", label="suspect")
ax[1].set(ylim=(0, 2500), xlabel="hours since the recording started", ylabel="RR (ms)", title="twenty minutes near hour 4.1")
ax[1].legend(loc="upper right")
plt.tight_layout()

# %% [markdown]
# Most of the night is a tidy band between about 1000 and 1400 ms. Near hour 4.1 the intervals
# collapse to 300 to 600 ms for about six minutes, a heart rate of 100 to 200 a minute, which a
# sleeping heart does not reach. The strap was most likely counting noise while the sleeper moved
# and the electrodes lost contact. Some of those noise beats happen to agree with the one before
# them, so a beat-by-beat rule alone will not catch them all. Those minutes must not feed an HRV
# number, but the rules must not throw away the good beats around them either.
#
# ### Step 4 · Cleanse
#
# The rules, written before looking at any HRV number:
#
# 1. An interval outside 300 to 2000 ms is removed.
# 2. An interval more than 20% away from the previous **recorded** interval is removed.
# 3. A successive difference is used only when both of its beats were kept.
# 4. A five-minute window counts only if it keeps at least 120 beats and at least 80% of its
#    beats, the Heart app's test for a window valid for HRV.
#
# Rule 2 has a trap. Compare with the previous **kept** interval instead, and one bad beat can
# become the reference for everything after it.

# %%
# Step 4 · The previous recorded beat, or the previous kept beat?
def keep_recorded(rr):
    prev = np.r_[np.nan, rr[:-1]]
    return (rr >= 300) & (rr <= 2000) & (np.abs(rr - prev) <= 0.2 * prev)

def keep_kept(rr):                                   # the trap, written out for comparison
    keep, last = np.zeros(len(rr), bool), np.nan
    for i, v in enumerate(rr):
        if 300 <= v <= 2000 and (np.isnan(last) or abs(v - last) <= 0.2 * last):
            keep[i], last = True, v
    return keep

def longest_gap(keep):
    runs = np.diff(np.flatnonzero(np.r_[True, keep, True])) - 1
    return int(runs.max())

for k, d in nights.items():
    rr = d["rr_ms"].to_numpy(float)
    a, b = keep_recorded(rr), keep_kept(rr)
    print(f"{k}: previous recorded removes {(~a).sum():5d} (longest run {longest_gap(a):4d}); "
          f"previous kept removes {(~b).sum():5d} (longest run {longest_gap(b):4d})")

# %% [markdown]
# The "previous kept" version removes thousands of beats on each night, including a run of
# more than 4000 good beats on the first: once an odd interval sets the reference, every normal
# beat after it looks 20% away and is thrown out, for hours. Comparing with the previous
# recorded beat lets the series recover two beats after an artifact. Now apply rules 1 to 4,
# write the clean copies and a change log.

# %%
# Step 4 · Apply the rules, windows and a change log
import os

os.makedirs("clean", exist_ok=True)
log, wins = [], []
for k, d in nights.items():
    rr = d["rr_ms"].to_numpy(float)
    d["keep"] = keep_recorded(rr)
    d["pair"] = d["keep"] & np.r_[False, d["keep"].to_numpy()[:-1]]
    d["sq"] = np.where(d["pair"], np.r_[np.nan, np.diff(rr)] ** 2, 0.0)
    g = d.groupby(d["t_s"] // 300)
    w = pd.DataFrame({"night": k, "start_h": g["t_s"].min() / 3600, "beats_kept": g["keep"].sum(),
                      "kept_share": g["keep"].mean(), "rmssd_ms": np.sqrt(g["sq"].sum() / g["pair"].sum()),
                      "hr_bpm": 60000 / g["rr_ms"].mean()})
    w["valid"] = (w["beats_kept"] >= 120) & (w["kept_share"] >= 0.8)
    wins.append(w)
    d[["t_s", "rr_ms", "keep"]].to_csv(f"clean/{k}_beats.csv", index=False)
    log += [{"night": k, "rule": "1-2 beats removed", "count": int((~d["keep"]).sum())},
            {"night": k, "rule": "3 differences used", "count": int(d["pair"].sum())},
            {"night": k, "rule": "4 windows dropped", "count": int((~w["valid"]).sum())}]
wins = pd.concat(wins).round(3)
wins.to_csv("clean/windows.csv", index=False)
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
print(pd.DataFrame(log).pivot(index="rule", columns="night", values="count").to_string())

# %% [markdown]
# Three windows of the first night fail rule 4, two of them the noisy minutes near hour 4.1,
# where rule 2 alone had let some noise beats through. One window of the second night fails
# because it is only the last few minutes. The raw files are untouched; the clean copies mark
# each beat as kept or not, so anyone can check the rules.
#
# ### Step 5 · Features: a number per night, and how sure it is
#
# The nightly number is the median RMSSD of the valid windows, and its natural logarithm, ln
# RMSSD, the form used for day-to-day comparisons (Section 5.5). How precise is one night's
# median? Resample the night with a bootstrap. Neighbouring windows are alike (sleep comes in
# cycles), so resample blocks of six windows, half an hour at a time, not single windows.

# %%
# Step 5 · Nightly RMSSD with a bootstrap interval
rng = np.random.default_rng(0)
nightly = []
for k, w in wins[wins["valid"]].groupby("night"):
    v = w["rmssd_ms"].to_numpy()
    blocks = [v[i:i + 6] for i in range(0, len(v) - 5, 6)]   # half-hour blocks
    boot = [np.median(np.concatenate([blocks[j] for j in rng.integers(0, len(blocks), len(blocks))]))
            for _ in range(2000)]
    lo, hi = np.percentile(boot, [2.5, 97.5])
    nightly.append({"night": k, "windows": len(v), "rmssd_ms": np.median(v), "ln_rmssd": np.log(np.median(v)),
                    "ci_low_ms": lo, "ci_high_ms": hi, "lowest_5min_hr": w["hr_bpm"].min()})
nightly = pd.DataFrame(nightly).round(2)
nightly.to_csv("clean/nightly_rmssd.csv", index=False)
case_file = pd.read_csv("raw/hrv_nightly.csv")
print(nightly.to_string(index=False))
print("case file's summary:", dict(zip(case_file["night"], case_file["median_rmssd_ms"])))

# %% [markdown]
# The second night matches the case file. The first is 1.5 ms higher, and only rule 4 differs:
# the case file keeps the three windows of the first night in which only 36 to 70% of the beats
# survived, and their RMSSD of 41 to 45 ms pulls the median down. A window rule moves the number
# too. An earlier version of the case file's script also broke rule 3: it took differences
# between successive *kept* beats, so a difference could reach across a removed beat, and it
# reported 58.5 and 61.6 ms, 6.7 and 2.9 ms too high. The same word, RMSSD, and the same rule
# for beats, gave different numbers: always say how the differences and windows were taken.
#
# Each night's interval is wide, about ±10 ms on the first night: sleep varies within a
# night, and a nightly median carries that. The two nights differ by 6.9 ms, less than either
# interval.
#
# ### Step 5 · A baseline band from two nights?
#
# The decision needs a band: the usual range of this athlete's ln RMSSD, so that a new night can
# be called "normal for you" or "below your band". Section 5.5 builds it from seven mornings:
# the mean, and the day-to-day standard deviation as the noise. Here there are two nights. What
# would a band from two nights be worth?

# %%
# Step 5 · How well do n nights pin down the day-to-day spread?
from scipy import stats

ln = np.log(nightly["rmssd_ms"].to_numpy())
sd = ln.std(ddof=1)
print(f"two nights: ln RMSSD {ln[0]:.2f} and {ln[1]:.2f}; mean {ln.mean():.2f}, SD {sd:.3f}")
v = wins[wins["valid"]]["rmssd_ms"]
print(f"not a day-to-day spread: SD of ln RMSSD over all {len(v)} windows = {np.log(v).std(ddof=1):.2f}")
n = np.array([2, 3, 5, 7, 14, 28])
low = np.sqrt((n - 1) / stats.chi2.ppf(0.975, n - 1))       # 95% range of the true SD,
high = np.sqrt((n - 1) / stats.chi2.ppf(0.025, n - 1))      # as a multiple of the measured one
print(pd.DataFrame({"nights": n, "true SD from": low, "to": high}).round(2).to_string(index=False))

fig, ax = plt.subplots(1, 2, figsize=(9, 3.4))
yerr = [nightly["rmssd_ms"] - nightly["ci_low_ms"], nightly["ci_high_ms"] - nightly["rmssd_ms"]]
ax[0].errorbar(nightly["night"], nightly["rmssd_ms"], yerr=yerr, fmt="o", capsize=6, color="k")
ax[0].set(ylabel="nightly RMSSD (ms)", title="two nights, 95% bootstrap intervals", xlim=(-0.5, 1.5))
ax[1].fill_between(n, low, high, alpha=0.3, step=None)
ax[1].plot(n, low, "o-", color="k", ms=4); ax[1].plot(n, high, "s--", color="k", ms=4)
ax[1].set(yscale="log", xlabel="nights in the baseline", ylabel="true SD / measured SD",
          title="how sure is the spread?")
plt.tight_layout()

# %% [markdown]
# From two nights the measured spread, 0.088 in ln units, could come from a true day-to-day
# spread anywhere from about half of it to 32 times it. A band built on that says nothing. With
# seven nights the range is 0.64 to 2.2 times, still wide but usable; with four weeks, 0.79 to
# 1.36. That is why Section 5.5 asks for seven mornings at least, and why a review of
# heart-rate monitoring found that HRV followed running performance only when 3 to 4 days or
# more were averaged, not from single days (Buchheit, 2014).
#
# So the honest answer to "is last night normal for me?" is: the case file cannot say yet. Two
# nights give two numbers, 51.8 and 58.7 ms, each uncertain by several milliseconds, and no
# band. The action is to collect the band, the same way every time.
