# CS-4: A messy watch export to a clean table

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

Web page: https://apopt.com/course/tutorials/cs04-messy-watch-export/ · Data: https://apopt.com/data/tutorials/cs04-messy-watch-export/

## The decision

A coach planning the athlete's next block asks: how much has he run in each quarter since mid-2024,
at what pace, and did anything change? The answer has to come from an export no one has checked.
If the units, the clock or the activity types were wrong, the totals could be off by a factor of a
thousand, put sessions on the wrong day, or count walks and indoor sessions with made-up distances
as runs.

## Predict first

Before any code: the first run has avg_running_cadence 86, avg_step_length 980, a timer time of 2355 s and an elapsed time of 3307 s. What units and which time would make it a plausible run?

## The raw data

- `raw/sessions_fit.csv`: 693 activity summaries, 28 June 2024 to 28 November 2026, one watch; the FIT session fields with the watch's own names and units Activity summaries from a COROS Training Hub archive of an adult male athlete in his mid-40s, published in the course case file (`athletes/jh/coros-history/`). GPS positions, per-second records and identifiers were removed before publication.
- `raw/activities_clean.csv`: the case file's own conversion of the same activities to SI units with local start times, for checking your conversion Same case file (`athletes/jh/coros-history/`).

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| activity_id | row id (local start time and sport) | text | 2024-06-28 – 2026-11-28 | never |
| start_time | start in UTC (the "Z") | ISO 8601 | 2024–2026 | never |
| utc_offset_h | local clock minus UTC at the start | h | −7 to +3 | never |
| sport / sub_sport | sport and sub-sport as the watch labels them | text | 8 sports / 7 sub-sports | sub_sport blank = none |
| total_timer_time | moving time (the timer stops on pauses) | s | 1.8 s – 8 h | never |
| total_elapsed_time | clock time from start to stop (pauses included) | s | 2.6 s – 8 h | never |
| total_distance | distance (wrist accelerometer on indoor runs) | m | 0 – 22 000 | blank or 0 on elliptical and indoor bike |
| enhanced_avg_speed / enhanced_max_speed | average (over timer time) and maximum speed | m/s | 0 – 24 | blank |
| avg_running_cadence | cadence of ONE foot on runs | strides/min (×2 for steps/min) | 0 – 96 | 0 = no reading |
| avg_cadence | cadence on other sports | pedal rpm (bike); strokes/min (swim); undefined elsewhere | 0 – 146 | 0 = no sensor |
| total_strides | strides of one foot | count | 0 – 9 500 | blank on non-running sports |
| avg_step_length | distance per step | mm | 0 – 2 490 | 0 = no reading |
| avg_stance_time | ground-contact time | ms | 0 – 329 | 0 = not estimated |
| avg_vertical_oscillation | vertical bounce of the torso | mm | 0 – 96 | 0 = not estimated |
| avg_vertical_ratio | oscillation ÷ step length | % | 0 – 12.6 | 0 = not estimated |
| avg_power | running power the watch estimates | W | 0 – 225 | 0 = not estimated |
| avg_heart_rate / max_heart_rate | heart rate (optical at the wrist) | beats/min | 67 – 209 | blank (weak on swims) |
| total_ascent | climb (barometer) | m | 0 – 1 185 | blank |
| total_calories | energy estimate | kcal | 0 – 1 700 | never |

What is wrong with it: no units in the file, and three of them are unusual (step length and
vertical oscillation in millimeters, running cadence counting one foot); one column, `avg_cadence`,
that means pedal rpm, swim strokes or something undefined depending on the sport; two durations, of
which only the timer gives the right pace; a UTC start with a separate offset, which changes on
trips; 0 used as "not measured" for stance time, oscillation, vertical ratio, power and cadence;
no distance on the elliptical and the indoor bike; indoor runs whose distance and cadence come from
the wrist; walks saved as runs; aborted starts of a few meters; a few single-sample speed spikes.

### Step 1 · Gather: the export as the watch wrote it

An adult male athlete in his mid-40s asked his watch maker's website for his data and got back
one FIT file per activity. The course case file keeps one row per file: the watch's own
**session** fields (the summary the watch writes when you press stop), with the watch's own names
and units, from one watch over two and a half years. GPS positions and per-second records were
removed. A coach wants one thing from it: a quarter-by-quarter summary of the running that can be
trusted.

*Predict first:* Will every activity have the same fields filled in?

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

raw = pd.read_csv("raw/sessions_fit.csv")
print(f"{len(raw)} activities, {raw.shape[1]} fields, {raw['start_time'].min()[:10]} to {raw['start_time'].max()[:10]}")
print(raw.groupby(["sport", raw["sub_sport"].fillna("-")]).size().to_string())
filled = raw.notna().sum().sort_values()
print("activities with each field (fewest first):", filled.head(9).to_dict())
print(raw.iloc[0].dropna().to_dict())
```

Output:

```
693 activities, 29 fields, 2024-06-28 to 2026-11-28
sport              sub_sport        
cycling            indoor_cycling        14
                   road                   5
fitness_equipment  elliptical            73
generic            -                     13
hiking             -                     13
running            -                    475
                   indoor_running        21
                   track                  1
swimming           -                      1
                   lap_swimming          66
training           strength_training      1
walking            -                     10
activities with each field (fewest first): {'num_active_lengths': 0, 'pool_length': 66, 'sub_sport': 181, 'avg_cadence': 195, 'Effort Pace': 473, 'avg_running_cadence': 497, 'max_running_cadence': 497, 'total_strides': 507, 'total_distance': 603}
{'activity_id': '2024-06-28_0719_running', 'start_time': '2024-06-28T13:19:52Z', 'utc_offset_h': -6.0, 'sport': 'running', 'total_timer_time': 2355.33, 'total_elapsed_time': 3306.93, 'total_distance': 6663.45, 'enhanced_avg_speed': 2.829, 'enhanced_max_speed': 3.861, 'avg_heart_rate': 168.0, 'max_heart_rate': 185.0, 'min_heart_rate': 106.0, 'avg_running_cadence': 86.0, 'max_running_cadence': 105.0, 'total_strides': 3309.0, 'avg_step_length': 980.0, 'avg_stance_time': 0.0, 'avg_vertical_oscillation': 0.0, 'avg_vertical_ratio': 0.0, 'avg_power': 118.0, 'total_ascent': 48.0, 'total_descent': 45.0, 'total_calories': 253, 'Effort Pace': 2.8980000019073486}
```

Eight sports, and fields that come and go with them: running cadence only on runs, pool length
only on some swims, a distance on 603 of 693 activities. The first run has
`avg_running_cadence` 86 and `avg_step_length` 980. Eighty-six steps a minute is a slow walk,
and 980 m is not a step. Nothing in the file says what the units are.

### Step 2 · Statistics: a unit audit

Do not guess units from one value. Use **identities** that must hold whatever the units: speed ×
time = distance; distance ÷ steps = step length; strides ÷ minutes = cadence; cadence × step
length = speed. Each one tests a unit hypothesis against the whole file at once. A **stride** is
one full cycle of one foot, so one stride is two steps.

*Predict first:* Speed is in m/s and distance in m. Which time, timer or elapsed, makes speed × time = distance hold?

```python
run = raw[(raw["sport"] == "running") & (raw["total_distance"] > 200)]
v, d = run["enhanced_avg_speed"], run["total_distance"]
checks = {
    "speed x timer / distance": v * run["total_timer_time"] / d,
    "speed x elapsed / distance": v * run["total_elapsed_time"] / d,
    "distance (mm) / (2 x strides) / step_length": 1000 * d / (2 * run["total_strides"]) / run["avg_step_length"],
    "strides per timer minute / running_cadence": run["total_strides"] / (run["total_timer_time"] / 60) / run["avg_running_cadence"],
    "2 x cadence x step (mm) / 60000 / speed": 2 * run["avg_running_cadence"] * run["avg_step_length"] / 60000 / v,
}
for name, ratio in checks.items():
    near = (ratio / ratio.median() - 1).abs() < 0.02
    print(f"{name:45s} median {ratio.median():.3f}; within 2% of it: {near.mean():.0%}")
ok = run["avg_vertical_ratio"] > 0
vr = run["avg_vertical_oscillation"] / run["avg_step_length"] * 100 / run["avg_vertical_ratio"]
print(f"{'oscillation / step x 100 / vertical_ratio':45s} median {vr[ok].median():.2f} ({ok.sum()} runs with a value)")
```

Output:

```
speed x timer / distance                      median 1.000; within 2% of it: 100%
speed x elapsed / distance                    median 1.308; within 2% of it: 4%
distance (mm) / (2 x strides) / step_length   median 0.998; within 2% of it: 86%
strides per timer minute / running_cadence    median 1.005; within 2% of it: 88%
2 x cadence x step (mm) / 60000 / speed       median 0.997; within 2% of it: 99%
oscillation / step x 100 / vertical_ratio     median 0.96 (179 runs with a value)
```

Speed × **timer** time gives the distance for every run; speed × **elapsed** time overshoots by
about 31%. The timer stops when the watch pauses (traffic lights, a water stop) and elapsed time
does not, so pace and moving time must come from the timer. Distance in millimeters ÷ twice the
strides matches `avg_step_length` (median ratio 0.998), so step length is in **millimeters** (980
is 0.98 m). Strides per timer minute match `avg_running_cadence` (1.005), so that cadence counts
**one foot**: double it for steps a minute (86 is 172). Twice the cadence times the step length
gives the speed for 99% of runs, which ties the three together. Vertical oscillation ÷ step length
comes out at 0.96 of the vertical ratio, so oscillation is in millimeters too.

Not every ratio sits within 2% for every run, and it does not need to. The file rounds step length
to 10 mm and cadence to whole strides. The wrong units would miss by far more: centimeters by a
factor of 10, steps instead of strides by a factor of 2. A median of 0.998 rules them out.

Three more traps do not show up in a runner's identities: a field whose meaning changes with the
sport, zeros that mean "no value", and a clock.

```python
kind = raw["sub_sport"].fillna(raw["sport"])
print("median avg_cadence by kind:", raw.groupby(kind)["avg_cadence"].median().dropna().to_dict())
print("distance blank or 0:", kind[raw["total_distance"].fillna(0) == 0].value_counts().to_dict())
runs_all = raw[raw["sport"] == "running"]
zero = runs_all[["avg_stance_time", "avg_vertical_oscillation", "avg_vertical_ratio", "avg_power"]] == 0
print(f"running activities with 0 (of {len(runs_all)}):", zero.sum().to_dict())
lag = runs_all["total_elapsed_time"] / runs_all["total_timer_time"]
print(f"elapsed / timer on runs: median {lag.median():.2f}; over 1.05 in {(lag > 1.05).sum()} runs")
utc = pd.to_datetime(raw["start_time"]).dt.tz_localize(None)
local = utc + pd.to_timedelta(raw["utc_offset_h"], unit="h")
print("utc_offset_h:", raw["utc_offset_h"].value_counts().to_dict())
away = ~raw["utc_offset_h"].isin([-6, -7])
print("away from -6/-7, by month:", local[away].dt.strftime("%Y-%m").value_counts().sort_index().to_dict())
print(f"activities whose UTC date is not the local date: {(utc.dt.date != local.dt.date).sum()}")
```

Output:

```
median avg_cadence by kind: {'elliptical': 57.0, 'generic': 89.0, 'hiking': 52.0, 'indoor_cycling': 0.0, 'lap_swimming': 29.0, 'road': 0.0, 'swimming': 27.0, 'walking': 50.0}
distance blank or 0: {'elliptical': 73, 'indoor_cycling': 14, 'running': 2, 'lap_swimming': 1, 'strength_training': 1}
running activities with 0 (of 497): {'avg_stance_time': 316, 'avg_vertical_oscillation': 316, 'avg_vertical_ratio': 316, 'avg_power': 23}
elapsed / timer on runs: median 1.30; over 1.05 in 376 runs
utc_offset_h: {-6.0: 465, -7.0: 191, 3.0: 16, -4.0: 14, -5.0: 7}
away from -6/-7, by month: {'2024-12': 2, '2025-03': 7, '2025-04': 7, '2025-12': 5, '2026-02': 14, '2026-03': 2}
activities whose UTC date is not the local date: 72
```

`avg_cadence` is one column with at least four meanings: pedal revolutions a minute on a bike
(where 0 means no cadence sensor), strokes a minute in the pool, most likely strides of one foot on
a walk or a hike, and a rhythm the file does not define on the elliptical. It must never be
averaged across sports. The elliptical and indoor-bike sessions have no distance at all: a sum of
distance that treats them as 0 km is right, and a mean that does is wrong.

On 316 of 497 running activities the ground-contact time (stance time), vertical oscillation and
vertical ratio are **0**, and power is 0 on 23. Nobody runs with zero bounce: 0 is the watch's code
for "not estimated", and a mean that keeps those zeros lands far below the true value. Elapsed time
is a median 1.30 times the timer on runs, and more than 5% longer on 376 of them.

The start is in UTC (the "Z"), and `utc_offset_h` says how far the wall clock was from it. Most
rows are −6 or −7 (US Mountain time, summer and winter), but the watch also logged trips at −5,
−4 and +3. A date taken from UTC puts 72 activities on the wrong date, and one fixed home
time zone would put every trip in the wrong hour. The local start is UTC plus the row's own offset.

### Step 3 · Visualize: what is labelled running?

Convert every field with the units the audit found, then plot each running activity's pace
against its cadence. Runs should cluster; anything else will stand apart.

```python
import matplotlib.pyplot as plt

is_bike, is_swim = raw["sport"] == "cycling", raw["sport"] == "swimming"
conv = pd.DataFrame({
    "activity_id": raw["activity_id"], "start_local": local, "utc_offset_h": raw["utc_offset_h"],
    "sport": raw["sport"], "sub_sport": raw["sub_sport"], "distance_km": raw["total_distance"] / 1000,
    "moving_min": raw["total_timer_time"] / 60, "elapsed_min": raw["total_elapsed_time"] / 60,
    "cadence_spm": 2 * raw["avg_running_cadence"], "step_m": raw["avg_step_length"] / 1000,
    "stance_ms": raw["avg_stance_time"], "vert_osc_mm": raw["avg_vertical_oscillation"],
    "vert_ratio_pct": raw["avg_vertical_ratio"], "power_w": raw["avg_power"],
    "pedal_rpm": raw["avg_cadence"].where(is_bike), "strokes_per_min": raw["avg_cadence"].where(is_swim),
    "max_speed_mps": raw["enhanced_max_speed"], "avg_hr_bpm": raw["avg_heart_rate"],
    "max_hr_bpm": raw["max_heart_rate"], "ascent_m": raw["total_ascent"], "energy_kcal": raw["total_calories"]})
conv["pace_min_km"] = conv["moving_min"] / conv["distance_km"].where(conv["distance_km"] > 0.2)
print(conv.loc[conv["sport"] == "running", ["distance_km", "moving_min", "pace_min_km", "cadence_spm", "step_m", "max_speed_mps"]].describe().loc[["50%", "min", "max"]].round(2).to_string())
```

Output:

```
     distance_km  moving_min  pace_min_km  cadence_spm  step_m  max_speed_mps
50%          8.9       47.64         5.24        176.0    1.08           5.59
min          0.0        0.04         3.11          0.0    0.00           0.00
max         16.1      130.43        37.05        192.0    2.49          23.81
```

*Predict first:* Where will the 21 indoor runs fall on this plot?

```python
fig, ax = plt.subplots(figsize=(6.4, 4))
for sub, mk, lab in [(None, "o", "outdoor"), ("indoor_running", "^", "indoor"), ("track", "s", "track")]:
    m = (conv["sport"] == "running") & (conv["sub_sport"].isna() if sub is None else conv["sub_sport"] == sub)
    ax.plot(conv.loc[m, "cadence_spm"], conv.loc[m, "pace_min_km"], mk, ms=4 if sub is None else 7,
            color="k", mfc="k" if sub is None else "white", alpha=0.5 if sub is None else 1, label=lab)
ax.set(xlabel="cadence (steps/min)", ylabel="pace (min/km, log scale)", yscale="log")
ax.set_yticks([3, 4, 5, 7, 10, 15, 20, 30, 50], labels=["3", "4", "5", "7", "10", "15", "20", "30", "50"])
ax.minorticks_off()
ax.legend(loc="upper right")
plt.tight_layout()
groups = conv[conv["sport"] == "running"].groupby(conv["sub_sport"].fillna("outdoor"))
print(groups[["cadence_spm", "pace_min_km", "avg_hr_bpm"]].median().round(1).to_string())
print("indoor runs with cadence of 150 or more:", (groups.get_group("indoor_running")["cadence_spm"] >= 150).sum())
```

Output:

```
                cadence_spm  pace_min_km  avg_hr_bpm
sub_sport                                           
indoor_running         92.0         14.0       153.0
outdoor               176.0          5.2       157.0
track                 168.0          4.4       157.0
indoor runs with cadence of 150 or more: 6
```

![Scatter of pace in minutes per kilometer (log scale, 3 to 50) against cadence in steps per minute (35 to 195) for every activity labelled running. Outdoor runs (gray dots) cluster at 165 to 185 steps a minute and 4.5 to 6 minutes per kilometer, with a few fast short efforts near 3 to 4 minutes; a small group of outdoor activities sits at 84 to 140 steps a minute and 7 to 14 minutes per kilometer. Most indoor runs (open triangles) scatter at 36 to 132 steps a minute and 9 to 37 minutes per kilometer, far from the cluster; six sit inside it. The one track session (open square) sits at the edge of the cluster.](https://apopt.com/course/tutorials/cs04-messy-watch-export/c08-1.png)

Most running activities form one tight cluster: about 176 steps a minute at 4.5 to 6 minutes a
kilometer. Two groups stand apart. A few outdoor activities move at 84 to 140 steps a minute and 7
to 14 minutes a kilometer: that is walking cadence, so these are walks saved as runs. Pace alone
would not find them, because a run up a mountain can be just as slow; cadence can. And 15
of the 21 **indoor** runs scatter far from the rest, at 36 to 132 steps a minute and paces as slow
as 37 minutes a kilometer. Indoors there is no GPS, and the watch takes distance and cadence from
its wrist accelerometer. Their median heart rate (153 beats a minute) says the work was real; their
distances and cadences cannot be trusted. The other 6 indoor runs land in the cluster, but their
distance still comes from the wrist, not from GPS. Last, the table's extremes: a run of 0 m and a
few seconds (an aborted start), a step of 2.49 m (an indoor run), and a maximum speed of 23.81 m/s
(86 km/h, one bad GPS sample).

### Step 4 · Cleanse: rules first, a change log, a clean copy

The rules, written before they are applied (Section 4.3). None deletes a row; each assigns a
category or marks a value, and the log counts what each one did:

1. Not labelled running: category `cross-training` (swims, elliptical, bike, hikes, walks).
2. Running with less than 200 m: category `aborted`.
3. Indoor running: category `indoor run`; it counts as training time, not toward distance or pace.
4. Cadence of 140 steps a minute or less **and** slower than 7 min/km: category `walk`; training
   time, not running pace.
5. Everything else: category `run`.
6. A run with a cadence of 140 or less at a running pace: cadence and step length set missing.
   The wrist missed steps; the distance and time are kept.
7. On foot, a maximum speed above 10 m/s (36 km/h): the maximum speed is set missing; the rest of
   the row is kept.
8. A 0 in distance, cadence, step length, stance time, vertical oscillation, vertical ratio, power
   or pedal cadence: set missing. It means "not measured".

```python
clean = conv.copy()
clean["category"] = "run"
RULES = [("cross-training", clean["sport"] != "running"),
         ("aborted", clean["distance_km"].fillna(0) < 0.2),
         ("indoor run", clean["sub_sport"] == "indoor_running"),
         ("walk", (clean["cadence_spm"] <= 140) & (clean["pace_min_km"] > 7))]
log = []
for name, hit in RULES:
    hit = hit & (clean["category"] == "run")              # first matching rule wins
    clean.loc[hit, "category"] = name
    log.append({"rule": f"category = {name}", "values": int(hit.sum())})
missed = (clean["category"] == "run") & (clean["cadence_spm"] <= 140)
clean.loc[missed, ["cadence_spm", "step_m"]] = np.nan
log.append({"rule": "run cadence and step set missing (missed steps)", "values": int(missed.sum())})
spike = (clean["max_speed_mps"] > 10) & (clean["sport"] != "cycling")   # 36 km/h on foot
clean.loc[spike, "max_speed_mps"] = np.nan
log.append({"rule": "max speed set missing (spike)", "values": int(spike.sum())})
ZERO = ["distance_km", "cadence_spm", "step_m", "stance_ms", "vert_osc_mm", "vert_ratio_pct", "power_w", "pedal_rpm"]
log.append({"rule": "0 set missing (not measured)", "values": int((clean[ZERO] == 0).sum().sum())})
clean[ZERO] = clean[ZERO].mask(clean[ZERO] == 0)
os.makedirs("clean", exist_ok=True)
clean.to_csv("clean/activities_categorized.csv", index=False)
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
print(pd.DataFrame(log).to_string(index=False))
print(clean["category"].value_counts().to_dict())
```

Output:

```
                                           rule  values
                      category = cross-training     196
                             category = aborted       4
                          category = indoor run      21
                                category = walk      15
run cadence and step set missing (missed steps)       3
                  max speed set missing (spike)       6
                   0 set missing (not measured)    1451
{'run': 457, 'cross-training': 196, 'indoor run': 21, 'walk': 15, 'aborted': 4}
```

```python
ref = pd.read_csv("raw/activities_clean.csv")              # the case file's own SI copy
assert (ref["activity_id"] == clean["activity_id"]).all()
assert (ref["start_local"] == clean["start_local"].dt.strftime("%Y-%m-%dT%H:%M")).all()
assert np.allclose(ref["distance_km"], clean["distance_km"], atol=0.0006, equal_nan=True)   # to the meter
assert np.allclose(ref["moving_time_min"], clean["moving_min"], atol=0.006)          # to the second
has = ref["avg_cadence_spm"].notna()                        # the case file leaves 0 cadence blank
assert np.allclose(ref.loc[has, "avg_cadence_spm"], conv.loc[has, "cadence_spm"])
print(f"all {len(ref)} rows match the case file's SI table: local start, distance, moving time;")
print(f"running cadence matches on all {has.sum()} rows where the case file has one")
```

Output:

```
all 693 rows match the case file's SI table: local start, distance, moving time;
running cadence matches on all 495 rows where the case file has one
```

457 runs remain, and nothing was thrown away: the 196 cross-training sessions, the 21 indoor
runs, the 15 walks and the 4 aborted starts are all still in the table with their category. Three
runs keep their distance and time but lose a cadence the wrist undercounted, 6 maximum speeds that
were single spikes are marked missing, and so are 1,451 zeros that meant "not measured". The case
file's own conversion agrees with yours on every local start, distance and moving time, and on all
495 running cadences it gives, which checks the unit audit a second way. Notice what an "outlier"
rule would have done: the walks and the indoor runs look like outliers in pace, and they are real
sessions.

### The quarter-by-quarter summary

Now the table the coach asked for, one row per calendar quarter, with the runs summarized and
everything else counted as hours so that no training disappears. The first and last quarters are
partial, so the summary also gives kilometers per week of the span each quarter covers.

```python
clean["quarter"] = clean["start_local"].dt.to_period("Q")
runs = clean[clean["category"] == "run"]
summary = runs.groupby("quarter").agg(runs=("distance_km", "size"), km=("distance_km", "sum"),
                                      long_km=("distance_km", "max"), median_pace=("pace_min_km", "median"),
                                      cadence=("cadence_spm", "median"), hr=("avg_hr_bpm", "median"))
other = clean[clean["category"] != "run"].groupby("quarter")["moving_min"].sum() / 60
summary["other_h"] = other.reindex(summary.index).fillna(0)
first, last = clean["start_local"].min().normalize(), clean["start_local"].max().normalize()
start = summary.index.start_time.where(summary.index.start_time > first, first)
end = summary.index.end_time.normalize().where(summary.index.end_time < last, last)
summary["weeks"] = ((end - start).days + 1) / 7
summary["km_per_week"] = summary["km"] / summary["weeks"]
summary["median_pace"] = summary["median_pace"].map(lambda p: f"{int(p)}:{60 * (p % 1):02.0f}")
summary.round(1).to_csv("clean/quarter_summary.csv")
print(summary.round(1).to_string())
ref_km = ref.loc[runs.index].groupby(runs["quarter"])["distance_km"].sum()   # same rows, case file's units
print(f"largest quarterly difference from activities_clean.csv: {(ref_km - summary['km']).abs().max():.3f} km")
```

Output:

```
         runs     km  long_km median_pace  cadence     hr  other_h  weeks  km_per_week
quarter                                                                               
2024Q2      1    6.7      6.7        5:53    172.0  168.0      0.2    0.4         15.5
2024Q3     41  270.1     12.5        6:05    169.0  157.0     18.5   13.1         20.6
2024Q4     39  244.6     11.8        5:15    176.0  161.0      4.6   13.1         18.6
2025Q1     49  363.8     13.5        5:09    176.0  160.0     27.4   12.9         28.3
2025Q2     52  426.7     13.0        5:12    176.0  156.0     23.4   13.0         32.8
2025Q3     57  509.2     13.0        5:08    176.0  157.0     21.0   13.1         38.7
2025Q4     45  419.3     11.8        5:11    176.0  156.0     20.9   13.1         31.9
2026Q1     36  333.9     11.6        5:09    176.0  157.0     20.8   12.9         26.0
2026Q2     44  398.0     14.5        5:06    176.0  157.5     17.1   13.0         30.6
2026Q3     44  416.7     16.1        5:18    176.0  155.0     31.1   13.1         31.7
2026Q4     49  479.7     15.6        5:15    176.0  157.0      8.8    8.4         56.9
largest quarterly difference from activities_clean.csv: 0.005 km
```

Read the weeks column before the totals. The first "quarter" is three days in June 2024 with one
run, and the last stops on 28 November 2026 (8.4 weeks), so compare kilometers per week, not
totals. Per week, the running grew from about 19 to 21 km in the second half of 2024 to 28 to 39 km
in 2025 and 26 to 32 km in most of 2026; the last quarter of 2026 is the biggest by far, at about 57
km a week. Pace changed once: the median was 6:05 a kilometer at 169 steps a minute in the summer of
2024, and 5:06 to 5:18 at 176 steps a minute in every quarter since, at about the same median heart
rate (155 to 161). The quarterly totals agree with `activities_clean.csv` to 5 m.

Two dips are questions for the athlete, not for the file. The first quarter of 2026 holds a trip
(the +3 h offset in February) and only 36 runs; and in May 2026 a second watch recorded
most of the runs, so they are not in this export at all (the challenge).

```python
labelled = conv[conv["sport"] == "running"]
month_raw = labelled.set_index("start_local")["distance_km"].resample("MS").sum()
month_run = runs.set_index("start_local")["distance_km"].resample("MS").sum().reindex(month_raw.index, fill_value=0)
fig, ax = plt.subplots(figsize=(9, 3.4))
ax.bar(month_raw.index, month_raw, width=25, color="0.8", label="labelled running, as exported")
ax.bar(month_run.index, month_run, width=12, color="k", label="runs after the rules")
ax.set(ylabel="distance per month (km)")
ax.legend(loc="upper left")
plt.tight_layout()
diff = (month_raw - month_run).sort_values(ascending=False)
print("largest exported-minus-clean months (km):", {d.strftime("%Y-%m"): round(v, 1) for d, v in diff.head(4).items()})
```

Output:

```
largest exported-minus-clean months (km): {'2024-08': 50.5, '2025-03': 24.3, '2025-04': 22.0, '2024-10': 21.5}
```

![Bars of distance per month from June 2024 to November 2026. Light bars, every activity labelled running as exported; dark bars, runs only after the rules. The two agree in most months. The light bars stand clearly above the dark in August and October 2024 (walks saved as runs) and in March and April 2025 (indoor runs with wrist-accelerometer distance). The dark bars rise from about 75 to 115 km a month in the second half of 2024 to about 240 km in October and November 2026, with dips in December 2024, February, May and September 2026.](https://apopt.com/course/tutorials/cs04-messy-watch-export/c15-1.png)

## How good is the number?

The unit audit is checked two ways: by identities across every run (speed × timer time = distance
for all of them; cadence × step length = speed within 2% for 99%), and against the case file's own
SI table, which matches every local start, distance and moving time and all 495 running cadences it
gives. The categories rest on written rules, and the change log says how many activities each one
moved (196 cross-training, 21 indoor runs, 15 walks, 4 aborted) and how many values it marked (3
undercounted cadences, 6 speed spikes, 1,451 zeros). The quarterly totals agree with
`activities_clean.csv` to 5 m. The summary's limits are coverage, not cleaning: the first and last
quarters are partial, the indoor runs carry no trusted distance, and in May 2026 a second watch
recorded most of the runs, so they are missing here. Wrist heart rate is a rough guide to effort.

## Track it

This study makes the record a table with rules. Add one row per quarter: `test=quarter-summary`,
`metric=run_km_per_week` (and `run_km`, `run_count`, `median_pace_min_per_km`, `median_hr_bpm`),
`date` = the last day of the quarter, `device=gps-watch`, `note` = "partial quarter" where it is.
Keep `data_dictionary.csv` and `change_log.csv` beside the record; rows are appended, never edited.

## With your own data

Request your own data export from your watch maker's website, find the activity files or summary
table, and run the unit audit before anything else. Write down which time your watch uses for pace
and how it stores the time zone. Remove names, places and positions before you share any of it.

## The same method in another field

A unit audit by identities is how engineers check a historian export from a plant: flow × time must
equal the volume a tank level shows, power must equal voltage × current. The Machine Learning for
Engineers page on [data cleansing](https://apmonitor.com/pds/index.php/Main/CleanseData) shows rule-based
filters for the same kinds of fault.

## Acknowledgements

Activity summaries from a COROS Training Hub archive of an adult male athlete in his mid-40s, from the
course case file `athletes/jh/coros-history/`, prepared by `data-repo/prepare_watch.py`.

## Action card

- **Finding:** Your running has grown from about 19 to 21 km a week in late 2024 to about 57 km a week since October 2026, and since the fall of 2024 your median pace has held at 5:06 to 5:18 a kilometer at about the same heart rate.
- **Evidence:** 457 runs after eight written rules, from units checked by identity and against the case file's own conversion; walks, indoor runs and other sports kept and counted as hours; volume compared per week because the first and last quarters are partial.
- **Sure:** High for outdoor volume and pace; indoor runs have no trusted distance, May 2026 is mostly on another watch, and wrist heart rate is approximate. Training information, not medical advice.
- **Action:** Treat the current 57 km a week as a new high, not a baseline; hold it for a few weeks before adding more, and record treadmill runs with the treadmill's distance in the notes.
- **Retest:** Rerun the same notebook on each new export; the rules and the change log make the quarters comparable.

## Challenge: The same audit on a second watch

In April and May 2026 the athlete also wore a second watch from the same maker, and the case file
`athletes/jh/watch/` holds its 19 runs: one summary row each, already in SI units, and a
per-second record file for every run. One run was recorded by both watches; the others are missing
from this study's export.

1. Write a data dictionary for its `activities.csv` before you check a value, and test each unit with an identity (distance, moving time, pace, cadence).
2. Compute distance and moving time for each run from its per-second record file and compare with the summary row.
3. Find the run both watches recorded and compare the two rows field by field. Decide which watch's row to keep, and write the rule down.
4. Add the other runs to this study's quarterly summary without counting any run twice, and recompute the second quarter of 2026.

Deliverables:

- the notebook with its outputs
- the dictionary, the change log and the new summary as CSV files
- three sentences for the coach on what the second watch changes in the summary

## References

- *Data-Driven Athletics*, Chapter 2, The Oxygen Path (Section 2.3, the energy cost of running); Chapter 4, The data dictionary (Section 4.2.5) and Cleaning (Section 4.3).

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