# CS-2: A step test and a first straight line

Data-Driven Athletics tutorial · Week 2 · Chapter 2 · about 50 min · workflow steps: Gather, Statistics, Visualize, Split

Web page: https://apopt.com/course/tutorials/cs02-step-test-line/ · Data: https://apopt.com/data/tutorials/cs02-step-test-line/

## The decision

Sam wants one number to keep easy sessions easy: a heart rate to stay under. A step test with a
talk test gives it, if the line through the counts can be trusted on a workload it was not fitted
to. If the line missed held-out stages by 10 beats a minute, no single number would be worth giving.

## Predict first

Before any code: by how many beats a minute will Sam's heart rate rise from the first stage (15 step cycles a minute) to the fifth (35), and will a straight line predict a held-out stage to within 5 beats a minute?

## The raw data

- `raw/steptest_five_stages_synthetic.csv`: a partner's step-test sheet, SYNTHETIC; a 30 s resting count and five 3-minute stages on a 0.30 m bench, with the metronome setting, the beats counted, the length of each count and the talk-test answer Made by this tutorial's `prepare.py` from the same model as the book's step test (Chapter 2, Sections 2.4 and 2.11); a made-up 70 kg student, not a real person.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| stage | rest or stage 1–5 | text | rest; stage 1 … stage 5 | none |
| metronome_bpm | metronome setting; four beats per step cycle | beats/min | 0–140 | 0 at rest |
| count_s | length of the pulse count | s | 15 or 30 | none |
| beats | beats counted in that time | beats | 20–40 | none |
| talk | talk-test answer at the end of the stage: could the athlete speak comfortably? | yes, yes but, no | — | empty at rest |

Nothing is wrong with the numbers, but none is in the unit you need. The metronome is in beats a
minute, not step cycles; the counts have two different lengths; and heart rate is not on the sheet
at all. The counts also start two seconds after each stage ends, so every one reads a little lower
than the heart rate during the stage, more at the harder stages. The file is synthetic, so the true
heart rate is known: at the fifth stage it was 155 at the moment Sam stopped, and the count gave 140.

### Step 1 · Gather: the partner's sheet

Sam (a made-up student; every number here is **synthetic**, made by `prepare.py` from the same
model as the book's step test in Section 2.11) stepped on a 0.30 m bench for five 3-minute
stages, each faster than the last. Sam weighs 70 kg. After each stage a partner counted beats for
15 seconds, starting two seconds after Sam stopped, and asked Sam to read a short paragraph aloud:
could Sam speak comfortably? (the talk test, Section 7.4.4). Before the test the partner also
counted 30 seconds at rest. The file is the sheet as the partner wrote it.

*Predict first:* The metronome column for the first stage reads 60. How many step cycles a minute is that?

```python
import pandas as pd

sheet = pd.read_csv("raw/steptest_five_stages_synthetic.csv")
print(sheet.to_string(index=False))
```

Output:

```
  stage  metronome_bpm  count_s  beats    talk
   rest              0       30     33     NaN
stage 1             60       15     25     yes
stage 2             80       15     27     yes
stage 3            100       15     31     yes
stage 4            120       15     33 yes but
stage 5            140       15     35      no
```

Two things on the sheet are not yet the numbers you need. The metronome is set in **beats** a
minute, four beats per step cycle (up, up, down, down), so 60 on the metronome is 15 cycles a
minute. And the counts are not all the same length: 30 seconds at rest, 15 after each stage.
Turn each into the quantity it stands for, with the unit in the column name, and keep the sheet
untouched.

```python
import os

MASS, G, BENCH = 70, 9.81, 0.30                        # kg, m/s², m
df = sheet.copy()
df["rate_cpm"] = df["metronome_bpm"] / 4               # step cycles a minute
df["power_W"] = (MASS * G * BENCH * df["rate_cpm"] / 60).round(1)   # lifting power
df["hr_bpm"] = df["beats"] * 60 / df["count_s"]        # beats in the count, per minute
os.makedirs("clean", exist_ok=True)
df.to_csv("clean/steptest_clean.csv", index=False)
print(df[["stage", "rate_cpm", "power_W", "hr_bpm", "talk"]].to_string(index=False))
```

Output:

```
  stage  rate_cpm  power_W  hr_bpm    talk
   rest       0.0      0.0    66.0     NaN
stage 1      15.0     51.5   100.0     yes
stage 2      20.0     68.7   108.0     yes
stage 3      25.0     85.8   124.0     yes
stage 4      30.0    103.0   132.0 yes but
stage 5      35.0    120.2   140.0      no
```

### Step 2 · Statistics: what can these counts resolve?

A profile before any fit. How far does heart rate move across the test, and what is the smallest
step a count can show?

*Predict first:* Over five stages, how many beats a minute will heart rate rise from the first stage to the last?

```python
st = df[df["stage"] != "rest"]
print(f"rest: {df.loc[df['stage'] == 'rest', 'hr_bpm'].iloc[0]:.0f} bpm (30 s count)")
print(f"stages: {st['hr_bpm'].min():.0f} to {st['hr_bpm'].max():.0f} bpm over "
      f"{st['power_W'].min()} to {st['power_W'].max()} W")
print("resolution of a 15 s count: 60/15 =", 60 // 15, "bpm; of the 30 s rest count:", 60 // 30, "bpm")
print("rise per stage (bpm):", st["hr_bpm"].diff().dropna().astype(int).tolist())
```

Output:

```
rest: 66 bpm (30 s count)
stages: 100 to 140 bpm over 51.5 to 120.2 W
resolution of a 15 s count: 60/15 = 4 bpm; of the 30 s rest count: 2 bpm
rise per stage (bpm): [8, 16, 8, 8]
```

Heart rate rises by 40 beats a minute across the five stages, in steps of 8, 16, 8 and 8. Each
count can only move in steps of 4, and a partner can miscount by a beat, so a single stage can be
4 beats a minute off either way. That is the size of error the fit must be judged against.

### Step 3 · Visualize

```python
import matplotlib.pyplot as plt

marks = {"yes": "o", "yes but": "^", "no": "X"}
fig, ax = plt.subplots(figsize=(6.4, 3.8))
for answer, m in marks.items():
    s = st[st["talk"] == answer]
    ax.plot(s["power_W"], s["hr_bpm"], m, ms=10, color="k", mfc="white" if answer != "no" else "k",
            label=f"talk test: {answer}")
rest = df[df["stage"] == "rest"]
ax.plot(rest["power_W"], rest["hr_bpm"], "s", ms=9, color="0.5", label="rest (30 s count)")
ax.set(xlabel="lifting power (W)", ylabel="heart rate (beats/min)", xlim=(-5, 130))
ax.legend(loc="upper left")
plt.tight_layout()
```

![Heart rate in beats per minute against lifting power in watts. Five stage counts rise from 100 bpm at 51.5 W to 140 bpm at 120.2 W, marked by talk-test answer: circles for yes at the first three stages, a triangle for yes but at the fourth, a cross for no at the fifth. The resting count, 66 bpm, is a square at 0 W.](https://apopt.com/course/tutorials/cs02-step-test-line/c07-1.png)

The five stages lie close to a straight line. Rest, at 66, happens to sit near where that line
would meet zero watts, but nothing guarantees it: in Q-5's three-stage test the line met zero
watts 11 beats a minute below rest. A line is only tested over the range of its data. Sam
could talk comfortably through the first three stages, only just at the fourth, not at the fifth.

### Step 8 · Split: fit the line, then test it on a stage it has not seen

A line through five points always looks good on the points it was fitted to. The honest test is
a point it has **not** seen. Hold out one stage, fit the line to the other four, predict the
held-out stage, and repeat for each stage in turn. Compare with the **mean baseline**: ignore
power and always guess the average heart rate of the four training stages. A line that cannot
beat that has learned nothing (Section 2.11, the engineer's note "Your first straight-line fit").

*Predict first:* Which held-out stage will the line miss by the most, and why?

```python
import numpy as np

P, HR = st["power_W"].to_numpy(), st["hr_bpm"].to_numpy()
b, a = np.polyfit(P, HR, 1)
r2 = 1 - ((HR - (a + b * P)) ** 2).sum() / ((HR - HR.mean()) ** 2).sum()
print(f"all five: HR = {a:.1f} bpm + {b:.3f} bpm/W x P   (R² {r2:.3f}); "
      f"{b * MASS * G * BENCH / 60:.2f} bpm per cycle/min")
rows = []
for i in range(len(P)):
    keep = np.arange(len(P)) != i
    bi, ai = np.polyfit(P[keep], HR[keep], 1)
    rows.append({"held out": st["stage"].iloc[i], "measured": HR[i],
                 "line": round(ai + bi * P[i], 1), "line miss": round(HR[i] - (ai + bi * P[i]), 1),
                 "baseline miss": round(HR[i] - HR[keep].mean(), 1)})
held = pd.DataFrame(rows)
print(held.to_string(index=False))
print(f"mean absolute miss: line {held['line miss'].abs().mean():.1f} bpm, "
      f"baseline {held['baseline miss'].abs().mean():.1f} bpm")
```

Output:

```
all five: HR = 68.8 bpm + 0.606 bpm/W x P   (R² 0.982); 2.08 bpm per cycle/min
held out  measured  line  line miss  baseline miss
 stage 1     100.0 100.0       -0.0          -26.0
 stage 2     108.0 111.5       -3.5          -16.0
 stage 3     124.0 120.0        4.0            4.0
 stage 4     132.0 130.8        1.2           14.0
 stage 5     140.0 144.0       -4.0           24.0
mean absolute miss: line 2.5 bpm, baseline 16.8 bpm
```

Fitted to all five stages, each watt adds 0.61 beats a minute, or 2.1 per extra step cycle a
minute. On stages it had not seen, the line misses by 2.5 beats a minute on average, against 16.8
for the mean baseline: it has learned something real. Its misses are about one count's
resolution, 4 beats a minute, so the line is about as good as the counts allow, even at the fifth
stage, where it had to extrapolate beyond the four it was fitted to. The baseline misses the two
end stages by the most, 26 and 24 beats a minute, because they are farthest from the average.

```python
fig, ax = plt.subplots(figsize=(6.4, 3.4))
x = np.arange(len(held))
ax.axhspan(-4, 4, color="0.9", label="one count step (±4 bpm)")
ax.plot(x, held["line miss"], "o", ms=9, color="k", label="straight line")
ax.plot(x, held["baseline miss"], "s", ms=8, mfc="none", color="k", label="mean baseline")
ax.axhline(0, color="k", lw=0.8)
ax.set(xticks=x, xticklabels=held["held out"], ylabel="measured − predicted (bpm)")
ax.legend(loc="upper left")
plt.tight_layout()
```

![Markers of the miss in beats per minute for each held-out stage. The straight line misses by 4 or less at every stage, inside a shaded band of one count step; the mean baseline misses by 4 to 26 beats, largest at the two end stages.](https://apopt.com/course/tutorials/cs02-step-test-line/c11-1.png)

### A heart rate for an easy session

The talk test gives the decision a boundary. Sam could still talk comfortably at the third stage
and not quite at the fourth. Section 7.4.4 reports that the last comfortable stage of a talk test
falls close to the first threshold, the top of the easy range. So read the line at the third
stage's power, and use the held-out misses as the band.

```python
easy = st[st["talk"] == "yes"].iloc[-1]
hr_easy = a + b * easy["power_W"]
band = held["line miss"].abs().max()
print(f"last 'yes' stage: {easy['stage']}, {easy['rate_cpm']:.0f} cycles/min, {easy['power_W']} W")
print(f"line: {hr_easy:.0f} bpm, held-out band ±{band:.0f} bpm -> easy up to about {hr_easy:.0f} bpm")
print(f"counts start 2 s after stopping, so a strap read while moving shows more (Section 2.12)")
```

Output:

```
last 'yes' stage: stage 3, 25 cycles/min, 85.8 W
line: 121 bpm, held-out band ±4 bpm -> easy up to about 121 bpm
counts start 2 s after stopping, so a strap read while moving shows more (Section 2.12)
```

The line puts the top of Sam's easy range at about 121 beats a minute, give or take 4. That
number comes from counts taken after Sam stopped, and heart rate starts falling the moment work
stops; Section 2.12 measured that effect at about 9 beats a minute for the book's version of this
test. A strap read while moving will therefore show somewhat more at the same effort. Say so on
the action card, and retest with the same bench, the same metronome and the same partner.

## How good is the number?

Three checks. **Held-out error:** fitted to four stages and tested on the fifth, the line misses by
2.5 beats a minute on average and at most 4, the resolution of a 15-second count; the mean baseline
misses by 16.8. **Resolution:** the counts move in steps of 4, and a partner may miss a beat, so no
stage is known to better than about ±4. **Bias:** counts start after the athlete stops, so they read
low, by about 9 beats a minute at the book's last stage (Section 2.12) and more at higher heart rates.
Five points also cannot show whether the true relation bends near the top of the range.

## Track it

Add one row per stage: `test=step-test, metric=hr_stage3_bpm` (and stages 1–5), `value`, `unit=bpm`,
`protocol_version=v1-bench30-15s-count`, plus one row for the slope:
`metric=hr_slope_bpm_per_w, unit=bpm/W`. The slope and the heart rate at a fixed stage are the two
numbers to compare at the next battery.

## With your own data

Replace the sheet with your own counts and change `MASS` and `BENCH` in the Step 1 cell. Keep the talk
test the same every time. Heart rate is a personal health number: it is never graded or shared without
your consent.

## The same method in another field

Fitting a line on most of the data and testing it on the point left out is how a sensor calibration is
checked in a plant: calibrate a thermocouple at four reference temperatures, test it at the fifth. The
Machine Learning for Engineers page on [splitting data](https://apmonitor.com/pds/index.php/Main/SplitData)
shows the same idea with more data.

## Acknowledgements

The model of the synthetic test is the book's (Chapter 2, `code/make_synthetic.py`); this five-stage
version is made by `prepare.py` in this tutorial's folder.

## Action card

- **Finding:** Your easy range tops out at about 121 beats a minute, measured by a 15-second count right after stopping.
- **Evidence:** A straight line through five stages (0.61 beats a minute per watt) predicted each held-out stage to within 4 beats a minute; you could still talk comfortably at the third stage, where the line reads 121.
- **Sure:** Moderate. Counts are ±4 beats a minute, and they read low because heart rate falls as soon as you stop; a strap worn while moving will show several beats more.
- **Action:** Keep easy sessions at a pace where you can still talk comfortably and your heart rate stays at or under about 121 by a quick count (roughly 130 on a strap, which reads about 9 beats a minute above a count). This is training information, not medical advice.
- **Retest:** Repeat the same test, same bench, metronome and partner, in six weeks; a lower heart rate at the same stage means the same work costs your heart less.

## Challenge: Your own step test, against a strap

Run the step test of Chapter 2's field exercise yourself, with a partner, the talk test at each stage,
and, if you have one, a chest strap or a watch recording at the same time. Use the book's strap
record of Sam's test (`book/ch02-system/data/steptest_hr.csv`, synthetic) if you have no strap.

1. Type your sheet in the same format and convert it with the Step 1 cell; record your mass and bench height.
2. Fit heart rate against lifting power and give the slope in bpm per watt and per step cycle a minute.
3. Hold out each stage in turn and report the line's and the baseline's mean absolute miss.
4. Take the strap's heart rate over the last 30 s of each stage and fit the same line; compare the slopes and intercepts.
5. Read off your easy-session heart rate from the last comfortable talk-test stage, by count and by strap.

Deliverables:

- the notebook with its outputs
- a table of held-out misses, line against baseline
- an action card with both easy-session numbers and their band

## References

- *Data-Driven Athletics*, Chapter 2: The Response to a Step (Section 2.4), Measuring Yourself: A Step Test (Section 2.11), How Good Is the Number? (Section 2.12); Chapter 7, Thresholds without blood (Section 7.4.4).

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