# CS-12: The body-weight force of each foot plant

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

Web page: https://apopt.com/course/tutorials/cs12-foot-plant-force/ · Data: https://apopt.com/data/tutorials/cs12-foot-plant-force/

## The decision

A runner who had a sore right shin asks whether the right leg now "lands harder" than the
left. There is no force plate, only a phone clip. Physics turns contact and flight time into
a force estimate for every foot plant. Decide whether the left–right difference it shows is
larger than what the clip can resolve; if it is not, the answer is "can't tell yet", not "yes".
This is training information, not a medical assessment.

## Predict first

The model needs only contact time and flight time. A runner's contact is 0.25 s and a step 0.349 s. What peak force does the model give, in body weights, and by how much would it change if the contact were read one frame short at 30 frames per second?

## 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`).
- `raw/biomechanics.txt`: one row per left-foot step on an instrumented treadmill, with contact time, stride rate and measured peak force (2,625 rows) From the Data-Driven Engineering case study [Biomechanic Regression](https://apmonitor.com/dde/index.php/Main/BiomechanicRegression) ([file](https://apmonitor.com/dde/uploads/Main/biomechanics.txt)); data courtesy of Iain Hunter, BYU Biomechanics. The same file CS-13 uses.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| frame | frame number from 0 | count | 0–463 | none |
| t | time from the first frame | s | 0–15.43 | none |
| l_ankle_y, r_ankle_y | ankle image height; y grows downward | pixels | 1136–1688 | none |
| l_ankle_c, r_ankle_c | the pose model's confidence | 0 to 1 | 0.68–1.00 | none |
| lgt | left-foot ground contact time (treadmill file) | s | 0.12–0.27 | -9999 |
| sr | stride rate (treadmill file) | strides/s | 1.26–1.95 | -9999 |
| lpeakforce | measured left peak vertical force (treadmill file) | body weights | 2.1–4.7 | -9999 |

What is wrong with it: the clip is filmed from behind, so the foot moves away from the camera
during stance and the end of the stance is harder to place than in a side view; every time is
a whole number of frames at 30 frames per second, so a 0.2 s contact is only 6 frames; and the
runner's body mass is not known, so forces stay in body weights. In the treadmill file, 25 rows
hold the missing-value code −9999.

### The model, before any data

Over one whole step at a steady speed, the vertical force under the runner must average
exactly one body weight (BW); if it averaged more the runner would rise, less and the runner
would sink. The foot is on the ground for only part of the step, the **contact time** t_c,
and in the air for the rest, the **flight time** t_f. So while the foot is down the force
must average more:

mean force / BW = step time / contact time = 1 + t_f / t_c.

If the force during contact has the shape of half a sine wave, its peak is π/2 times its mean:

peak force / BW = (π/2) × (1 + t_f / t_c).

This is the sine-wave model of the running-stiffness method of Morin and colleagues (2005).
It needs two times and nothing else. The number it gives is **modeled**, not measured
(Section 5.1's distinction).

### Step 1 · Gather

Two files. The timing comes from Chapter 9's treadmill runner, filmed from behind at 30 frames
per second: both ankles' image position in every frame. The check comes from the Data-Driven
Engineering running data: an instrumented treadmill that measured the peak force of each
left-foot step, beside its contact time and stride rate.

*Predict first:* A runner's contact lasts 0.25 s and a whole step 0.349 s. What peak force, in body weights, does the model give?

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

FPS = 30
ankles = pd.read_csv("raw/form1_ankles.csv")
lab = pd.read_csv("raw/biomechanics.txt")
print(f"ankle table: {ankles.shape}, {len(ankles) / FPS:.2f} s at {FPS} frames per second")
print(f"treadmill file: {lab.shape}, columns {', '.join(lab.columns)}")

def mean_bw(tc, tf): return 1 + tf / tc
def peak_bw(tc, tf): return np.pi / 2 * (1 + tf / tc)

tc, step = 0.25, 0.349
print(f"by hand: mean {mean_bw(tc, step - tc):.2f} BW, peak {peak_bw(tc, step - tc):.2f} BW "
      f"= {peak_bw(tc, step - tc) * 70 * 9.80665:.0f} N for a 70 kg runner")
```

Output:

```
ankle table: (464, 8), 15.47 s at 30 frames per second
treadmill file: (2625, 11), columns speed, lgt, sr, sl, lkneeswing, lhipflex, lhipext, lcmvert, lkneesep, lcmtoe, lpeakforce
by hand: mean 1.40 BW, peak 2.19 BW = 1505 N for a 70 kg runner
```

### Step 2 · Statistics

Profile the columns each model input will come from: the ankle confidence and range, and
the three treadmill columns the check uses, `lgt` (left contact time, s), `sr` (stride rate,
strides per second) and `lpeakforce` (measured left peak force, BW).

```python
cols = ["l_ankle_y", "l_ankle_c", "r_ankle_y", "r_ankle_c"]
print(ankles[cols].describe().loc[["count", "mean", "min", "max"]].round(2).to_string())
print()
print(lab[["lgt", "sr", "lpeakforce"]].describe().loc[["count", "mean", "min", "max"]].round(3).to_string())
print("treadmill rows holding -9999 in these columns:", int((lab[["lgt", "sr", "lpeakforce"]] == -9999).any(axis=1).sum()))
```

Output:

```
       l_ankle_y  l_ankle_c  r_ankle_y  r_ankle_c
count     464.00     464.00     464.00     464.00
mean     1460.01       0.96    1440.67       0.97
min      1136.41       0.68    1138.60       0.83
max      1688.33       1.00    1656.35       1.00

            lgt        sr  lpeakforce
count  2625.000  2625.000    2625.000
mean    -95.034   -93.700     -92.293
min   -9999.000 -9999.000   -9999.000
max       0.267     1.951       4.744
treadmill rows holding -9999 in these columns: 25
```

The ankle table is clean: 464 frames, confidence never below 0.5. The treadmill file has the
missing-value code −9999 in every column, as CS-13 found; those rows are removed in Step 4
before any average is taken.

### Step 3 · Visualize: where is the foot on the belt?

The running app's stance rule (Chapter 9, `form/src/lib/metrics.ts`): smooth the ankle's image
height over 3 frames, take each lowest point in the bottom 15% of its range as a contact, and
grow the stance backward and forward while the foot stays in the bottom 30%. Draw the stances
on the trace before computing anything from them.

```python
import matplotlib.pyplot as plt

def stances(y):
    y = pd.Series(y).rolling(3, center=True, min_periods=1).mean().to_numpy()
    hi, lo = np.percentile(y, 85), np.percentile(y, 70)
    peaks = [i for i in range(1, len(y) - 1) if y[i] >= hi and y[i] >= y[i - 1] and y[i] >= y[i + 1]]
    out, last = [], -99
    for p in peaks:
        if p - last < int(0.2 * FPS):
            continue                                   # contacts at least 0.2 s apart
        i = j = last = p
        while i > 0 and y[i - 1] >= lo: i -= 1
        while j < len(y) - 1 and y[j + 1] >= lo: j += 1
        out.append((i, j))                             # first and last frame on the ground
    return out

st = {s: stances(ankles[f"{s}_ankle_y"].to_numpy()) for s in "lr"}
fig, ax = plt.subplots(figsize=(8, 3.2))
for s, style, shade in (("l", "-", 0.35), ("r", "--", 0.15)):
    ax.plot(ankles["t"], ankles[f"{s}_ankle_y"], style, color="black", lw=1, label=f"{s} ankle")
    for k, (i, j) in enumerate(st[s]):
        ax.axvspan(i / FPS, (j + 1) / FPS, color="gray", alpha=shade, lw=0, label=f"{s} stance" if k == 0 else None)
ax.set(xlim=(0, 4), xlabel="time (s)", ylabel="ankle y (pixels, down is down)")
ax.invert_yaxis(); ax.legend(loc="lower center", bbox_to_anchor=(0.5, 1.0), ncol=4, frameon=False)
plt.tight_layout()
print({s: len(v) for s, v in st.items()}, "stances")
```

Output:

```
{'l': 22, 'r': 22} stances
```

![Left and right ankle image height over the first four seconds, axis turned over so the belt is at the bottom, with each detected stance shaded, left stances darker than right; the gaps between a left and the next right stance are the flights.](https://apopt.com/course/tutorials/cs12-foot-plant-force/c05-1.png)

### Step 4 · Cleanse: pair each contact with the flight after it

A foot plant is one contact and the flight that follows it, up to the other foot's next
contact. Rules, written first: a stance must last 0.08 to 0.45 s (the app's bounds); the next
contact must be the **other** foot; and the flight must be longer than zero (an overlap means
walking, or an error). Every rule's removals go in a change log.

```python
import os

events = sorted([(i, j, s) for s in "lr" for i, j in st[s]])
rows, log = [], {"stance outside 0.08-0.45 s": 0, "next contact on the same foot": 0, "no flight": 0}
for (i, j, s), (i2, _, s2) in zip(events[:-1], events[1:]):
    tc, tf = (j - i + 1) / FPS, (i2 - j - 1) / FPS
    if not 0.08 <= tc <= 0.45:
        log["stance outside 0.08-0.45 s"] += 1
    elif s2 == s:
        log["next contact on the same foot"] += 1
    elif tf <= 0:
        log["no flight"] += 1
    else:
        rows.append({"foot": s, "start_frame": i, "contact_frames": j - i + 1,
                     "flight_frames": i2 - j - 1, "tc_s": round(tc, 4), "tf_s": round(tf, 4)})
plants = pd.DataFrame(rows)
os.makedirs("clean", exist_ok=True)
plants.to_csv("clean/foot_plants.csv", index=False)
print(f"{len(events) - 1} contacts with a next contact; kept {len(plants)}; removed: {log}")
print(plants.groupby("foot")[["contact_frames", "flight_frames"]].agg(lambda v: v.value_counts().to_dict()).to_string())
```

Output:

```
43 contacts with a next contact; kept 43; removed: {'stance outside 0.08-0.45 s': 0, 'next contact on the same foot': 0, 'no flight': 0}
           contact_frames        flight_frames
foot                                          
l     {6: 13, 7: 7, 5: 1}  {4: 13, 3: 5, 5: 3}
r     {6: 13, 7: 8, 5: 1}  {5: 10, 4: 9, 6: 3}
```

### Step 5 · Features: the force of each foot plant

Now the model, one foot plant at a time, then the mean of each foot and the asymmetry index of
Section 9.5, 100 × |L − R| / ((L + R) / 2).

*Predict first:* Will the left and right mean peak forces differ by more or less than 5%?

```python
plants["mean_bw"] = mean_bw(plants["tc_s"], plants["tf_s"])
plants["peak_bw"] = peak_bw(plants["tc_s"], plants["tf_s"])
plants.round(3).to_csv("clean/foot_plants.csv", index=False)
by_foot = plants.groupby("foot")["peak_bw"].agg(["count", "mean", "std", "min", "max"])
print(by_foot.round(2).to_string())
L, R = by_foot.loc["l", "mean"], by_foot.loc["r", "mean"]
se = np.sqrt((by_foot["std"] ** 2 / by_foot["count"]).sum())   # chance scatter of R - L
print(f"R - L = {R - L:.2f} BW (chance scatter of that difference {se:.2f} BW); "
      f"asymmetry index {100 * abs(L - R) / ((L + R) / 2):.1f} %")
print("mean frames:", plants.groupby("foot")[["contact_frames", "flight_frames"]].mean().round(2).to_dict("index"))
print(f"distinct peak values in the whole run: {plants['peak_bw'].round(3).nunique()}")
```

Output:

```
      count  mean   std   min   max
foot                               
l        21  2.56  0.20  2.24  2.88
r        22  2.76  0.22  2.47  3.14
R - L = 0.20 BW (chance scatter of that difference 0.06 BW); asymmetry index 7.5 %
mean frames: {'l': {'contact_frames': 6.29, 'flight_frames': 3.9}, 'r': {'contact_frames': 6.32, 'flight_frames': 4.73}}
distinct peak values in the whole run: 9
```

Three things to see. The model gives this runner a peak of about 2.6 BW on the left and 2.8 BW
on the right: a 7.5% asymmetry, and 0.20 BW is more than three times the 0.06 BW that the
plant-to-plant scatter alone would produce by chance. But look at where it comes from. Both
feet's contacts average just over 6 frames; the flights after a right contact average 4.73
frames, after a left contact 3.90. The whole difference is **less than one frame** of flight.
And the run produces only 9 distinct values: with contact and flight both counted in whole
frames, the model can only return a value from a small grid. The next step asks how much one
frame is worth.

### Step 5 continued · Carry one frame of error through

Read the contact one frame short or one frame long, with the step held fixed, and recompute.
Do it for the hand example at 60 and at 30 frames per second, and for this runner's median foot
plant at the 30 frames per second it was filmed at.

*Predict first:* One frame too few at 60 frames per second raises the peak by about how much? And at 30?

```python
def one_frame(tc, step, fps):
    base = peak_bw(tc, step - tc)
    short, long_ = (peak_bw(tc + d / fps, step - tc - d / fps) for d in (-1, 1))
    return base, 100 * (short / base - 1), 100 * (long_ / base - 1)

cases = [("hand example", 0.25, 0.349, 60), ("hand example", 0.25, 0.349, 30),
         ("this runner, median", plants["tc_s"].median(), (plants["tc_s"] + plants["tf_s"]).median(), 30)]
for name, tc, step, fps in cases:
    base, up, down = one_frame(tc, step, fps)
    print(f"{name:20s} {fps} fps: peak {base:.2f} BW; one frame short {up:+.1f} %, one frame long {down:+.1f} %")
print(f"left-right difference of the means: {100 * abs(L - R) / ((L + R) / 2):.1f} %")
```

Output:

```
hand example         60 fps: peak 2.19 BW; one frame short +7.1 %, one frame long -6.3 %
hand example         30 fps: peak 2.19 BW; one frame short +15.4 %, one frame long -11.8 %
this runner, median  30 fps: peak 2.88 BW; one frame short +20.0 %, one frame long -14.3 %
left-right difference of the means: 7.5 %
```

One frame too few at 60 frames per second raises the modeled peak by 7.1%; at 30, by 15.4% for
the hand example and by 20.0% for this runner, whose contact is only 6 frames long. One frame
too many lowers it by 6.3%, 11.8% and 14.3%. The left–right difference, 7.5%, is about half of
one frame's worth at 30 frames per second. It is consistent across the run, so it is not
random rounding, but a rule that ends the stance one frame earlier on one foot than the other
would produce it, and filmed from behind, the two feet are not seen the same way (Section 9.8).
That is the finding: from a phone clip at 30 frames per second, a left–right difference in
modeled force of this size cannot be told from a one-frame bias in the events.

Explore the same model with your own times in the viewer below: move contact time, flight time
and frame rate and watch the band.

### Step 5, checked · The model against a force-measuring treadmill

A model is only as good as its agreement with a measurement. The Data-Driven Engineering file
has left contact time and stride rate beside the left peak force measured by the treadmill, for
2,600 steps after the −9999 rows are dropped. A stride is two steps, so the step time is
1 / (2 × stride rate), and the flight is the step time minus the contact time.

```python
ok = lab[["lgt", "sr", "lpeakforce"]].ne(-9999).all(axis=1) & (lab["lgt"] > 0)
tr = lab[ok].copy()
tr["step_s"] = 1 / (2 * tr["sr"])
tr["model_bw"] = peak_bw(tr["lgt"], tr["step_s"] - tr["lgt"])
err = tr["model_bw"] - tr["lpeakforce"]
r2 = 1 - (err ** 2).sum() / ((tr["lpeakforce"] - tr["lpeakforce"].mean()) ** 2).sum()
print(f"{len(tr)} steps; measured {tr['lpeakforce'].mean():.2f} BW, modeled {tr['model_bw'].mean():.2f} BW")
print(f"mean error {err.mean():+.2f} BW ({100 * err.mean() / tr['lpeakforce'].mean():+.0f} %), "
      f"spread (SD) {err.std():.2f} BW, correlation {np.corrcoef(tr['model_bw'], tr['lpeakforce'])[0, 1]:.2f}, R² {r2:.2f}")
print(f"after removing the mean error: typical error {np.sqrt(((err - err.mean()) ** 2).mean()):.2f} BW")

fig, ax = plt.subplots(figsize=(4.8, 4.2))
ax.plot(tr["lpeakforce"], tr["model_bw"], ".", ms=2, alpha=0.4, color="black")
ax.plot([1.5, 5], [1.5, 5], "--", color="gray", lw=1, label="model = measured")
ax.set(xlabel="measured peak force (BW)", ylabel="half-sine model (BW)", aspect="equal")
ax.legend(loc="upper left", fontsize=8)
plt.tight_layout()
```

Output:

```
2600 steps; measured 2.96 BW, modeled 2.64 BW
mean error -0.32 BW (-11 %), spread (SD) 0.27 BW, correlation 0.74, R² -0.10
after removing the mean error: typical error 0.27 BW
```

![Modeled peak force against measured peak force for about 2,600 treadmill steps, with the line of equality: the points follow the line's slope but sit below it.](https://apopt.com/course/tutorials/cs12-foot-plant-force/c15-1.png)

The model rises and falls with the measured force (correlation 0.74), but it runs 0.32 body
weights low on average, 11% of the measured mean, the same bias CS-13 found on this file; and
the gap grows at the highest forces. With the bias removed the typical error is still 0.27 BW.
A real running force curve is more peaked than half a sine wave, so π/2 times the mean
underestimates the peak. And the impact peak at heel strike is
not in a sine wave at all. Read a modeled peak as a number to compare with the same runner's
other numbers, computed the same way, not as a force-plate value.

Set the two parts side by side. A one-frame error at 30 frames per second moves this runner's
modeled peak by 14 to 20%, about 0.4 to 0.6 BW; the model's own bias against the treadmill is
0.32 BW and its scatter 0.27 BW. On a phone clip, the frame rate is the larger error. Film at
120 frames per second or more and the one-frame error falls to about 4%, below the model's
own scatter.

## How good is the number?

Three errors, from largest to smallest on this clip. **The frame grid:** one frame at 30 frames
per second moves this runner's modeled peak by +20% or −14% (about 0.4 to 0.6 BW); at 60 frames
per second the hand example moves by +7.1% or −6.3%. The run produces only 9 distinct values.
**The event rule:** Chapter 9 shows the same clip's median contact time ranging from 0.13 to
0.28 s as the stance threshold moves from the 80th to the 60th percentile, which moves the
modeled force more than any frame. **The model:** against the force-measuring treadmill
(2,600 steps) the half-sine model is 0.32 BW low on average (11%), correlates 0.74 with the
measured peak, and has a typical error of 0.27 BW once the bias is removed, the same bias CS-13
found. The left–right difference here, 0.20 BW or 7.5%, is consistent across the run (three
times its chance scatter) but smaller than a one-frame bias in either foot's events.

## Track it

One row per session, per foot: `date, test=run-form-3.5, metric=modeled_peak_force_left_bw`
(and `_right_bw`), `value, unit=BW`, with the frame rate in `device` and the camera view in
`protocol_version`. Record contact and flight time too (`contact_time_s`, `flight_time_s`): the
force is computed from them, and they are what you measured.

## With your own data

Film yourself running on a treadmill from the side at the highest frame rate your phone offers,
build the two-ankle table (Chapter 9's first listing), and run this notebook from Step 1 with
your file. Set `FPS` to the rate you filmed at, not the rate the file says.

## The same method in another field

The same momentum balance gives the mean force of any repeated impact from its duty cycle: a
hammer drill, a pile driver, a stamping press. The Data-Driven Engineering page
[Biomechanic Regression](https://apmonitor.com/dde/index.php/Main/BiomechanicRegression) fits
regression models to the treadmill data; CS-13 sets this physics estimate beside them.

## Acknowledgements

The treadmill data and the original case study are from the Data-Driven Engineering course,
with data courtesy of Iain Hunter, BYU Biomechanics. The ankle table is from Chapter 9 of
*Data-Driven Athletics*, made with Ultralytics YOLO26 (AGPL-3.0).

## Action card

- **Finding:** The model gives about 2.6 body weights on the left and 2.8 on the right, a 7.5% difference.
- **Evidence:** The difference is less than one frame of flight time per step; one frame at 30 frames per second moves the estimate 14 to 20%.
- **Sure:** Low for the left–right difference; the clip cannot separate it from a one-frame bias in the events.
- **Action:** Don't change anything on this evidence. Refilm from the side at 120 frames per second or more, on the same treadmill speed.
- **Retest:** Compare the two feet again on the new clip, with the one-frame error band shown beside the difference.

## Challenge: The timing model against the measured force, both legs

The Data-Driven Engineering challenge file `biomechanics2.txt` has both legs. Use it to test
the timing model on each leg and to ask whether the left–right differences it gives match the
measured ones.

1. Load `biomechanics2.txt` from the Data-Driven Engineering Biomechanic Regression page, drop the placeholder name and e-mail columns and the −9999 rows, and keep a change log.
2. Compute the half-sine peak for each leg from its own contact time (`lgt`, `rgt`) and the shared stride rate, and compare it with `lpeakforce` and `rpeakforce` (bias, correlation, typical error).
3. For each trial, compute the measured and the modeled asymmetry index between legs, and plot one against the other.
4. Carry a one-frame error at 60 and at 240 frames per second through the modeled asymmetry, and say at which frame rate a phone could see the measured differences.

Deliverables:

- a notebook that runs top to bottom
- a table of bias, correlation and typical error by leg
- one paragraph for a coach on what a phone can and cannot say about left and right

## References

- Morin, J.-B., Dalleau, G., Kyröläinen, H., Jeannin, T., and Belli, A. (2005). A simple method for measuring stiffness during running. *Journal of Applied Biomechanics*, 21(2), 167–180. https://doi.org/10.1123/jab.21.2.167
- Lorimer, A. V., Keogh, J. W. L., and Hume, P. A. (2018). Using stiffness to assess injury risk: comparison of methods for quantifying stiffness and their reliability in triathletes. *PeerJ*, 6, e5845. https://doi.org/10.7717/peerj.5845 (Table 1 restates the sine-wave peak-force equation).
- Data-Driven Engineering: [Biomechanic Regression](https://apmonitor.com/dde/index.php/Main/BiomechanicRegression).

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