# Q-27: An asymmetry index, three definitions

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

Web page: https://apopt.com/course/tutorials/q27-asymmetry/ · Data: https://apopt.com/data/tutorials/q27-asymmetry/

## The decision

A runner is told one leg spends longer on the ground than the other. Before anyone acts on
it, decide whether the difference is larger than the measurement can resolve, and whether the
number was computed the same way as the one it is being compared with.

## 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`).

An **asymmetry index** compares a left value with a right value. Section 9.5 gives the common
form, the difference as a percentage of the mean of the two sides:

A = 100 × |L − R| / ((L + R) / 2).

It is not the only one. The walking app uses three definitions for three of its measures
(checked in `walk/src/lib/metrics.ts`): stance time uses the mean of the two sides as the
denominator, arm swing uses the **larger** side, and knee bend uses the plain difference in
degrees. Apply all three to one runner's contact times and see how much the definition and the
frame rate decide the answer.

*Predict first:* At 30 frames per second, how large an asymmetry does a difference of one frame in a 6-frame contact make?

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

FPS = 30
df = pd.read_csv("raw/form1_ankles.csv")

def contact_frames(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, _ = find_peaks(y, height=hi, distance=int(0.2 * FPS))
    out = []
    for p in peaks:                                   # grow the stance while the foot stays low
        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
        out.append(j - i + 1)
    return np.array(out)

L, R = contact_frames(df["l_ankle_y"]), contact_frames(df["r_ankle_y"])
print(f"left:  {len(L)} contacts, frames {np.bincount(L)[4:].tolist()} (counts of 4, 5, 6, ... frames)")
print(f"right: {len(R)} contacts, frames {np.bincount(R)[4:].tolist()}")
print(f"mean contact: left {L.mean() / FPS * 1000:.0f} ms, right {R.mean() / FPS * 1000:.0f} ms")
```

Output:

```
left:  22 contacts, frames [0, 1, 13, 8] (counts of 4, 5, 6, ... frames)
right: 22 contacts, frames [0, 1, 13, 8]
mean contact: left 211 ms, right 211 ms
```

Every contact is a whole number of frames, mostly 6 or 7 (200 or 233 ms), and the two feet
have exactly the same mix: 13 contacts of 6 frames and 8 of 7 on each side. Now the three
definitions, on the runner's two means and on a pair of values that do differ, the median
single-leg hop heights of Section 10.2's worked example (0.142 m left, 0.121 m right).

```python
def a_mean(l, r): return 100 * abs(l - r) / ((l + r) / 2)     # stance time in the walking app
def a_max(l, r): return 100 * abs(l - r) / max(l, r)          # arm swing in the walking app
def a_diff(l, r): return abs(l - r)                           # knee bend in the walking app (deg)

l_ms, r_ms = L.mean() / FPS * 1000, R.mean() / FPS * 1000
for name, (l, r, unit) in {"runner, contact time": (l_ms, r_ms, "ms"),
                           "hops, height (Section 10.2)": (14.2, 12.1, "cm")}.items():
    print(f"{name}: mean denominator {a_mean(l, r):.1f} %, larger denominator {a_max(l, r):.1f} %, "
          f"plain difference {a_diff(l, r):.1f} {unit}")
print(f"one frame in a 6-frame contact: {a_mean(6, 7):.1f} % by the mean, {a_max(6, 7):.1f} % by the larger")
```

Output:

```
runner, contact time: mean denominator 0.0 %, larger denominator 0.0 %, plain difference 0.0 ms
hops, height (Section 10.2): mean denominator 16.0 %, larger denominator 14.8 %, plain difference 2.1 cm
one frame in a 6-frame contact: 15.4 % by the mean, 14.3 % by the larger
```

```python
import matplotlib.pyplot as plt

n = min(len(L), len(R))
pairs = [a_mean(l, r) for l, r in zip(L[:n], R[:n])]
fig, ax = plt.subplots(figsize=(6.4, 3.2))
ax.plot(range(1, n + 1), pairs, "o-", ms=4, label="each left-right pair")
ax.axhline(a_mean(l_ms, r_ms), color="black", lw=2, label="from the two means")
for level in (3, 8):
    ax.axhline(level, color="gray", ls="--", lw=1)
ax.set(xlabel="pair of contacts", ylabel="asymmetry (% of the mean)")
ax.legend(fontsize=8)
plt.tight_layout()
print(f"pairs: median {np.median(pairs):.1f} %, {sum(p == 0 for p in pairs)} of {n} exactly 0")
```

Output:

```
pairs: median 15.4 %, 9 of 22 exactly 0
```

![The mean-denominator asymmetry of each pair of consecutive left and right contacts across the run, jumping between 0 and 15 percent (once 33), the asymmetry of the two means at 0, and dashed lines at 3 and 8 percent.](https://apopt.com/course/tutorials/q27-asymmetry/c04-1.png)

Three lessons, one per cell.

* **The definition matters.** For the same two hops, the asymmetry is 16.0% with the mean as
  denominator, 14.8% with the larger side, and 2.1 cm as a plain difference. A published
  value can be compared with yours only if the formula matches (Section 9.5).
* **The frame grid matters more.** At 30 frames per second a contact of 6 frames against one
  of 7 is already 15.4% by the mean. Pair by pair, this runner swings between 0% and 15.4%
  (median 15.4%, 9 of 22 pairs exactly 0, one pair 33%), only because each contact is rounded
  to whole frames. The walking app's stance-time bands for walking, good under 3% and okay
  under 8% (the dashed lines), are smaller than one frame here.
* **Average before comparing.** The two feet's means are identical, 211 ms each, so the
  asymmetry of the means is 0.0%. Compare means over many contacts, never single pairs.

**For the athlete:** a left–right difference in contact time from a 30-frames-per-second clip
means nothing unless it is larger than one frame and shows in the average over many steps.

## With your own data

Run this page on your own two-ankle table, then film the same run at the highest frame rate
your phone offers and compare the pair-by-pair spread.

## The same method in another field

Comparing two channels that should match, two load cells under one beam or two temperature
sensors on one pipe, needs the same care: state the formula, and compare the difference with
the resolution of each channel before calling it real.

## Acknowledgements

Ankle table from Chapter 9 of *Data-Driven Athletics*; the hop heights are the worked example
of Chapter 10.

## References

- Chapter 9 of *Data-Driven Athletics*: The walking measures (the asymmetry index).

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