# Q-26: Cadence from a cycle length

Data-Driven Athletics tutorial · Week 9 · Chapter 9 · about 15 min · workflow steps: Features

Web page: https://apopt.com/course/tutorials/q26-cadence/ · Data: https://apopt.com/data/tutorials/q26-cadence/

## The decision

A runner's cadence is the first number a coach asks for. From a 30-frames-per-second clip,
which way of computing it gives a number good to a step or two a minute?

## The raw data

- `raw/form1_ankles.csv`: both ankles' image position and confidence in every frame of a treadmill run filmed from behind at 30 frames per second (464 rows) Chapter 9's example table, also published with the book's data (`book/ch09-gait`).

**Cadence** is steps per minute. A **stride** is one foot's contact to that foot's next
contact, and holds two steps, so

cadence = 60 / step time = 120 / stride time.

The ankle table is Chapter 9's treadmill runner, filmed from behind at 30 frames per second.
Three ways to get the cycle length give three cadences. Find out why, and which to report.

```python
import numpy as np
import pandas as pd
from scipy.signal import find_peaks

FPS = 30
df = pd.read_csv("raw/form1_ankles.csv")
y = df["l_ankle_y"].to_numpy()
z = y - y.mean()
ac = np.correlate(z, z, "full")[len(z) - 1:] / (z @ z)     # 1 at lag 0
lo, hi = int(0.4 * FPS), int(1.5 * FPS)                     # strides of 0.4 to 1.5 s
lag = lo + int(np.argmax(ac[lo:hi]))
print(f"stride {lag} frames = {lag / FPS:.3f} s -> cadence {120 * FPS / lag:.1f} steps/min")
```

Output:

```
stride 21 frames = 0.700 s -> cadence 171.4 steps/min
```

### Way 2 and Way 3 · From the contacts

Find each foot's contacts, at most one per 0.6 of a stride, merge the two feet into one list
of steps, and take either the **median** step or the **span**: the number of steps divided
by the time from the first contact to the last.

*Predict first:* Every step lasts a whole number of frames. If the true step is 0.353 s (10.6 frames), what will the median step be?

```python
t = []
for side in "lr":
    s = df[f"{side}_ankle_y"].to_numpy()
    peaks, _ = find_peaks(s, distance=int(0.6 * lag), height=np.percentile(s, 70))
    t += list(peaks / FPS)
t = np.sort(t)
steps = np.diff(t)
print(f"{len(t)} contacts, {len(steps)} steps; step lengths in frames: "
      f"{pd.Series(np.round(steps * FPS).astype(int)).value_counts().sort_index().to_dict()}")
print(f"median step {np.median(steps):.3f} s -> {60 / np.median(steps):.1f} steps/min")
print(f"span: {len(steps)} steps in {t[-1] - t[0]:.2f} s -> {60 * len(steps) / (t[-1] - t[0]):.1f} steps/min")
slope = np.polyfit(np.arange(len(t)), t, 1)[0]              # seconds per step, all contacts at once
print(f"line through all contacts: {slope:.4f} s per step -> {60 / slope:.1f} steps/min")
```

Output:

```
44 contacts, 43 steps; step lengths in frames: {8: 2, 9: 3, 10: 14, 11: 16, 12: 6, 13: 2}
median step 0.367 s -> 163.6 steps/min
span: 43 steps in 15.23 s -> 169.4 steps/min
line through all contacts: 0.3535 s per step -> 169.7 steps/min
```

```python
import matplotlib.pyplot as plt

frames = np.round(steps * FPS).astype(int)
counts = pd.Series(frames).value_counts().sort_index()
fig, ax = plt.subplots(1, 2, figsize=(8, 3.2), gridspec_kw={"width_ratios": [1, 1.3]})
ax[0].bar(counts.index, counts.values, color="gray", edgecolor="black")
ax[0].set(xlabel="step length (frames at 30 per second)", ylabel="number of steps")
grid = 60 * FPS / np.arange(9, 13)                          # cadences a whole-frame step can give
ax[1].plot(np.arange(9, 13), grid, "o--", color="gray", label="whole-frame steps")
ax[1].axhline(60 * len(steps) / (t[-1] - t[0]), color="black", lw=2, label="span of all steps")
ax[1].set(xlabel="step length (frames)", ylabel="cadence (steps/min)")
ax[1].legend(fontsize=8)
plt.tight_layout()
```

![Left, bar chart of step lengths in frames from 8 to 13, most of them 10 or 11. Right, the cadence each whole-frame step length gives (200, 180, 163.6 and 150 steps per minute) with a horizontal line for the span estimate, 169.4, which falls between the 10- and 11-frame values.](https://apopt.com/course/tutorials/q26-cadence/c04-1.png)

At 30 frames per second a step can only be read as a whole number of frames: 10 frames gives
180 steps a minute, 11 frames gives 163.6, and nothing in between. Most of this runner's steps
(30 of 43) are 10 or 11 frames, so the median lands on one of them, 163.6 here, and the
autocorrelation's stride of 21 frames lands on 171.4. The span uses every step at once, so the rounding at its two ends
is shared by 43 steps: 169.4 steps a minute, and a straight line through all the contact times
agrees with it (169.7). The key idea from Chapter 9: a median of rounded intervals is still rounded;
estimate a rate from many events at once.

**For the athlete:** your cadence from this clip is about 169 steps a minute; read it from the
whole run, not from one or two steps.

## With your own data

Run Q-25 and this page on your own two-ankle table, then count your steps over 30 s of the
same clip by hand, double the count, and compare.

## The same method in another field

Any rate measured from events on a sampled clock, from shaft revolutions on a tachometer to
heartbeats in a 250 Hz ECG, has the same choice: rate from the span of many events, not from
the median of single intervals.

## Acknowledgements

Ankle table from Chapter 9 of *Data-Driven Athletics*.

## References

- Chapter 9 of *Data-Driven Athletics*: Period first, then events; The frame budget.

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