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

> Hedengren, J. (Ed.) (2027). Chapter 9: Gait and Cyclic Sports. In *Data-Driven Athletics: Measuring, Modeling and Coaching Human Performance with Video and Wearable Data* (pp. 236–262). IRSRI Sports Research Institute. CC BY 4.0.

**Question.** Is this runner overstriding, or is the camera angle making it look that way?

**Objectives.**
- Find the period of a repeating movement first, then detect the events inside each cycle, in a keypoint trace.
- Compute cadence, contact time, flight time, duty factor and step length, and say which of them need a scale.
- Explain the running form measures a coach asks about, and grade the evidence behind each.
- Apply the same method to walking, pedaling and swimming, and name the reference each sport gives you for free.
- Design a small study with a metronome and a tape measure, and turn its result into one cue for a runner.

# 9 Gait and Cyclic Sports

Running, walking, pedaling and swimming share one property that makes them
easier to measure than a jump or a throw: they repeat. A runner at a steady
pace takes the same step hundreds of times, and a video of fifteen seconds
holds forty of them. One noisy step is hard to read; forty steps averaged are
not. The price is a new first job. Before you can measure a step you have to
find where each step begins and ends, and a computer has no idea where that
is until you tell it how to look.

This chapter teaches one method for all four sports: *find the period
first, then the events*. You will apply it to a real ankle trace from a
treadmill runner, then to walking, to the pedal stroke and to the swimming
stroke. Along the way you will meet the measures a coach asks about, such as
cadence, overstride and hip drop, and you will learn how strong the evidence
behind each one is. For several of them it is weaker than the confidence with
which they are usually taught. The pose model, the scale and the four levels
of error come from Chapter 8; this chapter uses them without
repeating them.

## 9.1 Cycles and Events

A *cyclic movement* is one whose pattern repeats. Its *period* is the
time one repetition takes, and its *events* are the instants inside a
cycle that the measurement is built on: the foot touching the ground, the
pedal at the bottom of its circle, the hand entering the water. Almost every
number in this chapter is either a time between events or a quantity read at
an event. Knee angle is read at foot contact; contact time runs from contact to
toe-off; cadence counts contacts per minute. An event placed two frames late
moves every one of those numbers.

### 9.1.1 The running example

Our running example is the clip `form1_30fps.mp4` from the course
examples: a runner on a treadmill, filmed from behind at 30 fps for
15.5 s. Listing 9.1 runs the YOLO pose model of
Chapter 8 on it and keeps only the two ankles. The model found a
person in all 464 frames, and the median ankle confidence was 0.99, so the
trace is clean.

**Listing 9.1.** Two ankle traces from a running clip.

```python
from ultralytics import YOLO
import pandas as pd
model = YOLO("yolo26n-pose.pt")          # the nano (smallest) pose model
rows = []
for i, r in enumerate(model("form1_30fps.mp4", stream=True, verbose=False)):
    if r.keypoints is None or len(r.keypoints) == 0:
        continue
    xy, c = r.keypoints.xy[0].tolist(), r.keypoints.conf[0].tolist()
    rows.append([i, i / 30, *xy[15], c[15], *xy[16], c[16]])  # ankles 15, 16; 30 fps
cols = ["frame", "t", "l_ankle_x", "l_ankle_y", "l_ankle_c",
        "r_ankle_x", "r_ankle_y", "r_ankle_c"]
pd.DataFrame(rows, columns=cols).to_csv("form1_ankles.csv", index=False)
```

Figure 9.1 plots the vertical image position of each
ankle for the first four seconds. Image $y$ grows downward, so the plot turns
the axis over: down on the page is down in the world. Each foot drops to the
belt, stays there for a moment, lifts, swings and drops again. The two feet
take turns. That is the whole of running, seen through one keypoint.

*Figure 9.1. The ankle traces of the running example (treadmill, filmed from behind, 30 fps), first four seconds. The axis is reversed, so a foot on the belt is at the bottom. Dots mark the lowest point of each stance, found by the peak search of Listing 9.6 (`thresholds.py`). One stride (same foot to same foot) is 21 frames, 0.70 s.*

### 9.1.2 Period first, then events

A tempting first program looks for every low point of the ankle and calls it a
contact. It fails on real data, because a noisy trace has many small dips, and
a doubled dip counts one step twice. The fix is to ask a different question
first: *how long is one cycle?* Once you know the period, you can tell the
event detector that two contacts of the same foot cannot be closer than, say,
six tenths of a period. The period does the thinking that a hand-tuned
threshold would otherwise have to do.

The tool for the period is the *autocorrelation*: slide a copy of the
trace along itself and see at which shift the two line up best. For a
repeating signal the best match, after a shift of zero, is a shift of one
period.

> **Engineer's note: Autocorrelation in one line.**
> 
> For a trace $y_k$ with its mean removed, the autocorrelation at lag $\ell$
> frames is
> 
$$>   R(\ell) = \frac{\sum_k y_k\,y_{k+\ell}}{\sum_k y_k^2}.
>$$

> $R(0)=1$. If the trace repeats every $N$ frames, $R(N)$ is close to 1 again,
> and lags in between give smaller values. Restrict the search to plausible
> periods (for a running stride, 0.4 to 1.5 s) so that a
> half-period match, one foot against the other, is never taken for a full
> one. The result is a whole number of frames; Exercise 9.12
> shows how to refine it.

Listing 9.2 finds the stride period from the left ankle,
then finds one contact per period on each foot and merges the two feet into a
single list of steps.

**Listing 9.2.** Find the period first, then the events. (`code/period_first.py`)

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

FPS = 30.0
df = pd.read_csv("form1_ankles.csv")
y = df["l_ankle_y"].to_numpy()               # image y grows downward

# 1. Period: the lag where the trace best matches a shifted copy of itself
z = y - y.mean()
ac = np.correlate(z, z, "full")[len(z) - 1:] / (z @ z)
lo, hi = int(0.4 * FPS), int(1.5 * FPS)      # strides of 0.4-1.5 s
lag = lo + np.argmax(ac[lo:hi])
print(f"stride period {lag} frames = {lag / FPS:.3f} s")

# 2. Events: one lowest-foot peak per period, at least 0.6 period apart
ic = {}
for side in ["l", "r"]:
    s = df[f"{side}_ankle_y"].to_numpy()
    ic[side], _ = find_peaks(s, distance=int(0.6 * lag),
                             height=np.percentile(s, 70))
t = np.sort(np.concatenate([ic["l"], ic["r"]])) / FPS
steps = np.diff(t)
print("contacts L, R:", len(ic["l"]), len(ic["r"]))
print(f"median step {np.median(steps):.3f} s -> {60 / np.median(steps):.0f} steps/min")
print(f"{len(steps)} steps in {t[-1] - t[0]:.2f} s -> "
      f"{60 * len(steps) / (t[-1] - t[0]):.0f} steps/min")
```

Its output:

```text
stride period 21 frames = 0.700 s
contacts L, R: 22 22
median step 0.367 s -> 164 steps/min
43 steps in 15.23 s -> 169 steps/min
```

Two answers for one runner. Which is right? At 30 fps a step can only
last a whole number of frames: 10 frames is 0.333 s, 11 frames is
0.367 s. This runner's true step lies between the two, so the
measured steps alternate between 10 and 11 frames, and the *median* picks
one of them. That gives either 180 steps/min or 164 steps/min, never the true
value in between. Counting all 43 steps over the 15.23 s from the
first contact to the last uses every event, and the rounding at the two ends
is spread over the whole span: 169 steps/min. The lesson reaches beyond this
clip.

> **Key idea.**
> 
> A median of rounded intervals is still rounded. When events sit on a frame
> grid, estimate a rate from the *span* of many events (or a straight line
> through all of them), not from the median of single intervals.

The rest of the chapter reuses this pattern. Walking, pedaling and swimming
each need a different signal, but every detector does the same three things:
build a one-number-per-frame trace in which the event is an extreme, learn the
period or a minimum spacing, then accept extremes that are both large enough
and far enough apart.
Table 9.1 shows the four versions side by side.

The same three steps fit in a dozen lines of JavaScript, which is this week's
build step (Exercise 9.20). Listing 9.3
keeps the rule of the apps: a peak must reach a level and be at least
`minGap` samples from the last one, and a taller peak inside the gap
replaces the earlier one, so a doubled peak counts once.

**Listing 9.3.** An event detector for the student app (`peaks.js`). (`code/peaks.js`)

```javascript
export function peaks(y, minGap, level) {
  const out = [];
  for (let i = 1; i < y.length - 1; i++) {
    if (!(y[i] >= y[i - 1] && y[i] > y[i + 1] && y[i] >= level)) continue;
    const last = out[out.length - 1];
    if (last === undefined || i - last >= minGap) out.push(i);
    else if (y[i] > y[last]) out[out.length - 1] = i;
  }
  return out;
}
// Events per minute from the first to the last event.
export function ratePerMin(idx, fps) {
  if (idx.length < 2) return null;
  return (60 * (idx.length - 1) * fps) / (idx[idx.length - 1] - idx[0]);
}
```

*Table 9.1. One method, four sports: the trace each app builds, the event that is an extreme of it, how the spacing of events is guarded, and the reference each sport gives you for free. Rules checked in the app source on 2026-11-26.*

| Sport | Trace | Event | Spacing guard | Free reference |
|---|---|---|---|---|
| Running | Foot height in the image (heel, else ankle) | Lowest point: contact | At least 0.2 s; stance 0.08–0.45 s | Metronome; taped 20 m |
| Walking | Ankle ahead of hip, along the path | Foot furthest forward: near heel strike | At least $\max(8, 0.3f)$ frames; stance 32–78% of the cycle | Timed 10 m; floor marks |
| Cycling | Hip-to-ankle distance | Maximum: leg most extended | At least $\max(5\text{ frames}, \SI{0.22}{\second})$ | Ruler on the seat post; crank length |
| Swimming | Wrist gap (breast, fly) or one wrist from body center (free, back) | Maximum: one arm cycle | At least 0.45 s (0.75 s breast) | Pace clock; lane marks; stroke count |

## 9.2 Running: Contact and Flight

> **Body science: The running cycle.**
> 
> A *stride* runs from one foot's contact to the next contact of the same
> foot; a *step* runs from one foot's contact to the other foot's contact.
> One stride is two steps. Each leg spends part of the stride in
> *stance* (on the ground) and the rest in *swing*. In running the
> two stances do not overlap: between them both feet are off the ground, the
> *flight* phase. The stance leg behaves like a spring. It compresses
> after contact as the knee and ankle bend, storing energy in tendons such as
> the Achilles, and recoils to push the body up and forward. In walking the
> stances overlap instead, and the body vaults over a nearly straight leg
> (Section 9.5).

### 9.2.1 The five temporal measures

With contacts and toe-offs found, five numbers follow without any scale.

$$\text{cadence} &= \frac{60}{t_{\text{step}}}\ \text{steps/min}, \\
  t_c &= t_{\text{toe-off}} - t_{\text{contact}}, \\
  t_f &= t_{\text{contact, next foot}} - t_{\text{toe-off}}, \\
  D &= 100\,\frac{t_c}{T_{\text{stride}}}\ \%, \\
  L_{\text{step}} &= \frac{60\,v}{\text{cadence}}.$$

*Cadence* (also called step rate) is steps per minute. *Contact
time* $t_c$ is how long one foot is on the ground. *Flight time* $t_f$ is
how long both feet are off. The *duty factor* $D$ is the share of the
stride a foot spends on the ground; note the denominator is the stride
$T_{\text{stride}}$, two steps, not one. Running at ordinary speeds gives $D$
well under 50%, and a value above 50% means two stances overlap: walking, or
a detector error. Step length needs a speed $v$, and therefore a scale or a
treadmill reading; the first four do not.

> **Check it by hand: Cadence and duty factor.**
> 
> A runner's contacts are 0.345 s apart on average. Cadence is
> $60/0.345 = 174 steps/min$. Each contact lasts 0.25 s and a
> stride is 0.70 s, so $D = 100\times0.25/0.70 = 36%$. If you had
> divided by a step (0.35 s) you would have reported 71%, a walking
> value for a running athlete. Step length at 3.5 m/s and
> 172 steps/min is $60\times3.5/172 = 1.22 m$.
> *Confirm it:* run Listing 9.4 below, and open the
> running app's Advanced mode on your own clip; its duty factor uses the same
> stride denominator.

**Example 9.1: Steps over a taped 20 meters.**

You tape two lines 20 m apart on a path, with room to reach pace before the
first. A runner crosses the section in 6.6 s, and a partner counts
18 steps between the lines. Then

$$v &= 20/6.6 = \SI{3.03}{\metre\per\second}, &
  L_{\text{step}} &= 20/18 = \SI{1.11}{\metre}, &
  \text{cadence} &= 60\times18/6.6 = \SI{163.6}{\spm}.$$

Equation \eqref{ch09-gait:eq:steplength} must agree:
$60\times3.03/163.6 = \SI{1.11}{\metre}$. It does, because the three numbers
come from the same count and time. That is the point of the check: if the
app's step length for the same run is 1.30 m while its cadence
matches, the error is in its speed, which means its scale. A count of 18 steps
is uncertain by about half a step at each line, about 3% of 18 at each end, so count
over the longest section you can film.

### 9.2.2 How the running app finds a contact

The running app works on the vertical position of the foot: the heel if the
chosen pose model has one, otherwise the ankle, because the 17-keypoint models
(MoveNet and YOLO) have no heel. It smooths that trace over about
0.08 s. It takes as a contact candidate any lowest point that lies
in the bottom 15% of the foot's range (above the 85th percentile of image
$y$) and is at least 0.2 s after the previous one. It then grows
each candidate backward and forward while the foot stays in the bottom 30%
of its range (above the 70th percentile) or is nearly still, moving less than
half of its swing range (the 20th to 85th percentile) per second; a gate
stated per second, unlike one stated per frame, means the same at every frame
rate. Stances shorter
than 0.08 s or longer than 0.45 s are thrown out, and
the left and right contacts are merged into one sequence of steps that
alternate sides. A gap between contacts of more than 1.6 typical step
intervals counts as missed steps, so the side advances by that many; an
earlier version forced a strict left, right, left order, and one missed
contact swapped the label of every later step.
Toe-off is not detected separately: it is the last frame of the grown stance.
Percentiles rather than pixel values make the rule work at any camera distance.

Listing 9.4 is a simplified version of that rule.

**Listing 9.4.** Contact time and duty factor with a percentile stance rule. (`code/stance.py`)

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

FPS = 30.0
df = pd.read_csv("form1_ankles.csv")
y = df["l_ankle_y"].rolling(3, center=True, min_periods=1).mean().to_numpy()
hi, lo = np.percentile(y, 85), np.percentile(y, 70)
peaks, _ = find_peaks(y, height=hi, distance=int(0.2 * FPS))

stances = []
for p in peaks:
    i, j = p, p
    while i > 0 and y[i - 1] >= lo: i -= 1
    while j < len(y) - 1 and y[j + 1] >= lo: j += 1
    if 0.08 <= (j - i + 1) / FPS <= 0.45:
        stances.append((i, j))
tc = np.median([(j - i + 1) / FPS for i, j in stances])
stride = np.median(np.diff([i for i, _ in stances])) / FPS
print(f"{len(stances)} stances, contact {tc:.3f} s = {tc * FPS:.0f} frames")
print(f"stride {stride:.3f} s, duty factor {100 * tc / stride:.0f}%")
```

Its output on the running example:

```text
22 stances, contact 0.200 s = 6 frames
stride 0.700 s, duty factor 29%
```

A contact of 0.200 s is six frames at 30 fps. One frame more
or less is 33 ms, which moves the duty factor by
$100\times0.033/0.70 = 4.8$ percentage points, half the width of the app's
whole Elite band for duty factor (35 to 45%). Section 9.8
shows that the threshold itself moves the answer even more. Treat this 29% as
a number to be checked, not a finding.

> **Try it in the app: Your own cadence.**
> 
> Film yourself from the side for 15 to 30 seconds of steady running, phone
> still at hip height, whole body in frame. Run Basic mode and save the PDF and
> the text result. Count your steps over 30 seconds of the same clip by hand,
> double the count, and compare it with the app's cadence. They should agree
> within about 2 steps/min.
> 
> 
> https://apopt.com/form/form.php

### 9.2.3 What decides distance-running performance

Form is a small part of running performance. A distance runner's speed over
a race is set mostly by aerobic capacity, by the fraction of it that can be
held, and by *running economy*, the oxygen cost of running at a given
speed (Chapter 2). Biomechanics enters through economy. A review of
modifiable factors found that some, such as a stride length near the
runner's preferred one, are linked with better economy, but warned against
recommending one general economical technique .
An older experiment had ten runners vary their stride length at
3.83 m/s: each had a most economical length, and the
length they chose freely cost only
0.2 mL/kg/min more oxygen than
it . Runners, left alone, tend to find an
economical stride. That is worth remembering before you tell one to change it.

### 9.2.4 The force of each foot plant

Section 3.7.2 showed that over a steady running
step the ground's vertical force averages one body weight, so the timing of a
step gives a modeled force: a half-sine contact peaks at
$(\pi/2)(1+t_f/t_c)$ body weights
(Equation \eqref{ch03-mechanics:eq:fpeak}). Video gives you that per foot.
Pair each contact with the flight that *follows* it, the time until the
other foot lands: that flight is what this foot's push paid for. Then each foot
plant has its own contact, flight and peak, and the two sides have their own
means, which the asymmetry index of Equation \eqref{ch09-gait:eq:asym}
compares. Listing 9.5 does this on the running
example with the stance rule of Listing 9.4.

**Listing 9.5.** Modeled peak force per foot plant (`code/foot_force.py`). (`code/foot_force.py`)

```python
import numpy as np, pandas as pd
from scipy.signal import find_peaks
FPS, df = 30.0, pd.read_csv("form1_ankles.csv")

def stances(col, side):                    # yields (first frame, last frame, side)
    y = df[col].rolling(3, center=True, min_periods=1).mean().to_numpy()
    hi, lo = np.percentile(y, 85), np.percentile(y, 70)
    for p in find_peaks(y, height=hi, distance=int(0.2 * FPS))[0]:
        i = j = p
        while i > 0 and y[i - 1] >= lo: i -= 1
        while j < len(y) - 1 and y[j + 1] >= lo: j += 1
        if 0.08 <= (j - i + 1) / FPS <= 0.45: yield i, j, side

s = sorted([*stances("l_ankle_y", "L"), *stances("r_ankle_y", "R")])
f = pd.DataFrame([(a[2], (a[1] - a[0] + 1) / FPS, (b[0] - a[1] - 1) / FPS)
                  for a, b in zip(s, s[1:]) if a[2] != b[2]],   # contact + next flight
                 columns=["side", "contact", "flight"])
f["peak_bw"] = np.pi / 2 * (1 + f.flight / f.contact)
m = f.groupby("side").agg(n=("side", "size"), contact=("contact", "mean"),
                          flight=("flight", "mean"), peak_bw=("peak_bw", "mean"))
print(m.round(3))
L, R = m.peak_bw["L"], m.peak_bw["R"]
print(f"asymmetry index {100 * abs(L - R) / ((L + R) / 2):.1f}%")
```

Output:

```text
       n  contact  flight  peak_bw
side
L     21    0.210   0.130    2.559
R     22    0.211   0.158    2.757
asymmetry index 7.5%
```

The right foot's plants come out 0.20  body weights higher, an asymmetry
of 7.5%. Is that real? Ask the two questions every difference needs. First,
is it larger than the scatter? The peaks of single plants have a standard
deviation of about 0.2 body weights, so each side's mean of 21 or 22 plants
is good to about 0.045 , and the difference is several times that. It is
not chance. Second, is it larger than the error that does *not* average
out? The whole difference comes from the flights, 0.130  against
0.158 s, which differ by 0.027 s: 0.8 of a frame.
Every contact here is 5 to 7 frames long, so one frame moves a single plant's
estimate by about 20%. If the stance rule placed every left toe-off one frame
late, a consistent bias that averaging cannot remove, the asymmetry would be
22%; one frame early, and the left side would come out 10% *higher*.
A difference whose sign flips with a one-frame bias is inside the error. The
finding is that this clip cannot tell the two feet apart, and that is a
finding worth reporting.

*Table 9.2. The frame budget of the modeled peak force, for the contact of 0.25 s and step of 0.349 s of Example 3.7 (peak 2.19 body weights). One frame moved from contact to flight raises the estimate; one frame the other way lowers it.*

| Capture rate | One frame | Share of contact | One frame short | One frame long |
|---|---|---|---|---|
| 30 fps | 33.3 ms | 13.3% | $+15.4\%$ | $-11.8\%$ |
| 60 fps | 16.7 ms | 6.7% | $+7.1\%$ | $-6.2\%$ |
| 120 fps | 8.3 ms | 3.3% | $+3.4\%$ | $-3.2\%$ |
| 240 fps | 4.2 ms | 1.7% | $+1.7\%$ | $-1.6\%$ |

Table 9.2 gives the frame budget for the force
(compare the budget for contact time in
Section 9.8.1). Because the estimate goes as
$1/t_c$, one frame short at 60 fps raises it about 7%, and at
30 fps about 15%. To see a 5% difference between the feet you need a
frame that is a small share of the contact, which means 120 fps or
better, and a camera square to the runner's side. The threshold that ends
stance matters even more: at the 60th, 70th and 80th percentile rules of
Table 9.6 (contacts of 0.267, 0.200 and
0.133 s), the same mean step of 0.354 s gives peaks of
2.08, 2.78 and 4.18 body weights. So treat the absolute number as modeled and
uncertain, and use it the way you use contact time: to compare a runner with
themselves, filmed the same way at the same pace. It is training information.
A left–right difference in a modeled force is not evidence of an injury, a
weakness or a risk.

## 9.3 Running: Shape

Coaches talk about shape more than timing: overstriding, sitting back,
landing on a straight knee, bouncing, dropping a hip. Each of these is a real
mechanical property, and each is partly visible to one camera. This section
defines each as the apps measure it, then asks what it is thought to matter
for and how strong the evidence is.

### 9.3.1 Definitions

- **Overstride**  The horizontal distance, in the direction of travel, from
the hip to the foot at contact. The running app reports it in centimeters and
as a percentage of leg length (the median hip-to-ankle distance in the same
video), and grades the worse of the two. The percentage needs no scale and is
the better form to track. With a 17-keypoint model the ankle stands in for the
heel.

- **Trunk lean**  The angle of the line from mid-hip to mid-shoulder away from
image vertical, at contact, positive when leaning forward. Image vertical is
world vertical only if the camera is level.

- **Knee angle at contact**  The included hip–knee–ankle angle at the
contact frame; \ang{180} is a straight leg. The app also reports the smallest
knee angle during stance.

- **Vertical oscillation**  The up-and-down travel of mid-hip, a stand-in for
the body's center of mass, over a window of 2.5 s, in centimeters.
It needs the scale.

- **Hip drop**  From behind, how far the swing-side hip sits below the
stance-side hip at mid-stance (the running app), or the tilt of a bright band
worn at the waist (the hip drop app). The
hip drop app turns the band's slope into an angle,
$\alpha = \arctan(\text{rise}/\text{run})$: a slope of 8% is \ang{4.6}.

> **Body science: Why the pelvis drops.**
> 
> When you stand on one leg, your body weight acts on the far side of the
> supporting hip. The hip abductors on the stance side, chiefly gluteus medius,
> pull down on the pelvis on that side to keep the other side from falling. If
> they act late or weakly, the swing-side hip drops: *contralateral pelvic
> drop*. A few degrees is normal in running. The clinical name for a large drop
> seen in standing on one leg is a positive Trendelenburg sign, which is a
> clinician's call, not an app's.

### 9.3.2 How strong is the evidence?

Table 9.3 grades each measure. Read the last column
first. Most of what is known links a form variable to an injury
*cross-sectionally*: injured runners were compared with healthy ones at
one moment, which cannot tell a cause from a consequence. A systematic review
of the prospective studies, the ones that measure first and wait for injuries,
found the evidence “sparse and inconsistent”; the one factor with limited
support was greater hip adduction in female runners who later developed knee
or iliotibial band pain .

*Table 9.3. Running form measures: what each is thought to matter for, and the strength of the evidence. “Lab mechanics” means changes measured in healthy runners in a laboratory, not injuries prevented.*

| Measure | Thought to matter for | Evidence |
|---|---|---|
| Cadence | Knee and hip loading; patellofemoral (kneecap) force | Lab mechanics, consistent ; symptoms: one case series of 12 |
| Overstride | Braking; loading at contact | Coupled to cadence; injured runners landed with a straighter knee (cross-sectional) |
| Trunk lean | Hip and knee load | More forward lean in injured runners (cross-sectional) |
| Knee at contact | Impact absorption | Straighter in injured runners (cross-sectional) |
| Vertical oscillation | Economy; impact | Falls when cadence rises ; link to economy conditional |
| Hip drop | Knee, iliotibial band, shin pain | Strongest discriminator in (cross-sectional); prospective support limited |
| Contact time, duty factor | Speed and style | Descriptive; change with speed |

\paragraph{Cadence.} Cadence is the most studied form variable you can change.
When 45 healthy runners ran on a treadmill at a fixed speed with their step
rate raised by 5% and 10%, step length, vertical travel of the center of
mass, braking and the energy absorbed at the knee all fell; the hip changed
only at +10% . A +10% step rate cut
modeled peak force behind the kneecap by 14% in 30
adults , and a review of ten studies
agreed on the direction of these
changes . That is good evidence that
cadence changes *loading*. Evidence that it changes *injury* is much
thinner. The best is a case series of 12 runners with kneecap pain who were
taught a 10% higher step rate in one session; pelvic drop fell by about
\ang{3} and pain improved at four weeks and three
months . A case series has no control group, so
some of the improvement may have come with time alone.

\paragraph{Overstride.} Overstriding is the measure a coach asks about most
and the one with the least direct evidence. It is not independent of cadence:
at a fixed speed, a higher cadence shortens each step, and the foot lands
closer under the hip. The injured runners in one large comparison landed with
a straighter knee and a more upturned
ankle , which is what an overstride
looks like, but that study was cross-sectional and did not measure overstride
as a distance. No study we found shows that reducing a measured overstride
prevents injury.

\paragraph{Hip drop and trunk lean.} The same comparison of 72 injured and 36
healthy runners found greater contralateral pelvic drop and forward trunk lean
in the injured groups, and pelvic drop was the strongest single
discriminator: each extra degree raised the odds of being in the injured group
by about 80% . That is a large effect
and an honest reason to look at hip drop. It is still a difference between
groups seen at one time, not a prediction for one runner.

\paragraph{The strongest evidence that form matters.} One randomized trial
gave 166 novice runners two weeks of gait retraining with real-time feedback
to land more softly and compared them with 154 controls. Over a year, 16% of
the retrained runners and 38% of the controls were
injured . Notice what was retrained: impact
loading, measured with instruments, not cadence or overstride measured from
video. And notice the general rule from screening research: even a real group
difference does not let you predict which individual will be
injured .

> **Limits and cautions: Not a diagnosis, not a prediction.**
> 
> A form measure is training information. It does not diagnose an injury, clear
> a runner to train, or predict that a runner will be hurt. Reported running
> injury rates range from about 2.5 to 33 injuries per 1000 hours of running
> across groups of runners , and
> form is only one of many things that differ between them. A runner with
> pain sees a clinician first.

### 9.3.3 The app's target bands

Table 9.4 lists the running app's distance-running
bands. “Elite” means inside the first band and “Pro” inside the second;
anything else is labeled “Good”, the lowest of the three. The bands are a
presentation choice assembled from coaching practice, not percentiles of a
published distribution, and no study shows that moving a runner from Pro to
Elite on any row changes performance or injury. Use them as a rough map of
typical values. The step-length row is one step, $60v/\text{cadence}$, and
it is empty when the app has no speed. An earlier version labeled that row
“stride” and, without a speed, filled it with a constant proportional to the
runner's height; reading the formula behind the label exposed both.

*Table 9.4. Distance-running bands in the running app (Elite / Pro). Checked in the app source on 2026-11-26.*

| Measure | Elite | Pro |
|---|---|---|
| Cadence | 165–185 steps/min | 158–190 steps/min |
| Step length | 1.1–1.6 m | 0.9–1.9 m |
| Contact time | 180–250 ms | 150–320 ms |
| Flight time | 90–180 ms | 60–220 ms |
| Duty factor | 35–45% | 32–48% |
| Overstride | $\le\SI{5}{\centi\metre}$ and $\le8\%$ leg | $\le\SI{10}{\centi\metre}$ and $\le15\%$ |
| Vertical oscillation | 6–10 cm | 5–12 cm |
| Trunk lean | 3–10 | 0–14 |
| Pelvic drop (rear view, worse side) | $\le\ang{4}$ | $\le\ang{7}$ |

### 9.3.4 From behind: rear-view measures

A side view sees forward and up; a rear view sees side to side. The running
app's rear view reports pelvic drop, the lean of the trunk to the side, a
projected knee angle, and step width. Pelvic drop is how far the swing-side
hip sits below the stance-side hip at the middle of each stance (rejected if
over \ang{25}), shown for each stance foot as “L \ldots{} $\cdot$ R \ldots” and
graded on the worse side; an earlier version pooled one signed image tilt over
both sides, so drops to the left and right partly cancelled. Step width is
the side-to-side distance from each planted foot to the line joining the
other foot's contacts before and after it, measured at contact rather than
over every frame. A step width over 35 cm, wider than any
running step, is withheld and shown as N/A with the reason; it usually means
a side-view clip was run as a back view. Every one of these is small, every one is built from two keypoints
close together, and every one changes when the camera is not level or not
directly behind the runner. Rear-view angles are the least reliable numbers
the running app gives. Even for trained raters working on two-dimensional
running video, agreement with laboratory measurements ranged from poor to
good across studies .

The hip drop app avoids the hip keypoints altogether. You wear a bright band
around the waist and it tracks the band by its color, with no pose model. The
band is wider and sharper than a pair of estimated hip joints, which helps.
Two details of the app shape what its number means. First, it subtracts the
session's median tilt before grading, so a camera that is rolled by a constant
amount does not count as hip drop. Second, it does not find stances; it
reports the typical largest tilt to each side within 5-second windows and
grades the larger of the two (men: Elite at most \ang{5}, Pro at most
\ang{7}; women: \ang{7} and \ang{9}). Its own report says it does not
identify the stance leg, so “drop toward the left of the screen” means
opposite things from in front and from behind.

> **Check it by hand: Tilt from a slope.**
> 
> On a paused frame the band's left end is at $(412, 980)$ and its right end at
> $(562, 992)$, in pixels. The rise is 12 px over a run of 150 px, a slope of
> 8%, and the tilt is $\arctan(12/150)=\ang{4.6}$. A tilt of \ang{5} is a slope
> of 8.75%: on a band 150 px wide, a rise of 13 px. One pixel at each end is
> about \ang{0.4} here, so film close enough that the band is wide in the frame.
> *Confirm it:* pause your own hip drop clip, measure the band's ends, and compare with the app's tilt at that moment.

\paragraph{Back to the opening question.} Is the runner overstriding, or is the
camera making it look that way? Overstride is a horizontal distance between
two keypoints, measured in the image plane. If the camera is not square to
the runner, the image shortens horizontal distances along the line of sight
(Chapter 8), and if the runner is moving toward or away from the
camera, the scale changes during the clip. A runner filmed from in front and
to one side can look as if the foot lands far ahead of the hip when it does
not, or the reverse. The checks are simple: film square to the path, from far
enough back that the runner crosses the frame without growing or shrinking,
and prefer the percentage of leg length, which divides out the scale. Then
film again on another day. If the value moves more between days than it
differs from the target, the question cannot be answered with this setup.

## 9.4 Sprinting Is a Different Movement

A sprinter is not a distance runner going faster. In a study of 33 runners
whose top speeds ranged from 6.2 to 11.1 m/s, the faster
runners did not reposition their legs faster: the time a leg spent swinging
was about the same for all of them. They went faster by pushing harder on the
ground in a shorter contact, with average support forces 1.26 times larger
for the fastest runner than for the
slowest . Faster running means shorter
contacts, lower duty factors and longer steps, so a distance band applied to a
sprinter marks good sprinting as a fault.

The running app therefore has a separate sprint mode, chosen by the user
(it does not detect sprinting by itself). Its bands are different: cadence
of at least 220 steps/min for Elite, contact time 80 to
140 ms, duty factor 25 to 38%, and a knee at contact of
\ang{150} to \ang{165} rather than \ang{160} to \ang{170}. At
30 fps a 100 ms contact is three frames, so sprint
contact times need a high capture rate (Chapter 8) and a correct
frame-rate setting before they mean anything. Starts and acceleration are
single events, not cycles, and belong to Chapter 10.

## 9.5 Walking

> **Body science: Walking is not slow running.**
> 
> In walking each foot is on the ground for roughly 60% of the gait cycle, so
> there are two moments in every cycle when both feet are down:
> *double support*. There is no flight. The body vaults over a nearly
> straight stance leg like an upside-down pendulum, trading height for speed and
> back again, which is why walking costs little energy at ordinary speeds. Above
> a certain speed this exchange stops working and people break into a run.

The running detector does not work on walking, for two reasons. The foot is
never airborne in the running sense, so there is no clean plateau between
two peaks, and stance lasts anywhere from about half a second to well over a
second, so a fixed duration band either rejects slow steps or merges fast
ones. The walking app turns the order around, which is exactly the
period-first idea. It tracks the *forward* position of each ankle
relative to the hip. That signal peaks once per cycle, when the foot is
furthest ahead, close to heel strike. Each pair of peaks on the same foot is
one cycle; contact begins just before the peak, and stance is given a length
of 32 to 78% of that cycle (64% if nothing better is found), trimmed where
the foot-height trace or the forward-position trough says stance ends. A
second detector works on foot height, as the running app does, and the two are
merged. Every bound scales with the cycle the walker actually produced.

*Figure 9.2. Stance bars for the two feet. Running (top): a contact of 0.25 s in a 0.70 s stride, duty factor 36%, with flight between stances. Walking (bottom): each stance is 0.62 s of a 1.05 s stride, so the stances overlap twice per stride (hatched, DS), for 18% double support. Time in seconds.*

### 9.5.1 The walking measures

$$v &= \frac{L_{\text{stride}}\times\text{cadence}}{120}, \\
  \Phi_{\text{DS}} &= 100\,\frac{t_L + t_R - T_{\text{stride}}}{T_{\text{stride}}}, \\
  A &= 100\,\frac{|p_L - p_R|}{\tfrac12(p_L + p_R)}.$$

Gait speed $v$ is stride length times strides per second; a stride is two
steps, hence the 120. The walking app prefers to measure speed from the hip's
travel across the frame and falls back on Equation \eqref{ch09-gait:eq:walkspeed}.
The *double support* share $\Phi_{\text{DS}}$ uses the fact that the two
stance times $t_L$ and $t_R$ together exceed one stride by exactly the time
both feet are down. The *asymmetry index* $A$ compares a left and a right
value. Asymmetry indices in the gait literature are defined in several
non-equivalent ways, which is why a published value can be compared with
yours only if the formula matches .
Even within the walking app, stance asymmetry uses the mean of the two sides
as the denominator, arm-swing asymmetry uses the larger side, and knee-flexion
asymmetry is a plain difference in degrees.

> **Check it by hand: Walking speed and double support.**
> 
> A stride of 1.3 m at a cadence of 110 steps/min gives
> $v = 1.3\times110/120 = 1.19 m/s$. If each stance lasts
> 0.62 s and the stride 1.05 s, double support is
> $100\times(0.62+0.62-1.05)/1.05 = 18%$. *Confirm it:* walk a taped
> 10 m and time it (Exercise 9.9), and
> compare with the walking app's gait speed.

### 9.5.2 Walking as a health measure

Gait speed is a mechanical quantity with a stopwatch definition, and it is
also one of the most studied markers of health in older adults. Pooled across
nine cohorts of 34,485 people aged 65 and over, each 0.1 m/s
of faster usual walking speed went with a lower risk of death over the
follow-up , which is why walking speed has
been called “the sixth vital sign” . The
standard test is a timed 10 m walk, whose repeat reliability in
healthy older adults is excellent .

Two cautions keep that honest. First, those associations were found with a
stopwatch and a taped course. A video estimate is a different measurement,
and it inherits none of that evidence until it agrees with the stopwatch.
Second, a population association does not forecast a person. The walking
app's bands (gait speed above 1.0 m/s for Elite, double
support under 25%) are coaching bands, not clinical cut-offs. The value of a
phone here is frequency: a weekly measurement shows a trend that two clinic
visits a year cannot.

## 9.6 Cycling

Cycling turns the gait problem inside out. There is no foot contact to detect;
the foot never leaves the pedal. The positions that matter, the pedal at the
bottom of its circle and at the top, are crank angles, and the crank itself is
often hidden by the leg, the frame or a shoe cover. What the app needs is the
crank's phase, and it gets it from the rider.

> **Body science: What decides cycling performance.**
> 
> Mechanical power at the pedals is crank torque times angular speed, so a
> rider can make the same power with a hard gear at low cadence or an easy gear
> at high cadence. Sustained power comes from the aerobic system
> (Chapter 2). On flat roads at racing speed most of that power goes
> into pushing air aside, so a lower, narrower position can be faster even if
> it costs a little power; the trade-off is comfort and the ability to keep
> producing power in that position. Fitting a bicycle is the search for a
> position the rider can hold, powerfully, for hours.

### 9.6.1 Crank phase without seeing the crank

Take the straight-line distance $r$ from the hip keypoint to the ankle
keypoint on one side. The hip barely moves on the saddle, and the ankle goes
round with the pedal. If $d$ is the distance from the hip to the bottom
bracket (the crank's axle), $L_c$ the crank length and $\psi$ the crank angle
measured from the line joining the bracket to the hip, the law of cosines
gives

$$r(\psi) = \sqrt{d^2 + L_c^2 - 2\,d\,L_c\cos\psi}.$$

Three facts follow, and they are the whole method. $r$ has exactly one maximum
and one minimum per revolution, half a revolution apart, whatever the rider
or the camera. Its peak-to-peak range is $2L_c$, about 345 mm
for a 172.5 mm crank, a large swing compared with keypoint
noise. And the maximum is where the leg is most extended, which is close to,
but not exactly at, the bottom of the pedal circle if the saddle sits behind
the bracket. Figure 9.3 draws the signal.

*Figure 9.3. Hip-to-ankle distance through two pedal revolutions, from Equation ch09-gait:eq:rpsi with $d=0.75 m$ and $L_c=0.1725 m$. Triangles: maxima (the app's “bottom” frames); squares: minima (“top”). They alternate, half a revolution apart, and the range is $2L_c$.*

The cycling app smooths $r$ over about 0.07 s, accepts maxima above
the 65th percentile as bottom positions and minima below the 35th percentile as
top positions, keeps them at least the larger of five frames and
0.22 s apart, and computes cadence from the mean number of frames
between bottom positions:

$$\text{cadence} = \frac{60\,f}{\overline{N}_{\text{rev}}}\ \text{rev/min},$$

where $f$ is the capture rate. Values outside 35 to 180 rpm are
rejected. Forty frames per revolution at 60 fps is 90 rpm.

### 9.6.2 What the cycling app reports

From the side, the app reports the knee angle (hip–knee–ankle) near the
bottom of the stroke, the hip angle (shoulder–hip–knee) near the top, the
trunk angle from horizontal and the shoulder angle (hip–shoulder–wrist),
the last two averaged over all frames. From behind, it reports the side-to-side
travel of the knee, the up-and-down travel of each hip (labeled “Hip
Vertical Travel”), and the side-to-side
sway of the shoulders, each divided by the rider's hip width in the same image
so that camera distance cancels. Its Elite bands are a cadence of 85 to
105 rpm, a knee angle at the bottom of \ang{140} to \ang{150}, a hip
angle at the top of \ang{45} to \ang{60} and a trunk of \ang{35} to \ang{50}.

A knee angle of \ang{140} to \ang{150} is \ang{30} to \ang{40} of flexion, the
range one study of well-trained cyclists called
optimal ; a review of saddle height
suggested \ang{25} to \ang{30} instead . The
two recommendations do not even agree with each other, and the same study
found that 56.5% of its cyclists had a saddle outside the usual
inseam-based rule . Two details of
the app matter when you compare with these numbers. Its “maximum knee
extension” is the largest knee angle within each detected stroke, taken as
the median over strokes, and the minimum hip angle is found the same way; if
no stroke is detected it reports nothing. An earlier version averaged the
angle over the frames near the bottom, which is not the extreme the name
promises, and with no strokes it averaged over every frame, which is not
a fit measure at all.

### 9.6.3 The bicycle as a ruler

A bicycle is a calibrated machine, and that gives you an experiment that
needs no laboratory. Raise the saddle by a measured $\Delta h$ and the leg is
longer at the bottom of the stroke by about the same amount. With thigh
length $a$, shank length $b$ and knee angle $\theta$, the law of cosines gives
$r^2 = a^2 + b^2 - 2ab\cos\theta$, and so

$$\Delta\theta \approx \frac{r}{a\,b\,\sin\theta}\,\Delta h.$$

> **Engineer's note: Where Equation ch09-gait:eq:saddle comes from.**
> 
> Differentiate $r^2 = a^2+b^2-2ab\cos\theta$ with $a$ and $b$ fixed:
> $2r\,\mathrm{d}r = 2ab\sin\theta\,\mathrm{d}\theta$, so
> $\mathrm{d}\theta/\mathrm{d}r = r/(ab\sin\theta)$ in radians per meter.
> For $a=0.40 m$, $b=0.45 m$ and $\theta=\ang{145}$,
> $r = 0.811 m$ and the sensitivity is \ang{0.45} per millimeter.
> A 10 mm raise predicts about \ang{4.5}; 5 mm
> predicts about \ang{2.2}.

All of $a$, $b$, $\theta$ and $r$ can be read from the rider's own video, so
the prediction needs no body measurements, and because it is a
difference within one rider and one camera position, a constant bias in the
angle cancels. This is the design of Exercise 9.19. The
size of the effect matters: a single-camera study of 26 cyclists found that a
pose model differed from marker-based motion capture by \ang{4} to \ang{8} at
the hip and knee and \ang{15} to \ang{22} at the
ankle , and in another study every field
method, two-dimensional video included, underestimated the knee angle at the
bottom of the stroke compared with three-dimensional capture; the authors
suggest adding \ang{2.2} to video values . Errors of that size are as wide as
the target band itself. A 10 mm change, measured twice with
the camera untouched, is the kind of question one camera can answer; “is this
saddle exactly right?” is not.

## 9.7 Swimming

Swimming speed is the product of how often the arms turn over and how far the
body travels per turnover. With *stroke rate* SR in cycles per minute and
*distance per cycle* DPC in meters,

$$v = \frac{\text{SR}\times\text{DPC}}{60},\qquad
  \text{DPC} = \frac{60\,v}{\text{SR}},\qquad
  \text{SI} = v\times\text{DPC}.$$

In all four strokes, swimmers raise speed mainly by raising stroke rate while
distance per stroke falls . The
*stroke index* SI rewards holding a long stroke at speed. In freestyle and
backstroke one cycle is a full turn of *both* arms; some coaches count
single arm pulls, which doubles the number, so always say which you mean.

> **Body science: What decides swimming performance.**
> 
> Water is about 800 times denser than air, so drag dominates. A swimmer goes
> faster by producing more propulsion with the hands and feet, by losing less to
> drag through a streamlined body, or both, and both the energy supply and the
> mechanics predict performance . The race
> is not all swimming: in 100 m finals at a European championship, the start and
> the turn together took almost a third of the race
> time . A camera on the deck sees above the
> surface well and under it poorly, so the measures that survive are rates,
> times and distances along the lane.

The swimming app follows the same three steps. For breaststroke and butterfly,
where the arms move together, its signal is the distance between the wrists,
which peaks once per cycle. For freestyle and backstroke the arms alternate, so
a two-wrist signal would peak twice per cycle; the app instead follows the one
wrist seen in more frames, relative to the body's center. Peaks must reach the
58th percentile of the signal and be at least 0.45 s apart
(0.75 s in breaststroke), and stroke rate is 60 divided by the
median cycle time. Following one wrist matters: switching wrists whenever one
drops out would add half-cycles and double the rate, a plausible-looking wrong
number.

> **Check it by hand: Stroke rate, distance per cycle, stroke index.**
> 
> A freestyle cycle lasts 1.25 s: SR $= 60/1.25 = 48$ cycles a
> minute. At 1.6 m/s, DPC $= 60\times1.6/48 =
> 2.0 m$ and SI $= 1.6\times2.0 = 3.2 m²/s$.
> *Confirm it:* count cycles over one 25\,m length and time it with the
> pace clock (Exercise 9.16).

Two features make the swimming app unusual. First, each of its 51 measures
declares where it applies: the segment (stroke, start, turn or finish), the
view (side, head-on, rear or overhead), the stroke, and whether the camera is
above or under the water. A measure that cannot be seen in your
configuration is not shown at all, rather than shown with a guessed value.
Second, speed, DPC and stroke index need a scale, and the pool supplies it:
mark two points a known distance apart along the lane (a lane line, the
backstroke flags, the 15\,m mark) for a side view, or four corners of a known
rectangle for the other views. Without that calibration the app reports
stroke rate but not speed. Stroke rate, DPC and stroke index carry no target
bands; only measures such as cycle-to-cycle variation (Elite at most 3%) are
graded.

## 9.8 How Good Is the Number?

Chapter 8 sorted results into three levels of trust: counts, times
and ratios of like quantities; angles in the plane the camera is square to;
and front-view tilts and anything in meters.
The measures of this chapter fall neatly into them, and
Table 9.5 gives the main error sources with a typical
size and a free check for each.

*Table 9.5. Error sources for cyclic measures, with a typical size and a free reference to check each.*

| Source | Typical size | Free check |
|---|---|---|
| Frame grid | One frame: 33 ms at 30 fps, 4.2 ms at 240 fps; 4.8 duty-factor points per frame at 30 fps | Film the same run at two rates |
| Event threshold | Contact time 0.13 to 0.28 s on one clip as the threshold moves (Table 9.6) | Frame-by-frame count by two raters |
| Wrong frame rate | Every time scaled by stored/capture rate (Chapter 8) | A stopwatch or pace clock in frame |
| Scale | Lengths and speeds carry the whole scale error (Chapter 8) | Taped distance in frame; steps over a taped 20 m |
| Camera yaw | Shortens horizontal distances; frontal angles worst | Film square, then 20 off |
| Rear view | Small angles from two close keypoints | Level line on a wall; bubble level on the phone |
| Treadmill | No travel across the frame; speed known from the belt | Compare with overground at the same pace |

### 9.8.1 The frame budget

A distance runner's contact of 0.22 s spans 6.6 frames at
30 fps, 13 at 60 fps and 53 at 240 fps. At 30 fps
each contact time you read is one of a handful of values, and one frame is 15%
of the answer (a force modeled from it inherits the same share;
Table 9.2). Cadence is far more forgiving, because it comes from the
interval between *many* events and a constant offset in where each event
is placed cancels. That is why reviews of two-dimensional running video find
step rate reliable , why gait timing from
a single camera agreed with motion capture to about 0.02 s per
step in walking , and why the
agreement between raters on running angles is much more
variable .

### 9.8.2 The threshold decides the contact time

Where does stance end? On a video there is no force plate to say. The running
app's rule ends it when the foot rises out of the bottom 30% of its range.
Listing 9.6 moves that line on the running example.

**Listing 9.6.** Move the stance threshold on a real clip (first part of `thresholds.py`). (`code/thresholds.py`)

```python
df = pd.read_csv("form1_ankles.csv")
marks = []
for side in "lr":
    y = df[f"{side}_ankle_y"].rolling(3, center=True, min_periods=1).mean().to_numpy()
    peaks, _ = find_peaks(y, height=np.percentile(y, 85), distance=int(0.2 * FPS))
    marks += [(p / FPS, y[p], side) for p in peaks if p < 4 * FPS]
    for q in (60, 70, 80):
        lo, dur = np.percentile(y, q), []
        for p in peaks:
            i = j = p
            while i > 0 and y[i - 1] >= lo: i -= 1
            while j < len(y) - 1 and y[j + 1] >= lo: j += 1
            dur.append((j - i + 1) / FPS)
        print(f"{side} ankle, grow while above p{q}: contact {np.median(dur):.3f} s")
```

*Table 9.6. Median contact time on the running example as the stance threshold moves. The app's rule is the 70th percentile.*

| Grow stance while above | 60th pct | 70th pct | 80th pct |
|---|---|---|---|
| Left ankle | 0.267 s | 0.200 s | 0.133 s |
| Right ankle | 0.283 s | 0.200 s | 0.133 s |

One reasonable choice gives a contact time twice as long as another. Without a
reference you cannot say which is right; you can only say that each is
consistent with itself. Use contact time to compare a runner with themselves,
filmed the same way, and check its absolute value against a high-speed clip
counted frame by frame.

### 9.8.3 A metronome is an exact reference

A metronome does not drift and needs no calibration, so a runner who matches
it gives you a known cadence. Listing 9.7 makes
synthetic ankle traces at three metronome settings, with noise, and measures
cadence from a straight line through all the contact times. The traces are
made up; the method is the one you will use on your own video.

**Listing 9.7.** Cadence against a metronome on synthetic traces (the functions are reused by Listing 9.8). (`code/metronome.py`)

```python
def ankle_y(step_s, contact_s, lag_s=0.0):
    """Image y of one ankle (px): flat on the ground, a hump in swing."""
    t = np.arange(0, SECONDS, 1 / FPS) - lag_s
    f = contact_s / (2 * step_s)                       # stance share of stride
    swing = np.clip(((t / (2 * step_s)) % 1 - f) / (1 - f), 0, 1)
    return 1600 - 300 * np.sin(np.pi * swing) + rng.normal(0, 6, t.size)

def contact_times(traces, period_frames):
    ic = [find_peaks(y, distance=int(0.6 * period_frames),
                     height=np.percentile(y, 70))[0] for y in traces]
    return np.sort(np.concatenate(ic)) / FPS

if __name__ == "__main__":
    for spm in (160, 170, 180):
        step = 60 / spm
        t = contact_times([ankle_y(step, 0.24), ankle_y(step, 0.24, step)],
                          2 * step * FPS)
        slope = np.polyfit(np.arange(len(t)), t, 1)[0]  # seconds per step
        print(f"metronome {spm}: {len(t)} contacts, "
              f"measured {60 / slope:.1f} steps/min")
```

Output:

```text
metronome 160: 40 contacts, measured 160.3 steps/min
metronome 170: 43 contacts, measured 170.1 steps/min
metronome 180: 45 contacts, measured 179.7 steps/min
```

Listing 9.8 builds the table the field exercise asks
for. In synthetic data you set the truth, so the table shows both the
measured and the true contact time. Here contact time and overstride were
*assumed* to fall as cadence rises (at a fixed speed, a shorter step lands
closer under the hip). Those inputs are illustrations, not findings.

**Listing 9.8.** A three-cadence table (main loop of `three_cadence.py`). (`code/three_cadence.py`)

```python
for spm, tc_true, os_true in [(160, 0.26, 10), (170, 0.24, 8), (180, 0.22, 6)]:
    step = 60 / spm
    yl, yr = ankle_y(step, tc_true), ankle_y(step, tc_true, step)
    t = contact_times([yl, yr], 2 * step * FPS)
    cad = 60 / np.polyfit(np.arange(len(t)), t, 1)[0]
    tc = contact_time(yl, 2 * step * FPS)
    over = os_true + rng.normal(0, 2, len(t))       # cm, 2 cm noise per contact
    rows.append([spm, cad, tc_true, tc, 100 * tc / (120 / cad), over.mean()])
cols = ["set", "cadence", "tc_true", "tc_meas", "duty_%", "overstride_cm"]
print(pd.DataFrame(rows, columns=cols).round(2).to_string(index=False))
```

```text
 set  cadence  tc_true  tc_meas  duty_%  overstride_cm
 160   160.24     0.26     0.28   37.84          10.40
 170   170.18     0.24     0.25   35.45           8.13
 180   180.88     0.22     0.23   35.17           5.86
```

Cadence lands within 1 steps/min of the metronome. Contact time follows the
trend but reads 0.01 to 0.02 s long, because the
stance rule used here (foot within 10% of its swing height of the ground)
is generous. With your own videos you will not know the true column; the
metronome column is the only exact one you will have. A test with a known
answer like this one belongs in every analysis you write (Appendix A).

### 9.8.4 Side or rear, treadmill or ground

A side view gives the events, the timing measures and the sagittal angles
(knee, trunk lean, overstride); a rear view gives the frontal ones (hip drop,
step width). Neither gives both, and for the events the side view is better,
because the foot's height and its forward travel are both in the image plane.
From behind, as in our running example, the foot's height still shows the
stances, but the foot also moves away from the camera during stance, which
tilts the plateau and is one reason the contact time of 0.20\,s in
Section 9.2 should not be taken at face value.

A treadmill makes filming easy: the runner stays in the frame, the camera can
be close, and the belt speed gives $v$ for step length without any scale.
The running app accepts a treadmill speed for exactly this reason. The cost is
that treadmill running is not identical to running over ground, so compare a
runner with themselves on the same surface. Over ground, the runner crosses
the frame, the scale changes if they are not square to the camera, and only a
few strides are visible from close range; film from further back with the
phone zoomed as little as possible, and put a taped distance in the frame.

### 9.8.5 Reliability: the same runner tomorrow

A measure is useful for tracking only if it changes less between two days
when nothing changed than it does when something did. The *typical
error*, the within-person standard deviation across repeat trials (for a
test and a retest, the standard deviation of the differences divided by
$\sqrt2$), is the standard way to state this , and
Chapter 11 turns it into a smallest detectable change. Rebuild the
camera setup between sessions so that its contribution is inside the error.

## 9.9 Telling the Runner

A report on a run can list twelve numbers. A runner can act on one. Pick the
one measure that is both outside its usual range for this runner and
supported by evidence that changing it changes something, say what to do in
words the runner already uses, and set a date to film again.

> **Coach's translation: A good message.**
> 
> “Your steps were steady at about 160 a minute at your easy pace. For the next
> two weeks, on two easy runs a week, set a metronome to 168 (about 5% faster)
> and match it for five minutes at a time; keep your pace the same, so the steps
> get a little shorter. That has been shown to reduce the load on the knee in
> lab tests. It is not a fix for an injury; if anything hurts, stop and see
> someone. We'll film again on the 14th, same place, same camera spot.”

> **Coach's translation: A poor message.**
> 
> “Cadence 160 spm (Good 1/3). Target 180. Overstride 12.4 cm (15.1% leg),
> duty factor 38.2%, VO 9.8 cm, pelvic drop 4.3$^\circ$. Fix your overstride and
> hip drop to reduce injury risk.”

The poor message gives seven numbers and two instructions with no way to carry
them out. It shows decimals the measurement cannot support. It calls a
textbook figure, 180, a target, though no study shows that one cadence suits
every runner, and the evidence above supports changes of 5 to 10% from the
runner's own value at the same speed. It promises less injury, which no form
measure can promise. And it reads “Good (1/3)” as the lowest grade, which
the runner will not guess. Chasing a textbook cadence has its own risk: a jump
from 160 to 180 is a 12.5% change, beyond what the studies tested, and a
runner who forces it may simply shorten steps at the cost of economy they had
found for themselves .

\paragraph{Going further.} The https://apmonitor.com/dde/index.php/Main/BiomechanicRegression module predicts a
runner's peak stride force from ten gait measures such as knee swing angle and
center-of-mass vertical oscillation, measured on several runners at several
speeds. It is a good next step from this chapter: the inputs are the
quantities you have just learned to measure, and Chapter 11
uses the same dataset to ask which of them carry information.

## Summary

- Find the period first, then the events. Build a trace in which the event
  is an extreme, learn the cycle length (autocorrelation, or peak spacing),
  then accept extremes that are large enough and far enough apart.

- Timing measures (cadence, contact, flight, duty factor) need no scale;
  step length, stride length, speed and overstride in centimeters do.

- Estimate a rate from the span of many events, not from a median of
  frame-rounded intervals.

- Contact time depends on the frame rate and on the threshold that ends
  stance; cadence depends on neither very much.

- Contact and the flight that follows give a modeled peak force for each
  foot plant. One frame is 7% of it at 60 fps and 15% at
  30 fps, so most left–right differences seen on a phone are inside
  the error.

- Cadence changes joint loading in the laboratory; evidence that it, or
  overstride, changes injury in runners is thin. Hip drop discriminates
  injured runners in cross-sectional data. No form measure predicts injury in
  an individual.

- Walking needs cycle-relative stance bounds and has double support;
  cycling gets crank phase from the hip–ankle distance; swimming gets speed
  from stroke rate times distance per cycle, with the pool as the scale.

- Every sport gives a free reference: a metronome, a taped distance, the
  bicycle's own geometry, the pool's markings and clock.

- Tell the runner one thing, with a retest date.

*Table 9.7. Formulas of Chapter 9.*

| Quantity | Formula |
|---|---|
| Cadence | $60/t_{\text{step}}$ steps/min |
| Duty factor | $100\,t_c/T_{\text{stride}}$ |
| Step length | $60\,v/\text{cadence}$ |
| Walking speed | $L_{\text{stride}}\times\text{cadence}/120$ |
| Double support | $100\,(t_L+t_R-T_{\text{stride}})/T_{\text{stride}}$ |
| Asymmetry index | $100\,\|p_L-p_R\|/\big(\tfrac12(p_L+p_R)\big)$ |
| Peak force per plant (half sine) | $(\pi/2)\,(1+t_f/t_c)$ body weights |
| Pedaling cadence | $60\,f/\overline{N}_{\text{rev}}$ rev/min |
| Saddle sensitivity | $\Delta\theta \approx r\,\Delta h/(ab\sin\theta)$ |
| Stroke rate; DPC; stroke index | $60/T_{\text{cycle}}$ ; $60\,v/\text{SR}$ ; $v\times\text{DPC}$ |
| Hip tilt from slope | $\arctan(\text{rise}/\text{run})$ |

**New terms:** asymmetry index, autocorrelation, cadence,
contact time, contralateral pelvic drop, cyclic movement, distance per cycle,
double support, duty factor, event, flight time, period, running economy,
stance, step, stride, stroke index, stroke rate, swing, typical error.

**Track it:** cadence, contact time and modeled peak force per foot, `run-form` test (Appendix J).

## Exercises

> **Course use: Week 9.**
> 
> **H18** (due Class 18, *Measure*): 9.1, 9.2, 9.5, 9.8, 9.18; about 90 minutes.
> 
> **P19** (due Class 19, *Model and tell*): 9.11, 9.20, 9.21, 9.22, 9.23, 9.24; about 220 minutes. A case-file exercise may be done on your own data instead. The full map is in the Course Guide.

**Exercise 9.1** (Concept check · Foundation · 1 min · CORE)

Which of these running measures cannot be computed without a scale from
pixels to meters (or a known speed)?

(a) Cadence
(b) Duty factor
(c) Step length
(d) Flight time

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

On a 30 fps clip, the median step time gives 164 steps/min but 43 steps
counted over 15.23 s give 169 steps/min. Why do they differ?

(a) Steps last a whole number of frames, so the median picks one rounded
value (10 or 11 frames) while the span uses every event
(b) The runner sped up
during the clip
(c) The median ignores the left foot
(d) The pose model misses half
the contacts

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

A student's script reports a duty factor of 70% for a runner at an easy
pace. What is the most likely explanation?

(a) The runner is sprinting
(b) The runner is overstriding
(c) The camera was
too far away
(d) Contact time was divided by a step time instead of a stride
time

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

Which statement about running cadence is best supported by the studies in
Section 9.3?

(a) About 180 steps/min is the optimal cadence for every runner
(b) Raising step
rate by 5 to 10% at the same speed reduces loading at the knee in laboratory
studies, but evidence that it prevents injury is thin
(c) Randomized trials show that
raising cadence halves running injuries
(d) A runner's freely chosen cadence is
usually far from economical

**Exercise 9.5** (Hand calculation · Foundation · 8 min · CORE)

A runner on a treadmill at 3.2 m/s is filmed at
60 fps. Contacts of alternate feet are 20 frames apart, each contact
lasts 12 frames, and a stride is 40 frames.

- Cadence. *Checkpoint:* {180 steps/min.}

- Contact time and duty factor. *Checkpoint:* {0.200 s; 30%.}

- Step length. *Checkpoint:* {1.07 m.}

- Confirm one of these in the running app (Advanced mode, the treadmill
speed entered) or with Listing 9.4 on a clip of your
own.

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

The frame budget.

- How many frames does a 0.18 s contact span at 30, 60 and
240 fps? *Checkpoint:* {5.4, 10.8, 43.2.}

- At 60 fps with a 0.70 s stride, how many
duty-factor percentage points is one frame? *Checkpoint:* {2.4.}

- At 60 fps, what cadences correspond to steps of exactly 21 and 22
frames? *Checkpoint:* {171.4 and 163.6 steps/min.}

- A clip filmed at 120 fps is stored at 30 fps and analyzed
as 30 fps. A true contact of 0.20 s is reported as what?
*Checkpoint:* {0.80 s.}

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

Pedals and pools.

- A rider's bottom positions are 38 frames apart at 60 fps. Cadence?
*Checkpoint:* {94.7 rpm.}

- From the rider's video, thigh $a=\SI{0.42}{\metre}$, shank
$b=\SI{0.44}{\metre}$ and knee angle at the bottom $\theta=\ang{150}$. Find
$r$ and the predicted change in $\theta$ for an 8 mm saddle
raise. *Checkpoint:* {$r=\SI{0.831}{\metre}$; \ang{0.52} per mm; \ang{4.1}.}

- A swimmer covers 25 m in 16.0 s with 18 freestyle cycles.
Find speed, stroke rate, distance per cycle and stroke index.
*Checkpoint:* {1.5625 m/s; 67.5 cycles/min;
1.39 m; 2.17 m²/s.}

**Exercise 9.8** (App lab · Foundation · 20 min · CORE)

Analyze yourself running (the five-step pattern).

- Film yourself from the side, phone still on a tripod at hip height,
whole body in frame, 15 to 30 seconds of steady easy running, at
60 fps or more. Note the capture rate.

- Open the running app (https://apopt.com/form/form.php), Distance mode, Basic
mode. If the app's frame-rate note appears, set the rate you filmed at. Save the
PDF and the text result.

- Pick cadence. Count your steps over 30 seconds of the clip by hand and
double it.

- Open Advanced mode. Find one measure Basic mode left out (duty factor,
flight time, overstride as % of leg) and say whether it changes your reading.

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

**Exercise 9.9** (App lab · Core · 25 min)

Walking speed against the ten-meter walk test.

- Tape a 14 m straight path with marks at 2 m and 12 m; the middle
10 m is timed, the ends are for speeding up and slowing down.

- A partner times you from the 2 m to the 12 m mark at your usual pace
with a stopwatch, three times.

- Film one walk from the side, square to the path, phone at hip height,
far enough back to see at least three strides.

- Run the walking app (https://apopt.com/walk/walk.php), Basic mode, side view, and
save the text result.

Compare the app's gait speed with $10/\text{time}$. Which of the two inherits
the evidence on gait speed and health in Section 9.5, and
why?

**Exercise 9.10** (App lab · Core · 20 min)

Hip drop from a waist band.

- Wear a bright band flat around the waist, in a color nothing else in the
frame shares.

- Fix the phone level (use its level or a bubble level) behind you on a
tripod at waist height, with even light.

- Record 20 seconds of marching or slow running in place, then 20 seconds
standing on one leg, each side.

- Run the hip drop app (https://apopt.com/hip/hip.php) and save the text result.

On one paused frame, measure the band's left and right ends in pixels and
compute the tilt by hand. Name two things other than your pelvis that could
tilt the band.

**Exercise 9.11** (Python analysis · Foundation · 20 min · CORE)

Download `form1_ankles.csv` (this chapter's data) and run
Listing 9.2 with an AI assistant's help.

- Before running, predict the stride period in frames from
Figure 9.1.

- Change the listing to estimate cadence from a straight-line fit of the
contact times against their index (as in Listing 9.7).
*Checkpoint:* {About 169.7 steps/min.}

- Explain in two sentences why the fit and the span agree with each other
but not with the median.

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

The autocorrelation gives the period in whole frames. Refine it: fit a
parabola through the peak lag $k$ and its two neighbours and take its vertex,

$$k^\ast = k + \tfrac12\,\frac{R(k-1)-R(k+1)}{R(k-1)-2R(k)+R(k+1)}.$$

Apply it to both ankles of the running example and convert to cadence.
*Checkpoint:* {About 21.15 frames, 170 steps/min.}

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

Imitate a 30 fps camera by keeping every second sample of the
synthetic 60 fps traces of Listing 9.8, and
rerun the cadence and contact-time analysis (use a 2-sample smoothing window).
Which measure survives the lower rate, and which loses its trend?

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

In two or three sentences each, for a reader with no physiology: (a) why does
walking have double support and running a flight phase? (b) What does the
stance leg do in running that it does not do in walking?

**Exercise 9.15** (Body science · Core · 6 min)

Which muscle group holds the pelvis level when you stand on one leg, and on
which side is it? Why can a 17-keypoint pose model measure pelvic drop only
roughly, even from behind?

**Exercise 9.16** (Science of the sport · Foundation · 6 min)

A swimmer's 25 m freestyle lengths, timed on the pace clock with cycles
counted from the deck: easy, 16 cycles in 20.0 s; hard, 19 cycles
in 17.0 s. Compute speed, stroke rate and distance per cycle for
each, and say what the swimmer did to go faster. Which of the pool's markings
would you use to calibrate a side-view video of the same lengths?

**Exercise 9.17** (Science of the sport · Core · 6 min)

A sprint coach runs the running app in its default Distance mode on a
10 m/s sprint and gets “Good” for contact time
(95 ms) and duty factor (26%). Explain to the coach, using
what decides top speed, why the grade is misleading and what to change.

**Exercise 9.18** (Field collection · Foundation · 60 min · CORE)

Three cadences and a taped 20 m.
*Equipment:* phone and tripod, metronome app, tape measure, floor tape
or chalk, a flat path of about 40 m. *Consent:* if you film a teammate,
get their written consent on the Appendix E form first; for a teammate under 18,
a parent or guardian gives written consent and the teammate gives their own
assent, and no image of a minor leaves the team. *Safety:* warm up for ten minutes;
easy pace only; stop if anything hurts; skip this if you are injured.

- Mark a 20 m section with tape, with 10 m run-ins at each end. Put the
phone on a tripod square to the middle of the section, far enough back that
the runner crosses the frame without changing size; film at 60 fps or
more.

- Run once at your own easy pace with no metronome. Count the steps in the
20 m and have a partner time it.

- Find your natural cadence from the clip. Set the metronome to it, then
5% and 10% above it, in random order, holding the same pace.

- For each run record: metronome setting, time for 20 m, steps in 20 m,
and the app's cadence, contact time and overstride (% of leg).

- Compute speed ($20/t$), step length ($20/\text{steps}$) and cadence
($60\times\text{steps}/t$) by hand, and fill a table like the one printed by
Listing 9.8.

What changed as cadence rose at the same pace, and was the change larger than
the run-to-run spread at the natural cadence?

**Exercise 9.19** (Field collection · Extension · 60 min)

The bicycle as a ruler: a 10 mm saddle change.
*Equipment:* stationary bicycle or a bicycle on a trainer, ruler, tape,
phone and tripod, metronome. *Consent and safety:* if the rider is not you, the rider's written consent (Appendix E; under 18, a parent or guardian's too, with the rider's own assent); a
competent person checks the seat-post clamp after every change; stop for any
discomfort; return the saddle to its starting height at the end.

- Mark the seat post at the starting height with tape. Fix the phone
square to the bicycle at saddle height, on the side you will film, and do not
move it again.

- Pedal at 90 rpm to the metronome for 60 seconds; film the last
20 seconds. Run the cycling app (https://apopt.com/cycling/cycling.php), side view.

- Raise the saddle 10 mm (ruler against the mark), repeat, then lower it
back and repeat once more.

- From the first clip read or measure $a$, $b$ and $\theta$ and predict
the change with Equation \eqref{ch09-gait:eq:saddle}.

Record the three knee angles, the predicted and measured change, and the
difference between the two runs at the starting height.

**Exercise 9.20** (Build · Core · 75 min · CORE)

Build step B-9: an event detector in your page.

- Add `peaks.js` (Listing 9.3) to your project. It finds local
maxima at or above a level and at least `minGap` samples apart, and
reports events per minute from the first to the last event.

- Write the test first: a 1.5 Hz wave sampled at 30 fps
for 20 seconds must give 30 peaks and 90.0 per minute. Your page must
pass it (the book's `peaks.test.js` prints `30 peaks, rate 90.0
per min`).

- Load the ankle CSV from B-4, choose the column, set the level to the
70th percentile and `minGap` from a period you enter, mark the peaks on
your line chart, and print the rate.

- Run it on `form1_ankles.csv`; double the per-foot rate to get
cadence.

**Exercise 9.21** (Communicate · Core · 25 min · CORE)

Using the clip and results from the three-cadence field exercise (or the
running example in this chapter), write a message of at most 120 words to the
runner. Give one cue, what to do, how often, for how long, and a retest date.
State one thing the measurement cannot tell them.

**Exercise 9.22** (Check the AI · Core · 8 min)

An assistant wrote this function and said “tested, duty factor for your
runner is 58%, which suggests too much time on the ground.”

{\ttfamily
def duty_factor(contacts, toe_offs, fps):

\hspace*{2em}tc = np.median(toe_offs - contacts) / fps

\hspace*{2em}step = np.median(np.diff(contacts)) / fps

\hspace*{2em}return 100 * tc / step}

Find the flaw, say what the true value is if $t_c=\SI{0.20}{\second}$ and the
contacts list holds both feet with steps of 0.345 s, and say what
else is wrong with the assistant's sentence.

**Exercise 9.23** (Python analysis · Core · 60 min)

Case file: can contact time be predicted from cadence for a runner the model
has never seen? Fit a straight line and score it with a split by athlete.

- A known answer first. Make synthetic data: six athletes, each with an
offset of their own, eight clips each, contact time falling
2 ms for every step a minute of cadence, plus noise. Fit the
line, and score it with a random five-fold split and with one athlete held out
at a time (`LeaveOneGroupOut` in scikit-learn).
*Checkpoint:* {The fitted slope is within about 15% of the one you built in, and
the mean absolute error is larger with athletes held out than with the random
split.}

- Build the case-file table. Run the running app (https://apopt.com/form/form.php)
on side-view running clips of at least four case-file athletes, two or more
clips each (different paces or days), and record athlete, clip, capture frame
rate, cadence and ground contact time from each result.
*Checkpoint:* {Every duty factor, $D = 100\,t_c\times\text{cadence}/120$ with $t_c$
in seconds, is well under 50%; a value above 50% means a detector error or walking
(Equation \eqref{ch09-gait:eq:duty}).}

- Fit contact time against cadence. Report the mean absolute error, in
milliseconds, of the mean baseline and of the line, each with the random split
and with athletes held out.

- Repeat on the course running data (https://apmonitor.com/dde/index.php/Main/BiomechanicRegression, file
`biomechanics2.txt`, loaded with `gait_data.py` from
Chapter 11's code, which labels each runner): contact time
`lgt` from cadence ($120\times$`sr`), then from cadence and
speed, holding runners out. *Checkpoint:* {2{,}620 steps, 22 runners; mean
absolute error with runners held out 25.7 ms for the mean
baseline, 12.8 ms for cadence ($R^2 = 0.74$),
9.0 ms for cadence and speed ($R^2 = 0.85$).}

- The line says faster cadence goes with shorter contact. Does it show that
raising cadence would shorten an athlete's contact? Use part (d).

**Exercise 9.24** (Communicate · Core · 30 min)

Case file: turn the previous exercise into a two-slide pitch for the coach of
one of your case-file athletes. Slide 1: the user (the coach), the decision the
model would help with, and the data. Slide 2: one chart of the model's error
with athletes held out beside the mean baseline's, one limit, and one next
step. Add speaker notes of at most 60 words per slide.

**Exercise 9.25** (Hand calculation · Core · 15 min)

A runner filmed from the side at 60 fps has a contact of
0.20 s and a flight of 0.10 s on one foot
(Section 9.2.4).

- Find the modeled peak force of that plant in body weights.
*Checkpoint:* {2.36 body weights.}

- Recompute it with the contact one frame shorter (and the flight one
frame longer), and one frame longer (flight one shorter). Give each as a
percentage change. Repeat at 240 fps.

- An app reports a mean modeled peak of 2.40 body weights on the left and
2.55 on the right from the 60 fps clip. Compute the asymmetry index of
Equation \eqref{ch09-gait:eq:asym}. Can you tell the runner one side pushes
harder? Say what would let you decide.

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

Start from Listing 9.5 on the running example.

- Move every left toe-off one frame later (left contact one frame longer,
the following flight one frame shorter) and recompute the asymmetry index.
Then move it one frame earlier.

- Put the stance threshold at the 60th and the 80th percentile instead of
the 70th (as in Table 9.6) and print the per-side mean
peaks and the asymmetry index for each.

- In three sentences for a coach, say what this clip can and cannot tell
about the force of each foot.
