<!-- Generated by book/tools/make-index.py from the book source. -->

> Hedengren, J. (Ed.) (2027). Chapter 6: GPS Watches and Motion Sensors. In *Data-Driven Athletics: Measuring, Modeling and Coaching Human Performance with Video and Wearable Data* (pp. 151–181). IRSRI Sports Research Institute. CC BY 4.0.

**Question.** The watch says 10.14 km. The course was measured at 10.00 km. Did the runner run farther, or did the watch?

**Objectives.**
- Explain how a satellite receiver finds its position and why one fix a second limits what pace can show.
- Compute the distance between two fixes by hand, and explain why summed distance runs long when moving slowly and short on tight turns.
- Read an activity file, resample it and clean it, and handle a zero-length time step by an explicit, tested rule.
- Explain what an accelerometer measures and how cadence, contact time and vertical oscillation are derived from it.
- Fit critical speed from two or three time trials as a linear regression, with the slope in units, the residuals and a mean baseline, and use it to set training paces.
- Describe training load over weeks and give a coach a defensible summary.

# 6 GPS Watches and Motion Sensors

A running watch looks like a simple instrument: it shows distance, pace and heart rate, and at the end it draws a map. Inside it are two very different sensors. A *satellite receiver* measures where the watch is, about once a second. An *accelerometer* measures how the watch is shaken, many times a second. Almost every number on the screen is computed from these two, with a model in between. This chapter takes each number apart: where it comes from, what it measures directly, what it estimates, and how wrong it can be. It ends with the slowest-moving number of all, training load over weeks, and with a summary you could hand a coach.

\paragraph{The running example.} One real run is used throughout: a 30-minute easy run recorded by a wrist watch, shared by its owner for this book. The original file is not shipped. What ships is a de-identified table, `data/run.csv`: clock times replaced by seconds from the start, no names or device details, and every position within 500 m of the start or the end removed and every longitude shifted by a fixed amount, so the route does not show where the runner lives (Section 6.3 shows how). A few examples use synthetic data instead, where the true answer must be known; each says so.

## 6.1 Finding Position from Satellites

A navigation satellite carries an atomic clock and broadcasts, over and over, the time and its own position. A receiver on your wrist hears the signal a little after it was sent, because radio travels at the speed of light, about 3e8 m/s. The delay times the speed of light is the distance to that satellite. The general name for these systems is *global navigation satellite systems* (GNSS); GPS is the best-known one, and modern receivers listen to several systems at once.

\paragraph{Ranges to a position.} One range puts you somewhere on a sphere around the satellite. Two ranges narrow that to a circle, three to two points, one of which is far out in space. So three satellites would be enough, if the watch's clock were perfect. It is not: a watch carries a cheap quartz clock, and light travels 0.3 m in a nanosecond, so a clock error of one microsecond is a range error of 300 m. The receiver treats its own clock error as a fourth unknown and solves for it with a fourth satellite (Figure 6.1). This is *trilateration*: position from distances, not from angles.

> **Engineer's note: Four unknowns, four equations.**
> 
> For satellite $i$ at known position $(x_i,y_i,z_i)$ with measured signal delay $\Delta t_i$, the receiver at $(x,y,z)$ with clock error $b$ satisfies
> 
$$> \sqrt{(x-x_i)^2+(y-y_i)^2+(z-z_i)^2} = c\,(\Delta t_i - b),i=1,\dots,4.
>$$

> Four equations, four unknowns. With more than four satellites in view the system is overdetermined and the receiver solves it by least squares, which averages out some of the error in each range. Solving it again every second, with a filter that also predicts where you will be, gives the track you see.

*Figure 6.1. Left: ranges to several satellites meet at the receiver; a fourth range solves for the receiver's clock error. Right: among buildings a signal can arrive by reflection (dashed), along a longer path than the straight line, so its range reads long.*

\paragraph{What spoils a fix.} The ranges are only as good as the signals. Four things matter most in sport.

- **Sky view.** Satellites spread across the sky give ranges from different directions that cross at wide angles, and a sharp fix. A canyon of buildings, a steep valley or a stadium stand hides part of the sky, and the remaining ranges cross at narrow angles, so a small range error becomes a large position error.

- **Reflections.** A signal that bounces off a wall before it reaches you (*multipath*) has traveled farther than the straight line, so its range is too long (Figure 6.1, right).

- **Trees and bodies.** Wet leaves weaken the signal; so does your own body and arm when the watch faces down or sits under a sleeve.

- **Movement and the filter.** The receiver smooths successive fixes with a model of how you move. That helps on straight roads and hurts at sharp turns, where the model expects you to keep going straight.

Receivers that track two frequency bands from each satellite (*multi-band* or dual-frequency receivers) can correct part of the delay that the upper atmosphere adds, and they resist some reflections. In a static engineering test of one phone, the 95th percentile of horizontal error fell from 9.31 m with one band to 3.32 m with two (and to 2.72 m when differential corrections from a nearby station were added as well) . That was a phone standing still, not a runner; Section 6.7 has the status for sport.

\paragraph{Doppler speed.} A satellite's signal arrives at a slightly higher frequency when you move toward it and a lower one when you move away, the Doppler effect you hear in a passing siren. Receivers measure that shift for every satellite and solve for your velocity directly, without differencing positions. In a study of runners and walkers on a straight path, speed from the Doppler shift correlated with true speed at $r = 0.9994$, against $0.9984$ for speed from successive positions, and 90.8% of Doppler values fell within \pm0.1 m/s; on curves speed read slightly low . A receiver can report this Doppler speed directly, and it is a better basis for the pace on the screen than differenced positions; positions still give the map and the distance.

> **Key idea.**
> 
> A satellite receiver measures time; distance to each satellite, position, distance run and pace are all computed from it. Every step of that chain adds error, and the error depends on where you run far more than on which watch you wear.

## 6.2 From Fixes to Distance and Pace

### 6.2.1 The distance between two fixes

A watch stores each *fix* as a latitude and a longitude in degrees. The distance between two fixes along the Earth's surface comes from the *haversine formula*. With latitudes $\varphi_1,\varphi_2$ and longitudes $\lambda_1,\lambda_2$ in radians and $R = \SI{6371}{\kilo\metre}$, the Earth's mean radius,

$$d = 2R\arcsin\sqrt{\sin^2\frac{\varphi_2-\varphi_1}{2} + \cos\varphi_1\cos\varphi_2\,\sin^2\frac{\lambda_2-\lambda_1}{2}}.$$

**Example 6.1: Two fixes one ten-thousandth of a degree apart.**

Two fixes differ by \ang{0.0001} of latitude and not at all in longitude. Then the second term under the root is zero, and $d = 2R\arcsin(\sin(\Delta\varphi/2)) = R\,\Delta\varphi$. In radians $\Delta\varphi = 0.0001\times\pi/180 = \num{1.745e-6}$, so $d = \num{6371000}\times\num{1.745e-6} = \SI{11.1}{\metre}$. A degree of latitude is about 111 km everywhere. A degree of longitude is 111 km times $\cos\varphi$: at \ang{40} of latitude, 85 km.

> **Engineer's note: When a flat map is good enough.**
> 
> Over the few metres between two fixes, the Earth is flat to any precision a watch can reach. Then $\Delta x = R\cos\varphi\,\Delta\lambda$ (east) and $\Delta y = R\,\Delta\varphi$ (north), and $d = \sqrt{\Delta x^2+\Delta y^2}$. This *equirectangular* approximation is also how the build step at the end of the chapter turns a route into pixels. Its most common mistake is to forget the $\cos\varphi$, which stretches every east–west step by $1/\cos\varphi$ (30% at \ang{40}). Exercise 6.21 has an assistant make exactly that mistake.

Listing 6.1 writes Equation \eqref{ch06-gps-motion:eq:haversine} as a NumPy function, checks it against Example 6.1, and sums it over the example run. It compares only steps where both ends have a fix, because the de-identified file has no positions near the start and end.

**Listing 6.1.** Haversine distance, checked by hand, then summed over the run (`code/distance.py`)

```python
import numpy as np, pandas as pd
R = 6_371_000.0                                # mean Earth radius, m

def haversine(lat1, lon1, lat2, lon2):
    p1, p2 = np.radians(lat1), np.radians(lat2)
    dp, dl = p2 - p1, np.radians(lon2 - lon1)
    a = np.sin(dp / 2)**2 + np.cos(p1) * np.cos(p2) * np.sin(dl / 2)**2
    return 2 * R * np.arcsin(np.sqrt(a))

print(f"{haversine(40.0, -111.0, 40.0001, -111.0):.2f} m")   # hand check

run = pd.read_csv("data/run.csv")
a, b = run.iloc[:-1].reset_index(), run.iloc[1:].reset_index()
ok = a.lat.notna().values & b.lat.notna().values   # both ends have a fix
step = haversine(a.lat, a.lon, b.lat, b.lon)[ok]
dev = (b.dist_m - a.dist_m)[ok]
print(f"{ok.sum()} steps: positions {step.sum():.0f} m, device {dev.sum():.0f} m")
print(f"difference {100 * (step.sum() / dev.sum() - 1):+.1f}%")
```

```text
11.12 m
1492 steps: positions 4840 m, device 4836 m
difference +0.1%
```

Over those 1492 one-second steps, the sum of distances between fixes and the watch's own distance field agree within 0.1%. The watch has already filtered its fixes before storing them, and its distance is built from the same filtered track. The agreement says the arithmetic is right. It does not say either number is the true distance run; for that you need a measured course (Section 6.7).

### 6.2.2 Why summed distance runs long, and short

Each fix is the true position plus an error of a few metres. When you add up the straight lines between fixes, the errors do not cancel. A runner moving 3.3 m in a second, with fixes each off by a few metres in random directions, gets a zigzag line that is longer than the true path. The slower you move compared with the size of the position error, the worse this is. Walking is worse than running, and standing still at a traffic light adds distance while you go nowhere. The effect has been worked out in theory and confirmed with data: summed distance from noisy positions is biased upward, and the bias shrinks when the error in one fix is strongly correlated with the error in the next .

Real receiver errors are correlated. They wander slowly, because the same satellites, the same reflections and the same filter shape fix after fix. Listing 6.2 shows how much that matters. It moves a runner in a straight line at 3.33 m/s for 20 minutes and adds position errors with a standard deviation of 3 m in each direction, first independent from second to second, then wandering, with a correlation of 0.99 from one second to the next.

**Listing 6.2.** Synthetic track: the same 3 m error, independent or wandering (`code/noise.py`)

```python
import numpy as np
rng = np.random.default_rng(6)
v, T, sd = 3.33, 1200, 3.0                     # m/s, s, m of error per axis
x = v * np.arange(T + 1.0)                     # true path: straight, 3996 m
y = np.zeros_like(x)

def wander(rho):                               # error with correlation rho per s
    e = np.zeros((T + 1, 2)); e[0] = rng.normal(0, sd, 2)
    for k in range(1, T + 1):
        e[k] = rho * e[k-1] + rng.normal(0, sd * np.sqrt(1 - rho**2), 2)
    return e

for rho in (0.0, 0.99):
    e = wander(rho)
    px, py = x + e[:, 0], y + e[:, 1]
    step = np.hypot(np.diff(px), np.diff(py))
    s10 = np.hypot(px[10:] - px[:-10], py[10:] - py[:-10]) / 10
    print(f"rho {rho}: distance {step.sum():.0f} m ({100*(step.sum()/x[-1]-1):+.0f}%), "
          f"speed SD 1 s {step.std():.2f}, 10 s {s10.std():.2f} m/s")
```

```text
rho 0.0: distance 7404 m (+85%), speed SD 1 s 3.03, 10 s 0.41 m/s
rho 0.99: distance 4036 m (+1%), speed SD 1 s 0.43, 10 s 0.14 m/s
```

With independent errors the summed distance is 85% long and one-second speed is useless: its scatter (3.03 m/s) is as large as the speed itself. With wandering errors of the same size the distance is 1% long and one-second speed scatters by 0.43 m/s. Real receivers sit between the two cases, much nearer the second, which is why watches give believable distances at all. Figure 6.2 shows one lap of a track recorded both ways.

*Figure 6.2. One synthetic 400 m lap in lane 1 at 3.33 m/s, fixes once a second (`code/make_figure_data.py`). The thin gray line is the true lane. Left: 3 m errors independent from fix to fix; the joined fixes measure 744 m. Right: errors of the same size that wander slowly; the joined fixes measure 403 m, but the whole lap is shifted and bent.*

> **Check it by hand: Why one second is too short.**
> 
> At 5:00 per km a runner covers $1000/300 = 3.33 m$ a second. If each fix has an independent error with a standard deviation of 3 m along the direction of travel, the difference of two fixes has an error of $3\sqrt2 = 4.2 m$: more than the distance moved. Over ten seconds the runner moves 33.3 m and the error is still 4.2 m, so the speed is off by $4.2/33.3 = 13%$ (one standard deviation). Over a minute it is 2%. Averaging over time is the only cure, and its price is lag.

Measured one-second speeds tell the same story. In a test of a receiver carried on a bicycle, checked against a calibrated speedometer, 45% of speed values were within 0.2 m/s of the true speed and a further 19% within 0.4 m/s . A pace of 5:00 per km is 3.33 m/s; an error of 0.2 m/s makes it read anywhere from 4:43 to 5:19.

\paragraph{Turns.} Fixes taken once a second cut every corner: the watch joins them with straight chords, and a chord is shorter than its arc. On a running track the effect is tiny, because the bend radius is about 37 m and a runner turns only about \ang{5} between fixes. In tight turns it is not: receivers underestimated speed on circular paths, most on those of small radius . Smoothing makes it worse, because a smoothed track takes the inside of every bend. So the summed distance has two biases in opposite directions: long from noise when moving slowly or standing, short from cut corners on twisty routes. Which one wins depends on the route.

### 6.2.3 Smoothing and its cost

To show a steady pace, a watch averages. You met the cost in Chapter 4, Example 4.7: a trailing average of $N$ samples is $(N-1)/2$ samples late on a steady ramp. For pace, that lag is what an athlete sees in an interval: they speed up, and the pace on the screen catches up only seconds later. No published study measures this lag for watches, so compute it from first principles. Listing 6.3 gives a runner a sudden surge from 5:00 to 4:10 per km and asks how long each display takes to show 90% of the change.

**Listing 6.3.** How long a smoothed pace takes to show a surge (`code/lag.py`)

```python
import numpy as np, pandas as pd
t = np.arange(180)
speed = pd.Series(np.where(t < 60, 10/3, 4.0))       # 5:00/km, then 4:10/km at t = 60 s

def t90(shown):                              # seconds until 90% of the change shows
    return int(np.argmax(shown.values >= 10/3 + 0.9 * (4.0 - 10/3))) - 60

for n in (5, 10, 30):
    shown = speed.rolling(n, min_periods=1).mean()
    print(f"trailing {n:2d} s mean: 90% after {t90(shown)} s")
for alpha in (0.2, 0.05):
    shown = speed.ewm(alpha=alpha, adjust=False).mean()
    print(f"exponential alpha {alpha}: 90% after {t90(shown)} s")

ramp = pd.Series(3.0 + 0.01 * t)                      # speeding up 0.01 m/s each second
late = (ramp - ramp.rolling(10).mean()).iloc[-1] / 0.01
print(f"on a steady ramp the 10 s mean is {late:.1f} s behind")
```

```text
trailing  5 s mean: 90% after 4 s
trailing 10 s mean: 90% after 8 s
trailing 30 s mean: 90% after 27 s
exponential alpha 0.2: 90% after 10 s
exponential alpha 0.05: 90% after 44 s
on a steady ramp the 10 s mean is 4.5 s behind
```

*Predict before you run:* a 30-second repeat at a target pace, displayed with a 10-second average. For how much of the repeat does the screen show the pace you are running? (About the last 22 seconds; the first 8 are spent catching up.) The trade is unavoidable. A short window is fast and noisy; a long one is steady and late. Doppler speed, where a watch uses it, is far less noisy than differenced positions, so it needs less smoothing. For short repeats, run by time and effort and read the pace afterward from the whole repeat (Chapter 5 made the same point for heart rate).

\paragraph{Track mode.} Some watches offer a track mode. The runner tells the watch the lane, and the watch fits the noisy fixes to the known shape of a standard 400 m lane, so each lap counts as exactly one lap. This replaces the measurement by a model of the track. It works well when the runner stays in that lane, and it is wrong by design when they do not.

### 6.2.4 Elevation

A watch can know height in two ways. Satellite height is the least precise part of a fix, because all satellites are above you and none below, so vertical ranges cross at narrow angles. A *barometric altimeter* measures air pressure instead (Figure 6.3). Pressure falls with height because there is less air above you: the change is $\Delta p = -\rho g\,\Delta h$, and with air density $\rho = \SI{1.2}{\kilo\gram\per\cubic\metre}$ near sea level that is about 12 \pascal per metre, or one hectopascal (hPa) per 8.5 m.

*Figure 6.3. A barometric altimeter reads height from pressure: the higher cell has less air above it. Weather changes the pressure too, and the sensor cannot tell the two apart.*

A barometer is very sensitive to small changes in height, which is why it is used, but it cannot tell height from weather. A weather system that lowers the pressure by 3 \hecto\pascal during a long run looks like a climb of about 25 m. Watches correct for this by recalibrating to a known height, to satellite height or to a map, and different watches do it differently. This drift is taught here as a mechanism. The one watch study of elevation found no measurable effect of weather, but its trials lasted about 15 minutes; its authors note that pressure changes may still matter in longer activities .

\paragraph{Elevation gain.} Total climb, or *elevation gain*, adds up every rise and ignores every fall. That rule turns noise into climb: a reading that jitters up and down by a metre on flat ground adds a metre of gain at every upward jitter. Listing 6.4 shows it on the example run and on a synthetic flat half hour.

**Listing 6.4.** Elevation gain from a noisy altitude trace (`code/gain.py`)

```python
import numpy as np, pandas as pd
run = pd.read_csv("data/run.csv")
alt = run.alt_m.dropna().values                       # whole metres, once a second

def gain(z):                                  # add every rise, ignore every fall
    return np.clip(np.diff(z), 0, None).sum()

def gain_hysteresis(z, h=3.0):                # count a rise only after h metres
    total, ref = 0.0, z[0]
    for v in z[1:]:
        if v >= ref + h: total += v - ref; ref = v
        elif v < ref: ref = v
    return total

print(f"every rise: {gain(alt):.0f} m; "
      f"with a 3 m threshold: {gain_hysteresis(alt):.0f} m")
print(f"net change start to end: {alt[-1] - alt[0]:+.0f} m")
flat = np.round(1400 + np.random.default_rng(1).normal(0, 0.5, 1800))  # flat 30 min
print(f"flat ground with noise: {gain(flat):.0f} m vs {gain_hysteresis(flat):.0f} m")
```

```text
every rise: 53 m; with a 3 m threshold: 42 m
net change start to end: -8 m
flat ground with noise: 481 m vs 15 m
```

The watch itself reported 48 m of gain for this run, between the two. A flat half hour with half a metre of noise “climbs” 481 m if every rise counts. Watches therefore smooth or apply a threshold before summing, and their gain depends on that choice. In a study of three watches worn by 18 people on a hilly course and on a flat track, gain on the hills read 3.3% to 9.8% low with default settings, and on flat ground the watches added 0 to 4.8 m of false gain per 1200 m .

**Example 6.2: Grade.**

A hill rises 35 m over 500 m of road. Its *grade* is rise over run, $35/500 = 0.07$, or 7%. The Watch dashboard computes grade the same way for each stretch of a run longer than 8 m, from the altitude and distance fields.

> **Try it in the app: Distance and climb, two ways.**
> 
> The Watch dashboard reads FIT, GPX and TCX files in the browser; nothing is uploaded. For a FIT file it uses the watch's own distance and climb fields. For a GPX file, which carries only positions and heights, it sums the haversine distance between fixes; for a TCX file it uses the file's own distance field and sums positions only where that field is missing. For both it smooths the altitude with a 30-second moving average and then counts a climb only once it reaches 3 m, the threshold of Listing 6.4. Given the example run's heights as a GPX file, it reports 33 m of climb, against the watch's own 48. An earlier version added every rise, as the first line of the listing does (53 m here, hundreds on a noisy flat track). Export one of your runs as FIT and as GPX, load each, and compare distance and climb. The climb usually differs more than the distance; you now know why.
> 
> 
> https://apopt.com/watch

### 6.2.5 A zero-length interval

Speed is distance moved divided by time taken, and pace is its inverse. Both
divide, and a watch file can hand you a zero to divide by. The time stamp of a
FIT record is a whole number of seconds, so if a watch writes two records
within one second (it can happen around a lap press or a pause and resume),
both get the same stamp. The time step between them is zero. In Python a zero divisor
does not stop the program: NumPy and pandas return `inf` for a
positive number over zero and `nan` (“not a number”) for zero over
zero, and carry on. One `inf` turns the mean speed of the whole run
into `inf`, and a pace of 0:00 per km becomes the run's fastest
kilometer. Standing still causes the mirror problem: distance stops, so speed
is zero and pace is infinite.

Listing 6.5 builds six seconds of a runner at
3.5 m/s with one extra record from a lap press at
102.5 s, stored as 102, then stands still for the last second.

**Listing 6.5.** A repeated time stamp, found and handled by a stated rule (`code/zero_interval.py`)

```python
import numpy as np, pandas as pd
# 3.5 m/s; a lap press at 102.5 s writes an extra record, time stored as 102
rec = pd.DataFrame({"t_s":    [100, 101, 102, 102, 103, 104, 105],
                    "dist_m": [330.0, 333.5, 337.0, 338.75, 340.5, 344.0, 344.0]})
dt, dd = rec.t_s.diff(), rec.dist_m.diff()
with np.errstate(divide="ignore", invalid="ignore"):
    print("speed m/s:", (dd / dt).round(2).tolist()[1:])
    print("pace s/km:", (1000 * dt / dd).round(0).tolist()[1:])

bad = dt <= 0                                 # zero (or backward) time step
print(f"zero-length intervals: {bad.sum()} of {len(rec) - 1}; dropped")
clean = rec[~bad]                             # keep the first record of each second
assert clean.t_s.diff().dropna().gt(0).all()  # rule: time strictly increases
speed = clean.dist_m.diff() / clean.t_s.diff()
pace = (1000 / speed).where(speed > 0)        # standing still: no pace, not inf
print("speed m/s:", speed.round(2).tolist()[1:])
print("pace s/km:", pace.round(0).tolist()[1:])
```

```text
speed m/s: [3.5, 3.5, inf, 1.75, 3.5, 0.0]
pace s/km: [286.0, 286.0, 0.0, 571.0, 286.0, inf]
zero-length intervals: 1 of 6; dropped
speed m/s: [3.5, 3.5, 3.5, 3.5, 0.0]
pace s/km: [286.0, 286.0, 286.0, 286.0, nan]
```

The first two lines show the damage: an infinite speed, a pace of zero, and
then a false slow second (1.75 m/s) because the extra
record took half of the next interval's distance. The rule the listing
applies is explicit, counted and tested: drop any record whose time does not
increase, keeping the first record of each second, because when stamps are rounded
down the first record is the one written closest to its stamp; print how many were
dropped; and `assert` that time now strictly increases, so a file that
breaks the rule another way stops the program instead of passing silently.
Pace where the runner stands still is set to missing, not to infinity, so a
chart leaves a gap and a mean skips it. Other rules are defensible, such as
merging the two records or resampling distance onto a one-second grid as in
Section 6.3.4; what is not defensible is no rule. The example run has no repeated stamps (0 of its 1802 intervals); run the same check on every file of your own.
Exercise 6.23 works a case by hand.

## 6.3 Activity Files

### 6.3.1 What a record holds

An activity file is a table with one row, a *record*, per sample, plus some summary rows. A record from a running watch typically holds the time, latitude and longitude, the distance so far, speed, altitude, heart rate, cadence, and for some watches temperature, power and running-dynamics fields. Summary rows describe each *lap* (a stretch the athlete or the watch marks: a manual button press, or automatically every kilometer or mile) and the whole *session*. Three formats are common:

- **FIT** (Flexible and Interoperable Data Transfer), a compact binary format written by most watches and bike computers. Each kind of message is defined once in the file, then its rows follow. Values are stored as integers with a scale.

- **TCX**, a text (XML) format with laps, track points, heart rate and cadence.

- **GPX**, a text (XML) format for routes and tracks. Its core holds only position, elevation and time; heart rate and cadence ride in optional extensions.

Watches record either every second or only when something changes enough (“smart” or change-triggered recording, which saves memory). A change-triggered file has uneven spacing between records, which is one more reason to resample before analysis.

**Example 6.3: Positions stored as semicircles.**

To fit an angle into a 32-bit integer, a FIT file stores latitude and longitude in *semicircles*: $2^{31}$ semicircles make \ang{180}. A stored value of 479409000 is $\num{479409000}\times180/2^{31} = \ang{40.18}$. A program that forgets the conversion puts the runner thousands of kilometers away, or, worse, plots a tiny smear that looks plausible.

### 6.3.2 Reading a FIT file

Listing 6.6 reads a FIT file with `fitdecode`, an open Python library (`fitdecode` 0.11 was used; `fitparse` is an alternative. For GPX, `gpxpy`. File-reading libraries change faster than the methods; check the current one.), collects the records into a pandas table, converts semicircles to degrees, and prints the facts you need before any analysis. Run it on a file of your own. The output below is from the original file of the example run.

**Listing 6.6.** Read a FIT file and print what it holds (`code/read_fit.py`)

```python
import sys, warnings
import fitdecode, pandas as pd
warnings.simplefilter("ignore")        # one watch writes a malformed definition
SEMI = 180 / 2**31                     # degrees per semicircle

rows, laps, session = [], 0, {}
with fitdecode.FitReader(sys.argv[1]) as fit:
    for m in fit:
        if not isinstance(m, fitdecode.FitDataMessage):
            continue                   # skip headers and definitions
        if m.name == "record":
            rows.append({f.name: f.value for f in m.fields})
        elif m.name == "lap":
            laps += 1
        elif m.name == "session":
            session = {f.name: f.value for f in m.fields}

df = pd.DataFrame(rows)
df["lat"] = df["position_lat"] * SEMI
gaps = df["timestamp"].diff().dt.total_seconds()
print(len(df), "records,", laps, "laps; gaps over 1 s:", gaps[gaps > 1].tolist())
print("device distance", session["total_distance"], "m")
print("timer", session["total_timer_time"], "s;",
      "elapsed", session["total_elapsed_time"], "s")
print("cadence field", session["avg_running_cadence"], "per leg")
```

```text
1803 records, 4 laps; gaps over 1 s: [3787.0, 23.0]
device distance 5880.46 m
timer 1801.67 s; elapsed 5609.84 s
cadence field 88 per leg
```

Four facts come out, and each changes the analysis.

- **The watch was paused twice.** One gap is 23 seconds; the other is 3787 seconds, more than an hour, in the middle of the run. The *timer time* (1802 s, the time the watch was running) and the *elapsed time* (5610 s from start to finish) differ by those pauses. Pace must use timer time; a pace computed from elapsed time would be three times too slow.

- **The laps are miles.** The four laps are three of 1609.3 m and the remainder, because the watch was set to split every mile.

- **The distance is the watch's own.** 5880.46 m is a field the watch computed. You can recompute it from positions (Listing 6.1), but the watch's figure is what the athlete saw.

- **Cadence is per leg.** The file stores 88; the runner took about 176 steps a minute (Section 6.4).

> **Key idea.**
> 
> Before you trust any number from an activity file, find the pauses, the units and the lap rule. Most wrong analyses of watch data are wrong at this step, not in the mathematics.

### 6.3.3 De-identifying a route

A route is personal data. A run that starts and ends at the same point usually starts and ends at home. Before you share a file with a teammate, a class or an AI service, remove what identifies the person (Chapter 4 covered names, dates and clock times). For a route the rule in this book is: drop every position within 500 m of the start and of the end, shift times so the first record is at zero, and add one fixed offset to every longitude so the route no longer lies where it was run. A longitude offset changes no distance: the haversine formula depends only on the latitudes and on differences of longitude. The script `code/deidentify.py` does all three for the example run (offset \ang{40}); it removed 304 of 1798 positions, and every distance in this chapter is the same as from the unshifted file. Removing positions is not the same as removing information: the distance field, the timing and the heart rate remain, and the middle of the route still shows a neighborhood. Share the least you need.

### 6.3.4 Splits, pauses and resampling

The example file is already one record a second, except at the pauses. Resampling onto a regular grid, filling short gaps and leaving long ones empty, was covered in Chapter 4 (Section 4.4); the same rules apply here, with one addition: never interpolate across a pause. Listing 6.7 rebuilds timer time by treating any gap longer than a second as a pause, then finds the time at which each kilometer and each mile was reached by interpolating in the distance field.

**Listing 6.7.** Timer time, splits per kilometer and per mile (`code/splits.py`)

```python
import numpy as np, pandas as pd
run = pd.read_csv("data/run.csv")
dt = run.t_s.diff().fillna(0)
run["timer_s"] = dt.where(dt <= 1, 0).cumsum()        # a gap longer than 1 s is a pause
print("timer", run.timer_s.iloc[-1], "s; wall clock", run.t_s.iloc[-1], "s")

def splits(every_m):
    marks = np.arange(every_m, run.dist_m.iloc[-1], every_m)
    times = np.interp(marks, run.dist_m, run.timer_s)  # timer time at each mark
    return np.diff(np.r_[0, times])

for name, d in (("km", 1000), ("mile", 1609.344)):
    s = splits(d)
    pace = [f"{int(x // 60)}:{x % 60:04.1f}" for x in s * 1000 / d]
    print(name, "splits (s):", s.round(1).tolist())
    print("  pace per km:", pace)

step = run.dist_m.diff()[dt == 1]                     # metres moved in each 1 s
print("1 s steps (m):", step.value_counts().head(3).to_dict())
```

```text
timer 1800.0 s; wall clock 5610 s
km splits (s): [298.3, 288.0, 303.8, 354.0, 301.9]
  pace per km: ['4:58.3', '4:48.0', '5:03.8', '5:54.0', '5:01.9']
mile splits (s): [476.7, 502.4, 517.7]
  pace per km: ['4:56.2', '5:12.2', '5:21.7']
1 s steps (m): {3.5: 982, 3.0: 422, 4.0: 184}
```

The kilometer and mile splits are the same to a tenth of a second as the Watch dashboard's for this file (it shows either, with a unit selector set to miles by default: 7:57, 8:22 and 8:38 per mile, or 4:58, 4:48, 5:04, 5:54 and 5:02 per km), because both interpolate the watch's distance field against timer time. Timer time here is 1800 s, 1.7 s short of the watch's own, because the watch also counts fractions of a second around each pause. The fourth kilometer is almost a minute slower than the others. The file cannot say why; a hill, a road crossing or a walk are all possible, and the athlete is the one to ask.

The last line of output is a warning about the distance field itself. It is stored to the nearest half metre, so the distance moved in one second takes only a few values: 3.5 m in 982 seconds, 3.0 m in 422, 4.0 m in 184. A one-second speed from this field jumps in steps of 0.5 m/s, which is 15 % of the runner's speed, even though the watch's own speed field is smooth. Figure 6.4 shows both. Resolution, not just noise, limits a derivative.

*Figure 6.4. The first four minutes of the example run. One-second speed from the distance field (dots) sits on a few levels because distance is stored to 0.5 m. A 10-second mean (dashed) follows the watch's own speed field (solid) closely, a few seconds late.*

## 6.4 Motion Sensing

### 6.4.1 What an accelerometer measures

An *accelerometer* is a tiny mass held by springs inside a housing (Figure 6.5). When the housing accelerates, the mass lags behind and the springs stretch; the sensor measures that stretch, electrically, along three perpendicular axes. A wearable accelerometer is a chip a few millimeters across that reports, many times a second, the acceleration along each axis in units of $g = \SI{9.81}{\metre\per\square\second}$.

There is a catch that matters for everything below. Lying on a table, the accelerometer reads $1\,g$ upward, not zero, because the table pushes the mass up against gravity exactly as an upward acceleration would. An accelerometer measures acceleration *minus* gravity. That is a nuisance when you want motion, and a gift when you want orientation: at rest, the direction of the $1\,g$ reading tells you which way is down. A *gyroscope* beside it measures rate of rotation. Together they make an *inertial measurement unit* (IMU).

*Figure 6.5. An accelerometer: a proof mass on springs. At rest the mass sits centered (left); when the housing accelerates, the mass lags and the springs deflect (right). The sensor reads the deflection.*

### 6.4.2 From acceleration to steps

Each footstrike sends a sharp jolt up through the body, and an accelerometer anywhere on the trunk or leg sees it as a spike. Find the spikes and you have the steps; count them per minute and you have *cadence*. The recipe is the one you used for R peaks in Chapter 5: filter to the frequencies where the events live, find peaks, and refuse peaks closer together than the event can happen.

**Example 6.4: Cadence and step length.**

You count 43 steps in 15 seconds. Cadence is $43\times60/15 = \SI{172}{\spm}$. A FIT file counts one leg, so it stores 86 (strides a minute), and the Watch dashboard doubles it back to 172. At 3.33 m/s the runner takes $172/60 = 2.87$ steps a second, so each step is $3.33/2.87 = \SI{1.16}{\metre}$ long. Step length is not measured by a wrist watch; it is speed divided by cadence.

> **Body science: Step and stride.**
> 
> A *step* goes from one foot's contact to the other foot's contact; a *stride* is two steps, from one foot's contact to the same foot's next contact. Runners usually quote cadence in steps a minute (160 to 190 in distance running), and file formats often store strides a minute. Each step has a *ground contact time*, when the foot is on the ground, and a flight time, when neither is. *Vertical oscillation* is how far the trunk rises and falls in each step, a few centimeters. Chapter 9 measures all of these from video.

Listing 6.8 reads the running-dynamics fields of the example run, doubles the cadence, and checks the step length the watch stored against speed divided by cadence.

**Listing 6.8.** Cadence, step length and running dynamics from the file (`code/cadence.py`)

```python
import pandas as pd
run = pd.read_csv("data/run.csv")
steady = run[(run.speed_mps > 2.5) & run.cad_leg.notna()]  # running, not stopping

spm = 2 * steady.cad_leg                      # the file counts one leg; double it
step_m = steady.speed_mps / (spm / 60)        # metres per step = speed / steps per s
print(f"cadence {spm.mean():.0f} steps/min, speed {steady.speed_mps.mean():.2f} m/s")
print(f"step length from speed and cadence {step_m.mean():.2f} m; "
      f"file's own field {steady.step_mm.mean() / 1000:.2f} m")
ratio = steady.vo_mm / steady.step_mm         # vertical oscillation per step length
print(f"contact {steady.gct_ms.mean():.0f} ms, "
      f"oscillation {steady.vo_mm.mean():.0f} mm, "
      f"ratio {100 * ratio.mean():.1f}%")
```

```text
cadence 177 steps/min, speed 3.36 m/s
step length from speed and cadence 1.14 m; file's own field 1.13 m
contact 208 ms, oscillation 90 mm, ratio 8.0%
```

Step length from speed and cadence agrees with the watch's own field within a centimeter, which suggests the watch computes it the same way. The *vertical ratio*, oscillation divided by step length, is $90/1130 = 8.0\%$: how much of each step's effort goes up rather than forward, as the watch models it. For the whole session the Watch dashboard shows 176 steps a minute, 1.11 m, 210 ms and 90 mm with a ratio of 8.1%; it uses the watch's session averages, which include the slow minutes the listing left out.

### 6.4.3 Where the sensor sits decides what it can know

A sensor on the foot feels each contact directly and can time it within milliseconds. A sensor on the lower back moves with the body's center and sees both steps and the up-and-down of the trunk. A wrist sensor feels the foot only through the whole arm, swinging on its own rhythm, so its step count is good and its contact time is a model. A chest strap moves with the trunk.

The evidence follows that logic. A review of 131 studies of wearables for running found cadence (step frequency) studied in 36 and vertical oscillation in only 7 to 9 (the review's text and table differ) . A meta-analysis of where an IMU is worn, from 39 studies, found contact time, flight time and step frequency reliable from the foot and the lower back; valid contact time from the foot, tibia and lower back; and step length pooled only for foot sensors. Whether stride events can be detected accurately from the upper back (thoracic spine) was unclear . So: trust cadence from almost anywhere, trust contact time from the foot or lower back, and treat vertical oscillation from a wrist as an estimate with little published support.

### 6.4.4 Steps and breaths from the chest

A sensor on the chest sees two rhythms. Running, it sees footstrikes along the body's long axis, two or three a second. Lying still on your back, gravity points straight through the chest, and each breath tilts the chest wall a few degrees, which changes how much of the $1\,g$ falls on the front-to-back axis: a slow wave, a breath every few seconds. The course chest strap streams its accelerometer at 25 to 200 samples a second, and the Heart app's Live Capture shows cadence and a breathing estimate from it (Chapter 5). A phone held on the chest with an elastic band and a sensor-logging app records the same thing.

No real chest recording was available when this chapter was written, so Listing 6.9 runs on a synthetic one, `data/chest-acc.csv`, made by `code/make_chest.py` with known answers: 30 seconds of running at 172 steps/min with natural step-to-step variation, five seconds of lying down, then a minute lying still at 15 breaths a minute. The same function finds both rhythms with different filters and different minimum gaps. Exercise 6.11 repeats it on your own recording.

**Listing 6.9.** Steps while running and breaths lying still, from a chest accelerometer (`code/chest.py`)

```python
import numpy as np, pandas as pd
from scipy.signal import butter, filtfilt, find_peaks
acc = pd.read_csv("data/chest-acc.csv")
fs = 1 / acc.t_s.diff().median()                       # samples per second

def rate(t, x, lo, hi, min_gap_s):                     # events per minute
    b, a = butter(2, [lo, hi], btype="band", fs=fs)
    y = filtfilt(b, a, x)                               # two passes: no lag
    pk, _ = find_peaks(y, distance=int(min_gap_s * fs), prominence=0.5 * y.std())
    return len(pk), 60 * (len(pk) - 1) / (t[pk[-1]] - t[pk[0]])

run = acc[acc.t_s < 30]                     # running: impacts on the long axis
n, spm = rate(run.t_s.values, run.vert_g.values, 0.5, 5.0, 0.25)
print(f"{fs:.0f} samples/s; running: {n} steps, {spm:.1f} steps/min")

lie = acc[acc.t_s >= 35]                    # lying: each breath tilts the chest
n, bpm = rate(lie.t_s.values, lie.fwd_g.values, 0.1, 0.7, 2.0)
print(f"lying: {n} breaths, {bpm:.1f} breaths/min")
```

```text
50 samples/s; running: 86 steps, 171.9 steps/min
lying: 13 breaths, 15.0 breaths/min
```

Both rates match the truth (171.9 and 15.0). The breath count does not: there were 15 breaths in the minute, and the listing found 13, because a peak cannot be found at the very edge of a window. That is why the listing reports a rate from the first to the last event found, not a count divided by the window length. Figure 6.6 shows both signals.

*Figure 6.6. The synthetic chest record of Listing 6.9. Top: four seconds of running; raw acceleration (gray) and band-passed (solid), with one detected step per circle. Bottom: forty seconds lying still; the front-axis signal after a 0.1–0.7 Hz band-pass rises and falls with each breath (circles), a change of less than 0.01 g.*

### 6.4.5 Power: modeled for running, measured for cycling

“Running power” in watts appears on many watches and foot pods. There is no instrument that measures the mechanical power of a runner directly in the field, and no agreed reference to check it against, so running power is a *modeled* output: the device estimates it from acceleration, speed, slope and body mass, with a model the maker chooses. Two studies show what that means. In six recreational runners on a treadmill, one foot pod's power tracked oxygen uptake closely ($R^2 = 0.82$), but it underestimated the absolute mechanical power . In 12 trained men tested with five running-power technologies, the foot pod was the most repeatable (coefficient of variation at most 4.3%) and tracked oxygen uptake best ($r \ge 0.91$); the others kept some relation to oxygen uptake, but their low repeatability questions their suitability . Power from one device is a consistent number for that device. Do not compare it with power from another.

Cycling power is different. A cycling *power meter* measures torque with strain gauges in the crank, pedal or hub, and the angular speed of the crank; power is their product, $P = \tau\omega$. A torque of 35 Nm at 90 rpm ($\omega = 90\times2\pi/60 = \SI{9.42}{\radian\per\second}$) is 330 W. That is a measurement, with errors you can name (zero offset, temperature) and check against a calibrated rig.

## 6.5 Pace, Economy and the Speed–Duration Curve

### 6.5.1 The energy cost of running

How much energy does it take to run a kilometer? On level ground the answer is surprisingly simple: the *energy cost of running* is close to 3.40 J per kilogram per meter, nearly independent of speed . Running faster spends energy faster, but covers the distance sooner, and the two cancel. Chapter 2 used a rounder rule from another study, about 1 \kcal per kilogram per kilometer (4.2 J/kg/m). Studies, methods and runners differ by that much; treat either figure as a rough guide, and keep to one when you compare.

**Example 6.5: Energy for a 10 km run.**

A 70 kg runner covers 10 km on the level. Energy $= 3.40\times70\times10\,000 = \SI{2.38}{\mega\joule}$, which is $\num{2380000}/4184 = \SI{569}{\kcal}$, at any comfortable speed. This is the metabolic energy above rest that the cost figure describes. A watch's calorie number is a modeled estimate; reviews find it inaccurate for every maker (Section 6.7).

Hills change this a great deal. In the same study, the cost rose to 18.93 J/kg/m at a 45% uphill grade and fell to its lowest, 1.73 J/kg/m, at a 20% downhill grade . Uphill, every meter of climb lifts the body against gravity; downhill, gravity helps until the slope gets so steep that the legs must brake. So pace alone misleads on hills. A runner who holds 5:00 per km up a 7% grade is working much harder than at 5:00 on the flat, and one who slows on the climb to keep effort steady is pacing well. Wind works the same way: air resistance grows with the square of the speed relative to the air, so a headwind costs more than a tailwind of the same speed gives back. On a hilly or windy day, judge an easy run by heart rate or by how it feels, not by pace.

### 6.5.2 Critical speed

Chapter 2 asked why a runner can hold one pace for an hour and a slightly faster one for only ten minutes. Here is the model that answers it with a ruler. Plot each best effort as distance against time. The points lie close to a straight line:

$$d = \text{CS}\cdot t + D'.$$

The slope CS is the *critical speed*, the highest speed at which the body can reach a steady state. The intercept $D'$ (“D prime”) is a fixed distance the runner can cover *above* critical speed before having to slow down, like a small reserve tank . Running faster than CS uses the tank; the time it lasts is

$$t_\text{lim} = \frac{D'}{v - \text{CS}}.$$

For one elite runner's best performances from 2 to 15 km, Jones and Vanhatalo give a critical speed of 5.91 m/s and a $D'$ of 351 m . Chapter 11 fits the same line by least squares and asks how precise it is.

**Example 6.6: Critical speed from two time trials.**

A runner runs 1200 m in 4:00 (240 s) and 3600 m in 13:20 (800 s), each as fast as they can, on different days.

- Slope: $\text{CS} = (3600-1200)/(800-240) = 2400/560 = \SI{4.2857}{\metre\per\second}$, or 3:53 per km.

- Intercept: $D' = 1200 - (2400/560)\times240 = 1200 - 1028.6 = \SI{171}{\metre}$.

- If you round CS to 4.29 first, $D' = 1200 - 4.29\times240 = \SI{170}{\metre}$. A rounded slope multiplied by a long time loses a meter; keep the fraction until the end.

- At 5.0 m/s, Equation \eqref{ch06-gps-motion:eq:tlim} gives $171.4/(5.0-4.2857) = \SI{240}{\second}$, which is the first trial again: the line passes through both points by construction.

**Listing 6.10.** Critical speed and $D'$ by a straight-line fit (`code/critical_speed.py`)

```python
import numpy as np
t = np.array([240.0, 800.0])                  # 1200 m in 4:00, 3600 m in 13:20
d = np.array([1200.0, 3600.0])
cs, dprime = np.polyfit(t, d, 1)              # straight line d = CS * t + D'
pace = 1000 / cs                               # seconds per km
print(f"CS = {cs:.4f} m/s ({pace // 60:.0f}:{pace % 60:02.0f} per km), "
      f"D' = {dprime:.1f} m")
print(f"rounding CS to 4.29 first gives D' = {1200 - 4.29 * 240:.1f} m")

t3 = np.append(t, 480.0); d3 = np.append(d, 2200.0)   # add 2200 m in 8:00
cs3, dp3 = np.polyfit(t3, d3, 1)
res = d3 - (cs3 * t3 + dp3)
print(f"three trials: CS = {cs3:.3f} m/s, D' = {dp3:.0f} m, residuals {res.round(1)} m")

for v in (4.5, 5.0):                          # how long can each speed last?
    print(f"{v} m/s lasts about {dprime / (v - cs):.0f} s")
```

```text
CS = 4.2857 m/s (3:53 per km), D' = 171.4 m
rounding CS to 4.29 first gives D' = 170.4 m
three trials: CS = 4.291 m/s, D' = 159 m, residuals [ 10.8   8.1 -18.9] m
4.5 m/s lasts about 800 s
5.0 m/s lasts about 240 s
```

A third trial, 2200 m in 8:00, changes CS very little and $D'$ by 12 m, and its residual of -19 m says it was run a little below the line: a pacing error, a windy day or a tired runner. Two points always make a line. Three let you see whether the line fits (Figure 6.7).

*Figure 6.7. Distance against time for Example 6.6. The slope of the line is critical speed; its intercept is $D'$, the distance that can be run above critical speed. The third trial (square) sits 19 m below the line.*

> **Body science: What happens above critical speed.**
> 
> Below critical speed, oxygen uptake and blood lactate rise at the start of a run and then level off; the effort can last a long time. Above it, they do not level off: oxygen uptake keeps creeping up toward the maximum and lactate keeps rising until the runner must slow down. Critical speed is the running form of critical power on a bike, and it sits near the boundary that Chapter 2 called the second threshold. $D'$ is not a literal fuel tank; it stands for the limited work that can be done while the body drifts away from a steady state.

\paragraph{Using it to set paces.} Critical speed gives training paces a physiological anchor. Steady runs belong well below it. Threshold work sits just under it. Intervals above it are limited by $D'$: repeats of 1000 m at 4.5 m/s use $1000 - 4.2857\times(1000/4.5) = \SI{48}{\metre}$ of a 171 m $D'$ each, so the recoveries between them decide how many can be run. The Watch dashboard does not compute critical speed; it estimates race times from equivalence tables instead. Fit it in Python, or watch the model respond in the treadmill pacing simulator at https://apmonitor.com/apps, which uses the same model.

> **Engineer's note: Your first straight-line fit.**
> 
> Listing 6.10 is a *linear regression*: `np.polyfit` picks the slope and intercept that make the sum of squared misses smallest (least squares). Three habits go with every fit. Give the slope its units: distance in metres over time in seconds, so the slope CS is in m/s and the intercept $D'$ in metres. Look at the *residual*s, measured minus fitted; with an intercept they always sum to zero, and they should show no pattern. And beat a *mean baseline*, the model that ignores time and guesses the average distance every time. $R^2 = 1-SSE/SST$ is the line's squared error (SSE) against the baseline's (SST). Here the baseline is easy to beat; a harder one is “the same average speed at every duration”, the line forced through the origin, which Exercise 6.22 tries. Section 11.4 of Chapter 11 fits lines to many runners and tests them on data the fit has not seen.

Listing 6.11 fits the three trials again with scikit-learn and does the three checks.

**Listing 6.11.** Critical speed as a regression: units, residuals and a mean baseline (`code/cs_regression.py`)

```python
import numpy as np
from sklearn.linear_model import LinearRegression
t = np.array([240.0, 480.0, 800.0])            # s: the three trials in the text
d = np.array([1200.0, 2200.0, 3600.0])         # m
model = LinearRegression().fit(t.reshape(-1, 1), d)
cs, dprime = model.coef_[0], model.intercept_  # slope m/s, intercept m
resid = d - model.predict(t.reshape(-1, 1))    # measured minus fitted, m
base = d - d.mean()                            # baseline: guess the mean distance
print(f"slope CS = {cs:.3f} m/s, intercept D' = {dprime:.0f} m")
print("residuals (m):", resid.round(1), " sum", round(resid.sum(), 6))
print(f"RMSE line {np.sqrt((resid**2).mean()):.1f} m, "
      f"mean baseline {np.sqrt((base**2).mean()):.0f} m")
print(f"R^2 = {model.score(t.reshape(-1, 1), d):.4f}")
```

```text
slope CS = 4.291 m/s, intercept D' = 159 m
residuals (m): [ 10.8 -18.9   8.1]  sum 0.0
RMSE line 13.4 m, mean baseline 984 m
R^2 = 0.9998
```

The line's root-mean-square error (RMSE) is 13 m against 984 m for the mean baseline, and $R^2$ rounds to 1. That is less impressive than it looks. Distance grows with time for any runner at any speed, so almost any line through these points beats the mean; the residuals, tens of metres on trials of kilometres, say more about the fit than $R^2$ does.

## 6.6 Load over Weeks

One run says little about training. A season is a time series of runs, and coaches summarize it with a *load* score per session, added up per day and per week, and with averages that look back over different spans.

### 6.6.1 A score per run

Chapter 5 defined the training impulse, which weights each minute by heart-rate reserve. The Watch dashboard uses a simpler score:

$$\text{load} = \text{minutes}\times\left(\frac{\text{mean heart rate}}{\text{maximum heart rate}}\right)^2,$$

with the ratio held between 0.45 and 1.08. The maximum is the one the athlete enters, or else an estimate from age and the highest values seen. A 40-minute run at a mean of 152 bpm with a maximum of 190 scores $40\times(152/190)^2 = 40\times0.8^2 = 25.6$.

The dashboard then keeps two exponentially weighted averages of daily load, one that forgets quickly (time constant 7 days, labeled fatigue) and one that forgets slowly (42 days, labeled fitness). Each day, each average moves a fraction $k = 1 - \ee^{-1/\tau}$ of the way toward that day's load: $0.133$ for 7 days, $0.023$ for 42. Their difference is labeled form. It also reports the *acute:chronic ratio*: the mean daily load of the last 7 days divided by the mean of the last 28.

> **Check it by hand: One week against four.**
> 
> Three weeks each total 100 load units. In the fourth week the athlete runs 40 minutes at 152 on Monday (25.6), 30 minutes at 171 on Wednesday ($30\times0.9^2 = 24.3$), 50 minutes at 133 on Thursday ($50\times0.7^2 = 24.5$), 80 minutes at 152 on Saturday ($80\times0.64 = 51.2$) and 20 minutes at 133 on Sunday (9.8). The week totals 135.4.

> Acute: $135.4/7 = 19.34$ a day. Chronic: $(300 + 135.4)/28 = 15.55$ a day. Ratio: $19.34/15.55 = 1.24$, the same as $135.4/(435.4/4)$, this week over the four-week weekly mean.

### 6.6.2 A season

Listing 6.12 applies the same rules to a synthetic twelve-week season (`data/season.csv`, made by `code/make_season.py`): five runs a week, a gentle build, a training camp in week 9 with about 1.6 times the usual load, an easy week 10, then two normal weeks.

**Listing 6.12.** Load per run, per week, two averages and the 7/28 ratio (`code/load.py`)

```python
import numpy as np, pandas as pd
HRMAX = 190                                            # entered, not estimated

def run_load(minutes, hr):                             # the Watch dashboard's score
    return minutes * np.clip(hr / HRMAX, 0.45, 1.08) ** 2

def ewma(x, days):                           # starts from zero, as the app does
    k, y, out = 1 - np.exp(-1 / days), 0.0, []
    for v in x:
        y += k * (v - y); out.append(y)
    return np.array(out)

print(f"40 min at 152: {run_load(40, 152):.1f}")       # hand check
runs = pd.read_csv("data/season.csv")
daily = (runs.assign(load=run_load(runs.minutes, runs.hr))
             .groupby("day").load.sum().reindex(range(84), fill_value=0.0))
ratio = daily.rolling(7).mean() / daily.rolling(28).mean()          # acute:chronic
apart = daily.rolling(7).mean() / daily.shift(7).rolling(21).mean()  # 21 days before
end = np.arange(6, 84, 7)                              # last day of each week
weekly = daily.groupby(daily.index // 7).sum()
print("weekly load:", weekly.round(0).astype(int).tolist())
print("7/28 ratio: ", ratio.iloc[end].round(2).tolist())
print(f"week 9: coupled {ratio.iloc[62]:.2f}, uncoupled {apart.iloc[62]:.2f}")
print(f"day 83: 7-day {ewma(daily, 7)[-1]:.1f}, 42-day {ewma(daily, 42)[-1]:.1f}")
```

```text
40 min at 152: 25.6
weekly load: [102, 110, 117, 130, 139, 126, 134, 158, 218, 78, 137, 138]
7/28 ratio:  [nan, nan, nan, 1.13, 1.12, 0.99, 1.01, 1.14, 1.37, 0.53, 0.93, 0.97]
week 9: coupled 1.37, uncoupled 1.56
day 83: 7-day 20.2, 42-day 17.0
```

The Watch dashboard's own code, given the same sixty runs with a maximum of 190, reports the same weekly loads, the same ratios at the end of each week and the same two averages at the end of week 12 (CHECKS.md gives the harness). Figure 6.8 shows the season.

*Figure 6.8. Twelve synthetic weeks scored as the Watch dashboard scores them. Top: daily load (bars), the 7-day average (dashed) and the 42-day average (solid). Bottom: the 7-day over 28-day ratio, which exists only from day 27. The camp in week 9 (days 56–62) lifts the ratio to 1.37.*

### 6.6.3 The limits of ratio-based injury rules

The acute:chronic ratio became popular as an injury warning: keep it in a “sweet spot” and avoid spikes. Look at what the camp week did. Its load was 1.56 times the mean of the three weeks before it, yet the ratio shows 1.37, because the camp week is itself one quarter of the 28-day chronic window. Acute load is part of chronic load, so the two are mathematically coupled. A ratio built that way cannot exceed 4 (the value when the three earlier weeks were empty), it moves less than the change it is meant to show, and coupling alone produces correlations between the ratio and anything related to acute load . A critical review lists further problems: a ratio of two noisy averages adds noise, it can produce artifacts when the chronic load is small, and recommending that athletes change their ratio to change injury rates assumes a causal effect that no study has properly estimated; the authors conclude that there is no evidence for using the ratio to manage load or reduce injury .

The Watch dashboard labels a ratio above 1.5 “Load well above your recent average”. That is what the evidence supports: the last week was much bigger than the last month, which is worth noticing and worth a conversation. An earlier version called it a “spike” with the note “elevated injury risk”, a forecast the ratio cannot make; checking the label against the literature above is what changed it. The dashboard still calls 0.8 to 1.3 a “sweet spot”, a phrase borrowed from the same injury literature; read it, too, as a description of training, not a measured risk for this athlete.

> **Limits and cautions: Load numbers describe; they do not predict.**
> 
> A load score compares sessions for one athlete measured the same way. It inherits every error of its inputs: a wrong maximum heart rate, a wrist sensor locked to cadence, a strength session the watch never saw. No load score or ratio is a diagnosis, a clearance or a forecast of injury. Use them to see the shape of the training and to ask better questions.

## 6.7 How Good Is the Number?

Table 6.1 collects the evidence for the numbers in this chapter, with what was measured and against what. The pattern is the same as for heart rate: the setting matters more than the brand, and modeled outputs earn the least trust.

*Table 6.1. How good are watch numbers? Findings from the studies cited, by output and setting.*

| Output and setting | Finding | Study |
|---|---|---|
| Distance, by setting | Eight watches against a measuring wheel: mean absolute percentage error 3.2 to 6.1% overall; 0.9 to 4.1% on a track (reading long); 3.5 to 8.5% in forest and 3.9 to 8.9% among buildings (mostly reading short) |  |
| Distance, a race | Half marathon: watches 0.6% from the certified distance on average (179 self-reported readings) |  |
| Speed, Doppler | $r = 0.9994$ against true speed on a straight; 90.8% within 0.1 m/s; slightly low on curves |  |
| Speed, one second | 45% within 0.2 m/s, a further 19% within 0.4 m/s |  |
| Elevation gain | 3.3 to 9.8% low on a hilly course; 0 to 4.8 m false gain per 1200 m on the flat |  |
| Cadence, contact time | Of 131 studies, cadence in 36 and vertical oscillation in 7 to 9; contact time and step frequency reliable from foot or lower back |  |
| Running power | Tracks oxygen uptake for one foot pod; most technologies not repeatable enough; no reference standard |  |
| Maximal oxygen uptake estimate | From rest: bias 2.2 mL/kg/min, limits of agreement $-13$ to $+17$ ; from exercise: limits $-10$ to $+10$ ; good for groups, large errors for individuals |  |
| Calories | Energy expenditure accurate for no brand | 158 studies |
| Sleep stages, wrist | Agreement with laboratory sleep recording (kappa) 0.21 to 0.53, fair to moderate; wake often missed |  |
| Readiness scores | 14 composite scores; no maker disclosed its formula; few offered validation |  |

\paragraph{Answering the opening question.} A watch that reads 10.14 km on a 10.00 km course is 1.4% long. That is inside the range of watch error in open and built-up settings, so the watch alone cannot answer. But the runner contributes too. A course is measured along one line; a runner who swings wide at corners, weaves past others or crosses the road to a water table covers more. Both effects push the reading up. A track test (Exercise 6.17) separates them for your own watch: in lane 1 the line is known, so the watch's error is the only error left.

**Example 6.7: A device check on a track.**

Ten laps in lane 1 are 4000 m. The watch reads 4.06 km: $4060/4000 - 1 = +1.5\%$. Repeat on another day before you call it the watch's bias, since sky view and the satellites overhead change.

> **Status: 2026.**
> 
> {Multi-band receivers in sport}
> Receivers that use two frequency bands are now common in running watches and are sold as more accurate. As of November 2026, no peer-reviewed study had compared the same watch with dual-frequency tracking on and off during running or walking. One test of a smartwatch found that using more satellite systems improved the fix standing still but not while walking . For dual-frequency itself, the clearest evidence is a static phone test, where the 95th-percentile error fell from 9.31 m to 3.32 m . Treat “more accurate in sport” as plausible and unproven until a track test of your own says otherwise.

\paragraph{Measured, derived, modeled.} Sort every watch output with the habit of Chapter 5. Measured: position fixes, Doppler speed, acceleration, pressure, cycling torque. Derived: distance, pace, cadence, step length, grade, elevation gain. Modeled: running power, contact time and vertical oscillation from a wrist, calories, maximal oxygen uptake, sleep stages, readiness and recovery scores, race predictions. Give each the trust its tag deserves.

## 6.8 Telling the Coach

The communicate step for this chapter is a weekly summary: three numbers, one chart, one recommendation. Here are two summaries of week 9 of the season in Figure 6.8, written for the athlete's coach.

> **Coach's translation: A poor summary.**
> 
> “Load spiked to 218, ACWR 1.37, fatigue 28.6 vs fitness 16.7, TSB $-12$. Running economy probably dropped. Injury risk is elevated, so cut volume by half next week.”

> **Coach's translation: A better summary.**
> 
> “Camp week: 6 hours 3 minutes of running in 5 sessions (week 8: 4 h 18 min), a load of 218 against 139 on average over the three weeks before, so about 1.6 times her recent weeks. Her heart rate at easy pace was the same as last month, which fits an athlete who absorbed the week. Chart: weekly load for the season, with this week marked. Next week is planned easy; I would keep it that way, then check easy-run heart rate and how she feels before the next hard week. Load is computed from watch time and heart rate, so it misses strength work and is only as good as her entered maximum.”

The poor summary is a list of abbreviations, quotes a ratio the coach cannot interpret, guesses at a cause (economy), and turns a description into an injury prediction with an outsized instruction. The better one gives three numbers the coach can picture (time, load against recent weeks, easy-run heart rate), points to one chart, makes one proportionate recommendation, and states what the number cannot see.

## 6.9 Build Step B-6: An Activity File on a Map

This week your page reads an activity file and shows a run: distance, splits per kilometer, pace, heart rate and elevation charts, and a route on a canvas (steps W-6 and W-7 of the wearables plan). GPX is the easiest format in a browser, because it is text; FIT needs a parsing library such as `fit-file-parser`, the one the Watch dashboard uses. Put the arithmetic in small functions with tests, and the page code around them.

**Listing 6.13.** Haversine, cumulative distance and splits in JavaScript (`code/track.js`) (`code/track.js`)

```javascript
// Distance and splits for a list of fixes {t, lat, lon}, t in seconds.
const R = 6371000, rad = (deg) => (deg * Math.PI) / 180;

export function haversine(a, b) {
  const dp = rad(b.lat - a.lat), dl = rad(b.lon - a.lon);
  const h = Math.sin(dp / 2) ** 2 +
    Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dl / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(h));
}
export function cumulative(fixes) {                  // adds d (m) to every fix
  let d = 0;
  return fixes.map((f, i) => ({ ...f, d: (d += i ? haversine(fixes[i - 1], f) : 0) }));
}

export function splits(track, every = 1000) {   // seconds for each full 'every' m
  const out = []; let mark = every, last = track[0].t;
  for (let i = 1; i < track.length; i++) {
    while (track[i].d >= mark) {                     // interpolate the crossing time
      const a = track[i - 1], b = track[i];
      const t = a.t + ((mark - a.d) / (b.d - a.d)) * (b.t - a.t);
      out.push(t - last); last = t; mark += every;
    }
  }
  return out;
}
```

**Listing 6.14.** Fixes to canvas pixels (`code/project.js`) (`code/project.js`)

```javascript
// Fixes to canvas pixels: a flat (equirectangular) map is fine for a run-sized area.
export function project(fixes, width, height, pad = 10) {
  const lat0 = fixes.reduce((s, f) => s + f.lat, 0) / fixes.length;
  const k = Math.cos((lat0 * Math.PI) / 180);        // a degree of longitude is shorter
  const xs = fixes.map((f) => f.lon * k), ys = fixes.map((f) => f.lat);
  const [x0, x1] = [Math.min(...xs), Math.max(...xs)];
  const [y0, y1] = [Math.min(...ys), Math.max(...ys)];
  const s = Math.min((width - 2 * pad) / (x1 - x0 || 1),
                     (height - 2 * pad) / (y1 - y0 || 1));
  return fixes.map((f, i) => [pad + (xs[i] - x0) * s, height - pad - (ys[i] - y0) * s]);
}
```

**Listing 6.15.** Known-answer tests (run with `node track.test.js`) (`code/track.test.js`)

```javascript
// Run with: node track.test.js   Known answers from the chapter's hand calculations.
import assert from "node:assert/strict";
import { haversine, cumulative, splits } from "./track.js";
import { project } from "./project.js";

const d = haversine({ lat: 40, lon: -111 }, { lat: 40.0001, lon: -111 });
assert.ok(Math.abs(d - 11.12) < 0.01);               // 0.0001 deg of latitude = 11.1 m

const fixes = [];                                    // due north at 3.336 m/s for 650 s
for (let t = 0; t <= 650; t++) fixes.push({ t, lat: 40 + 0.00003 * t, lon: -111 });
const track = cumulative(fixes);
const sp = splits(track, 1000);
console.log(d.toFixed(2), track.at(-1).d.toFixed(1), sp.map((s) => s.toFixed(1)));
assert.equal(sp.length, 2);                          // 2168 m holds two full km
assert.ok(Math.abs(sp[0] - 299.8) < 0.1);            // 1000 m / 3.336 m/s

const px = project([{ lat: 40, lon: -111 }, { lat: 40.001, lon: -110.999 }], 200, 200);
console.log(px.map((p) => p.map((v) => v.toFixed(1))));
```

```text
11.12 2168.3 [ '299.8', '299.8' ]
[ [ '10.0', '190.0' ], [ '147.9', '10.0' ] ]
```

The tests check the hand calculation of Example 6.1, a synthetic run due north at 3.336 m/s whose kilometer splits must be 299.8 s, and a map projection in which \ang{0.001} of longitude at \ang{40} draws shorter than \ang{0.001} of latitude (137.9 against 180 pixels). Listing 6.16 joins them in the page. It uses clock time from the file, so a paused run puts the pause inside a split; handling that is part of Exercise 6.19.

**Listing 6.16.** Load a GPX file in the page, report splits and draw the route (`code/load-gpx.js`) (`code/load-gpx.js`)

```javascript
// In the page: <input type="file" id="file" accept=".gpx"> and <canvas id="map">.
import { cumulative, splits } from "./track.js";
import { project } from "./project.js";

document.getElementById("file").addEventListener("change", async (e) => {
  const text = await e.target.files[0].text();
  const xml = new DOMParser().parseFromString(text, "application/xml");
  const pts = [...xml.getElementsByTagName("trkpt")];
  const t0 = Date.parse(pts[0].getElementsByTagName("time")[0].textContent);
  const fixes = pts.map((p) => ({
    lat: +p.getAttribute("lat"), lon: +p.getAttribute("lon"),
    t: (Date.parse(p.getElementsByTagName("time")[0].textContent) - t0) / 1000,
  }));
  const track = cumulative(fixes);
  console.log((track.at(-1).d / 1000).toFixed(2), "km; km splits (s):", splits(track));

  const canvas = document.getElementById("map"), ctx = canvas.getContext("2d");
  ctx.beginPath();
  project(fixes, canvas.width, canvas.height)
    .forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)));
  ctx.stroke();
});
```

Everything runs in the browser; the file never leaves the device. Before you load a teammate's route, de-identify it as in Section 6.3.

## Summary

- A satellite receiver measures signal travel times; position needs four satellites because the receiver's clock is a fourth unknown. Sky view, reflections, trees and the receiver's filter decide the error.

- Distance between fixes comes from the haversine formula; \ang{0.0001} of latitude is 11.1 m. Summed distance runs long when movement is small against position error and short on tight turns.

- One-second speed from positions is too noisy to use; averaging fixes it at the price of lag, about $(N-1)/2$ seconds for an $N$-second trailing mean on a ramp. Doppler speed is better than differenced positions.

- Elevation gain adds every rise, so noise becomes climb; barometric altitude also drifts with the weather.

- Before analysis, find the pauses (timer against elapsed time), the units (semicircles, per-leg cadence, half-metre distance) and the lap rule. De-identify routes before sharing.

- An accelerometer measures acceleration minus gravity. Steps come from impact peaks; cadence is reliable from many sites, contact time from the foot or lower back; running power is a model, cycling power a measurement.

- The energy cost of level running is about 3.4 J/kg/m, nearly independent of speed; grade and wind change it, so pace misleads on hills.

- Distance against time for best efforts is a line whose slope is critical speed and whose intercept is $D'$. It is a linear regression: report the slope in m/s, look at the residuals, and compare with a baseline.

- A repeated time stamp gives a zero time step and an infinite speed. Find such steps, apply a stated rule, count what it changed, and `assert` that time strictly increases.

- Load ratios are coupled and noisy; they describe training and do not predict injury.

*Table 6.2. Formulas of Chapter 6.*

| Haversine distance | Equation ch06-gps-motion:eq:haversine; $R = \SI{6371}{\kilo\metre}$ |
|---|---|
| Flat-map step | $\Delta x = R\cos\varphi\,\Delta\lambda$ , $\Delta y = R\,\Delta\varphi$ |
| Semicircles to degrees | $\text{value}\times180/2^{31}$ |
| Pace from speed | seconds per km $= 1000/v$ |
| Cadence | steps counted $\times 60/$ seconds; FIT value $\times 2$ |
| Step length | $v/(\text{cadence}/60)$ |
| Grade | rise / run |
| Pressure and height | $\Delta p = -\rho g\,\Delta h$ (about 8.5 m per hPa) |
| Critical speed | $d = \text{CS}\,t + D'$ ; $t_\text{lim} = D'/(v-\text{CS})$ |
| Load (Watch dashboard) | minutes $\times$ (HR / HR $_\text{max}$ ) $^2$ |
| Exponential average | $y \leftarrow y + (1-\ee^{-1/\tau})(x - y)$ |
| Acute:chronic ratio | mean of last 7 days / mean of last 28 days |

**New terms:** acute:chronic ratio, barometric altimeter, cadence, critical speed, $D'$, elapsed time, elevation gain, energy cost of running, equirectangular, fix, global navigation satellite systems, grade, gyroscope, haversine formula, inertial measurement unit, lap, linear regression, load, mean baseline, multi-band, multipath, power meter, record, residual, satellite receiver, semicircles, session, step, stride, timer time, trilateration, vertical oscillation, vertical ratio.

**Going further:** https://apmonitor.com/dde/index.php/Main/VideoData for data handling in Python, and https://apmonitor.com/pds/index.php/Main/CleanseData for removing bad values from a time series.

**Track it:** critical speed (`cs-two-effort`) and weekly running minutes (Appendix J).

## Exercises

> **Course use: Week 6.**
> 
> **H12** (due Class 12, *Measure*): 6.1, 6.2, 6.5, 6.8, 6.17, 11.28; about 90 minutes.
> 
> **H13** (due Class 13, *Model and tell*): 6.10, 6.19, 6.20, 6.21, 6.22, 6.24; about 225 minutes. Exercises from another chapter carry this week's syllabus topic. A case-file exercise may be done on your own data instead. The full map is in the Course Guide.

Your own routes, heart rates and loads are never graded or shared; where an answer depends on your data, you are graded on the method. De-identify any route before you give it to a teammate or an AI service (Section 6.3).

**Exercise 6.1** (Concept check · Foundation · 2 min · CORE)

A walker's watch adds 0.4 km to a 3 km walk that a runner's watch measures within 1% on the same path. What is the most likely reason?

(a) Walkers swing their arms more, which blocks the satellites.
(b) Position errors are large compared with the short distance moved between fixes, and summing them adds length.
(c) The walker's watch smooths more, so it cuts corners.
(d) Doppler speed does not work at walking speed.

**Exercise 6.2** (Concept check · Foundation · 2 min · CORE)

A FIT file from a running watch shows a cadence of 86 for most of a run. What was the runner's cadence?

(a) 86 steps a minute, a slow shuffle.
(b) 43 steps a minute.
(c) 172 steps a minute.
(d) 86 steps a minute per kilometer.

**Exercise 6.3** (Concept check · Core · 2 min)

Which of these watch outputs is *modeled* rather than measured or derived?

(a) Distance, summed from position fixes.
(b) Cadence, from accelerometer peaks.
(c) Elevation gain, summed from a barometer.
(d) Running power in watts from a wrist watch.

**Exercise 6.4** (Concept check · Core · 3 min)

The acute:chronic ratio is the mean daily load of the last 7 days divided by the mean of the last 28 days, which include those 7. What is the largest value it can take?

(a) 4.
(b) 1.
(c) 7.
(d) It has no upper limit.

**Exercise 6.5** (Hand calculation · Foundation · 10 min · CORE)

- Two fixes differ by \ang{0.0002} of latitude and nothing in longitude. How far apart are they? *Checkpoint:* {22.2 m.}

- Two fixes at \ang{40} of latitude differ by \ang{0.0001} of longitude only. How far apart are they? *Checkpoint:* {8.52 m.}

- A FIT file stores a latitude of 500000000 semicircles. What is it in degrees? *Checkpoint:* {\ang{41.91}.}

- What speed is a pace of 4:30 per km? What pace per mile is that? *Checkpoint:* {3.70 m/s; 7:14.5 per mile.}

Confirm (a) and (b) with the `haversine` function of Listing 6.1.

**Exercise 6.6** (Hand calculation · Core · 10 min)

A runner's two best efforts this season are 1600 m in 5:20 and 4800 m in 18:00.

- Find critical speed and $D'$, keeping the fraction. *Checkpoint:* {4.2105 m/s; 252.6 m.}

- What is $D'$ if you round CS to 4.21 first? *Checkpoint:* {252.8 m.}

- Give critical speed as a pace per km. *Checkpoint:* {3:57.5.}

- How long could the runner hold 4.6 m/s? *Checkpoint:* {About 649 s.}

Confirm with Listing 6.10 by changing the two trials.

**Exercise 6.7** (Hand calculation · Extension · 12 min)

Six short calculations from one training week.

- Eight laps in lane 1 read 3.15 km. What is the watch's error? *Checkpoint:* {$-1.6\%$.}

- You count 46 steps in 15 seconds. What is the cadence, and what would a FIT file store? *Checkpoint:* {184 steps/min; 92.}

- At 3.6 m/s and that cadence, how long is each step? *Checkpoint:* {1.17 m.}

- A climb gains 24 m in 400 m. What is its grade? *Checkpoint:* {6%.}

- A 50-minute run at a mean of 160 bpm, entered maximum 200. What load does the Watch dashboard give? *Checkpoint:* {32.}

- During a long run the air pressure falls by 2 \hecto\pascal because of the weather. About how much false climb can a barometric altimeter show? *Checkpoint:* {About 17 m.}

**Exercise 6.8** (App lab · Foundation · 30 min · CORE)

**Your own run in the Watch dashboard.** App: Watch dashboard, https://apopt.com/watch. Input: the FIT file (or GPX or TCX) of one of your own runs of 20 to 60 minutes, exported from your watch or phone.

- Enter your age and, if you know it from a strap, your maximum heart rate. Load the file. Save the PDF report and the text summary.

- Pick one number and confirm it by hand from the file: the doubled cadence against a 30-second step count you make on your next run, or one mile split converted to pace per km and checked against the dashboard's kilometer splits.

- Find the timer time and the elapsed time. Did you pause? Where?

- Open the run's detail and the report, and find one thing the summary card left out (pauses, a slow kilometer that the mile splits average away, the running-dynamics fields). Does it change your reading of the run?

- Write half a page: what you measured, what it shows, how sure you are, what you would change, when you would retest.

**Exercise 6.9** (App lab · Extension · 25 min)

**Load and its labels.** App: Watch dashboard, https://apopt.com/watch. Input: at least five weeks of your own runs (a ZIP of FIT files works).

- Read the latest workload ratio and its label, and the fitness, fatigue and form values.

- Compute the load of your longest run of the last week by hand from its minutes and mean heart rate, with Equation \eqref{ch06-gps-motion:eq:load}, and compare with the dashboard. Which maximum heart rate did it use?

- Change the maximum heart rate by 10 beats and reload. By what fraction did each run's load change? Did the ratio change?

- The dashboard labels a ratio above 1.5 “Load well above your recent average” and one from 0.8 to 1.3 a “sweet spot”. Using Section 6.6.3, write two sentences on what a ratio above 1.5 does and does not tell you, and say which of the two labels claims more than the ratio can show.

**Exercise 6.10** (Python analysis · Foundation · 25 min · CORE)

**Your own file, three ways.** Run Listings 6.1, 6.7 and 6.8 on `data/run.csv`. Known answers: 4840 m from positions against 4836 m from the device over 1492 steps; kilometer splits 298.3, 288.0, 303.8, 354.0 and 301.9 s; cadence 177. Then run Listing 6.6 on a FIT file of your own (or read a GPX file with `gpxpy`) and report: number of records, pauses, timer and elapsed time, distance from positions against the device's distance, and your kilometer splits. *Predict before you run:* will your summed distance be longer or shorter than the watch's?

**Exercise 6.11** (Python analysis · Core · 45 min)

**Chest motion: steps and breaths** (strap exercise H-14). Equipment: the chest strap with the Heart app's Live Capture (https://apopt.com/heart), or a phone held flat on the sternum by an elastic band with a sensor-logging app that saves acceleration to CSV.

- Known-answer test: Listing 6.9 on `data/chest-acc.csv` must print 86 steps at 171.9 steps/min and 15.0 breaths a minute.

- Record one file: two minutes walking, two minutes jogging, then lie on your back and keep still for three minutes. Count your steps for 30 seconds while jogging and your breaths for one minute while lying.

- Load your file. Find which axis carries the footstrikes and which one changes with breathing (plot all three).

- Run the listing's `rate` function on each part, adjusting the filter bands and the minimum gap. Compare with your counts and, for a live capture, with the Heart app's cadence and breathing panels.

Safety: jog only at an easy pace on a safe surface. Breathing and heart numbers are yours and are not graded.

**Exercise 6.12** (Python analysis · Extension · 30 min)

**Noise, correlation and lag.** Start from Listings 6.2 and 6.3.

- Change the loop to `for rho in (0.0, 0.9, 0.99):`. How does the distance error change with $\rho$? *Checkpoint:* {About $+85\%$, $+9\%$, $+1\%$.}

- For $\rho = 0.9$, how long must a trailing window be for the speed scatter to fall below 0.1 m/s (3% at 5:00 per km)? Try windows of 10, 30 and 60 seconds.

- For the window you chose in (b), how long does the display take to show 90% of a sudden surge? What does that mean for a 60-second repeat?

**Exercise 6.13** (Body science · Foundation · 5 min)

An accelerometer lying still on a table reads $1\,g$ upward. In free fall it reads zero. Explain both in two sentences each, and say why this lets a chest sensor see breathing when you lie still but makes it harder to see on a run.

**Exercise 6.14** (Body science · Core · 8 min)

A runner can hold 4.2 m/s for an hour but 4.5 m/s for only about 13 minutes. Her critical speed is 4.29 m/s. Explain, for a reader who has not studied physiology, what changes in her body between the two speeds and why the second effort ends.

**Exercise 6.15** (Science of the sport · Foundation · 8 min)

A 60 kg runner races a half marathon (21.0975 km) on a level course.

- Using 3.40 J/kg/m, how much energy does the run cost, in kJ and kcal? *Checkpoint:* {4304 kJ; 1029 \kcal.}

- Her watch says 1350 calories. Give two reasons for the difference.

- On a hilly course, should she pace by the watch's pace? Explain with the energy cost of grades.

**Exercise 6.16** (Science of the sport · Extension · 10 min)

The runner of Example 6.6 (CS 4.2857 m/s, $D'$ 171.4 m) plans $400$ m repeats at 5.0 m/s.

- How long does each repeat take, and how much of $D'$ does it use? *Checkpoint:* {80 s; 57.1 m.}

- With no recovery at all, how many repeats could she run? *Checkpoint:* {3.0.}

- Why can she in practice run eight or ten, and what decides how many?

**Exercise 6.17** (Field collection · Foundation · 40 min · CORE)

**Track check of your watch.** Equipment: your watch or phone, a 400 m track you are allowed to use, a stopwatch.

- Check that the track is free for laps and that you may use lane 1. Warm up for ten minutes, easy.

- Start a recording and wait 30 seconds still, so the receiver has a fix. Note the sky view (open, stands, trees).

- Run ten laps in lane 1, about 30 cm from the inside edge, at an easy steady pace. During lap 5, count your steps for 30 seconds.

- Stop, save, and record the watch's distance, time, average cadence and lap splits.

- Compute the watch's percentage error against 4000 m, your counted cadence against the watch's, and pace from distance and time against the watch's average pace.

- Repeat on another day, at another time, and once more in lane 4 or with track mode if your watch has it.

Safety: run at an easy pace; give way to faster runners; stop if unwell. No consent is needed for your own data. If you record a teammate's run, get their written consent first on the form of Section E.2 (for a teammate under 18, a parent's or guardian's written consent and the athlete's own assent), and they choose whether to share their numbers.

**Exercise 6.18** (Field collection · Core · 30 min)

**Cadence three ways.** With a teammate. Equipment: a watch that records cadence, a phone on a tripod, a metronome app.

- Get your teammate's written consent on the form of Appendix E (Section E.2) to film them and record their cadence, and agree that the clip stays within the team. For a teammate under 18: a parent's or guardian's written consent and the athlete's own assent (Section E.4).

- Your teammate runs three 2-minute bouts at an easy pace on a straight, with a metronome at 160, 170 and 180 steps/min, walking 1 minute between.

- Film 10 seconds of each bout from the side at 60 fps or more and analyze it with the Running app (https://apopt.com/form/form.php, Chapter 9).

- Count steps for 30 seconds in each bout.

- Read the watch's cadence for each bout from its file (remember to double it).

Report a table of three bouts by three methods, and say which method you would trust and why. Safety: easy pace, a clear straight, stop if unwell.

**Exercise 6.19** (Build · Core · 90 min · CORE)

**Build step B-6: an activity file on a map** (W-6, W-7). Work in your Vite project from earlier weeks. Prompt your AI assistant for each part, then test it.

- Load a GPX file and compute cumulative distance with the haversine formula. Test: \ang{0.0001} of latitude must give 11.12 m, and the due-north synthetic run of Listing 6.15 must give kilometer splits of 299.8 s.

- Draw pace (from a 10-second trailing mean of speed), heart rate and elevation against distance on canvases.

- Draw the route with the projection of Listing 6.14, and show a table of kilometer splits.

- Handle pauses: treat any gap longer than 5 seconds as a pause, exclude it from split times, and test with a synthetic file that pauses for 60 seconds at 500 m: the first split must still be 299.8 s.

- Optional: read FIT files with a parsing library, and remember the semicircles.

**Exercise 6.20** (Communicate · Core · 30 min · CORE)

**A weekly summary for a coach.** Use four or more weeks of your own runs in the Watch dashboard (or the synthetic season of Listing 6.12, week 11). Write a summary of the latest week for a coach: three numbers, one chart, one recommendation, and one sentence on what the numbers cannot see. Compare it with the two summaries of Section 6.8.

**Exercise 6.21** (Check the AI · Core · 10 min)

An AI assistant wrote this to compute the distance of a route from a GPX file:
`d = np.hypot(np.diff(lat), np.diff(lon)) * 111195  # metres per degree`

`total = d.sum()`

On a route at \ang{40} north that goes \ang{0.01} north and then \ang{0.01} east, what does it give, what is the true distance, and what is wrong? Fix the line.

**Exercise 6.22** (Python analysis · Core · 25 min)

Core. Start from Listing 6.11 and the three trials: 1200 m in 240 s, 2200 m in 480 s, 3600 m in 800 s.

- Fit $d = \text{CS}\,t + D'$ and give both numbers with units, and the RMSE. *Checkpoint:* {4.291 m/s; 159 m; RMSE 13.4 m.}

- Fit the harder baseline $d = v\,t$: one constant speed and no intercept (in scikit-learn, set `fit_intercept=False` when you make the model). Report $v$, its residuals and RMSE. *Checkpoint:* {4.552 m/s; residuals 107.6, 15.2, -41.4 m; RMSE 67.1 m.}

- Leave out the 2200 m trial, fit each model to the other two, and predict it. Which model predicts it better? *Checkpoint:* {Line: 2228.6 m (error -28.6 m); constant speed: 2179.8 m (error +20.2 m).}

- The line fits all three trials better, yet loses the test in (c). What does that tell you, and what would you need to settle which model is better?

**Exercise 6.23** (Hand calculation · Core · 12 min)

Two watch files hold the same six records except one distance. Times (s): 10, 11, 12, 12, 13, 14. Distances (m), file A: 30.0, 33.0, 36.0, 36.0, 39.0, 42.0; file B: 30.0, 33.0, 36.0, 37.5, 39.0, 42.0.

- Compute the five interval speeds of each file as NumPy would, writing `inf` or `nan` where the division is not a number. *Checkpoint:* {A: 3, 3, nan, 3, 3 m/s; B: 3, 3, inf, 1.5, 3 m/s.}

- pandas skips `nan` when it takes a mean, but not `inf`. What mean speed does each file report? *Checkpoint:* {A: 3.0 m/s; B: inf.}

- Apply the rule of Listing 6.5 (drop a record whose time does not increase) and give the speeds and the mean pace. *Checkpoint:* {3, 3, 3, 3 m/s for both; 5:33 per km (333 s).}

- File A's mean looked right before the rule. Why is that a reason to apply the rule anyway?

**Exercise 6.24** (Python analysis · Core · 45 min)

Case file: use your case-file athlete's watch archive (see https://apopt.com/data/athletes) to fit a speed–duration line.

- For every running activity, find the greatest distance covered in any window of 3, 6, 10 and 20 minutes of timer time (pauses removed, Listing 6.7), using the device distance field. Keep the best of the archive for each duration. Check every file for repeated time stamps first (Listing 6.5). *Checkpoint:* {Best distance rises with duration and mean speed falls; if a longer window has a higher mean speed than a shorter one, the shorter best was not a hard effort.}

- Fit $d = \text{CS}\,t + D'$. Report both with units, and the residuals. *Checkpoint:* {$D' > 0$ and CS lies below the mean speed of every window you fitted.}

- Compare the line's RMSE with the mean baseline and with the constant-speed baseline of Exercise 6.22.

- Refit without the 3-minute window. *Checkpoint:* {The two CS estimates agree within a few percent; if not, say which window you distrust and why.}

**Exercise 6.25** (Python analysis · Core · 35 min)

Case file: chart weekly training load from your case-file athlete's watch archive (see https://apopt.com/data/athletes).

- Score every activity with Equation \eqref{ch06-gps-motion:eq:load} as in Listing 6.12, using timer minutes and mean heart rate. Use the maximum heart rate the case file gives; if it gives none, the highest heart rate in the archive, and say which you used. *Checkpoint:* {Activities without heart rate are listed and left unscored, not scored as zero.}

- Sum the scores by calendar week on a complete calendar, so a week with no activity appears as zero. *Checkpoint:* {The sum of the weekly loads equals the sum of the activity loads; the number of weeks equals the span of the archive.}

- Draw weekly load as bars with a four-week rolling mean as a line, axes labeled with units, and write a caption of two sentences: one observation, then one possible explanation marked as such.

- In one sentence for a coach, say what the chart cannot show.
