# Q-15: One night's RMSSD

Data-Driven Athletics tutorial · Week 5 · Chapter 5 · about 20 min · workflow steps: Gather, Statistics, Visualize, Cleanse, Features

Web page: https://apopt.com/course/tutorials/q15-rmssd/ · Data: https://apopt.com/data/tutorials/q15-rmssd/

## The decision

One night of sleep, one number for heart rate variability. Which number, computed how, so that
it can be compared with the next night?

## The raw data

- `raw/2026-06-28_2343_sleep_rr.csv`: one night of the instructor's sleep, one row per beat (t_s seconds from the start, rr_ms the strap's beat interval, hr_bpm the strap's heart rate where reported) The instructor's own Polar H10 recording, night of 28 June 2026, from the course case file `athletes/jh/heart/`, published under his name.

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

*Predict first:* About what share of the night's beats do you expect to be artifacts (missed, split or impossible beats)?

```python
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())}")
```

Output:

```
17082 beats over 6.01 h
RR from 293 to 2383 ms, median 1279 ms
outside 300-2000 ms (treated as not physiological): 5
```

### 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.

```python
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")
```

Output:

```
kept 16879 of 17082 beats (98.8%); 16701 successive differences
RMSSD over the whole night: 59.6 ms
```

### 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.

*Predict first:* Will the median of the five-minute RMSSDs be above or below the whole-night value?

```python
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")
```

Output:

```
72 valid windows of 73, RMSSD from 29.6 to 98.0 ms
median RMSSD 58.7 ms (middle half 49.7 to 67.2); ln RMSSD 4.07
lowest 5-minute heart rate 43.4 beats/min
```

### The night as a picture

```python
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()
```

![Two panels against hours of sleep. Top, RMSSD per five-minute window in milliseconds, between about 30 and 100 ms with the median as a dashed line. Bottom, heart rate per window, mostly 43 to 52 beats a minute, with one window near 68.](https://apopt.com/course/tutorials/q15-rmssd/c07-1.png)

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."

## With your own data

Wear the strap overnight (or record five minutes on waking) with the Heart app, export the beat
intervals as a two-column file `t_s, rr_ms`, and run the same cells on it.

## Action card

- **Finding:** Last night's RMSSD was 58.7 ms, the median of 72 five-minute windows.
- **Evidence:** 98.8% of beats passed the artifact rule; the windows ranged from 29.6 to 98.0 ms.
- **Sure:** The night's number is solid; what it means needs other nights measured the same way.
- **Action:** Record the same way for at least six more nights before reading anything into it.
- **Retest:** Every night or morning, same strap, same rule.

## References

- *Data-Driven Athletics*, Chapter 5, Artifacts and ectopic beats (Section 5.4) and Heart Rate Variability (Section 5.5).

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
