# CS-7: Critical speed from a watch archive

Data-Driven Athletics tutorial · Week 6 · Chapter 6 · about 60 min · workflow steps: Gather, Statistics, Visualize, Cleanse, Features, Split

Web page: https://apopt.com/course/tutorials/cs07-critical-speed/ · Data: https://apopt.com/data/tutorials/cs07-critical-speed/

## The decision

The instructor wants a pace for threshold sessions, the steady hard runs that sit just under
critical speed (Section 6.5). He has run no test, only six weeks of training. If the archive
pins critical speed down, the threshold pace follows from it; if it does not, he needs either
a cautious pace or a proper test.

## Predict first

A season of ordinary training runs holds some fast stretches. Do you expect the best efforts from them to give a critical speed precise to within about 0.1 m/s (6 s per km), or not?

## The raw data

- `raw/activities.csv`: one row per run, 19 runs from 10 April to 18 May 2026 (date, distance_km, moving and elapsed time, pace in min/km, heart rate, cadence, elevation, power, laps, the records file, a load score) The instructor's own watch, from the course case file `athletes/jh/watch/`, published under his name.
- `raw/laps.csv`: the watch's lap summaries for the same runs (start time, timer_s, distance_m, heart rate, cadence, ascent, power) Same case file.
- `raw/records/`: one CSV per run, a record every second (time, elapsed_s, distance_m, speed_mps, heart_rate_bpm, cadence_spm, altitude_m, power_w, running dynamics, temperature_c); 61,483 records in all, no positions Same case file; converted from the watch's FIT files with every GPS coordinate removed.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| time | sample time | ISO 8601 UTC | Apr–May 2026 | none |
| elapsed_s | seconds since the run started | including pauses | s | 0–10 887 | none |
| distance_m | cumulative distance computed by the watch | m | 0–16 148 | none |
| speed_mps | instantaneous speed from the watch | m/s | 0–7.3 | empty while stopped |
| heart_rate_bpm | optical heart rate at the wrist | beats/min | 57–182 | empty |
| cadence_spm | steps a minute (both feet) | steps/min | 0–226 | empty |
| altitude_m | barometric altitude | m | 1365–1479 | empty |

What is wrong with it: the watch was paused 122 times across the 19 runs, so clock time and
running time differ; the distance field sometimes stays still for a few seconds and then
catches up in one-second steps of 14 to 26 m; heart rate is optical, from the wrist, and lags
at the start of runs. Above all, no run was a test: the fast stretches are tempo miles inside
training runs, run hard but not to exhaustion.

### Step 1 · Gather

The archive is the instructor's 19 runs from April and May 2026, as his watch recorded them:
one table of runs, one table of laps, and one file per run with a record every second
(positions removed). No run in it was planned as a test. The question is whether a season of
ordinary training holds enough hard running to estimate a critical speed, and so a pace for
threshold sessions.

*Predict first:* Of 19 training runs, how many do you think contain a hard, sustained effort of 10 minutes or more?

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

runs = pd.read_csv("raw/activities.csv")
rec = {a: pd.read_csv(f"raw/{f}", parse_dates=["time"]) for a, f in zip(runs["activity_id"], runs["records_file"])}
print(f"{len(runs)} runs from {runs['date'].min()} to {runs['date'].max()}, "
      f"{runs['distance_km'].sum():.0f} km in {runs['moving_time_min'].sum() / 60:.1f} h")
print(f"{sum(len(r) for r in rec.values())} one-second records; columns: {list(rec[runs['activity_id'][0]].columns)}")
print(runs[["date", "distance_km", "moving_time_min", "pace_min_per_km", "avg_hr_bpm", "laps"]].to_string(index=False))
```

Output:

```
19 runs from 2026-04-10 to 2026-05-18, 198 km in 17.1 h
61483 one-second records; columns: ['time', 'elapsed_s', 'distance_m', 'speed_mps', 'heart_rate_bpm', 'cadence_spm', 'altitude_m', 'power_w', 'stance_time_ms', 'vertical_oscillation_mm', 'step_length_mm', 'temperature_c']
      date  distance_km  moving_time_min  pace_min_per_km  avg_hr_bpm  laps
2026-04-10       11.567            59.95             5.18         146    15
2026-04-11       14.326            69.15             4.83         124    10
2026-05-04        8.606            40.63             4.72         154     6
2026-05-04        8.674            47.74             5.50         138     6
2026-05-05        8.343            41.85             5.02         141     6
2026-05-06        8.498            46.95             5.52         149     6
2026-05-06       11.068            61.72             5.58         138     7
2026-05-08       12.720            66.17             5.20         134     8
2026-05-08        6.788            37.79             5.57         127     5
2026-05-09       15.472            75.13             4.86         147    10
2026-05-11        8.048            38.60             4.80         128     5
2026-05-11       10.487            62.41             5.95         137    22
2026-05-12       16.148            80.86             5.01         143    11
2026-05-13        8.059            42.25             5.24         138     6
2026-05-13       12.318            67.84             5.51         130     8
2026-05-14        5.880            30.03             5.11         138     4
2026-05-15       10.960            60.34             5.51         139    28
2026-05-16       11.147            54.93             4.93         146     7
2026-05-18        8.720            40.10             4.60         131     6
```

Pace in the run table is minutes per kilometre: all 19 runs average between 4.6 and 6.0
minutes per km, steady running. A hard effort would hide inside a run, so the records are
what to search.

### Step 2 · Statistics

*Predict first:* What is the largest distance you expect the watch to add in a single second?

```python
rows = []
for a, r in rec.items():
    gap = r["time"].diff().dt.total_seconds()
    step = r["distance_m"].diff()[gap == 1]
    rows.append({"run": a[:15], "records": len(r), "pauses": int((gap > 1).sum()),
                 "max_1s_step_m": step.max(), "steps_over_8m": int((step > 8).sum()),
                 "max_hr": r["heart_rate_bpm"].max()})
prof = pd.DataFrame(rows)
print(prof.to_string(index=False))
print(f"highest heart rate in the archive: {prof['max_hr'].max():.0f} beats/min")
```

Output:

```
            run  records  pauses  max_1s_step_m  steps_over_8m  max_hr
2026-04-10_1505     3596       6            9.5              2   182.0
2026-04-11_0809     4150       3            6.5              0   156.0
2026-05-04_1028     2439       0            4.5              0   172.0
2026-05-04_1509     2864      11           20.0              5   175.0
2026-05-05_0827     2510       4           15.0              1   174.0
2026-05-06_0831     2818       1            6.0              0   174.0
2026-05-06_1507     3705      15           26.0             21   176.0
2026-05-08_0755     3971       5           15.0              3   180.0
2026-05-08_1517     2268       7           16.0              3   175.0
2026-05-09_0830     4509       4           25.0              2   175.0
2026-05-11_0945     2317       1            6.5              0   145.0
2026-05-11_1507     3746      21           14.0              8   176.0
2026-05-12_0616     4852       1           14.0              1   175.0
2026-05-13_1005     2536       0            7.0              0   161.0
2026-05-13_1506     4072       8           24.0              4   176.0
2026-05-14_0726     1803       2            7.0              0   173.0
2026-05-15_1509     3623      19           17.5              3   179.0
2026-05-16_1118     3297       9            8.0              0   173.0
2026-05-18_1507     2407       5            7.5              0   167.0
highest heart rate in the archive: 182 beats/min
```

Most runs have pauses (traffic, a drink, the watch stopped between repeats), and several have
one-second distance steps of 14 to 26 m: 14 to 26 m/s, faster than any runner. A picture of one
shows what they are.

### Step 3 · Visualize

```python
import matplotlib.pyplot as plt

r = rec["2026-05-15_1509_running"]
w = r[(r["time"] >= "2026-05-15 22:11:55+00:00") & (r["time"] < "2026-05-15 22:12:25+00:00")]
s = (w["time"] - w["time"].iloc[0]).dt.total_seconds()
from_speed = w["distance_m"].iloc[0] + w["speed_mps"].fillna(0).cumsum().shift(fill_value=0)
print(w[["time", "distance_m", "speed_mps"]].iloc[8:16].to_string(index=False))
fig, ax = plt.subplots(figsize=(8, 3.2))
ax.step(s, w["distance_m"], where="post", color="k", label="distance field (raw)")
ax.plot(s, from_speed, "o--", ms=3, label="sum of the speed field")
ax.set(xlabel="time (s)", ylabel="distance (m)", title="2026-05-15: start of a fast repeat")
ax.legend(loc="upper left")
plt.tight_layout()
```

Output:

```
                     time  distance_m  speed_mps
2026-05-15 22:12:05+00:00      7047.0      1.975
2026-05-15 22:12:06+00:00      7047.0      3.669
2026-05-15 22:12:07+00:00      7064.5      4.611
2026-05-15 22:12:08+00:00      7082.0      5.553
2026-05-15 22:12:09+00:00      7088.5      5.853
2026-05-15 22:12:10+00:00      7095.0      6.153
2026-05-15 22:12:11+00:00      7101.5      6.278
2026-05-15 22:12:12+00:00      7108.0      6.406
```

![Distance in metres against time in seconds for 30 seconds of the 15 May run. The watch's distance field stays flat for several seconds while the runner starts moving, then jumps by 17.5 m twice; the distance from the watch's own speed field rises smoothly through the same seconds.](https://apopt.com/course/tutorials/cs07-critical-speed/c05-1.png)

The runner was standing, then started a fast repeat. The watch's speed field rises at once,
but its distance field stays put for twelve seconds and then catches up in two steps of
17.5 m, ending about 15 m above the summed speed. Which of the two is right second by second
the file cannot say; over whole runs they differ by a percent or two. What matters here is
narrower: a best effort whose window starts just before such a jump gains metres that were not
run inside the window.

### Step 4 · Cleanse

The rules, written before any best effort is computed:

1. A pause (a gap over 1 s between records) ends a stretch; no effort may span a pause.
2. An effort may not contain a one-second distance step over 8 m, faster than anything this
   runner does; such a window is skipped, not repaired.
3. Only durations from 2 to 15 minutes are used, the range in which the critical-speed model
   is normally fitted (Jones and Vanhatalo, 2017).

```python
import os

DURATIONS = [120, 180, 240, 300, 420, 600, 720, 900]          # seconds, rule 3

def best_efforts(a, r):
    gap = r["time"].diff().dt.total_seconds()
    jump = ((r["distance_m"].diff() > 8) & (gap == 1)).to_numpy()
    out = []
    for _, g in r.groupby((gap != 1).cumsum()):                 # rule 1: stretches without pauses
        d, j, hr = g["distance_m"].to_numpy(), np.cumsum(jump[g.index]), g["heart_rate_bpm"].to_numpy()
        for T in [T for T in DURATIONS if len(d) > T]:
            gain = np.where(j[T:] - j[:-T] > 0, -1, d[T:] - d[:-T])  # rule 2: skip windows with a jump
            i = int(np.argmax(gain))
            if gain[i] > 0:
                out.append({"t_s": T, "d_m": gain[i], "run": a[:10], "start": g["time"].iloc[i],
                            "hr": np.nanmean(hr[i:i + T])})
    return out

eff = pd.DataFrame([e for a, r in rec.items() for e in best_efforts(a, r)])
best = eff.loc[eff.groupby("t_s")["d_m"].idxmax()].reset_index(drop=True)
best["v_mps"] = best["d_m"] / best["t_s"]
best["hr_pct"] = 100 * best["hr"] / prof["max_hr"].max()
os.makedirs("clean", exist_ok=True); best.to_csv("clean/best_efforts.csv", index=False)
print(f"{len(eff)} candidate efforts; the best at each duration:")
print(best[["t_s", "d_m", "v_mps", "run", "hr", "hr_pct"]].round(2).to_string(index=False))
```

Output:

```
393 candidate efforts; the best at each duration:
 t_s    d_m  v_mps        run     hr  hr_pct
 120  645.0   5.38 2026-05-18 163.88   90.04
 180  952.0   5.29 2026-05-18 162.63   89.36
 240 1236.0   5.15 2026-05-18 161.33   88.64
 300 1522.0   5.07 2026-05-18 160.23   88.04
 420 2113.0   5.03 2026-05-18 160.13   87.98
 600 2944.0   4.91 2026-05-18 157.28   86.42
 720 3281.0   4.56 2026-04-11 149.75   82.28
 900 4059.0   4.51 2026-04-11 148.48   81.58
```

Every best effort from 2 to 10 minutes comes from one run, 18 May, and the 12- and 15-minute
bests from another, 11 April. The run table explains it: both runs held hard miles in the
middle (on 18 May two miles in 343 and 321 s, on 11 April three in 369, 359 and 347 s), and
no other run did. The heart rate says neither was all-out: 86 to 90% of the highest heart rate
in the archive on 18 May, about 82% on 11 April.

### Step 5 · Features: the speed–duration line

Section 6.5: plot each best effort as distance against time and fit a straight line,
d = CS·t + D′. The slope is the critical speed; the intercept D′ is the distance that can be
run above it.

*Predict first:* Will the eight points lie on one straight line, within a few metres?

```python
cs, dprime = np.polyfit(best["t_s"], best["d_m"], 1)
best["resid_m"] = best["d_m"] - (cs * best["t_s"] + dprime)
pace = lambda v: f"{int(1000 / v // 60)}:{1000 / v % 60:04.1f} per km"
print(f"CS = {cs:.2f} m/s ({pace(cs)}), D' = {dprime:.0f} m")
print("residuals (m):", best["resid_m"].round(0).tolist())
print(f"R² = {1 - (best['resid_m'] ** 2).sum() / ((best['d_m'] - best['d_m'].mean()) ** 2).sum():.4f}")
```

Output:

```
CS = 4.37 m/s (3:48.8 per km), D' = 192 m
residuals (m): [-72.0, -27.0, -6.0, 18.0, 85.0, 129.0, -59.0, -68.0]
R² = 0.9964
```

A critical speed of 4.37 m/s and a D′ of 192 m are plausible numbers for a trained runner, and
R² is 0.996, as high as a fit of distance against time always is (Section 6.5). The residuals are
not plausible: they run from −72 m up to +129 m and back down to −68 m, a curve, not
scatter. The 18 May points rise above the line and the 11 April points fall below it. A line
through efforts from two different days, neither run to exhaustion, mostly measures how hard
each day was.

### Step 8 · Split: hold out an effort, then hold out a run

Hold out one effort, fit the other seven, and predict the one left out. Then do it the way
CS-13 taught: the efforts of one run are not independent (the 2-minute best sits inside the
10-minute best), so hold out a whole run.

```python
def fit(sub):
    return np.polyfit(sub["t_s"], sub["d_m"], 1)

loo = [best.loc[i, "d_m"] - np.polyval(fit(best.drop(i)), best.loc[i, "t_s"]) for i in best.index]
print("leave one effort out, prediction errors (m):", np.round(loo).astype(int).tolist())
for run in best["run"].unique():
    c, d0 = fit(best[best["run"] != run])
    print(f"fitted without {run}: CS {c:.2f} m/s ({pace(c)}), D' {d0:.0f} m")

fig, ax = plt.subplots(1, 2, figsize=(9, 3.6))
for run, m in zip(best["run"].unique(), ["o", "s"]):
    sub = best[best["run"] == run]
    ax[0].plot(sub["t_s"], sub["d_m"], m, mfc="none", color="k", label=run)
    ax[1].plot(sub["t_s"], sub["resid_m"], m, mfc="none", color="k", label=run)
tt = np.array([0, 960])
ax[0].plot(tt, cs * tt + dprime, "-", label="all efforts")
for run, ls in zip(best["run"].unique(), ["--", ":"]):
    ax[0].plot(tt, np.polyval(fit(best[best["run"] == run]), tt), ls, label=f"{run} only")
ax[0].set(xlabel="duration (s)", ylabel="best distance (m)"); ax[0].legend(fontsize=8)
ax[1].axhline(0, color="gray", lw=1)
ax[1].set(xlabel="duration (s)", ylabel="residual from all-efforts line (m)")
plt.tight_layout()
```

Output:

```
leave one effort out, prediction errors (m): [-104, -36, -7, 22, 97, 156, -81, -141]
fitted without 2026-05-18: CS 4.32 m/s (3:51.4 per km), D' 169 m
fitted without 2026-04-11: CS 4.79 m/s (3:28.9 per km), D' 85 m
```

![Left, distance against time for the eight best efforts, circles for 18 May and squares for 11 April, with three lines: all efforts, 18 May only, and 11 April only. Right, the residual of each effort from the all-efforts line, in metres, against duration.](https://apopt.com/course/tutorials/cs07-critical-speed/c11-1.png)

Holding out one effort at a time, the line misses by as much as 156 m. Holding out a run, the
answer depends on which run is left: the 11 April efforts alone give 4.32 m/s, the 18 May
efforts alone 4.79 m/s, 3:51 against 3:29 per kilometre. The archive brackets the
critical speed; it does not measure it.

That is the finding. Smyth and Muniz-Pumares (2020) estimated critical speed from the
training logs of thousands of marathon runners and noted that raw training data cannot verify
that an effort was maximal. Here the heart rate shows that it was not. For setting a threshold
pace, the safe choice is the lowest estimate: threshold work sits just under critical speed
(Section 6.5), and 4.32 m/s is the speed the athlete has already held for 15 minutes.

## How good is the number?

**Fit.** R² is 0.996, which says nothing here: distance always grows with time. The residuals
say more: they curve from −72 m to +129 m and back to −68 m, so the points do not lie on one
line.

**Held out.** Leaving one effort out, the line misses it by up to 156 m. Leaving one *run*
out, the honest split because the efforts of one run are nested inside each other, critical
speed moves from 4.32 to 4.79 m/s.

**Reference.** Critical speed is normally fitted to three to five exhausting trials lasting
about 2 to 15 minutes, run on different days (Jones and Vanhatalo, 2017). The archive has
efforts of the right lengths from only two days, at 82 to 90% of the highest heart rate on
record. The estimate is a bracket, not a measurement.

## Track it

Add one row: `date=2026-05-18`, `test=cs-archive`, `metric=critical_speed_mps`, `value=4.37`,
`unit=m/s`, `device=watch`, `protocol_version=best-efforts-2-15min-v1`, `note=bracket 4.32-4.79`.
When the two-effort test is run, record it as a different test (`cs-two-effort`), not as a new
value of this one.

## With your own data

Put your own runs (one CSV per run with `time`, `distance_m` and `heart_rate_bpm`, one row a
second, Q-16 shows how to make it from a FIT file) in `raw/records/` with a matching
`activities.csv`, and rerun. Check the heart rate of each best effort before you trust it.

## The same method in another field

A straight line through a few points, tested by leaving points out, is a calibration curve. In
a laboratory the same mistake appears when all calibration standards come from one batch:
the fit looks perfect and the next batch disagrees. Leave out whole batches, as this study
leaves out whole runs. See the Machine Learning for Engineers pages on
[linear regression](https://apmonitor.com/pds/index.php/Main/LinearRegression) and
[splitting data](https://apmonitor.com/pds/index.php/Main/SplitData).

## Acknowledgements

Runs recorded by the instructor with his own watch and published under his name in the course
case file. GPS coordinates were removed before publication.

## Action card

- **Finding:** The training archive brackets critical speed between 4.32 and 4.79 m/s (3:51 to 3:29 per km); it does not pin it down.
- **Evidence:** Eight best efforts of 2 to 15 minutes, all from two tempo runs; the answer depends on which run is held out.
- **Sure:** Low for the critical speed itself; high that 4.32 m/s is sustainable, because it was held for 15 minutes at about 82% of the highest heart rate.
- **Action:** Run threshold sessions at about 3:52 per km (4.3 m/s), no faster, until a test narrows the bracket.
- **Retest:** Run a two-effort test, about 3 and 12 minutes all-out on separate days on a flat route, within the next three weeks.

## Challenge: Two efforts, one line, one held out

The archive could not pin critical speed down because no run was a test. Run the test, or
use your own watch archive, and see how much tighter the answer gets.

1. Run two all-out efforts of about 3 and 12 minutes on a flat route, on separate days, after the same warm-up (or find your own archive's best efforts with this notebook).
2. Fit critical speed and D′ from the two efforts by hand and in code (Section 6.5's example).
3. Add a third effort of about 6 minutes on another day, and use it as the held-out test of the two-effort line.
4. Compare with the bracket from your archive, if you have one, and decide on a threshold pace.

Deliverables:

- a notebook with the efforts, the fit and the held-out prediction
- a plot of distance against time with the line and the held-out point
- an action card with a threshold pace and when to retest

## References

- Jones, A. M., and Vanhatalo, A. (2017). The 'critical power' concept: applications to sports performance with a focus on intermittent high-intensity exercise. *Sports Medicine*, 47(Suppl 1), 65–78. [doi:10.1007/s40279-017-0688-0](https://doi.org/10.1007/s40279-017-0688-0)
- Smyth, B., and Muniz-Pumares, D. (2020). Calculation of critical speed from raw training data in recreational marathon runners. *Medicine & Science in Sports & Exercise*, 52(12), 2637–2645. [doi:10.1249/MSS.0000000000002412](https://doi.org/10.1249/MSS.0000000000002412)
- *Data-Driven Athletics*, Chapter 2, Thresholds (Section 2.5), and Chapter 6, Activity Files (6.3) and Pace, Economy and the Speed–Duration Curve (6.5).

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