<!-- Generated by book/tools/make-index.py from the book source. -->

> Hedengren, J. (Ed.) (2027). Chapter 5: Heart Rate, ECG and Heart Rate Variability. In *Data-Driven Athletics: Measuring, Modeling and Coaching Human Performance with Video and Wearable Data* (pp. 121–150). IRSRI Sports Research Institute. CC BY 4.0.

**Question.** Two devices on the same runner disagree by 15 beats a minute in the middle of an interval session. Which one is right, and how would you know?

**Objectives.**
- Explain how a chest-strap ECG sensor and an optical sensor each detect a heartbeat, and why they fail in different ways.
- Convert between RR interval and heart rate, and compute RMSSD, SDNN and pNN50 by hand for a short series.
- Compare two devices with bias, mean absolute error, mean absolute percentage error and limits of agreement.
- Describe how heart rate responds to the start of exercise, to steady work and to recovery, and fit a time constant to each.
- Set heart-rate zones three ways and compute a training-load score.
- Report a heart-rate finding to an athlete without overstating it.

# 5 Heart Rate, ECG and Heart Rate Variability

Heart rate is the first wearable signal most athletes meet, and the most misunderstood. A watch shows a number every second, the number looks exact, and two watches on the same arm can disagree by a large margin. This chapter starts from the heartbeat itself, follows it into two kinds of sensor, and ends with a sentence you could say to an athlete. On the way you will meet the electrocardiogram (ECG), heart rate variability (HRV), the time course of heart rate in exercise, training zones and load, and the statistics of comparing one device with another.

The running example uses real recordings. The Heart app at https://apopt.com/heart ships three de-identified recordings from a chest strap, made by two people who agreed to share them: eight minutes of seated rest, one night of sleep, and a hard 35-minute run with five efforts. You can open all three in the app with no strap of your own, and every Python listing in this chapter reads them. Then you record yourself.

## 5.1 Wearable Sensors at a Glance

Chapters 5, 6 and 7 cover sensors worn on the body. Before you study one closely, look at them all together. Table 5.1 lists the sensors you are likely to meet in sport, where each is worn, the physical principle it uses, what it measures directly and what it only derives or models. The column “Main sources of error” is the one to remember. Error depends far more on the activity and on where the sensor sits than on the brand.

*Table 5.1. Wearable sensors in sport. “Measured directly” is what the physics delivers; everything in the next column is computed from it, and modeled outputs deserve the least trust.*

| Sensor | Principle | Measured directly | Derived or modeled | Main sources of error | Ch. |
|---|---|---|---|---|---|
| Chest-strap ECG | Two skin electrodes pick up the heart's electrical signal | R-wave times, so RR intervals; raw ECG on some straps | Heart rate, HRV, breathing-rate estimate | Dry electrodes at the start, static from synthetic shirts, strap slip, ectopic beats | 5 |
| Optical, wrist | Light into skin; a photodiode reads blood-volume pulses (PPG) | Pulse wave | Heart rate; pulse-interval variability at rest | Arm motion, cadence lock, loose fit, cold skin, wrist flexion, tattoos | 5 |
| Optical, upper arm or forearm | As at the wrist | Pulse wave | Heart rate | The same causes, each smaller | 5 |
| Ring, in-ear | Optical, at a site with good blood flow | Pulse wave | Night heart rate and HRV; sleep estimate | Motion in exercise; fit | 5, 7 |
| Satellite positioning | Timing signals from several satellites | Position and time; Doppler speed | Distance, pace, route, elevation | Buildings, trees, tight turns, slow movement, smoothing | 6 |
| Barometric altimeter | Air pressure falls with height | Pressure | Elevation gain | Weather drift, a blocked port | 6 |
| Accelerometer and gyroscope | Tiny masses on springs | Acceleration, angular rate | Cadence, contact time, vertical oscillation, “running power” | Where it is worn; the model behind each estimate | 6 |
| Cycling power meter | Strain gauges measure torque | Torque and cadence | Power, work | Zero offset, temperature | 6 |
| Pulse oximeter, wrist | Two colors of light | Light ratio | Oxygen saturation | Motion, cold, altitude | 7 |
| Interstitial glucose | Enzyme on a filament under the skin | Glucose in the fluid between cells | Blood glucose estimate, trends | Lag behind blood, pressure, exercise | 7 |
| Lactate (in development) | Enzyme on microneedles or in a sweat patch | Lactate in tissue fluid or sweat | Blood lactate and threshold estimates | Calibration, enzyme life, sweat rate | 7 |
| Core temperature estimate | Heat flow through the skin | Skin temperature, heat flux | Core temperature | Sun, wind, sweat, hard exercise | 7 |
| Muscle oxygen | Near-infrared light over a muscle | Light absorption | Muscle oxygen saturation | Skin-fold thickness, placement | 7 |
| Sweat patch | Sweat fills a channel; chemistry changes | Local sweat volume, chloride | Whole-body sweat and sodium loss | Adhesion; local-to-whole-body scaling | 7 |
| Pressure insole | Pressure cells under the foot | Plantar pressure | Contact time, force estimate | Under-reads force; sampling rate | 6 |

Two habits from the table run through all three chapters. First, tag every output as *measured* (an RR interval, a position fix), *derived* (pace, cadence, heart rate) or *modeled* (a maximal oxygen uptake estimate, calories, a sleep stage, a readiness score). Second, ask what corrupts the measurement in the activity you care about. A wrist sensor that is excellent on a treadmill can be poor in the weight room.

> **Key idea.**
> 
> A heart-rate number is only as good as the beat detection under it. Find out what the device actually sensed, then judge everything computed from it.

## 5.2 The Heart as a Signal Source

Each heartbeat starts as an electrical event. A small patch of tissue in the right atrium, the *sinoatrial node*, fires on its own about once a second at rest. The wave of electrical activation spreads over the two upper chambers (the atria), pauses briefly at the junction between upper and lower chambers, then races down a fast conduction system into the two lower chambers (the ventricles). The ventricles contract a few hundredths of a second after the electrical wave reaches them, and push blood into the arteries. A pressure wave travels along the arteries and reaches your wrist a fraction of a second later.

> **Body science: The waves of one heartbeat.**
> 
> Electrodes on the skin record the sum of the heart's electrical activity as a voltage, the *electrocardiogram* (ECG). One beat has three main parts (Figure 5.1). The small *P wave* is the atria being activated. The tall, sharp *QRS complex* is the ventricles being activated: Q is a small dip, R the tall spike, S the dip after it. The broad *T wave* is the ventricles recovering, ready for the next beat. The time from one R wave to the next is the *RR interval*.

*Figure 5.1. One heartbeat as the ECG records it (schematic). The R wave is the tallest and sharpest part, so it is the easiest to time. Figure 5.2 shows real beats.*

Why time the R wave and not the P or T wave? Because it is tall and narrow. A sharp peak can be located to within one sample; a broad hump cannot. The R wave is also large compared with the noise from muscles and movement, so it survives a run better than the other waves. A chest strap does not record a clinical ECG. It records one *lead*, the voltage between two electrodes placed left and right on the chest, which is enough to find R waves and measure their spacing, and not enough to judge the health of the heart.

> **Limits and cautions: A training sensor, not a diagnosis.**
> 
> A one-lead strap and the Heart app give training information. They do not diagnose, they do not clear anyone for exercise, and they do not predict injury. If a recording shows a rhythm that looks irregular to you, or you have chest pain, faintness or unusual breathlessness, talk to a clinician. Exercises in this book never ask you to interpret a rhythm.

*Figure 5.2. Ten seconds of the resting example (seconds 60 to 70 of `subject-a/rest.csv.gz`), sampled 129.9 times a second. Circles mark the ten R peaks found by Listing 5.2.*

**Example 5.1: Heart rate from one interval.**

An RR interval of 0.800 s means one beat every 0.8 seconds. In a minute there are $60/0.800 = 75$ such intervals, so the heart rate is 75 bpm. In general

$$\HR = \frac{60}{\mathrm{RR}\ (\si{\second})} = \frac{60\,000}{\mathrm{RR}\ (\si{\milli\second})}.$$

In Figure 5.2 the nine intervals between ten peaks average 994.9 ms, which is 60.3 bpm. Notice that heart rate and RR interval are reciprocals: a heart rate that rises by equal steps shortens the RR interval by shrinking steps.

## 5.3 Two Ways to See a Heartbeat

There are two ways to detect a heartbeat without a needle: electrically, from the ECG, or optically, from the pulse of blood under the skin.

\paragraph{Electrical sensing.} A chest strap presses two conductive pads against the skin below the chest muscles. The strap's electronics amplify the voltage between them, find each R wave, and send the result over Bluetooth. The course strap streams three things: single-lead ECG at 130 samples a second, in microvolts; an accelerometer at 25, 50, 100 or 200 samples a second with a range of $\pm2$, 4 or 8 g; and heart rate with beat-to-beat RR intervals through the standard Bluetooth heart-rate service . Because it times the R wave itself, a strap can be accurate even in hard exercise. In a comparison with a clinical ambulatory ECG recorder (a Holter monitor) in 10 people, the strap detected 99.6% of RR intervals correctly against 94.6% for the Holter, and 99.4% against 89.8% during high-intensity work . Its weak points are mechanical: dry electrodes in the first minutes, static from a synthetic shirt, and a strap that slips.

\paragraph{Optical sensing.} A watch or band shines green or infrared light into the skin and measures how much returns to a photodiode. Each heartbeat sends a pulse of blood into the small vessels, which absorbs a little more light, so the returned light rises and falls with the pulse. This is *photoplethysmography* (PPG). The sensor sees the pulse wave, not the electrical beat, and it sees it a fraction of a second later (Figure 5.3).

*Figure 5.3. Left: a chest strap sits below the chest muscles with one electrode each side of the heart. Right: one beat seen two ways. The upper trace is the ECG; the lower trace is the optical pulse at the wrist, which starts after the R wave (arrow) and has a rounded top that is harder to time.*

*Figure 5.4. An optical sensor at the wrist (left) and on the upper arm (right), drawn to the same scale. At the wrist, tendons and bone lie just under the skin and move with every grip; the upper arm has more soft tissue and a firmer fit.*

At rest, the pulse wave is large and the noise is small, and optical sensors do well. In motion, the picture changes. Every arm swing moves the sensor against the skin and moves blood in the wrist, and both change the returned light. The sensor's software has to separate a pulse of about 2 to 3 per second from a motion of similar rate. Wrist flexion in a grip, a loose band, cold skin with little blood flow, and tattoo ink all make the job harder.

\paragraph{Why the upper arm beats the wrist.} The causes of optical error are the same at the upper arm, but each is smaller: there is more soft tissue under the sensor, the band sits more firmly, and no tendons slide beneath it (Figure 5.4). In one study of two devices from the same maker, worn by 16 people with a chest strap as the reference, the mean absolute error was 1.43 bpm for the upper-arm band and 6.41 bpm for the wrist watch .

\paragraph{Cadence lock.} A runner at 170 steps a minute swings each arm 85 times a minute, and every footstrike sends a jolt through the body 170 times a minute. If the runner's heart rate is near 170 as well, the motion signal and the pulse signal sit at almost the same frequency, and the sensor's software can lock onto the step rhythm and report it as heart rate. The reported number then follows the cadence, not the heart: it stays flat when the athlete speeds up on a hill, or jumps to 170 when the true rate is 150 (Figure 5.5). A chest strap cannot be fooled in this way, because the R wave is an electrical event that footstrikes do not produce.

*Figure 5.5. Cadence lock, drawn as a schematic. Between minutes 3.5 and 6.5 the optical reading (dashed) follows the runner's step rate (dotted) instead of the heart (solid). The flat stretch at exactly the cadence is the clue.*

> **Coach's translation: Two devices disagree in an interval session.**
> 
> Return to the question that opened the chapter. A strap and a wrist sensor disagree by 15 beats a minute in the middle of an interval. The strap times electrical events and is rarely fooled by motion. The wrist sensor reads a pulse through moving skin and may have locked to the arm swing. Unless the strap is dry or slipping, believe the strap, and check: does the wrist number sit flat at the runner's cadence?

## 5.4 From ECG to Beats

A strap that streams raw ECG lets you find the beats yourself. That is worth doing once, because it shows you what every heart-rate device does inside, and where it can go wrong.

### 5.4.1 Sampling and timing

An ECG stream is a list of voltages taken at a fixed rate. The course strap takes 130 samples a second, so samples are $1000/130 = \SI{7.7}{\milli\second}$ apart. An R peak can only be placed on a sample, so each RR interval is a whole number of samples: in the resting example the intervals of Figure 5.2 are 977.8, 970.1, 970.1, 985.5, \ldots milliseconds, and every difference between them is a multiple of 7.7 ms.

**Example 5.2: Timing resolution.**

At 130 samples a second one sample is 7.7 ms. At 60 bpm the RR interval is 1000 ms, so an R peak placed one sample late changes that interval by $7.7/1000 = 0.77\%$. At 150 bpm the interval is 400 ms and the same one-sample slip is $7.7/400 = 1.9\%$ of it. Timing error matters more as a share of the interval when the heart beats fast; but at rest the beat-to-beat *differences* that HRV is built from are only tens of milliseconds, so there a few milliseconds of timing error is a large share of the signal you want.

### 5.4.2 Finding R peaks

Most R-peak detectors follow a design published in 1985 by Pan and Tompkins. It turns the ECG into a signal that is large only during QRS complexes, then picks one peak per beat. The Heart app does it in these steps (the source is public; CHECKS.md gives the lines):

- **Condition.** Remove slow baseline wander by subtracting a moving average about 0.66 s wide, smooth lightly, and flip the sign if the strap is worn upside down so that R waves point up.

- **Differentiate.** A five-point derivative makes the steep QRS slopes large and the gentle P and T waves small.

- **Square.** Squaring makes every value positive and exaggerates large slopes over small ones.

- **Average.** A moving average over 150 ms, about the width of a QRS complex, merges each complex into one hump.

- **Threshold.** A hump counts as a beat if it rises above a threshold that starts at 0.3 of the largest value in the first two seconds and then adapts to the size of recent beats.

- **Refractory period.** After a beat, ignore anything for 200 ms. The heart cannot beat again that soon, so a second hump is noise or a T wave.

- **Refine.** Move the beat to the largest ECG value within 15 samples either side, so that the time is the R peak itself, not the center of the hump.

The app then runs a second, energy-based detector with a 240 ms refractory period and counts how many beats the two detectors agree on within 100 ms. That agreement score is one input to its signal-quality grade. Figure 5.6 shows the stages on three seconds of the resting example.

*Figure 5.6. R-peak detection stages on three seconds of the resting example, each scaled to its own maximum. The squared slope is large only in the QRS complexes; after averaging, each beat is one hump that crosses the threshold (dashed) once. Made with the steps of Listing 5.2.*

Listing 5.1 loads the resting example and measures its sample rate from the timestamps, as the Heart app does. Listing 5.2 finds the R peaks with the same steps, using a band-pass filter from 5 to 15 Hz (the frequencies where QRS energy lives) for conditioning, and `scipy.signal.find_peaks` with a minimum distance for the refractory period.

**Listing 5.1.** Load a strap ECG file and measure its sample rate (`code/load_ecg.py`)

```python
# load a chest-strap ECG file, measure its sample rate, plot 10 s.
# rest.csv.gz is examples/subject-a/rest.csv.gz from the Heart app's
# public repository (pandas reads the gzip directly).
import pandas as pd
import matplotlib.pyplot as plt

ecg = pd.read_csv("rest.csv.gz")                # time,ecg,hr,rr,marker
t = (ecg["time"] - ecg["time"].iloc[0]) / 1e9   # nanoseconds -> seconds
fs = 1 / t.diff().median()                      # samples per second
print(f"{len(ecg)} samples, {t.iloc[-1]:.1f} s, {fs:.2f} samples/s")
print(f"one sample = {1000 / fs:.2f} ms")

ten = (t >= 60) & (t < 70)                      # ten seconds to look at
plt.plot(t[ten], ecg["ecg"][ten], lw=0.8)
plt.xlabel("Time (s)"); plt.ylabel("ECG (mV)")
plt.savefig("rest-10s.png", dpi=150)
```

```text
64240 samples, 494.6 s, 129.89 samples/s
one sample = 7.70 ms
```

**Listing 5.2.** R peaks in the style of Pan and Tompkins, then RR intervals (`code/rpeaks.py`)

```python
# find R peaks the Pan-Tompkins way, then RR intervals.
import numpy as np, pandas as pd
from scipy.signal import butter, filtfilt, find_peaks

ecg = pd.read_csv("rest.csv.gz")
t = (ecg["time"].to_numpy() - ecg["time"].iloc[0]) / 1e9
x = ecg["ecg"].to_numpy()
fs = 1 / np.median(np.diff(t))

b, a = butter(2, [5, 15], btype="band", fs=fs)   # keep the QRS band
d = np.gradient(filtfilt(b, a, x))               # 1 differentiate
e = d ** 2                                       # 2 square
w = int(0.150 * fs)                              # 3 average over 150 ms
m = np.convolve(e, np.ones(w) / w, mode="same")
pk, _ = find_peaks(m, height=0.3 * m.max(), distance=int(0.2 * fs))  # 4, 5
lo = np.maximum(pk - w, 0)                       # refine: largest ECG value
r = np.array([a + np.argmax(x[a:i + w]) for a, i in zip(lo, pk)])  # near each

rr = np.diff(t[r]) * 1000                        # ms
pd.DataFrame({"t_s": t[r][1:], "rr_ms": rr}).to_csv("rest-rr.csv",
                                                     index=False, float_format="%.3f")
print(f"{len(r)} beats, {len(rr)} RR intervals")
print(f"mean RR {rr.mean():.1f} ms, mean HR {60000 / rr.mean():.1f} beats/min")
```

```text
479 beats, 478 RR intervals
mean RR 1034.1 ms, mean HR 58.0 beats/min
```

*Predict before you run:* if you removed the refractory distance from `find_peaks`, would the beat count go up or down, and where would the extra peaks come from? (Up; T waves and noise humps would be counted as beats.)

The strap itself reported 479 RR intervals for this recording, and the Heart app kept 478 clean intervals with a mean of 1034.1 ms. Listing 5.2 agrees with both. Agreement on the count and the mean does not yet mean agreement on every interval, as the next section shows.

### 5.4.3 Artifacts and ectopic beats

Two things put wrong intervals into an RR series. An *artifact* is a measurement error: a missed beat makes one interval twice as long; a noise spike counted as a beat splits one interval into two short ones. An *ectopic beat* is real: a beat that starts somewhere other than the sinoatrial node, arrives early, and is usually followed by a longer pause. Ectopic beats are common in healthy people. Neither belongs in heart rate variability, because HRV is meant to describe the rhythm set by the sinoatrial node.

The Heart app uses these rules, each against the median of the 21 surrounding intervals: an interval shorter than 0.8 times the local median, followed by one longer than 1.2 times it, with the pair summing to within 25% of two medians, is flagged as an ectopic pair; an interval of 2000 ms or more that is also 1.5 times the median is a pause; intervals outside 300 to 2000 ms are discarded as non-physiological; and of the rest, only intervals within 25% of the local median are kept as clean “normal-to-normal” (NN) intervals for HRV. It also drops beats in ten-second segments whose signal-quality score is too low. Listing 5.3 uses a simpler rule with the same idea: keep intervals within 20% of the median of their 11 neighbors.

*Figure 5.7. The Heart app's signal-quality timeline for the resting example. The app grades every ten-second segment separately for heart rate, for HRV and for beat shape, and excludes poor segments from HRV.*

## 5.5 Heart Rate Variability

Even at rest the RR interval is not constant. It lengthens and shortens by tens of milliseconds from beat to beat (Figure 5.8). That variation is *heart rate variability* (HRV), and it carries information about the nervous system's control of the heart.

> **Body science: Two brakes and an accelerator.**
> 
> Left to itself, the sinoatrial node fires faster than a resting heart beats. Two branches of the autonomic nervous system adjust it. The *parasympathetic* branch, through the vagus nerve, slows the heart, and acts within a beat or two. The *sympathetic* branch speeds it up, and acts over several seconds. At rest the vagal brake dominates, which is why a resting heart rate is below the node's own rate. Vagal activity also rises and falls with breathing: heart rate speeds up a little as you breathe in and slows as you breathe out. This *respiratory sinus arrhythmia* is the main source of beat-to-beat variation at rest. More vagal activity means more fast, beat-to-beat variation.

*Figure 5.8. The RR series (tachogram) of the resting example from Listing 5.2. Fast wiggles are mostly breathing; slower swings over a minute or more have other causes.*

### 5.5.1 Three time-domain measures

Write the clean intervals as $\mathrm{RR}_1,\ldots,\mathrm{RR}_N$ and their mean as $\overline{\mathrm{RR}}$.

$$\RMSSD &= \sqrt{\frac{1}{N-1}\sum_{i=1}^{N-1}\left(\mathrm{RR}_{i+1}-\mathrm{RR}_i\right)^2}\\
\SDNN &= \sqrt{\frac{1}{N}\sum_{i=1}^{N}\left(\mathrm{RR}_i-\overline{\mathrm{RR}}\right)^2}\\
\mathrm{pNN50} &= 100\% \times \frac{\text{number of }|\mathrm{RR}_{i+1}-\mathrm{RR}_i| > \SI{50}{\milli\second}}{N-1}$$

*RMSSD* (root mean square of successive differences) looks only at the change from one beat to the next, so it measures the fast, vagal part of the variation. *SDNN* (standard deviation of NN intervals) measures all variation in the window, fast and slow. *pNN50* is the percentage of successive differences larger than 50 ms. Note the divisor in SDNN: the Heart app divides by $N$, the population form; many statistics libraries divide by $N-1$. For a five-minute window the difference is a fraction of a percent; for five beats it is not.

**Example 5.3: RMSSD, SDNN and pNN50 by hand.**

Five RR intervals: 812, 790, 835, 801, 822 ms.

- Successive differences: $-22$, 45, $-34$, 21. Squares: 484, 2025, 1156, 441, which sum to 4106. Mean square $4106/4 = 1026.5$. $\RMSSD = \sqrt{1026.5} = \SI{32.0}{\milli\second}$.

- Mean $4060/5 = \SI{812}{\milli\second}$. Deviations 0, $-22$, 23, $-11$, 10; squares sum to 1234. Dividing by $N=5$ gives 246.8 and $\SDNN = \SI{15.7}{\milli\second}$; dividing by $N-1=4$ gives 308.5 and 17.6 ms.

- No difference exceeds 50 ms, so $\mathrm{pNN50} = 0\%$.

Now confirm the first line with Listing 5.3, whose `assert` line does exactly this.

**Listing 5.3.** RR intervals to HRV, tested first on the hand example (`code/hrv.py`)

```python
# RR intervals to HRV, tested on the hand example first.
import numpy as np, pandas as pd

def rmssd(rr): return np.sqrt(np.mean(np.diff(rr) ** 2))
def sdnn(rr):  return np.std(rr)                  # divides by N, as the app does
def pnn50(rr): return 100 * np.mean(np.abs(np.diff(rr)) > 50)

def clean(rr, k=11, tol=0.20):                    # artifact rule: drop beats more
    med = pd.Series(rr).rolling(k, center=True, min_periods=1).median()
    return rr[np.abs(rr - med) <= tol * med]      # than 20% from the local median

hand = np.array([812, 790, 835, 801, 822])        # the worked example in the text
assert round(rmssd(hand), 1) == 32.0 and round(sdnn(hand), 1) == 15.7

rr = pd.read_csv("rest-rr.csv")["rr_ms"].to_numpy()
nn = clean(rr)
print(f"{len(rr)} RR, {len(rr) - len(nn)} removed as artifact")
print(f"RMSSD {rmssd(nn):.1f} ms  SDNN {sdnn(nn):.1f} ms  pNN50 {pnn50(nn):.1f}%")
print(f"ln RMSSD {np.log(rmssd(nn)):.2f}")
```

```text
478 RR, 0 removed as artifact
RMSSD 22.8 ms  SDNN 51.6 ms  pNN50 3.4%
ln RMSSD 3.13
```

How do these compare with other ways of computing the same thing? Listing 5.4 runs the maintained `neurokit2` package on the same ECG, and also uses the RR intervals the strap itself reported in the file's `rr` column.

**Listing 5.4.** An independent check with a library and with the strap's own intervals (`code/nk_check.py`)

```python
# an independent check with a maintained library, and with
# the RR intervals the strap itself reported (the file's rr column).
import numpy as np, pandas as pd, neurokit2 as nk

ecg = pd.read_csv("rest.csv.gz")
t = (ecg["time"] - ecg["time"].iloc[0]).to_numpy() / 1e9
fs = 1 / np.median(np.diff(t))

clean = nk.ecg_clean(ecg["ecg"], sampling_rate=fs)
_, info = nk.ecg_peaks(clean, sampling_rate=fs)
h = nk.hrv_time(info, sampling_rate=fs)
print(len(info["ECG_R_Peaks"]), "R peaks")
print("neurokit2: RMSSD {:.1f} ms  SDNN {:.1f} ms  pNN50 {:.1f}%".format(
    *h[["HRV_RMSSD", "HRV_SDNN", "HRV_pNN50"]].iloc[0]))

strap = ecg["rr"].dropna().to_numpy()             # ms, from the strap's firmware
print("strap rr:  RMSSD {:.1f} ms  SDNN {:.1f} ms  ({} intervals)".format(
    np.sqrt(np.mean(np.diff(strap) ** 2)), np.std(strap), len(strap)))
```

```text
478 R peaks
neurokit2: RMSSD 22.6 ms  SDNN 51.6 ms  pNN50 2.1%
strap rr:  RMSSD 22.1 ms  SDNN 51.4 ms  (479 intervals)
```

*Table 5.2. One resting recording, four computations. Heart app values are for the whole recording (`subject-a/rest.csv.gz`, age 35, recording type Rest).*

| Source | RMSSD (ms) | SDNN (ms) | pNN50 (%) |
|---|---|---|---|
| Heart app | 22.5 | 51.5 | 2.7 |
| Listing 5.3 | 22.8 | 51.6 | 3.4 |
| `neurokit2` | 22.6 | 51.6 | 2.1 |
| Strap's own RR | 22.1 | 51.4 | – |

Table 5.2 collects the results. RMSSD agrees within 0.7 ms, about 3%, and SDNN within 0.2 ms. pNN50 ranges from 2.1% to 3.4%, a spread of more than half its value. The reason is that pNN50 counts differences that cross a hard line at 50 ms. In this recording only 10 to 16 of 477 differences are that large, and a one-sample shift in a single R peak (7.7 ms) can move a difference across the line. A measure built on a threshold is fragile when few values are near it.

> **Key idea.**
> 
> When two programs disagree on an HRV number, look for four causes: different beats (detection and artifact rules), different timing (sampling and peak refinement), a different window, and a different formula ($N$ or $N-1$).

### 5.5.2 Why RMSSD is the working measure

For athletes, RMSSD is the measure to use. A widely cited overview of HRV metrics calls it the primary time-domain measure used to estimate the vagally mediated changes reflected in HRV, and notes that it is more influenced by vagal activity than SDNN . It is stable over short recordings of a few minutes, and it does not need the slow swings that only long recordings capture. It is skewed, with a long tail toward high values, so day-to-day comparisons use its natural logarithm, *ln RMSSD*: 22.8 ms gives $\ln 22.8 = 3.13$.

\paragraph{A morning protocol.} HRV changes with posture, breathing, caffeine, the last meal, the time since waking and the last hard session. To see a change in you rather than in the conditions, fix the conditions: on waking, after emptying the bladder, lie or sit in the same position, breathe normally, and record two to five minutes; discard the first minute; compute ln RMSSD; keep a log of sleep, illness and training. Seven mornings give a baseline: its mean, and its day-to-day standard deviation, which is your noise (Exercise 5.18). A single morning below the baseline by less than that noise is not a finding. Several mornings in a row well below it, together with how the athlete feels, are worth a conversation about training, not a diagnosis.

### 5.5.3 Other HRV measures, to recognize

The Heart app reports more measures than these three. You should recognize them in a report, even if you do not use them for decisions.

- **Frequency-domain power.** The app resamples the NN series at 4 Hz, estimates its power spectrum by Welch's method in each valid five-minute window, and sums the power in bands: very low (0.0033 to 0.04 Hz), low (LF, 0.04 to 0.15 Hz) and high (HF, 0.15 to 0.4 Hz). HF power follows breathing and vagal activity. The LF/HF ratio is often read as a “balance” of the two branches, a reading that physiologists dispute.

- **Poincaré plot.** Plot each interval against the next one. The spread across the line of identity, SD1, measures beat-to-beat variation; Shaffer and Ginsberg call it identical to RMSSD , and as the Heart app computes it, SD1 is the standard deviation of successive differences divided by $\sqrt{2}$, which is RMSSD$/\sqrt{2}$ whenever those differences average zero; the spread along it, SD2, measures slower variation.

- **pNN20.** As pNN50 with a 20 ms line, less fragile for people with low HRV.

- \textbf{DFA $\alpha_1$.} A short-term scaling exponent from detrended fluctuation analysis, which describes how correlated successive intervals are. It falls as exercise gets harder, and a value of 0.75 has been proposed as a marker of the aerobic threshold, the first ventilatory threshold . The support is at the group level, with wide scatter between individuals, and when the course strap was compared with a clinical ECG in 25 people during a cycling ramp, the exponent's bias was 0.9% at low intensity but 8.6% at high intensity, with limits of agreement from $-40.9$ to $+58.1\%$ . Treat it as a research idea.

## 5.6 How Heart Rate Answers Exercise

Heart rate is the body's fastest-moving measure of effort, but it is not instant. Figure 5.9 shows the workout example: a warm-up jog, five hard efforts of about one to two minutes with jogging between, and a cool-down.

*Figure 5.9. The workout example (`subject-b/workout.csv.gz`) as five-second means of the strap's beat-to-beat heart rate. The numbers mark the five efforts.*

### 5.6.1 Rest, onset, steady state, drift and recovery

- **Resting heart rate** is lowest on waking, lying still. It falls with endurance training and rises with poor sleep, illness, heat and dehydration. The Heart app estimates it from a rest or sleep recording as the median of the lowest quarter of stable five-minute windows.

- **Onset.** When work starts, heart rate rises within seconds, first as the vagal brake is released, then more slowly as sympathetic drive builds. In effort 3 of the workout, heart rate rose from 142 toward 182 with a time constant of about 28 seconds.

- **Steady state.** In moderate steady work, heart rate levels off within a few minutes. In hard work above the threshold it keeps climbing.

- **Drift.** Over long steady efforts, heart rate creeps upward at the same pace, as the body heats and loses fluid and the heart pumps a little less blood per beat. The Heart app reports drift as the change from the first to the last third of a session of 30 minutes or more, and only when the session has no interval structure.

- **Recovery.** When work stops, heart rate falls quickly for the first minute, then slowly. The drop in the first 60 seconds is a common field measure.

### 5.6.2 A first-order model

Engineers describe a response like this with a *first-order model*. If work steps up at time zero, heart rate moves from its starting value $\HR_0$ toward a new level $\HR_\infty$ as

$$\HR(t) = \HR_\infty + \left(\HR_0 - \HR_\infty\right)\ee^{-t/\tau}.$$

The *time constant* $\tau$ is the time to cover 63% of the change; after $2\tau$ it has covered 86%, after $3\tau$ 95%. The *gain* is the change in heart rate per unit of work, $(\HR_\infty-\HR_0)/\Delta\text{work}$. In words, for everyone: heart rate heads for the level the work demands, fast at first and then more slowly, and $\tau$ says how quickly.

> **Engineer's note: Where the 63% comes from.**
> 
> Equation \eqref{ch05-heart:eq:first} solves $\tau\,\dd{\HR}{t} = \HR_\infty - \HR$: the rate of change is proportional to the distance still to go. At $t=\tau$ the remaining distance is $\ee^{-1} = 0.368$ of the start, so $1 - 0.368 = 0.632$ is covered. Taking the logarithm of the remaining distance gives a straight line in $t$ with slope $-1/\tau$, a quick fit when you know the level it falls toward. The Heart app fits the curve itself, level included, to one-second heart rates over up to five minutes after the end of work, and reports no $\tau$ when the fit is poor or the time constant is longer than two-thirds of the recorded tail.

Listing 5.5 fits Equation \eqref{ch05-heart:eq:first} with `scipy.optimize.curve_fit` to the rise and the fall of effort 3, using the strap's own RR intervals (a small helper, `beats.py` in the chapter's code folder, reads them and keeps intervals from 300 to 2000 ms). Figure 5.10 shows the fits.

**Listing 5.5.** Gain and time constant of the heart-rate response (`code/first_order.py`)

```python
# gain and time constant of the heart-rate response.
import numpy as np
from scipy.optimize import curve_fit
from beats import strap_beats

b = strap_beats("workout.csv.gz")
hr = b.groupby(np.floor(b.t)).hr.mean()           # one value per second

def step(t, hr0, hr_end, tau):                    # first-order response
    return hr_end + (hr0 - hr_end) * np.exp(-t / tau)

for name, t0, t1 in [("rise", 1010, 1070), ("fall", 1065, 1180)]:
    seg = hr.loc[t0:t1]
    p, cov = curve_fit(step, seg.index - t0, seg, p0=[seg.iloc[0], seg.iloc[-1], 30])
    sd = np.sqrt(np.diag(cov))
    print(f"{name}: {p[0]:.0f} -> {p[1]:.0f} beats/min, "
          f"tau = {p[2]:.0f} +/- {sd[2]:.0f} s")
```

```text
rise: 142 -> 182 beats/min, tau = 28 +/- 1 s
fall: 182 -> 129 beats/min, tau = 79 +/- 12 s
```

*Figure 5.10. Effort 3 of the workout example with the two fits of Listing 5.5. The rise is well described; the fall is noisier because the runner kept jogging, so heart rate settled near 130, not at rest.*

The rise is fast and the fit is tight. The fall is slower, and its time constant has a large uncertainty ($\pm\SI{12}{\second}$) because recovery was a jog, not a stop. The Heart app reports no recovery time constant for this session: after effort 5 the trace levels off for two minutes, and no single exponential fits it. An earlier version fitted one anyway, from the session's peak, and printed 106 s. The fit you can defend is shorter than the one you can compute. A time constant only has meaning together with the window it was fitted on, the method, and what the athlete was doing.

**Example 5.4: Recovery in one minute.**

Heart rate 176 bpm when work stops; sixty seconds later, 141 bpm. The one-minute recovery is $176 - 141 = 35$ beats. The Heart app measures from the *end of work*, the start of the sustained fall after the last hard effort, which it locates by fitting a level-then-fall curve; heart rate there is the mean of the last five seconds, and each later value is the mean of ten seconds centered on 30, 60 and 120 seconds. For the workout example work ends at 1686 s at 177 bpm (the effort's top was 181), and the drops are 13.1, 30.1 and 37.3 beats. An earlier version measured from the session's peak, which on a plateau can come well before the stop; checking it against a synthetic recording with a known recovery exposed the difference (it read a 45-beat drop as 17). Compare a recovery only with your own earlier recoveries after the same kind of effort.

### 5.6.3 Maximal heart rate

Zones and load scores need a *maximal heart rate*. The familiar estimate $220 - \text{age}$ has no single source study, and age-only equations miss individuals by 7 to 11 beats a minute as one standard error of the estimate, so misses of 20 beats occur . A laboratory study of 514 people likewise found standard deviations of 7 to 11 beats a minute around its age equation . For a 20-year-old the formula says 200; the true value could well be 180 or 220. A measured maximum is better: the highest value seen in a hard, well-recorded race or test, from a strap, not a wrist sensor. The Heart app has an optional field for it, *Measured max HR*; when it is empty the app falls back to $220 - \text{age}$. No one in this course is asked to do a maximal test.

## 5.7 Zones and Load

Coaches divide heart rate into *zones* so that a session can be prescribed and checked. There are three common ways to set them.

- **Percent of maximum.** The Heart app uses five zones: below 60%, 60–70%, 70–80%, 80–90% and above 90% of maximum.

- **Heart-rate reserve.** The *heart-rate reserve* is maximum minus resting rate. A target at a fraction $f$ of reserve is $\HR_\text{rest} + f\,(\HR_\text{max} - \HR_\text{rest})$. Because it uses the resting rate, it adapts to a fitter athlete whose resting rate is low.

- **Threshold-anchored zones.** Two heart rates from a test, at the first and second thresholds (where breathing or blood lactate change behavior; Chapter 2), split effort into three zones: easy below the first, moderate between, hard above the second. This model is tied to the athlete's own physiology, not to a formula.

**Example 5.5: A target from the heart-rate reserve.**

Resting 50 bpm, maximum 190 bpm, so the reserve is 140. A session at 70% of reserve targets $50 + 0.70\times140 = \SI{148}{\bpm}$. The same 70% of maximum would be 133 bpm.

### 5.7.1 Training impulse

A load score turns a session into one number that combines how long and how hard. The *training impulse* (TRIMP) in Banister's exponential form weights each minute by the fraction of reserve $f$ and by a factor that grows exponentially with it:

$$\mathrm{TRIMP} = \sum \Delta t\ (\text{min}) \times f \times 0.64\,\ee^{1.92 f},\qquad f = \frac{\HR - \HR_\text{rest}}{\HR_\text{max}-\HR_\text{rest}}.$$

The exponential term stands for the steep rise of blood lactate with intensity; the constants 0.64 and 1.92 are the ones commonly used for men (other constants are used for women). A simpler *zone-sum load* multiplies the minutes in each of five zones by the zone number (1 to 5) and adds them.

> **Check it by hand: Training impulse for one steady session.**
> 
> Thirty minutes at 150 bpm, resting 50, maximum 190.

> $f = (150-50)/140 = 0.714$. $\ee^{1.92\times0.714} = \ee^{1.371} = 3.94$.

> $\mathrm{TRIMP} = 30\times0.714\times0.64\times3.94 = 54$.

> Now try it in the Heart app: it computes Equation \eqref{ch05-heart:eq:trimp} beat by beat, so each beat contributes its own interval in minutes.

The Heart app's choices matter. It takes *maximum* from the Measured max HR field (100 to 230 beats a minute) when you fill it in, and otherwise as $220 - \text{age}$, with age 30 if none is given; enter a measured maximum whenever you have one you trust. It takes *rest* as the session's own 5th-percentile heart rate, capped at 80 bpm, because a workout file holds no true resting rate. For the workout example the 5th percentile is 101, so rest is set to 80; with age 30 and the field left empty the maximum is 190, and the app reports a TRIMP of 40.9 and a zone-sum load of 99. Listing 5.6 reproduces both scores from the strap's own RR intervals and adds the other two zone models, with a resting rate of 50 and thresholds of 150 and 170 assumed for the illustration.

**Listing 5.6.** Zones three ways and two load scores (`code/zones_trimp.py`)

```python
# zones three ways and two load scores for the workout example.
import numpy as np
from beats import strap_beats

b = strap_beats("workout.csv.gz")
mins = b.rr / 60000                               # each beat's share of a minute
HRMAX, HRREST = 190, 50                           # stated, not measured here

pct = b.hr / HRMAX                                # model 1: percent of maximum
z1 = np.digitize(pct, [0.6, 0.7, 0.8, 0.9]) + 1
hrr = (b.hr - HRREST) / (HRMAX - HRREST)          # model 2: heart-rate reserve
z2 = np.digitize(hrr, [0.5, 0.6, 0.7, 0.8]) + 1
z3 = np.digitize(b.hr, [150, 170]) + 1            # model 3: two thresholds
for name, z, n in [("% max", z1, 5), ("reserve", z2, 5), ("threshold", z3, 3)]:
    print(f"{name:9s}", " ".join(f"{mins[z == k].sum():5.1f}" for k in range(1, n + 1)))

zone_sum = sum(k * mins[z1 == k].sum() for k in range(1, 6))
rest = min(80, np.percentile(b.hr, 5))            # the app's session rest
f = np.clip((b.hr - rest) / (HRMAX - rest), 0, 1)
trimp = np.sum(mins * f * 0.64 * np.exp(1.92 * f))
print(f"zone-sum {zone_sum:.0f}, TRIMP {trimp:.1f} (rest {rest:.0f})")
```

```text
% max       4.1   4.2  16.8   6.4   3.0
reserve     4.3   5.0  14.4   5.0   5.9
threshold  24.3   6.8   3.4
zone-sum 104, TRIMP 42.3 (rest 80)
```

The listing's scores are 3% to 5% higher than the app's because it keeps every strap interval, while the app drops beats from poor-quality segments (it kept 98.5% of beats). The zone tables disagree by much more. The same 34 minutes contain 9.4 “hard” minutes (zones 4 and 5) by percent of maximum, 10.9 by reserve, and only 3.4 above the second threshold. The zone model is a choice, and the athlete's prescription should name it.

> **Limits and cautions: What a load score can and cannot say.**
> 
> A load score compares sessions for one athlete measured the same way. It cannot compare two athletes, it does not see strength work or running technique, it depends on the rest and maximum it was given, and heart rate itself drifts with heat and fatigue. Rules that turn load ratios into injury predictions have serious limits (Chapter 6). Use a load score to describe training, not to forecast injury.

### 5.7.2 Monitoring recovery

A load score says what the athlete did. Recovery measures ask how the athlete is absorbing it. Five are in common use, and Table 5.3 sets them side by side with what each can and cannot show. Two findings shape how to use them. First, no single heart measure covers everything: a review of heart-rate monitoring concludes that heart rate cannot tell you about every part of wellness, fatigue and performance, and recommends combining it with training logs and questionnaires . Second, a systematic review of 56 studies found that athletes' own ratings of how they feel responded to changes in training load more consistently than the objective measures did, and that the two kinds generally did not agree . The cheapest measure, asking, is not the weakest.

*Table 5.3. Five recovery measures. Read each one against the athlete's own baseline, never against another person.*

| Measure | How | Can show | Cannot show |
|---|---|---|---|
| Resting heart rate | One minute on waking, same posture each day | A slow trend over weeks; a run of high mornings worth asking about | What caused one high morning: heat, coffee, a poor night and an infection look the same |
| ln RMSSD (Section 5.5) | Two to five minutes on waking, the morning protocol | A shift from your seven-morning baseline, read as an average of several mornings | Good or bad by direction alone: it can rise with fatigue after hard training in the heat |
| Sleep | Hours and a 1–5 quality rating in a log, or a tracker | Short sleep; elite athletes often sleep under 7 hours | Wake time and sleep stages from a consumer tracker, which tends to score wake as sleep |
| Session RPE | Rate the whole session 0–10 after it, times its minutes | Internal load for any session, strength work included | A fixed scale: heat, altitude, caffeine and music all move the rating |
| Wellness score | Four or five items (fatigue, soreness, sleep, stress, mood) rated 1–5 each morning | Change with training load, more consistently than objective measures | Validity until you have checked it: the review's recommended questionnaires are longer, tested ones |

\paragraph{Average before you react.} Every row of the table is noisy from day to day. In short field recordings the day-to-day coefficient of variation of RMSSD is about 12%, and the noise of an average of $n$ mornings falls as $1/\sqrt n$ : four mornings halve it to 6%, seven take it to 4.5%. The same review found that an average of at least three or four days, not a single morning, was what tracked running performance, and a review of elite endurance athletes argues for long-term monitoring with suitable averaging to learn each athlete's own pattern . In practice: keep a rolling average, compare it with the baseline band, and look for agreement. A low HRV average, a high resting-rate average, short sleep and a falling wellness score together say more than any one of them.

\paragraph{Session RPE in one line.} Ask “How was your workout?” after the session, on the 0–10 scale, and multiply by its minutes: a rating of 6 for a 50-minute run is 300 arbitrary units. A review of 36 studies found the method valid and reliable across sports, ages and levels , which makes it the one load score that covers the sessions a strap does not see (Section 5.7).

These numbers are personal health information. In this course they are never graded or shared, and they are training information, not a medical test. A run of poor values together with feeling unwell is a reason to rest and, if it persists, to see a clinician; it is not something to diagnose from a table. Chapter 2 uses these measures when it plans training around recovery.

## 5.8 How Good Is the Number?

### 5.8.1 Agreement between two devices

To judge a device you need a better one worn at the same time (a *reference*), the same moments from both, and statistics that describe the differences. Write $d_i = \text{device}_i - \text{reference}_i$ for $n$ paired readings.

- *Bias*: the mean of $d_i$. Does the device read high or low on average?

- *Mean absolute error* (MAE): the mean of $|d_i|$. How far off is a typical reading, in beats a minute?

- *Mean absolute percentage error* (MAPE): the mean of $|d_i|/\text{reference}_i$, as a percentage.

- *Limits of agreement*: bias $\pm 1.96$ standard deviations of $d_i$. About 95% of single readings should differ from the reference by an amount inside them. A plot of $d_i$ against the mean of each pair, with these lines drawn, is a *Bland–Altman plot*.

A correlation coefficient is not on the list. Two devices can correlate at 0.99 and still disagree by ten beats on every reading.

**Example 5.6: Five paired readings.**

In an interval session, a strap (reference) reads 152, 168, 175, 160, 145 and a wrist sensor reads 150, 158, 171, 163, 140 at the same five moments.

- Differences: $-2$, $-10$, $-4$, $+3$, $-5$. Bias $= -18/5 = \SI{-3.6}{\bpm}$.

- MAE $= (2+10+4+3+5)/5 = \SI{4.8}{\bpm}$.

- Percentage errors 1.32, 5.95, 2.29, 1.88, 3.45%; MAPE $= 3.0\%$.

- Standard deviation of the differences (dividing by $n-1$) 4.72 bpm; limits of agreement $-3.6 \pm 1.96\times4.72$, from $-12.9$ to $+5.7$ bpm.

The wrist sensor reads low on average, by a few beats, but a single reading could be 13 beats low. Five pairs are too few for limits you would rely on; they show the arithmetic.

**Listing 5.7.** Agreement statistics, tested on Example 5.6 and run on a real file (`code/agreement.py`)

```python
# agreement between a device and a reference.
import numpy as np, pandas as pd

def agreement(ref, dev):
    d = np.asarray(dev, float) - np.asarray(ref, float)
    bias, sd = d.mean(), d.std(ddof=1)
    return dict(bias=bias, mae=np.abs(d).mean(),
                mape=100 * np.mean(np.abs(d) / np.asarray(ref, float)),
                lo=bias - 1.96 * sd, hi=bias + 1.96 * sd)

strap = [152, 168, 175, 160, 145]                 # the worked example in the text, beats/min
wrist = [150, 158, 171, 163, 140]
print({k: round(float(v), 1) for k, v in agreement(strap, wrist).items()})

# Real file: the strap's displayed rate (hr column) against the rate from
# its own beat-to-beat intervals, both averaged over the same 5 s windows.
ecg = pd.read_csv("workout.csv.gz")
ecg["w"] = ((ecg.time - ecg.time.iloc[0]) // 5e9).astype(int)
ok = ecg.rr.between(300, 2000)
beat = (60000 / ecg.rr[ok]).groupby(ecg.w[ok]).mean()
shown = ecg.hr.groupby(ecg.w).mean()
pair = pd.concat([beat, shown], axis=1, keys=["ref", "dev"]).dropna()
print(len(pair), {k: round(float(v), 2) for k, v in agreement(pair.ref, pair.dev).items()})
```

```text
{'bias': -3.6, 'mae': 4.8, 'mape': 3.0, 'lo': -12.9, 'hi': 5.7}
416 {'bias': 0.23, 'mae': 1.08, 'mape': 0.88, 'lo': -5.56, 'hi': 6.02}
```

The second line of output compares two outputs of one strap: the heart rate it displays (the file's `hr` column, about once a second) and the rate computed from its own beat-to-beat intervals, both averaged over the same five-second windows. Even these differ, by 1.1 bpm on average and by up to about 6 beats in single windows (Figure 5.11), because the displayed rate is smoothed over several beats. When you compare a wrist device with a strap, align the clocks first; a lag of a few seconds during an interval looks like a large error.

*Figure 5.11. Bland–Altman plot of the strap's displayed heart rate against the rate from its own RR intervals, 416 five-second windows of the workout example. Solid line: bias 0.23 bpm. Dashed lines: limits of agreement, $-5.6$ to $+6.0$ bpm.*

### 5.8.2 What the studies show

Table 5.4 collects the published evidence by sensor site and activity. Read each row with its study: who was measured, against what, doing what.

*Table 5.4. Accuracy of heart-rate sensors by site and activity, from the studies cited.*

| Sensor and activity | Finding | Study |
|---|---|---|
| Chest strap, many exercise modes | Concordance with laboratory ECG 0.996 | 50 adults |
| Wrist and forearm optical, same study | Concordance 0.67 to 0.92 for wrist devices, 0.75 for a forearm band; every device below 0.80 on an elliptical with arm movement | 50 adults |
| Course strap, rest to high intensity | 99.6% of RR intervals correctly detected (Holter 94.6%); 99.4% in high-intensity work (Holter 89.8%) | 10 people |
| Wrist optical, by activity (meta-analysis) | Mean difference near zero at rest and on a treadmill; $-4.6$ bpm in cycling; $-7.3$ bpm in resistance training, where the underestimate grows by about 3 beats for each 10-beat rise in heart rate | 44 studies |
| Wrist optical, by activity | MAPE 3.8% walking, 6.9% cycling, 8.5% running, 13.4% rowing | 10 healthy volunteers, strap reference |
| Upper arm against wrist | MAE 1.43 bpm (arm band) against 6.41 bpm (wrist), one maker | 16 people |
| Consumer devices overall | Heart rate acceptable in the laboratory; energy expenditure not accurate for any maker | Review of 158 studies |
| Skin tone | Not a significant factor; activity type and device were | 53 people |
| Skin tone, review | Four of ten studies found worse accuracy on darker skin, four found none, two mixed: inconclusive | 469 people |
| Tattooed skin | 22.9% error at rest over tattoos |  |
| Ring, at night | Bias about -0.6 bpm for heart rate and -1.2 ms for RMSSD against ECG | 49 adults |

The pattern is consistent. A strap is close to a clinical ECG across activities. Optical sensors are good at rest and in steady running, worse in cycling, worse again in rowing and strength work where the hands grip and the wrist flexes, and better on the upper arm than the wrist. Skin tone is not settled; tattoos clearly hurt. The same study, in 30 cardiac rehabilitation patients, found the wrist readings accurate (within 10% of the strap) 57% of the time in arm-intensive exercise, against 78% of the time in exercise without much arm movement .

### 5.8.3 Running your own small validation

You can check any device against the strap in an hour (Exercise 5.11). Choose the activity you care about, because error depends on it. Record both devices for the whole session and note the clock time of a few clear events, such as the start of each effort. Export both files. Resample both to one value a second and find the clock offset by shifting one series against the other until they line up best (the shift with the highest correlation). Then compute bias, MAE, MAPE and limits of agreement, separately for rest, steady work and intervals, and look at the worst minute. Report the number of people (one), the activity and the reference, so that no one mistakes your result for a general one.

## 5.9 Recording with the Heart App

The Heart app runs entirely in your browser; analysis happens in a background worker and nothing is uploaded. It accepts one or more CSV files, or a ZIP of them, with a time column in nanoseconds and an ECG column in millivolts or microvolts (header `time,ecg,hr,rr,marker`, with `rr` in milliseconds), and measures the sample rate from the timestamps. There are two ways to make that file.

- **Live Capture**, in the page itself. In a browser that supports Web Bluetooth, the app connects to the strap, streams its raw ECG, its accelerometer and its heart rate with RR intervals, keeps the samples in the browser's own storage about every five seconds, and exports a finished recording as the same CSV, which goes straight into the analysis. A live capture also feeds motion panels (cadence, vertical oscillation, tilt, a breathing estimate from chest motion) that the CSV path does not.

- **A phone logging app** that records the strap's ECG to CSV. This is the way for iPhone users and anyone without a compatible browser; the course kit page names the logger.

> **Status: 2026.**
> 
> {Browser Bluetooth and Live Capture}
> Web Bluetooth works in Chrome, Edge, Opera and Samsung Internet on computers and in Chrome on Android. It does not work in Firefox or Safari, and iPhone and iPad browsers do not offer it. A page can use it only over a secure (HTTPS) connection and only after a tap or click . The Heart app's Live Capture was tested against simulated straps when this chapter was written; its checklist for a real strap had not yet been completed. If Live Capture cannot find or hold your strap, record with the phone logger and upload the file.

> **Try it in the app: Open the resting example.**
> 
> Load `subject-a/rest.csv.gz` from the app's examples, set the age and choose recording type Rest. Check that RMSSD is 22.5 ms and that every ten-second segment is graded usable. Then open the ECG Explorer and find the R peaks of Figure 5.2.
> 
> 
> https://apopt.com/heart

*Figure 5.12. The Heart app's ECG Explorer on the resting example. The tall, regular R peaks are what every number in this chapter is built on; the explorer lets you read their times off the screen.*

The app reports far more than this chapter uses: a quality score, resting heart rate, the HRV measures of Section 5.5, zones, TRIMP and recovery for workouts, an interval test of three or more one-minute repeats, a sleep-stage proxy that it labels as a heuristic, and an ECG-derived breathing estimate that it labels as experimental. Its outputs are a PDF report, a Markdown summary written for an AI assistant (with no raw ECG in it), and a breathing CSV. For each output, ask the question of Section 5.1: measured, derived or modeled?

### 5.9.1 Your own live page

The build step this week (B-5) is a page of your own that reads RR intervals, computes HRV, and then connects to a heart-rate sensor over Bluetooth. Your page uses only the standard *heart-rate service* (Bluetooth number `0x180D`), which every strap and many watches offer. Its *Heart Rate Measurement* characteristic (`0x2A37`) sends a short message with each update :

- byte 0 is a set of flags: bit 0 says whether heart rate is one byte or two; bit 1 whether skin contact is detected; bit 2 whether contact detection is supported; bit 3 whether an energy-expended field is present; bit 4 whether RR intervals follow;

- then the heart rate, as one byte or as two bytes with the low byte first;

- then, if bit 3 is set, two bytes of energy expended;

- then, if bit 4 is set, one or more RR intervals, each two bytes, low byte first, oldest first, in units of **1/1024 of a second**.

**Example 5.7: The 2.4% trap.**

A message carries an RR value of 819. In milliseconds that is $819\times1000/1024 = \SI{799.8}{\milli\second}$. A program that reads 819 as milliseconds overstates the interval by $819/799.8 = 1.024$, that is by 2.4%, and so reports a heart rate of $60\,000/819 = 73.3$ instead of $60\,000/799.8 = 75.0$, which is 2.3% low. Nothing looks wrong on screen. Only a test with a known answer catches it.

**Listing 5.8.** Decode one Heart Rate Measurement message (`code/hrm-decode.js`)

```javascript
// decode one Heart Rate Measurement message (characteristic
// 0x2A37 of the standard heart-rate service 0x180D).
export function decodeHrm(bytes) {               // bytes: a Uint8Array
  const flags = bytes[0];
  let i = 1;
  const hr = flags & 0x01 ? bytes[i] | (bytes[i + 1] << 8) : bytes[i];
  i += flags & 0x01 ? 2 : 1;                     // bit 0: 16-bit rate
  if (flags & 0x08) i += 2;                      // bit 3: energy field, skip
  const rr = [];
  if (flags & 0x10) {                            // bit 4: RR intervals follow
    for (; i + 1 < bytes.length; i += 2) {
      const ticks = bytes[i] | (bytes[i + 1] << 8);  // units of 1/1024 s
      rr.push((ticks * 1000) / 1024);                // milliseconds
    }
  }
  return { hr, rr };
}
```

Test the decoder before you trust it. Listing 5.9 feeds it three messages built by hand. The first has flags `0x10` (8-bit rate, RR present), a rate of `0x4B` = 75 and one RR value of `0x0333` = 819, whose answer you know from Example 5.7.

**Listing 5.9.** A test with known answers (run with `node hrm-decode.test.js`) (`code/hrm-decode.test.js`)

```javascript
// Test with a known answer: node hrm-decode.test.js
import { decodeHrm } from "./hrm-decode.js";
const a = decodeHrm(new Uint8Array([0x10, 0x4b, 0x33, 0x03]));
console.log(a.hr, a.rr.map((x) => x.toFixed(1)));   // 75 [ '799.8' ]
const b = decodeHrm(new Uint8Array([0x17, 0xaf, 0x00, 0x5f, 0x01, 0x57, 0x01]));
console.log(b.hr, b.rr.map((x) => x.toFixed(1)));   // 175 [ '342.8', '335.0' ]
const c = decodeHrm(new Uint8Array([0x18, 0x8c, 0x10, 0x00, 0x00, 0x02]));
console.log(c.hr, c.rr.map((x) => x.toFixed(1)));   // 140 [ '500.0' ]
```

```text
75 [ '799.8' ]
175 [ '342.8', '335.0' ]
140 [ '500.0' ]
```

In the page, the connection starts from a button, because the browser opens its Bluetooth chooser only after a tap (Listing 5.10). Each notification's bytes go to `decodeHrm`.

**Listing 5.10.** Connect to the heart-rate service from a button (`code/connect.js`)

```javascript
// Connect to a heart-rate sensor from a button (Chromium browsers, HTTPS).
import { decodeHrm } from "./hrm-decode.js";

export function wireConnectButton(button, show) {
  button.addEventListener("click", async () => {   // a tap is required
    const device = await navigator.bluetooth.requestDevice({
      filters: [{ services: ["heart_rate"] }],      // service 0x180D
    });
    const server = await device.gatt.connect();
    const service = await server.getPrimaryService("heart_rate");
    const hrm = await service.getCharacteristic(0x2a37);
    hrm.addEventListener("characteristicvaluechanged", (event) =>
      show(decodeHrm(new Uint8Array(event.target.value.buffer))));
    await hrm.startNotifications();
  });
}
```

The Heart app's Live Capture is a working reference for your page: run both on the same strap in the same minute and compare the RR intervals. Some straps accept two Bluetooth connections at once and some do not; if yours refuses the second, alternate the two pages and report that as a finding. The strap's raw ECG uses a vendor-specific service rather than the standard one, described in the vendor's public documentation . Reading it is an optional extension for strong programmers.

## 5.10 Telling the Athlete

A finding is finished when an athlete could act on it. Here are two reports of the same morning HRV data, for a runner who has recorded seven mornings and then an eighth after a hard weekend.

> **Coach's translation: A poor report.**
> 
> “Your HRV crashed to 50 today, that's way below normal. Your nervous system is stressed and you're at risk of overtraining. Take the week off.”

> **Coach's translation: A better report.**
> 
> “This morning your RMSSD was 50 ms. Over the last seven mornings it averaged about 62, and it normally moves by roughly 9% from day to day, so today is lower than your usual range, by more than your normal day-to-day change. One low morning after a hard weekend is common and often gone in a day or two. I'd keep today easy, as planned, and record again tomorrow; if it is still low on the third morning, let's talk about the week. This is training information from a chest strap, not a medical test.”

The poor report uses a number without its baseline or its noise, states a cause it cannot know (“stressed”), predicts a risk no HRV study supports for one person, and gives an instruction out of proportion to the evidence. The better one gives the number, the athlete's own baseline, the size of normal variation, a plain reading, one modest recommendation, a retest date and the scope. Five sentences carry all of it.

## Summary

- A chest strap times the electrical R wave and stays accurate in hard exercise; an optical sensor reads the pulse wave through moving skin and is best at rest, worse in cycling, rowing and strength work, and better on the upper arm than the wrist.

- Heart rate is $60\,000/\mathrm{RR}$ in milliseconds. At 130 samples a second each R peak is known to within 7.7 ms.

- R peaks are found by filtering, differentiating, squaring, averaging, thresholding with a refractory period, and refining to the peak. Artifacts and ectopic beats are removed before HRV.

- RMSSD is the working short-term HRV measure; use ln RMSSD for day-to-day comparison against your own baseline and its noise. pNN50 is fragile; SDNN depends on the window and on $N$ or $N-1$.

- Heart rate follows work as a first-order response with a time constant of tens of seconds at onset; recovery is slower and depends on what the athlete does.

- Age formulas for maximal heart rate miss individuals by about ten beats as one standard error. Zones and load scores inherit that error and the choice of model.

- Compare devices with bias, MAE, MAPE and limits of agreement, by activity, after aligning clocks; never with correlation alone.

- The standard heart-rate message carries RR in units of 1/1024 s; reading them as milliseconds is a silent 2.4% error.

*Table 5.5. Formulas of Chapter 5.*

| Heart rate | $\HR = 60\,000/\mathrm{RR}$ (ms) |
|---|---|
| RR from a message | $\mathrm{RR}\ (\text{ms}) = \text{raw}\times1000/1024$ |
| RMSSD | $\sqrt{\text{mean of }(\mathrm{RR}_{i+1}-\mathrm{RR}_i)^2}$ |
| SDNN | standard deviation of RR (the app divides by $N$ ) |
| pNN50 | % of successive differences $> \SI{50}{\milli\second}$ |
| First-order response | $\HR_\infty + (\HR_0-\HR_\infty)\,\ee^{-t/\tau}$ |
| Reserve target | $\HR_\text{rest} + f\,(\HR_\text{max}-\HR_\text{rest})$ |
| TRIMP | $\sum \Delta t\,f\,0.64\,\ee^{1.92f}$ |
| Agreement | bias $=\bar d$ ; MAE $=\overline{\|d\|}$ ; limits $\bar d \pm 1.96\,s_d$ |

**New terms:** artifact, bias, Bland–Altman plot, derived, ectopic beat, electrocardiogram, first-order model, gain, heart-rate reserve, heart-rate service, heart rate variability, limits of agreement, ln RMSSD, maximal heart rate, mean absolute error, mean absolute percentage error, measured, modeled, P wave, parasympathetic, photoplethysmography, pNN50, QRS complex, reference, respiratory sinus arrhythmia, RMSSD, RR interval, SDNN, sinoatrial node, sympathetic, T wave, time constant, training impulse, zone-sum load, zones.

**Going further:** https://apmonitor.com/dde/index.php/Main/VideoData for data handling in Python, and https://apmonitor.com/pds/index.php/Main/CleanseData for removing bad values from a time series.

**Track it:** waking heart rate and ln RMSSD (test `resting-hr`) against baseline (Appendix J).

## Exercises

> **Course use: Week 5.**
> 
> **H10** (due Class 10, *Measure*): 5.1, 5.2, 5.5, 5.8, 5.18; about 60 minutes.
> 
> **H11** (due Class 11, *Model and tell*): 5.10, 5.20, 5.21, 5.22, 5.23, 11.22; about 220 minutes. Exercises from another chapter carry this week's syllabus topic. A case-file exercise may be done on your own data instead. The full map is in the Course Guide.

Every exercise that shows you a rhythm carries the same note: an irregular rhythm is a reason to talk to a clinician, not something to interpret in class. Your own heart numbers are never graded or shared; where an answer depends on your data, you are graded on the method.

**Exercise 5.1** (Concept check · Foundation · 2 min · CORE)

A runner's wrist sensor shows exactly 170 for four minutes of a hilly run while the runner's step rate is 170 a minute. A chest strap worn at the same time shows 150 rising to 158. What is the most likely explanation?

(a) The strap's electrodes are dry.
(b) The optical sensor has locked onto the step rhythm.
(c) The runner's heart rate really is 170 and the strap is smoothing it.
(d) Hills raise the pulse at the wrist more than at the chest.

**Exercise 5.2** (Concept check · Foundation · 2 min · CORE)

Why is RMSSD, rather than SDNN, the usual short-term HRV measure for athletes?

(a) It does not need clean beats, so artifacts do not affect it.
(b) It is measured directly by the strap.
(c) It depends on beat-to-beat changes, which mostly reflect vagal activity, and it is stable over short recordings.
(d) It is always larger than SDNN, so changes are easier to see.

**Exercise 5.3** (Concept check · Core · 2 min)

A validation study reports limits of agreement of $-12.9$ to $+5.7$ bpm for a wrist sensor against a strap. What does that mean?

(a) The sensor's average error is between $-12.9$ and $+5.7$.
(b) The sensor correlates with the strap at 95%.
(c) The sensor is accurate to within 5.7 bpm.
(d) About 95% of single readings differ from the strap by an amount between $-12.9$ and $+5.7$ bpm.

**Exercise 5.4** (Concept check · Core · 2 min)

For the five intervals 812, 790, 835, 801, 822 ms, the Heart app's formula gives SDNN 15.7 ms and a Python library gives 17.6 ms. The most likely reason is:

(a) The app divides by $N$ and the library by $N-1$.
(b) The library removed an ectopic beat.
(c) The app works on 10-second segments.
(d) The library uses RR in units of 1/1024 s.

**Exercise 5.5** (Hand calculation · Foundation · 8 min · CORE)

- An RR interval is 0.750 s. What is the heart rate? *Checkpoint:* {80 bpm.}

- An RR interval is 1.250 s. What is the heart rate? *Checkpoint:* {48 bpm.}

- A heart-rate message carries a raw RR value of 700. Convert it to milliseconds, give the correct heart rate, and the heart rate a program would show if it read 700 as milliseconds. By what percentage is that rate low? *Checkpoint:* {683.6 ms; 87.8 bpm; 85.7 bpm; 2.3% low.}

- At 130 samples a second, what share of the interval is a one-sample error at 150 bpm? At 60 bpm? *Checkpoint:* {1.9%; 0.77%.}

Confirm (c) with the decoder of Listing 5.8: the message `[0x10, 0x46, 0xBC, 0x02]` carries a rate of 70 and a raw RR of `0x02BC`.

**Exercise 5.6** (Hand calculation · Core · 10 min)

Six RR intervals from a seated recording: 1010, 985, 1040, 1002, 950, 1013 ms. This is H-3 of the course's strap exercises, first on paper.

- Compute the successive differences and RMSSD. *Checkpoint:* {$-25, 55, -38, -52, 63$; 48.5 ms.}

- Compute the mean, the mean heart rate, and SDNN dividing by $N$ and by $N-1$. *Checkpoint:* {1000 ms; 60 bpm; 27.7 ms; 30.3 ms.}

- Compute pNN50. *Checkpoint:* {60%.}

- Check all three with Listing 5.3 by replacing the `hand` array. Then take 20 consecutive intervals from your own recording, compute RMSSD in Python, and compare with the Heart app's value for the five-minute window that contains them. Name the likely causes of any difference.

**Exercise 5.7** (Hand calculation · Extension · 12 min)

An athlete has a resting heart rate of 55 and a measured maximum of 185.

- What heart rate is 65% of reserve? What is 65% of maximum? *Checkpoint:* {139.5 (about 140); 120.}

- Compute the exponential TRIMP of 40 minutes at a steady 140 bpm. *Checkpoint:* {$f = 0.654$; $\ee^{1.92f} = 3.51$; TRIMP 58.7.}

- Heart rate is 182 at the end of the last interval and 150 sixty seconds later. What is the one-minute recovery? *Checkpoint:* {32 beats.}

- If heart rate fell from 182 toward 120 as a first-order response with $\tau = \SI{60}{\second}$, what would it read after 60 seconds? *Checkpoint:* {142.8 bpm.}

**Exercise 5.8** (App lab · Foundation · 40 min · CORE)

**Your first recording** (strap exercises H-1, H-2 and H-10). App: Heart, https://apopt.com/heart. Recording: one continuous ECG file, three minutes with dry electrodes then five minutes with wet electrodes, seated.

- Put the strap on below the chest muscles with the electrodes *dry*. Start a recording with the Heart app's Live Capture if your computer's browser supports Bluetooth (Section 5.9); otherwise use the phone logger. Live Capture had not yet been tested on a real strap when this book was written; if it cannot find or hold the strap, switch to the logger and note it.

- After three minutes, wet the electrodes without stopping the recording. Sit still for five minutes. During minute 6 count your pulse at the wrist for 60 seconds.

- Analyze the file with recording type Rest and your age. Save the PDF and the Markdown summary.

- Compare your 60-second count with the app's heart rate for that minute.

- Open the ECG Explorer on a clean ten-second window. Read off the times of the R peaks, compute the RR intervals and the mean heart rate by hand, and compare with the app.

- Find the dry-electrode minutes in the signal-quality timeline. How did the app grade them, and were they used for HRV?

- Change the Activity interpretation menu to another mode. Does anything you read change?

- Write half a page: what you measured, what it shows, how sure you are, what you would change, when you would retest.

**Exercise 5.9** (App lab · Core · 20 min)

App: Heart, https://apopt.com/heart, with the workout example `subject-b/workout.csv.gz` (34.6 minutes), recording type Workout.

- Analyze with age 30. Record the TRIMP, the zone-sum load and the minutes in each zone. *Checkpoint:* {TRIMP 40.9; load 99; 3.8, 3.9, 15.6, 6.3, 3.1 minutes.}

- Suppose a hard race showed this runner's maximum to be 185. Enter 185 in the Measured max HR field, analyze again and record TRIMP and the zone-sum load. *Checkpoint:* {TRIMP 45.6; load 104.}

- The app took “rest” as 80, not the runner's true resting rate. Where does 80 come from, and would a true resting rate of 50 raise or lower the TRIMP?

- Listing 5.6 gives a TRIMP of 42.3 at age 30. Give two reasons it differs from the app.

**Exercise 5.10** (Python analysis · Foundation · 20 min · CORE)

Run Listings 5.1, 5.2 and 5.3 on the resting example. *Predict before you run:* will RMSSD of the first 6 intervals be larger or smaller than RMSSD of the first 20? Then compute both, and SDNN and pNN50 of the first 20, by adding one line to Listing 5.3. Finally, repeat on your own recording from Exercise 5.8.

**Exercise 5.11** (Python analysis · Core · 60 min)

**Strap against wrist** (H-6). Wear the strap and a wrist or arm optical device for a session of four one-minute hard efforts with one-minute rests, after a ten-minute easy warm-up. Stop if you feel unwell.

- Export both files. Resample both to one value a second and find the clock offset by cross-correlation.

- Using Listing 5.7, report bias, MAE, MAPE and limits of agreement, separately for rest and effort minutes, and the worst minute.

- Known-answer test first: Listing 5.7 run on the workout example must print a bias of 0.23 and an MAE of 1.08 bpm over 416 windows.

**Exercise 5.12** (Python analysis · Extension · 30 min)

**Sampling rate** (H-11). Take every second sample of the resting example (`t[::2]`, `x[::2]`) so that it runs at about 65 samples a second. Rerun the steps of Listing 5.2 and 5.3.

- What are the new RMSSD and the smallest step between RR values? *Checkpoint:* {24.1 ms against 22.8; about 15.4 ms.}

- Why does timing resolution matter more for HRV at rest than for heart rate in exercise?

- Then do the same on your own recording and say how much RMSSD changed.

**Exercise 5.13** (Python analysis · Extension · 45 min)

**Onset and recovery time constants** (H-7). Walk or jog at a steady pace for six minutes from rest, then stand still for three. Fit Equation \eqref{ch05-heart:eq:first} to the rise and to the recovery with Listing 5.5.

- Known-answer test: on the workout example the listing must give $\tau \approx \SI{28}{\second}$ for the rise and 79 s for the fall of effort 3.

- Report your two time constants with their uncertainties and compare with a teammate's.

- Change the fit window by 30 seconds at the end. How much does $\tau$ move? What does that say about reporting a time constant?

**Exercise 5.14** (Body science · Foundation · 25 min)

**Posture test** (H-4). Record five minutes lying down, then five minutes standing, in one file. Report the change in mean heart rate and RMSSD between the last three minutes of each. Which branch of the nervous system explains the change, and why does standing call for it?

**Exercise 5.15** (Body science · Core · 25 min)

**Paced breathing** (H-5). Breathe at six breaths a minute for three minutes with a metronome (4 s in, 6 s out), then normally for three minutes. Plot the RR series for both parts. Explain what you see. Does the Heart app's breathing estimate find six a minute? Before you answer, read the app's own description of that estimate, and say what you would need to know before trusting it.

**Exercise 5.16** (Science of the sport · Foundation · 10 min)

Listing 5.6 sorted the 34 minutes of the workout example into zones three ways. A coach asks: “How much of that session was hard?” Using zones 4 and 5 of the five-zone models and zone 3 of the threshold model, answer for each model, and explain to the coach why the answers differ.

**Exercise 5.17** (Science of the sport · Extension · 10 min)

A coach sets 30-second hill repeats “at 175 heart rate”. The athlete starts each repeat at 120, and her heart rate approaches about 175 as a first-order response with $\tau = \SI{30}{\second}$.

- What heart rate does she reach by the end of a 30-second repeat? Of a 60-second repeat? *Checkpoint:* {154.8; 167.6.}

- Why is heart rate a poor target for short repeats, and what would you use instead?

**Exercise 5.18** (Field collection · Foundation · 10 min · CORE)

**Seven mornings** (H-9). Equipment: the strap, the Heart app or the logger.

- Each morning for seven days, on waking and after emptying the bladder, lie or sit in the same position.

- Record three minutes, breathing normally. Discard the first minute.

- Record RMSSD for the last two minutes and note sleep, illness, alcohol and the previous day's training.

- Compute ln RMSSD for each day, then the mean and the day-to-day standard deviation.

Safety: none beyond normal life; skip a day when ill and say so. Keep the record: in Chapter 11 the standard deviation becomes your typical error, the day-to-day noise a real change has to beat. As a worked check: seven mornings of 62, 58, 71, 55, 66, 60, 64 ms give a mean ln RMSSD of 4.129 and a standard deviation of 0.085.

**Exercise 5.19** (Field collection · Core · 30 min)

**The interval test** (H-8). App: Heart, recording type Interval test. Equipment: the strap, a track or treadmill, a stopwatch.

- Start one continuous recording. Warm up for ten minutes, easy.

- Run one hard but controlled effort of exactly one minute, the same pace or speed each time.

- Recover (walk or stand, the same way each time) until heart rate returns near the starting level.

- Repeat for five efforts in all. Keep recording through the last recovery.

- Analyze. For each repeat record the rise, the peak and the 60-second recovery, and the drift from first to last.

Safety: stop if you feel unwell, faint, or have chest pain or unusual breathlessness. This is not a maximal test. Repeat the protocol in week 12 under the same conditions and decide, with Chapter 11, whether any change exceeds your day-to-day variation.

**Exercise 5.20** (Build · Core · 90 min · CORE)

**Build step B-5: heart rate from a file, then live** (W-1 to W-4, H-13). Work in your Vite project from earlier weeks. Prompt your AI assistant for each part, then test it.

- A page that loads an RR-interval CSV (use `data/rest-rr.csv` from this chapter, columns `t_s,rr_ms`) and draws heart rate against time on a canvas.

- Add RMSSD, SDNN (dividing by $N$) and pNN50. Test with the known answer: for 812, 790, 835, 801, 822 ms your functions must give 32.0, 15.7 and 0.0. On the full file they must give about 22.8, 51.6 and 3.4.

- Add a Connect button that opens the browser's Bluetooth chooser for the heart-rate service, subscribes to characteristic `0x2A37`, and shows live heart rate. This needs HTTPS (or a local development server) and a browser with Web Bluetooth; if your computer's or phone's browser does not support it, pair with a teammate who has one.

- Decode the whole message with your own version of Listing 5.8, including RR in 1/1024 s, and pass the three tests of Listing 5.9.

- Run your page and the Heart app's Live Capture on the same strap for the same minute (two computers) and compare the RR intervals. If the strap refuses a second connection, alternate the two pages and report that as a finding.

**Exercise 5.21** (Communicate · Core · 30 min · CORE)

**Report for a teammate** (H-15). With your teammate's written consent (Appendix E; under 18, a parent or guardian's consent and the teammate's own assent), analyze one of their workout recordings in the Heart app. Write five sentences for them: what you measured, what it shows, how sure you are, one suggestion, and when to retest. Give it to them and note their reply.

**Exercise 5.22** (Check the AI · Core · 10 min)

An AI assistant analyzed a one-minute seated recording made just after a hard workout. It reported: “RMSSD is 311 ms, which indicates excellent recovery and very high vagal tone.” The intervals were 602, 598, 330, 920, 600, 597, 604, 325, 925, 601, 599, 603 ms. Find the flaw, correct the RMSSD, and rewrite the sentence.

**Exercise 5.23** (Python analysis · Core · 60 min)

Case file: the instructor's case file holds chest-strap recordings of several
nights of sleep and of an interval session, as CSV files with the columns
`time` (nanoseconds), `ecg` (millivolts), `hr`,
`rr` (milliseconds) and `marker`. The question: how sure can we
be of a recovery number from one session?

- Load one file. Convert `time` to seconds from the start and keep
the beat rows (where `rr` is present), as `beats.py` in this
chapter's code folder does. *Checkpoint:* {The median step between ECG rows is
about 7.7 ms (130 Hz); a value near 7.7 million
means the nanoseconds were not converted. Over a quiet minute, $60000$ divided
by the mean `rr` is within a few beats a minute of the mean
`hr`.}

- RMSSD by night. For each sleep recording, clean the intervals with the
rule of Listing 5.3, compute RMSSD in consecutive
five-minute windows, and report the median window RMSSD and its ln RMSSD for
each night, with the share of intervals removed. *Checkpoint:* {The `assert`
on the hand example (32.0 ms) passes before any real data is
read; the removed share is reported for every night.}

- One-minute recovery per repeat. In the interval session, find the end of
each repeat (from `marker` if the repeats were marked, otherwise the
start of the sustained fall, as in Example 5.4).
Recovery is the mean heart rate of the last five seconds of work minus the
mean of the ten seconds centered on 60 seconds later. Test your function first
on a made-up repeat: 176 bpm of work, then an exponential fall toward
120 bpm that passes 141 bpm at 60 s.
*Checkpoint:* {The made-up repeat gives 35.0 beats. One recovery per repeat; the
number of rows equals the number of repeats.}

- A range by resampling. Give a 95% bootstrap interval for the mean
recovery by resampling the *repeats*, with replacement, at least 10{,}000
times (the bootstrap subsection of Chapter 11, “A range by
resampling”). Test it on six made-up recoveries, 31, 35, 28, 33, 30 and 26
beats. *Checkpoint:* {Mean 30.5; interval about 28 to 33 beats (the ends move by a
few tenths with the random seed).} Then resample individual one-second heart
rates instead, and compare the width of the two intervals.

- Which interval would you report, and why?

**Exercise 5.24** (Communicate · Core · 20 min)

Case file: write a note of at most 120 words to the athlete whose recordings
you analyzed in the previous exercise (the instructor, or your case-file
athlete if their case file has strap recordings). Give the night-to-night
RMSSD and the mean one-minute recovery with its interval, in plain words; say
what the interval means; give one suggestion for the next interval session that
would make the number more certain; and state the scope.

**Exercise 5.25** (Body science · Core · 20 min)

**After a hard block.** An athlete's seven-morning baseline is a resting heart rate of 52 bpm
(standard deviation 2.5) and an ln RMSSD of 4.20 (standard deviation 0.10).
After a hard training block the next four mornings give resting rates of 55,
57, 54 and 56 bpm; ln RMSSD of 4.05, 3.98, 4.08 and 4.01; sleep of 6.2,
5.8, 7.0 and 6.5 hours; and a five-item wellness score (5 to 25) of 18, 15, 17
and 16, against a usual 20. These are illustrative values.

- Find the four-morning mean of resting heart rate and of ln RMSSD, and
express each shift from baseline in baseline standard deviations.

- The noise of a four-morning mean is the single-morning standard deviation
divided by $\sqrt4$. Express each shift in those units. Does averaging make the
shift clearer or less clear?

- Which of the five measures of Table 5.3 agree,
and what one training change would you suggest for the next few days?

- Name two things these numbers cannot tell you.
