<!-- Generated by book/tools/make-index.py from the book source. -->

> Hedengren, J. (Ed.) (2027). Chapter 4: Athlete Data in Python. In *Data-Driven Athletics: Measuring, Modeling and Coaching Human Performance with Video and Wearable Data* (pp. 83–119). IRSRI Sports Research Institute. CC BY 4.0.

**Question.** You wore a chest strap and a watch for the same interval session. The two files have gaps, a few impossible beats, and clocks that do not agree. What was your heart rate, second by second, and how do you know?

**Objectives.**
- Write a notebook someone else can run: restart and run all, stated versions, a fixed seed, and functions checked against known cases.
- Load a table, a time series and a folder of app results files into pandas, and put every time stamp on one clock; describe each file in a data dictionary.
- Find missing values, spikes, flat lines, duplicates and unit mix-ups with rules you wrote down before you looked; keep the raw file, and log every change.
- Resample two devices onto one grid, find the offset between their clocks by cross-correlation, and join tables on a key with a check after every join.
- Smooth a signal with a moving average, a median filter and a low-pass filter, and state the lag each one costs; explain why a derivative amplifies noise.
- Describe a disagreement with a bias and limits of agreement, show a distribution, and draw a chart that makes one point without misleading.
- Use an AI assistant to write the code, and a hand-computed answer to check it.

# 4 Athlete Data in Python

Every measurement in this book ends up as a file. A chest strap writes one heart
rate a second. A phone writes three accelerations fifty or a hundred times a
second. The movement apps write a report, a highlight video and two text files for
each clip. None of these files is ready to be believed. A strap slips and records a
beat of 190. A watch logs local time without saying which zone. A phone in a
pocket freezes for a second and a half and then carries on. A coach types one
athlete's jump in inches into a sheet that is otherwise in centimeters.

This chapter teaches the small amount of Python you need to turn such files into
numbers you can defend. It uses one running example: an interval session recorded
by two devices at once, plus a walk recorded by a phone and the jump results files
from weeks 1 and 3. The data files are *synthetic*: they were generated by a
script in the chapter's `code/` folder so that the right answer is known.
Each problem in them (a seven-second clock error, a spike, a frozen sensor, a
time-zone trap) was put there on purpose, and the listings must find it.

The chapter assumes you write code with a generative AI assistant. That changes what
you need to learn. You do not need to memorize syntax. You need to say exactly what
the code must do, recognize whether the code you get does it, and check one result
a second way. The method has four steps, used in every exercise of the book:
*specify*, *generate*, *verify*, *defend*
(Section 4.9).

## 4.1 A Working Setup

Use a *hosted notebook*: a web page that runs Python on a remote computer and
keeps code, output and notes together in cells. Nothing is installed on your laptop,
and the libraries this book uses come preinstalled on the common services:
pandas for tables , NumPy for
arrays , SciPy for filters and signal
tools  and Matplotlib for
charts . Create a new notebook, upload the chapter's
`data` folder into it, and run Listing 4.1.

**Listing 4.1.** The setup check (`code/l01_setup.py`)

```python
# the setup check. Run it once in a fresh notebook.
import numpy as np, pandas as pd, matplotlib, scipy

print(pd.__version__, np.__version__, scipy.__version__, matplotlib.__version__)
strap = pd.read_csv("data/strap_hr.csv")   # upload the chapter's data/ folder first
print(strap.head(3))
print(len(strap))                          # rows: one per second for 25 min
```

```text
3.1.1 2.5.5 1.18.1 3.11.2
               time_utc  hr_bpm
0  2027-01-15T23:50:00Z     100
1  2027-01-15T23:50:01Z     101
2  2027-01-15T23:50:02Z     101
1500
```

Your version numbers may be newer; the last line must be `1500`, one heart
rate a second for 25 minutes. If it is not, the file did not upload whole. That
habit—ending every listing with one number you can predict—runs through the
chapter. Table 4.1 lists nearly every pandas command the
book uses. You do not need to learn them now; you need to recognize them when an
assistant writes them.

*Table 4.1. The pandas commands this book uses, and what each one does.*

| Command | What it does |
|---|---|
| `pd.read_csv(path)` | Read a comma-separated file into a table (a DataFrame). |
| `df.head()`, `len(df)`, `df.describe()` | First rows; number of rows; count, mean, spread and percentiles of each column. |
| `pd.to_datetime(...)` | Turn text such as `2027-01-15T23:50:00Z` into time stamps. |
| `.dt.tz_localize(zone)`, `.dt.tz_convert("UTC")` | Say which zone a time was written in; move it to another zone. |
| `df.melt(...)`, `df.pivot(...)` | Reshape a wide sheet into one row per observation, and back. |
| `df.drop_duplicates()`, `df.dropna()` | Remove repeated rows; remove rows with a missing value. |
| `s.diff()`, `s.shift(k)` | Difference from the previous row; move a column $k$ rows. |
| `s.rolling(5, center=True).mean()` | A moving window: here a centered five-point average (`.median()` for the median). |
| `s.resample("1s").mean()` | Put a time-indexed column on a regular grid, one value per second. |
| `s.interpolate(limit=5)` | Fill short gaps by straight lines, at most five in a row. |
| `pd.concat([a, b], axis=1)` | Put columns side by side, matched on their time stamps. |
| `df.groupby("week")["h"].mean()` | One summary number per group. |

> **Limits and cautions: Your data, someone else's computer.**
> 
> A hosted notebook runs on a company's server. Upload only data you are allowed to
> share, and remove names, birth dates and route start points first. The same rule
> applies, more strongly, to pasting data into an AI assistant: give it the column
> names and five made-up rows, not the athlete's file. Section 4.9
> returns to this.

### 4.1.1 A notebook someone else can run

A notebook lets you run cells in any order, and it remembers every variable you
made, even from a cell you have since deleted. That memory is called
*hidden state*, and it is the most common reason a notebook that “worked”
fails for the next person. *Reproducibility* means that someone else, with your
files, gets your numbers. For a notebook it takes five habits:

- **Restart and run all** before you share or hand in. Use the menu item
  that restarts the kernel and runs every cell from the top. If it fails, the
  notebook depended on a cell that ran earlier, or in a different order.

- **State the packages and versions** in the first cell, by printing them
  (or in a `requirements.txt` file beside the notebook).

- **Fix the random seed** once, at the top. Simulations, the bootstrap
  (Chapter 11) and train-and-test splits draw random numbers; a seed
  makes the draw the same every run. With another NumPy version the same seed may
  give other numbers, which is one more reason to print the version.

- **Name every file by its address**, such as
  `data/strap_hr.csv`, never by a path on your own laptop.

- **Check each function against three known cases** with `assert`,
  a line that stops the notebook with an error if its condition is false. Choose one
  ordinary case, one round-number case and one case that tests a unit.

**Example 4.1: Three known cases for a pace.**

Pace is time per kilometer, so \(pace=t/(d/1000)\) with \(t\) in seconds and
\(d\) in meters. A 10 km run in 50:00 is \(3000/10=300 s\) a kilometer,
5:00/km. One 400 m lap in 90 s is \(90/0.4=225 s\), 3:45/km.
A 6:00 mile is 1609.344 m (exact) in 360 s:
\(360/1.609344=223.69 s\), about 3:44/km. *Checkpoint:* 300, 225
and 223.69 s/km. The third case catches a function that assumes kilometers.

**Listing 4.2.** The first cell of a notebook someone else can run (`code/l16_pace.py`)

```python
# the first cell of a notebook someone else can run
import sys, numpy as np, pandas as pd
print(sys.version.split()[0], np.__version__, pd.__version__)   # state the versions
rng = np.random.default_rng(seed=4)          # one seed, set once, at the top

def pace_s_per_km(distance_m, time_s):
    """Pace in seconds per kilometer from a distance (m) and a time (s)."""
    if distance_m <= 0:
        raise ValueError("distance must be positive")
    return time_s / (distance_m / 1000)

assert pace_s_per_km(10_000, 3000) == 300               # 10 km in 50:00 -> 5:00 /km
assert pace_s_per_km(400, 90) == 225                    # a lap in 90 s -> 3:45 /km
assert abs(pace_s_per_km(1609.344, 360) - 223.69) < 0.01   # a 6:00 mile
print("3 known cases pass")
print(rng.normal(0, 0.2, size=3).round(3))   # simulated timing error (s): same every run
```

```text
3.12.3 2.5.5 3.1.1
3 known cases pass
[-0.13  -0.035  0.333]
```

Restart and run all twice. The last line must print the same three numbers both
times; if it does not, a random draw happens before the seed is set. A function
that fails an `assert` stops the notebook at once, which is what you want:
a wrong pace should never reach a chart. The function also refuses a distance of
zero rather than returning an infinite pace.

## 4.2 Tables and Time Series

### 4.2.1 Lists, arrays, and arithmetic on whole columns

A Python *list* holds values in order: `lap_s = [92.0, 88.5, 90.2]`.
You reach one value by its *index*, counted from zero, so `lap_s[0]` is
the first lap and `lap_s[-1]` the last. A *slice*
`lap_s[1:4]` takes positions 1, 2 and 3: it starts at the first number and
stops *before* the second. A NumPy *array* looks like a list but does
arithmetic on every value at once: `d / t` divides each distance by its own
time. Writing arithmetic on whole columns instead of a loop is called
*vectorizing*. A pandas column is an array with a name and an index, so
`df["d"] / df["t"]` works the same way.

**Example 4.2: Six laps by hand.**

Six 400 m laps take 92.0, 88.5, 90.2, 87.1, 91.4 and 84.0 s. The speed of lap 1
is \(400/92.0=4.348 m/s\); of lap 6,
\(400/84.0=4.762 m/s\). The session speed is the total distance
over the total time: \(2400/533.2=4.501 m/s\). The mean of the
six lap speeds is 4.505 m/s, slightly different, because each
lap counts equally however long it took. *Checkpoint:* 4.35 and 4.76 for laps 1
and 6; 4.501 for the session.

**Listing 4.3.** A loop and an array give the same answer (`code/l17_arrays.py`)

```python
# lists and arrays: six 400 m laps
import numpy as np
lap_m = [400, 400, 400, 400, 400, 400]          # a list: one distance per lap
lap_s = [92.0, 88.5, 90.2, 87.1, 91.4, 84.0]    # lap times, s
print(lap_s[0], lap_s[-1], lap_s[1:4])          # index from 0; a slice stops before 4
speed_loop = []
for d, t in zip(lap_m, lap_s):                  # a loop: one lap at a time
    speed_loop.append(d / t)
d, t = np.array(lap_m), np.array(lap_s)         # arrays: the whole column at once
speed = d / t                                   # m/s, one value per lap
print(speed.round(2))
print(np.allclose(speed_loop, speed))           # loop and array agree
print(len(lap_m * 2), (d * 2)[:2])              # a list repeats; an array multiplies
print(round(d.sum() / t.sum(), 3), round(speed.mean(), 3))   # session speed, mean of laps
```

```text
92.0 84.0 [88.5, 90.2, 87.1]
[4.35 4.52 4.43 4.59 4.38 4.76]
True
12 [800 800]
4.501 4.505
```

The loop and the array do the same divisions in the same order, so they agree
(`True`). The array is shorter to write, has no counter to get wrong, and on
a file of a million rows runs tens of times faster. Two traps are in the output.
Multiplying a *list* by 2 repeats it (12 items); multiplying an array doubles
each value. And the mean of ratios is not the ratio of the totals: report the session
speed as 4.501 m/s, not 4.505.

### 4.2.2 Tidy tables

A coach's spreadsheet usually has one row per athlete and one column per week.
That layout is easy to type and awkward to analyze, because “week” is a variable
but it lives in the column names. A *tidy* table has each variable in a
column, each observation in a row, and each kind of observation in its own
table . One jump by one athlete in one week is an
observation, so a tidy jump table has columns `athlete`, `week`,
`height` and `unit`, and one row per jump.
Listing 4.4 reshapes the sheet with `melt`.

**Listing 4.4.** A wide sheet made tidy (`code/l02_tidy.py`)

```python
# a coach's sheet (one column per week) made tidy
import pandas as pd

sheet = pd.read_csv("data/squad_wide.csv")
tidy = sheet.melt(id_vars=["athlete", "unit"], value_vars=["week1", "week3"],
                  var_name="week", value_name="height")
tidy["week"] = tidy["week"].str.replace("week", "").astype(int)
print(tidy.head(4))
print(len(tidy))          # one row per athlete per week (duplicates included)
```

```text
  athlete unit  week  height
0     A01   cm     1    31.2
1     A02   cm     1    28.4
2     A03   cm     1    35.0
3     A04   in     1    12.1
18
```

Eight athletes and two weeks should give 16 rows, not 18. The extra two come from a
row the coach typed twice; the fourth row is in inches. Both are fixed in
Section 4.3. Notice that the tidy layout made both
problems easy to see.

### 4.2.3 Time stamps, time zones and clocks that disagree

A *time series* is a table whose rows are ordered by a time stamp. Three
questions decide whether two time series can be compared: in which zone was each
time written, are the two clocks right, and how often was each sample taken?

The chest strap file writes `2027-01-15T23:50:00Z`. That is the
ISO 8601 form, and the final `Z` means *UTC*, Coordinated Universal
Time, the zone with no offset and no daylight saving. The watch file writes
`2027-01-15 16:50:09` and says nothing about the zone. The watch showed the
local time where it was worn, in the American Mountain zone, seven hours behind
UTC in January. A time with no zone is called *naive*. Python's standard
library and pandas read the rules for every zone (when daylight saving starts,
when a country changes its offset) from the public IANA time zone
database , so you name the zone, `America/Denver`,
rather than type “minus seven”, which is wrong for half the year.

**Example 4.3: Two clocks, one moment.**

The watch's first sample reads 16:50:09 local time in January, when the zone is
UTC\(-7\). In UTC it is \(16{:}50{:}09+7{:}00=23{:}50{:}09\) on the same date.
The session lasts 25 minutes from 23:50 UTC, so it ends at 00:15 UTC on
*16 January*. A filter “keep rows dated 15 January” on the UTC file would
throw away the last quarter hour of the session, although the athlete trained on
one evening.

**Listing 4.5.** Two files on one clock (`code/l03_clocks.py`)

```python
# two files, two clocks, one time line (UTC)
import pandas as pd

strap = pd.read_csv("data/strap_hr.csv")
watch = pd.read_csv("data/watch_hr.csv")
strap["t"] = pd.to_datetime(strap["time_utc"], utc=True)         # ...Z means UTC
watch["t"] = (pd.to_datetime(watch["timestamp"])                  # no zone written
              .dt.tz_localize("America/Denver")                   # where it was worn
              .dt.tz_convert("UTC"))
print(strap["t"].iloc[0], watch["t"].iloc[0])
print(strap["t"].dt.date.nunique())        # calendar days the UTC file spans
gap = (watch["t"].iloc[0] - strap["t"].iloc[0]).total_seconds()
print(gap)                                 # seconds between the two first samples
```

```text
2027-01-15 23:50:00+00:00 2027-01-15 23:50:10+00:00
2
10.0
```

The UTC file spans two calendar days, as Example 4.3
predicted. The first watch sample is 10 s after the first strap sample.
That is not yet the clock error: the watch may simply have started later. Every
device keeps its own clock, set from a phone or a satellite signal at some point
and drifting since. Two clocks can differ by a fraction of a second or by many
seconds, and nothing in either file says by how much. Section 4.4
measures the difference from the data themselves.

### 4.2.4 Sample rate

The *sample rate* is the number of samples per second, in hertz (Hz). A phone
logging app asks for a rate, but the phone delivers samples when it can, so the
spacing wanders. Never take the rate from the settings screen; compute it from
the time stamps, as in Listing 4.6. The walk file stores
each time stamp in nanoseconds since 1 January 1970 UTC, the form many logging apps
use, so dividing by \(10^9\) gives seconds.

**Listing 4.6.** The real sample rate of a phone log (`code/l04_rate.py`)

```python
# what is the sample rate, really?
import pandas as pd

walk = pd.read_csv("data/walk_accel.csv")
t = walk["time"] / 1e9                      # nanoseconds -> seconds
dt = t.diff().dropna()
print((1000 * dt).describe()[["min", "50%", "max"]].round(1))   # ms
print((dt > 3 * dt.median()).sum(), "gaps longer than 3 samples")
print((dt <= 0).sum(), "steps that do not move forward in time")
print(round(1 / dt.median(), 1))            # sample rate, Hz
```

```text
min      0.0
50%     20.0
max    820.0
Name: time, dtype: float64
1 gaps longer than 3 samples
20 steps that do not move forward in time
49.9
```

The median spacing is 20 ms, so the rate is about 50 Hz.
The minimum of 0 ms and the 20 steps that do not move forward
mean some rows repeat a time stamp; the maximum of 820 ms is a
gap. Use the median, not the mean, for the rate: one long gap moves the mean
spacing but not the median.

> **Engineer's note: How fast is fast enough?.**
> 
> A signal sampled at rate \(f_s\) can represent frequencies up to \(f_s/2\), the
> *Nyquist frequency* . Faster content is not
> lost quietly: it folds back and appears as a slower, false oscillation
> (*aliasing*). Walking steps come about twice a second and their sharpest
> features stay below about 10 Hz, so 50 Hz is ample. A beat-to-beat
> heart rate needs no more than one value a beat, but the electrocardiogram behind it
> needs hundreds of samples a second (Chapter 5).

### 4.2.5 The data dictionary

Every problem so far (a zone not stated, inches in a centimeter column, a rate that
was not the rate asked for) is a fact about a file that the file did not say. A
*data dictionary* says it. It is a table with one row per field and six
columns: the field's name; its meaning; its unit; its type (integer, decimal, text,
time); its allowed range; and its *missing-value code*, the way the file writes
“no value”. Table 4.2 gives one for a watch activity
table (the per-second record messages of a FIT file written out as CSV;
Section F.3) and one for the Heart app's CSV
(Section F.2). The ranges are your rules, written
before you look, as in Section 4.3.

*Table 4.2. Data dictionaries for a watch activity table and a Heart app CSV. Ranges are the analyst's rules; “empty” means an empty cell.*

| Field | Meaning | Unit | Type | Allowed range | Missing |
|---|---|---|---|---|---|
| 6@l*Watch activity table: one row a second while recording; no rows while paused* |  |  |  |  |  |
| timestamp | time of the record | ISO 8601, UTC | time | session start to end | never |
| heart_rate | heart rate from the watch | bpm | integer | 30–220 | empty |
| distance_m | distance since the start | m | decimal | 0–100 000, never falls | empty |
| speed_m_s | speed | m/s | decimal | 0–12 | empty |
| cadence | strides a minute of *one* foot; steps $=2\times$ | strides/min | integer | 0–130 | empty |
| 6@l*Heart app CSV: one row per ECG sample, about 130 a second* |  |  |  |  |  |
| time | Unix time | ns | integer | rises every row | never |
| ecg | ECG voltage | mV | decimal | $-5$ to $+5$ | never |
| hr | the strap's heart rate | bpm | integer | 30–220 | empty |
| rr | beat-to-beat interval | ms (old files: s) | decimal | 270–2000 | empty |
| marker | event label | none | text | any | empty |

Two lines of the table carry most of its value. Cadence in a FIT file counts one
foot, so a runner at 170 steps/min shows 85; and the Heart CSV's `hr` and
`rr` are filled only on the rows where the strap reported a beat, so most of
their cells are empty by design, not by fault. The `rr` range of 270 to
2000 ms is the heart-rate range turned into intervals:
\(60 000/2000=30 bpm\) and \(60 000/270\approx222 bpm\).
Listing 4.7 checks a synthetic 15-minute run against
the watch dictionary. It reads every cell as text first, so a cell that is not a
number is counted rather than silently turned into an empty one.

**Listing 4.7.** A file checked against its data dictionary (`code/l18_dictionary.py`)

```python
# check a watch activity table against its data dictionary
import pandas as pd
DICT = {  # field: (unit, low, high); missing-value code: an empty cell
    "heart_rate": ("bpm", 30, 220),
    "distance_m": ("m", 0, 100_000),
    "speed_m_s":  ("m/s", 0, 12),
    "cadence":    ("strides/min, one foot", 0, 130)}
act = pd.read_csv("data/watch_activity.csv", dtype=str)   # read as text first
print(len(act), "rows")
for field, (unit, lo, hi) in DICT.items():
    empty = act[field].isna()
    x = pd.to_numeric(act[field], errors="coerce")   # not a number -> NaN
    text = int((x.isna() & ~empty).sum())
    out = int(((x < lo) | (x > hi)).sum())
    print(f"{field:10s} empty {empty.sum()}  not a number {text}  outside range {out}")
t = pd.to_datetime(act["timestamp"], utc=True)            # dictionary: ISO 8601, UTC
step = t.diff().dt.total_seconds()
print(int(t.duplicated().sum()), "repeated stamps;",
      int((step > 5).sum()), "gap over 5 s:", step.max(), "s")
```

```text
855 rows
heart_rate empty 8  not a number 0  outside range 3
distance_m empty 0  not a number 0  outside range 0
speed_m_s  empty 0  not a number 2  outside range 0
cadence    empty 0  not a number 0  outside range 0
2 repeated stamps; 1 gap over 5 s: 48.0 s
```

The three heart rates outside the range are zeros: the converter that wrote the file
used 0 for “no reading”, a second missing-value code the dictionary did not list.
The two speeds that are not numbers are \texttt{-{}-}, a third. The gap of
48 s is an auto-pause, 47 seconds with no rows, which the dictionary's
first line allows. *Checkpoint:* 900 recorded seconds, less 47 paused, plus 2
rows written twice, is 855 rows. Update the dictionary with what you found, then
clean by it.

## 4.3 Cleaning

*Cleaning* means finding values that do not describe the athlete and deciding,
by a rule, what to do with each. Five problems cover most athlete data
(Table 4.3).

*Table 4.3. Five common problems, a rule that finds each, and a usual treatment.*

| Problem | A rule that finds it | Treatment |
|---|---|---|
| Missing value | An empty cell, or a gap in time longer than three sample spacings | Leave empty; fill only short gaps, and say so |
| Spike | More than a stated amount away from the median of its neighbors, or outside the physical range | Mark as missing; never average it in |
| Flat line | The same reading repeated for longer than a stated time | Mark the run as missing |
| Duplicate | The same time stamp (or the same whole row) twice | Keep one |
| Unit mix-up | A value in the wrong range for the unit, or a unit column that varies | Convert with an exact factor |

> **Key idea.**
> 
> Write the cleaning rules before you look at the data, and keep them in the code as
> numbers with units. A rule chosen after looking can be bent, without meaning to,
> toward the answer you hoped for. Science calls the cure
> preregistration ; in a notebook it is a dictionary
> called `RULES` at the top of the cell.

Figure 4.1 shows what the rules must find in the walk.
Listing 4.8 applies three of them. The spike rule is a
moving median: a sample more than 5 m/s² away from the
median of the five samples around it is not a step, because a step takes many
samples to rise and fall. This is a simple form of the *Hampel filter*, which
compares each sample with the median of its window .
The flat-line rule labels each run of identical values and measures how long it
lasted; real sensor noise never repeats a five-decimal reading for half a second.

*Figure 4.1. Part of the synthetic phone walk (vertical acceleration). A one-sample spike, a 1.5 s run in which the sensor repeated one reading, and a 0.8 s gap with no rows. A block of rows written twice (at 12 s) cannot be seen in a plot at all.*

**Listing 4.8.** Cleaning rules written before the data are seen (`code/l05_clean.py`)

```python
# cleaning rules written down BEFORE looking at the walk
import pandas as pd

RULES = {"max_abs": 4 * 9.81,     # m/s^2: walking stays under 4 g
         "flat_s": 0.5,           # identical readings this long = a frozen sensor
         "spike": 5.0}            # m/s^2 away from the median of 5 neighbors
walk = pd.read_csv("data/walk_accel.csv")
n0 = len(walk)
walk = walk.drop_duplicates(subset="time")                       # rows written twice
walk["t"] = walk["time"] / 1e9 - walk["time"].iloc[0] / 1e9
y = walk["y"]
med = y.rolling(5, center=True, min_periods=1).median()
spike = ((y - med).abs() > RULES["spike"]) | (y.abs() > RULES["max_abs"])
run = (y.diff() != 0).cumsum()                                   # runs of equal values
run_len = walk.groupby(run)["t"].transform(lambda s: s.max() - s.min())
flat = run_len >= RULES["flat_s"]
walk.loc[spike | flat, ["z", "y", "x"]] = float("nan")           # mark, do not delete
print(n0 - len(walk), "duplicates;", int(spike.sum()), "spike;", int(flat.sum()), "flat")
print(int(walk["y"].isna().sum()))          # samples now missing in y
```

```text
20 duplicates; 1 spike; 76 flat
77
```

The rules found the 20 duplicated rows, the one spike and the 76 frozen samples
(1.5 s at 50 Hz plus the run's first sample). The last
number, 77, counts the samples now marked missing in the vertical column. Notice
the line `walk.loc[...] = float("nan")`: the listing *marks* bad samples
rather than deleting rows, so the time line stays intact and anyone can count what
was removed.

The coach's sheet needs different rules (Listing 4.9). The
duplicate row goes. One athlete's heights are in inches, so they are multiplied by
2.54, which is exact by definition. One athlete missed week 1; that value stays
missing rather than being guessed.

**Listing 4.9.** Duplicates, a missing week and a unit mix-up (`code/l06_units.py`)

```python
# duplicates, a missing value and a unit mix-up in the coach's sheet
import pandas as pd

sheet = pd.read_csv("data/squad_wide.csv").drop_duplicates()   # A03 was typed twice
tidy = sheet.melt(id_vars=["athlete", "unit"], value_vars=["week1", "week3"],
                  var_name="week", value_name="height")
inch = tidy["unit"] == "in"
tidy.loc[inch, "height"] = tidy.loc[inch, "height"] * 2.54     # 1 in = 2.54 cm exactly
tidy["unit"] = "cm"
wide = tidy.pivot(index="athlete", columns="week", values="height")
change = (wide["week3"] - wide["week1"]).dropna()              # A07 missed week 1
print(change.round(1).to_dict())
print(round(change.mean(), 2))             # mean change, cm, over athletes with both weeks
```

```text
{'A01': 2.3, 'A02': 0.6, 'A03': 1.1, 'A04': 2.0, 'A05': 1.4, 'A06': -0.4, 'A08': 1.8}
1.26
```

Without the unit fix, athlete A04 would have improved by 0.8 cm
(12.1 to 12.9) and would have been the weakest jumper on the team by a factor of two;
with it, the change is 2.0 cm from a 30.7 cm start.
A value that is the right shape but the wrong size is the hardest error to see,
which is why the range check comes first.

> **Body science: What a heart-rate file can and cannot show.**
> 
> Heart rate is the number of heartbeats a minute. During exercise it rises with the
> work rate, but not at once: after a sudden change it takes tens of seconds to
> settle, which is why the strap's trace in Figure 4.2 curves
> up rather than stepping. A single beat of 190 in a run of 130s is almost always the
> device, not the heart: a strap that lost skin contact or a wrist sensor that locked
> onto the rhythm of the arm swing. Cleaning removes such values as measurement
> errors. It cannot tell whether a heart rhythm is normal, and it is not meant to.
> Anyone who feels chest pain, faintness or a racing irregular heartbeat should stop
> and see a clinician, whatever the file says.

### 4.3.1 Keep the raw file: provenance and a change log

Cleaning changes data, so it must leave a trail. *Provenance* is the record of
where a file came from: which device or app wrote it, with which settings, when,
who downloaded it, and what has been done to it since. Three rules keep it:

- **Never edit the original.** Keep the raw file exactly as it arrived (make
  it read-only), and record its fingerprint, a short code computed from every byte.
  If one byte changes, the fingerprint changes, so a month later you can prove the
  raw file is the one you started from.

- **Write the cleaned data to a new file**, beside the raw one, by code that
  anyone can rerun.

- **Keep a** *change log*: one line for each rule applied, the rule as
  a number with a unit, and how many rows it touched.

Listing 4.10 is Listing 4.8
extended to do all three. The `RULES` dictionary is unchanged; each rule now
also appends a line to `log`, and the log is saved as a CSV file beside the
cleaned copy.

**Listing 4.10.** The cleaning rules write their own change log (`code/l19_changelog.py`)

```python
# Listing 4.5's rules, now writing a cleaned copy and a change log
import hashlib, os, pandas as pd
RAW = "data/walk_accel.csv"                         # read, never written
RULES = {"max_abs": 4 * 9.81, "flat_s": 0.5, "spike": 5.0}
digest = hashlib.sha256(open(RAW, "rb").read()).hexdigest()[:12]  # the file's fingerprint
log = [("source " + RAW, "sha256 " + digest, "")]
walk = pd.read_csv(RAW)
log.append(("rows read", "", len(walk)))
n = len(walk); walk = walk.drop_duplicates(subset="time")
log.append(("drop repeated time stamp", "keep first", n - len(walk)))
t = (walk["time"] - walk["time"].iloc[0]) / 1e9
y = walk["y"]; med = y.rolling(5, center=True, min_periods=1).median()
spike = ((y - med).abs() > RULES["spike"]) | (y.abs() > RULES["max_abs"])
log.append(("spike: mark NaN", f"> {RULES['spike']} from median of 5", int(spike.sum())))
run = (y.diff() != 0).cumsum()
flat = t.groupby(run).transform(lambda s: s.max() - s.min()) >= RULES["flat_s"]
log.append(("flat line: mark NaN", f">= {RULES['flat_s']} s unchanged", int(flat.sum())))
walk.loc[spike | flat, ["z", "y", "x"]] = float("nan")
os.makedirs("out", exist_ok=True)
walk.to_csv("out/walk_clean.csv", index=False)       # a new file beside the raw one
log.append(("rows written", "out/walk_clean.csv", len(walk)))
log = pd.DataFrame(log, columns=["step", "rule", "rows"])
log.to_csv("out/walk_changelog.csv", index=False)
print(log.to_string(index=False))
```

```text
                      step                   rule rows
source data/walk_accel.csv    sha256 85c1c0be003f
                 rows read                        2980
  drop repeated time stamp             keep first   20
           spike: mark NaN > 5.0 from median of 5    1
       flat line: mark NaN     >= 0.5 s unchanged   76
              rows written     out/walk_clean.csv 2960
```

*Checkpoint:* \(2980-20=2960\) rows written, and \(1+76=77\) samples marked
missing, the same 77 as Listing 4.8. The fingerprint is the
first 12 characters of the file's SHA-256 hash; if your copy of
`walk_accel.csv` gives another, it is not the file the book used. A reader of
the log can now answer the questions a reviewer asks first: which file, which rules,
and how much did they remove? If a rule removed a fifth of a file, the log says so
before any chart does.

\paragraph{Where this goes next.} Gathering, describing, plotting and cleaning are
the first four steps of the nine-step data workflow on the page *The Data
Workflow* in the front matter. The case studies of Part V run all of them on raw
files; Case Study ? writes its
cleaning rules for a raw chest-strap night before it computes anything.

## 4.4 Resampling and Aligning

The strap records once a second, on the second. The watch records when it can:
usually every second, sometimes every two or three, at fractional seconds, and a few
values are empty. Before two such series can be compared, both go onto one regular
grid. *Resampling* puts the samples that fall inside each one-second bin into
one value (the mean of the bin), and *interpolation* fills an empty bin from
its neighbors. Fill only short gaps: `interpolate(limit=5)` draws a straight
line across at most five missing seconds and leaves longer gaps empty, because a
straight line across a minute invents a minute of data.

Once both are on the grid, the clock error can be measured. Slide one series
against the other a second at a time; at each shift compute the correlation between
them; the shift with the highest correlation is the offset. This is
*cross-correlation*, a standard tool for comparing two signals in
biomechanics . It works when the signal has features
both devices see: an interval session, with its sharp rises and falls, is ideal,
and a steady easy run is poor.

**Listing 4.11.** Resample both devices and find the clock offset (`code/l07_align.py`)

```python
# put both devices on one 1 s grid and find the clock offset
import numpy as np, pandas as pd

strap = pd.read_csv("data/strap_hr.csv")
watch = pd.read_csv("data/watch_hr.csv").dropna()
strap.index = pd.to_datetime(strap["time_utc"], utc=True)
watch.index = (pd.to_datetime(watch["timestamp"]).dt.tz_localize("America/Denver")
               .dt.tz_convert("UTC"))
watch.index.name = None
a = strap["hr_bpm"].resample("1s").mean().interpolate()
b = watch["heart_rate"].astype(float).resample("1s").mean().interpolate(limit=5)
both = pd.concat([a, b], axis=1, keys=["strap", "watch"]).dropna()
x = both["strap"] - both["strap"].mean()
y = both["watch"] - both["watch"].mean()
lags = np.arange(-30, 31)                                   # seconds to try
r = [np.corrcoef(x[30:-30], y.shift(-k)[30:-30])[0, 1] for k in lags]
best = int(lags[np.argmax(r)])
print(round(max(r), 3))
print(best)                                 # watch clock minus true time, s
```

```text
0.995
7
```

*Figure 4.2. Left: at the start of the first hard interval the watch (dashed), converted to UTC but not yet corrected, rises about 7 s after the strap (solid). Right: the correlation between the two series against the shift applied to the watch peaks at 7 s. Synthetic data.*

The watch clock is 7 s fast, which is the offset the data generator
put in. Two things make the answer trustworthy. The peak correlation is high
(0.995), and the curve in Figure 4.2 has one clear peak
rather than a flat top. Before you trust a cross-correlation on your own data, check
it by eye: pick one sharp feature, such as the start of an interval, and read its
time in both files.

> **Check it by hand: The offset from one edge.**
> 
> In Figure 4.2, left, the strap first reaches 140 bpm at
> 369 s; the uncorrected watch first reaches it at 377 s.
> The difference, 8 s, agrees with Listing 4.11 to within the
> watch's noise.
> One edge gives the offset to a second or two; the cross-correlation uses every edge
> in the session.

> **Engineer's note: What the correlation measures.**
> 
> For two series \(x\) and \(y\) with their means removed, the correlation at shift
> \(k\) is
> 
$$> r(k)=\frac{\sum_t x_t y_{t+k}}{\sqrt{\sum_t x_t^2}\sqrt{\sum_t y_{t+k}^2}},
> 
>$$

> a number between \(-1\) and 1. Removing the means matters: two heart-rate series
> are both near 130 bpm, and without it every shift looks alike. If one device
> also responds more slowly (a wrist sensor that averages over several seconds), the
> peak moves by that delay too, and cross-correlation cannot separate a clock error
> from a slow sensor. It measures how far apart the two series are, not why.

### 4.4.1 Joining tables on keys

Aligning puts two series on one clock. Often you must also match rows by what they
describe: a strap file has heart rates labeled by session, and the coach's log says
what each session was (easy, tempo, intervals). A *key* is the column that
identifies the thing both tables describe, here `session_id`. A
*join* (`merge` in pandas) copies the log's columns onto every strap row
with the same key. The log should have one row per session and the strap many, so
this is a *many-to-one join*: every strap row should find exactly one log row.

Three things go wrong, and none of them raises an error by default.

- A **duplicate key**: a session typed twice in the log. Each of its strap
  rows matches both copies, so the joined table has two copies of that session's
  heart rates, and every mean that counts rows is weighted wrongly.

- **Unmatched rows**: a strap session the log does not list (recorded but
  not logged), or a logged session with no strap file. An inner join drops both
  without a word.

- **Row growth**: the joined table has more rows than the strap table it
  started from, the visible sign of a duplicate key.

**Example 4.4: Predict the rows before you join.**

The strap file has sessions S01 to S04 with 60 rows each and S06 with 45: 285 rows.
The log lists S01 to S05, and S03 twice. A left join keeps every strap row, so
S01, S02 and S04 give 60 rows each, S03 gives \(60×2=120\), and S06 keeps its
45 rows with an empty session type: \(180+120+45=345\). *Checkpoint:* 345 rows,
60 more than the strap file, and 45 of them unmatched.

**Listing 4.12.** A join, and the check to run after every join (`code/l20_join.py`)

```python
# join strap rows to the coach's session log, and check the join
import pandas as pd
log = pd.read_csv("data/sessions.csv")          # should be one row per session
hr = pd.read_csv("data/session_hr.csv")         # many rows per session
print(len(log), log["session_id"].nunique(), len(hr))
m = hr.merge(log, on="session_id", how="left", indicator=True)
print(len(m), m["_merge"].value_counts().to_dict())
try:
    hr.merge(log, on="session_id", how="left", validate="many_to_one")
except pd.errors.MergeError as err:
    print("MergeError:", str(err).splitlines()[0])
print(log[log.duplicated("session_id", keep=False)].to_string())
log = log.drop_duplicates()                     # the two S03 rows are identical
m = hr.merge(log, on="session_id", how="left", validate="many_to_one", indicator=True)
only_strap = m.loc[m["_merge"] == "left_only", "session_id"].unique().tolist()
only_log = sorted(set(log["session_id"]) - set(hr["session_id"]))
print(len(m), only_strap, only_log)
```

```text
6 5 285
345 {'both': 300, 'left_only': 45, 'right_only': 0}
MergeError: Merge keys are not unique in right dataset; not a many-to-one merge
  session_id        date   type
2        S03  2027-01-20  tempo
3        S03  2027-01-20  tempo
285 ['S06'] ['S05']
```

The first line already shows the trouble: 6 log rows but 5 distinct keys. The first
join grows from 285 to 345 rows, as predicted. The argument
`validate="many_to_one"` turns the silent duplicate into an error, and
`indicator=True` adds a column `_merge` that says, for each row,
whether it matched (`both`) or came from one side only. After the identical
S03 rows are dropped, the join keeps 285 rows, and two questions remain for the
coach: what was S06, and did S05 happen without the strap? Neither is answered by
deleting rows. Run the same check after *every* join:

- predict the number of rows, and compare;

- state the relation with `validate=` (`"one_to_one"` or
  `"many_to_one"`);

- count the unmatched rows with `indicator=True`, and write the
  decision about them in the change log.

## 4.5 Smoothing and Differentiating

Every sensor adds noise. *Smoothing* replaces each sample by a combination of
its neighbors, so that random noise partly cancels. Three filters cover most needs:
the moving average, the median filter and the low-pass filter. Each has a cost, and
the main one is *lag*: the smoothed signal shows a change later than it
happened.

### 4.5.1 Moving average and median

An \(N\)-point *moving average* replaces each sample by the mean of \(N\)
samples. It is the best simple filter for random noise on a signal with sharp
steps , and it is easy to compute by hand.

**Example 4.5: A five-point moving average.**

Ten heart rates, one a second:
\(120, 122, 125, 124, 128, 130, 129, 133, 135, 134\) bpm.
A centered five-point average at sample 3 uses samples 1 to 5:
\((120+122+125+124+128)/5=619/5=123.8 bpm\). Sliding one sample at a time
gives, for samples 3 to 8,

$$123.8,\;125.8,\;127.2,\;128.8,\;131.0,\;132.2.$$

Samples 1, 2, 9 and 10 have no value, because a centered window needs two
neighbors on each side. The average loses \((N-1)/2=2\) samples at each end.

**Example 4.6: The same data with one bad beat.**

Now the strap slips and sample 6 reads 190 instead of 130. Every window that
contains sample 6 rises by \(60/5=12\) bpm, so samples 4 to 8 of the average become
\(137.8, 139.2, 140.8, 143.0, 144.2\). One bad beat has corrupted five seconds.
The *median filter* takes the middle value of each window instead. At sample 6
the window is \(124, 128, 190, 129, 133\); sorted, \(124, 128, 129, 133, 190\);
the middle value is 129. For samples 3 to 8 the median filter gives
\(124, 125, 128, 129, 133, 134\): the spike is gone, and the values stay close to the
clean data.

Listing 4.13 confirms both examples. The last line is the
moving average at the spike, 140.8 bpm, against a true value near
129 bpm.

**Listing 4.13.** The hand calculations of Examples 4.5 and 4.6, confirmed (`code/l08_filters.py`)

```python
# check the hand calculations of the two worked examples
import pandas as pd

hr = pd.Series([120, 122, 125, 124, 128, 130, 129, 133, 135, 134], index=range(1, 11))
spiked = hr.copy()
spiked[6] = 190                                   # one bad beat at sample 6
ma = hr.rolling(5, center=True).mean()            # 5-point centered moving average
ma_s = spiked.rolling(5, center=True).mean()
med_s = spiked.rolling(5, center=True).median()   # 5-point median filter
print(pd.DataFrame({"hr": hr, "MA": ma, "spiked": spiked,
                    "MA spiked": ma_s, "median spiked": med_s}).T.round(1).to_string())
print(ma_s[6])                                    # the average at the spike
```

```text
                  1      2      3      4      5      6      7      8      9      10
hr             120.0  122.0  125.0  124.0  128.0  130.0  129.0  133.0  135.0  134.0
MA               NaN    NaN  123.8  125.8  127.2  128.8  131.0  132.2    NaN    NaN
spiked         120.0  122.0  125.0  124.0  128.0  190.0  129.0  133.0  135.0  134.0
MA spiked        NaN    NaN  123.8  137.8  139.2  140.8  143.0  144.2    NaN    NaN
median spiked    NaN    NaN  124.0  125.0  128.0  129.0  133.0  134.0    NaN    NaN
140.8
```

The lesson is an order of operations: remove spikes with a median (or a rule, as in
Listing 4.8) first, then average.

### 4.5.2 Lag

A centered window uses future samples, so it can only be applied after the fact. A
live display, a watch screen or an app that reacts in real time must use a
*trailing* window of the last \(N\) samples. A trailing average is late.

**Example 4.7: The lag of a trailing average.**

Heart rate is rising by 1 bpm each second: \(\ldots,126,127,128,129,130\).
The trailing five-point average at the moment the value is 130 is
\((126+127+128+129+130)/5=128\), which is the value of two seconds earlier. On any
straight ramp the trailing \(N\)-point average is \((N-1)/2\) samples late: two
samples for \(N=5\), so 2 s at one sample a second and
40 ms at 50 Hz.

A *low-pass filter* lets slow changes through and removes fast ones above a
chosen *cut-off frequency*. The Butterworth filter is the usual choice in
biomechanics. Run once, forward in time, it delays the signal; run forward and then
backward over a recorded file (`filtfilt` in SciPy) the two delays cancel and
the result has no lag . Listing 4.14
measures both cases, and Figure 4.3 shows them.

**Listing 4.14.** The lag of three filters (`code/l09_lag.py`)

```python
# the price of smoothing is lag
import numpy as np, pandas as pd
from scipy.signal import butter, lfilter, filtfilt

ramp = pd.Series(np.arange(100.0))                 # a signal rising 1 unit per sample
trail = ramp.rolling(5).mean()                     # uses only the past (live data)
print(float(ramp[50] - trail[50]))                 # trailing 5-point: 2 samples late
fs = 50.0                                          # Hz, the walk's rate
b, a = butter(2, 3.0 / (fs / 2))                   # 2nd-order low-pass, 3 Hz cut-off
t = np.arange(0, 4, 1 / fs)
x = np.sin(2 * np.pi * 1.8 * t)                    # the 1.8 Hz step rhythm
one = lfilter(b, a, x)                             # one pass, forward in time
two = filtfilt(b, a, x)                            # forward and backward
lag = lambda y: np.argmax(np.correlate(y[50:], x[50:150], "valid"))
print(lag(two))                                    # samples of lag, two passes
print(round(1000 * lag(one) / fs))                 # ms of lag, one pass
```

```text
2.0
0
80
```

*Figure 4.3. Left: Example 4.6. One spike lifts five values of the moving average (squares, dashed); the median filter (triangles) ignores it. Right: a 1.8 Hz step rhythm through a 3 Hz low-pass filter. One forward pass (dashed) arrives 80 ms late; a forward-and-backward pass (dotted) has no lag.*

The one-pass filter is 80 ms (4 samples) late on the step rhythm.
For a recorded file there is no reason to accept that: use the two-pass filter. For
a live display, accept the lag and report it.

### 4.5.3 Why a derivative amplifies noise

Speed is the rate of change of position, and acceleration the rate of change of
speed. From samples, the rate of change is a difference divided by the time between
samples, \(\Delta t=1/f_s\). The difference of two noisy positions has the noise of
both, and dividing by a small \(\Delta t\) multiplies it. This is one of the oldest
problems in movement analysis .

**Example 4.8: Noise in a speed from video.**

A pose model places a jumper's hip with random noise of standard deviation
\(\sigma=5 mm\) in each frame of a 30 fps video. The speed
from two neighboring frames is \(v=(h_2-h_1)/\Delta t\). The noise of a difference
of two independent values is \(\sqrt2 \sigma\), so

$$\sigma_v=\frac{\sqrt2\,\sigma}{\Delta t}=\sqrt2\times0.005\times30=\SI{0.21}{\metre\per\second}.$$

The acceleration from three frames, \((h_3-2h_2+h_1)/\Delta t^2\), has noise
\(\sqrt{1+4+1} \sigma/\Delta t^2=\sqrt6×0.005×900=11 m/s²\),
larger than gravity itself.

**Listing 4.15.** A simulated jump: the noise in velocity and acceleration (`code/l10_derivative.py`)

```python
# differentiating multiplies the noise
import numpy as np

rng = np.random.default_rng(1)
fs, sigma = 30.0, 0.005                     # 30 fps video, 5 mm of pose noise
t = np.arange(0, 0.5, 1 / fs)
h = 2.62 * t - 9.81 * t**2 / 2              # a jump's centre of mass in flight, m
noisy = h + rng.normal(0, sigma, (20000, t.size))
v = np.diff(noisy, axis=1) * fs             # first difference: velocity
a = np.diff(noisy, n=2, axis=1) * fs**2     # second difference: acceleration
print(round(v.std(axis=0).mean(), 3))       # velocity noise, m/s
print(round((a.mean(axis=0)).mean(), 2))    # the mean is still right: -9.81
print(round(a.std(axis=0).mean(), 1))       # acceleration noise, m/s^2
```

```text
0.212
-9.81
11.0
```

*Figure 4.4. One simulated jump at 30 fps with 5 mm of noise (dots) and the truth (gray). The height looks clean, the velocity is ragged, and the acceleration is mostly noise.*

The mean acceleration over many jumps is still correct (-9.81 m/s²)
but any single value is not (Figure 4.4). Two cures work:
filter before differentiating, or fit a smooth curve and differentiate the curve.
The Savitzky–Golay filter does the second in one step, fitting a polynomial in a
moving window . Chapter 3 gave
the third cure: where you can, measure a time (flight time) rather than an
acceleration.

### 4.5.4 Putting it together: cadence from a walk

Listing 4.16 applies the chapter so far to the phone walk:
remove duplicates, clip the spike, put the samples on a regular 50 Hz
grid, low-pass at 3 Hz with two passes, find the peaks, and turn the time
between peaks into a cadence.

**Listing 4.16.** Cadence from a cleaned walk (`code/l12_cadence.py`)

```python
# from a cleaned walk to a cadence
import numpy as np, pandas as pd
from scipy.signal import butter, filtfilt, find_peaks

walk = pd.read_csv("data/walk_accel.csv").drop_duplicates(subset="time")
t = (walk["time"] - walk["time"].iloc[0]) / 1e9
grid = np.arange(0, t.iloc[-1], 0.02)                   # regular 50 Hz grid, s
y = np.interp(grid, t, walk["y"].clip(-40, 40))         # fills the 0.8 s gap linearly
b, a = butter(2, 3.0 / 25.0)                            # 3 Hz low-pass, fs/2 = 25 Hz
ys = filtfilt(b, a, y)
peaks, _ = find_peaks(ys, height=11.0, distance=int(0.3 / 0.02))
walking = (grid[peaks] > 6) & (grid[peaks] < 54)        # skip start and stop
step_t = np.diff(grid[peaks][walking])
print(len(peaks), "peaks;", round(np.median(step_t), 3), "s per step")
print(round(60 / np.mean(step_t), 1))                  # cadence, steps per minute
```

```text
90 peaks; 0.56 s per step
108.0
```

The generator walked at 1.8 steps a second, 108 steps/min, and the listing
recovers it. The median step time (0.56 s) can only take values on the
20 ms grid, so the listing reports the cadence from the mean step
time instead. The same peak count by ear is the free check: count steps for 30 seconds
and double.

## 4.6 Describing Data

A column of numbers is described by a center, a spread and its extremes. The
*mean* is the sum divided by the count; the *median* is the middle value
after sorting, and one wild value cannot move it. The *standard deviation*
(SD) is the typical distance from the mean. A *percentile* is the value below
which a stated share of the data lies: the 5th and 95th percentiles bracket the
middle 90%.

When two devices measure the same thing, the useful description is of their
*difference*. Plot the difference against the mean of the two, then draw the
mean difference (the *bias*) and the bias \(\pm1.96\) SD (the *limits of
agreement*). This is the *agreement plot* of Bland and
Altman . A correlation is the wrong tool here: two devices
can correlate at 0.99 and still disagree by 10 bpm at every beat.

**Listing 4.17.** Bias and limits of agreement, watch against strap (`code/l11_agree.py`)

```python
# describe the disagreement between the devices (after alignment)
import pandas as pd

strap = pd.read_csv("data/strap_hr.csv")
watch = pd.read_csv("data/watch_hr.csv").dropna()
strap.index = pd.to_datetime(strap["time_utc"], utc=True)
watch.index = (pd.to_datetime(watch["timestamp"]).dt.tz_localize("America/Denver")
               .dt.tz_convert("UTC") - pd.Timedelta(seconds=7))   # the 7 s clock offset
watch.index.name = None
a = strap["hr_bpm"].resample("1s").mean()
b = watch["heart_rate"].astype(float).resample("1s").mean()        # no filling here
d = (b - a).dropna()                                                # watch minus strap
print(d.describe(percentiles=[0.05, 0.5, 0.95]).round(2).to_string())
bias, sd = d.mean(), d.std()
print(round(bias - 1.96 * sd, 1), round(bias + 1.96 * sd, 1))      # limits of agreement
print(round(bias, 2))                                               # bias, bpm
```

```text
count    974.00
mean       0.97
std        2.57
min       -7.00
5%        -3.35
50%        1.00
95%        5.00
max        9.00
-4.1 6.0
0.97
```

*Figure 4.5. Agreement plot for the synthetic session after the 7 s clock correction: the watch reads 1.0 bpm high on average, and 95% of its seconds lie within \(-4.1\) to \(+6.0\) bpm of the strap. Points are jittered slightly so that whole-number values do not hide each other.*

After the clock correction the watch reads 0.97 bpm high on average, and 95%
of its seconds fall within \(-4.1\) to \(+6.0\) bpm of the strap
(Figure 4.5). Without the correction the limits are far
wider, because every rise and fall is compared with a value seven seconds away;
Exercise 4.9 asks you to measure by how much.

### How good is the number?

Three errors sit inside any agreement study, and the listings show how to size each.
The clock error, here 7 s, is found by cross-correlation and removed.
The bias, here 1 bpm, is the device's systematic error against the reference.
The random error, here an SD of 2.6 bpm, is what remains. In real devices all
three depend on the activity: one study of 50 adults found the chest strap agreed
almost perfectly with an electrocardiogram while wrist devices varied by brand and
exercise . For repeated measures of one athlete the
matching idea is the *typical error*, the SD of an athlete's repeated
values . From a test and a retest it is the SD of the
differences divided by \(\sqrt2\); Chapter 11 shows why and uses it
to decide whether a change is real.

## 4.7 Charts That Make One Point

A chart for a coach has one job: to make one point that the coach can see in five
seconds. Choose the form from the point (Table 4.4), then
remove everything that does not serve it.

*Table 4.4. The point decides the chart.*

| The point | A chart that makes it |
|---|---|
| A value changed over a session | Line against time, one line per device |
| A group changed between two weeks | Dots for each trial and a mark for each mean, zero on the axis |
| Two devices agree or not | Agreement plot (difference against mean) |
| One athlete against the squad | Dot strip of the squad, the athlete marked and named |
| One number matters | No chart: write the number, its unit and its uncertainty |

*Figure 4.6. The same six valid jump results and one invalid one. Left, a default chart: the axis starts at 29 cm, so a 4 cm range looks like a fivefold one; “Series1” to “Series7” say nothing; seven shades suggest seven categories; the invalid clip is included. Right: weeks as the categories, each jump shown, means labeled, zero on the axis, and the point as the title.*

Figure 4.6 draws the jump results of
Section 4.8 twice. The left chart is what a spreadsheet
produces by default. The right one follows five rules:

- The title states the finding (“Week 3 jumps: 2.8 cm higher”), not the
  variable.

- Every trial is shown, not only a bar for the mean. With three or four values
  per group, a bar hides how they spread .

- Lengths start at zero, so a change looks as large as it is.

- Axis labels have units, and the categories are words a coach uses.

- Identity is carried by position and labels, never by color alone, so the chart
  survives a black-and-white printer.

A difference of 2.8 cm on a jump of 31 cm is
about 9%: worth reporting, and also within reach of measurement noise for three jumps a
week (Chapter 11). The honest chart lets the coach see both.

### 4.7.1 A distribution, and three ways a chart misleads

The *distribution* of a measure is how its values spread: where they bunch,
how far they reach, whether they form one group or several. Two charts show it. A
*histogram* cuts the range into equal bins and draws a bar for the number of
values in each. A *box plot* draws five numbers: a box from the first to the
third quartile (the middle half of the values), a line at the median, and whiskers
out to the extremes (here the minimum and maximum; some programs stop the whiskers
at 1.5 box lengths and draw the rest as dots). Listing 4.18
computes both for the strap's 1500 heart rates, and
Figure 4.7 draws them.

**Listing 4.18.** What a box plot and a histogram each draw (`code/l21_distribution.py`)

```python
# one measure, two summaries: the strap's 1500 heart rates
import numpy as np, pandas as pd
hr = pd.read_csv("data/strap_hr.csv")["hr_bpm"]
q = hr.quantile([0, 0.25, 0.5, 0.75, 1])        # what a box plot draws
print(q.round(0).astype(int).tolist())
counts, edges = np.histogram(hr, bins=np.arange(90, 191, 10))
for lo, c in zip(edges[:-1], counts):           # what a histogram draws
    print(f"{lo:3.0f}-{lo + 10:3.0f} {c:4d} " + "#" * (c // 20))
```

```text
[100, 111, 131, 160, 174]
 90-100    0
100-110  343 #################
110-120  148 #######
120-130  190 #########
130-140  240 ############
140-150  104 #####
150-160   88 ####
160-170  210 ##########
170-180  177 ########
180-190    0
```

*Figure 4.7. The strap's 1500 heart rates (synthetic). *Observation:* the values form three clusters, near 100–115, 125–135 and 165–175 bpm; the box plot shows one middle half from 111 to 160 bpm and hides them. *Explanation, from the session plan, not the chart:* warm-up and cool-down, the easy recoveries, and the four hard intervals.*

The box says the middle half of the session lay between 111 and 160 bpm, with
a median of 131. The histogram says what the box cannot: there were three
clusters, and the top of the box, 140 to 160 bpm, is a range the heart passed
through rather than stayed in. Draw the histogram first; use box plots
when you compare many groups side by side and already know each is a single cluster.

The caption of Figure 4.7 follows a rule worth
keeping: separate the *observation* (what the chart shows, which anyone can
check against it) from the *explanation* (why, which needs other evidence) and
label each. A reader can then accept the first while questioning the second.

Figure 4.8 shows three common ways a correct number
makes a misleading chart, each drawn wrong and then corrected.

- **Truncated axis.**  Bars whose axis starts at 4.40 s make a 30 m time
  of 4.51 s look \(0.11/0.02=5.5\) times as long as 4.42 s. A bar's length is its
  message, so a bar axis starts at zero; to show a small difference, write it
  (0.09 s, 2%) or use dots on an axis that says where it starts.

- **Dual axis.**  Two lines on two vertical scales can be made to cross, track or
  diverge by choosing the scales, here suggesting that a 60% rise in weekly
  distance moved the 5 km time just as much. It moved 2%. Give each measure its own
  panel and unit, on a shared time axis.

- **Overplotting.**  Heart rates are whole numbers, so the 974 points of the
  agreement plot fall on only 457 places, and solid dots stack out of sight. Make the
  dots small and see-through and jitter them slightly (as in
  Figure 4.5), or count them in a two-dimensional
  histogram.

*Figure 4.8. Three ways a chart misleads (left) and their corrections (right). Top: a truncated bar axis. Middle: two scales chosen so the lines track; corrected as two panels. Bottom: 974 solid points that cover each other; corrected with small, see-through, jittered dots. Invented sprint and training numbers; the bottom row uses the data of Figure 4.5.*

## 4.8 The App Results Files

Every movement app at \apopt{} can analyze one video at a time, and each also has a
*process-a-folder* page (`automation.html` in the app's folder) that
analyzes every video in a folder you choose. The page runs in a desktop browser
that can read and write a local folder; the videos never leave the computer. For a
video called `jump_wk1_t1.mp4` it writes four files beside the
original:

- `results_jump_wk1_t1.mp4`, the highlight video;

- `results_jump_wk1_t1.pdf`, the report;

- `results_jump_wk1_t1.md`, the text results, in Markdown;

- `results_jump_wk1_t1.json`, a *receipt*: the settings and
  frame rates the analysis used. It is written last, so a folder with a
  `.json` file has a complete set.

Files whose names start with `results_` are never treated as input, and
existing results are never overwritten.

> **Try it in the app: Process a folder.**
> 
> Put your week 1 and week 3 jump clips in one folder. Open the jump app's
> process-a-folder page in a desktop browser, choose the folder, enter your height and
> the frame rate each clip was *recorded* at (120 for a 120 fps slow-motion clip,
> even though the file says 30), and press the process button. Keep the
> `.md` and `.json` files for Exercise 4.12.
> 
> 
> https://apopt.com/jump/automation.html

\paragraph{How data moves through an app.} Every number in a results file has passed
through several hands, and its unit changed on the way
(Figure 4.9). A camera stores frames and the rate it
claims; the app finds joints in pixels, turns pixels into centimeters with the
height you typed and frames into seconds with the frame rate, and writes text such
as “32.9 cm”; your notebook turns that text back into a number. A chest strap
sends its voltage in microvolts and its beat intervals in 1/1024ths of a second; the
Heart app writes millivolts and milliseconds. Each arrow is a place where a wrong
setting (a frame rate, a height, a unit) changes every number downstream without
any error. When a result looks wrong, walk the figure from top to bottom and check
the unit at each arrow. Chapter 12 uses the same picture to design an app.

*Figure 4.9. How data moves through two of the course's apps, with the unit at each step. Left: a video through a movement app; right: a chest strap through the Heart app. Both end as numbers in a notebook, where the unit belongs in the column name (`height_cm`, `rr_ms`).*

### 4.8.1 The text results

The Markdown file is meant to be read by a person, by a spreadsheet and by an AI
assistant, so it has a fixed layout shared by all the apps. In order:
a title line `# Jump Form Analysis results`; a hidden marker
`<!– irsri-results app=jump format=markdown version=1 –>` that names the app
and the format version; an *Analysis* table of settings (time generated, in
UTC to the minute, the video name, and the app's assumptions such as height and frame
rate); a *Summary* list; *Focus areas*; a *Metrics* table; optional
extra tables; *Metric details*; *Notes*; a disclaimer line; and, when the
folder page made the file, a *Batch processing* section with the analyzed time
range and any warnings. Listing 4.19 shows the parts a
program needs.

**Listing 4.19.** Excerpt of `results_jump_wk3_t3.md` (synthetic)

```text
# Jump Form Analysis results

<!-- irsri-results app=jump format=markdown version=1 -->

## Analysis

| Setting | Value |
| --- | --- |
| Generated | 2027-01-22 16:09 UTC |
| Video | jump_wk3_t3.mp4 |
| Athlete height | 175.0 cm / 68.9 in |
| Analyzed frames | 476 samples at 30.0 Hz |
| Frame rate | 30 fps capture (detected) |
...
## Metrics
...
| Section | Metric | Value | Rating | Target |
| --- | --- | --- | --- | --- |
| Jump Outcome | Jump Height | 32.9 cm / 13.0 in | Pro (2/3) | 49 cm or more (28% of standing height); Pro from 32 cm |
| Jump Outcome | Flight Time | N/A | N/A | 600 ms or more; Pro from 400 ms |
| Lower Body Power | Amortization | N/A | N/A | 120 ms or less; Pro up to 200 ms |
...
## Batch processing

Analyzed video time: 0.000–15.900 seconds.

- This video is 30 fps, so quick moments can fall between frames. If it was filmed
  in slow motion (for example 120 or 240 fps) and saved at 30 fps, choose the
  recorded frame rate so times and speeds are correct.
- The jump measured a 2.07 s flight, more than any person can jump, so the flight
  time and every time and speed taken from the video clock (phase times, timing
  offsets, extension and arm-swing speeds) are not used. The clip is probably slow
  motion: set the frame rate the camera recorded at (likely 120 fps).
```

The Metrics table always has the columns *Section, Metric, Value, Rating,
Target* when any metric has a rating (*Section, Metric, Value, Target*
otherwise). The Value cell carries its unit as text, sometimes in two systems
(“32.9 cm / 13.0 in”), and `N/A` when the clip could not measure it. The
Rating cell holds Elite (3/3), Pro (2/3), Good (1/3) or N/A; note that “Good” is
the *lowest* rating (Chapter 13 returns to that choice of
word). The two `.md` warnings come from the frame-rate check: this week-3
clip was filmed at 120 fps but analyzed at the file's 30 fps header.

### 4.8.2 The receipt

The `.json` receipt holds no metrics. It records how the analysis was run:

**Listing 4.20.** The receipt `results_jump_wk3_t3.json`, warnings shortened

```text
{
  "version": 1,
  "savedAt": "2027-01-22T16:09:58.000Z",
  "id": "b1a4a030-a86c-40c3-9025-147a0328b421",
  "state": "succeeded",
  "stage": "Saved",
  "progress": 1,
  "input": "jump_wk3_t3.mp4",
  "options": { "captureFps": "auto", "heightMeters": 1.75, "model": "movenet_thunder",
               "outputFormat": "vertical", "metricCycleSeconds": 5 },
  "warnings": [ "This video is 30 fps, ...", "The jump measured a 2.07 s flight, ..." ],
  "outputs": { "mp4": { "name": "results_jump_wk3_t3.mp4", "size": 3097215 },
               "pdf": { "name": "results_jump_wk3_t3.pdf", "size": 1299038 },
               "md":  { "name": "results_jump_wk3_t3.md",  "size": 17045 } },
  "sourceFps": 30,
  "actualCaptureFps": 30,
  "analyzedRange": { "start": 0, "end": 15.9 }
}
```

The fields that matter for analysis are `input` (the video),
`options.captureFps` (`"auto"` or the rate you typed),
`sourceFps` (the rate written in the file), `actualCaptureFps` (the
rate the analysis used), `options.heightMeters` (the scale) and
`warnings`. The real files are pretty-printed with one field per line; the
listing compresses a few lines to fit the page.

> **Limits and cautions: The folder in data/results is synthetic.**
> 
> The seven result pairs in the chapter's `data/results` folder were written by
> the jump app's own text-results code and the folder page's file layout, fed with
> invented measurements for an invented athlete 1.75 m tall. The format is
> exact; the jumps never happened. The time-based values in
> `results_jump_wk3_t3.md` were made four times too long on purpose, as a
> 120 fps clip read at 30 fps would make them; the app's own check then withheld
> them, as it would for a real clip.

### 4.8.3 A folder into one table

Listing 4.21 reads every Markdown file, finds the Metrics
table, splits each row at the `|` signs, and takes the leading number of the
Value cell. It joins each file to its receipt by the shared name. The result is a
tidy table with one row per metric per clip: 7 clips times 17 metrics.

**Listing 4.21.** A folder of app results into one table (`code/l13_results.py`)

```python
# a folder of app results into one table
import json, pathlib, re
import pandas as pd

rows = []
for md in sorted(pathlib.Path("data/results").glob("results_*.md")):
    receipt = json.loads(md.with_suffix(".json").read_text())    # same stem, .json
    in_table = False
    for line in md.read_text(encoding="utf-8").splitlines():
        if line.startswith("## "):
            in_table = line == "## Metrics"                      # inside the table?
        elif in_table and line.startswith("| ") and "---" not in line:
            cells = [c.strip() for c in line.strip("|").split(" | ")]
            if cells[0] == "Section":
                continue                                          # the header row
            num = re.match(r"[+-]?\d+(\.\d+)?", cells[2])        # "32.9 cm / 13.0 in"
            rows.append({"file": receipt["input"], "metric": cells[1],
                         "value": float(num.group()) if num else None,
                         "rating": cells[3], "fps": receipt["actualCaptureFps"],
                         "warnings": len(receipt["warnings"])})
df = pd.DataFrame(rows)
print(df.shape)
h = df[df.metric == "Jump Height"].set_index("file")["value"]
print(h.to_string())
print(round(h.mean(), 1))                   # mean jump height, cm, all seven files
```

```text
(119, 6)
file
jump_wk1_t1.mp4    31.2
jump_wk1_t2.mp4    29.8
jump_wk1_t3.mp4    32.1
jump_wk3_t1.mp4    33.5
jump_wk3_t2.mp4    34.1
jump_wk3_t3.mp4    32.9
jump_wk3_t4.mp4    33.8
32.5
```

The mean of 32.5 cm mixes two weeks and includes a clip analyzed at the wrong rate.
The receipts can catch that clip, but only against a record you kept: the rate each
clip was filmed at. Listing 4.22 checks each receipt
against that log before comparing the weeks.

**Listing 4.22.** Check the receipts against the session log, then compare weeks (`code/l14_receipts.py`)

```python
# check each receipt against the session log, then compare weeks
import json, pathlib, re
import pandas as pd

LOG_FPS = {"wk1": 30, "wk3": 120}          # what the camera recorded, from the log sheet
rows = []
for js in sorted(pathlib.Path("data/results").glob("results_*.json")):
    r = json.loads(js.read_text())
    md = js.with_suffix(".md").read_text(encoding="utf-8")
    height = re.search(r"^\| Jump Outcome \| Jump Height \| ([\d.]+) cm", md, re.M)
    week = r["input"].split("_")[1]
    rows.append({"file": r["input"], "week": week, "fps": r["actualCaptureFps"],
                 "ok": r["actualCaptureFps"] == LOG_FPS[week],
                 "height_cm": float(height.group(1))})
df = pd.DataFrame(rows)
print(df.to_string(index=False))
good = df[df.ok].groupby("week")["height_cm"].mean()
print(round(good["wk3"] - good["wk1"], 1))   # change in mean height, cm
```

```text
           file week  fps    ok  height_cm
jump_wk1_t1.mp4  wk1   30  True       31.2
jump_wk1_t2.mp4  wk1   30  True       29.8
jump_wk1_t3.mp4  wk1   30  True       32.1
jump_wk3_t1.mp4  wk3  120  True       33.5
jump_wk3_t2.mp4  wk3  120  True       34.1
jump_wk3_t3.mp4  wk3   30 False       32.9
jump_wk3_t4.mp4  wk3  120  True       33.8
2.8
```

The week-3 mean is 2.8 cm above week 1. Notice what the wrong clip
did and did not spoil. Its jump height, 32.9 cm, is plausible, because the jump app
scales height from pixels and the athlete's stature, not from time. Its flight
time, 2.07 s, is impossible, so the app withheld it and every other time
and speed. An earlier version withheld only the flight time and still printed and
rated an amortization of 468 ms and a concentric time of about a second, four times
too long; checking the files against the session log exposed that, and the app now
drops them all. The app can catch a wrong rate only when the flight comes out
impossible, though. A 0.5 s jump filmed at 60 fps and read at
30 fps becomes a believable 1.0 s flight, below the app's
1.1 s limit, and every time in the file is then doubled without a
warning. The safe rule is the one in the listing: a clip whose capture rate does not
match the log is excluded entirely.

> **Key idea.**
> 
> A results file says what the app measured under the settings it was given. Whether
> those settings were right is something only your session log can say. Keep one:
> date, clip name, frame rate filmed at, camera view, athlete height.

## 4.9 Coding with an Assistant

Every listing in this chapter could have been written by an AI assistant in seconds.
The listings are short so that you can read them, because the assistant is not
responsible for the numbers you hand to an athlete; you are. The four-step method
makes that responsibility practical.

*Table 4.5. Specify, generate, verify, defend.*

| Step | What you do |
|---|---|
| Specify | Write what the code must do: the input file and its columns, the output, the units, the rules, and one test with an answer you computed by hand. |
| Generate | Give the specification to the assistant. Paste column names and a few invented rows, never the athlete's data. |
| Verify | Run your test. Read every line and say what it does. Check one result a second way: by hand, with an app, or with a different library. |
| Defend | Be ready to explain any line a reviewer points to, and to say what the code does with an empty file, a missing value or a duplicated row. |

A specification for Listing 4.13 might read:

Write a Python function `moving_average(x, n=5)` that returns a centered
\(n\)-point moving average of the list `x`, as a NumPy array of the same
length. Positions without \((n-1)/2\) neighbors on both sides are NaN, not computed
from fewer points. Test: for
120, 122, 125, 124, 128, 130, 129, 133, 135, 134 the output at positions 3, 4 and 8
(counting from 1) is 123.8, 125.8 and 132.2, and positions 1 and 10 are NaN.

The test is the part you write yourself, from Example 4.5. A
common first answer from an assistant uses `np.convolve(..., mode="same")`,
which looks right and passes a quick glance. Listing 4.23
runs the test on it.

**Listing 4.23.** A test from a hand calculation catches a plausible error (`code/l15_test.py`)

```python
# a test written from the hand calculation, run on the assistant's code
import numpy as np

def moving_average(x, n=5):                 # as the assistant first wrote it
    return np.convolve(x, np.ones(n) / n, mode="same")

HR = [120, 122, 125, 124, 128, 130, 129, 133, 135, 134]
HAND = {3: 123.8, 4: 125.8, 8: 132.2}       # sample (from 1): hand answer

def test_moving_average(f):
    y = f(np.array(HR, dtype=float))
    for k, v in HAND.items():
        assert abs(y[k - 1] - v) < 0.05, f"sample {k}: {y[k - 1]:.1f}, hand {v}"
    assert np.isnan(y[0]), f"sample 1 should be empty, got {y[0]:.1f}"
    assert np.isnan(y[-1]), f"sample 10 should be empty, got {y[-1]:.1f}"

try:
    test_moving_average(moving_average)
except AssertionError as e:
    print("FAILED:", e)
y = moving_average(np.array(HR, dtype=float))
print(round(y[0], 1))                       # what the code put at sample 1
```

```text
FAILED: sample 1 should be empty, got 73.4
73.4
```

The middle values are right; the ends are not. `mode="same"` pads the data
with zeros, so sample 1 becomes \((0+0+120+122+125)/5=73.4\). On a heart-rate trace
that is a plunge to 73 bpm at the start and end of every file: the kind of
error that a chart shows as “a fast recovery” and a reader believes. The test
caught it because it checked the edges, which is where code is usually wrong.

\paragraph{Reading code you did not write.} Read it line by line and, for each line,
say in words what it does to the table. Run it on five rows you can check by eye.
Then ask: what happens with an empty file? A column of text where numbers were
expected? A time stamp with no zone? The questions in
Section 4.3 are the edge cases most worth testing.

\paragraph{The prompt log.} Keep, with every notebook, a log of what you asked the
assistant, what it gave, and what you changed and why. One line each is enough:
2027-01-16. Asked for a cross-correlation offset finder (spec in cell 3). First
version did not remove the means; every shift gave 0.99. Added mean removal, test
with a 7 s synthetic shift now passes.

The log is how a reviewer, or you in a month, can tell which choices were yours.

> **Check the AI: An offset that is too good.**
> 
> An assistant reports: “The watch and strap agree perfectly: the correlation is 0.98
> at every shift from \(-30\) to \(+30\) s, so there is no clock offset.” What is
> wrong? A correlation that does not change with the shift means the code compared
> something that does not depend on the shift, most often the raw levels without the
> means removed, or the same column twice. Equation \eqref{ch04-python:eq:xcorr} and
> the single sharp peak of Figure 4.2 are what a working
> version gives.

## 4.10 Telling the Athlete

The athlete who wore the two devices asks: “Can I trust my watch for intervals?”
Compare two answers.

*Poor:* “After UTC normalization and a cross-correlation-derived 7 s offset
correction, Bland–Altman analysis gives a bias of 0.97 bpm with 95% limits of
agreement of \(-4.1\) to \(+6.0\) bpm (n = 974).”

*Better:* “Yes, for this session. Once we lined up the two clocks, which were
7 seconds apart, your watch read about 1 beat a minute higher than the chest strap,
and almost always within 4 to 6 beats of it. That is close enough to use for
interval targets. Two cautions: this was one session, and wrist readings can be
worse in some sports, so check it once more on a bike ride before relying on it there.”

The better answer answers the question asked, puts the numbers in units the athlete
uses, states the size of the uncertainty, gives one action, and stays within scope:
it judges a device, not the athlete's heart.

## 4.11 Build Step B-4: A CSV File on a Canvas

This week's step adds a page that loads a CSV file and draws one column as a line.
The file is read in the browser and never uploaded. The module in
Listing 4.24 has two functions: one splits the text into a
header and rows, the other scales the values to the canvas and draws them, leaving
a gap where a value is missing rather than drawing a line through it. The page
`code/b4/index.html` adds a file input and a column menu.

**Listing 4.24.** The B-4 module, `csv-chart.js` (`code/b4/csv-chart.js`)

```javascript
// Build step B-4: load a CSV file in the page and draw one column on a canvas.
export function parseCsv(text) {
  const lines = text.trim().split(/\r?\n/);
  const header = lines[0].split(",");
  const rows = lines.slice(1).map((l) => l.split(","));
  return { header, rows };
}
export function drawLine(canvas, ys) {
  const g = canvas.getContext("2d"), w = canvas.width, h = canvas.height, pad = 30;
  const good = ys.filter(Number.isFinite);
  const lo = Math.min(...good), hi = Math.max(...good);
  g.clearRect(0, 0, w, h);
  g.beginPath();
  let penDown = false;
  ys.forEach((y, i) => {
    if (!Number.isFinite(y)) { penDown = false; return; }   // a gap, not invented data
    const px = pad + (i / (ys.length - 1)) * (w - 2 * pad);
    const py = h - pad - ((y - lo) / (hi - lo || 1)) * (h - 2 * pad);
    penDown ? g.lineTo(px, py) : g.moveTo(px, py);
    penDown = true;
  });
  g.stroke();
  g.fillText(`${lo} to ${hi}`, 4, 12);                    // the range, so the scale is honest
}
```

The test with a known answer: load `strap_hr.csv`; the page must find
1500 rows and a peak of 174 bpm, the same as `len(strap)` and
`strap.hr_bpm.max()` in pandas. The file `code/b4/test-parse.mjs`
runs that check without a browser.

## Summary

- End every analysis in a number you can predict, and check it. Restart and run
  all before sharing; print versions, fix the seed, test functions on known cases.

- Arrays do arithmetic on whole columns; a loop gives the same answer, slower.

- Keep data tidy: one variable per column, one observation per row. Describe
  every field in a data dictionary: meaning, unit, type, range, missing-value code.

- Convert every time stamp to UTC with a named zone; a time with no zone is a
  question, not an answer. Compute the sample rate from the time stamps.

- Write cleaning rules, with numbers and units, before looking. Mark bad values;
  do not silently delete them. Remove spikes before averaging. Never edit the raw
  file; write a cleaned copy and a change log with counts.

- Resample to a common grid, fill only short gaps, and find a clock offset by
  cross-correlation; check it by eye on one sharp feature. After every join, predict
  the rows, state the relation with `validate=`, count unmatched rows.

- Every smoothing filter trades noise for lag; a two-pass filter on a recorded file
  has none. Differentiating multiplies noise by \(\sqrt2/\Delta t\) for a speed.

- Describe agreement with a bias and limits of agreement, not a correlation.

- A chart makes one point: title as the finding, every value shown, zero on a
  length axis, labels with units, no meaning carried by color alone. Show a
  distribution with a histogram before a box plot; avoid truncated bar axes, dual
  axes and overplotting; caption the observation apart from the explanation.

- The apps write `results_<video>.md` (the measurements) and
  `.json` (the settings that produced them); check the settings against
  your log before using the measurements.

- With an AI assistant: specify, generate, verify, defend, and keep a prompt log.

| Quantity | Formula |
|---|---|
| Sample rate | $f_s=1/\operatorname{median}(\Delta t)$ |
| Nyquist frequency | $f_s/2$ |
| Centered $N$ -point moving average | $\bar x_i=\frac1N\sum_{j=-(N-1)/2}^{(N-1)/2}x_{i+j}$ |
| Lag of a trailing $N$ -point average on a ramp | $(N-1)/2$ samples |
| Noise of a first difference | $\sigma_v=\sqrt2\,\sigma/\Delta t$ |
| Noise of a second difference | $\sigma_a=\sqrt6\,\sigma/\Delta t^2$ |
| Limits of agreement | bias $\pm1.96\,\mathrm{SD}$ of the differences |
| Inches to centimeters | $\times2.54$ (exact) |
| Pace (s/km) | $t/(d/1000)$ , $t$ in s, $d$ in m |
| Rows after a left many-to-one join | rows of the left table, if keys are unique |

**New terms:** tidy data, time series, UTC, naive time, sample rate,
Nyquist frequency, aliasing, cleaning, Hampel filter, resampling, interpolation,
cross-correlation, moving average, median filter, trailing window, lag, low-pass
filter, cut-off frequency, bias, limits of agreement, agreement plot, typical error,
receipt, process-a-folder page, specify–generate–verify–defend, prompt log,
hidden state, reproducibility, list, index, slice, array, vectorizing, data
dictionary, missing-value code, provenance, change log, key, join, many-to-one join,
distribution, histogram, box plot, observation, explanation.

**Going further:** https://apmonitor.com/pds/index.php/Main/GatherData, https://apmonitor.com/pds/index.php/Main/StatisticsMath,
https://apmonitor.com/pds/index.php/Main/VisualizeData and https://apmonitor.com/pds/index.php/Main/CleanseData cover loading, summarizing, plotting and
cleaning data in the same style; https://apmonitor.com/dde/index.php/Main/PandasTimeSeries covers joining and
resampling time-indexed tables; https://apmonitor.com/dde/index.php/Main/SmartphoneSensors shows how to log a phone's
motion sensors to CSV and load them.

**Track it:** `cmj` rows converted from the results files by script, not retyped (Appendix J).

## Exercises

> **Course use: Week 4.**
> 
> **H08** (due Class 8, *Measure*): 4.1, 4.2, 4.5, 4.12, 4.14; about 65 minutes.
> 
> **H09** (due Class 9, *Model and tell*): 4.8, 4.19, 4.20, 4.21, 4.28, 4.33; about 170 minutes. A case-file exercise may be done on your own data instead. The full map is in the Course Guide.

**Exercise 4.1** (Concept check · Foundation · 2 min · CORE)

A watch file has the time stamp `2027-03-02 07:15:00` and no zone. Which
statement is right?
\choices{It is UTC, because files store UTC unless told otherwise}
{It cannot be placed on a common time line until you know where, and on which date, the watch was set}
{It is the local time of the computer that opens the file}
{It can be compared directly with a chest-strap file written in UTC}

**Exercise 4.2** (Concept check · Core · 2 min · CORE)

You smooth a live heart-rate display with a trailing 9-point moving average of
one value a second. On a steady rise, how late is the display?
\choices{0 s, because averaging removes only noise}
{1 s}
{9 s}
{4 s}

**Exercise 4.3** (Concept check · Foundation · 2 min)

Two heart-rate devices give a correlation of 0.99 over a session. What does that
show?
\choices{That they rise and fall together; it says nothing about whether one reads higher than the other}
{That they agree to within about 1%}
{That either device can replace the other}
{That the clock offset between them is zero}

**Exercise 4.4** (Concept check · Core · 2 min)

A 120 fps slow-motion jump clip, stored with a 30 fps header, is processed with the
capture rate left on “auto”. Which results in its Markdown file stay trustworthy?
\choices{All of them, because the app warns about the frame rate}
{Only the ratings, because they are relative}
{Jump height and countermovement depth, which the jump app scales from pixels, but not times or speeds}
{Only the flight time, because the app corrects it}

**Exercise 4.5** (Hand calculation · Foundation · 10 min · CORE)

A GPS watch gives ten speeds, one a second, in m/s:
\(3.2, 3.4, 3.3, 3.5, 3.6, 3.4, 3.7, 3.8, 3.6, 3.9\).

- Compute the centered five-point moving average at samples 3 to 8.
  *Checkpoint:* {3.40 at sample 3; 3.68 at sample 8.}

- The satellite fix jumps and sample 5 reads 9.6 instead of 3.6. Recompute the
  average at sample 5 and the five-point median at sample 5.
  *Checkpoint:* {average 4.70; median 3.50.}

- A live display uses a trailing three-point average at 10 samples a second. How
  late is it on a steady rise, in samples and in seconds?
  *Checkpoint:* {1 sample, 0.1 s.}

- Confirm (a) and (b) by changing the data in Listing 4.13.

**Exercise 4.6** (Hand calculation · Core · 10 min)

A pose model places the hip with random noise of \(\sigma=3 mm\) in
each frame.

- Compute the noise in a speed from two neighboring frames at 60 fps.
  *Checkpoint:* {0.25 m/s.}

- Repeat at 240 fps, with the same 3 mm per frame.
  *Checkpoint:* {1.02 m/s.}

- Compute the noise in an acceleration from three frames at 60 fps.
  *Checkpoint:* {26.5 m/s².}

- A faster camera gave a noisier speed. Explain why, and name two ways to use the
  extra frames well.

**Exercise 4.7** (Hand calculation · Core · 8 min)

A chest strap writes `05:58:41Z` at the moment you press a lap button. A watch
worn in a zone two hours ahead of UTC records the same press at local time 07:58:30.

- Convert the watch time to UTC. *Checkpoint:* {05:58:30.}

- Is the watch clock fast or slow, and by how much? *Checkpoint:* {slow, 11 s.}

- A phone log has time stamps (ms) 0, 9, 21, 30, 40, 50, 61, 70, 80, 89. Find the
  sample rate from the median spacing, and the Nyquist frequency.
  *Checkpoint:* {100 Hz; 50 Hz.}

**Exercise 4.8** (Python analysis · Foundation · 20 min · CORE)

The course module https://apmonitor.com/dde/index.php/Main/SmartphoneSensors publishes a real phone accelerometer
file, https://apmonitor.com/dde/uploads/Main/Accelerometer.csv. Download it
in a browser and upload it to your notebook (some servers refuse requests from
notebook code). With an assistant, write a cell that prints:

- the number of rows and the column names, in the order they appear;

- the median time between samples in ms and the sample rate in Hz;

- the recording's length in seconds and its start time in UTC;

- the mean of \(\sqrt{x^2+y^2+z^2}\).

Then explain what (d) tells you about the file, given that a phone at rest feels
9.81 m/s² of gravity.

**Exercise 4.9** (Python analysis · Core · 20 min)

Change Listing 4.17 so that it does *not* subtract the
7 s offset, and run it.

- Report the bias, the SD and the limits of agreement.

- By what factor did the correction narrow the limits?

- Explain why the bias hardly changed while the SD grew.

**Exercise 4.10** (Python analysis · Extension · 20 min)

The spike rule of Listing 4.8 uses a threshold of
5 m/s² from the five-point median. Run it with
thresholds of 5, 2 and 1 m/s\(^2\) (keep the duplicate removal) and report how many
samples each flags. Which threshold would you write in `RULES` before seeing
the data, and why? What should you do now that you *have* seen the counts?

**Exercise 4.11** (Python analysis · Extension · 30 min)

Give an AI assistant the seven `.md` files in `data/results` (not the
`.json` receipts) and ask for a five-line summary of the athlete's progress for
a coach. Then check its summary line by line against the files and against
Listing 4.22. Write down each claim, the file and line that
supports or contradicts it, and your corrected summary.

**Exercise 4.12** (App lab · Core · 20 min · CORE)

Analyze yourself with the jump app's process-a-folder page (https://apopt.com/jump/automation.html),
following the five-step pattern of the book.

- Film three countermovement jumps from the side, phone on a tripod at waist
  height, whole body in frame from setup to landing, one clip per jump of about 4–6 s,
  at 60 fps or more (or slow motion, noting the rate). Put the clips in one folder.

- Run the folder page with your height and the recorded frame rate. Keep the
  `.md`, `.json` and PDF files.

- Load the three Markdown files with Listing 4.21. Check
  that `actualCaptureFps` in each receipt equals the rate you filmed at.
  Confirm one jump's flight-time height (the “cm derived” figure in the Flight
  Time row, not the headline jump height, which is the hips' rise from standing) by
  hand from its flight time, \(h=g t^2/8\) (Chapter 3).

- Open one clip in the single-video app in Advanced mode and find one metric the
  Markdown summary did not stress.

- Write half a page: what you measured, the mean and range of the three heights,
  how sure you are, what you would change, when you would retest.

**Exercise 4.13** (App lab · Extension · 25 min)

Process one slow-motion jump clip twice with the jump app's folder page: once with
the capture rate on “auto” and once with the rate the camera recorded at (rename a
copy of the clip so both sets of results can sit in one folder). Load both Markdown
files into one table and list, for every metric, the ratio of the two values. Sort
the metrics into those that do not change, those that change by the frame-rate ratio,
and those that the app refused. Which receipt field would let a program catch the
mistake without a session log, and when would it fail?

**Exercise 4.14** (Field collection · Foundation · 30 min · CORE)

Record a walk with your phone's motion sensors and find your cadence.

- Install a free sensor-logging app that exports CSV. Set the accelerometer to
  50–100 Hz and record raw acceleration (including gravity) if the app offers both.

- Equipment: the phone, a pocket or armband, a stopwatch, a straight path or
  track of at least 100 m with no traffic.

- Safety: walk at a comfortable pace on a clear path; stop if you feel unwell.
  If a classmate walks instead of you, get their written consent first (Appendix E;
  under 18, a parent or guardian's consent and their own assent) and let them keep
  their own file.

- Stand still 5 s, walk 60 s at a steady pace, stand still 5 s. While walking,
  have a partner count your steps for the middle 30 s.

- Export the CSV and record: phone model kept private, pocket used, sample rate
  requested, the hand count.

- In a notebook, find the real sample rate (Listing 4.6)
  and the cadence (Listing 4.16, adjusting the column name
  and peak height to your file). Compare with twice the hand count.

**Exercise 4.15** (Body science · Foundation · 5 min)

In the synthetic session, the strap's heart rate takes tens of seconds to settle
after each change of pace. In plain words, why does heart rate not jump at once
when the work rate does, and what does that mean for a coach who reads a heart-rate
target during a 30 s sprint?

**Exercise 4.16** (Body science · Core · 5 min)

A wrist heart-rate sensor shines light into the skin and measures how much returns
as blood volume pulses with each beat. During a run it sometimes reports a value
close to the runner's cadence (for example 165 a minute) instead of the heart rate.
Explain why, and name a cleaning rule from this chapter that would and one that would
not catch it.

**Exercise 4.17** (Science of the sport · Foundation · 5 min)

You want to check a watch's clock against a chest strap by cross-correlation. Which
session would you choose: a steady 40-minute easy run, or a session of 6 \(×\)
1-minute fast running with 1 minute of jogging between? Explain in terms of what the
correlation needs.

**Exercise 4.18** (Science of the sport · Extension · 8 min)

A coach wants to see whether a squad's countermovement jump improved over a
four-week block. From what you know about jumping and about measurement, list three
things, other than training, that could change the measured heights between the two
sessions, and for each, one thing to keep the same.

**Exercise 4.19** (Build · Core · 60 min · CORE)

Build step B-4. Add to your week-1 Vite project a page that loads a CSV file chosen
by the user and draws one column on a canvas, using Listing 4.24
as a model.

- The page must read the file in the browser, without uploading it.

- A menu lists the columns; choosing one redraws the chart.

- Missing values leave a gap in the line.

- Test with a known answer: with `strap_hr.csv` the page reports 1500 rows
  and a maximum of 174 in `hr_bpm`.

- Load `watch_hr.csv` and describe, in two sentences, what your chart
  shows where values are missing.

**Exercise 4.20** (Communicate · Core · 20 min · CORE)

A coach sends you a default spreadsheet chart of the squad's jump heights: a 3-D
column chart, one color per athlete, the axis starting at 25 cm, legend
“Series1–Series8”, title “Chart 1”. Using Listing 4.9's
cleaned table, redraw it so that the coach gets one point in five seconds, and write the
one-sentence caption you would send with it.

**Exercise 4.21** (Check the AI · Core · 8 min)

An assistant wrote this to put the watch on UTC before aligning it with the strap:
`watch.index = pd.to_datetime(watch["timestamp"], utc=True)`. The
cross-correlation over shifts of \(\pm30\) s then gave a flat curve with no clear
peak. Find the flaw, say what offset the two series really had with this code, and
give the corrected line.

**Exercise 4.22** (Python analysis · Foundation · 15 min)

Run Listing 4.23. Then fix the function so that the test
passes, without changing the test. Show the passing output and say in one sentence
why your version leaves the ends empty.

**Exercise 4.23** (Python analysis · Foundation · 15 min)

Extend Listing 4.2 (Section 4.1.1).

- Add a fourth known case: a marathon, 42195 m, in 3:30:00. Compute
  the pace by hand first, then write the `assert`.
  *Checkpoint:* {298.6 s a kilometer, 4:58.6/km.}

- Add a check that the function refuses a distance of zero: call it inside
  `try`, and `assert` that a `ValueError` was raised.

- Restart and run all twice. Copy the three random numbers from each run.
  *Checkpoint:* {the two runs print the same three numbers.}

- Move the line `rng = np.random.default_rng(seed=4)` below the
  `print` that uses it, restart and run all, and say what happens and why.

**Exercise 4.24** (Python analysis · Foundation · 15 min)

Write a function `speed_kmh(distance_m, time_s)` that returns speed in
kilometers an hour, and three known cases you compute by hand before you write any
code: 10 km in 50 min; one 400 m lap in 90 s; 100 m in
10 s.

- Give the three hand answers. *Checkpoint:* {12, 16 and 36 km/h.}

- Write the three `assert` lines and run them on your function.

- An assistant writes `return distance_m / 1000 / (time_s / 60)`. Which
  of your cases fail, and what unit does that version really return?

**Exercise 4.25** (Hand calculation · Foundation · 8 min)

Four 200 m repetitions take `t = [40, 38, 36, 40]` seconds.

- What are `t[1:3]` and `t[-1]`? *Checkpoint:* {\([38, 36]\); 40.}

- Compute the speed of each repetition in m/s, as `200 / np.array(t)`
  would. *Checkpoint:* {5.00, 5.26, 5.56, 5.00.}

- Compute the session speed (total distance over total time) and the mean of
  the four speeds. Which would you report, and why?
  *Checkpoint:* {5.195 and 5.205 m/s.}

- What does `t * 2` give if `t` is a list, and if it is an array?

**Exercise 4.26** (Python analysis · Foundation · 15 min)

Load `data/walk_accel.csv` and compute the magnitude
\(\sqrt{x^2+y^2+z^2}\) of every row twice: with a loop over the rows, and with one
line of array arithmetic.

- Report the number of rows and the mean magnitude (ignore missing values).
  *Checkpoint:* {2980 rows; 9.96 m/s².}

- Compare the two results with `np.allclose`. Explain the answer, and fix
  the comparison. *Checkpoint:* {`False`, then `True`.}

- Time both with `time.perf_counter()` and give the ratio.

**Exercise 4.27** (Python analysis · Core · 20 min)

Write a data dictionary (Section 4.2.5) for this chapter's
two heart-rate files, the strap's and the watch's (`strap_hr.csv` and
`watch_hr.csv` in `data/`):
for each field, its meaning, unit, type, allowed range and missing-value code. Then
adapt Listing 4.7 to check both files against it.

- Give the dictionary as a table.

- Report rows, empty cells and values outside your range for each file.
  *Checkpoint:* {strap 1500 rows, 0 empty; watch 986 rows, 12 empty; none outside
  30–220 bpm.}

- The watch's `timestamp` has no zone. What must its dictionary line say,
  and why can no check of the file itself find that out?

**Exercise 4.28** (Python analysis · Core · 20 min)

Apply provenance and a change log (Section 4.3.1) to the
synthetic watch activity table in the file `data/watch_activity.csv`. Using the dictionary of
Table 4.2, write rules that drop repeated time stamps,
mark heart rates of 0 as missing and mark speeds that are not numbers as missing.
Write the cleaned copy to a new file and the change log to another.

- Give your change log. *Checkpoint:* {2 repeated stamps dropped; 3 zero heart
  rates and 2 text speeds marked missing; 853 rows written.}

- How many heart rates are missing in the cleaned file?
  *Checkpoint:* {11.}

- Run your code twice. Show that the raw file's fingerprint did not change and
  that the two change logs are identical.

**Exercise 4.29** (App lab · Foundation · 15 min)

Process one clip of yourself with the jump app's process-a-folder page,
https://apopt.com/jump/automation.html: side view, phone on a stand at hip height, one
countermovement jump, a clip of 5 to 10 seconds, filmed at 30 fps or
60 fps (write down which). Redraw the left column of
Figure 4.9 for your clip, labeling each arrow with the
values you can read from your files.

- From the receipt: `sourceFps`, `actualCaptureFps` and
  `options.heightMeters`. From the Markdown: the *Athlete height* and
  *Frame rate* rows. *Checkpoint:* {`heightMeters` \(×100\) equals the
  height in cm in the Markdown; `actualCaptureFps` equals the rate you filmed at.}

- Read the Jump Height into a notebook as a number in a column named with its
  unit. Which arrow changed the unit, and which setting would change the number if it
  were wrong?

**Exercise 4.30** (Python analysis · Core · 20 min)

Use `data/sessions.csv` and `data/session_hr.csv`
(Section 4.4.1).

- Before running anything, predict the rows of an *inner* join of the raw
  tables, and of an *outer* join. Then run both with `indicator=True`.
  *Checkpoint:* {300 and 346.}

- The inner join has 300 rows while the strap file has 285. Account for the
  difference exactly.

- After removing the duplicate log row, join with
  `validate="many_to_one"` and compute the mean heart rate by session type.
  *Checkpoint:* {easy 127.3, intervals 149.0, tempo 157.2 bpm.}

- What happened to S06 in (c), and what would you write in the change log?

**Exercise 4.31** (Check the AI · Core · 8 min)

An assistant writes `df = hr.merge(log, on="session_id")` for the files of
Section 4.4.1 and reports: “Joined successfully: 300 rows, no
errors, every heart-rate row now has its session type.” List what is wrong with the
claim, and give the two arguments that would have exposed it.

**Exercise 4.32** (Communicate · Core · 20 min)

Draw a histogram and a box plot of the watch's heart rates in
`data/watch_hr.csv` (Section 4.7.1).

- Report the five numbers of the box plot. *Checkpoint:* {99, 112, 132, 162,
  182 bpm.}

- Write a two-sentence caption: one sentence of observation, one of explanation,
  each labeled. Say which chart you would send to the athlete, and why.

- A teammate's chart puts the watch's mean heart rate per session on a left axis
  and weekly distance on a right axis, scaled so the lines cross. Name the problem
  and describe the corrected chart in one sentence.

**Exercise 4.33** (Python analysis · Core · 40 min)

Case file: Audit your case-file athlete's watch archive (see apopt.com/data/athletes)
for data quality. Read each activity's FIT file with `fitdecode` and make a
per-second record table (time stamp, heart rate, distance, speed, cadence). Write its
data dictionary first.

- For each activity, report: start time (UTC), rows, heart rates missing (empty
  or 0) as a percentage, repeated time stamps, pauses (gaps longer than
  5 s) and total paused time. *Checkpoint:* {for a recording at one row a
  second, rows \(-\) repeated stamps \(+\) seconds missing in all gaps \(=\) elapsed
  seconds \(+1\), exactly.}

- If the median spacing is not 1 s, the watch recorded only when
  something changed. Say which activities do, and why the checkpoint in (a) does not
  apply to them.

- Write the audit as one table, with a change log of anything you excluded.

**Exercise 4.34** (Communicate · Core · 20 min)

Case file: Write a half-page data-quality note about your case-file athlete's watch
archive (see apopt.com/data/athletes) for the coach, from your audit in the previous
exercise. Include one chart (for example the share of missing heart rate per activity),
a caption that separates observation from explanation, what you will exclude and why,
and one question you need the athlete to answer.
