# Q-13: Find the beats in ten seconds of ECG

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

Web page: https://apopt.com/course/tutorials/q13-ecg-beats/ · Data: https://apopt.com/data/tutorials/q13-ecg-beats/

## The decision

Before any heart-rate or HRV number from a strap is used, check that the strap is finding the
beats. Ten seconds of raw ECG is enough to see it with your own eyes and count.

## The raw data

- `raw/2026-06-26_2141_day_excerpt.csv`: three minutes of the instructor's resting ECG at about 130 samples a second (columns time, ecg, hr, rr, marker) The instructor's own Polar H10 recording, 26 June 2026, from the course case file `athletes/jh/heart/`, published under his name.

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

*Predict first:* The instructor's resting heart rate is about 58 beats a minute. How many beats do you expect in ten seconds?

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

Output:

```
23379 samples in 180.0 s: 129.88 samples/s, one sample = 7.70 ms
ten-second window: 1298 samples, ECG from -1.20 to 1.77 mV
```

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.

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

Output:

```
10 beats, 9 intervals: [970, 985, 986, 1009, 1009, 1009, 1016, 978, 962] ms
mean interval 991.5 ms -> 60.5 beats/min
```

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

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

Output:

```
strap: 10 intervals reported in the same ten seconds, mean 997.8 ms
difference in mean interval: -6.3 ms
```

![Ten seconds of resting ECG in millivolts against time, with a circle on each of the ten detected R peaks.](https://apopt.com/course/tutorials/q13-ecg-beats/c05-1.png)

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

## With your own data

Record two minutes at rest with the Heart app or a logging app that writes the same five
columns, open your file instead, and pick a ten-second window where you sat still.

## Action card

- **Finding:** The strap finds the beats; 10 R peaks in ten seconds at rest, 60.5 beats a minute.
- **Evidence:** The detected mean interval (991.5 ms) and the strap's own (997.8 ms) differ by less than one sample.
- **Sure:** High for this clean, resting stretch; a dry or slipping strap needs the same check.
- **Action:** Wet the strap's electrodes before each session and look at ten seconds of ECG once.
- **Retest:** Repeat the check whenever a heart-rate number looks wrong.

## References

- Pan, J., and Tompkins, W. J. (1985). A real-time QRS detection algorithm. *IEEE Transactions on Biomedical Engineering*, BME-32(3), 230–236.
- *Data-Driven Athletics*, Chapter 5, From ECG to Beats (Section 5.4).

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