# Q-8: Speed from positions, and what noise does to it

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

Web page: https://apopt.com/course/tutorials/q08-speed-noise/ · Data: https://apopt.com/data/tutorials/q08-speed-noise/

## The decision

A coach wants the athlete's takeoff speed and peak acceleration from video. Before reporting
either, find out how much keypoint jitter each one can survive.

## The raw data

- `raw/noise_flight.csv`: hip height through one flight at 60 samples a second, with 5 mm of added jitter, the true height and speed, and the book's derivatives (synthetic; heights in cm) *Data-Driven Athletics*, Chapter 3, Section 3.2.4 (`data/noise_flight.csv`, made by the chapter's `code/make_data.py`; a parabola with known noise, no real person).

### Positions in, speed out

Video gives positions, one per frame. Speed (velocity) is the change of position per unit of
time, so it has to be computed, and the usual way is the **central difference**: the positions
on either side of a frame, divided by the time between them (Section 3.2.1):

v_i ≈ (y_(i+1) − y_(i−1)) / (2 Δt)

The file holds the height of Jordan's hips through one flight, 60 samples a second, with 5 mm
of made-up keypoint jitter added to a perfect parabola (the book's **synthetic** example of
Section 3.2.4). Because it is synthetic, the true height and speed are in the file too, so you
can see exactly what the jitter does.

*Predict first:* The positions are off by only 5 mm. How far off will the speed be, in m/s?

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

f = pd.read_csv("raw/noise_flight.csv")
t, y = f["t"].to_numpy(), f["y"].to_numpy() / 100          # the file is in cm; work in m
dt = np.median(np.diff(t))
v = (y[2:] - y[:-2]) / (2 * dt)                              # central difference
v_err = v - f["vtrue"].to_numpy()[1:-1]
print(f"{len(t)} samples, dt = {1000 * dt:.1f} ms; position error sd "
      f"{1000 * (y - f['ytrue'] / 100).std():.1f} mm")
print(f"speed error: sd {v_err.std():.2f} m/s (theory sigma/(sqrt(2) dt) = {0.005 / (np.sqrt(2) * dt):.2f})")
```

Output:

```
33 samples, dt = 16.7 ms; position error sd 5.6 mm
speed error: sd 0.22 m/s (theory sigma/(sqrt(2) dt) = 0.21)
```

Five millimeters of jitter becomes about 0.2 m/s of error in speed, close to the theory of
Section 3.2.4: the difference of two independent errors is √2 times bigger, and dividing by the
short time 2Δt magnifies it. Take the difference once more and you get acceleration.

```python
a = (y[2:] - 2 * y[1:-1] + y[:-2]) / dt**2                  # second difference
print(f"acceleration: mean {a.mean():.1f} m/s², sd {a.std():.0f} m/s² (truth: -9.81, sd 0)")
for fps in (30, 60, 120, 240):
    d = 1 / fps
    print(f"{fps:3d} fps: speed noise {0.005 / (np.sqrt(2) * d):5.2f} m/s, "
          f"acceleration noise {np.sqrt(6) * 0.005 / d**2:7.0f} m/s²")
c = np.polyfit(t, y, 2)                                      # one parabola, all samples at once
print(f"a parabola fitted to the whole flight: acceleration {2 * c[0]:.2f} m/s²")
```

Output:

```
acceleration: mean -6.4 m/s², sd 50 m/s² (truth: -9.81, sd 0)
 30 fps: speed noise  0.11 m/s, acceleration noise      11 m/s²
 60 fps: speed noise  0.21 m/s, acceleration noise      44 m/s²
120 fps: speed noise  0.42 m/s, acceleration noise     176 m/s²
240 fps: speed noise  0.85 m/s, acceleration noise     705 m/s²
a parabola fitted to the whole flight: acceleration -9.82 m/s²
```

The raw acceleration swings by about 50 m/s² around a mean that is not even gravity. And a
faster camera makes it **worse**: halving Δt doubles the speed noise and quadruples the
acceleration noise. Fitting one parabola to the whole flight, which uses the physics as well as
the data, recovers gravity almost exactly (Q-9 does this on a real jump).

### One chart

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 1, figsize=(6.4, 4.6), sharex=True)
ax[0].plot(t[1:-1], v, "o", ms=4, color="k", label="central difference")
ax[0].plot(t, f["vtrue"], "--", color="0.5", label="true")
ax[0].set(ylabel="speed (m/s)")
ax[0].legend(loc="upper right")
ax[1].plot(t[1:-1], a, "s", ms=4, color="k", label="second difference")
ax[1].axhline(-9.81, ls="--", color="0.5", label="gravity")
ax[1].set(xlabel="time in flight (s)", ylabel="acceleration (m/s²)")
ax[1].legend(loc="upper right")
plt.tight_layout()
print(f"largest speed error {np.abs(v_err).max():.2f} m/s; largest acceleration {np.abs(a).max():.0f} m/s²")
```

Output:

```
largest speed error 0.55 m/s; largest acceleration 140 m/s²
```

![Two panels against time in flight, 0 to 0.53 s. Top: speed from the central difference, dots scattered within about 0.55 m/s of the straight true line falling from 2.6 to -2.6 m/s. Bottom: acceleration from the second difference, dots swinging between about -140 and +125 m/s squared around the dashed line at -9.81.](https://apopt.com/course/tutorials/q08-speed-noise/c05-1.png)

The speed is usable: it follows the true line with a scatter you can state. The acceleration is
not, without smoothing or a model. That is why the apps smooth keypoints before they
differentiate them, and why a takeoff speed read from two frames carries an error band.

**For the athlete:** "Your takeoff speed from video is good to about 0.2 m/s; we'll compare
sessions by speeds and heights, not by accelerations read frame to frame."

## With your own data

Take the hip-midpoint height from a keypoint table of your own jump (CS-1 writes one), convert it
to meters with your scale, and run the same two cells on the frames in the air. Report the speed
with its noise; do not report a frame-to-frame acceleration.

## References

- *Data-Driven Athletics*, Chapter 3, Describing Motion: Position, velocity and acceleration from samples, and What noise does to a derivative (Section 3.2).

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