# Q-10: Open a phone sensor log and plot it

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

Web page: https://apopt.com/course/tutorials/q10-phone-log/ · Data: https://apopt.com/data/tutorials/q10-phone-log/

## The decision

A walker wants a step count from a phone in a pocket. Before counting anything, find out what the
phone actually recorded: how often, along which axes, and with what faults.

## The raw data

- `raw/walk_accel.csv`: a phone accelerometer log of a 60 s walk at about 50 samples a second, with time in nanoseconds and x, y, z in m/s² (synthetic, with planted faults) *Data-Driven Athletics*, Chapter 4 (`data/walk_accel.csv`, made by the chapter's `code/make_data.py`; invented, no real person).

### What a phone writes

A free sensor-logging app on a phone writes the accelerometer as a table: a time stamp and three
accelerations, x, y and z, along the phone's own axes, in m/s². The file here is the book's
**synthetic** 60-second walk (Chapter 4), made by a script so that its faults are known: the
phone was in a pocket, the walker stood still for about 5 seconds, walked, and stood again.
Open it and look before you compute anything.

*Predict first:* About 50 samples a second for 60 seconds. How many rows do you expect?

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

walk = pd.read_csv("raw/walk_accel.csv")
print(walk.shape)
print(walk.head(3).to_string(index=False))
print(walk.isna().sum().to_string())
```

Output:

```
(2980, 5)
               time  seconds_elapsed      z       y       x
1799704800000000000           0.0000 0.7775 10.3907 -0.4525
1799704800020080128           0.0201 0.0022 10.0185 -0.1915
1799704800041169664           0.0412 0.7386  9.3640 -0.0227
time               0
seconds_elapsed    0
z                  0
y                  0
x                  6
```

The `time` column is in **nanoseconds** since 1 January 1970, the form many logging apps use;
`seconds_elapsed` counts from the start of the log. Six cells of `x` are empty. Now the clock.
Never take the sample rate from the app's settings screen; compute it from the time stamps
(Section 4.2.4).

```python
t = (walk["time"] - walk["time"].iloc[0]) / 1e9               # ns -> s since the start
dt = t.diff().dropna()
print(f"median spacing {1000 * dt.median():.1f} ms -> {1 / dt.median():.1f} Hz")
print(f"largest gap {1000 * dt.max():.0f} ms; steps that do not move forward: {int((dt <= 0).sum())}")
walk["t_s"] = t
walk["mag"] = np.sqrt(walk["x"]**2 + walk["y"]**2 + walk["z"]**2)   # total acceleration
print(f"total acceleration: median {walk['mag'].median():.2f} m/s², largest {walk['mag'].max():.1f}")
```

Output:

```
median spacing 20.0 ms -> 49.9 Hz
largest gap 820 ms; steps that do not move forward: 20
total acceleration: median 10.11 m/s², largest 78.4
```

About 50 samples a second, with one gap of 820 ms and 20 rows that do not move forward in time:
a block the phone wrote twice. The **magnitude** of the three axes, √(x² + y² + z²), does not
care how the phone sits in the pocket. Standing still it reads gravity, 9.81 m/s²; walking makes
it swing around that. The largest value, 78 m/s², is eight times gravity: a spike to check.

### One chart

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 1, figsize=(8, 4.6))
ax[0].plot(walk["t_s"], walk["mag"], "-", color="k", lw=0.6)
ax[0].axhline(9.81, color="0.5", ls="--", lw=1, label="gravity")
ax[0].set(xlabel="time (s)", ylabel="acceleration (m/s²)", ylim=(0, 25))
ax[0].legend(loc="upper right")
win = walk[(walk["t_s"] > 10) & (walk["t_s"] < 14)]
ax[1].plot(win["t_s"], win["mag"], "o-", ms=2, color="k", lw=0.8)
ax[1].set(xlabel="time (s)", ylabel="acceleration (m/s²)")
plt.tight_layout()
print(f"samples between 10 and 14 s: {len(win)} (expected about {4 / dt.median():.0f})")
```

Output:

```
samples between 10 and 14 s: 220 (expected about 200)
```

![Two panels of total acceleration in m/s squared against time in seconds. Top, the whole 60 s: flat near 9.8 for the first and last 5 s, swinging between about 5 and 15 while walking, with one spike to 78 near 21 s and a short flat stretch near 33 s. Bottom, 10 to 14 s: a regular wave with about two peaks a second.](https://apopt.com/course/tutorials/q10-phone-log/c05-1.png)

The top panel shows the shape of the session: still, walking, still, and two faults, the spike
near 21 s (drawn off the scale here) and a stretch near 33 s where the line goes flat because the
sensor froze. The zoom shows the steps themselves, about two a second. The zoom window also
holds about 20 more samples than 4 seconds should: that is the block written twice, near 12 s.
Nothing has been cleaned yet; Q-12 marks what is wrong without deleting it.

**For the athlete:** "Your phone logged about 50 readings a second and caught your walking
rhythm clearly; before we count steps we'll fix one spike, one frozen second and one repeated
block in the file."

## With your own data

Record a minute of standing, walking and standing with a free sensor-logging app, phone in a
pocket, export the accelerometer as CSV, and run the same cells. Check the rate it delivered
against the rate you set.

## References

- *Data-Driven Athletics*, Chapter 4, Sample rate (Section 4.2.4) and Cleaning (Section 4.3).

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