# Q-6: A first-order response: heart rate after a step

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

Web page: https://apopt.com/course/tutorials/q06-first-order/ · Data: https://apopt.com/data/tutorials/q06-first-order/

## The decision

A coach wants to know how long after the start of an interval the athlete's heart rate is worth
reading. The answer is a time constant, and a fit gives it with an uncertainty.

## The raw data

- `raw/steptest_hr.csv`: second-by-second heart rate through a three-stage step test and five minutes of recovery, with the phase of each second (synthetic) *Data-Driven Athletics*, Chapter 2, Sections 2.4 and 2.11: Sam's step test, synthetic data built with a 35 s time constant for the climb and 50 s for recovery.

### A step in work, a curve in heart rate

When Sam steps onto the bench, the work jumps to its new level at once. Heart rate does not: it
climbs toward a new level over tens of seconds. Section 2.4 models that climb as a
**first-order response**, the curve of a tank filling through a valve:

y(t) = y∞ + (y₀ − y∞) e^(−t/τ)

where y₀ is the heart rate before the step, y∞ the level it settles toward, and τ (tau) the
**time constant**: the time to cover 63% of the change. The file is a chest strap's heart
rate, one value a second, through Sam's step test. Sam is made up; the data are the book's
**synthetic** test, built with a time constant of 35 s for the climb, so you can check the fit.

*Predict first:* The first stage starts at 120 s. About how long will heart rate take to cover two thirds of its rise?

```python
import numpy as np
import pandas as pd

hr = pd.read_csv("raw/steptest_hr.csv")
print(hr["phase"].value_counts().to_string())
stage = hr[(hr["time_s"] >= 120) & (hr["time_s"] < 300)]
t = stage["time_s"].to_numpy() - 120        # seconds since the step
y = stage["hr_bpm"].to_numpy()
print(f"stage 1: {len(t)} s, heart rate {y[0]} -> {y[-10:].mean():.0f} bpm (mean of the last 10 s)")
```

Output:

```
phase
step        540
recovery    330
rest        120
pause        40
stage 1: 180 s, heart rate 64 -> 104 bpm (mean of the last 10 s)
```

### Fit the curve

`curve_fit` from SciPy adjusts y₀, y∞ and τ together until the squared misses, in beats a
minute, are as small as possible. It needs a rough starting guess: the first value, the last
values, and 30 s.

```python
from scipy.optimize import curve_fit

def first_order(t, y0, yinf, tau):
    return yinf + (y0 - yinf) * np.exp(-t / tau)

p, cov = curve_fit(first_order, t, y, p0=(y[0], y[-10:].mean(), 30))
se = np.sqrt(np.diag(cov))
y0, yinf, tau = p
print(f"y0 {y0:.1f} bpm, y_inf {yinf:.1f} bpm, tau {tau:.1f} +/- {se[2]:.1f} s")
y63 = y0 + 0.63 * (yinf - y0)
print(f"63% of the rise is {y63:.0f} bpm; the data first reach it at t = {t[np.argmax(y >= y63)]} s")
```

Output:

```
y0 64.9 bpm, y_inf 103.9 bpm, tau 37.2 +/- 1.4 s
63% of the rise is 89 bpm; the data first reach it at t = 35 s
```

The fit gives a time constant of 37 ± 1.4 s, against the 35 s the data were built with. The
63% rule read straight off the data gives 35 s. The fit is a little long because
the synthetic heart rate also drifts up slowly through the stage (Section 2.4, "Drift"), which a
single exponential cannot follow, so it stretches τ to absorb it.

### One chart

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.plot(t, y, ".", color="0.6", label="strap, every second")
ax.plot(t, first_order(t, *p), "k-", lw=2, label=f"first-order fit, tau = {tau:.0f} s")
ax.axvline(tau, color="k", ls="--", lw=1)
ax.axhline(y63, color="k", ls=":", lw=1, label="63% of the rise")
ax.set(xlabel="time since the step (s)", ylabel="heart rate (beats/min)")
ax.legend(loc="lower right")
plt.tight_layout()
print(f"after 3 tau ({3 * tau:.0f} s) the fit is within {100 * np.exp(-3):.0f}% of its new level")
```

Output:

```
after 3 tau (112 s) the fit is within 5% of its new level
```

![Heart rate in beats per minute against seconds since the step, 0 to 180 s. Gray dots from the strap rise from about 64 to about 104; a black fitted curve follows them; a dashed vertical line at tau, about 37 s, meets the curve at 63% of the rise.](https://apopt.com/course/tutorials/q06-first-order/c05-1.png)

After three time constants, just under two minutes, heart rate is within 5% of its new level. That
is why the step test's stages last three minutes: a count taken earlier would catch heart rate
still climbing.

**For the athlete:** "Your heart rate takes 35 to 40 seconds to cover most of its rise when you
start a new effort, so judge an interval's intensity by your heart rate only after the first two
minutes."

## With your own data

Record a chest strap through a rest and a steady effort (Chapter 5 shows how), cut out the first
three minutes of the effort, and fit the same curve. Real heart rate is noisier than this file;
report τ with its ± from the fit.

## References

- *Data-Driven Athletics*, Chapter 2, The Response to a Step (Section 2.4) and Measuring Yourself: A Step Test (Section 2.11).

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