# Q-40: Export a run from the running simulator and read it

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

Web page: https://apopt.com/course/tutorials/q40-running-sim-export/ · Data: https://apopt.com/data/tutorials/q40-running-sim-export/

## The decision

A runner wants to know whether a pace can be held, and for how long if it cannot. A simulated
step test answers both, and because the simulator also logs what it knows, you can see how
close each method gets.

## The raw data

- `raw/treadmill-runner_20261202_221900.csv`: SIMULATED: the running simulator's CSV export of scenario 2 (A speed step by hand), one row a second for 24.5 minutes, 124 columns, exactly as the Export CSV button writes it [Running simulator](https://apmonitor.com/apps/treadmill-runner/), recreational male preset, scenario 2 · A speed step by hand (seeded, so every run of the scenario gives the same file).

### A treadmill you can run in a browser

The [running simulator](https://apmonitor.com/apps/treadmill-runner/) puts a modeled runner on
a treadmill. You set the belt speed; the model answers with heart rate, blood lactate, oxygen
uptake, core temperature, fuel and an anaerobic reserve, once a second. Its **Export CSV**
button writes every logged second to a file. This page reads one such file.

The file comes from the simulator's scenario **2 · A speed step by hand**: a minute standing,
then the belt steps to 9.4 km/h, and at 15 minutes it steps to 11.2 km/h and stays there until
the runner drifts off the back of the belt. The runner is the simulator's recreational male
preset. Every number is **simulated**. That is the point of the exercise: the file holds both
what a sensor would read (`hr_meas_bpm`, with noise) and what the model knows and no real test
can give you (`hr_bpm`, the true value, and `wp_J`, the anaerobic reserve). You can check each
method against the truth.

To make the file yourself: open the simulator, choose that scenario, press **Run** (the fastest
speed is fine), wait for the runner to go off the back, and press **Export CSV**.

*Predict first:* The run lasts about 24.5 minutes, logged once a second. How many rows do you expect?

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

raw = pd.read_csv("raw/treadmill-runner_20261202_221900.csv", comment="#")   # 2 header lines start with #
tcol = raw.columns[0]                     # the app picks the time unit from the run's length
scale = {"Time (s)": 1, "Time (min)": 60, "Time (h)": 3600}[tcol]
print(f"{raw.shape[0]} rows, {raw.shape[1]} columns; time column '{tcol}'")

run = pd.DataFrame({
    "t_s": (raw[tcol] * scale).round(2),
    "speed_kmh": raw["speed_kmh"],
    "hr_bpm": raw["hr_meas_bpm"],         # what a chest strap would read
    "lac_mmol": raw["lac_meas_mmol"],     # what a lactate meter would read
    "hr_true": raw["hr_bpm"],             # the model's own value: no real test has it
    "reserve_J": raw["wp_J"],             # the anaerobic reserve, also hidden in real life
})
print(run.describe().loc[["min", "max"]].round(1).to_string())
print(f"the run ended at {run.t_s.iloc[-1]:.0f} s after {raw['dist_km'].iloc[-1]:.2f} km")
```

Output:

```
1470 rows, 124 columns; time column 'Time (min)'
        t_s  speed_kmh  hr_bpm  lac_mmol  hr_true  reserve_J
min     0.0        0.0    59.6       0.9     60.0      206.4
max  1468.2       11.2   178.1       6.1    177.4    59137.5
the run ended at 1468 s after 3.93 km
```

A one-second log of 24.5 minutes is 1,470 rows. The export has 124 columns: the settings
(`param_…`), the controllers (`ctrl_…`), scores (`metric_…`) and the signals. Reading the header
for the time unit matters: a run under a minute is written in seconds and a run over an hour in
hours, so a fixed `* 60` would be wrong for someone else's file.

### Look before you fit

```python
import matplotlib.pyplot as plt

m = run.t_s / 60
fig, ax = plt.subplots(3, 1, figsize=(6.4, 5.4), sharex=True)
ax[0].plot(m, run.speed_kmh, "k-")
ax[1].plot(m, run.hr_bpm, ".", color="0.6", ms=2, label="strap (noisy)")
ax[1].plot(m, run.hr_true, "k-", lw=1, label="model's true value")
ax[2].plot(m, run.lac_mmol, "k-")
ax[0].set_ylabel("belt (km/h)")
ax[1].set_ylabel("heart rate (bpm)")
ax[2].set_ylabel("lactate (mmol/L)")
ax[2].set_xlabel("time (min)")
ax[1].legend(loc="lower right", fontsize=8)
for a in ax:
    a.axvline(15, color="k", ls=":", lw=1)
plt.tight_layout()
print(f"heart rate at 14.9 min {run.hr_bpm[run.t_s.between(890, 899)].mean():.0f} bpm, "
      f"at 24 min {run.hr_bpm[run.t_s.between(1435, 1445)].mean():.0f} bpm")
```

Output:

```
heart rate at 14.9 min 156 bpm, at 24 min 177 bpm
```

![Three stacked panels against minutes, 0 to 25. Top, belt speed steps from 0 to 9.4 km/h at 1 minute and to 11.2 km/h at 15 minutes. Middle, heart rate climbs from 60 to about 156 beats per minute and levels off, then climbs again to about 177. Bottom, lactate rises to about 3 mmol/L and levels off in the first stage, then climbs without leveling to about 6.1 in the second.](https://apopt.com/course/tutorials/q40-running-sim-export/c03-1.png)

Both curves bend toward a level in the first stage. In the second, heart rate nearly levels
off but lactate keeps climbing. Heart rate alone would not tell you the second stage was too
fast.

### How fast does heart rate answer?

Q-6 fitted a first-order response. The belt takes a few seconds to reach speed and the heart
lags behind the legs, so this fit adds a **dead time** θ (theta), a delay before the curve starts.

*Predict first:* Q-6's synthetic runner had a 35 s time constant. Longer or shorter here?

```python
from scipy.optimize import curve_fit

def fopdt(t, y0, gain, tau, theta):
    x = np.clip(t - 60 - theta, 0, None)          # the belt starts at 60 s
    return y0 + gain * (1 - np.exp(-x / tau))

st1 = run[(run.t_s >= 60) & (run.t_s < 900)]
fits = {}
for col in ["hr_bpm", "hr_true"]:
    p, cov = curve_fit(fopdt, st1.t_s, st1[col], p0=(60, 90, 60, 10))
    se = np.sqrt(np.diag(cov))
    fits[col] = p
    print(f"{col:7s} gain {p[1]:.1f} bpm, tau {p[2]:.1f} +/- {se[2]:.1f} s, "
          f"dead time {p[3]:.1f} s")
gain, tau, theta = fits["hr_bpm"][1:]
print(f"strap: within 5% of the new level {(theta + 3 * tau) / 60:.1f} min after the belt starts")
```

Output:

```
hr_bpm  gain 92.9 bpm, tau 67.6 +/- 0.3 s, dead time 30.6 s
hr_true gain 92.4 bpm, tau 67.6 +/- 0.3 s, dead time 24.7 s
strap: within 5% of the new level 3.9 min after the belt starts
```

The noisy strap and the true value give the same time constant, 68 s, to within its standard
error: one-second noise of about 1 bpm averages out over 840 points. The dead time does not
agree: 31 s for the strap and 25 s for the true value. The simulated strap smooths its readings
with a 6 s filter, as a real one smooths its beat-to-beat values, and smoothing delays a signal.
In the chart above the gray dots run just to the right of the black line on the climb. Three
time constants after the delay, heart rate is within 5% of its new level: about four minutes
after the belt starts, so a heart rate read in the first three minutes of a stage is too low.

### Steady or not, and how long is left?

A stage is below the threshold if lactate levels off. Measure that as the slope over the last
five minutes of each stage. Then use the critical-speed model of Section 6.5:
t_lim = D′ / (v − CS). The export carries both numbers: `speed_sus_mps` is the model's critical
speed and `param_dprime_m` its D′.

*Predict first:* At 11.2 km/h, about how many minutes can the runner last?

```python
for a, b in [(600, 900), (1140, 1440)]:
    w = run[(run.t_s >= a) & (run.t_s < b)]
    slope = np.polyfit(w.t_s / 60, w.lac_mmol, 1)[0]
    print(f"{a / 60:.0f}-{b / 60:.0f} min at {w.speed_kmh.iloc[0]:.1f} km/h: lactate "
          f"{slope:+.2f} mmol/L per min")

i = run.index[run.t_s == 900][0]                 # the moment of the second step
cs = raw["speed_sus_mps"].iloc[i]
dprime = raw["param_dprime_m"].iloc[i]
v = raw["speed_mps"].iloc[i + 10]                # the belt's new speed
t_lim = dprime / (v - cs)
print(f"CS {cs * 3.6:.2f} km/h, D' {dprime:.0f} m, belt {v * 3.6:.2f} km/h")
print(f"forecast: off the back at {(900 + t_lim) / 60:.1f} min; "
      f"the simulator says {run.t_s.iloc[-1] / 60:.1f} min")
```

Output:

```
10-15 min at 9.4 km/h: lactate +0.07 mmol/L per min
19-24 min at 11.2 km/h: lactate +0.24 mmol/L per min
CS 10.03 km/h, D' 190 m, belt 11.16 km/h
forecast: off the back at 25.1 min; the simulator says 24.5 min
```

The first stage gains 0.07 mmol/L a minute, close to level; the second gains 0.24, more than
three times as fast. The critical-speed forecast says 25.1 minutes and the runner actually went
off at 24.5, 38 s early. The miss has a cause you can find in the file: the model's critical
speed is not fixed. Plot `speed_sus_mps` and you will see it fall from 10.03 to 9.77 km/h as the
runner heats up and tires, so the reserve drains a little faster than the forecast assumed.

**For the athlete:** "At 9.4 km/h your lactate settles near 3 mmol/L and you could hold it; at
11.2 km/h it never settles, and you have about ten minutes before you must slow down."

## With your own data

Make your own export and test a prediction. In the running simulator switch the units to SI,
choose scenario **2 · A speed step by hand** and press Run. When the second step lands at
15 minutes, press Pause, set **Belt speed** to about 10.6 km/h, and write down when
t_lim = D′ / (v − CS), with this page's CS and D′, says the runner will go off the back. Press
Run, wait, export, and load your file here in place of the one above. Is your miss bigger or
smaller than 38 s, and why?

## The same method in another field

A first-order fit with a dead time is how process engineers describe a heat exchanger or a
tank level after a valve moves; the same three numbers (gain, time constant, delay) tune its
controller. The simulator's own scenarios tune a heart-rate controller from them. See the
[Dynamic Data Engineering course](https://apmonitor.com/dde) for the same fit on plant data.

## Acknowledgements

Data made with the running simulator at apmonitor.com/apps/treadmill-runner.

## References

- Chapter 2 of *Data-Driven Athletics*: The Response to a Step; Thresholds.
- Chapter 6 of *Data-Driven Athletics*: Critical speed.

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