# Q-17: Split a run into laps

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

Web page: https://apopt.com/course/tutorials/q17-laps/ · Data: https://apopt.com/data/tutorials/q17-laps/

## The decision

A coach wants each repeat of an interval session as one row: distance, time and speed. The
watch has one record a second and its own lap summaries. Can you rebuild the laps, and do
they match?

## The raw data

- `raw/2026-05-11_1507_running.csv`: one record a second from the instructor's run of 11 May 2026 (time, elapsed_s, distance_m, speed_mps, heart_rate_bpm, cadence, altitude and running dynamics; no positions) The instructor's own watch, converted from FIT to CSV with GPS removed, from the course case file `athletes/jh/watch/`, published under his name.
- `raw/laps.csv`: the watch's lap summaries for all 19 runs in the case file (activity_id, lap, start_time, timer_s, distance_m, heart rate, cadence, ascent, power) Same case file.

On 11 May 2026 the instructor ran a session with a set of short, fast repeats in the middle,
pressing the lap button at the start and end of each. The watch saved one record a second and
a summary of each lap. You will split the records into the laps yourself, check your laps
against the watch's, and pick out the fast ones.

### Open the records and the laps

*Predict first:* How many laps do you think the watch saved for a session with nine fast repeats?

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

rec = pd.read_csv("raw/2026-05-11_1507_running.csv", parse_dates=["time"])
laps = pd.read_csv("raw/laps.csv", parse_dates=["start_time"])
laps = laps[laps["activity_id"] == "2026-05-11_1507_running"].reset_index(drop=True)
gap = rec["time"].diff().dt.total_seconds()
print(f"{len(rec)} records over {rec['elapsed_s'].iloc[-1] / 60:.0f} min of clock time; {len(laps)} laps")
print(f"{int((gap > 1).sum())} pauses (gaps over 1 s), adding up to {gap[gap > 1].sum() / 60:.0f} min")
```

Output:

```
3746 records over 94 min of clock time; 22 laps
21 pauses (gaps over 1 s), adding up to 32 min
```

The watch was paused 21 times, for over half an hour in all: a pause between repeats is
normal in a session like this. Time running is what matters for pace, so count only the
one-second steps.

### Put each record in its lap

A record belongs to the last lap that started at or before it. `np.searchsorted` finds that
lap for every record at once. Then each lap's running time is the sum of its one-second steps,
and its distance is the watch's distance at the next lap's start minus at its own.

*Predict first:* Will your lap times match the watch's to the second?

```python
rec["lap"] = np.searchsorted(laps["start_time"].values, rec["time"].values, side="right")
rec["step_s"] = gap.where(gap <= 1, 0).fillna(0)          # pauses add no running time
g = rec.groupby("lap")
start = g["distance_m"].first().to_numpy()
mine = pd.DataFrame({"time_s": g["step_s"].sum().to_numpy(),
                     "dist_m": np.diff(np.r_[start, rec["distance_m"].iloc[-1]]),
                     "hr_bpm": g["heart_rate_bpm"].mean().round(0).to_numpy()}, index=laps["lap"])
mine["speed_mps"] = mine["dist_m"] / mine["time_s"]
print(f"largest difference from the watch's laps: time {np.abs(mine['time_s'] - laps['timer_s'].to_numpy()).max():.1f} s, "
      f"distance {np.abs(mine['dist_m'] - laps['distance_m'].to_numpy()).max():.1f} m")
print(mine.round(2).T.to_string())
```

Output:

```
largest difference from the watch's laps: time 6.4 s, distance 3.3 m
lap             1        2       3       4       5       6       7       8       9       10     11      12      13      14      15      16      17      18      19      20       21       22
time_s      557.00   501.00  275.00   54.00   68.00   32.00  110.00   15.00  146.00   55.00   73.0   51.00  157.00   31.00   97.00   33.00  103.00   32.00  113.00   31.00   726.00   464.00
dist_m     1606.00  1611.00  793.00  298.00  125.00  195.00  243.00   95.00  280.00  311.00  102.0  299.00  327.00  199.50  219.50  194.50  215.50  199.00  219.00  192.00  1609.00  1153.00
hr_bpm      132.00   132.00  129.00  126.00  150.00  146.00  154.00  163.00  135.00  135.00  154.0  155.00  145.00  120.00  163.00  170.00  168.00  155.00  162.00  155.00   131.00   129.00
speed_mps     2.88     3.22    2.88    5.52    1.84    6.09    2.21    6.33    1.92    5.65    1.4    5.86    2.08    6.44    2.26    5.89    2.09    6.22    1.94    6.19     2.22     2.48
```

The distances agree within a few metres. The times agree within a second on most laps and
within about 6 seconds on the long ones: the watch counts fractions of a second around each
pause that whole-second records cannot see.

### The fast laps

```python
import matplotlib.pyplot as plt

fast = mine[mine["speed_mps"] > 5]
print(f"{len(fast)} fast laps: {fast['dist_m'].min():.0f} to {fast['dist_m'].max():.0f} m "
      f"at {fast['speed_mps'].min():.1f} to {fast['speed_mps'].max():.1f} m/s")
edges = np.r_[0, mine["time_s"].cumsum()] / 60
fig, ax = plt.subplots(figsize=(9, 3.2))
ax.stairs(mine["speed_mps"], edges, color="k", lw=1.2)
ax.plot((edges[:-1] + edges[1:])[mine["speed_mps"] > 5] / 2, fast["speed_mps"], "o", mfc="none", label="fast lap")
ax.set(xlabel="running time (min, pauses removed)", ylabel="lap speed (m/s)")
ax.legend(loc="upper left")
plt.tight_layout()
```

Output:

```
9 fast laps: 95 to 311 m at 5.5 to 6.4 m/s
```

![A step chart of speed in metres per second against running time in minutes, one step per lap. Nine short steps rise to between 5.5 and 6.4 m/s, separated by slow recovery laps near 2 m/s, between longer laps near 3 m/s at the start and 2.2 to 2.5 m/s at the end.](https://apopt.com/course/tutorials/q17-laps/c05-1.png)

Nine fast laps stand out, 95 to 311 m each, separated by slow recovery jogs. A lap table is
the step between a one-second record and a training question: each fast lap is now one row
with a distance, a time and a speed, ready for the case study CS-7.

**For the athlete:** "Your nine repeats on 11 May ran at 5.5 to 6.4 metres a second; the lap
button did its job, and the laps we rebuilt from your records match your watch's."

## With your own data

Export one of your own interval sessions (Q-16 shows how to turn a FIT file into CSV), with
the lap button pressed at the start and end of each repeat, and run the same cells on it.

## Action card

- **Finding:** The session held nine fast repeats of 95 to 311 m at 5.5 to 6.4 m/s.
- **Evidence:** The laps rebuilt from the records match the watch's within 3.3 m and about 6 s.
- **Sure:** High for distance and lap boundaries; lap times carry up to a second per pause.
- **Action:** Use the rebuilt lap table, one row per repeat, for pacing questions.
- **Retest:** Press the lap button at the start and end of every repeat in the next session too.

## References

- *Data-Driven Athletics*, Chapter 6, Splits, pauses and resampling (Section 6.3).

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