# Q-18: Count steps from an accelerometer

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

Web page: https://apopt.com/course/tutorials/q18-step-count/ · Data: https://apopt.com/data/tutorials/q18-step-count/

## The decision

A runner wants a cadence from a chest sensor. Before trusting a step count, check the method on
a record whose answer is known.

## The raw data

- `raw/chest-acc-synthetic.csv`: SYNTHETIC chest accelerometer, 50 samples a second, in g (t_s, vert_g along the body, fwd_g out of the chest); 30 s of running at 172 steps a minute, then lying still Made by `book/ch06-gps-motion/code/make_chest.py` for Chapter 6 of *Data-Driven Athletics*; the same file as `book/ch06-gps-motion/data/chest-acc.csv`.

Each footstrike sends a jolt up the body, and an accelerometer on the chest sees it as a spike
on the axis along the body. Find the spikes and you have the steps. The file is the
**synthetic** chest record of Chapter 6 (Section 6.4): it was made by a script with a known
answer, 30 seconds of running at 172 steps a minute with a little natural variation from step
to step, then lying still. Because the answer is known, you can check your count exactly.

### Open the record

*Predict first:* At about 172 steps a minute, how many steps do you expect in 30 seconds?

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

acc = pd.read_csv("raw/chest-acc-synthetic.csv")          # t_s, vert_g, fwd_g
fs = 1 / acc["t_s"].diff().median()
run = acc[acc["t_s"] < 30]                                # the running part
t, x = run["t_s"].to_numpy(), run["vert_g"].to_numpy()
print(f"{len(acc)} samples at {fs:.0f} samples/s; running part {len(run)} samples")
print(f"vertical axis while running: mean {x.mean():.2f} g, from {x.min():.2f} to {x.max():.2f} g")
```

Output:

```
4750 samples at 50 samples/s; running part 1500 samples
vertical axis while running: mean 1.17 g, from 0.15 to 2.89 g
```

The mean is 1.17 g, not 0: standing or running, the sensor feels 1 g of gravity as well as
motion (Section 6.4), and the footstrike spikes push it up from there, to almost 3 g.

### Filter, then find peaks with a minimum gap

The recipe is the one used for R peaks in Q-13. A band-pass from 0.5 to 5 Hz keeps the step
rhythm and drops gravity and sensor noise; `find_peaks` then refuses any peak closer than
0.25 s to the last one, because no runner takes more than 240 steps a minute.

```python
from scipy.signal import butter, filtfilt, find_peaks

b, a = butter(2, [0.5, 5.0], btype="band", fs=fs)
y = filtfilt(b, a, x)                                    # two passes, so no time lag

def steps(min_gap_s):
    pk, _ = find_peaks(y, distance=max(1, int(min_gap_s * fs)), prominence=0.5 * y.std())
    return pk

pk = steps(0.25)
cadence = 60 * (len(pk) - 1) / (t[pk[-1]] - t[pk[0]])     # from the first to the last step found
print(f"{len(pk)} steps; cadence {cadence:.1f} steps/min")
```

Output:

```
86 steps; cadence 171.9 steps/min
```

The script that made the file put exactly 86 steps in the first 30 seconds, at 171.9 steps a
minute, so both numbers are right. The cadence comes from the time between the first and last
step found, not from the count
divided by 30 s: a step at the very edge of the window cannot be found, and that would bias
the count but not the spacing.

### How much does the minimum gap matter?

*Predict first:* If the minimum gap were 0.5 s instead of 0.25 s, would you count more steps or fewer, and roughly how many?

```python
import matplotlib.pyplot as plt

for gap in [0.0, 0.25, 0.5]:
    print(f"minimum gap {gap:.2f} s: {len(steps(gap))} steps")
f = np.fft.rfftfreq(len(x), 1 / fs)
p = np.abs(np.fft.rfft(x - x.mean())) ** 2
f_step = f[np.argmax(p[f > 0.5]) + np.sum(f <= 0.5)]
print(f"spectrum peak {f_step:.2f} Hz = {60 * f_step:.0f} steps/min")

fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
w = (t > 10) & (t < 14)
ax[0].plot(t[w], y[w], lw=1)
ax[0].plot(t[pk][(t[pk] > 10) & (t[pk] < 14)], y[pk][(t[pk] > 10) & (t[pk] < 14)], "o", mfc="none")
ax[0].set(xlabel="time (s)", ylabel="band-passed vertical (g)")
ax[1].plot(f, p / p.max(), "k-", lw=1)
ax[1].set(xlim=(0, 8), xlabel="frequency (Hz)", ylabel="relative power")
plt.tight_layout()
```

Output:

```
minimum gap 0.00 s: 86 steps
minimum gap 0.25 s: 86 steps
minimum gap 0.50 s: 43 steps
spectrum peak 2.87 Hz = 172 steps/min
```

![Two panels. Left, four seconds of the band-passed vertical acceleration with a circle on each detected step. Right, the spectrum of the running part, with one tall peak at 2.87 Hz, the step frequency, and a smaller one at twice that frequency.](https://apopt.com/course/tutorials/q18-step-count/c05-1.png)

A minimum gap of 0.5 s is longer than one step (0.35 s at 172 steps a minute), so the
detector skips every other step and counts 43. With no minimum gap the count here barely changes, because the
band-pass already smoothed each spike into one hump; on a real, noisier recording the small
wiggles would count. The spectrum gives a second, independent check: one tall peak at the step
frequency. The smaller peak at twice that frequency is a harmonic: the spikes are sharper than
a sine wave.

**For the athlete:** "Your chest sensor counted your steps as well as a stopwatch could: about
172 a minute, and two different methods agree."

## With your own data

Strap a phone to your chest with an elastic band, log its accelerometer with a sensor-logging
app while you run for 30 seconds, and use the axis along your body in place of `vert_g`.
Count your steps by ear for the same 30 seconds to have a known answer.

## Action card

- **Finding:** The detector finds all 86 steps; cadence 171.9 steps a minute.
- **Evidence:** Peak counting and the spectrum (2.87 Hz, 172 steps a minute) agree with the record's known 86 steps at 171.9.
- **Sure:** High on this synthetic record; a real recording needs the same check on a counted stretch.
- **Action:** Use a minimum gap of about 0.25 s for running, and report cadence from the spacing of the steps.
- **Retest:** Count 15 seconds of steps by ear on your own recording and compare.

## References

- *Data-Driven Athletics*, Chapter 6, Motion Sensing (Section 6.4): from acceleration to steps, steps and breaths from the chest.

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