# CS-8: Find a lactate threshold, and see if it moved

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

Web page: https://apopt.com/course/tutorials/cs08-lactate-threshold/ · Data: https://apopt.com/data/tutorials/cs08-lactate-threshold/

## The decision

A runner (invented for this study) did a lactate step test, trained for eight weeks, and did
it again. Her coach wants to know: *did the threshold move?* If it did, her threshold sessions
get faster; if the tests cannot tell, the paces stay and the testing plan changes.

## Predict first

Training raised her lactate clearance capacity by 10%. Predict how far her true threshold speed moved, and whether one test before and one after will show it.

## The raw data

- `raw/steptests_simulated.csv`: SIMULATED step tests of an invented runner, A (2027-01-11) and B (2027-03-08): one row per 3-minute stage (test, date, stage, speed_kmh, stage_min, lactate_mmol, note); one reading of B is missing Made by this study's `prepare.py` from the production–clearance model of Section 7.4 with stated parameters, meter noise and day-to-day variation. No person was tested.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| test | which test | — | A or B | none |
| date | test date (invented) | YYYY-MM-DD | 2027-01-11 and 2027-03-08 | none |
| stage | stage number | count | 1–8 | none |
| speed_kmh | treadmill speed for the stage | km/h | 10–17 | none |
| stage_min | stage length | min | 3 | none |
| lactate_mmol | simulated blood lactate at the end of the stage | read to 0.1 | mmol/L | 0.7–8.3 | empty when no reading |
| note | what happened at the stage | text | — | empty |

What is wrong with it: the data are simulated, so they hold only the faults that were put in.
Those are meter noise (standard deviation 0.1 mmol/L plus 4% of the value), readings rounded to
0.1 mmol/L, a 2% day-to-day variation in production, and one failed strip in test B. Real tests
add more: stage timing, sampling technique, diet and sleep before the test, and the meter
itself. The stage length, 3 minutes, is short enough that lactate near the threshold has not
reached its steady value when it is sampled.

**Every number in this study is simulated.** There are no real step tests in the course
files, and nobody in the course is asked to give blood. Instead, two step tests of one
invented runner were generated from the production–clearance model of Section 7.4, with the
meter noise and day-to-day variation a real test has. That has one large advantage: the true
threshold is known, so you can see which threshold rules find it.

### Step 1 · Gather

*Predict first:* Between the tests the runner trained for eight weeks and her clearance capacity rose by 10%. How far do you think her threshold speed moved, in km/h?

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

raw = pd.read_csv("raw/steptests_simulated.csv")
print(raw.fillna({"note": ""}).to_string(index=False))
```

Output:

```
test       date  stage  speed_kmh  stage_min  lactate_mmol                    note
   A 2027-01-11      1       10.0          3           0.7                        
   A 2027-01-11      2       11.0          3           0.7                        
   A 2027-01-11      3       12.0          3           0.9                        
   A 2027-01-11      4       13.0          3           0.8                        
   A 2027-01-11      5       14.0          3           1.4                        
   A 2027-01-11      6       15.0          3           2.0                        
   A 2027-01-11      7       16.0          3           4.1                        
   A 2027-01-11      8       17.0          3           8.3                        
   B 2027-03-08      1       10.0          3           0.9                        
   B 2027-03-08      2       11.0          3           0.8                        
   B 2027-03-08      3       12.0          3           NaN strip error, no reading
   B 2027-03-08      4       13.0          3           1.2                        
   B 2027-03-08      5       14.0          3           1.2                        
   B 2027-03-08      6       15.0          3           2.1                        
   B 2027-03-08      7       16.0          3           3.6                        
   B 2027-03-08      8       17.0          3           8.2
```

Each test is a row per 3-minute stage, from 10 km/h upward by 1 km/h, stopped after the first
stage above 6 mmol/L. One reading of test B is missing: the strip failed.

### Step 2 · Statistics

```python
prof = raw.groupby("test").agg(date=("date", "first"), stages=("stage", "count"),
                               readings=("lactate_mmol", "count"), lowest=("lactate_mmol", "min"),
                               highest=("lactate_mmol", "max"), top_speed=("speed_kmh", "max"))
print(prof.to_string())
```

Output:

```
            date  stages  readings  lowest  highest  top_speed
test                                                          
A     2027-01-11       8         8     0.7      8.3       17.0
B     2027-03-08       8         7     0.8      8.2       17.0
```

Both tests reached 17 km/h and stopped there, above 6 mmol/L. The lowest readings differ (0.7
against 0.8 mmol/L), which matters for any rule that starts from the lowest value.

### Step 3 · Visualize, and Step 4 · Cleanse

The cleaning rule is short and written first: a stage without a reading is left out, never
filled in, because every threshold rule below interpolates between stages anyway, and a filled
value would be a guess dressed as a measurement.

```python
import matplotlib.pyplot as plt
import os

clean = raw.dropna(subset=["lactate_mmol"]).reset_index(drop=True)
os.makedirs("clean", exist_ok=True)
clean.to_csv("clean/steptests_simulated_clean.csv", index=False)
print(f"kept {len(clean)} of {len(raw)} stages; left out: "
      f"{raw.loc[raw['lactate_mmol'].isna(), ['test', 'speed_kmh', 'note']].values.tolist()}")
fig, ax = plt.subplots(figsize=(6.4, 3.6))
for (name, g), m in zip(clean.groupby("test"), ["o-", "s--"]):
    ax.plot(g["speed_kmh"], g["lactate_mmol"], m, mfc="none", color="k", label=f"test {name} ({g['date'].iloc[0]})")
ax.set(xlabel="speed (km/h)", ylabel="blood lactate (mmol/L), simulated")
ax.legend(loc="upper left")
plt.tight_layout()
```

Output:

```
kept 15 of 16 stages; left out: [['B', 12.0, 'strip error, no reading']]
```

![Simulated blood lactate in mmol/L against speed in km/h for test A (circles) and test B (squares). Both stay near 1 mmol/L to 14 km/h and bend upward; at 16 km/h B reads 3.6 against 4.1 for A, and both reach about 8 at 17 km/h.](https://apopt.com/course/tutorials/cs08-lactate-threshold/c05-1.png)

The two curves nearly overlap. Test B reads a little lower at 16 km/h (3.6 against 4.1) and
the same at 17. Whether there is a real shift under that noise is the question of this study.

### Step 5 · Features: four threshold rules

A threshold is a rule applied to the curve, and there are dozens (Faude and colleagues
counted 25 concepts in three families). Four common ones:

* **Fixed 2.0** and **fixed 4.0**: the speed where lactate crosses 2.0 or 4.0 mmol/L.
* **Baseline + 1.0**: the speed where it rises 1.0 mmol/L above the lowest reading.
* **Dmax**: fit a smooth curve (exponential plus a constant), draw the straight line from its
  first to its last point, and take the speed where the curve lies farthest below that line.

*Predict first:* Which rule do you expect to give the highest speed, and which the lowest?

```python
from scipy.optimize import curve_fit

def cross(v, lac, level):
    i = int(np.argmax(lac >= level))                       # first stage at or above the level
    return v[i - 1] + (level - lac[i - 1]) * (v[i] - v[i - 1]) / (lac[i] - lac[i - 1]) if i else np.nan

def dmax(v, lac):
    f = lambda x, a, b, c: a + b * np.exp(c * (x - 10))
    p, _ = curve_fit(f, v, lac, p0=(1, 0.05, 1), maxfev=5000)
    x = np.linspace(v[0], v[-1], 601)
    line = f(v[0], *p) + (f(v[-1], *p) - f(v[0], *p)) * (x - v[0]) / (v[-1] - v[0])
    return x[np.argmax(line - f(x, *p))]

RULES = {"fixed 2.0": lambda v, l: cross(v, l, 2.0), "fixed 4.0": lambda v, l: cross(v, l, 4.0),
         "baseline + 1.0": lambda v, l: cross(v, l, l.min() + 1.0), "Dmax": dmax}
found = pd.DataFrame({t: {r: f(g["speed_kmh"].to_numpy(), g["lactate_mmol"].to_numpy()) for r, f in RULES.items()}
                      for t, g in clean.groupby("test")})
found["B - A"] = found["B"] - found["A"]
print(found.round(2).to_string())
```

Output:

```
                    A      B  B - A
fixed 2.0       15.00  14.89  -0.11
fixed 4.0       15.95  16.09   0.13
baseline + 1.0  14.50  14.67   0.17
Dmax            14.88  15.02   0.14
```

The four rules spread over 1.45 km/h on the same test (14.50 to 15.95 km/h on test A), and
they disagree on the change too: from −0.11 to +0.17 km/h. A coach who switched rules between
tests could report almost any change. The rule must be fixed before the first test.

Which, if any, is right? In real life nobody knows. Here the model is known, so ask it.

### Step 5 · The model behind the curves

Lactate is made all the time and used all the time: it is a major fuel for other tissues and
the main raw material from which the liver makes glucose (Brooks, 2018). Section 7.4 writes
blood lactate as a tank: V dL/dt = P − R(L). Production P rises with speed
as faster fibres are recruited; clearance R grows with L but saturates at a ceiling, Rmax.
While P stays below Rmax, lactate settles at a steady value, L* = K·P / (Rmax − P). Above it,
no steady state exists and lactate climbs for as long as the pace is held. The speed where
P = Rmax is the true threshold of this runner, the highest speed with a steady state. The
simulation used K = 0.5 mmol/L and Rmax = 3.0 mmol/L per minute before training, 3.3 after (10%
more clearance, a size chosen for illustration; MacRae and colleagues found higher lactate clearance
after nine weeks of endurance training).

```python
from scipy.optimize import brentq

K, RMAX = 0.5, {"A": 3.0, "B": 3.3}
P = lambda v: 1.9 + 0.05 * np.exp(0.55 * (v - 10))         # production, mmol/L per min
true = {t: brentq(lambda v: P(v) - r, 10, 20) for t, r in RMAX.items()}
print(f"true threshold: A {true['A']:.2f}, B {true['B']:.2f} km/h; moved {true['B'] - true['A']:+.2f} km/h")
print(f"true steady-state lactate at the true threshold minus 0.5 km/h (A): "
      f"{K * P(true['A'] - 0.5) / (RMAX['A'] - P(true['A'] - 0.5)):.1f} mmol/L")
fig, ax = plt.subplots(1, 2, figsize=(9, 3.6))
for (t, r), ls in zip(RMAX.items(), ["-", "--"]):
    v = np.linspace(10, true[t] - 0.02, 300)
    ax[0].plot(v, K * P(v) / (r - P(v)), ls, color="k", label=f"steady state, {t}")
    ax[0].axvspan(true[t], 18, alpha=0.12)
    g = clean[clean["test"] == t]
    ax[0].plot(g["speed_kmh"], g["lactate_mmol"], "o" if t == "A" else "s", mfc="none", label=f"step test {t}")
ax[0].set(xlim=(10, 18), ylim=(0, 10), xlabel="speed (km/h)", ylabel="lactate (mmol/L)", title="shaded: severe domain"); ax[0].legend(fontsize=8, loc="upper left")
for dv, ls in zip([-0.5, -0.1, 0.4], ["-", "--", ":"]):
    L, trace = 1.0, []
    for _ in range(30 * 60):                                 # 30 min in 1-s steps
        L += (P(true["A"] + dv) - RMAX["A"] * L / (K + L)) / 60
        trace.append(L)
    ax[1].plot(np.arange(1, 1801) / 60, trace, ls, color="k", label=f"{true['A'] + dv:.1f} km/h")
ax[1].set(xlabel="time (min)", ylabel="lactate (mmol/L)", title="test A runner, steady runs"); ax[1].legend(fontsize=8)
plt.tight_layout()
```

Output:

```
true threshold: A 15.62, B 16.06 km/h; moved +0.44 km/h
true steady-state lactate at the true threshold minus 0.5 km/h (A): 5.2 mmol/L
```

![Two panels. Left, steady-state lactate against speed for the model before (solid) and after training (dashed), each rising steeply to a vertical asymptote at its true threshold, 15.62 and 16.06 km/h, with the simulated step-test readings as points; the region above each threshold is shaded as the severe domain. Right, lactate against time for 30-minute runs before training at 15.1, 15.5 and 16.0 km/h: the first flattens toward a plateau, the second is still climbing at 30 minutes, the third climbs steeply.](https://apopt.com/course/tutorials/cs08-lactate-threshold/c09-1.png)

The true threshold moved by +0.44 km/h. On the right, half a kilometre an hour below it
lactate flattens toward its steady value of 5.2 mmol/L; a little closer, at 15.5 km/h, it is
still climbing after 30 minutes; above the threshold it never stops rising. Far below the
threshold, at easy speeds, lactate settles within a few minutes. These are the three intensity
domains that physiologists describe for lactate and oxygen uptake: a quick steady state
(moderate), a late and high one (heavy), and none at all (severe). In people the boundary
between heavy and severe is critical power, or critical speed for a runner (CS-7), and the
maximal lactate steady state measured with blood sits on average about 7% below it (Jones and
colleagues, 2019). The model has one boundary, the true threshold here; where its curve
"first rises" is a matter of definition, which is one reason the rules disagree.

No rule found the true threshold of test A (15.62 km/h): three fell 0.6 to 1.1 km/h below it
and fixed 4.0 landed 0.3 above. Nothing in the model makes 4.0 special; with other parameters a
different rule would land closest. With 3-minute stages the blood has no time to reach its
steady value near the threshold, so each reading there is below the steady state at that
speed. Change the stage length in the model below and watch the curve move.

### Step 5 · How much does a threshold move between two tests of the same runner?

Before saying the threshold moved, you need the typical error of each rule: how much it
changes between two tests when nothing has changed. With a model, that is easy. Run test A
300 times with fresh meter noise and fresh day-to-day variation, and see how much each rule
scatters.

*Predict first:* Which rule will scatter most between repeat tests of an unchanged runner?

```python
def simulate(rmax, day, noise=None):                     # many step tests at once, 3-min stages
    L, read = np.ones(len(day)), []
    for v in np.arange(10.0, 18.0):
        for _ in range(180):
            L = L + (day * P(v) - rmax * L / (K + L)) / 60
        read.append(L if noise is None else np.round(L + noise.normal(0, 0.1 + 0.04 * L), 1))
    return np.array(read).T

def apply_rules(x):
    k = int(np.argmax(x > 6)) + 1 if (x > 6).any() else len(x)    # the stop rule
    return {r: f(np.arange(10.0, 10.0 + k), x[:k]) for r, f in RULES.items()}

rng = np.random.default_rng(1)
rep = pd.DataFrame([apply_rules(x) for x in simulate(RMAX["A"], 1 + rng.normal(0, 0.02, 300), rng)])
te = rep.std()
ideal = {t: apply_rules(simulate(RMAX[t], np.ones(1))[0]) for t in RMAX}     # no noise at all
print(pd.DataFrame({"mean (km/h)": rep.mean(), "typical error (km/h)": te, "as % of mean": 100 * te / rep.mean(),
                    "change without noise": pd.Series(ideal["B"]) - pd.Series(ideal["A"])}).round(2).to_string())
```

Output:

```
                mean (km/h)  typical error (km/h)  as % of mean  change without noise
fixed 2.0             14.49                  0.26          1.77                  0.66
fixed 4.0             15.83                  0.16          0.98                  0.38
baseline + 1.0        14.29                  0.26          1.84                  0.52
Dmax                  14.87                  0.09          0.58                  0.09
```

In the simulation each rule repeats within 0.09 to 0.26 km/h, under 2% of the speed. That is
the noise that was put in, and no more. Real repeat tests are noisier: in 17 recreational
runners tested twice in the same way, the threshold speed repeated with a coefficient of
variation of 3.7% to 5.8%, depending on the curve model, and 5.4% for a fixed 3.5 mmol/L rule
(Camargo Alves and colleagues, 2016). A simulation shows how the noise you know about
propagates; it cannot tell you about the noise you left out.

The last column is what each rule would report with no noise at all: +0.09 to +0.66 km/h for
a true change of +0.44. Even a perfect measurement depends on the rule.

### Step 5 · Did it move?

Use the decision rule of Section 11.1. The coach and runner agreed beforehand that 0.2 km/h
is worth having. For each rule, the noise in a change between two single tests is √2 × the
typical error. Use two typical errors: the simulation's, and 4% of the speed, from real
repeat tests.

```python
from scipy.stats import norm

SWC = 0.2
rows = []
for r in RULES:
    delta = found.loc[r, "B - A"]
    for source, e in (("simulation", te[r]), ("real tests, 4%", 0.04 * found.loc[r, "A"])):
        noise = np.sqrt(2) * e
        gain, loss = 1 - norm.cdf((SWC - delta) / noise), norm.cdf((-SWC - delta) / noise)
        rows.append({"rule": r, "TE from": source, "change": delta, "gain": gain, "trivial": 1 - gain - loss, "loss": loss})
print(pd.DataFrame(rows).round(2).to_string(index=False))
```

Output:

```
          rule        TE from  change  gain  trivial  loss
     fixed 2.0     simulation   -0.11  0.20     0.40  0.40
     fixed 2.0 real tests, 4%   -0.11  0.36     0.18  0.46
     fixed 4.0     simulation    0.13  0.38     0.55  0.06
     fixed 4.0 real tests, 4%    0.13  0.47     0.17  0.36
baseline + 1.0     simulation    0.17  0.46     0.37  0.16
baseline + 1.0 real tests, 4%    0.17  0.48     0.19  0.33
          Dmax     simulation    0.14  0.31     0.69  0.00
          Dmax real tests, 4%    0.14  0.47     0.19  0.34
```

The measured changes, −0.11 to +0.17 km/h, are smaller than any rule's noise-free change.
The two test days were different: `prepare.py` gave test A a day with production 3.5% below
average and test B a day 2.8% above, and that hid most of the gain. Even with the
simulation's small errors no rule gives better than "possibly" (at most a 46% chance of a
worthwhile gain), and with the error of real tests every rule sits near even odds. A true gain
of +0.44 km/h, under 3% of the speed, cannot be seen in one test before and one after when a
single test varies by about 4%. That is the finding, and it is about the measurement, not the
runner. To see a change of this size, test twice each time with the rule and stage length
fixed, or wait longer so the change can grow.

**Without blood.** Most athletes will never have a step test. Critical speed from a watch (CS-7)
aims at the heavy–severe boundary itself (Jones and colleagues, 2019). The talk test aims
lower: in 15 people the lactate threshold sat close to the last stages at which they answered
"yes" or "yes, but" to "can you speak comfortably?" (Quinn and Coons, 2011). Section 7.4 rates four such methods; each has
its own typical error, and the same arithmetic decides whether a change is real.

## How good is the number?

**Against the truth.** On test A the rules gave 14.50 to 15.95 km/h against a true threshold of
15.62: three below it by 0.6 to 1.1 km/h, fixed 4.0 above it by 0.3. That ordering is a
property of the chosen model, not a law.

**Repeat tests.** Simulated repeat tests of an unchanged runner scatter by 0.09 to 0.26 km/h
(under 2%), depending on the rule. Real repeat tests scatter more: a coefficient of variation
of 3.7% to 5.8% in 17 recreational runners (Camargo Alves and colleagues, 2016). The simulation
can only show the noise that was put into it.

**The decision.** With a worthwhile change of 0.2 km/h and noise of √2 × the typical error, no
rule gives more than a 48% chance of a worthwhile gain from these two tests. The honest answer
is "unclear".

## Track it

Nothing from this study goes into a real athlete's record: the data are simulated. With real
step tests, add one row per test and name the rule in the metric:
`test=lactate-step-3min, metric=speed_at_4mmol_kmh, value, unit=km/h, protocol_version=3min-1kmh-v1`.

## With your own data

If you have real step-test results from a coach or laboratory, put them in the same columns
and apply the four rules and the decision rule. Nobody in this course is required to give
blood; Section 7.4 lists field methods that need none.

## The same method in another field

A simulation with a known answer is how engineers test a measurement method before trusting
it on a real plant: generate data from a model, add the noise you expect, and see whether the
estimator recovers the truth and how often. See the Machine Learning for Engineers notebooks on
[differential equations](https://apmonitor.com/pds/notebooks/11_differential_equations.html)
and [interpolation](https://apmonitor.com/pds/notebooks/09_interpolation.html).

## Acknowledgements

Simulated data; no person was tested. The tank model is the one of *Data-Driven Athletics*
Section 7.4. Training information only, not medical advice.

## Action card

- **Finding:** One test before and one after cannot tell whether her threshold moved; the true gain (+0.44 km/h, known only because this is a simulation) was hidden.
- **Evidence:** The four rules reported −0.11 to +0.17 km/h; with real-test noise of about 4%, every rule gave roughly even odds of a worthwhile gain.
- **Sure:** Sure that the tests cannot decide; the simulated numbers themselves describe an invented runner.
- **Action:** Keep threshold paces where they are, and fix one rule (for example Dmax or fixed 4.0) and one stage length for every future test.
- **Retest:** Test twice, a few days apart, at the end of the next block, and compare the means of two tests.

## Challenge: Design a test that can see the change

One test before and one after could not see a true gain of +0.44 km/h. Use the model to
design a testing plan that can, before anyone gives a drop of blood.

1. Use the simulation of Step 5 to make 300 simulated pairs of tests (before and after training), with the same noise.
2. For one rule, find the share of pairs in which the decision rule says "likely" or better for a gain, with one test each time and with the mean of two.
3. Change the stage length from 3 to 5 and 8 minutes and repeat. Which rule is least biased against the true threshold, and does the bias change the measured gain?
4. Write the testing plan you would give the coach.

Deliverables:

- a notebook with the simulations and a table of detection rates by rule, stage length and number of tests
- one figure of the detection rate against the number of tests
- a testing plan of five lines or fewer

## References

- Faude, O., Kindermann, W., and Meyer, T. (2009). Lactate threshold concepts: how valid are they? *Sports Medicine*, 39(6), 469–490. [doi:10.2165/00007256-200939060-00003](https://doi.org/10.2165/00007256-200939060-00003)
- Brooks, G. A. (2018). The science and translation of lactate shuttle theory. *Cell Metabolism*, 27(4), 757–785. [doi:10.1016/j.cmet.2018.03.008](https://doi.org/10.1016/j.cmet.2018.03.008)
- Jones, A. M., Burnley, M., Black, M. I., Poole, D. C., and Vanhatalo, A. (2019). The maximal metabolic steady state: redefining the 'gold standard'. *Physiological Reports*, 7(10), e14098. [doi:10.14814/phy2.14098](https://doi.org/10.14814/phy2.14098)
- MacRae, H. S., Dennis, S. C., Bosch, A. N., and Noakes, T. D. (1992). Effects of training on lactate production and removal during progressive exercise in humans. *Journal of Applied Physiology*, 72(5), 1649–1656. [doi:10.1152/jappl.1992.72.5.1649](https://doi.org/10.1152/jappl.1992.72.5.1649)
- Camargo Alves, J. C., Segabinazi Peserico, C., Nogueira, G. A., and Machado, F. A. (2016). The influence of the regression model and final speed criteria on the reliability of lactate threshold determined by the Dmax method in endurance-trained runners. *Applied Physiology, Nutrition, and Metabolism*, 41(10), 1039–1044. [doi:10.1139/apnm-2016-0075](https://doi.org/10.1139/apnm-2016-0075)
- Quinn, T. J., and Coons, B. A. (2011). The Talk Test and its relationship with the ventilatory and lactate thresholds. *Journal of Sports Sciences*, 29(11), 1175–1182. [doi:10.1080/02640414.2011.585165](https://doi.org/10.1080/02640414.2011.585165)
- *Data-Driven Athletics*, Chapter 2, Thresholds (2.5); Chapter 7, Lactate (7.4); Chapter 11, One Athlete, Many Days (11.1).

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